-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add validation function and oauth signin
- Loading branch information
1 parent
dfa1e52
commit bf0839b
Showing
19 changed files
with
402 additions
and
14 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
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
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,55 @@ | ||
import asyncHandler from "express-async-handler"; | ||
import { Request, Response } from "express"; | ||
import { z } from "zod"; | ||
import AuthService from "../service/authService"; | ||
|
||
|
||
const oauthSignIn = asyncHandler(async (req: Request, res: Response) => { | ||
const { redirectURL } = req.body; | ||
|
||
try { | ||
const resp = await AuthService.oauthSignIn(redirectURL); | ||
res.status(resp.status).json({ resp }); | ||
} catch (error) { | ||
res.status(500).json({ message: 'Internal Server Error' }); | ||
} | ||
}); | ||
|
||
const authCallback = asyncHandler(async (req: Request, res: Response) => { | ||
let codeString: string; | ||
let nextString: string | undefined; | ||
let append = '#status=auth_failure'; | ||
|
||
try { | ||
console.log(req.query); | ||
const { code, next } = req.query; | ||
|
||
if (!code) { | ||
throw new Error('Invalid code'); | ||
} | ||
|
||
codeString = z.string().parse(code); | ||
nextString = z.string().optional().parse(next); | ||
|
||
const { accessToken, refreshToken } = await AuthService.oauthCallback(codeString, nextString); | ||
append = `#access_token=${accessToken}&refresh_token=${refreshToken}&status=auth_success`; | ||
|
||
} catch (err) { | ||
console.error(err); | ||
} finally { | ||
if (nextString) { | ||
res.redirect(303, nextString + append); | ||
} else { | ||
res.status(append === '#status=auth_failure' ? 400 : 200).json({ message: append }); | ||
} | ||
} | ||
|
||
}); | ||
|
||
|
||
const AuthController = { | ||
oauthSignIn, | ||
authCallback, | ||
} | ||
|
||
export { AuthController as default }; |
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
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
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,21 @@ | ||
// jwt middleware for express | ||
import jwt from "jsonwebtoken"; | ||
import { Request, Response, NextFunction } from "express"; | ||
|
||
const jwtMiddleware = (req: Request, res: Response, next: NextFunction) => { | ||
const authHeader = req.headers['authorization']; | ||
const token = authHeader && authHeader.split(' ')[1]; | ||
|
||
if (token == null) { | ||
return res.sendStatus(401); | ||
} | ||
|
||
jwt.verify(token, process.env.JWT_SECRET || "", (err, user) => { | ||
if (err) { | ||
return res.sendStatus(403); | ||
} | ||
next(); | ||
}); | ||
} | ||
|
||
export default jwtMiddleware; |
This file was deleted.
Oops, something went wrong.
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
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,10 @@ | ||
import Express from "express"; | ||
import AuthController from "../controllers/auth"; | ||
|
||
const router = Express.Router(); | ||
|
||
router.post("/oauth/signin", AuthController.oauthSignIn); | ||
router.get("/oauth/callback", AuthController.authCallback); | ||
// router.get("/:userID/rankings", SeasonController.getUserAllSeasonRankings); | ||
|
||
export { router as default }; |
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 |
---|---|---|
@@ -1,10 +1,8 @@ | ||
import Express from "express"; | ||
import UserController from "../controllers/user"; | ||
import SeasonController from "../controllers/season"; | ||
|
||
const router = Express.Router(); | ||
|
||
router.post("/", UserController.createUser); | ||
// router.get("/:userID/rankings", SeasonController.getUserAllSeasonRankings); | ||
router.get("/:userID", UserController.createUser); | ||
|
||
export { router as default }; |
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,90 @@ | ||
import { SupabaseService } from '../utils/supabase'; | ||
|
||
import { jwtDecode } from "jwt-decode"; | ||
import UserService from "../service/userService"; | ||
import { isValidEmail, getEmailPrefix } from "../utils/validator"; | ||
import supabase from "../utils/supabase"; | ||
import { z } from 'zod'; | ||
import TokenService from './tokenService'; | ||
import { GeneralResp, OauthcallbackResp } from '../types/types'; | ||
|
||
const oauthSignIn = async ( | ||
url: string | ||
) => { | ||
let redirectURL: string; | ||
try { | ||
redirectURL = z.string().url().parse(url); | ||
} catch (err) { | ||
return { | ||
status: 400, | ||
message: 'Invalid redirectURL', | ||
data: null, | ||
} as GeneralResp; | ||
} | ||
|
||
try { | ||
const resp = await SupabaseService.signInWithAzure(redirectURL); | ||
return { | ||
status: 302, | ||
message: 'waiting for response from azure', | ||
data: resp, | ||
} as GeneralResp; | ||
} catch (err) { | ||
console.log("error in createUser with azure: ", err) | ||
return { | ||
status: 500, | ||
message: 'Internal Server Error', | ||
data: null, | ||
} as GeneralResp; | ||
} | ||
} | ||
|
||
const oauthCallback = async ( | ||
code: string, | ||
next: string | undefined, | ||
): Promise<OauthcallbackResp> => { | ||
// verify the query parameters | ||
const resp = await supabase.auth.exchangeCodeForSession(code); | ||
|
||
const supabaseToken = resp.data.session?.access_token; | ||
|
||
if (resp.error || !supabaseToken) { | ||
throw new Error("Failed to exchange code for session."); | ||
} | ||
|
||
const decodedJWTToken = jwtDecode(supabaseToken); | ||
const decodedJWTObj = decodedJWTToken as { | ||
aud: string; | ||
exp: number; | ||
iat: number; | ||
iss: string; | ||
sub: string; | ||
email: string; | ||
role: string; | ||
session_id: string; | ||
} | ||
console.log(decodedJWTObj); | ||
|
||
let user = await UserService.getUserByEmail(decodedJWTObj.email); | ||
|
||
if (!user) { | ||
const email = isValidEmail.parse(decodedJWTObj.email); | ||
const userName = getEmailPrefix(email); | ||
user = await UserService.createUser(userName, decodedJWTObj.email); | ||
} | ||
|
||
const accessToken = await TokenService.generateAccessToken(user._id.toString(), user.email); | ||
const refreshToken = await TokenService.generateRefreshToken(user._id.toString(), user.email); | ||
|
||
return { | ||
accessToken: accessToken, | ||
refreshToken: refreshToken, | ||
} | ||
} | ||
|
||
const AuthService = { | ||
oauthSignIn, | ||
oauthCallback, | ||
} | ||
|
||
export { AuthService as default }; |
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
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
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,32 @@ | ||
import jwt from "jsonwebtoken"; | ||
|
||
const minuteInSeconds = 60; | ||
|
||
const generateAccessToken = async ( | ||
id: string, | ||
email: string | ||
) => { | ||
const secret = process.env.JWT_SECRET || ""; | ||
const token = jwt.sign({ id, email }, secret, { | ||
expiresIn: 10 * minuteInSeconds | ||
}); | ||
return token; | ||
} | ||
|
||
const generateRefreshToken = async ( | ||
id: string, | ||
email: string | ||
) => { | ||
const secret = process.env.JWT_SECRET || ""; | ||
const token = jwt.sign({ id, email }, secret, { | ||
expiresIn: "7d" | ||
}); | ||
return token; | ||
} | ||
|
||
const TokenService = { | ||
generateAccessToken, | ||
generateRefreshToken, | ||
} | ||
|
||
export { TokenService as default }; |
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
Oops, something went wrong.