From 264574f5f3761cb6cd58eb8fb6370cf82f6b8434 Mon Sep 17 00:00:00 2001 From: seo-wo <4nyth4me@gmail.com> Date: Fri, 1 Dec 2023 16:20:58 +0900 Subject: [PATCH] feat: add auth middleware for signup add google middleware to verify google access_token #18 --- src/auth/google/google.middleware.ts | 45 ++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/auth/google/google.middleware.ts diff --git a/src/auth/google/google.middleware.ts b/src/auth/google/google.middleware.ts new file mode 100644 index 0000000..5116812 --- /dev/null +++ b/src/auth/google/google.middleware.ts @@ -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' }); + } + } +}