feat(identity): store users, email tokens, and sessions
This commit is contained in:
1 parent
15e2e50561
commit
e7d0d92ef9
30 files changed
+4792
-32
No files matched your search
@@ -0,0 +1,67 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var ErrInvalidSession = errors.New("invalid session")
|
||||
|
||||
// Session is a server-side login session. The cookie carries the raw
|
||||
// SecretToken; storage keeps only TokenHash. ID identifies the session inside
|
||||
// the server, for example to revoke it, and never leaves the server.
|
||||
//
|
||||
// A session is active while it is not revoked, ExpiresAt (the absolute
|
||||
// deadline) is in the future, and LastSeenAt is within the idle timeout.
|
||||
// Activity moves only LastSeenAt.
|
||||
type Session struct {
|
||||
ID uuid.UUID
|
||||
UserID uuid.UUID
|
||||
TokenHash SecretTokenHash
|
||||
CreatedAt time.Time
|
||||
LastSeenAt time.Time
|
||||
ExpiresAt time.Time
|
||||
RevokedAt *time.Time
|
||||
}
|
||||
|
||||
// NewSessionInput describes a session to start. AbsoluteLifetime fixes
|
||||
// ExpiresAt; the idle timeout is applied when the session is looked up.
|
||||
type NewSessionInput struct {
|
||||
UserID uuid.UUID
|
||||
TokenHash SecretTokenHash
|
||||
StartedAt time.Time
|
||||
AbsoluteLifetime time.Duration
|
||||
}
|
||||
|
||||
// NewSession validates input and assigns a UUIDv7 identifier.
|
||||
func NewSession(input NewSessionInput) (Session, error) {
|
||||
switch {
|
||||
case input.UserID == uuid.Nil:
|
||||
return Session{}, invalidSession("user ID must not be nil")
|
||||
case input.TokenHash.IsZero():
|
||||
return Session{}, invalidSession("token hash must be set")
|
||||
case input.StartedAt.IsZero():
|
||||
return Session{}, invalidSession("start time must be set")
|
||||
case input.AbsoluteLifetime <= 0:
|
||||
return Session{}, invalidSession("absolute lifetime must be positive")
|
||||
}
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return Session{}, fmt.Errorf("domain.NewSession - generate session ID: %w", err)
|
||||
}
|
||||
return Session{
|
||||
ID: id,
|
||||
UserID: input.UserID,
|
||||
TokenHash: input.TokenHash,
|
||||
CreatedAt: input.StartedAt,
|
||||
LastSeenAt: input.StartedAt,
|
||||
ExpiresAt: input.StartedAt.Add(input.AbsoluteLifetime),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func invalidSession(reason string) error {
|
||||
return fmt.Errorf("domain.NewSession - %s: %w", reason, ErrInvalidSession)
|
||||
}
|
||||
Reference in new issue
Block a user