fix: migrate sigin to testable code #181

This commit is contained in:
2024-10-04 23:25:57 +02:00
parent abd8663cf3
commit 5b4160b09f
6 changed files with 252 additions and 133 deletions

View File

@@ -6,6 +6,7 @@ import (
"database/sql"
"errors"
"strings"
"time"
"github.com/google/uuid"
@@ -13,6 +14,7 @@ import (
var (
ErrUserNotFound = errors.New("User not found")
ErrUserExists = errors.New("User already exists")
)
type User struct {
@@ -41,6 +43,10 @@ func NewUser(id uuid.UUID, email string, emailVerified bool, emailVerifiedAt *ti
type DbAuth interface {
GetUser(email string) (*User, error)
InsertUser(user *User) error
GetEmailVerificationToken(userId uuid.UUID) (string, error)
InsertEmailVerificationToken(userId uuid.UUID, token string) error
}
type DbAuthSqlite struct {
@@ -77,3 +83,49 @@ func (db DbAuthSqlite) GetUser(email string) (*User, error) {
return NewUser(userId, email, emailVerified, emailVerifiedAt, isAdmin, password, salt, createdAt), nil
}
func (db DbAuthSqlite) InsertUser(user *User) error {
_, err := db.db.Exec(`
INSERT INTO user (user_uuid, email, email_verified, email_verified_at, is_admin, password, salt, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
user.Id, user.Email, user.EmailVerified, user.EmailVerifiedAt, user.IsAdmin, user.Password, user.Salt, user.CreateAt)
if err != nil {
if strings.Contains(err.Error(), "email") {
return ErrUserExists
}
utils.LogError("SQL error InsertUser", err)
return types.ErrInternal
}
return nil
}
func (db DbAuthSqlite) GetEmailVerificationToken(userId uuid.UUID) (string, error) {
var token string
err := db.db.QueryRow(`
SELECT token
FROM user_token
WHERE user_uuid = ?
AND type = 'email_verify'`, userId).Scan(&token)
if err != nil && err != sql.ErrNoRows {
utils.LogError("Could not get token", err)
return "", types.ErrInternal
}
return token, nil
}
func (db DbAuthSqlite) InsertEmailVerificationToken(userId uuid.UUID, token string) error {
_, err := db.db.Exec(`
INSERT INTO user_token (user_uuid, type, token, created_at)
VALUES (?, 'email_verify', ?, datetime())`, userId, token)
if err != nil {
utils.LogError("Could not insert token", err)
return types.ErrInternal
}
return nil
}