From 14fcf05893e1360762d1aadfca8accfc1910204b Mon Sep 17 00:00:00 2001 From: Suzy Date: Sat, 22 Jul 2023 23:50:20 +0530 Subject: [PATCH] feat: add authentication --- server/src/middleware/auth.ts | 46 +++++++++++++++++++++++++ server/src/projects/projects.service.ts | 1 + server/src/user/user.service.ts | 1 + 3 files changed, 48 insertions(+) create mode 100644 server/src/middleware/auth.ts diff --git a/server/src/middleware/auth.ts b/server/src/middleware/auth.ts new file mode 100644 index 000000000..be4bae5a7 --- /dev/null +++ b/server/src/middleware/auth.ts @@ -0,0 +1,46 @@ +import { Request, Response, NextFunction } from 'express' +const clientId = process.env.CLIENT_ID +const clientSecret = process.env.CLIENT_SECRET + +export const checkAuth = async ( + req: Request, + res: Response, + next: NextFunction +) => { + const { data } = req.query + + if (!data) { + return res.status(400).json({ success: false, message: 'data not found' }) + } + + try { + const tokenResponse = await fetch( + 'https://github.com/login/oauth/access_token', + { + method: 'POST', + headers: { Accept: 'application/json' }, + body: JSON.stringify({ + client_id: clientId, + client_secret: clientSecret, + code: data, + }), + } + ).then((res) => res.json()) + + const accessToken = tokenResponse.data.access_token + + const userResponse = await fetch('https://api.github.com/user', { + method: 'GET', + headers: { Authorization: `token ${accessToken}` }, + }).then((res) => res.json()) + + // const userData = userResponse.data + + // req.session.user = userData + + next() + } catch (error) { + console.error('GitHub OAuth Error:', error) + return res.status(500).json({ success:false,message: 'GitHub authentication failed' }) + } +} diff --git a/server/src/projects/projects.service.ts b/server/src/projects/projects.service.ts index 576f70fdc..a146bbead 100644 --- a/server/src/projects/projects.service.ts +++ b/server/src/projects/projects.service.ts @@ -1,3 +1,4 @@ +import { ProjectModel } from '../schema/Projects/project.schema' import { AllProjectsType } from './project.interface' const getAllProjects = async () => { diff --git a/server/src/user/user.service.ts b/server/src/user/user.service.ts index f210a8a49..f33daa2a3 100644 --- a/server/src/user/user.service.ts +++ b/server/src/user/user.service.ts @@ -1,3 +1,4 @@ +import { UserModel } from "../schema/User/user.schema" import { UserType } from "./user.interface"