chore(auth): start refactoring for testable code #181
This commit is contained in:
78
db/auth.go
Normal file
78
db/auth.go
Normal file
@@ -0,0 +1,78 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user