### Install Limen dependencies Source: https://github.com/thecodearcher/limen/blob/master/README.md Use go get to install the core library and required adapters or plugins. ```bash go get github.com/thecodearcher/limen ``` ```bash go get github.com/thecodearcher/limen/adapters/gorm go get github.com/thecodearcher/limen/plugins/credential-password ``` -------------------------------- ### Run Basic Limen Example Source: https://github.com/thecodearcher/limen/blob/master/examples/README.md Execute the basic Limen example using the database/sql adapter. Ensure the DATABASE_URL environment variable is set. ```bash DATABASE_URL="postgres://..." go run ./examples/basic ``` -------------------------------- ### Run Limen GORM Adapter Example Source: https://github.com/thecodearcher/limen/blob/master/examples/README.md Execute the Limen example specifically showcasing the GORM adapter with password credentials. The DATABASE_URL environment variable is required. ```bash DATABASE_URL="postgres://..." go run ./examples/adapters/gorm ``` -------------------------------- ### Run Limen Database/SQL Adapter Example Source: https://github.com/thecodearcher/limen/blob/master/examples/README.md Execute the Limen example demonstrating the standard database/sql adapter with password credentials. Ensure the DATABASE_URL environment variable is set. ```bash DATABASE_URL="postgres://..." go run ./examples/adapters/sql ``` -------------------------------- ### Run Limen OAuth Google Example Source: https://github.com/thecodearcher/limen/blob/master/examples/README.md Execute the Limen example demonstrating OAuth authentication with Google. Requires DATABASE_URL, GOOGLE_CLIENT_ID, and GOOGLE_CLIENT_SECRET environment variables. ```bash DATABASE_URL="postgres://..." GOOGLE_CLIENT_ID=... GOOGLE_CLIENT_SECRET=... go run ./examples/oauth-google ``` -------------------------------- ### Run Limen Gin Example Source: https://github.com/thecodearcher/limen/blob/master/examples/README.md Execute the Limen example integrated with the Gin framework, using the GORM adapter. The DATABASE_URL environment variable must be set. ```bash DATABASE_URL="postgres://..." go run ./examples/gin ``` -------------------------------- ### Initiate 2FA Setup via API Source: https://context7.com/thecodearcher/limen/llms.txt Initiates the two-factor authentication setup process. Requires an active session token. ```bash # Step 1: Initiate 2FA setup (requires authentication) curl -X POST "http://localhost:8080/api/auth/two-factor/initiate-setup" \ -H "Content-Type: application/json" \ -H "Cookie: limen_session=session-token" ``` -------------------------------- ### Build and Install Limen CLI Source: https://github.com/thecodearcher/limen/blob/master/cmd/limen/README.md Commands to compile the CLI from source or install the latest version globally via Go. ```bash cd cmd/limen go build -o limen ``` ```bash go install github.com/thecodearcher/limen/cmd/limen@latest ``` -------------------------------- ### Gin Integration Example Source: https://context7.com/thecodearcher/limen/llms.txt Integrate Limen with the Gin web framework. This example sets up GORM, Limen authentication, a protected route, and mounts the Limen handler. ```go import ( "github.com/gin-gonic/gin" "github.com/thecodearcher/limen" gormadapter "github.com/thecodearcher/limen/adapters/gorm" credentialpassword "github.com/thecodearcher/limen/plugins/credential-password" ) func main() { db, _ := gorm.Open(postgres.Open(os.Getenv("DATABASE_URL")), &gorm.Config{}) auth, _ := limen.New(&limen.Config{ BaseURL: "http://localhost:8080", Database: gormadapter.New(db), Secret: []byte("your-32-byte-secret-key-here!!!!"), Plugins: []limen.Plugin{credentialpassword.New()}, }) r := gin.Default() // Protected route using Limen's session validation r.GET("/api/profile", func(c *gin.Context) { session, err := auth.GetSession(c.Request) if err != nil { c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"}) return } c.JSON(http.StatusOK, gin.H{ "user": session.User, "session": session.Session, }) }) // Mount Limen auth handler r.Any("/api/auth/*path", func(c *gin.Context) { auth.Handler().ServeHTTP(c.Writer, c.Request) }) r.Run(":8080") } ``` -------------------------------- ### Run Limen Two-Factor Example Source: https://github.com/thecodearcher/limen/blob/master/examples/README.md Execute the Limen example that includes two-factor authentication alongside password credentials. Ensure the DATABASE_URL environment variable is set. ```bash DATABASE_URL="postgres://..." go run ./examples/two-factor ``` -------------------------------- ### POST /api/auth/two-factor/initiate-setup Source: https://context7.com/thecodearcher/limen/llms.txt Initiates the 2FA setup process for an authenticated user. ```APIDOC ## POST /api/auth/two-factor/initiate-setup ### Description Initiates the 2FA setup process. Requires an active session. ### Method POST ### Endpoint /api/auth/two-factor/initiate-setup ### Response #### Success Response (200) - **secret** (string) - The TOTP secret key. - **uri** (string) - The otpauth URI for QR code generation. - **backup_codes** (array) - List of initial backup codes. #### Response Example { "secret": "JBSWY3DPEHPK3PXP", "uri": "otpauth://totp/MyApp:user@example.com?secret=JBSWY3DPEHPK3PXP&issuer=MyApp", "backup_codes": ["ABC123XYZ9", "DEF456UVW8"] } ``` -------------------------------- ### SQL Adapter Initialization Source: https://context7.com/thecodearcher/limen/llms.txt Initialize the SQL adapter for Limen using Go's standard database/sql package. This example shows PostgreSQL; MySQL is also supported. ```go import ( "database/sql" _ "github.com/lib/pq" sqladapter "github.com/thecodearcher/limen/adapters/sql" ) db, _ := sql.Open("postgres", "postgres://user:pass@localhost/myapp?sslmode=disable") // PostgreSQL adapter adapter := sqladapter.NewPostgreSQL(db) // MySQL adapter // adapter := sqladapter.NewMySQL(db) auth, _ := limen.New(&limen.Config{ Database: adapter, // ... }) ``` -------------------------------- ### Finalize 2FA Setup via API Source: https://context7.com/thecodearcher/limen/llms.txt Completes the two-factor authentication setup by providing the TOTP code. Requires an active session token. ```bash # Step 2: Finalize 2FA setup with TOTP code curl -X POST "http://localhost:8080/api/auth/two-factor/finalize-setup" \ -H "Content-Type: application/json" \ -H "Cookie: limen_session=session-token" \ -d '{"code": "123456"}' ``` -------------------------------- ### Configure Basic 2FA Setup Source: https://context7.com/thecodearcher/limen/llms.txt Set up two-factor authentication with TOTP, OTP, and backup codes. Ensure the secret key is 32 bytes long. ```go import ( "github.com/thecodearcher/limen" credentialpassword "github.com/thecodearcher/limen/plugins/credential-password" twofactor "github.com/thecodearcher/limen/plugins/two-factor" ) auth, err := limen.New(&limen.Config{ BaseURL: "http://localhost:8080", Database: gormadapter.New(db), Secret: []byte("your-32-byte-secret-key-here!!!!"), Plugins: []limen.Plugin{ credentialpassword.New(), twofactor.New( twofactor.WithTOTP( twofactor.WithTOTPIssuer("MyApp"), twofactor.WithTOTPDigits(twofactor.TOTPDigitsSix), twofactor.WithTOTPAlgorithm(twofactor.TOTPAlgorithmSHA1), ), twofactor.WithOTP( twofactor.WithOTPEnabled(true), twofactor.WithOTPCodeExpiration(10*time.Minute), twofactor.WithOTPSendCode(func(ctx context.Context, user *twofactor.UserWithTwoFactor, code string) { // Send OTP code via SMS or email fmt.Printf("OTP for %s: %s\n", user.Email, code) }), ), twofactor.WithBackupCodes( twofactor.WithBackupCodesCount(10), twofactor.WithBackupCodesLength(10), ), ), }, }) ``` -------------------------------- ### Generated Go Model Example Source: https://github.com/thecodearcher/limen/blob/master/cmd/limen/README.md Sample output of a generated Go struct file. ```go package models import ( "time" ) // User represents the users table type User struct { ID string `json:"id"` // primary key Email string `json:"email"` CreatedAt time.Time `json:"created_at"` UpdatedAt *time.Time `json:"updated_at"` } ``` -------------------------------- ### Migration File Structure Source: https://github.com/thecodearcher/limen/blob/master/cmd/limen/README.md Example directory structure for generated migration files. ```text migrations/ ├── 20240101120000_users.up.sql ├── 20240101120000_users.down.sql ├── 20240101120001_sessions.up.sql └── 20240101120001_sessions.down.sql ``` -------------------------------- ### Gin Integration Source: https://context7.com/thecodearcher/limen/llms.txt Example of integrating Limen with the Gin web framework. ```APIDOC ## Gin Integration ### Description Limen integrates seamlessly with the Gin web framework, providing middleware for session validation and a handler for authentication routes. ### Example Usage ```go import ( "net/http" "github.com/gin-gonic/gin" "github.com/thecodearcher/limen" gormadapter "github.com/thecodearcher/limen/adapters/gorm" credentialpassword "github.com/thecodearcher/limen/plugins/credential-password" "gorm.io/driver/postgres" "gorm.io/gorm" "os" ) func main() { // Initialize GORM and Limen db, _ := gorm.Open(postgres.Open(os.Getenv("DATABASE_URL")), &gorm.Config{}) auth, _ := limen.New(&limen.Config{ BaseURL: "http://localhost:8080", Database: gormadapter.New(db), Secret: []byte("your-32-byte-secret-key-here!!!!"), Plugins: []limen.Plugin{credentialpassword.New()}, }) r := gin.Default() // Protected route using Limen's session validation r.GET("/api/profile", func(c *gin.Context) { session, err := auth.GetSession(c.Request) if err != nil { c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"}) return } c.JSON(http.StatusOK, gin.H{ "user": session.User, "session": session.Session, }) }) // Mount Limen auth handler for authentication routes r.Any("/api/auth/*path", func(c *gin.Context) { auth.Handler().ServeHTTP(c.Writer, c.Request) }) r.Run(":8080") } ``` ``` -------------------------------- ### Basic OAuth Plugin Setup Source: https://context7.com/thecodearcher/limen/llms.txt Initialize the Limen authentication with the OAuth plugin, configuring multiple providers like Google and GitHub. Ensure to set client IDs, secrets, and redirect URLs for each provider. Environment variables can be used for sensitive credentials. ```go import ( "github.com/thecodearcher/limen" "github.com/thecodearcher/limen/plugins/oauth" oauthgoogle "github.com/thecodearcher/limen/plugins/oauth-google" oauthgithub "github.com/thecodearcher/limen/plugins/oauth-github" ) auth, err := limen.New(&limen.Config{ BaseURL: "http://localhost:8080", Database: gormadapter.New(db), Secret: []byte("your-32-byte-secret-key-here!!!!"), Plugins: []limen.Plugin{ oauth.New( oauth.WithProviders( oauthgoogle.New( oauthgoogle.WithClientID("google-client-id"), oauthgoogle.WithClientSecret("google-client-secret"), oauthgoogle.WithRedirectURL("http://localhost:8080/api/auth/oauth/google/callback"), oauthgoogle.WithScopes("openid", "email", "profile"), ), oauthgithub.New( oauthgithub.WithClientID(os.Getenv("GITHUB_CLIENT_ID")), oauthgithub.WithClientSecret(os.Getenv("GITHUB_CLIENT_SECRET")), ), ), ), }, }) ``` -------------------------------- ### POST /api/auth/two-factor/finalize-setup Source: https://context7.com/thecodearcher/limen/llms.txt Finalizes the 2FA setup by verifying the provided TOTP code. ```APIDOC ## POST /api/auth/two-factor/finalize-setup ### Description Finalizes the 2FA setup using a TOTP code. ### Method POST ### Endpoint /api/auth/two-factor/finalize-setup ### Request Body - **code** (string) - Required - The TOTP code to verify. ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example { "message": "Two-factor authentication enabled" } ``` -------------------------------- ### OAuth Plugin Configuration Source: https://context7.com/thecodearcher/limen/llms.txt Basic setup for the OAuth plugin, including configuration for multiple providers. ```APIDOC ## OAuth Plugin Basic Setup This section outlines the basic configuration for the OAuth plugin, allowing integration with various OAuth 2.0 providers. ### Method Not applicable (configuration code) ### Endpoint Not applicable (configuration code) ### Parameters #### Request Body - **oauth.WithProviders** ([]oauth.Provider) - Required - A list of configured OAuth providers. - **oauthgoogle.New** - Configuration for Google OAuth. - **oauthgoogle.WithClientID** (string) - Required - Google Client ID. - **oauthgoogle.WithClientSecret** (string) - Required - Google Client Secret. - **oauthgoogle.WithRedirectURL** (string) - Required - The redirect URI registered with Google. - **oauthgoogle.WithScopes** ([]string) - Optional - Scopes to request from Google. - **oauthgithub.New** - Configuration for GitHub OAuth. - **oauthgithub.WithClientID** (string) - Required - GitHub Client ID. - **oauthgithub.WithClientSecret** (string) - Required - GitHub Client Secret. ### Request Example ```go import ( "github.com/thecodearcher/limen" "github.com/thecodearcher/limen/plugins/oauth" oauthgoogle "github.com/thecodearcher/limen/plugins/oauth-google" oauthgithub "github.com/thecodearcher/limen/plugins/oauth-github" ) auth, err := limen.New(&limen.Config{ BaseURL: "http://localhost:8080", Database: gormadapter.New(db), Secret: []byte("your-32-byte-secret-key-here!!!!"), Plugins: []limen.Plugin{ oauth.New( oauth.WithProviders( oauthgoogle.New( oauthgoogle.WithClientID("google-client-id"), oauthgoogle.WithClientSecret("google-client-secret"), oauthgoogle.WithRedirectURL("http://localhost:8080/api/auth/oauth/google/callback"), oauthgoogle.WithScopes("openid", "email", "profile"), ), oauthgithub.New( oauthgithub.WithClientID(os.Getenv("GITHUB_CLIENT_ID")), oauthgithub.WithClientSecret(os.Getenv("GITHUB_CLIENT_SECRET")), ), ), ), }, }) ``` ### Response Not applicable (configuration code) ``` -------------------------------- ### Global Flag Usage Source: https://github.com/thecodearcher/limen/blob/master/cmd/limen/README.md Example of using the global schema flag to specify a custom path. ```bash limen -s /path/to/schemas.json generate models ``` -------------------------------- ### GET /api/auth/oauth/google/callback Source: https://context7.com/thecodearcher/limen/llms.txt Handles the callback from Google after user authorization. ```APIDOC ## GET /api/auth/oauth/google/callback ### Description This endpoint is called by Google after the user has authorized the application. It exchanges the authorization code for tokens, creates a session, and redirects the user to the specified `redirect_uri`. ### Method GET ### Endpoint /api/auth/oauth/google/callback ### Parameters #### Query Parameters - **code** (string) - Required - The authorization code received from Google. - **state** (string) - Required - The state parameter used to maintain state between the request and callback. ### Request Example (This endpoint is called by the OAuth provider, not directly by the user) `GET /api/auth/oauth/google/callback?code=AUTHORIZATION_CODE&state=STATE_VALUE` ### Response #### Success Response (302 Found) Redirects to the user's `redirect_uri`. #### Response Example (Redirect to user-defined `redirect_uri`) ``` -------------------------------- ### GET /api/auth/oauth/google/authorize Source: https://context7.com/thecodearcher/limen/llms.txt Initiates the OAuth 2.0 authorization flow for Google. ```APIDOC ## GET /api/auth/oauth/google/authorize ### Description Redirects the user to Google's authorization server to grant access to their Google account. ### Method GET ### Endpoint /api/auth/oauth/google/authorize ### Parameters #### Query Parameters - **redirect_uri** (string) - Required - The URI to redirect to after authorization. Must be pre-registered. ### Request Example ```bash curl "http://localhost:8080/api/auth/oauth/google/authorize?redirect_uri=http://localhost:3000/callback" ``` ### Response #### Success Response (200) - **url** (string) - The URL to redirect the user to for Google authorization. #### Response Example ```json { "url": "https://accounts.google.com/o/oauth2/v2/auth?client_id=...&redirect_uri=...&state=..." } ``` ``` -------------------------------- ### Get Current Session Info Source: https://context7.com/thecodearcher/limen/llms.txt Retrieve information about the current user's session by making a GET request to the /api/auth/me endpoint. Authentication is required via a 'limen_session' cookie. ```bash # Get current session/user info (requires authentication) curl "http://localhost:8080/api/auth/me" \ -H "Cookie: limen_session=session-token" ``` ```json # Response (200 OK): { "user": { "id": "uuid", "email": "user@example.com", "email_verified_at": "2024-01-15T10:30:00Z" } } ``` -------------------------------- ### GitHub Actions: Apply Migrations Source: https://github.com/thecodearcher/limen/blob/master/cmd/limen/README.md Example of applying database migrations within a GitHub Actions workflow. Ensures database changes are applied automatically on deployment. ```yaml - name: Apply migrations run: | migrate -path ./migrations \ -database "${{ secrets.DATABASE_URL }}" \ up ``` -------------------------------- ### GitHub Actions: Generate Migrations Source: https://github.com/thecodearcher/limen/blob/master/cmd/limen/README.md Example of generating database migrations within a GitHub Actions workflow. Uses secrets for sensitive information like the database URL. ```yaml # Example GitHub Actions workflow - name: Generate migrations run: | limen generate migrations \ -d postgres \ -c "${{ secrets.DATABASE_URL }}" \ -o ./migrations ``` -------------------------------- ### GET /api/auth/oauth/accounts Source: https://context7.com/thecodearcher/limen/llms.txt Lists all OAuth accounts linked to the currently authenticated user. ```APIDOC ## GET /api/auth/oauth/accounts ### Description Retrieves a list of all OAuth accounts that have been linked to the current user's session. ### Method GET ### Endpoint /api/auth/oauth/accounts ### Parameters #### Headers - **Cookie**: `limen_session=session-token` - Required - Authentication token for the user. ### Request Example ```bash curl "http://localhost:8080/api/auth/oauth/accounts" \ -H "Cookie: limen_session=session-token" ``` ### Response #### Success Response (200) - **provider** (string) - The OAuth provider (e.g., "google"). - **provider_account_id** (string) - The unique identifier for the account on the provider's platform. - **created_at** (string) - The timestamp when the account was linked. #### Response Example ```json [ { "provider": "google", "provider_account_id": "123456789", "created_at": "2024-01-15T10:30:00Z" } ] ``` ``` -------------------------------- ### List All Active Sessions Source: https://context7.com/thecodearcher/limen/llms.txt View all active sessions for the authenticated user by sending a GET request to the /api/auth/sessions endpoint. Requires authentication with a 'limen_session' cookie. ```bash # List all active sessions (requires authentication) curl "http://localhost:8080/api/auth/sessions" \ -H "Cookie: limen_session=session-token" ``` ```json # Response (200 OK): [ { "id": "session-id-1", "token": "token-hash", "created_at": "2024-01-15T10:30:00Z", "expires_at": "2024-01-22T10:30:00Z", "last_access": "2024-01-16T08:00:00Z" } ] ``` -------------------------------- ### Creating a Limen Instance Source: https://context7.com/thecodearcher/limen/llms.txt Demonstrates how to initialize a new Limen authentication instance with configuration, database adapter, and plugins. ```APIDOC ## Creating a Limen Instance ### Description The `limen.New()` function creates a new authentication instance with the provided configuration. It validates the config, initializes plugins, sets up session management, and prepares database schemas. ### Method `limen.New(config *limen.Config) (*Limen, error)` ### Parameters #### Request Body - **config** (*limen.Config) - Required - Configuration for the Limen instance. - **BaseURL** (string) - Required - The base URL of the application. - **Database** (limen.DatabaseAdapter) - Required - The database adapter to use. - **Secret** ([]byte) - Required - A secret key for signing tokens (must be 32 bytes). - **Plugins** ([]limen.Plugin) - Optional - A list of authentication plugins to enable. ### Request Example ```go package main import ( "log" "net/http" "gorm.io/driver/postgres" "gorm.io/gorm" "github.com/thecodearcher/limen" gormadapter "github.com/thecodearcher/limen/adapters/gorm" credentialpassword "github.com/thecodearcher/limen/plugins/credential-password" ) func main() { db, err := gorm.Open(postgres.Open("postgres://user:pass@localhost/myapp"), &gorm.Config{}) if err != nil { log.Fatal(err) } auth, err := limen.New(&limen.Config{ BaseURL: "http://localhost:8080", Database: gormadapter.New(db), Secret: []byte("your-32-byte-secret-key-here!!!!"), // Must be exactly 32 bytes Plugins: []limen.Plugin{ credentialpassword.New(), }, }) if err != nil { log.Fatal(err) } mux := http.NewServeMux() mux.Handle("/api/auth/", auth.Handler()) log.Println("Server listening on :8080") log.Fatal(http.ListenAndServe(":8080", mux)) } ``` ### Response #### Success Response (200) - **Limen** (*limen.Limen) - The initialized Limen authentication instance. #### Error Response (400, 500) - **error** (string) - Description of the error during initialization. ``` -------------------------------- ### Initialize Limen Instance Source: https://context7.com/thecodearcher/limen/llms.txt Creates a new authentication instance with a database adapter and required plugins. The secret key must be exactly 32 bytes. ```go package main import ( "log" "net/http" "gorm.io/driver/postgres" "gorm.io/gorm" "github.com/thecodearcher/limen" gormadapter "github.com/thecodearcher/limen/adapters/gorm" credentialpassword "github.com/thecodearcher/limen/plugins/credential-password" ) func main() { db, err := gorm.Open(postgres.Open("postgres://user:pass@localhost/myapp"), &gorm.Config{}) if err != nil { log.Fatal(err) } auth, err := limen.New(&limen.Config{ BaseURL: "http://localhost:8080", Database: gormadapter.New(db), Secret: []byte("your-32-byte-secret-key-here!!!!"), // Must be exactly 32 bytes Plugins: []limen.Plugin{ credentialpassword.New(), }, }) if err != nil { log.Fatal(err) } mux := http.NewServeMux() mux.Handle("/api/auth/", auth.Handler()) log.Println("Server listening on :8080") log.Fatal(http.ListenAndServe(":8080", mux)) } ``` -------------------------------- ### Initialize Limen with GORM Source: https://github.com/thecodearcher/limen/blob/master/README.md Configure the Limen instance with a database adapter and authentication plugins within a standard Go HTTP server. ```go package main import ( "log" "net/http" "gorm.io/driver/postgres" "gorm.io/gorm" "github.com/thecodearcher/limen" gormadapter "github.com/thecodearcher/limen/adapters/gorm" credentialpassword "github.com/thecodearcher/limen/plugins/credential-password" ) func main() { db, err := gorm.Open(postgres.Open("your-dsn"), &gorm.Config{}) if err != nil { log.Fatal(err) } auth, err := limen.New(&limen.Config{ BaseURL: "http://localhost:8080", Database: gormadapter.New(db), Secret: []byte("your-32-byte-secret-key-here!!!!"), Plugins: []limen.Plugin{ credentialpassword.New(), }, }) if err != nil { log.Fatal(err) } mux := http.NewServeMux() mux.Handle("/api/auth/", auth.Handler()) log.Println("listening on :8080") log.Fatal(http.ListenAndServe(":8080", mux)) } ``` -------------------------------- ### GORM Adapter Initialization Source: https://context7.com/thecodearcher/limen/llms.txt Initialize the GORM adapter for Limen by opening a GORM database connection and then creating a new GORM adapter instance. Supports PostgreSQL, MySQL, and SQLite. ```go import ( "gorm.io/driver/postgres" "gorm.io/driver/mysql" "gorm.io/driver/sqlite" "gorm.io/gorm" gormadapter "github.com/thecodearcher/limen/adapters/gorm" ) // PostgreSQL db, _ := gorm.Open(postgres.Open("host=localhost user=app dbname=myapp"), &gorm.Config{}) adapter := gormadapter.New(db) // MySQL db, _ := gorm.Open(mysql.Open("user:pass@tcp(localhost:3306)/myapp"), &gorm.Config{}) adapter := gormadapter.New(db) // SQLite db, _ := gorm.Open(sqlite.Open("myapp.db"), &gorm.Config{}) adapter := gormadapter.New(db) auth, _ := limen.New(&limen.Config{ Database: adapter, // ... }) ``` -------------------------------- ### Sign Up via REST API Source: https://context7.com/thecodearcher/limen/llms.txt Creates a new user account using the /signup/credential endpoint. ```bash # Sign up a new user curl -X POST http://localhost:8080/api/auth/signup/credential \ -H "Content-Type: application/json" \ -d '{ "email": "user@example.com", "password": "SecurePass123!" }' ``` -------------------------------- ### GET /api/auth/oauth/google/tokens Source: https://context7.com/thecodearcher/limen/llms.txt Retrieves the OAuth access and refresh tokens for a linked Google account. ```APIDOC ## GET /api/auth/oauth/google/tokens ### Description Fetches the current OAuth access and refresh tokens associated with the user's linked Google account. ### Method GET ### Endpoint /api/auth/oauth/google/tokens ### Parameters #### Headers - **Cookie**: `limen_session=session-token` - Required - Authentication token for the user. ### Request Example ```bash curl "http://localhost:8080/api/auth/oauth/google/tokens" \ -H "Cookie: limen_session=session-token" ``` ### Response #### Success Response (200) - **access_token** (string) - The OAuth access token. - **refresh_token** (string) - The OAuth refresh token. - **expires_in** (integer) - The lifetime in seconds of the access token. #### Response Example (Response body not provided in source) ``` -------------------------------- ### Programmatic API Usage Source: https://context7.com/thecodearcher/limen/llms.txt Demonstrates how to use the plugin API for custom authentication flows, password hashing, and reset operations. ```go import credentialpassword "github.com/thecodearcher/limen/plugins/credential-password" // Get the plugin API cpAPI := credentialpassword.Use(auth) // Programmatic sign in result, err := cpAPI.SignInWithCredentialAndPassword( ctx, "user@example.com", "SecurePass123!", ) if err != nil { // Handle authentication error log.Printf("Sign in failed: %v", err) return } // result.User contains the authenticated user // Programmatic sign up with additional fields result, err = cpAPI.SignUpWithCredentialAndPassword( ctx, &limen.User{ Email: "newuser@example.com", Password: stringPtr("SecurePass123!"), }, map[string]any{ "first_name": "John", "last_name": "Doe", }, ) // Hash and compare passwords hash, err := cpAPI.HashPassword("MyPassword123!") match, err := cpAPI.ComparePassword("MyPassword123!", &hash) // Request password reset programmatically verification, err := cpAPI.RequestPasswordReset(ctx, "user@example.com") // verification.Token contains the reset token // Reset password with token err = cpAPI.ResetPassword(ctx, token, "NewPassword456!") ``` -------------------------------- ### Configure Limen with Credential-Password Plugin Source: https://context7.com/thecodearcher/limen/llms.txt Initializes the Limen authentication instance with the credential-password plugin and custom password requirements. ```go import ( "github.com/thecodearcher/limen" credentialpassword "github.com/thecodearcher/limen/plugins/credential-password" ) auth, err := limen.New(&limen.Config{ BaseURL: "http://localhost:8080", Database: gormadapter.New(db), Secret: []byte("your-32-byte-secret-key-here!!!!"), Plugins: []limen.Plugin{ credentialpassword.New( credentialpassword.WithPasswordMinLength(8), credentialpassword.WithPasswordRequireUppercase(true), credentialpassword.WithPasswordRequireNumbers(true), credentialpassword.WithPasswordRequireSymbols(false), credentialpassword.WithAutoSignInOnSignUp(true), credentialpassword.WithResetTokenExpiration(30*time.Minute), credentialpassword.WithSendPasswordResetEmail(func(email, token string) { // Send password reset email fmt.Printf("Reset token for %s: %s\n", email, token) }), ), }, }) ``` -------------------------------- ### SQL Adapter Source: https://context7.com/thecodearcher/limen/llms.txt Configuration and usage of the standard SQL database adapter for Limen. ```APIDOC ## SQL Adapter ### Description The SQL adapter works with Go's standard `database/sql` package for direct database access. ### Usage #### PostgreSQL ```go import ( "database/sql" _ "github.com/lib/pq" sqladapter "github.com/thecodearcher/limen/adapters/sql" ) db, _ := sql.Open("postgres", "postgres://user:pass@localhost/myapp?sslmode=disable") adapter := sqladapter.NewPostgreSQL(db) // Initialize Limen with the SQL adapter // auth, _ := limen.New(&limen.Config{ Database: adapter }) ``` #### MySQL (Example - uncomment to use) ```go // import ( // "database/sql" // _ "github.com/go-sql-driver/mysql" // sqladapter "github.com/thecodearcher/limen/adapters/sql" // ) // // db, _ := sql.Open("mysql", "user:pass@tcp(127.0.0.1:3306)/myapp") // adapter := sqladapter.NewMySQL(db) // // // Initialize Limen with the SQL adapter // // auth, _ := limen.New(&limen.Config{ Database: adapter }) ``` ``` -------------------------------- ### Initialize Limen Application Source: https://github.com/thecodearcher/limen/blob/master/cmd/limen/README.md Initialize Limen in your application to generate the necessary schemas file. This is a prerequisite for other Limen operations. ```go // Your application code that initializes Limen // This creates .limen/schemas.json ``` -------------------------------- ### Apply Database Migrations Source: https://github.com/thecodearcher/limen/blob/master/cmd/limen/README.md Apply generated database migrations using the migrate tool. Provide the path to the migrations directory and the database connection string. ```bash migrate -path ./migrations \ -database "postgres://user:pass@localhost/mydb?sslmode=disable" \ up ``` -------------------------------- ### POST /api/auth/signup/credential Source: https://context7.com/thecodearcher/limen/llms.txt Creates a new user account using an email and password. ```APIDOC ## POST /api/auth/signup/credential ### Description Creates a new user account with email and password. ### Method POST ### Endpoint /api/auth/signup/credential ### Request Body - **email** (string) - Required - User email address - **password** (string) - Required - User password ### Request Example { "email": "user@example.com", "password": "SecurePass123!" } ### Response #### Success Response (201) - **user** (object) - Created user details - **session** (object) - Session token and expiration #### Response Example { "user": { "id": "uuid-here", "email": "user@example.com", "email_verified_at": null, "created_at": "2024-01-15T10:30:00Z" }, "session": { "token": "opaque-session-token", "expires_at": "2024-01-22T10:30:00Z" } } ``` -------------------------------- ### Generate Database Migrations Source: https://github.com/thecodearcher/limen/blob/master/cmd/limen/README.md Generate database migration files using the Limen CLI. Specify the database driver, connection string, and output directory for the migrations. ```bash limen generate migrations \ -d postgres \ -c "postgres://user:pass@localhost/mydb?sslmode=disable" \ -o ./migrations ``` -------------------------------- ### Generate Migrations Commands Source: https://github.com/thecodearcher/limen/blob/master/cmd/limen/README.md Commands to generate SQL migrations for different database drivers and configurations. ```bash limen generate migrations \ -d postgres \ -c "postgres://user:password@localhost:5432/mydb?sslmode=disable" ``` ```bash limen generate migrations \ -d mysql \ -c "user:password@tcp(localhost:3306)/mydb" ``` ```bash limen generate migrations \ -d postgres \ -c "postgres://user:pass@localhost/db" \ -o ./db/migrations ``` ```bash limen -s ./custom/schemas.json generate migrations \ -d postgres \ -c "postgres://user:pass@localhost/db" ``` -------------------------------- ### Apply Migrations with External Tools Source: https://github.com/thecodearcher/limen/blob/master/cmd/limen/README.md Commands to apply generated migration files using common migration tools. ```bash migrate -path ./migrations \ -database "postgres://user:pass@localhost/db?sslmode=disable" \ up ``` ```bash goose -dir ./migrations postgres "postgres://user:pass@localhost/db?sslmode=disable" up ``` -------------------------------- ### GORM Adapter Source: https://context7.com/thecodearcher/limen/llms.txt Configuration and usage of the GORM database adapter for Limen. ```APIDOC ## GORM Adapter ### Description The GORM adapter provides full support for GORM-based database operations including transactions. ### Usage #### PostgreSQL ```go import ( "gorm.io/driver/postgres" "gorm.io/gorm" gormadapter "github.com/thecodearcher/limen/adapters/gorm" ) db, _ := gorm.Open(postgres.Open("host=localhost user=app dbname=myapp"), &gorm.Config{}) adapter := gormadapter.New(db) // Initialize Limen with the GORM adapter // auth, _ := limen.New(&limen.Config{ Database: adapter }) ``` #### MySQL ```go import ( "gorm.io/driver/mysql" "gorm.io/gorm" gormadapter "github.com/thecodearcher/limen/adapters/gorm" ) db, _ := gorm.Open(mysql.Open("user:pass@tcp(localhost:3306)/myapp"), &gorm.Config{}) adapter := gormadapter.New(db) // Initialize Limen with the GORM adapter // auth, _ := limen.New(&limen.Config{ Database: adapter }) ``` #### SQLite ```go import ( "gorm.io/driver/sqlite" "gorm.io/gorm" gormadapter "github.com/thecodearcher/limen/adapters/gorm" ) db, _ := gorm.Open(sqlite.Open("myapp.db"), &gorm.Config{}) adapter := gormadapter.New(db) // Initialize Limen with the GORM adapter // auth, _ := limen.New(&limen.Config{ Database: adapter }) ``` ``` -------------------------------- ### Sign in with 2FA Enabled Source: https://context7.com/thecodearcher/limen/llms.txt Attempts to sign in with credentials. If 2FA is enabled, the response will indicate that a two-factor challenge is required. ```bash # Sign in with 2FA enabled returns a challenge curl -X POST "http://localhost:8080/api/auth/signin/credential" \ -H "Content-Type: application/json" \ -d '{"credential": "user@example.com", "password": "SecurePass123!"}' ``` -------------------------------- ### Limen CLI Command Structure Source: https://github.com/thecodearcher/limen/blob/master/cmd/limen/README.md The standard syntax for executing Limen CLI commands. ```bash limen [global-flags] generate [flags] ``` -------------------------------- ### Verify 2FA with Backup Code Source: https://context7.com/thecodearcher/limen/llms.txt Verifies the user's identity using a backup code. Requires a 2FA challenge token. ```bash # Verify with backup code instead curl -X POST "http://localhost:8080/api/auth/two-factor/verify" \ -H "Content-Type: application/json" \ -H "Cookie: limen_2fa_challenge=challenge-token" \ -d '{"code": "ABC123XYZ9", "type": "backup_code"}' ``` -------------------------------- ### Username Sign Up Source: https://context7.com/thecodearcher/limen/llms.txt API endpoint for signing up a new user with a username and password. ```APIDOC ## POST /api/auth/signup/credential ### Description Allows users to sign up using their email, password, and an optional username. ### Method POST ### Endpoint /api/auth/signup/credential ### Parameters #### Request Body - **email** (string) - Required - The user's email address. - **password** (string) - Required - The user's password. - **username** (string) - Optional - The user's chosen username. ### Request Example ```json { "email": "user@example.com", "password": "Pass123!", "username": "johndoe" } ``` ### Response #### Success Response (200) Details of the created user session or token. #### Response Example (Response body not provided in source) ``` -------------------------------- ### Sign In via REST API Source: https://context7.com/thecodearcher/limen/llms.txt Authenticates a user using the /signin/credential endpoint. ```bash # Sign in with email and password curl -X POST http://localhost:8080/api/auth/signin/credential \ -H "Content-Type: application/json" \ -d '{ "credential": "user@example.com", "password": "SecurePass123!", "remember_me": true }' ``` -------------------------------- ### Enable Username Support in Limen Source: https://context7.com/thecodearcher/limen/llms.txt Configure the credential password plugin to enable username support for sign-in and sign-up. Set minimum and maximum lengths, and optionally enforce username presence during sign-up. A custom regex can be provided for username validation. ```go auth, err := limen.New(&limen.Config{ BaseURL: "http://localhost:8080", Database: gormadapter.New(db), Secret: []byte("your-32-byte-secret-key-here!!!!"), Plugins: []limen.Plugin{ credentialpassword.New( credentialpassword.WithUsernameSupport(true), credentialpassword.WithUsernameMinLength(3), credentialpassword.WithUsernameMaxLength(30), credentialpassword.WithRequireUsernameOnSignUp(false), // Optional username // Custom regex: alphanumeric, underscore, hyphen only credentialpassword.WithUsernameValidationRegex(regexp.MustCompile(`^[a-zA-Z0-9_-]+$`)), ), }, }) ``` ```bash # Sign up with username # curl -X POST http://localhost:8080/api/auth/signup/credential \ # -H "Content-Type: application/json" \ # -d '{"email": "user@example.com", "password": "Pass123!", "username": "johndoe"}' ``` ```bash # Sign in with username # curl -X POST http://localhost:8080/api/auth/signin/credential \ # -H "Content-Type: application/json" \ # -d '{"credential": "johndoe", "password": "Pass123!"}' ``` ```bash # Check username availability # curl -X POST http://localhost:8080/api/auth/usernames/check \ # -H "Content-Type: application/json" \ # -d '{"username": "johndoe"}' # Response: {"available": false} ``` -------------------------------- ### Configure Limen Hooks in Go Source: https://context7.com/thecodearcher/limen/llms.txt Define before and after hooks within the Limen configuration to intercept and process requests or responses. ```go auth, _ := limen.New(&limen.Config{ BaseURL: "http://localhost:8080", Database: gormadapter.New(db), Secret: []byte("your-32-byte-secret-key-here!!!!"), HTTP: limen.NewDefaultHTTPConfig( limen.WithHTTPHooks(&limen.Hooks{ Before: []*limen.Hook{ { PathMatcher: func(ctx *limen.HookContext) bool { return ctx.RouteID() == "signin" // Only run for signin }, Run: func(ctx *limen.HookContext) bool { // Log sign-in attempts body := ctx.GetJSONBodyData() log.Printf("Sign-in attempt for: %v", body["credential"]) // Return true to continue, false to stop return true }, }, }, After: []*limen.Hook{ { Run: func(ctx *limen.HookContext) bool { // Log all responses resp := ctx.GetResponse() if resp != nil { log.Printf("Response: %d", resp.StatusCode) } return true }, }, }, }), ), Plugins: []limen.Plugin{ credentialpassword.New(), }, }) ``` -------------------------------- ### Generate Limen Models Source: https://github.com/thecodearcher/limen/blob/master/cmd/limen/README.md Use the Limen CLI to generate data models based on your schemas. Specify the output directory for the generated model files. ```bash limen generate models -o ./internal/models ``` -------------------------------- ### Generate Models Commands Source: https://github.com/thecodearcher/limen/blob/master/cmd/limen/README.md Various ways to invoke the generate models command with different flags. ```bash limen generate models ``` ```bash limen generate models -o ./internal/models ``` ```bash limen generate models -o ./models -p myapp ``` ```bash limen -s ./custom/schemas.json generate models -o ./models ``` -------------------------------- ### Configure HTTP Settings Source: https://context7.com/thecodearcher/limen/llms.txt Configures HTTP settings for the Limen instance using functional options. This includes setting the base URL, database adapter, secret key, and various HTTP-specific options like base path, trusted origins, CSRF protection, origin checking, custom cookie names, secure and HttpOnly cookies, SameSite mode, and rate limiting. ```go auth, err := limen.New(&limen.Config{ BaseURL: "https://myapp.com", Database: gormadapter.New(db), Secret: []byte("your-32-byte-secret-key-here!!!!"), HTTP: limen.NewDefaultHTTPConfig( limen.WithHTTPBasePath("/api/auth"), // Mount auth routes at /api/auth limen.WithHTTPTrustedOrigins([]string{ // Required for cross-domain cookies "https://myapp.com", "https://*.myapp.com", }), limen.WithHTTPCSRFProtection(true), // Enable CSRF protection (default: true) limen.WithHTTPOriginCheck(true), // Enable origin checking (default: true) limen.WithHTTPSessionCookieName("my_session"), // Custom cookie name limen.WithHTTPCookieSecure(true), // Secure cookies (default: true) limen.WithHTTPCookieHTTPOnly(true), // HttpOnly cookies (default: true) limen.WithHTTPCookieSameSite(http.SameSiteLaxMode), limen.WithHTTPRateLimiter( limen.WithRateLimiterEnabled(true), limen.WithRateLimiterDefaultLimit(100), limen.WithRateLimiterDefaultWindow(time.Minute), ), ), Plugins: []limen.Plugin{ credentialpassword.New(), }, }) ``` -------------------------------- ### Configure JWT Session Management Source: https://context7.com/thecodearcher/limen/llms.txt Configure Limen to use JWTs for sessions, enabling stateless authentication. Adjust token durations and rotation as needed. ```go import ( "github.com/thecodearcher/limen" sessionjwt "github.com/thecodearcher/limen/plugins/session-jwt" ) auth, err := limen.New(&limen.Config{ BaseURL: "http://localhost:8080", Database: gormadapter.New(db), Secret: []byte("your-32-byte-secret-key-here!!!!"), Plugins: []limen.Plugin{ credentialpassword.New(), sessionjwt.New( sessionjwt.WithAccessTokenDuration(15*time.Minute), sessionjwt.WithRefreshTokenDuration(7*24*time.Hour), sessionjwt.WithRefreshTokenRotation(true), // Issue new refresh token on refresh sessionjwt.WithIssuer("https://myapp.com"), sessionjwt.WithAudience("https://myapp.com", "https://api.myapp.com"), sessionjwt.WithBlacklistEnabled(true), // Enable token revocation sessionjwt.WithBlacklistStoreType(limen.StoreTypeCache), // Cache or Database ), }, }) ```