s3browser-backend/internal/db/db.go

97 lines
1.6 KiB
Go
Raw Normal View History

2021-10-20 14:11:18 +00:00
package db
import (
"context"
"database/sql"
_ "embed"
"time"
_ "github.com/go-sql-driver/mysql"
"golang.org/x/crypto/bcrypt"
)
//go:embed setup.sql
var setupSql string
const DB_NAME = "s3Browser"
type DB struct {
dbConn *sql.DB
}
func NewDB(driver, dataSourceName string) (*DB, error) {
db, err := sql.Open(driver, dataSourceName)
if err != nil {
return nil, err
}
if driver == "mysql" {
db.SetConnMaxLifetime(time.Minute * 3)
db.SetMaxOpenConns(10)
db.SetMaxIdleConns(10)
}
return &DB{
dbConn: db,
}, nil
}
func (d *DB) Setup() error {
tx, err := d.dbConn.Begin()
if err != nil {
return err
}
_, err = tx.Exec(setupSql)
if err != nil {
tx.Rollback()
return err
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}
func (d *DB) CheckLogin(ctx context.Context, username, password string) (bool, error) {
rows, err := d.dbConn.QueryContext(ctx, "SELECT password FROM user WHERE username = ?", username)
if err != nil {
return false, err
}
if !rows.Next() {
return false, nil
}
var passwordHash []byte
err = rows.Scan(&passwordHash)
if err != nil {
return false, err
}
if bcrypt.CompareHashAndPassword(passwordHash, []byte(password)) != nil {
return false, nil
}
return true, nil
}
func (d *DB) AddUser(ctx context.Context, username, password string) error {
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return err
}
_, err = d.dbConn.ExecContext(ctx, "INSERT INTO user (username,password) VALUES (?,?)", username, hash)
if err != nil {
return err
}
return nil
}