Files
lincodex/backend/internal/usecase/identity/credentials.go
T

55 lines
2.1 KiB
Go

// Package identity holds the account usecases.
package identity
import (
"context"
"fmt"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// Credentials applies the password rules in the order that keeps hashing
// bounded: the cheap length and encoding checks first, the expensive KDF only
// for a password that passes them.
type Credentials struct {
hasher outbound.PasswordHasher
}
func NewCredentials(hasher outbound.PasswordHasher) *Credentials {
return &Credentials{hasher: hasher}
}
// HashNewPassword applies the registration password policy to raw and hashes
// the normalized password. A password outside the policy returns an error
// wrapping domain.ErrInvalidPassword without calling the hasher. Errors
// never contain raw. Registration must call
// it on every branch before it looks up the email, so that neither the
// outcome nor the time depends on whether the account exists.
func (credentials *Credentials) HashNewPassword(ctx context.Context, raw string) (domain.PasswordHash, error) {
password, err := domain.NewPassword(raw)
if err != nil {
return domain.PasswordHash{}, fmt.Errorf("Credentials.HashNewPassword - validate password: %w", err)
}
hash, err := credentials.hasher.Hash(ctx, password)
if err != nil {
return domain.PasswordHash{}, fmt.Errorf("Credentials.HashNewPassword - hash password: %w", err)
}
return hash, nil
}
// VerifyLoginPassword normalizes and checks a password with the login bounds.
// It does not apply the registration blocklist, so an existing registration
// can confirm even when that password is no longer accepted for new accounts.
func (credentials *Credentials) VerifyLoginPassword(ctx context.Context, raw string, stored domain.PasswordHash) error {
const location = "Credentials.VerifyLoginPassword"
password, err := domain.ParseLoginPassword(raw)
if err != nil {
return fmt.Errorf("%s - validate password: %w", location, err)
}
if _, err := credentials.hasher.Verify(ctx, password, stored); err != nil {
return fmt.Errorf("%s - verify password: %w", location, err)
}
return nil
}