s3browser-backend/internal/db/mysql.go

95 lines
1.6 KiB
Go
Raw Normal View History

2022-02-07 14:59:43 +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 mysqlDB struct {
dbConn *sql.DB
}
func NewDB(dataSourceName string) (DB, error) {
db, err := sql.Open("mysql", dataSourceName)
if err != nil {
return nil, err
}
db.SetConnMaxLifetime(time.Minute * 3)
db.SetMaxOpenConns(10)
db.SetMaxIdleConns(10)
return &mysqlDB{
dbConn: db,
}, nil
}
func (d *mysqlDB) 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 *mysqlDB) 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 *mysqlDB) 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
}