-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
for signup add google middleware to verify google access_token #18
- Loading branch information
Showing
1 changed file
with
45 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
import { Injectable, NestMiddleware, Logger } from '@nestjs/common'; | ||
import { Request, Response, NextFunction } from 'express'; | ||
import axios from 'axios'; | ||
|
||
@Injectable() | ||
export class GoogleMiddleware implements NestMiddleware { | ||
private readonly logger = new Logger(GoogleMiddleware.name); | ||
constructor() {} | ||
|
||
async use(req: Request, res: Response, next: NextFunction) { | ||
const rawCookies = req.headers.cookie?.split(';'); | ||
const parsedCookies: any = {}; | ||
rawCookies?.forEach((rawCookie) => { | ||
const parsedCookie = rawCookie.split('='); | ||
parsedCookies[parsedCookie[0].trim()] = parsedCookie[1]; | ||
}); | ||
const token = parsedCookies.google_token; | ||
|
||
if (token) { | ||
try { | ||
const response = await axios.get( | ||
'https://www.googleapis.com/oauth2/v3/tokeninfo', | ||
{ | ||
params: { | ||
access_token: token, | ||
}, | ||
}, | ||
); | ||
const userInfo = response.data; | ||
if (!userInfo) { | ||
throw new Error('Invalid token'); | ||
} | ||
req['user'] = userInfo; | ||
console.log('userInfo', userInfo); | ||
next(); | ||
} catch (error) { | ||
this.logger.error(error); | ||
res.status(401).json({ message: 'Invalid token' }); | ||
} | ||
} else { | ||
this.logger.error('Token not found'); | ||
res.status(401).json({ message: 'Token not found' }); | ||
} | ||
} | ||
} |