# Authentication Quick Start Guide

## 🚀 5-Minute Integration

### 1. Install Dependencies
```bash
npm install hono effect bcrypt jose
npm install -D @types/bcrypt
```

### 2. Initialize Database
```bash
node --import tsx/esm src/server/database/init-db.ts
```

### 3. Create Your Server
```typescript
// src/server/index.ts
import { Hono } from "hono";
import { authRouter, authMiddleware } from "./auth/index.js";

const app = new Hono();

// Public routes
app.route("/api/auth", authRouter);

// Protected routes
app.get("/api/protected", authMiddleware, (c) => {
  const user = c.get("user");
  return c.json({ message: `Hello ${user.username}` });
});

export default app;
```

### 4. Test It
```bash
# Register
curl -X POST http://localhost:3000/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{"username":"john","email":"john@example.com","password":"SecurePass123"}'

# Login
curl -X POST http://localhost:3000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"john@example.com","password":"SecurePass123"}' \
  -c cookies.txt

# Access protected route
curl http://localhost:3000/api/protected \
  -b cookies.txt
```

## 📚 Key Endpoints

| Method | Endpoint | Auth | Description |
|--------|----------|------|-------------|
| POST | `/api/auth/register` | No | Create new account |
| POST | `/api/auth/login` | No | Login and get token |
| POST | `/api/auth/logout` | Yes | Revoke session |
| GET | `/api/auth/me` | Yes | Get current user |

## 🔐 Security Features

✅ **Password**: bcrypt (12 rounds), min 8 chars, uppercase + lowercase + number
✅ **Tokens**: JWT with RS256, 7-day expiry, httpOnly cookies
✅ **Lockout**: 5 failed attempts = 15 minute lockout
✅ **Sessions**: Revocable, tracked with IP/user agent
✅ **Audit**: All auth events logged

## 🛡️ Protected Routes

```typescript
// Single route
app.get("/api/secret", authMiddleware, (c) => {
  const user = c.get("user");
  const session = c.get("session");
  // Your logic here
});

// Route group
const protectedRoutes = new Hono();
protectedRoutes.use("*", authMiddleware);
protectedRoutes.get("/profile", (c) => { /* ... */ });
protectedRoutes.get("/settings", (c) => { /* ... */ });
app.route("/api/protected", protectedRoutes);
```

## 📝 Response Formats

### Success: Register
```json
{
  "user": {
    "id": "uuid",
    "username": "john",
    "email": "john@example.com",
    "emailVerified": false
  }
}
```

### Success: Login
```json
{
  "user": {
    "id": "uuid",
    "username": "john",
    "email": "john@example.com",
    "emailVerified": false
  },
  "token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..."
}
```

### Error: Validation
```json
{
  "error": "VALIDATION_ERROR",
  "field": "password",
  "message": "Password must be at least 8 characters long"
}
```

### Error: Authentication
```json
{
  "error": "AuthError",
  "message": "Invalid email or password"
}
```

## 🔧 Environment Variables

```bash
# Optional - defaults to development settings
NODE_ENV=production  # Enables secure cookies
PORT=3000           # Server port
```

## 🎯 Common Patterns

### Custom Error Handling
```typescript
app.post("/api/auth/login", async (c) => {
  try {
    const loginEffect = Effect.gen(function* () {
      const authService = yield* AuthService;
      return yield* authService.login(email, password, ip, ua);
    });

    const result = await Effect.runPromise(
      Effect.provide(loginEffect, AppLayer)
    );

    return c.json(result, 200);
  } catch (error) {
    // Your custom error handling
    if (error._tag === "AuthError") {
      logSecurityEvent(error);
    }
    return handleError(error);
  }
});
```

### Admin Check
```typescript
const adminMiddleware: MiddlewareHandler = async (c, next) => {
  const user = c.get("user");

  // Add your admin check logic
  const isAdmin = user.email.endsWith("@admin.com");

  if (!isAdmin) {
    return c.json({ error: "FORBIDDEN" }, 403);
  }

  await next();
};

app.get("/api/admin/*", authMiddleware, adminMiddleware, (c) => {
  // Admin-only logic
});
```

### Token from Request
```typescript
import { getCookie } from "hono/cookie";

const token = c.req.header("Authorization")?.substring(7)
  || getCookie(c, "auth_token");
```

### Manual Token Verification
```typescript
import { Effect } from "effect";
import { AppLayer } from "./auth/middleware/authMiddleware.js";
import { AuthService } from "./auth/services/AuthService.js";

const verifyEffect = Effect.gen(function* () {
  const authService = yield* AuthService;
  return yield* authService.verifyToken(token);
});

const { user, session } = await Effect.runPromise(
  Effect.provide(verifyEffect, AppLayer)
);
```

## 🐛 Debugging

### Enable Verbose Logging
```typescript
// Add to service methods
Effect.tap(() =>
  Effect.sync(() => console.log("Debug info here"))
)
```

### Check Session Status
```typescript
const session = c.get("session");
console.log({
  id: session.id,
  expires: new Date(session.expiresAt),
  isRevoked: session.isRevoked,
});
```

### View Audit Logs
```sql
-- Check recent auth events
SELECT * FROM audit_logs
WHERE action LIKE 'USER_%'
ORDER BY created_at DESC
LIMIT 10;
```

## 🔍 Troubleshooting

**401 Unauthorized**
- Token missing or malformed
- Token expired (>7 days)
- Session revoked
- User account inactive

**400 Bad Request**
- Validation failed
- Email/username already exists
- Password too weak

**Account Locked**
- 5+ failed login attempts
- Wait 15 minutes or contact admin

**TypeScript Errors**
- Ensure `tsconfig.json` has `"target": "ES2022"` or higher
- Check Effect-TS version compatibility

## 📖 Full Documentation

- **README.md** - Complete API reference and security details
- **ARCHITECTURE.md** - System design and data flow diagrams
- **IMPLEMENTATION_SUMMARY.md** - Implementation checklist and features
- **example-usage.ts** - Complete Hono integration example

## 💡 Next Steps

1. Add rate limiting to login endpoint
2. Implement email verification
3. Add password reset flow
4. Set up OAuth2 providers
5. Enable two-factor authentication
6. Add session management UI

## 🤝 Support

For issues or questions:
1. Check existing documentation
2. Review example-usage.ts
3. Inspect audit logs for security events
4. Verify database schema is initialized
