245 lines
6.9 KiB
Go
245 lines
6.9 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"crypto/hmac"
|
|
"crypto/sha256"
|
|
"crypto/subtle"
|
|
"database/sql"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/google/uuid"
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
const (
|
|
sessionCookieName = "studio_session"
|
|
visitorCookieName = "studio_visitor"
|
|
accessCookieName = "studio_gallery_access"
|
|
sessionDuration = 7 * 24 * time.Hour
|
|
accessDuration = 12 * time.Hour
|
|
)
|
|
|
|
var (
|
|
ErrInvalidCredentials = errors.New("invalid credentials")
|
|
ErrInvalidSession = errors.New("invalid session")
|
|
ErrCurrentPassword = errors.New("current password is incorrect")
|
|
)
|
|
|
|
type Service struct {
|
|
repository *Repository
|
|
secret []byte
|
|
secure bool
|
|
}
|
|
|
|
func NewService(repository *Repository, secret string, secureCookie bool) (*Service, error) {
|
|
if len(secret) < 32 {
|
|
return nil, fmt.Errorf("session secret must be at least 32 characters")
|
|
}
|
|
return &Service{repository: repository, secret: []byte(secret), secure: secureCookie}, nil
|
|
}
|
|
|
|
func (s *Service) Register(ctx context.Context, email, password, name string) (User, error) {
|
|
email = strings.ToLower(strings.TrimSpace(email))
|
|
name = strings.TrimSpace(name)
|
|
if !strings.Contains(email, "@") || len(email) > 254 {
|
|
return User{}, fmt.Errorf("enter a valid email address")
|
|
}
|
|
if len(password) < 8 {
|
|
return User{}, fmt.Errorf("password must be at least 8 characters")
|
|
}
|
|
if name == "" || len(name) > 120 {
|
|
return User{}, fmt.Errorf("name is required")
|
|
}
|
|
|
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
return User{}, fmt.Errorf("hash password: %w", err)
|
|
}
|
|
return s.repository.CreateUser(ctx, email, string(hash), name)
|
|
}
|
|
|
|
func (s *Service) Login(ctx context.Context, email, password string) (User, error) {
|
|
user, err := s.repository.FindByEmail(ctx, email)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return User{}, ErrInvalidCredentials
|
|
}
|
|
if err != nil {
|
|
return User{}, err
|
|
}
|
|
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password)); err != nil {
|
|
return User{}, ErrInvalidCredentials
|
|
}
|
|
return user.User, nil
|
|
}
|
|
|
|
func (s *Service) UpdateProfile(ctx context.Context, userID uuid.UUID, email, name string) (User, error) {
|
|
email = strings.ToLower(strings.TrimSpace(email))
|
|
name = strings.TrimSpace(name)
|
|
if !strings.Contains(email, "@") || len(email) > 254 {
|
|
return User{}, fmt.Errorf("enter a valid email address")
|
|
}
|
|
if name == "" || len(name) > 120 {
|
|
return User{}, fmt.Errorf("name is required")
|
|
}
|
|
return s.repository.UpdateUser(ctx, userID, email, name)
|
|
}
|
|
|
|
func (s *Service) ChangePassword(ctx context.Context, userID uuid.UUID, currentPassword, newPassword string) error {
|
|
if len(newPassword) < 8 {
|
|
return fmt.Errorf("new password must be at least 8 characters")
|
|
}
|
|
user, err := s.repository.FindByIDWithPassword(ctx, userID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(currentPassword)); err != nil {
|
|
return ErrCurrentPassword
|
|
}
|
|
hash, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
return fmt.Errorf("hash new password: %w", err)
|
|
}
|
|
return s.repository.UpdatePassword(ctx, userID, string(hash))
|
|
}
|
|
|
|
func (s *Service) SetSession(c *gin.Context, user User) {
|
|
payload := sessionPayload{UserID: user.ID.String(), ExpiresAt: time.Now().Add(sessionDuration).Unix()}
|
|
token, err := s.signJSON(payload)
|
|
if err != nil {
|
|
return
|
|
}
|
|
s.setCookie(c, sessionCookieName, token, int(sessionDuration.Seconds()), true)
|
|
}
|
|
|
|
func (s *Service) ClearSession(c *gin.Context) {
|
|
s.setCookie(c, sessionCookieName, "", -1, true)
|
|
}
|
|
|
|
func (s *Service) UserFromRequest(ctx context.Context, r *http.Request) (User, error) {
|
|
cookie, err := r.Cookie(sessionCookieName)
|
|
if err != nil {
|
|
return User{}, ErrInvalidSession
|
|
}
|
|
var payload sessionPayload
|
|
if err := s.verifyJSON(cookie.Value, &payload); err != nil {
|
|
return User{}, ErrInvalidSession
|
|
}
|
|
userID, err := uuid.Parse(payload.UserID)
|
|
if err != nil || payload.ExpiresAt <= time.Now().Unix() {
|
|
return User{}, ErrInvalidSession
|
|
}
|
|
user, err := s.repository.FindByID(ctx, userID)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return User{}, ErrInvalidSession
|
|
}
|
|
return user, err
|
|
}
|
|
|
|
type contextKey string
|
|
|
|
const userContextKey contextKey = "authenticated-user"
|
|
|
|
func (s *Service) Require() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
user, err := s.UserFromRequest(c.Request.Context(), c.Request)
|
|
if err != nil {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, map[string]string{"error": "authentication required"})
|
|
return
|
|
}
|
|
c.Set(userContextKey, user)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func UserFromContext(c *gin.Context) (User, bool) {
|
|
value, ok := c.Get(userContextKey)
|
|
user, valid := value.(User)
|
|
return user, ok && valid
|
|
}
|
|
|
|
func (s *Service) EnsureVisitor(c *gin.Context) string {
|
|
if cookie, err := c.Request.Cookie(visitorCookieName); err == nil {
|
|
if _, err := uuid.Parse(cookie.Value); err == nil {
|
|
return cookie.Value
|
|
}
|
|
}
|
|
|
|
visitorID := uuid.NewString()
|
|
s.setCookie(c, visitorCookieName, visitorID, int(365*24*time.Hour/time.Second), true)
|
|
return visitorID
|
|
}
|
|
|
|
func (s *Service) GrantGalleryAccess(c *gin.Context, slug string) {
|
|
payload := accessPayload{Slug: slug, ExpiresAt: time.Now().Add(accessDuration).Unix()}
|
|
token, err := s.signJSON(payload)
|
|
if err != nil {
|
|
return
|
|
}
|
|
s.setCookie(c, accessCookieName, token, int(accessDuration.Seconds()), true)
|
|
}
|
|
|
|
func (s *Service) HasGalleryAccess(c *gin.Context, slug string) bool {
|
|
cookie, err := c.Request.Cookie(accessCookieName)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
var payload accessPayload
|
|
if err := s.verifyJSON(cookie.Value, &payload); err != nil {
|
|
return false
|
|
}
|
|
return payload.Slug == slug && payload.ExpiresAt > time.Now().Unix()
|
|
}
|
|
|
|
func (s *Service) setCookie(c *gin.Context, name, value string, maxAge int, httpOnly bool) {
|
|
c.SetSameSite(http.SameSiteLaxMode)
|
|
c.SetCookie(name, value, maxAge, "/", "", s.secure, httpOnly)
|
|
}
|
|
|
|
type sessionPayload struct {
|
|
UserID string `json:"userId"`
|
|
ExpiresAt int64 `json:"expiresAt"`
|
|
}
|
|
|
|
type accessPayload struct {
|
|
Slug string `json:"slug"`
|
|
ExpiresAt int64 `json:"expiresAt"`
|
|
}
|
|
|
|
func (s *Service) signJSON(value any) (string, error) {
|
|
data, err := json.Marshal(value)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
encoded := base64.RawURLEncoding.EncodeToString(data)
|
|
return encoded + "." + s.signature(encoded), nil
|
|
}
|
|
|
|
func (s *Service) verifyJSON(token string, target any) error {
|
|
encoded, signature, ok := strings.Cut(token, ".")
|
|
if !ok || subtle.ConstantTimeCompare([]byte(signature), []byte(s.signature(encoded))) != 1 {
|
|
return ErrInvalidSession
|
|
}
|
|
data, err := base64.RawURLEncoding.DecodeString(encoded)
|
|
if err != nil {
|
|
return ErrInvalidSession
|
|
}
|
|
if err := json.Unmarshal(data, target); err != nil {
|
|
return ErrInvalidSession
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *Service) signature(value string) string {
|
|
hash := hmac.New(sha256.New, s.secret)
|
|
_, _ = hash.Write([]byte(value))
|
|
return base64.RawURLEncoding.EncodeToString(hash.Sum(nil))
|
|
}
|