Overview
The session package provides:- Session creation and retrieval
- User association
- Expiration tracking
- Database persistence
- Integration with the auth domain
Session Model
Sessions are represented by theSession struct:
- Has a unique ID (UUID)
- Is associated with a user ID
- Tracks creation time
- Has an expiration timestamp
Checking Expiration
TheSession model includes a helper method:
Setting Up Sessions
1
Create database connection
2
Create session domain
New function creates both the repository and service.3
Register repository
4
Run migrations
Service Methods
Thesession.Service provides methods for session management:
Create Session
Create a new session manually:Create Session for User
Create a session for a user (automatically sets ID, timestamps):Get Session
Retrieve a session by ID:Get Session by User ID
Retrieve a session by user ID:Get User ID from Session
Extract the user ID from a session:Delete Session
Delete a specific session:Delete All User Sessions
Delete all sessions for a user (useful for logout from all devices):Integration with Auth
The session service is designed to work with the auth domain. The auth service uses it to manage authentication sessions:CreateSessionForUser- When logging inGetUserIdFromSessionId- In authentication middlewareDeleteSession- When logging outDeleteSessionsByUserId- When deleting a user account
Domain Structure
Thesession.Domain contains both repository and service:
Repository Implementation
The repository handles database operations:session/migrations/*.sql.
Database Schema
The sessions table structure:user column is quoted because user is a reserved word in PostgreSQL.
Custom Expiration
To customize session expiration, create sessions manually:Session Cleanup
Expired sessions are not automatically deleted from the database. You should periodically clean them up:Session Validation
Always check session expiration when validating:Best Practices
Set reasonable expiration
Balance security and UX: short expiration (hours/days) for sensitive apps, longer (weeks/months) for convenience.
Clean up expired sessions
Schedule periodic cleanup to prevent the sessions table from growing indefinitely.
Invalidate on logout
Always delete sessions when users explicitly log out.
Rotate session IDs
Consider rotating session IDs after privileged operations to prevent session fixation attacks.