69 lines
1.7 KiB
Go
69 lines
1.7 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
var dbConn *pgx.Conn
|
|
|
|
func InitDatabase(ctx context.Context) {
|
|
conn, err := pgx.Connect(ctx, "postgres://master:secret@localhost:5432")
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
_, err = conn.Exec(ctx, `
|
|
CREATE TABLE IF NOT EXISTS users (
|
|
id SERIAL PRIMARY KEY,
|
|
name VARCHAR(20) UNIQUE NOT NULL,
|
|
pass_hash VARCHAR(60) NOT NULL,
|
|
pronouns VARCHAR(15) DEFAULT NULL,
|
|
color VARCHAR(3) DEFAULT NULL
|
|
);
|
|
CREATE TABLE IF NOT EXISTS chat_groups (
|
|
id SERIAL PRIMARY KEY,
|
|
name VARCHAR(48) NOT NULL,
|
|
creator_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
enable_user_colors BOOLEAN NOT NULL DEFAULT true,
|
|
group_color VARCHAR(3),
|
|
created_at TIMESTAMP NOT NULL DEFAULT NOW()
|
|
);
|
|
CREATE TABLE IF NOT EXISTS chat_group_members (
|
|
group_id INTEGER NOT NULL REFERENCES chat_groups(id) ON DELETE CASCADE,
|
|
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
joined_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
|
PRIMARY KEY (group_id, user_id)
|
|
);
|
|
`)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
dbConn = conn
|
|
}
|
|
|
|
func SaveClientWithoutGroups(ctx context.Context, client *Client) error {
|
|
var id uint64
|
|
var err error
|
|
|
|
var hashed []byte
|
|
hashed, err = bcrypt.GenerateFromPassword([]byte(client.PasswordHash), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
password := string(hashed)
|
|
|
|
c := string(client.Color[:])
|
|
err = dbConn.QueryRow(ctx, `
|
|
INSERT INTO users (name, pass_hash, pronouns, color)
|
|
VALUES ($1, $2, $3)
|
|
RETURNING id
|
|
`, client.Name, password, client.Pronouns, c).Scan(&id)
|
|
return err
|
|
}
|