LogixVast

Authentication

LogixVast APIs use Django's social authentication system with Google OAuth2, providing secure and convenient authentication for users.

Implementation Guide

1. Backend Setup

First, install the required Django packages:

pip install django-allauth django-rest-auth django-cors-headers

Configure your Django settings:

# settings.py

INSTALLED_APPS = [
    ...
    'django.contrib.sites',
    'corsheaders',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google',
    'rest_framework',
    'rest_framework.authtoken',
    'dj_rest_auth',
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    ...
]

# CORS settings
CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",  # Next.js development server
    "https://your-production-domain.com",
]

# Authentication settings
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
}

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'allauth.account.auth_backends.AuthenticationBackend',
]

# Social account settings
SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'APP': {
            'client_id': 'your-client-id',
            'secret': 'your-client-secret',
            'key': ''
        },
        'SCOPE': [
            'profile',
            'email',
        ],
        'AUTH_PARAMS': {
            'access_type': 'online',
        }
    }
}

# Session settings
SESSION_COOKIE_AGE = 1209600  # 2 weeks in seconds
SESSION_COOKIE_SECURE = True  # Use only with HTTPS
SESSION_COOKIE_SAMESITE = 'Lax'

2. Frontend Integration

Install the required packages for your Next.js frontend:

npm install @react-oauth/google jwt-decode

Create an authentication context and hook:

// hooks/useAuth.ts
import { createContext, useContext, useState, useEffect } from 'react';
import { GoogleLogin } from '@react-oauth/google';

interface AuthContextType {
  user: any;
  isAuthenticated: boolean;
  login: (googleToken: string) => Promise<void>;
  logout: () => Promise<void>;
}

const AuthContext = createContext<AuthContextType | null>(null);

export function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  const login = async (googleToken: string) => {
    try {
      const response = await fetch('/api/v1/auth/google/', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ token: googleToken }),
      });

      if (!response.ok) throw new Error('Authentication failed');

      const data = await response.json();
      setUser(data.user);
      setIsAuthenticated(true);
      localStorage.setItem('sessionToken', data.key);
    } catch (error) {
      console.error('Login error:', error);
      throw error;
    }
  };

  const logout = async () => {
    try {
      await fetch('/api/v1/auth/logout/', {
        method: 'POST',
        headers: {
          Authorization: `Token ${localStorage.getItem('sessionToken')}`,
        },
      });
    } finally {
      setUser(null);
      setIsAuthenticated(false);
      localStorage.removeItem('sessionToken');
    }
  };

  return (
    <AuthContext.Provider value={{ user, isAuthenticated, login, logout }}>
      {children}
    </AuthContext.Provider>
  );}

Implement the login component:

// components/Login.tsx
import { useAuth } from '@/hooks/useAuth';
import { GoogleLogin } from '@react-oauth/google';

export default function Login() {
  const { login } = useAuth();

  return (
    <div className="flex justify-center items-center min-h-screen">
      <div className="bg-white p-8 rounded-lg shadow-md">
        <h2 className="text-2xl font-bold mb-4">Sign in to LogixVast</h2>
        <GoogleLogin
          onSuccess={(credentialResponse) => {
            login(credentialResponse.credential);
          }}
          onError={() => {
            console.log('Login Failed');
          }}
        />
      </div>
    </div>
  );}

API Endpoints

Authentication

POST/api/v1/auth/google/

Authenticate with Google OAuth2 token

Request Body

Type: object

{
  "token": "google-oauth2-token"
}

Response

Type: object

{
  "key": "django-session-token",
  "user": {
    "id": 1,
    "email": "user@example.com",
    "first_name": "John",
    "last_name": "Doe"
  }
}

User Management

GET/api/v1/auth/user/

Get current user information

Response

Type: object

{
  "id": 1,
  "email": "user@example.com",
  "first_name": "John",
  "last_name": "Doe",
  "is_staff": false
}
POST/api/v1/auth/logout/

End the current session

Response

Type: object

{
  "detail": "Successfully logged out."
}

Security Considerations

  • Always use HTTPS in production
  • Store sensitive credentials in environment variables
  • Implement proper CORS settings to prevent unauthorized access
  • Use secure session cookies with appropriate flags
  • Implement rate limiting for authentication endpoints
  • Regularly rotate Google OAuth2 client secrets
  • Monitor authentication attempts for suspicious activity

Troubleshooting

Common Issues

  • CORS errors: Ensure your Django CORS settings include your frontend domain
  • Invalid token: Check if the Google OAuth2 token hasn't expired
  • Session issues: Verify cookie settings and domain configuration
  • Permission denied: Check user permissions in Django admin