hatecomputers.club/database/users.go

113 lines
2.6 KiB
Go

package database
import (
"database/sql"
"log"
"time"
_ "github.com/mattn/go-sqlite3"
)
const (
ExpiryDuration = time.Hour * 24
)
type User struct {
ID string `json:"sub"`
Mail string `json:"email"`
Username string `json:"preferred_username"`
DisplayName string `json:"name"`
CreatedAt time.Time `json:"created_at"`
}
type UserSession struct {
ID string `json:"id"`
UserID string `json:"user_id"`
ExpireAt time.Time `json:"expire_at"`
}
func GetUser(dbConn *sql.DB, id string) (*User, error) {
row := dbConn.QueryRow(`SELECT id, mail, username, display_name, created_at FROM users WHERE id = ?;`, id)
var user User
err := row.Scan(&user.ID, &user.Mail, &user.Username, &user.DisplayName, &user.CreatedAt)
if err != nil {
log.Println(err)
return nil, err
}
return &user, nil
}
func FindOrSaveUser(dbConn *sql.DB, user *User) (*User, error) {
_, err := dbConn.Exec(`INSERT OR REPLACE INTO users (id, mail, username, display_name) VALUES (?, ?, ?, ?);`, user.ID, user.Mail, user.Username, user.DisplayName)
if err != nil {
return nil, err
}
return user, nil
}
func MakeUserSessionFor(dbConn *sql.DB, user *User) (*UserSession, error) {
expireAt := time.Now().Add(time.Hour * 12)
_, err := dbConn.Exec(`INSERT OR REPLACE INTO user_sessions (id, user_id, expire_at) VALUES (?, ?, ?);`, user.ID, user.ID, time.Now().Add(ExpiryDuration))
if err != nil {
log.Println(err)
return nil, err
}
return &UserSession{
ID: user.ID,
UserID: user.ID,
ExpireAt: expireAt,
}, nil
}
func GetSession(dbConn *sql.DB, sessionId string) (*UserSession, error) {
row := dbConn.QueryRow(`SELECT id, user_id, expire_at FROM user_sessions WHERE id = ?;`, sessionId)
var id, userId string
var expireAt time.Time
err := row.Scan(&id, &userId, &expireAt)
if err != nil {
log.Println(err)
return nil, err
}
return &UserSession{
ID: id,
UserID: userId,
ExpireAt: expireAt,
}, nil
}
func DeleteSession(dbConn *sql.DB, sessionId string) error {
_, err := dbConn.Exec(`DELETE FROM user_sessions WHERE id = ?;`, sessionId)
if err != nil {
log.Println(err)
return err
}
return nil
}
func RefreshSession(dbConn *sql.DB, sessionId string) (*UserSession, error) {
newExpireAt := time.Now().Add(ExpiryDuration)
_, err := dbConn.Exec(`UPDATE user_sessions SET expire_at = ? WHERE id = ?;`, newExpireAt, sessionId)
if err != nil {
log.Println(err)
return nil, err
}
session, err := GetSession(dbConn, sessionId)
if err != nil {
log.Println(err)
return nil, err
}
return session, nil
}