Authentication Introduction
Nimbus ships with a flexible authentication system built around two core interfaces: auth.Guard and auth.User. Guards handle how users are authenticated (sessions, tokens, etc.), while the User interface represents the authenticated identity.
The User interface
Any type that implements GetID() string satisfies the auth.User interface. Your application's user model must implement this:
type AppUser struct {
database.Model
Name string
Email string
Password string
}
func (u *AppUser) GetID() string {
return fmt.Sprintf("%d", u.ID)
}
The Guard interface
A guard provides three methods for managing authentication state:
type Guard interface {
User(ctx context.Context) (User, error)
Login(ctx context.Context, user User) error
Logout(ctx context.Context) error
}
User(ctx)— Resolves the authenticated user from the request context. Returns nil if not authenticated.Login(ctx, user)— Establishes an authenticated session for the given user.Logout(ctx)— Removes the authenticated session.
Built-in guards
Nimbus provides auth.NewSessionGuard() out of the box, which stores sessions in memory keyed by session ID. You can implement additional guards (e.g. token-based) by satisfying the Guard interface.
guard := auth.NewSessionGuard()
Protecting routes with RequireAuth
The auth.RequireAuth(guard, redirectTo) middleware checks authentication on every request. If no user is found and redirectTo is set, it redirects. If redirectTo is empty, it returns a 401 JSON response.
// Redirect unauthenticated users to login page
app.Router.Use(auth.RequireAuth(guard, "/login"))
// Or return 401 JSON for API routes
api := app.Router.Group("/api")
api.Use(auth.RequireAuth(guard, ""))
Getting the authenticated user
After RequireAuth runs, retrieve the user in any handler with auth.UserFromContext:
func Dashboard(c *http.Context) error {
user := auth.UserFromContext(c.Request.Context())
if user == nil {
return c.JSON(401, map[string]string{"error": "not authenticated"})
}
appUser := user.(*AppUser)
return c.JSON(200, map[string]string{"welcome": appUser.Name})
}
Context helpers
Two helper functions manage the user in the request context:
auth.WithUser(ctx, user)— Sets the user on the context. Used internally by guards and middleware.auth.UserFromContext(ctx)— Retrieves the user from context. Returns nil if no user is set.