This repository has been archived on 2025-08-09. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
web-app-template/db/auth.go
Tim Wundenberg bd721a1e48
All checks were successful
Build Docker Image / Explore-Gitea-Actions (push) Successful in 45s
chore(auth): start refactoring for testable code #181
2024-09-25 22:45:45 +02:00

79 lines
1.7 KiB
Go

package db
import (
"database/sql"
"errors"
"me-fit/types"
"me-fit/utils"
"time"
"github.com/google/uuid"
)
var (
UserNotFound = errors.New("User not found")
)
type User struct {
Id uuid.UUID
Email string
EmailVerified bool
EmailVerifiedAt time.Time
IsAdmin bool
Password []byte
Salt []byte
CreateAt time.Time
}
func NewUser(id uuid.UUID, email string, emailVerified bool, emailVerifiedAt time.Time, isAdmin bool, password []byte, salt []byte, createAt time.Time) *User {
return &User{
Id: id,
Email: email,
EmailVerified: emailVerified,
EmailVerifiedAt: emailVerifiedAt,
IsAdmin: isAdmin,
Password: password,
Salt: salt,
CreateAt: createAt,
}
}
type Auth interface {
GetUser(email string) (*User, error)
}
type AuthSqlite struct {
db *sql.DB
}
func NewAuthSqlite(db *sql.DB) *AuthSqlite {
return &AuthSqlite{db: db}
}
func (a AuthSqlite) GetUser(email string) (*User, error) {
var (
userId uuid.UUID
emailVerified bool
emailVerifiedAt time.Time
isAdmin bool
password []byte
salt []byte
createdAt time.Time
)
err := a.db.QueryRow(`
SELECT user_uuid, email_verified, email_verified_at, password, salt, created_at
FROM user
WHERE email = ?`, email).Scan(&userId, &emailVerified, &emailVerifiedAt, &password, &salt, &createdAt)
if err != nil {
if err == sql.ErrNoRows {
return nil, UserNotFound
} else {
utils.LogError("SQL error GetUser", err)
return nil, types.InternalServerError
}
}
return NewUser(userId, email, emailVerified, emailVerifiedAt, isAdmin, password, salt, createdAt), nil
}