Skip to content

Commit

Permalink
feat: add auth middleware
Browse files Browse the repository at this point in the history
for signup add google middleware to verify google access_token

#18
  • Loading branch information
seo-wo committed Dec 1, 2023
1 parent 3d021cb commit 264574f
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions src/auth/google/google.middleware.ts
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' });
}
}
}

0 comments on commit 264574f

Please sign in to comment.