# Add Authentication to Your Application

This tutorial shows you how to add authentication to an existing Bangstack application, or customize the authentication system for your needs.

## Table of Contents

1. [Quick Start: Add Auth to Existing App](#quick-start-add-auth-to-existing-app)
2. [Authentication Options](#authentication-options)
   - JWT
   - Session-Based
   - OAuth (Social Login)
   - **Clerk (Managed Service)**
3. [Customize Authentication](#customize-authentication)
4. [Social Authentication (OAuth)](#social-authentication-oauth)
5. [Role-Based Access Control (RBAC)](#role-based-access-control-rbac)
6. [Multi-Factor Authentication (MFA)](#multi-factor-authentication-mfa)
7. [Advanced Patterns](#advanced-patterns)

## Quick Start: Add Auth to Existing App

Let's say you have an existing app without authentication. Here's how to add it in 2 minutes.

### Step 1: Update Your Workflow

Edit your workflow file (e.g., `workflows/my-app.workflow.yaml`):

```yaml
workflow:
  id: my-app
  version: 1.0.0
  name: My Application
  description: My app with authentication

# Add authentication configuration
authentication:
  enabled: true
  provider: jwt
  features:
    - login
    - signup
    - logout
    - refresh-token
    - password-reset
    - email-verification

# Define User model in your models section
models:
  User:
    description: Application user
    fields:
      - name: id
        type: uuid
        required: true
        system_field: true
      - name: email
        type: string
        length: 255
        required: true
        unique: true
        validation:
          format: email
      - name: username
        type: string
        length: 100
        required: true
        unique: true
        validation:
          min_length: 3
          max_length: 100
          pattern: "^[a-zA-Z0-9_]+$"
      - name: password_hash
        type: string
        length: 255
        required: true
      - name: full_name
        type: string
        length: 200
      - name: email_verified
        type: boolean
        default: false
      - name: last_login
        type: timestamp
      - name: created_at
        type: timestamp
        required: true
        system_field: true
      - name: updated_at
        type: timestamp
        required: true
        system_field: true
```

### Step 2: Regenerate Your Code

```bash
bang generate workflows/my-app.workflow.yaml --output ./my-app
```

Bangstack will add:
- Authentication middleware
- Login/signup endpoints
- Password hashing
- JWT token generation
- Frontend auth components
- Protected route handling

### Step 3: Test Authentication

Start your app and test the new auth features:

```bash
cd my-app
docker-compose up
```

Open `http://localhost:3000` and you'll see:
- Sign up form
- Login form
- Protected routes
- User session management

**That's it!** Your app now has complete authentication.

## Authentication Options

Bangstack supports multiple authentication strategies:

### 1. JWT (Recommended)

**Best for**: Most web applications, mobile apps, SPAs

```yaml
authentication:
  enabled: true
  provider: jwt
  jwt:
    secret_env: JWT_SECRET  # Environment variable name
    access_token_expiry: 15m
    refresh_token_expiry: 7d
    algorithm: HS256
  features:
    - login
    - signup
    - logout
    - refresh-token
```

**Generated code includes**:
- Access tokens (short-lived, 15 minutes)
- Refresh tokens (long-lived, 7 days)
- Token rotation on refresh
- Secure httpOnly cookies

### 2. Session-Based

**Best for**: Traditional server-rendered applications

```yaml
authentication:
  enabled: true
  provider: session
  session:
    store: redis  # or 'database' or 'memory'
    secret_env: SESSION_SECRET
    cookie_max_age: 86400000  # 24 hours in milliseconds
    cookie_secure: true  # HTTPS only in production
  features:
    - login
    - signup
    - logout
```

**Generated code includes**:
- Express sessions
- Session store (Redis, DB, or memory)
- Secure session cookies
- CSRF protection

### 3. OAuth (Social Login)

**Best for**: Consumer applications, quick signup flows

```yaml
authentication:
  enabled: true
  provider: oauth
  oauth:
    providers:
      - google
      - github
      - facebook
    callback_url: /auth/callback
    success_redirect: /dashboard
    failure_redirect: /login
  features:
    - social-login
    - account-linking
```

**Generated code includes**:
- OAuth 2.0 flows
- Provider-specific strategies
- Account linking
- Profile data mapping

### 4. Clerk (Managed Authentication Service)

**Best for**: Rapid development, fully managed auth, modern SaaS applications

[Clerk](https://clerk.com) is a complete authentication and user management platform that handles all aspects of auth for you.

```yaml
# Top-level auth configuration (not under technology)
auth:
  enabled: true
  provider: clerk
  strategies:
    - email
    - google
    - github

models:
  User:
    description: Application users
    fields:
      email:
        type: string
        required: true
        unique: true
      name:
        type: string
        required: true
      clerk_id:
        type: string
        required: false
        unique: true
        description: Clerk user ID
    timestamps: true
```

**Generated code includes**:

**Backend** (`@clerk/express` SDK):
- Express middleware with Clerk authentication
- Role-based authorization helpers
- Request auth context (`req.auth.userId`, `req.auth.sessionId`)
- TypeScript types for Express Request

**Frontend** (`@clerk/clerk-react` SDK):
- `<AuthProvider>` wrapper with ClerkProvider
- Pre-built `<Login>` and `<Signup>` pages
- `<ProtectedRoute>` component with role support
- Auth hooks: `useCurrentUser()`, `useAuthFunctions()`, `useHasRole()`

**Environment variables needed** (`.env`):
```bash
# Backend
CLERK_SECRET_KEY=sk_test_...

# Frontend
VITE_CLERK_PUBLISHABLE_KEY=pk_test_...
```

**Get your keys**: Sign up at [clerk.com](https://clerk.com), create an application, and copy your keys from the dashboard.

**Why use Clerk?**
- Zero infrastructure to manage
- Pre-built UI components (optional)
- Built-in support for social providers
- User management dashboard
- Session management
- Organizations and teams support
- Webhooks for user events
- Production-ready security

**Generated file structure**:
```
backend/
├── src/middleware/
│   └── clerk-auth.ts          # Authentication & authorization
└── types/
    └── clerk.d.ts             # TypeScript definitions

frontend/
├── src/
│   ├── components/
│   │   ├── AuthProvider.tsx   # Clerk provider wrapper
│   │   └── ProtectedRoute.tsx # Protected route component
│   ├── pages/
│   │   ├── Login.tsx          # Login page
│   │   └── Signup.tsx         # Signup page
│   └── hooks/
│       └── useAuth.ts         # Auth hooks
```

**Usage example**:

Backend:
```typescript
import { authenticate, authorize } from './middleware/clerk-auth';

// Require authentication
app.get('/api/protected', authenticate, (req, res) => {
  const userId = req.auth.userId;
  res.json({ userId });
});

// Require specific roles
app.delete('/api/admin/users/:id',
  authenticate,
  authorize(['admin']),
  deleteUser
);
```

Frontend:
```tsx
import { AuthProvider } from './components/AuthProvider';
import { ProtectedRoute } from './components/ProtectedRoute';
import { useCurrentUser, useAuthFunctions } from './hooks/useAuth';

// Wrap your app
<AuthProvider>
  <App />
</AuthProvider>

// Protect routes
<ProtectedRoute>
  <Dashboard />
</ProtectedRoute>

// Use auth in components
function ProfileButton() {
  const { user, isSignedIn } = useCurrentUser();
  const { signOut } = useAuthFunctions();

  if (!isSignedIn) return <LoginButton />;

  return (
    <div>
      {user?.fullName}
      <button onClick={() => signOut()}>Sign Out</button>
    </div>
  );
}
```

**Testing with Clerk**:
- Use Clerk's [test mode](https://clerk.com/docs/testing/overview) for development
- No need to mock auth in tests - Clerk provides test users
- Use Clerk's webhooks to sync user data to your database

## Customize Authentication

### Add Custom User Fields

Let's add profile fields to the User model:

```yaml
models:
  User:
    description: User with profile
    fields:
      # ... standard auth fields ...

      # Custom profile fields
      - name: avatar_url
        type: string
        length: 500
      - name: bio
        type: text
      - name: location
        type: string
        length: 100
      - name: website
        type: string
        length: 255
        validation:
          format: url
      - name: twitter_handle
        type: string
        length: 50
      - name: github_username
        type: string
        length: 100
```

Regenerate, and you'll automatically get:
- Profile update endpoints
- Profile display components
- Form validation for all fields

### Add Password Requirements

Configure strong password policies:

```yaml
authentication:
  enabled: true
  provider: jwt
  password_policy:
    min_length: 12
    require_uppercase: true
    require_lowercase: true
    require_numbers: true
    require_special_chars: true
    forbidden_passwords:
      - password123
      - admin123
  features:
    - login
    - signup
    - password-reset
    - password-strength-meter
```

Generated code includes:
- Frontend password strength meter
- Backend validation
- Custom error messages
- Password blacklist checking

### Email Verification Flow

Add email verification to prevent fake accounts:

```yaml
authentication:
  enabled: true
  provider: jwt
  email_verification:
    enabled: true
    token_expiry: 24h
    resend_cooldown: 5m
    email_template: verification
  email_service:
    provider: sendgrid  # or 'ses', 'mailgun', 'smtp'
    from_address: noreply@myapp.com
    from_name: My App
  features:
    - email-verification
    - resend-verification
```

Generated code includes:
- Verification email sending
- Token generation and validation
- Resend verification logic
- Email templates
- Rate limiting on resends

### Password Reset Flow

Add secure password reset:

```yaml
authentication:
  enabled: true
  provider: jwt
  password_reset:
    enabled: true
    token_expiry: 1h
    email_template: password-reset
    max_attempts: 3
    lockout_duration: 15m
  features:
    - password-reset
    - forgot-password
```

Generated code includes:
- Forgot password form
- Reset token generation
- Email with reset link
- New password form
- Token expiration handling

## Social Authentication (OAuth)

### Setup OAuth Providers

#### Google OAuth

```yaml
authentication:
  enabled: true
  provider: oauth
  oauth:
    providers:
      - name: google
        client_id_env: GOOGLE_CLIENT_ID
        client_secret_env: GOOGLE_CLIENT_SECRET
        scopes:
          - profile
          - email
        profile_fields:
          - email
          - name
          - picture
```

**Environment variables needed** (`.env`):
```bash
GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=your-client-secret
```

#### GitHub OAuth

```yaml
authentication:
  enabled: true
  provider: oauth
  oauth:
    providers:
      - name: github
        client_id_env: GITHUB_CLIENT_ID
        client_secret_env: GITHUB_CLIENT_SECRET
        scopes:
          - user:email
        profile_fields:
          - email
          - login
          - avatar_url
```

#### Multiple Providers

Support login with Google, GitHub, and Twitter:

```yaml
authentication:
  enabled: true
  provider: oauth
  oauth:
    providers:
      - google
      - github
      - twitter
    allow_signup: true
    account_linking: true  # Link multiple OAuth accounts to one user
  features:
    - social-login
    - account-linking
    - disconnect-provider
```

Generated frontend includes OAuth buttons:
```tsx
<SocialLoginButtons>
  <GoogleLoginButton />
  <GitHubLoginButton />
  <TwitterLoginButton />
</SocialLoginButtons>
```

## Role-Based Access Control (RBAC)

Add roles and permissions to your application.

### Define Roles

```yaml
authentication:
  enabled: true
  provider: jwt
  authorization:
    type: rbac
    roles:
      - name: admin
        description: Full system access
        permissions:
          - users:*
          - posts:*
          - settings:*
      - name: editor
        description: Content management
        permissions:
          - posts:create
          - posts:update
          - posts:delete
          - posts:publish
      - name: author
        description: Create and edit own posts
        permissions:
          - posts:create
          - posts:update:own
          - posts:delete:own
      - name: user
        description: Basic user
        permissions:
          - posts:read
          - comments:create
```

### Update User Model

Add role field:

```yaml
models:
  User:
    fields:
      # ... other fields ...
      - name: role
        type: enum
        enum_values:
          - admin
          - editor
          - author
          - user
        default: user
        required: true
```

### Generated Code

Bangstack generates:
- Role checking middleware
- Permission validation
- Frontend role-based rendering
- Admin user management UI

**Backend usage**:
```typescript
// Generated middleware
import { requireRole, requirePermission } from './middleware/auth';

router.delete('/posts/:id',
  requirePermission('posts:delete'),
  deletePost
);

router.get('/admin/users',
  requireRole('admin'),
  listUsers
);
```

**Frontend usage**:
```tsx
// Generated components
import { RequireRole, RequirePermission } from './components/auth';

<RequireRole role="admin">
  <AdminPanel />
</RequireRole>

<RequirePermission permission="posts:delete">
  <DeleteButton />
</RequirePermission>
```

## Multi-Factor Authentication (MFA)

Add an extra security layer with 2FA/MFA.

### TOTP (Authenticator App)

```yaml
authentication:
  enabled: true
  provider: jwt
  mfa:
    enabled: true
    methods:
      - totp
    totp:
      issuer: My App
      window: 1  # Allow 1 step before/after
      algorithm: sha256
    enforce_for_roles:
      - admin
  features:
    - mfa-setup
    - mfa-verify
    - backup-codes
```

Generated code includes:
- QR code generation for setup
- TOTP verification
- Backup codes generation
- Recovery flow

### SMS-Based MFA

```yaml
authentication:
  enabled: true
  provider: jwt
  mfa:
    enabled: true
    methods:
      - sms
    sms:
      provider: twilio
      from_number_env: TWILIO_PHONE_NUMBER
      code_length: 6
      code_expiry: 10m
```

### Email-Based MFA

```yaml
authentication:
  enabled: true
  provider: jwt
  mfa:
    enabled: true
    methods:
      - email
    email:
      code_length: 6
      code_expiry: 10m
      template: mfa-code
```

## Advanced Patterns

### Account Lockout Protection

Protect against brute force attacks:

```yaml
authentication:
  enabled: true
  provider: jwt
  security:
    account_lockout:
      enabled: true
      max_attempts: 5
      lockout_duration: 15m
      reset_after_success: true
  features:
    - account-lockout
    - unlock-account
```

### Session Management

Allow users to view and manage their active sessions:

```yaml
authentication:
  enabled: true
  provider: jwt
  session_management:
    enabled: true
    max_concurrent_sessions: 5
    track_device_info: true
    track_location: true
  features:
    - active-sessions
    - revoke-session
    - revoke-all-sessions
```

Generated UI shows:
- List of active sessions
- Device and location info
- Last active timestamp
- Logout buttons

### API Key Authentication

For API access and integrations:

```yaml
authentication:
  enabled: true
  provider: jwt
  api_keys:
    enabled: true
    prefix: sk_  # Stripe-style prefixes
    length: 32
    hashing: sha256
  features:
    - create-api-key
    - list-api-keys
    - revoke-api-key
```

### Audit Logging

Track all authentication events:

```yaml
authentication:
  enabled: true
  provider: jwt
  audit_logging:
    enabled: true
    events:
      - login_success
      - login_failure
      - logout
      - password_reset
      - email_verification
      - role_change
      - mfa_enabled
      - mfa_disabled
    storage: database
    retention_days: 90
```

## Complete Example: Enterprise Auth

Here's a full-featured enterprise authentication setup:

```yaml
workflow:
  id: enterprise-app
  version: 1.0.0
  name: Enterprise Application
  description: App with comprehensive authentication

authentication:
  enabled: true
  provider: jwt

  # JWT configuration
  jwt:
    secret_env: JWT_SECRET
    access_token_expiry: 15m
    refresh_token_expiry: 7d
    algorithm: HS256

  # Password policy
  password_policy:
    min_length: 12
    require_uppercase: true
    require_lowercase: true
    require_numbers: true
    require_special_chars: true

  # Email verification
  email_verification:
    enabled: true
    token_expiry: 24h

  # Password reset
  password_reset:
    enabled: true
    token_expiry: 1h
    max_attempts: 3

  # OAuth providers
  oauth:
    providers:
      - google
      - github
    account_linking: true

  # Role-based access control
  authorization:
    type: rbac
    roles:
      - name: admin
        permissions: ["*"]
      - name: user
        permissions: ["read"]

  # Multi-factor authentication
  mfa:
    enabled: true
    methods:
      - totp
      - sms
    enforce_for_roles:
      - admin

  # Security features
  security:
    account_lockout:
      enabled: true
      max_attempts: 5
      lockout_duration: 15m

  # Session management
  session_management:
    enabled: true
    max_concurrent_sessions: 3
    track_device_info: true

  # Audit logging
  audit_logging:
    enabled: true
    events:
      - login_success
      - login_failure
      - password_reset
      - role_change

  # All features
  features:
    - login
    - signup
    - logout
    - refresh-token
    - password-reset
    - email-verification
    - social-login
    - mfa-setup
    - mfa-verify
    - active-sessions
    - api-keys

models:
  User:
    description: Enterprise user account
    fields:
      - name: id
        type: uuid
        required: true
        system_field: true
      - name: email
        type: string
        length: 255
        required: true
        unique: true
      - name: username
        type: string
        length: 100
        required: true
        unique: true
      - name: password_hash
        type: string
        length: 255
        required: true
      - name: full_name
        type: string
        length: 200
      - name: role
        type: enum
        enum_values: [admin, user]
        default: user
      - name: email_verified
        type: boolean
        default: false
      - name: mfa_enabled
        type: boolean
        default: false
      - name: mfa_secret
        type: string
        length: 32
      - name: last_login
        type: timestamp
      - name: failed_login_attempts
        type: integer
        default: 0
      - name: locked_until
        type: timestamp
      - name: created_at
        type: timestamp
        required: true
        system_field: true
      - name: updated_at
        type: timestamp
        required: true
        system_field: true
```

Generate this with:

```bash
bang generate workflows/enterprise-app.workflow.yaml --output ./enterprise-app
```

You'll get a complete, production-ready authentication system!

## Testing Authentication

Bangstack generates comprehensive tests for authentication:

### Run Auth Tests

```bash
cd backend
npm test -- auth
```

Generated tests cover:
- ✅ User registration
- ✅ Login with valid credentials
- ✅ Login with invalid credentials
- ✅ Password hashing
- ✅ JWT token generation
- ✅ Token refresh
- ✅ Protected endpoints
- ✅ Role-based access
- ✅ Password reset flow
- ✅ Email verification
- ✅ MFA flows

### Test Coverage

```bash
npm run test:coverage
```

Bangstack generates tests with 90%+ coverage for authentication code.

## Deployment Considerations

### Environment Variables

Make sure to set these in production:

```bash
# JWT
JWT_SECRET=your-very-long-random-secret-string-here-at-least-32-chars
JWT_REFRESH_SECRET=another-different-secret-for-refresh-tokens

# Session (if using session-based auth)
SESSION_SECRET=your-session-secret-here

# OAuth (if using)
GOOGLE_CLIENT_ID=...
GOOGLE_CLIENT_SECRET=...
GITHUB_CLIENT_ID=...
GITHUB_CLIENT_SECRET=...

# Email (if using verification/reset)
SENDGRID_API_KEY=...
EMAIL_FROM=noreply@yourdomain.com

# SMS (if using MFA)
TWILIO_ACCOUNT_SID=...
TWILIO_AUTH_TOKEN=...
TWILIO_PHONE_NUMBER=...

# Clerk (if using Clerk provider)
CLERK_SECRET_KEY=sk_live_...
VITE_CLERK_PUBLISHABLE_KEY=pk_live_...
```

### Security Checklist

- ✅ Use HTTPS in production
- ✅ Set secure cookie flags
- ✅ Enable CORS properly
- ✅ Use environment variables for secrets
- ✅ Enable rate limiting
- ✅ Set up monitoring for failed login attempts
- ✅ Configure backup authentication methods
- ✅ Test account recovery flows
- ✅ Enable audit logging
- ✅ Regular security audits

## Troubleshooting

### "Invalid token" errors

Check that:
1. JWT_SECRET is set and consistent
2. Token hasn't expired
3. Token format is correct (Bearer token)

```typescript
// Backend logs
console.log('Token:', req.headers.authorization);
console.log('Decoded:', jwt.decode(token));
```

### Email verification not working

Check that:
1. Email service is configured
2. API keys are valid
3. FROM address is verified with provider
4. Check spam folder

### OAuth redirect issues

Ensure:
1. Callback URLs match exactly in provider settings
2. Environment variables are set
3. App is using HTTPS (required by most OAuth providers)

## Next Steps

- **Customize auth UI**: Edit generated components in `frontend/src/components/auth/`
- **Add custom claims**: Extend JWT payload in `backend/src/utils/jwt.ts`
- **Integrate with external systems**: Use generated API endpoints
- **Learn more**: Read [Workflow Best Practices](../WORKFLOW-BEST-PRACTICES.md)

## Resources

- [JWT Best Practices](https://datatracker.ietf.org/doc/html/rfc8725)
- [OAuth 2.0 Specification](https://oauth.net/2/)
- [OWASP Authentication Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html)
- [Extended Schema Guide](../EXTENDED-SCHEMA-GUIDE.md)

---

**Questions?** Open an issue on [GitHub](https://github.com/mogullabs/bangstack/issues) or join our [Discord](https://discord.gg/bangstack)
