Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/platforma-dev/platforma/llms.txt

Use this file to discover all available pages before exploring further.

Overview

The session package provides session management functionality for authentication systems. It handles session creation, retrieval, and deletion with database persistence.

Domain

session.Domain

The main domain aggregate for session management.
type Domain struct {
    Repository *Repository
    Service    *Service
}
Repository
*Repository
Database repository for session persistence
Service
*Service
Business logic service for session operations

Constructor

func New(db db) *Domain
db
db
required
Database interface (sqlx-compatible)
Domain
*Domain
Configured session domain with repository and service

Service

session.Service

Core business logic for session management.
type Service struct {
    repo *Repository
}

Methods

CreateSessionForUser

func (s *Service) CreateSessionForUser(ctx context.Context, userId string) (string, error)
Creates a new session for a user with a 100-day expiration.
userId
string
required
User ID to associate with the session
sessionId
string
Generated UUID for the new session
error
error
Error if session creation fails
session/service.go:46

GetUserIdFromSessionId

func (s *Service) GetUserIdFromSessionId(ctx context.Context, id string) (string, error)
Retrieves the user ID associated with a session.
id
string
required
Session ID to lookup
userId
string
User ID associated with the session
error
error
Error if session not found
session/service.go:37

Get

func (s *Service) Get(ctx context.Context, id string) (*Session, error)
Retrieves a session by ID.
id
string
required
Session ID to retrieve
Session
*Session
Session object if found
error
error
Error if session not found
session/service.go:25

GetByUserId

func (s *Service) GetByUserId(ctx context.Context, id string) (*Session, error)
Retrieves a session by user ID.
id
string
required
User ID to lookup
Session
*Session
Session object if found
error
error
Error if session not found
session/service.go:29

DeleteSession

func (s *Service) DeleteSession(ctx context.Context, id string) error
Deletes a session by ID.
id
string
required
Session ID to delete
error
error
Error if deletion fails
session/service.go:33

DeleteSessionsByUserId

func (s *Service) DeleteSessionsByUserId(ctx context.Context, userId string) error
Deletes all sessions for a user (used during account deletion).
userId
string
required
User ID whose sessions to delete
error
error
Error if deletion fails
session/service.go:62

Create

func (s *Service) Create(ctx context.Context, session *Session) error
Creates a session with custom parameters.
session
*Session
required
Session object to create
error
error
Error if creation fails
session/service.go:21

Repository

session.Repository

Database operations for session persistence.
type Repository struct {
    db db
}

Methods

func (r *Repository) Get(ctx context.Context, id string) (*Session, error)
func (r *Repository) GetByUserId(ctx context.Context, userID string) (*Session, error)
func (r *Repository) Create(ctx context.Context, session *Session) error
func (r *Repository) Delete(ctx context.Context, id string) error
func (r *Repository) DeleteByUserId(ctx context.Context, userId string) error
func (r *Repository) Migrations() fs.FS

Get

Retrieves a session from the sessions table by session ID. Query: SELECT * FROM sessions WHERE id = $1 session/repository.go:36

GetByUserId

Retrieves a session from the sessions table by user ID. Query: SELECT * FROM sessions WHERE "user" = $1 session/repository.go:45

Create

Inserts a new session into the sessions table. Query:
INSERT INTO sessions (id, "user", created, expires)
VALUES (:id, :user, :created, :expires)
session/repository.go:54

Delete

Deletes a session by ID. Query: DELETE FROM sessions WHERE id = $1 session/repository.go:66

DeleteByUserId

Deletes all sessions for a user. Query: DELETE FROM sessions WHERE "user" = $1 session/repository.go:77

Migrations

Returns embedded SQL migrations for the sessions table. session/repository.go:31

Models

Session

type Session struct {
    ID      string    `db:"id"      json:"id"`
    User    string    `db:"user"    json:"user"`
    Created time.Time `db:"created" json:"created"`
    Expires time.Time `db:"expires" json:"expires"`
}
ID
string
UUID primary key for the session
User
string
Foreign key to user ID
Created
time.Time
Timestamp when session was created
Expires
time.Time
Timestamp when session expires (default: 100 days from creation)
session/model.go:5

IsExpired

func (s *Session) IsExpired() bool
Checks if the session has expired by comparing the expiration time with the current time.
expired
bool
true if session is expired, false otherwise
session/model.go:12

Session Storage

Sessions are stored in a PostgreSQL sessions table with the following schema:
CREATE TABLE sessions (
    id      TEXT PRIMARY KEY,
    "user"  TEXT NOT NULL,
    created TIMESTAMP NOT NULL,
    expires TIMESTAMP NOT NULL
);
Storage characteristics:
  • Session IDs are UUIDs generated with uuid.NewString()
  • Sessions expire after 100 days by default
  • Sessions are deleted on user logout or account deletion
  • Multiple sessions per user are supported

Usage Example

package main

import (
    "context"
    "fmt"
    "time"

    "github.com/platforma-dev/platforma/database"
    "github.com/platforma-dev/platforma/session"
)

func main() {
    // Setup database
    dbDomain := database.New(database.Config{
        Host:     "localhost",
        Port:     5432,
        Database: "myapp",
        User:     "postgres",
        Password: "password",
    })

    // Initialize session domain
    sessionDomain := session.New(dbDomain.Service)

    ctx := context.Background()

    // Create a session for a user
    userId := "user-123"
    sessionId, err := sessionDomain.Service.CreateSessionForUser(ctx, userId)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Created session: %s\n", sessionId)

    // Retrieve user ID from session
    retrievedUserId, err := sessionDomain.Service.GetUserIdFromSessionId(ctx, sessionId)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Session belongs to user: %s\n", retrievedUserId)

    // Get full session details
    sessionObj, err := sessionDomain.Service.Get(ctx, sessionId)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Session created: %v\n", sessionObj.Created)
    fmt.Printf("Session expires: %v\n", sessionObj.Expires)
    fmt.Printf("Is expired: %v\n", sessionObj.IsExpired())

    // Delete the session (logout)
    err = sessionDomain.Service.DeleteSession(ctx, sessionId)
    if err != nil {
        panic(err)
    }
    fmt.Println("Session deleted")
}

Integration with Auth

The session package is designed to work seamlessly with the auth package:
import (
    "github.com/platforma-dev/platforma/auth"
    "github.com/platforma-dev/platforma/session"
)

// Session service implements the authStorage interface
type authStorage interface {
    GetUserIdFromSessionId(context.Context, string) (string, error)
    CreateSessionForUser(context.Context, string) (string, error)
    DeleteSession(ctx context.Context, sessionId string) error
    DeleteSessionsByUserId(ctx context.Context, userId string) error
}

// Initialize both domains
sessionDomain := session.New(db)
authDomain := auth.New(
    db,
    sessionDomain.Service,  // Pass session service as authStorage
    "session_id",
    nil,  // default username validator
    nil,  // default password validator
    nil,  // no cleanup enqueuer
)

Session Lifecycle

  1. Creation: When user logs in, CreateSessionForUser generates a UUID and stores it with 100-day expiration
  2. Validation: On each protected request, middleware calls GetUserIdFromSessionId to validate session and retrieve user
  3. Expiration: Sessions automatically expire after 100 days (can be checked with IsExpired())
  4. Deletion: Sessions are deleted on logout or account deletion via DeleteSession or DeleteSessionsByUserId

Database Interface

The repository requires a database interface with these methods:
type db interface {
    NamedExecContext(ctx context.Context, query string, arg any) (sql.Result, error)
    GetContext(ctx context.Context, dest any, query string, args ...any) error
    SelectContext(ctx context.Context, dest any, query string, args ...any) error
    ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}
This interface is compatible with sqlx.DB from the github.com/jmoiron/sqlx package.

Build docs developers (and LLMs) love