creating tokens and such

This commit is contained in:
talksik
2022-04-01 12:38:52 -04:00
parent ce0fb7a885
commit 0e69e0ed64
5 changed files with 48 additions and 34 deletions
+4 -1
View File
@@ -1,3 +1,6 @@
MONGO_CONNECTION_STRING=mongodb+srv://default:[email protected]/default?retryWrites=true&w=majority MONGO_CONNECTION_STRING=mongodb+srv://default:[email protected]/default?retryWrites=true&w=majority
JWT_TOKEN_SECRET=afajdslfwk1@lkkasdfl21ASDF!2 JWT_TOKEN_SECRET=afajdslfwk1@lkkasdfl21ASDF!2
GOOGLE_AUTH_CLIENT_ID=423533244953-banligobgbof8hg89i6cr1l7u0p7c2pk.apps.googleusercontent.com
GOOGLE_AUTH_CLIENT_SECRET=
+2
View File
@@ -10,5 +10,7 @@ export const loadConfig = () => {
return { return {
MONGO_CONNECTION_STRING: process.env.MONGO_CONNECTION_STRING!, MONGO_CONNECTION_STRING: process.env.MONGO_CONNECTION_STRING!,
JWT_TOKEN_SECRET: process.env.JWT_TOKEN_SECRET!, JWT_TOKEN_SECRET: process.env.JWT_TOKEN_SECRET!,
GOOGLE_AUTH_CLIENT_ID: process.env.GOOGLE_AUTH_CLIENT_ID!,
GOOGLE_AUTH_CLIENT_SECRET: process.env.GOOGLE_AUTH_CLIENT_SECRET!,
}; };
}; };
+8 -20
View File
@@ -1,10 +1,8 @@
import { NextFunction, Request, Response } from "express"; import { NextFunction, Request, Response } from "express";
import { OAuth2Client } from "google-auth-library"; import { loadConfig } from "../config";
const client = new OAuth2Client( const config = loadConfig();
"423533244953-banligobgbof8hg89i6cr1l7u0p7c2pk.apps.googleusercontent.com"
);
// used by specific routes that need to authentication // used by specific routes that need to authentication
export const authCheck = async ( export const authCheck = async (
@@ -12,25 +10,15 @@ export const authCheck = async (
res: Response, res: Response,
next: NextFunction next: NextFunction
) => { ) => {
const { authorization } = req.headers;
// verify jwt token
try { try {
// const ticket = await client.verifyIdToken({ const { authorization } = req.headers;
// idToken: authorization ?? "",
// audience:
// "423533244953-banligobgbof8hg89i6cr1l7u0p7c2pk.apps.googleusercontent.com", // Specify the CLIENT_ID of the app that accesses the backend
// });
// const userId = ticket.getPayload()?.sub;
// const email = ticket.getPayload()?.email;
// if (!userId) throw new Error("No google user Id found"); // verify jwt token
const jwtSecret = config.JWT_TOKEN_SECRET;
// // used in subsequent handlers if (!authorization) {
// // todo: have to get our database id for the user instead of google's id throw Error("No provided header");
// res.locals.userId = userId; }
// res.locals.email = email;
next(); next();
} catch (error) { } catch (error) {
+32 -9
View File
@@ -1,6 +1,7 @@
import { GoogleUserInfo, User } from "@nirvana/core/models"; import { GoogleUserInfo, User } from "@nirvana/core/models";
import express, { Application, Request, Response } from "express"; import express, { Application, Request, Response } from "express";
import LoginResponse from "../../core/responses/login.response";
import { OAuth2Client } from "google-auth-library"; import { OAuth2Client } from "google-auth-library";
import { ObjectID } from "bson"; import { ObjectID } from "bson";
import { ObjectId } from "mongodb"; import { ObjectId } from "mongodb";
@@ -8,10 +9,13 @@ import { UserService } from "../services/user.service";
import { UserStatus } from "../../core/models/user.model"; import { UserStatus } from "../../core/models/user.model";
import { authCheck } from "../middleware/auth"; import { authCheck } from "../middleware/auth";
import { collections } from "../services/database.service"; import { collections } from "../services/database.service";
import { loadConfig } from "../config";
const client = new OAuth2Client( const jwt = require("jsonwebtoken");
"423533244953-banligobgbof8hg89i6cr1l7u0p7c2pk.apps.googleusercontent.com"
); const config = loadConfig();
const client = new OAuth2Client(config.GOOGLE_AUTH_CLIENT_ID);
export default function getUserRoutes() { export default function getUserRoutes() {
const router = express.Router(); const router = express.Router();
@@ -38,8 +42,7 @@ async function login(req: Request, res: Response) {
try { try {
const ticket = await client.verifyIdToken({ const ticket = await client.verifyIdToken({
idToken: (id_token as string) ?? "", idToken: (id_token as string) ?? "",
audience: audience: config.GOOGLE_AUTH_CLIENT_ID, // Specify the CLIENT_ID of the app that accesses the backend
"423533244953-banligobgbof8hg89i6cr1l7u0p7c2pk.apps.googleusercontent.com", // Specify the CLIENT_ID of the app that accesses the backend
}); });
const googleUserId = ticket.getPayload()?.sub as string; const googleUserId = ticket.getPayload()?.sub as string;
const email = ticket.getPayload()?.email as string; const email = ticket.getPayload()?.email as string;
@@ -50,7 +53,7 @@ async function login(req: Request, res: Response) {
} }
// return user details if it passed auth middleware // return user details if it passed auth middleware
const user = await UserService.getUserByEmail(email); let user = await UserService.getUserByEmail(email);
// if no user found, then go ahead and create user // if no user found, then go ahead and create user
if (!user) { if (!user) {
@@ -86,17 +89,37 @@ async function login(req: Request, res: Response) {
newUser._id = insertResult?.insertedId; newUser._id = insertResult?.insertedId;
// create jwt token with new user info // create jwt token with new user info
const jwtToken = jwt.sign(
{
userId: newUser._id,
googleUserId: newUser.googleId,
picture: newUser.picture,
email: newUser.email,
name: newUser.name,
},
config.JWT_TOKEN_SECRET
);
insertResult insertResult
? res.status(200).send(newUser) ? res.status(200).send(new LoginResponse(jwtToken, newUser))
: res.status(500).send("Failed to create account, already exists"); : res.status(500).send("Failed to create account, already exists");
return; return;
} }
// create jwt token with existing user info // create jwt token with new user info
const jwtToken = jwt.sign(
{
userId: user._id,
googleUserId: user.googleId,
picture: user.picture,
email: user.email,
name: user.name,
},
config.JWT_TOKEN_SECRET
);
res.status(200).send(user); res.status(200).send(new LoginResponse(jwtToken, user));
} catch (error) { } catch (error) {
console.log(error); console.log(error);
res.status(500).send(`Problem with signing user up or logging in`); res.status(500).send(`Problem with signing user up or logging in`);
+2 -4
View File
@@ -59,11 +59,9 @@ export class UserService {
} }
static async createUserIfNotExists(newUser: User) { static async createUserIfNotExists(newUser: User) {
const exists = ( const getUser = await this.getUserByEmail(newUser.email);
await collections.users?.findOne({ googleId: newUser.googleId })
)?._id;
if (!exists) { if (!getUser) {
return await collections.users?.insertOne(newUser); return await collections.users?.insertOne(newUser);
} }