Skip to main content
CodePlanet Docs

Authentication System

Login, OAuth, and MFA security

CodePlanet uses a robust authentication system to ensure secure access to all platform features while providing seamless user experience.

🔐 Authentication Methods

Email/Password Authentication

Standard email and password registration with:

  • Secure password hashing using bcrypt
  • Email verification for account activation
  • Password reset functionality
  • Account lockout after failed attempts

OAuth 2.0 Integration

Connect with popular services:

  • GitHub: For developers and code portfolio integration
  • Google: Quick signup with Google account
  • Discord: Community access and notifications

Multi-Factor Authentication (MFA)

Enhanced security with:

  • Time-based One-Time Passwords (TOTP)
  • SMS verification codes
  • Authenticator app support
  • Backup recovery codes

🛡️ Security Features

Session Management

  • Secure HTTP-only cookies
  • Token-based authentication for API access
  • Automatic session expiration
  • Concurrent session limits

Password Security

  • Minimum 8-character passwords
  • Complexity requirements (uppercase, lowercase, numbers, symbols)
  • Password strength meter during registration
  • Regular security audits

Rate Limiting

  • Login attempt throttling
  • API request limiting
  • Brute force protection
  • Account lockout policies

🔄 Authentication Flow

User Registration

graph TD
    A[User Registration] --> B[Email Validation]
    B --> C[Password Hashing]
    C --> D[Account Creation]
    D --> E[Welcome Email]
    E --> F[Dashboard Access]

Login Process

graph TD
    A[Login Request] --> B[Credentials Validation]
    B --> C[Session Creation]
    C --> D[Token Generation]
    D --> E[User Redirect]

Password Reset

  1. User requests password reset
  2. System sends verification email
  3. User clicks reset link
  4. New password is set and confirmed
  5. Session is invalidated across all devices

🔑 API Authentication

JWT Tokens

  • Short-lived access tokens (15 minutes)
  • Refresh tokens for session extension
  • Token revocation capabilities
  • Automatic token refresh

API Key Management

  • User-specific API keys
  • Key rotation and expiration
  • Usage monitoring and limits
  • Fine-grained permission controls

👥 User Roles and Permissions

Role-Based Access Control

  • Guest: Limited access to public content
  • User: Full access to learning features
  • Pro User: Premium features and priority support
  • Admin: Platform management and moderation
  • Moderator: Community management tools

Permission Scopes

  • Read: View content and personal data
  • Write: Create and modify content
  • Execute: Run code and use development tools
  • Admin: Full system access and user management

📱 Device Management

Trusted Devices

  • Device fingerprinting for security
  • Session management across devices
  • Remote session termination
  • Login notification emails

Mobile Authentication

  • Biometric authentication support
  • Push notification approvals
  • Device-specific security settings
  • Offline access tokens

🔧 Implementation Details

Frontend Integration

// Authentication context setup
import { useAuth } from '@/hooks/use-auth'
 
function App() {
  const { user, login, logout } = useAuth()
  
  return (
    <div>
      {user ? (
        <button onClick={logout}>Logout</button>
      ) : (
        <button onClick={() => login()}>Login</button>
      )}
    </div>
  )
}

Backend API Protection

# Protected route example
@app.route('/api/user/profile')
@require_auth
@require_permission('read:profile')
def get_profile():
    user_id = get_current_user_id()
    return user_service.get_profile(user_id)

Token Refresh Handling

// Automatic token refresh
const api = axios.create({
  baseURL: '/api',
  timeout: 10000
})
 
api.interceptors.response.use(
  response => response,
  async error => {
    if (error.response?.status === 401) {
      try {
        const newToken = await refreshAccessToken()
        error.config.headers.Authorization = `Bearer ${newToken}`
        return api.request(error.config)
      } catch (refreshError) {
        // Redirect to login
        window.location.href = '/login'
      }
    }
    return Promise.reject(error)
  }
)

🛠️ Configuration

Environment Variables

# Authentication settings
AUTH_JWT_SECRET=your-super-secret-key
AUTH_JWT_EXPIRES_IN=15m
AUTH_REFRESH_SECRET=your-refresh-secret
AUTH_REFRESH_EXPIRES_IN=7d

# OAuth providers
GITHUB_CLIENT_ID=your-github-client-id
GITHUB_CLIENT_SECRET=your-github-client-secret
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret

# MFA settings
MFA_ENABLED=true
MFA_ISSUER=CodePlanet

Security Headers

  • Content Security Policy (CSP)
  • Strict Transport Security (HSTS)
  • X-Content-Type-Options
  • X-Frame-Options
  • Referrer-Policy

🔍 Monitoring and Logging

Security Events

  • Login attempts and success rates
  • Failed authentication attempts
  • Token usage and expiration
  • Suspicious activity detection

Audit Trails

  • User authentication history
  • Device access logs
  • Permission changes
  • Security incident reports

🆘 Troubleshooting

Common Issues

  • Locked Account: Contact support after multiple failed attempts
  • Token Expiration: Automatic refresh should handle this
  • OAuth Errors: Clear browser cache and try again
  • MFA Problems: Use backup codes or contact support

Debugging Steps

  1. Check browser console for errors
  2. Verify network connectivity
  3. Clear localStorage and cookies
  4. Try incognito/private browsing mode
  5. Contact support with error details

The authentication system is designed to be both secure and user-friendly, providing multiple access methods while maintaining the highest security standards.