ARCHIVED — moved to mike/gravity/libs/auth. Shared OIDC authentication library for Gravity platform services.
- Go 100%
Session-based OIDC auth for Gravity services. Provides login/callback/logout handler, route protection middleware, and user extraction from context. Closes OP#831 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> |
||
|---|---|---|
| .gitignore | ||
| auth.go | ||
| go.mod | ||
| go.sum | ||
| LICENSE | ||
| README.md | ||
gravity-auth
Shared OIDC authentication library for Gravity platform services. Wraps the Zitadel Go SDK to provide session-based login, route protection, and user extraction.
Install
go get git.bros.ninja/ai/gravity-auth
Usage
package main
import (
"context"
"log"
"net/http"
gravityauth "git.bros.ninja/ai/gravity-auth"
)
func main() {
ctx := context.Background()
auth, err := gravityauth.New(ctx, gravityauth.Config{
Domain: "auth.example.com",
KeyPath: "path/to/key.json",
ClientID: "your-client-id",
RedirectURI: "http://localhost:8910/auth/callback",
})
if err != nil {
log.Fatal(err)
}
mux := http.NewServeMux()
// Mount login/callback/logout routes
mux.Handle("/auth/", auth.Handler())
// Protected route — redirects to login if not authenticated
mux.Handle("GET /profile", auth.Require(http.HandlerFunc(profileHandler)))
// Optional auth — works with or without login
mux.Handle("GET /", auth.Check(http.HandlerFunc(homeHandler)))
log.Fatal(http.ListenAndServe(":8910", mux))
}
func profileHandler(w http.ResponseWriter, r *http.Request) {
user := gravityauth.UserFromContext(r.Context())
// user.ID, user.Email, user.DisplayName
w.Write([]byte("Hello, " + user.DisplayName))
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
if gravityauth.IsAuthenticated(r.Context()) {
user := gravityauth.UserFromContext(r.Context())
w.Write([]byte("Welcome back, " + user.DisplayName))
return
}
w.Write([]byte("Welcome, guest"))
}
Config
| Field | Required | Description |
|---|---|---|
| Domain | yes | Zitadel instance domain |
| KeyPath | yes | Path to Zitadel application key JSON file |
| ClientID | yes | OIDC client ID |
| RedirectURI | yes | Callback URL registered with Zitadel |
| Port | no | Non-standard Zitadel port (string, e.g. "8080") |
| Insecure | no | Disable TLS (local dev only) |
API
New(ctx, Config)— create an Auth instanceAuth.Handler()— http.Handler for /auth/ routes (login, callback, logout)Auth.Require(next)— middleware that redirects unauthenticated usersAuth.RequireFunc(next)— convenience wrapper for HandlerFuncAuth.Check(next)— middleware that populates context without redirectingUserFromContext(ctx)— extract*Userfrom context (nil if not logged in)IsAuthenticated(ctx)— check if context has a valid sessionUserInfoJSON(ctx)— full OIDC user info as JSON (for debugging)
License
Apache 2.0