44 lines
847 B
Go
44 lines
847 B
Go
// Package auth provides authentication functionality.
|
|
// It handles user authentication against the database and password verification.
|
|
package auth
|
|
|
|
import (
|
|
"dk/internal/models/users"
|
|
"dk/internal/password"
|
|
)
|
|
|
|
func Authenticate(usernameOrEmail, plainPassword string) (*users.User, error) {
|
|
var user *users.User
|
|
var err error
|
|
|
|
user, err = users.ByUsername(usernameOrEmail)
|
|
if err != nil {
|
|
user, err = users.ByEmail(usernameOrEmail)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
isValid, err := password.Verify(plainPassword, user.Password)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !isValid {
|
|
return nil, ErrInvalidCredentials
|
|
}
|
|
|
|
return user, nil
|
|
}
|
|
|
|
var (
|
|
ErrInvalidCredentials = &AuthError{"invalid username/email or password"}
|
|
)
|
|
|
|
type AuthError struct {
|
|
Message string
|
|
}
|
|
|
|
func (e *AuthError) Error() string {
|
|
return e.Message
|
|
}
|