Golang SQL Package not using defined database parameters - database

I'm trying to create a practice program where I accept API requests from a front end and then store data to a postgres database.
In the included code you can see that I define my parameters for connecting to the local database server, however when I run the Go program after starting the postgres server in my terminal, I get the error as included 'pq: database "root" does not exist'.
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
const (
host = "localhost"
port = 5432
user = "root"
password = ""
dbname = "postgres"
)
func ConnectDatabase() {
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", host, port, user, password, dbname)
db, err := sql.Open("postgres", psqlInfo)
if err != nil {
panic(err)
}
defer db.Close()
err = db.Ping()
if err != nil {
panic(err)
}
fmt.Println("Successfully connected!")
}
Image of the console containing the error
I'm quite new to this, but it doesn't really make sense to me as I'm directly specifiying which database to use (which is obviously not "root"). Could it somehow have something to do with postgres by default trying to access a database with the same name as my username. If so what is the point of specifying which databse I want to connect to?
Thanks for the help in advance.

Related

InfluxDB With GoLang

I'm very new to InfluxDB and seem to be having some trouble understanding how to use the Go client. I'm currently using the default example code but I can't understand where to find the data that is being uploaded, or if it is being uploaded at all. The current code looks like
package main
import (
"context"
"fmt"
"time"
influxdb2 "github.com/influxdata/influxdb-client-go/v2"
)
func main() {
token := "tokenInsertedHere"
fmt.Println("testing influxdb")
// Create a new client using an InfluxDB server base URL and an authentication token
client := influxdb2.NewClient("http://localhost:8086", token)
// Use blocking write client for writes to desired bucket
writeAPI := client.WriteAPIBlocking("orgName", "bucketName")
// Create point using full params constructor
p := influxdb2.NewPoint("test",
map[string]string{"unit": "temperature"},
map[string]interface{}{"avg": 24.5, "max": 45.0},
time.Now())
// write point immediately
writeAPI.WritePoint(context.Background(), p)
client.Close()
}
When I'm on the data explorer page filtering measurements in the bucket the code should've wrote to, the measurement doesn't pop up. What am I doing wrong? I've noticed that the client doesn't throw any errors, which is strange to me. I've tried using a fake token and it acts like there were no problems when writing to the db. Would appreciate any help!
I can't conclusively know if this is your issue, but keeping my token and org names lined up correctly always trips me up. In the Influx web client, go to "Switch Organizations" and verify that the organization that you are using matches the organization selected in the web client. Hopefully this helps.
Change the line with write to catch an error and check what error occured:
err := writeAPI.WritePoint(context.Background(), p)
if err != nil {
panic(err)
}

GOLANG HTTP Basic-Auth with Google App Engine URLFetch

How can I add an Authorization header to urlfetch client with Go?
There is a similar question answered for java and python, but not Go.
urlfetch.Client(ctx) returns an HTTP client (http://godoc.org/google.golang.org/appengine/urlfetch#Client)
The http.Client has methods for Get, Post, etc... It also has Do which you can hand an arbitrary request. Create a request using http.NewRequest:
req, err := http.NewRequest("GET", "http://www.google.com", nil)
Then you can add a header like this:
req.Header.Set("Authorization", "whatever")
And call Do:
res, err := client.Do(req)
I'm new to Go, please excuse this code for being ugly/malformed/just plain wrong.
I've been working my way though this and ran across the same problem on appengine.
#Caleb's answer above was a big help. I've just added some detail to that to help someone who might come across a similar problem.
Here's what my import statement looks like:
Import {
"appengine"
"appengine/urlfetch"
"bytes"
"encoding/json"
"fmt"
"golang.org/x/oauth2"
"io/ioutil"
"net/http"
"net/url"
}
This is a function that receives and incoming authentication callback request, then replies with a request for an access token from the authentication server. In this case, fitbit, which needs an Authentication header set to "Basic" with some extra information. I couldn't figure out how to do this with the stock Oauth2 library, which doesn't seem to easily allow changing the request headers.
As you can see we the context of the incoming request (r). From that context, we get the http.Client from urlfetch.
Then we pack up and send a request back, with some authorization information.
After we get a response we print the results to the browser.
Hope this helps!
func authCallbackHandler(w http.ResponseWriter, r *http.Request) {
data := url.Values{}
data.Set("client_id", "231343")
data.Add("grant_type", "authorization_code")
data.Add("redirect_uri", "http://localhost:8080/callmebacklaterok")
data.Add("code", "authcode123132")
encodedData := data.Encode()
c := appengine.NewContext(r)
client := urlfetch.Client(c)
urlStr := "https://api.fitbit.com/oauth2/token"
req, _ := http.NewRequest("POST", urlStr,bytes.NewBufferString(encodedData))
req.Header.Add("Authorization", "Basic RmFuY3kgbWVldGluZyB5b3UgaGVyZSEg")
resp, _ := client.Do(req)
defer resp.Body.Close()
fmt.Fprint(w, resp)
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err.Error())
}
var bodydata interface{}
err = json.Unmarshal(body, &bodydata)
if err != nil {
panic(err.Error())
}
fmt.Fprint(w, bodydata)
}

Node-SQL with node.js and MS integrated Security

I have some sample code that is successfully connecting to SQL Server using Microsoft SQL Server user name and password. But I was wondering if there is a way to use integrated security with this script. Basically which means use the logged in user's credentials without supplying a password in the script.
var sql = require('mssql');
var config = {
server: '127.0.0.1',
database: 'master',
user: 'xx',
password: 'xxx',
options : {
trustedConnection : true
}
}
var connection = new sql.Connection(config, function(err) {
// ... error checks
if(err) {
return console.log("Could not connect to sql: ", err);
}
// Query
var request = new sql.Request(connection);
request.query('select * from dbo.spt_monitor (nolock)', function(err, recordset) {
// ... error checks
console.dir(recordset);
});
// Stored Procedure
});
Wish I could add this as a comment but don't have enough reputation yet... but what happens when you run this without providing a username/password in the config object?
Windows Authentication happens at the login level so there is no need to provide it at the application level.
Just browsed the documentation and looks like you cannot provide a raw connection string to connect, but to connect you want to build something that looks like this:
var connectionString= 'Server=MyServer;Database=MyDb;Trusted_Connection=Yes;'
The source code of the mssql module is here: https://github.com/patriksimek/node-mssql/blob/master/src/msnodesql.coffee... maybe you can fork and do a pull request that would provide an optional flag whether to use Windows Authentication or not, and that flag would remove the Uid={#{user}};Pwd={#{password}} (as it's unneeded for Windows Authentication) from the CONNECTION_STRING_PORT variable in the module's source code.

How to properly add OAuth headers for a QuickBooks API call in Google Go

I am just trying to get a proof of concept working to test a connection to the QB api for a QB Online account. I have never tried to make an OAuth connection before like this, so I'm not sure that I am doing it right. Here's what I have so far, and it makes the request but I get a 401 error returned from QB's server (Unauthorized OAuth Token: signature_invalid401SERVER):
client := &http.Client{}
if req, err := http.NewRequest("GET", "https://qbo.intuit.com/qbo1/resource/customers/v2/717594130", nil); err != nil {
//handle error
} else {
req.Header.Add("Authorization", "OAuth oauth_token=\"MY_TOKEN\",oauth_nonce=\"7758caa9-e1f4-4fa1-84c5-5759fd513a88\",oauth_consumer_key=\"MY_KEY\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"1369259523\",oauth_version=\"1.0\",oauth_signature=\"MY_SIG\"")
if resp, err := client.Do(req); err != nil {
//handle error
} else {
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
//handle error
}
myOutput := string(contents)
}
}
Could the problem may be with my settings on my QB account instead? There is a setting for "Host Name Domain" that I think it might only allow connections from what I have entered there (which is currently intuit.com). If that is the case, how do I set that to allow connections from my dev app on my localhost?
Are you using the correct OAuth algorithm to generate the signature?
Can you post an actual request/response that shows the outgoing signature/OAuth header, and the response you get back from Intuit?
Your code doesn't show any of that, and it doesn't look like you're using an Intuit DevKit, so that's probably the place to start. My guess would be that the signature you're sending isn't valid. I would highly recommend you find a OAuth library, and use that OAuth library, rather than try to roll your own OAuth algorithm.
As far as this goes:
Could the problem may be with my settings on my QB account instead?
There is a setting for "Host Name Domain" that I think it might only
allow connections from what I have entered there (which is currently
intuit.com).
That is not likely to be the problem... but to get any further than a simple test request, you will need to set that to your host name. If it's a local dev box, you can enter your local dev boxes hostname (e.g. http://localhost/ or http://192.168.1.2/ or anything like that is fine - whatever URL you use to hit your dev box)

Access Denied when accessing WebDav resource from service

I have a service on Windows 2003 Server that needs to access a webdav resource as a UNC Path. The purpose of this service is to verify (and take corrective actions) webdav functionality to sharepoint. The idea is to write a file to sharepoint, and verify it's contents. If something goes wrong and the threshold was exceeded the mrxdav and webclient service will be restarted.
I run the service under a service account that is local admin on the 2003 server and has access to the sharepoint "folder". (I verified this by logging in with the service account and write a file to the same folder).
When the service tries to write a file to this folder it fails with ACCESS DENIED, process monitor shows that the service runs under LocalSystem and Impersonates my service account
I also tried to Impersonate the service account from my code using LogonUser and LogonUserEx (with the various options for logon interactive, network, network cleartext and providers) followed by ImpersonateUser but all result in the same ACCESS DENIED.
I presume this is something specific to a service using the WebClient service.
My code is written in Delphi but I've added the c tags as well to attract more readers since I don't think my problem is Delphi related.
EDIT: Perhaps relevant, I am running a seperate Thread that actually accesses the WebDav share.
EDIT: As a workaround I am create a network connection using explicit credentials using the following code:
function TGuardThread.Map(const Username: String; var Password: String;
const Domain: String): Boolean;
var
nr: NETRESOURCE;
dwRes: DWORD;
begin
try
ZeroMemory(#nr, SizeOf(nr));
nr.dwType := RESOURCETYPE_ANY;
nr.lpRemoteName := PChar('\\mywebdavroot\myfolder');
dwRes := WNetAddConnection2(nr, PChar(Password),
PChar(Format('%s\%s', [Domain, Username])), CONNECT_UPDATE_PROFILE);
Result := dwRes = NO_ERROR;
finally
if Length(Password) > 0 then
SecureZeroMemory(#Password[1], Length(Password) * SizeOf(Char));
end;
end;
Workaround is to use an explicit connection with credentials to the WebDav server, like this:
function TGuardThread.Map(const Username: String; var Password: String;
const Domain: String): Boolean;
var
nr: NETRESOURCE;
dwRes: DWORD;
begin
try
ZeroMemory(#nr, SizeOf(nr));
nr.dwType := RESOURCETYPE_ANY;
nr.lpRemoteName := PChar('\\mywebdavroot\myfolder');
dwRes := WNetAddConnection2(nr, PChar(Password),
PChar(Format('%s\%s', [Domain, Username])), CONNECT_UPDATE_PROFILE);
Result := dwRes = NO_ERROR;
finally
if Length(Password) > 0 then
SecureZeroMemory(#Password[1], Length(Password) * SizeOf(Char));
end;
end;

Resources