Skip to main content

Overview

FitAiid supports Google OAuth for both login and registration. These are separate endpoints with distinct purposes:
  • Google Login: For users who already have a FitAiid account
  • Google Register: For new users creating an account with Google
Both endpoints require Firebase Authentication on the client side. Users must first authenticate with Firebase, then send the Firebase UID to the backend.

Google Login

POST /api/auth/google
endpoint
Authenticate an existing user with their Google account

Authentication

Authorization
string
Not required - public endpoint

Request Body

email
string
required
User’s Google email address
  • Must already be registered in FitAiid database
  • Will be converted to lowercase
  • Example: “[email protected]
uid
string
required
Firebase Authentication UID
  • Obtained from Firebase after Google authentication
  • Used to verify the user’s identity
firstName
string
User’s first name from Google profile (optional, for logging purposes)
lastName
string
User’s last name from Google profile (optional, for logging purposes)

Response

success
boolean
Indicates if login was successful
message
string
Success message: “Inicio de sesión con Google exitoso”
token
string
JWT authentication token (expires in 30 days by default)
user
object
Complete user profile (same structure as standard login)

Error Responses

Status CodeError MessageDescription
400”El email y UID son obligatorios”Missing email or uid in request
401”Tu cuenta ha sido desactivada. Contacta soporte.”Account is inactive
404”Este correo no está registrado. Por favor regístrate primero.”Email not found in database

Code Examples

import { getAuth, signInWithPopup, GoogleAuthProvider } from 'firebase/auth';

// 1. Authenticate with Firebase
const auth = getAuth();
const provider = new GoogleAuthProvider();

try {
  const result = await signInWithPopup(auth, provider);
  const firebaseUser = result.user;
  
  // 2. Send to FitAiid backend
  const response = await fetch('https://api.fitaiid.com/api/auth/google', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      email: firebaseUser.email,
      uid: firebaseUser.uid,
      firstName: firebaseUser.displayName?.split(' ')[0],
      lastName: firebaseUser.displayName?.split(' ').slice(1).join(' ')
    })
  });
  
  const data = await response.json();
  
  if (data.success) {
    // Store token
    localStorage.setItem('authToken', data.token);
    console.log('Logged in:', data.user);
  } else {
    console.error('Login failed:', data.message);
  }
} catch (error) {
  console.error('Google login error:', error);
}

Example Response

{
  "success": true,
  "message": "Inicio de sesión con Google exitoso",
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": "65e4a321b4f78901234567890",
    "firstName": "John",
    "lastName": "Doe",
    "email": "[email protected]",
    "role": "customer",
    "isActive": true,
    "isEmailVerified": true,
    "fitnessProfile": {
      "questionnaireCompleted": false
    }
  }
}

Google Register

POST /api/auth/google-register
endpoint
Create a new user account using Google OAuth

Authentication

Authorization
string
Not required - public endpoint

Request Body

email
string
required
User’s Google email address
  • Must NOT already exist in FitAiid database
  • Will be converted to lowercase
  • Example: “[email protected]
uid
string
required
Firebase Authentication UID
  • Obtained from Firebase after Google authentication
  • Verified with Firebase Admin SDK on backend
firstName
string
User’s first name
  • If not provided, extracted from Firebase displayName
  • Falls back to “Usuario” if unavailable
lastName
string
User’s last name
  • If not provided, extracted from Firebase displayName
  • Falls back to “Google” if unavailable

Response

success
boolean
Indicates if registration was successful
message
string
Success message: “Registro con Google exitoso”
token
string
JWT authentication token (expires in 30 days by default)
user
object
Newly created user profile

Error Responses

Status CodeError MessageDescription
400”El email y UID son obligatorios”Missing email or uid in request
400”Este correo ya está registrado. Por favor inicia sesión.”Email already exists in database
400”Error al verificar con Google. Intenta de nuevo.”Firebase UID verification failed

Code Examples

import { getAuth, signInWithPopup, GoogleAuthProvider } from 'firebase/auth';

// 1. Authenticate with Firebase
const auth = getAuth();
const provider = new GoogleAuthProvider();

try {
  const result = await signInWithPopup(auth, provider);
  const firebaseUser = result.user;
  
  // 2. Register with FitAiid backend
  const response = await fetch('https://api.fitaiid.com/api/auth/google-register', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      email: firebaseUser.email,
      uid: firebaseUser.uid,
      firstName: firebaseUser.displayName?.split(' ')[0],
      lastName: firebaseUser.displayName?.split(' ').slice(1).join(' ')
    })
  });
  
  const data = await response.json();
  
  if (data.success) {
    // Store token
    localStorage.setItem('authToken', data.token);
    console.log('Registered:', data.user);
    
    // Redirect to fitness questionnaire
    window.location.href = '/questionnaire';
  } else {
    console.error('Registration failed:', data.message);
  }
} catch (error) {
  console.error('Google registration error:', error);
}

Example Response

{
  "success": true,
  "message": "Registro con Google exitoso",
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": "65e4b123c5g89012345678ab",
    "firstName": "Jane",
    "lastName": "Smith",
    "fullName": "Jane Smith",
    "email": "[email protected]",
    "role": "customer",
    "isActive": true,
    "isEmailVerified": true,
    "fitnessProfile": {
      "questionnaireCompleted": false
    },
    "customerLevel": "bronze",
    "totalOrders": 0,
    "totalSpent": 0,
    "loyaltyPoints": 0,
    "createdAt": "2024-03-06T15:45:00.000Z"
  }
}

Implementation Flow

1

Client Authentication

User clicks “Sign in with Google” button and authenticates with Firebase on the client side.
2

Obtain Firebase UID

Client receives Firebase user object containing uid, email, and displayName.
3

Choose Endpoint

  • If registering new user: call /api/auth/google-register
  • If logging in existing user: call /api/auth/google
4

Backend Verification

For registration, backend verifies the UID with Firebase Admin SDK to ensure authenticity.
5

Store Token

Client stores the returned JWT token for subsequent authenticated requests.
6

Redirect User

  • New users: Redirect to fitness questionnaire
  • Existing users: Redirect to dashboard

Security Features

Firebase Verification

For registration, the backend verifies the Firebase UID with Firebase Admin SDK to prevent fraudulent account creation.

Email Verification

Google OAuth users are automatically marked as email verified since Google has already verified their email.

Temporary Password

Google users are assigned the temporary password “GoogleTemp123” (securely hashed). They should never need to use it.

Activity Logging

All Google authentication events are logged with IP address for security auditing.

Common Issues

The email is already in the database. Use /api/auth/google for login instead of /api/auth/google-register.
The email doesn’t exist in the database. Use /api/auth/google-register to create an account first.
The Firebase UID is invalid or expired. Ensure the user properly authenticated with Firebase first and the UID is current.

Next Steps

Get Profile

Retrieve user profile after authentication

Email Registration

Alternative registration with email/password

Build docs developers (and LLMs) love