Skip to content

Commit

Permalink
Merge pull request #364 from Khingz/FEAT-Google-auth
Browse files Browse the repository at this point in the history
feat: reimplement google auth
  • Loading branch information
AdeGneus authored Jul 28, 2024
2 parents 75b8a80 + 6b732d2 commit 0c54e52
Show file tree
Hide file tree
Showing 10 changed files with 233 additions and 180 deletions.
31 changes: 0 additions & 31 deletions src/config/google.passport.config.ts

This file was deleted.

92 changes: 92 additions & 0 deletions src/controllers/AuthController.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { Request, Response, NextFunction } from "express";
import { AuthService } from "../services/auth.services";
import { BadRequest } from "../middleware";
import { GoogleAuthService } from "../services/google.auth.service";

const authService = new AuthService();

Expand Down Expand Up @@ -333,11 +335,101 @@ const changePassword = async (
}
};


/**
* @swagger
* /api/v1/auth/google:
* post:
* summary: Handle Google authentication and register/login a user
* description: This endpoint handles Google OAuth2.0 authentication. It accepts a Google user payload and either registers a new user or logs in an existing one.
* tags:
* - Auth
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* email:
* type: string
* format: email
* description: The user's email address.
* example: [email protected]
* email_verified:
* type: boolean
* description: Whether the user's email is verified.
* example: true
* name:
* type: string
* description: The user's full name.
* example: "John Doe"
* picture:
* type: string
* format: url
* description: URL to the user's profile picture.
* example: "https://example.com/avatar.jpg"
* sub:
* type: string
* description: Google user ID (subject claim).
* example: "1234567890"
* responses:
* 200:
* description: User authenticated successfully
* content:
* application/json:
* schema:
* type: object
* properties:
* message:
* type: string
* description: Verify if authentication is successful
* example: Authentication successful
* user:
* type: object
* description: The authenticated user object.
* access_token:
* type: string
* description: JWT access token for authentication.
* example: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
* 400:
* description: Bad Request - Invalid or missing data in request body
* 500:
* description: Internal Server Error - An unexpected error occurred
*/
const handleGoogleAuth = async (
req: Request,
res: Response,
next: NextFunction,
) => {
const googleAuthService = new GoogleAuthService();
const userData = req.body;
try {
if (!userData) {
throw new BadRequest("Bad request");
}
const isDbUser = await googleAuthService.getUserByGoogleId(userData.sub);
const dbUser = await googleAuthService.handleGoogleAuthUser(
userData,
isDbUser,
);
res.status(200).json({
status: "success",
message: "User successfully authenticated",
access_token: dbUser.access_token,
user: dbUser.user
});
} catch (error) {
next(error);
}
};

export {
signUp,
verifyOtp,
login,
forgotPassword,
resetPassword,
changePassword,
handleGoogleAuth
};
38 changes: 0 additions & 38 deletions src/controllers/GoogleAuthController.ts

This file was deleted.

4 changes: 1 addition & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import express, { Express, Request, Response } from "express";
import config from "./config";
import dotenv from "dotenv";
import cors from "cors";
import passport from "./config/google.passport.config";
import {
userRouter,
authRoute,
Expand Down Expand Up @@ -52,7 +51,6 @@ server.use(
);

server.use(Limiter);
server.use(passport.initialize());
server.use(express.json());
server.use(express.urlencoded({ extended: true }));

Expand Down Expand Up @@ -97,4 +95,4 @@ AppDataSource.initialize()
})
.catch((error) => log.error(error));

export default server;
export default server;
19 changes: 9 additions & 10 deletions src/models/profile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@ import {
import { getIsInvalidMessage } from "../utils";

@ValidatorConstraint({ name: "IsValidMobilePhone", async: false })
class IsValidMobilePhone implements ValidatorConstraintInterface {
validate(phone: string, args: ValidationArguments) {
return /^(?:\+\d{1,3}[- ]?)?\d{10}$/.test(phone);
}

defaultMessage(args: ValidationArguments) {
return getIsInvalidMessage("Phone number");
}
}
// class IsValidMobilePhone implements ValidatorConstraintInterface {
// validate(phone: string, args: ValidationArguments) {
// return /^(?:\+\d{1,3}[- ]?)?\d{10}$/.test(phone);
// }

// defaultMessage(args: ValidationArguments) {
// return getIsInvalidMessage("Phone number");
// }
// }

@Entity()
export class Profile extends ExtendedBaseEntity {
Expand All @@ -32,7 +32,6 @@ export class Profile extends ExtendedBaseEntity {
last_name: string;

@Column()
@Validate(IsValidMobilePhone)
phone: string;

@Column()
Expand Down
67 changes: 2 additions & 65 deletions src/routes/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,11 @@ import {
forgotPassword,
resetPassword,
changePassword,
handleGoogleAuth,
} from "../controllers";
import { Router } from "express";
import { authMiddleware, checkPermissions } from "../middleware";
import { UserRole } from "../enums/userRoles";
import {
googleAuthCallback,
initiateGoogleAuthRequest,
} from "../controllers/GoogleAuthController";

const authRoute = Router();

Expand All @@ -27,67 +24,7 @@ authRoute.put(
changeUserRole,
);

// ---------------------------Google Auth Route Begins------------------------- //

// For manually testing google auth functionality locally
authRoute.get("/auth/test-google-auth", (req, res) => {
res.send(
'<a href="http://localhost:8000/api/v1/auth/google">Authenticate with Google</a>',
);
});

/**
* @openapi
* /auth/google:
* get:
* summary: Initiates the Google authentication process
* tags:
* - Auth
* responses:
* '302':
* description: Redirects to Google login page for user authentication
* headers:
* Location:
* description: The URL to which the client is redirected (Google's OAuth2 authorization URL)
* schema:
* type: string
* format: uri
* '500':
* description: Internal Server Error
*/
authRoute.get("/google", initiateGoogleAuthRequest);

/**
* @openapi
* /auth/google/callback:
* get:
* summary: Handle Google authentication callback
* tags:
* - Auth
* parameters:
* - in: query
* name: code
* schema:
* type: string
* required: true
* description: The authorization code returned by Google
* responses:
* '302':
* description: Redirects to the dashboard after successful authentication
* headers:
* Location:
* description: The URL to which the client is redirected
* schema:
* type: string
* format: uri
* '401':
* description: Unauthorized - if authentication fails
* '500':
* description: Internal Server Error - if something goes wrong during the callback handling
*/
authRoute.get("/auth/google/callback", googleAuthCallback);

// ---------------------------Google Auth Route Ends------------------------- //
authRoute.post("/auth/google", handleGoogleAuth);

authRoute.post("/auth/forgot-password", forgotPassword);
authRoute.post("/auth/reset-password", resetPassword);
Expand Down
Loading

0 comments on commit 0c54e52

Please sign in to comment.