Session Guard

The SessionGuard is Nimbus's built-in session-based authentication guard. It stores user sessions in memory, mapping session IDs to authenticated users. The session ID is expected to come from a cookie set by your session middleware.

How it works

The SessionGuard maintains a thread-safe in-memory map of session IDs to auth.User values. When a request arrives, it reads the session_id from the request context (set by your cookie/session middleware) and looks up the corresponding user.

  • On Login: stores the user under the current session ID.
  • On User: looks up the user by session ID from context.
  • On Logout: removes the session ID entry from the map.

Setting up the guard

guard := auth.NewSessionGuard()

// Protect routes — redirect to /login if not authenticated
app.Router.Use(auth.RequireAuth(guard, "/login"))

Login flow

In your login handler, validate credentials, then call guard.Login to associate the user with the current session:

func HandleLogin(c *http.Context, guard *auth.SessionGuard) error {
    email := c.FormValue("email")
    password := c.FormValue("password")

    var user AppUser
    if err := db.Where("email = ?", email).First(&user).Error; err != nil {
        return c.JSON(401, map[string]string{"error": "invalid credentials"})
    }

    if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
        return c.JSON(401, map[string]string{"error": "invalid credentials"})
    }

    guard.Login(c.Request.Context(), &user)
    return c.Redirect(302, "/dashboard")
}

Logout flow

Call guard.Logout to remove the session. You should also clear the session cookie on the client:

func HandleLogout(c *http.Context, guard *auth.SessionGuard) error {
    guard.Logout(c.Request.Context())
    http.SetCookie(c.Response, &http.Cookie{
        Name:   "session_id",
        Value:  "",
        MaxAge: -1,
    })
    return c.Redirect(302, "/login")
}

Checking authentication status

Use guard.User(ctx) or auth.UserFromContext(ctx) to check if a user is authenticated:

func ProfileHandler(c *http.Context) error {
    user := auth.UserFromContext(c.Request.Context())
    if user == nil {
        return c.JSON(401, map[string]string{"error": "not authenticated"})
    }
    return c.JSON(200, map[string]string{"id": user.GetID()})
}

Session storage

The built-in SessionGuard stores sessions in memory. This works for single-server deployments but sessions are lost on restart. For production, implement the auth.Guard interface with a persistent store like Redis or a database table.