Files

87 lines
2.3 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package usecase
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"time"
"unicode/utf8"
"backend/internal/domain/model"
"backend/internal/domain/port"
)
type Auth struct {
sessions port.Sessions
passwords port.Passwords
messenger *Messenger
ttl time.Duration
now func() time.Time
}
type Session struct {
Token string
ExpiresAt time.Time
User model.User
}
func NewAuth(s port.Sessions, p port.Passwords, m *Messenger, ttl time.Duration, now func() time.Time) *Auth {
return &Auth{s, p, m, ttl, now}
}
func (a *Auth) Register(ctx context.Context, username, name, password string) (model.User, error) {
if n := utf8.RuneCountInString(password); n < 12 || n > 128 || !utf8.ValidString(password) {
return model.User{}, &model.ValidationError{Message: "password: 12–128 Unicode characters"}
}
draft, err := model.NewUserDraft(username, name)
if err != nil {
return model.User{}, err
}
hash, err := a.passwords.Hash(password)
if err != nil {
return model.User{}, err
}
draft.PasswordHash = hash
return a.messenger.repo.CreateUser(ctx, draft)
}
func (a *Auth) Login(ctx context.Context, username, password string) (Session, error) {
id, hash, err := a.sessions.Credentials(ctx, username)
if err != nil {
return Session{}, err
}
if !a.passwords.Verify(password, hash) {
return Session{}, model.ErrUnauthorized
}
user, err := a.messenger.repo.GetUser(ctx, id)
if err != nil {
return Session{}, err
}
raw := make([]byte, 32)
if _, err = rand.Read(raw); err != nil {
return Session{}, err
}
token := base64.RawURLEncoding.EncodeToString(raw)
expires := a.now().UTC().Add(a.ttl)
if err = a.sessions.CreateSession(ctx, TokenHash(token), id, expires); err != nil {
return Session{}, err
}
return Session{token, expires, user}, nil
}
func TokenHash(token string) string {
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:])
}
func (a *Auth) Authenticate(ctx context.Context, token string) (model.User, error) {
if len(token) != 43 {
return model.User{}, model.ErrUnauthorized
}
id, err := a.sessions.AuthenticateSession(ctx, TokenHash(token))
if err != nil {
return model.User{}, err
}
return a.messenger.repo.GetUser(ctx, id)
}
func (a *Auth) Logout(ctx context.Context, token string) error {
return a.sessions.RevokeSession(ctx, TokenHash(token))
}