ai slop ah
This commit is contained in:
@@ -14,6 +14,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
@@ -29,6 +30,7 @@ const (
|
||||
var (
|
||||
ErrInvalidCredentials = errors.New("invalid credentials")
|
||||
ErrInvalidSession = errors.New("invalid session")
|
||||
ErrCurrentPassword = errors.New("current password is incorrect")
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
@@ -78,33 +80,47 @@ func (s *Service) Login(ctx context.Context, email, password string) (User, erro
|
||||
return user.User, nil
|
||||
}
|
||||
|
||||
func (s *Service) SetSession(w http.ResponseWriter, user User) {
|
||||
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
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: sessionCookieName,
|
||||
Value: token,
|
||||
Path: "/",
|
||||
MaxAge: int(sessionDuration.Seconds()),
|
||||
HttpOnly: true,
|
||||
Secure: s.secure,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
s.setCookie(c, sessionCookieName, token, int(sessionDuration.Seconds()), true)
|
||||
}
|
||||
|
||||
func (s *Service) ClearSession(w http.ResponseWriter) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: sessionCookieName,
|
||||
Value: "",
|
||||
Path: "/",
|
||||
MaxAge: -1,
|
||||
HttpOnly: true,
|
||||
Secure: s.secure,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
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) {
|
||||
@@ -131,61 +147,47 @@ type contextKey string
|
||||
|
||||
const userContextKey contextKey = "authenticated-user"
|
||||
|
||||
func (s *Service) Require(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
user, err := s.UserFromRequest(r.Context(), r)
|
||||
func (s *Service) Require() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
user, err := s.UserFromRequest(c.Request.Context(), c.Request)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "authentication required"})
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, map[string]string{"error": "authentication required"})
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), userContextKey, user)))
|
||||
})
|
||||
c.Set(userContextKey, user)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func UserFromContext(ctx context.Context) (User, bool) {
|
||||
user, ok := ctx.Value(userContextKey).(User)
|
||||
return user, ok
|
||||
func UserFromContext(c *gin.Context) (User, bool) {
|
||||
value, ok := c.Get(userContextKey)
|
||||
user, valid := value.(User)
|
||||
return user, ok && valid
|
||||
}
|
||||
|
||||
func (s *Service) EnsureVisitor(w http.ResponseWriter, r *http.Request) string {
|
||||
if cookie, err := r.Cookie(visitorCookieName); err == nil {
|
||||
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()
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: visitorCookieName,
|
||||
Value: visitorID,
|
||||
Path: "/",
|
||||
MaxAge: int(365 * 24 * time.Hour / time.Second),
|
||||
HttpOnly: true,
|
||||
Secure: s.secure,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
s.setCookie(c, visitorCookieName, visitorID, int(365*24*time.Hour/time.Second), true)
|
||||
return visitorID
|
||||
}
|
||||
|
||||
func (s *Service) GrantGalleryAccess(w http.ResponseWriter, slug string) {
|
||||
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
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: accessCookieName,
|
||||
Value: token,
|
||||
Path: "/",
|
||||
MaxAge: int(accessDuration.Seconds()),
|
||||
HttpOnly: true,
|
||||
Secure: s.secure,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
s.setCookie(c, accessCookieName, token, int(accessDuration.Seconds()), true)
|
||||
}
|
||||
|
||||
func (s *Service) HasGalleryAccess(r *http.Request, slug string) bool {
|
||||
cookie, err := r.Cookie(accessCookieName)
|
||||
func (s *Service) HasGalleryAccess(c *gin.Context, slug string) bool {
|
||||
cookie, err := c.Request.Cookie(accessCookieName)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
@@ -196,6 +198,11 @@ func (s *Service) HasGalleryAccess(r *http.Request, slug string) bool {
|
||||
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"`
|
||||
@@ -235,9 +242,3 @@ func (s *Service) signature(value string) string {
|
||||
_, _ = hash.Write([]byte(value))
|
||||
return base64.RawURLEncoding.EncodeToString(hash.Sum(nil))
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user