2023-12-05 10:28:08 -08:00
package db
import (
"database/sql"
2023-12-28 16:58:54 -08:00
_ "github.com/go-sql-driver/mysql"
2023-12-05 10:28:08 -08:00
)
2023-12-28 16:53:59 -08:00
func AddAccountRecord ( uuid [ ] byte , username string , key , salt [ ] byte ) error {
2023-12-28 18:32:03 -08:00
_ , err := handle . Exec ( "INSERT INTO accounts (uuid, username, hash, salt, registered) VALUES (?, ?, ?, ?, UTC_TIMESTAMP())" , uuid , username , key , salt )
2023-12-28 16:53:59 -08:00
if err != nil {
return err
}
return nil
}
func AddAccountSession ( username string , token [ ] byte ) error {
2023-12-28 18:37:04 -08:00
_ , err := handle . Exec ( "INSERT INTO sessions (uuid, token, expire) SELECT a.uuid, ?, DATE_ADD(UTC_TIMESTAMP(), INTERVAL 1 WEEK) FROM accounts a WHERE a.username = ?" , token , username )
2023-12-28 16:53:59 -08:00
if err != nil {
return err
}
return nil
}
func GetUsernameFromToken ( token [ ] byte ) ( string , error ) {
2023-12-05 10:28:08 -08:00
var username string
2023-12-28 17:09:50 -08:00
err := handle . QueryRow ( "SELECT a.username FROM accounts a JOIN sessions s ON s.uuid = a.uuid WHERE s.token = ? AND s.expire > UTC_TIMESTAMP()" , token ) . Scan ( & username )
2023-12-05 10:28:08 -08:00
if err != nil {
if err == sql . ErrNoRows {
2023-12-28 16:53:59 -08:00
return "" , err
2023-12-05 10:28:08 -08:00
}
2023-12-28 16:53:59 -08:00
return "" , err
2023-12-05 10:28:08 -08:00
}
return username , nil
}
2023-12-28 16:53:59 -08:00
func GetAccountKeySaltFromUsername ( username string ) ( [ ] byte , [ ] byte , error ) {
var key , salt [ ] byte
2023-12-28 18:32:03 -08:00
err := handle . QueryRow ( "SELECT hash, salt FROM accounts WHERE username = ?" , username ) . Scan ( & key , & salt )
2023-12-28 16:53:59 -08:00
if err != nil {
return nil , nil , err
}
return key , salt , nil
}
func GetUUIDFromToken ( token [ ] byte ) ( [ ] byte , error ) {
var uuid [ ] byte
err := handle . QueryRow ( "SELECT uuid FROM sessions WHERE token = ? AND expire > UTC_TIMESTAMP()" , token ) . Scan ( & uuid )
if err != nil {
if err == sql . ErrNoRows {
return nil , err
}
return nil , err
}
return uuid , nil
}
func RemoveSessionFromToken ( token [ ] byte ) error {
_ , err := handle . Exec ( "DELETE FROM sessions WHERE token = ?" , token )
if err != nil {
return err
}
return nil
}