Skip to content

Commit

Permalink
feat: Add google auth for signin
Browse files Browse the repository at this point in the history
  • Loading branch information
GSinseswa721 committed May 4, 2024
1 parent b775d65 commit 6700d02
Show file tree
Hide file tree
Showing 8 changed files with 130 additions and 16 deletions.
13 changes: 0 additions & 13 deletions .env.example

This file was deleted.

8 changes: 7 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@
"jsend": "^1.1.0",
"morgan": "^1.10.0",
"nodemon": "^3.1.0",
"passport": "^0.7.0",
"passport-facebook": "^3.0.0",
"passport-google-oauth20": "^2.0.0",
"pg": "^8.11.5",
"reflect-metadata": "^0.2.2",
"source-map-support": "^0.5.21",
Expand All @@ -57,6 +60,9 @@
"@types/jsend": "^1.0.32",
"@types/morgan": "^1.9.9",
"@types/node": "^20.12.7",
"@types/passport": "^1.0.16",
"@types/passport-facebook": "^3.0.3",
"@types/passport-google-oauth20": "^2.0.14",
"@types/reflect-metadata": "^0.1.0",
"@types/supertest": "^6.0.2",
"@types/winston": "^2.4.4",
Expand All @@ -75,4 +81,4 @@
"typescript": "^5.4.5",
"typescript-eslint": "^7.7.1"
}
}
}
2 changes: 1 addition & 1 deletion src/controllers/authController.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Request, Response } from 'express';
import { User } from '../entities/User';;
import { User } from '../entities/User';
import bcrypt from 'bcrypt';
import { getRepository } from 'typeorm';

Expand Down
38 changes: 38 additions & 0 deletions src/controllers/facebook.auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { getRepository } from 'typeorm';
import { User } from '../entities/user.auth';

Check warning on line 2 in src/controllers/facebook.auth.ts

View workflow job for this annotation

GitHub Actions / build-lint-test-coverage

Trailing spaces not allowed

async function findUserAccountIdProvider(accountId: string, provider: string): Promise<User | undefined> {

Check warning on line 4 in src/controllers/facebook.auth.ts

View workflow job for this annotation

GitHub Actions / build-lint-test-coverage

Missing space before function parentheses
try {
const userRepository = getRepository(User);

Check warning on line 7 in src/controllers/facebook.auth.ts

View workflow job for this annotation

GitHub Actions / build-lint-test-coverage

Trailing spaces not allowed
const user = await userRepository.findOne({
where: {
accountId: accountId,
provider: provider,
},
});

Check warning on line 14 in src/controllers/facebook.auth.ts

View workflow job for this annotation

GitHub Actions / build-lint-test-coverage

Trailing spaces not allowed
if (user === null) {
return undefined;
}

Check warning on line 18 in src/controllers/facebook.auth.ts

View workflow job for this annotation

GitHub Actions / build-lint-test-coverage

Trailing spaces not allowed
return user as User;
} catch (error) {
console.error('Error finding user:', error);
return undefined;
}
}
const accountId = 'your_account_id';
const provider = 'facebook';

findUserAccountIdProvider(accountId, provider)
.then((user) => {
if (user) {
console.log('User found:', user);
} else {
console.log('User not found');
}
})
.catch((error) => {
console.error('Error:', error);
});
25 changes: 25 additions & 0 deletions src/entities/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,15 @@ import {
@Entity()
@Unique(['email'])
export class User {
save() {
throw new Error('Method not implemented.');
}
static create(arg0: { accountId: string; name: string; provider: string; }): User | PromiseLike<User | null> | null {
throw new Error('Method not implemented.');
}
static findOne(arg0: { accountId: any; provider: string; }) {
throw new Error('Method not implemented.');
}
@PrimaryGeneratedColumn('uuid')
@IsNotEmpty()
id!: string;
Expand Down Expand Up @@ -66,4 +75,20 @@ import {

@UpdateDateColumn()
updatedAt!: Date;

@Column({ nullable: true })
@IsString()
accountId?: string;

@Column({ nullable: true })
@IsString()
name?: string;

@Column({ nullable: true })
@IsString()
photoURL?: string;

@Column({ nullable: true })
@IsString()
provider?: string;
}
22 changes: 22 additions & 0 deletions src/entities/user.auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Entity, PrimaryGeneratedColumn, Column, BaseEntity } from 'typeorm';

@Entity()
export class User extends BaseEntity {
@PrimaryGeneratedColumn('uuid')
id: string | undefined;

@Column({ type: 'text', nullable: true, unique: true })
email: string | undefined;

@Column({ type: 'text', nullable: true })
accountId: string | undefined;

@Column({ type: 'text', nullable: true })
name!: string;

@Column({ type: 'text', nullable: true })
photoURL: string | undefined;

@Column({ type: 'text', nullable: true })
provider: string | undefined;
}
17 changes: 16 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import express, { Request, Response } from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import router from './routes';
import { addDocumentation } from './startups/docs';
import 'reflect-metadata';
import { passportConfig } from './middlewares/auth';
import dotenv from 'dotenv';
dotenv.config();


import { CustomError, errorHandler } from './middlewares/errorHandler';
import morgan from 'morgan';
import { dbConnection } from './startups/dbConnection';
import passport from 'passport';
dotenv.config();

export const app = express();
Expand All @@ -32,6 +35,18 @@ dbConnection();
const morganFormat = ':method :url :status :response-time ms - :res[content-length]';
app.use(morgan(morganFormat));

//passport
passportConfig();

//Google OAuth routes
app.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }));

app.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/login' }),
(req, res) => {
res.redirect('/profile');
}
);
export const server = app.listen(port, () => {
console.log(`[server]: Server is running at http://localhost:${port}`);
});
21 changes: 21 additions & 0 deletions src/middlewares/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import passport from 'passport';
import { Strategy as GoogleStrategy } from 'passport-google-oauth20';

export function passportConfig() {
const clientID = process.env.GOOGLE_CLIENT_ID;
const clientSecret = process.env.GOOGLE_CLIENT_SECRET;

if (!clientID || !clientSecret) {
throw new Error('Google client ID or client secret is missing.');
}

passport.use(new GoogleStrategy({
clientID,
clientSecret,
callbackURL: "/auth/google/callback"
},
(accessToken, refreshToken, profile, done) => {
done(null, profile);
}
));
}

0 comments on commit 6700d02

Please sign in to comment.