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"
|
|
|
|
"encoding/hex"
|
2021-12-16 04:29:16 -08:00
|
|
|
"time"
|
2021-12-11 20:17:12 -08:00
|
|
|
|
2021-12-15 06:29:43 -08:00
|
|
|
"goweb/config"
|
|
|
|
"goweb/ent"
|
2021-12-16 04:29:16 -08:00
|
|
|
"goweb/ent/passwordtoken"
|
2021-12-15 06:29:43 -08:00
|
|
|
"goweb/ent/user"
|
|
|
|
|
2021-12-11 20:17:12 -08:00
|
|
|
"github.com/labstack/echo-contrib/session"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
|
|
)
|
|
|
|
|
|
|
|
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
|
|
|
|
orm *ent.Client
|
|
|
|
}
|
|
|
|
|
2021-12-18 07:07:12 -08:00
|
|
|
// NewAuthClient creates a new authentication client
|
2021-12-17 17:58:51 -08:00
|
|
|
func NewAuthClient(cfg *config.Config, orm *ent.Client) *AuthClient {
|
|
|
|
return &AuthClient{
|
2021-12-15 06:29:43 -08:00
|
|
|
config: cfg,
|
|
|
|
orm: orm,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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 {
|
2021-12-18 07:07:12 -08:00
|
|
|
sess, err := session.Get(authSessionName, ctx)
|
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 {
|
2021-12-18 07:07:12 -08:00
|
|
|
sess, err := session.Get(authSessionName, ctx)
|
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) {
|
2021-12-18 07:07:12 -08:00
|
|
|
sess, err := session.Get(authSessionName, ctx)
|
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
|
2021-12-17 17:58:51 -08:00
|
|
|
func (c *AuthClient) GetAuthenticatedUser(ctx echo.Context) (*ent.User, error) {
|
2021-12-15 06:29:43 -08:00
|
|
|
if userID, err := c.GetAuthenticatedUserID(ctx); err == nil {
|
|
|
|
return c.orm.User.Query().
|
|
|
|
Where(user.ID(userID)).
|
2021-12-16 17:58:38 -08:00
|
|
|
Only(ctx.Request().Context())
|
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.
|
2021-12-17 17:58:51 -08:00
|
|
|
func (c *AuthClient) GeneratePasswordResetToken(ctx echo.Context, userID int) (string, *ent.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 {
|
|
|
|
return "", nil, err
|
|
|
|
}
|
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 {
|
|
|
|
return "", nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create and save the password reset token
|
|
|
|
pt, err := c.orm.PasswordToken.
|
|
|
|
Create().
|
|
|
|
SetHash(hash).
|
|
|
|
SetUserID(userID).
|
|
|
|
Save(ctx.Request().Context())
|
|
|
|
|
|
|
|
return token, pt, err
|
|
|
|
}
|
|
|
|
|
2021-12-17 16:58:44 -08:00
|
|
|
// GetValidPasswordToken returns a valid password token entity for a given user and a given token.
|
|
|
|
// Since the actual token is not stored in the database for security purposes, all non-expired token entities
|
|
|
|
// are fetched from the database belonging to the requesting user and a hash of the provided token is compared
|
|
|
|
// with the hash stored in the database.
|
2021-12-17 17:58:51 -08:00
|
|
|
func (c *AuthClient) GetValidPasswordToken(ctx echo.Context, token string, userID int) (*ent.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
|
|
|
|
2021-12-16 16:49:33 -08:00
|
|
|
// Query to find all tokens for te user that haven't expired
|
|
|
|
// We need to get all of them in order to properly match the token to the hashes
|
|
|
|
pts, err := c.orm.PasswordToken.
|
2021-12-16 04:29:16 -08:00
|
|
|
Query().
|
2021-12-16 16:49:33 -08:00
|
|
|
Where(passwordtoken.HasUserWith(user.ID(userID))).
|
|
|
|
Where(passwordtoken.CreatedAtGTE(expiration)).
|
|
|
|
All(ctx.Request().Context())
|
2021-12-16 04:29:16 -08:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
ctx.Logger().Error(err)
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2021-12-16 16:49:33 -08:00
|
|
|
// Check all tokens for a hash match
|
|
|
|
for _, pt := range pts {
|
|
|
|
if err := c.CheckPassword(token, pt.Hash); err == nil {
|
|
|
|
return pt, nil
|
|
|
|
}
|
2021-12-16 04:29:16 -08:00
|
|
|
}
|
|
|
|
|
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 {
|
2021-12-16 18:27:52 -08:00
|
|
|
_, err := c.orm.PasswordToken.
|
|
|
|
Delete().
|
|
|
|
Where(passwordtoken.HasUserWith(user.ID(userID))).
|
|
|
|
Exec(ctx.Request().Context())
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
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
|
|
|
}
|