2021-12-18 07:07:12 -08:00
|
|
|
package services
|
2021-12-11 20:17:12 -08:00
|
|
|
|
|
|
|
import (
|
2021-12-15 18:17:39 -08:00
|
|
|
"crypto/rand"
|
2024-07-11 21:09:15 -07:00
|
|
|
"database/sql"
|
2021-12-15 18:17:39 -08:00
|
|
|
"encoding/hex"
|
2022-01-08 12:32:18 -08:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
2021-12-16 04:29:16 -08:00
|
|
|
"time"
|
2021-12-11 20:17:12 -08:00
|
|
|
|
2022-01-08 12:32:18 -08:00
|
|
|
"github.com/golang-jwt/jwt"
|
2021-12-11 20:17:12 -08:00
|
|
|
"github.com/labstack/echo/v4"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
2024-07-09 17:57:05 -07:00
|
|
|
|
|
|
|
"git.grosinger.net/tgrosinger/saasitone/config"
|
2024-07-11 21:09:15 -07:00
|
|
|
"git.grosinger.net/tgrosinger/saasitone/pkg/models/sqlc"
|
2024-07-09 17:57:05 -07:00
|
|
|
"git.grosinger.net/tgrosinger/saasitone/pkg/session"
|
2021-12-11 20:17:12 -08:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2021-12-18 07:07:12 -08:00
|
|
|
// authSessionName stores the name of the session which contains authentication data
|
|
|
|
authSessionName = "ua"
|
2021-12-16 04:29:16 -08:00
|
|
|
|
2021-12-18 07:07:12 -08:00
|
|
|
// authSessionKeyUserID stores the key used to store the user ID in the session
|
|
|
|
authSessionKeyUserID = "user_id"
|
2021-12-16 16:49:33 -08:00
|
|
|
|
2021-12-18 07:07:12 -08:00
|
|
|
// authSessionKeyAuthenticated stores the key used to store the authentication status in the session
|
|
|
|
authSessionKeyAuthenticated = "authenticated"
|
2021-12-17 16:58:44 -08:00
|
|
|
)
|
2021-12-16 16:49:33 -08:00
|
|
|
|
2021-12-17 17:58:51 -08:00
|
|
|
// NotAuthenticatedError is an error returned when a user is not authenticated
|
|
|
|
type NotAuthenticatedError struct{}
|
|
|
|
|
|
|
|
// Error implements the error interface.
|
|
|
|
func (e NotAuthenticatedError) Error() string {
|
|
|
|
return "user not authenticated"
|
|
|
|
}
|
|
|
|
|
2021-12-18 07:07:12 -08:00
|
|
|
// InvalidPasswordTokenError is an error returned when an invalid token is provided
|
|
|
|
type InvalidPasswordTokenError struct{}
|
2021-12-17 17:58:51 -08:00
|
|
|
|
|
|
|
// Error implements the error interface.
|
2021-12-18 07:07:12 -08:00
|
|
|
func (e InvalidPasswordTokenError) Error() string {
|
|
|
|
return "invalid password token"
|
2021-12-17 17:58:51 -08:00
|
|
|
}
|
|
|
|
|
2021-12-18 07:07:12 -08:00
|
|
|
// AuthClient is the client that handles authentication requests
|
2021-12-17 17:58:51 -08:00
|
|
|
type AuthClient struct {
|
2021-12-15 06:29:43 -08:00
|
|
|
config *config.Config
|
2024-07-11 21:31:54 -07:00
|
|
|
db *DBClient
|
2021-12-15 06:29:43 -08:00
|
|
|
}
|
|
|
|
|
2021-12-18 07:07:12 -08:00
|
|
|
// NewAuthClient creates a new authentication client
|
2024-07-11 21:31:54 -07:00
|
|
|
func NewAuthClient(cfg *config.Config, db *DBClient) *AuthClient {
|
2021-12-17 17:58:51 -08:00
|
|
|
return &AuthClient{
|
2021-12-15 06:29:43 -08:00
|
|
|
config: cfg,
|
2024-07-11 21:09:15 -07:00
|
|
|
db: db,
|
2021-12-15 06:29:43 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-17 16:58:44 -08:00
|
|
|
// Login logs in a user of a given ID
|
2021-12-17 17:58:51 -08:00
|
|
|
func (c *AuthClient) Login(ctx echo.Context, userID int) error {
|
2024-06-15 13:56:47 -07:00
|
|
|
sess, err := session.Get(ctx, authSessionName)
|
2021-12-11 20:17:12 -08:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-12-18 07:07:12 -08:00
|
|
|
sess.Values[authSessionKeyUserID] = userID
|
|
|
|
sess.Values[authSessionKeyAuthenticated] = true
|
2021-12-15 06:29:43 -08:00
|
|
|
return sess.Save(ctx.Request(), ctx.Response())
|
2021-12-11 20:17:12 -08:00
|
|
|
}
|
|
|
|
|
2021-12-17 16:58:44 -08:00
|
|
|
// Logout logs the requesting user out
|
2021-12-17 17:58:51 -08:00
|
|
|
func (c *AuthClient) Logout(ctx echo.Context) error {
|
2024-06-15 13:56:47 -07:00
|
|
|
sess, err := session.Get(ctx, authSessionName)
|
2021-12-11 20:17:12 -08:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-12-18 07:07:12 -08:00
|
|
|
sess.Values[authSessionKeyAuthenticated] = false
|
2021-12-15 06:29:43 -08:00
|
|
|
return sess.Save(ctx.Request(), ctx.Response())
|
2021-12-11 20:17:12 -08:00
|
|
|
}
|
|
|
|
|
2021-12-17 16:58:44 -08:00
|
|
|
// GetAuthenticatedUserID returns the authenticated user's ID, if the user is logged in
|
2021-12-17 17:58:51 -08:00
|
|
|
func (c *AuthClient) GetAuthenticatedUserID(ctx echo.Context) (int, error) {
|
2024-06-15 13:56:47 -07:00
|
|
|
sess, err := session.Get(ctx, authSessionName)
|
2021-12-11 20:17:12 -08:00
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
2021-12-18 07:07:12 -08:00
|
|
|
if sess.Values[authSessionKeyAuthenticated] == true {
|
|
|
|
return sess.Values[authSessionKeyUserID].(int), nil
|
2021-12-11 20:17:12 -08:00
|
|
|
}
|
|
|
|
|
2021-12-16 04:29:16 -08:00
|
|
|
return 0, NotAuthenticatedError{}
|
2021-12-11 20:17:12 -08:00
|
|
|
}
|
|
|
|
|
2021-12-17 16:58:44 -08:00
|
|
|
// GetAuthenticatedUser returns the authenticated user if the user is logged in
|
2024-07-11 21:09:15 -07:00
|
|
|
func (c *AuthClient) GetAuthenticatedUser(ctx echo.Context) (*sqlc.User, error) {
|
2021-12-15 06:29:43 -08:00
|
|
|
if userID, err := c.GetAuthenticatedUserID(ctx); err == nil {
|
2024-07-11 21:09:15 -07:00
|
|
|
u, err := c.db.C.GetUserByID(ctx.Request().Context(), userID)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &u, nil
|
2021-12-15 06:29:43 -08:00
|
|
|
}
|
|
|
|
|
2021-12-16 04:29:16 -08:00
|
|
|
return nil, NotAuthenticatedError{}
|
2021-12-15 06:29:43 -08:00
|
|
|
}
|
|
|
|
|
2021-12-17 16:58:44 -08:00
|
|
|
// HashPassword returns a hash of a given password
|
2021-12-17 17:58:51 -08:00
|
|
|
func (c *AuthClient) HashPassword(password string) (string, error) {
|
2021-12-11 20:17:12 -08:00
|
|
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return string(hash), nil
|
|
|
|
}
|
|
|
|
|
2021-12-17 16:58:44 -08:00
|
|
|
// CheckPassword check if a given password matches a given hash
|
2021-12-17 17:58:51 -08:00
|
|
|
func (c *AuthClient) CheckPassword(password, hash string) error {
|
2021-12-11 20:17:12 -08:00
|
|
|
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
|
|
|
}
|
2021-12-15 18:17:39 -08:00
|
|
|
|
2021-12-17 16:58:44 -08:00
|
|
|
// GeneratePasswordResetToken generates a password reset token for a given user.
|
|
|
|
// For security purposes, the token itself is not stored in the database but rather
|
|
|
|
// a hash of the token, exactly how passwords are handled. This method returns both
|
|
|
|
// the generated token as well as the token entity which only contains the hash.
|
2024-07-11 21:09:15 -07:00
|
|
|
func (c *AuthClient) GeneratePasswordResetToken(ctx echo.Context, userID int) (string, sqlc.PasswordToken, error) {
|
2021-12-15 18:17:39 -08:00
|
|
|
// Generate the token, which is what will go in the URL, but not the database
|
2021-12-17 16:58:44 -08:00
|
|
|
token, err := c.RandomToken(c.config.App.PasswordToken.Length)
|
2021-12-16 17:58:38 -08:00
|
|
|
if err != nil {
|
2024-07-11 21:09:15 -07:00
|
|
|
return "", sqlc.PasswordToken{}, err
|
2021-12-16 17:58:38 -08:00
|
|
|
}
|
2021-12-15 18:17:39 -08:00
|
|
|
|
|
|
|
// Hash the token, which is what will be stored in the database
|
|
|
|
hash, err := c.HashPassword(token)
|
|
|
|
if err != nil {
|
2024-07-11 21:09:15 -07:00
|
|
|
return "", sqlc.PasswordToken{}, err
|
2021-12-15 18:17:39 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Create and save the password reset token
|
2024-07-11 21:09:15 -07:00
|
|
|
pt, err := c.db.C.CreatePasswordToken(ctx.Request().Context(), sqlc.CreatePasswordTokenParams{
|
|
|
|
Hash: hash,
|
|
|
|
PasswordTokenUser: userID,
|
|
|
|
})
|
2021-12-15 18:17:39 -08:00
|
|
|
|
|
|
|
return token, pt, err
|
|
|
|
}
|
|
|
|
|
2022-01-27 05:44:12 -08:00
|
|
|
// GetValidPasswordToken returns a valid, non-expired password token entity for a given user, token ID and token.
|
|
|
|
// Since the actual token is not stored in the database for security purposes, if a matching password token entity is
|
|
|
|
// found a hash of the provided token is compared with the hash stored in the database in order to validate.
|
2024-07-11 21:09:15 -07:00
|
|
|
func (c *AuthClient) GetValidPasswordToken(ctx echo.Context, userID, tokenID int, token string) (*sqlc.PasswordToken, error) {
|
2021-12-16 16:49:33 -08:00
|
|
|
// Ensure expired tokens are never returned
|
2021-12-17 16:58:44 -08:00
|
|
|
expiration := time.Now().Add(-c.config.App.PasswordToken.Expiration)
|
2021-12-16 04:29:16 -08:00
|
|
|
|
2022-01-27 05:44:12 -08:00
|
|
|
// Query to find a password token entity that matches the given user and token ID
|
2024-07-11 21:09:15 -07:00
|
|
|
pt, err := c.db.C.GetValidPasswordToken(ctx.Request().Context(),
|
|
|
|
sqlc.GetValidPasswordTokenParams{
|
|
|
|
ID: tokenID,
|
|
|
|
PasswordTokenUser: userID,
|
|
|
|
Datetime: expiration,
|
|
|
|
})
|
|
|
|
|
|
|
|
if err == sql.ErrNoRows {
|
|
|
|
return nil, InvalidPasswordTokenError{}
|
|
|
|
} else if err != nil {
|
|
|
|
return nil, err
|
2021-12-16 04:29:16 -08:00
|
|
|
}
|
|
|
|
|
2024-07-11 21:09:15 -07:00
|
|
|
// Check the token for a hash match
|
|
|
|
if err := c.CheckPassword(token, pt.Hash); err == nil {
|
|
|
|
return &pt, nil
|
|
|
|
}
|
2021-12-18 07:07:12 -08:00
|
|
|
return nil, InvalidPasswordTokenError{}
|
2021-12-16 04:29:16 -08:00
|
|
|
}
|
|
|
|
|
2021-12-17 16:58:44 -08:00
|
|
|
// DeletePasswordTokens deletes all password tokens in the database for a belonging to a given user.
|
|
|
|
// This should be called after a successful password reset.
|
2021-12-17 17:58:51 -08:00
|
|
|
func (c *AuthClient) DeletePasswordTokens(ctx echo.Context, userID int) error {
|
2024-07-11 21:09:15 -07:00
|
|
|
return c.db.C.DeletePasswordTokens(ctx.Request().Context(), userID)
|
2021-12-16 18:27:52 -08:00
|
|
|
}
|
|
|
|
|
2021-12-17 16:58:44 -08:00
|
|
|
// RandomToken generates a random token string of a given length
|
2021-12-17 17:58:51 -08:00
|
|
|
func (c *AuthClient) RandomToken(length int) (string, error) {
|
|
|
|
b := make([]byte, (length/2)+1)
|
2021-12-15 18:17:39 -08:00
|
|
|
if _, err := rand.Read(b); err != nil {
|
2021-12-16 17:58:38 -08:00
|
|
|
return "", err
|
2021-12-15 18:17:39 -08:00
|
|
|
}
|
2021-12-17 17:58:51 -08:00
|
|
|
token := hex.EncodeToString(b)
|
|
|
|
return token[:length], nil
|
2021-12-15 18:17:39 -08:00
|
|
|
}
|
2022-01-08 12:32:18 -08:00
|
|
|
|
|
|
|
// GenerateEmailVerificationToken generates an email verification token for a given email address using JWT which
|
|
|
|
// is set to expire based on the duration stored in configuration
|
|
|
|
func (c *AuthClient) GenerateEmailVerificationToken(email string) (string, error) {
|
|
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
|
|
|
"email": email,
|
|
|
|
"exp": time.Now().Add(c.config.App.EmailVerificationTokenExpiration).Unix(),
|
|
|
|
})
|
|
|
|
|
|
|
|
return token.SignedString([]byte(c.config.App.EncryptionKey))
|
|
|
|
}
|
|
|
|
|
|
|
|
// ValidateEmailVerificationToken validates an email verification token and returns the associated email address if
|
|
|
|
// the token is valid and has not expired
|
|
|
|
func (c *AuthClient) ValidateEmailVerificationToken(token string) (string, error) {
|
2023-12-16 08:07:20 -08:00
|
|
|
t, err := jwt.Parse(token, func(t *jwt.Token) (any, error) {
|
2022-01-08 12:32:18 -08:00
|
|
|
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
|
|
|
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
|
|
|
|
}
|
|
|
|
|
|
|
|
return []byte(c.config.App.EncryptionKey), nil
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
if claims, ok := t.Claims.(jwt.MapClaims); ok && t.Valid {
|
|
|
|
return claims["email"].(string), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return "", errors.New("invalid or expired token")
|
|
|
|
}
|