Connect to Postgres DB by a user which has no password - postgresql

I created a user by:
sudo -u postgres psql -c "CREATE USER sample;"
Then created a database:
sudo -u postgres psql -c "CREATE DATABASE practice OWNER sample;"
Now I'm trying to connect to this DB by following snippet:
dsn := url.URL{
User: url.UserPassword("sample", ""),
Scheme: "postgres",
Host: fmt.Sprintf("%s", "localhost"),
Path: "practice",
RawQuery: (&url.Values{"sslmode": []string{"disable"}}).Encode(),
}
db, err := gorm.Open(
"postgres",
dsn.String(),
)
if err != nil {
log.Fatal(err)
}
But the output is:
2020/07/07 16:43:44 pq: password authentication failed for user "sample"
How do I connect to DB with a user which has no password?

Either assign the user a password and then use it, or change your pg_hba.conf file so that some other method of authentication is used for that user/dbname/connection-method/host (and then restart your server so the change takes effect).
sudo -u postgres psql -c "ALTER USER sample password 'yahkeixuom5R';"

Related

Can't connect to PostgreSQL database using pgx driver but can using terminal

From code
The code bellow outputs the following:
2022/06/21 16:01:07 Failed to connect to db: failed to connect to 'host=localhost user=postgres database=local': server error (FATAL: Ident authentication failed for user "postgres" (SQLSTATE 28000)) exit status 1
import (
"context"
"log"
"github.com/jackc/pgx/v4"
)
func main() {
dbCtx := context.Background()
db, err := pgx.Connect(
dbCtx,
"postgres://postgres:smashthestate#localhost:5432/local",
)
if err != nil {
log.Fatalf("Failed to connect to db: %v\n", err)
}
defer db.Close(dbCtx)
// do stuff with db...
}
From terminal
However, connection to db is possible from terminal. For example, this command if run with the same parameters (db name, user name, password) will give correct output:
psql -d local -U postgres -W -c 'select * from interest;'
Notes
Command works correctly even if sent by user that is neither root nor postgres.
Authentication method for local connection is set to trust inside pg_hba.conf:
local all all trust
So, what am I missing here? Why everything works fine from the command line but doesn't work from code?
Go's defaults are different from psql's. If no hostname is given, Go defaults to using localhost, while psql defaults to using the Unix domain sockets.
To specify a Unix domain socket to Go, you need to do it oddly to get it to survive URI validation:
postgres://postgres:smashthestate#:5432/local?host=%2Ftmp
Though the end might need to be more like ?host=%2Fvar%2Frun%2Fpostgresql, depending on how the server was configured.
But why are you specifying a password which is not needed? That is going to cause pointless confusion.

Can not connect from golang to docker postgres container

I spin up the docker container for postgres
docker run -i -t -v=":/var/lib/postgresql" -p 5432:5432 my_image/postgresql:9.3
And verify that it is reachable from host using
psql -h my_docker_ip -p 5432 -U pguser -W pgdb // passowrd: pguser
Now I want to connect to the container postgres using go in my host machine.
import (
"database/sql"
_ "github.com/lib/pq"
"fmt"
)
func main() {
db, err := sql.Open("postgres", "user=pguser password='pguser' host=192.168.99.100 port=5432 sslmode=verify-full")
if err != nil {
fmt.Println(err)
}
rows, err := db.Query("SELECT * FROM test")
fmt.Println(rows)
}
While there were no error on initializing the db instance reference, the test query itself print out
<nil>
This should not happen because I created table test and multiple rows in table test prior to running the go code.
Can someone tell me what I am doing wrong?
Thanks
I saw the same error when using mysql client in golang:
Failed to connect to database: x509: cannot validate certificate for 10.111.202.229 because it doesn't contain any IP SANs
The solution in https://stackoverflow.com/a/54636760/8645590 worked for me.

Golang lib/pg can't connect to postgres

I have such code:
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/lib/pq"
)
func main() {
db, err := sql.Open("postgres", "user=postgres dbname=vagrant sslmode=disable")
if err != nil {
log.Fatal(err)
}
rows, err := db.Query("SELECT 3+5")
if err != nil {
log.Fatal(err)
}
fmt.Println(rows)
}
And its result is:
[vagrant#localhost go-postgres]$ go run test.go
2015/12/19 11:03:53 pq: Ident authentication failed for user "postgres"
exit status 1
But I can access postgres:
[vagrant#localhost go-postgres]$ psql -U postgres vagrant
psql (9.4.4)
Type "help" for help.
vagrant=#
And I don't have any troubles with using Rails app with postgres.
Anyone has an idea?
EDIT:
Here is my pg_hba.conf:
local all all trust
host all all 127.0.0.1/32 ident
host all all ::1/128 ident
EDIT2:
I found this in my postgres logs:
< 2015-12-19 12:13:05.094 UTC >LOG: could not connect to Ident server at address "::1", port 113: Connection refused
< 2015-12-19 12:13:05.094 UTC >FATAL: Ident authentication failed for user "postgres"
< 2015-12-19 12:13:05.094 UTC >DETAIL: Connection matched pg_hba.conf line 84: "host all all ::1/128 ident"
I think it will really help ;)
Ok,
correct connection string is:
"user=postgres host=/tmp dbname=vagrant sslmode=disable"
I assumed pg library uses same defaults as psql or ruby driver. Lesson learned.
Run in console:
psql "user=postgres dbname=vagrant sslmode=disable"
If you cannot connect so it needs to change sslmode else I will think more.
For me, setting host to /run/postgresql worked.
Credit: https://github.com/lib/pq/issues/645#issuecomment-320799610
The host url depends on the socket Postgres is using. The socket location varies based on how and where postgres was built. The socket location can be found using:
Inside psql, run \conninfo. It shows the socket location along with other details
unix_socket_directory value in postgresql.conf
In my Ubuntu distro, /var/run is a soft link to /run, that's why /run/postgresql works even though unix_socket_directory and \conninfo mention /var/run/postgresql.

Create user -- MongoDB

I'm trying to create a mongoDB user on a DigitalOcean droplet. I tried a lot of combinations, but basically, I can't make this work.
To start the service, I use mongod --noauth. Below is the command I used:
use admin
db.createUser( { user: "userhere", pwd: "passhere", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] } )
I restarted the service and tried to connect using:
mongo admin --port 61370 --host <host> -u userhere -p
Enter password:
2015-01-21T13:30:17.279-0500 Error: 18 { ok: 0.0, errmsg: "auth failed", code: 18 } at src/mongo/shell/db.js:1210
exception: login failed
It doesn't connect.
Does anyone know the step-by-step on how to create a user on MongoDB?
You must create the user with the appropriates privileges. So you should connect to your mongo instance with :
mongo -u siteUserAdmin -p password
See the documentation as well : http://docs.mongodb.org/manual/tutorial/add-user-to-database/
Try specifying -authenticationDatabase option
mongo -u mongoadmin -p password -authenticationDatabase admin

Connecting to a PostgreSQL database through pq returns a "bad connection" error

I am making a web app in Go and PostgreSQL using two different computers. The setup is the same on both computers (Ubuntu with last versions of Go and PostgreSQL). The problem is that I cannot get my app to connect to the database on my laptop.
I use this piece of code:
func (db *Database) Dial(user string, password string, dbname string) {
var err error
db.Conn, err = sql.Open("postgres", "user="+user+" password="+password+" dbname="+dbname+" sslmode=require")
if err != nil {
fmt.Println("Connection to " + dbname + " not possible!")
log.Fatal(err)
}
err = db.Conn.Ping()
if err != nil {
fmt.Println("Ping to " + dbname + " not possible!")
fmt.Println(err)
}
}
And I get:
Ping to my_database not possible!
driver: bad connection
I found many questions on SO with the same error, but I found no solution that would solve my case.
Also, on my laptop, just like on my desktop computer, there is a user postgres and I can connect to the database through psql, so the daemon is active and the password is right. I use the exact same setup and code on both computers.
My question is: how do I get more information about the error? I find "bad connection" to be too vague. I'm sure that a bit more of information would help me a lot.
Also, do you have an idea of would could cause the error?
Update
The PostgreSQL log says this:
2014-09-29 14:23:26 EDT FATAL: password authentication failed for user "postgres"
2014-09-29 14:23:26 EDT DETAIL: Connection matched pg_hba.conf line 92: "host all all 127.0.0.1/32 md5"
But I double checked the password and it shoud be fine. I can also log in as the posgres user, run the psql command and execute queries.
I found a way to fix this.
I log in as postgres and run psql postgres. In other words, I connect to the postgres database. Then I run the command \password and enter a new password.
I entered the exact same password that I have been using since the beginning and somehow now it works.
The problem is solved, but if someone has an idea about what could have been the cause, I'm interested. Maybe it has something to do with password expiration?