Skip to content

Commit

Permalink
Merge with main
Browse files Browse the repository at this point in the history
  • Loading branch information
mraysu committed Apr 9, 2024
2 parents 739b1c1 + 0c210a5 commit dd045fa
Show file tree
Hide file tree
Showing 30 changed files with 538 additions and 60 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/build-and-deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ jobs:
run: |
cd frontend
touch .env
echo APP_FIREBASE_CONFIG=${{ secrets.APP_FIREBASE_CONFIG }} >> .env
echo NEXT_PUBLIC_FIREBASE_CONFIG=${{ secrets.NEXT_PUBLIC_FIREBASE_CONFIG }} >> .env
- name: Create Backend .env
run: |
cd backend
Expand Down
3 changes: 3 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
"keywords": [],
"author": "",
"license": "ISC",
"engines": {
"node": "18"
},
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.3.1",
Expand Down
49 changes: 18 additions & 31 deletions backend/src/controllers/user.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { NextFunction, Request, Response } from "express";
import { validationResult } from "express-validator";
import { signInWithEmailAndPassword } from "firebase/auth";
import admin from "firebase-admin";

import { AuthError } from "../errors/auth";
import { ValidationError } from "../errors/validation";
import UserModel from "../models/user";
import { firebaseAdminAuth, firebaseAuth } from "../util/firebase";
import { firebaseAdminAuth } from "../util/firebase";
import validationErrorParser from "../util/validationErrorParser";

// Define the type for req.body
Expand All @@ -17,8 +16,7 @@ type CreateUserRequestBody = {
};

type LoginUserRequestBody = {
email: string;
password: string;
uid: string;
};

export const createUser = async (
Expand Down Expand Up @@ -65,31 +63,20 @@ export const loginUser = async (
nxt: NextFunction,
) => {
try {
// Check for validation errors
const errors = validationResult(req);
validationErrorParser(errors);

const { email, password } = req.body;
// Sign user into Firebase
await signInWithEmailAndPassword(firebaseAuth, email, password)
.then((userCredential) => {
const user = userCredential.user;
console.log(user);
return UserModel.findById(user.uid);
})
.then((user) => {
if (user !== null) {
res.status(200).json({ uid: user._id, approvalStatus: user.approvalStatus });
}
throw AuthError.LOGIN_ERROR;
})
.catch(() => {
throw AuthError.LOGIN_ERROR;
});
} catch (error) {
console.error(error);
nxt(error);
const uid = req.body.uid;
const user = await UserModel.findById(uid);
if (!user) {
throw ValidationError.USER_NOT_FOUND;
}
res
.status(200)
.json({ uid: user._id, role: user.accountType, approvalStatus: user.approvalStatus });
return;
} catch (e) {
nxt();
console.log(e);
return res.status(400).json({
error: e,
});
}

return;
};
4 changes: 0 additions & 4 deletions backend/src/errors/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@

import { CustomError } from "./errors";

const LOGIN_ERROR = "Login Failed. Please check the username and password.";

const DECODE_ERROR = "Error decoding the auth token. Make sure the auth token is valid";
const TOKEN_NOT_IN_HEADER =
"Token was not found in the header. Be sure to use Bearer <Token> syntax";
Expand All @@ -17,6 +15,4 @@ export class AuthError extends CustomError {
static TOKEN_NOT_IN_HEADER = new AuthError(1, 401, TOKEN_NOT_IN_HEADER);

static INVALID_AUTH_TOKEN = new AuthError(2, 401, INVALID_AUTH_TOKEN);

static LOGIN_ERROR = new AuthError(3, 401, LOGIN_ERROR);
}
2 changes: 2 additions & 0 deletions backend/src/errors/validation.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { CustomError } from "./errors";

const USER_CREATION_UNSUCCESSFUL = "User not created successfully";
const USER_NOT_FOUND = "User not found in database";

export class ValidationError extends CustomError {
constructor(code: number, status: number, message: string) {
super(code, status, "VALIDATION ERROR: " + message);
}
static USER_CREATION_UNSUCCESSFUL = new ValidationError(1, 400, USER_CREATION_UNSUCCESSFUL);
static USER_NOT_FOUND = new ValidationError(1, 400, USER_NOT_FOUND);
}
5 changes: 3 additions & 2 deletions backend/src/routes/user.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import express from "express";

import * as UserController from "../controllers/user";
import { verifyAuthToken } from "../validators/auth";
import * as UserValidator from "../validators/user";

const router = express.Router();

router.use(express.json());

router.post("/login", UserValidator.loginUser, UserController.loginUser);
router.post("/", UserValidator.createUser, UserController.createUser);
router.post("/create", UserValidator.createUser, UserController.createUser);

Check warning on line 11 in backend/src/routes/user.ts

View workflow job for this annotation

GitHub Actions / Backend lint and style check

Promise returned in function argument where a void return was expected
router.get("/", [verifyAuthToken], UserController.loginUser);

Check warning on line 12 in backend/src/routes/user.ts

View workflow job for this annotation

GitHub Actions / Backend lint and style check

Promise returned in function argument where a void return was expected

export default router;
9 changes: 2 additions & 7 deletions backend/src/util/firebase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,10 @@
* firebase to for authentication.
*/

import * as firebase from "firebase/app";
import { getAuth } from "firebase/auth";
import * as firebaseAdmin from "firebase-admin/app";
import { getAuth as getAdminAuth } from "firebase-admin/auth";

import { firebaseConfig, serviceAccountKey } from "../config";
import { serviceAccountKey } from "../config";

/**
* This will initialize the firebase app to store
Expand All @@ -21,9 +19,6 @@ firebaseAdmin.initializeApp({
credential: firebaseAdmin.cert(JSON.parse(serviceAccountKey) as string),
});

const firebaseApp = firebase.initializeApp(JSON.parse(firebaseConfig) as object);

const firebaseAdminAuth = getAdminAuth();
const firebaseAuth = getAuth(firebaseApp);

export { firebaseAdminAuth, firebaseAuth };
export { firebaseAdminAuth };
2 changes: 1 addition & 1 deletion backend/src/validators/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export const createUser: ValidationChain[] = [
];

export const loginUser: ValidationChain[] = [
body("email")
body("uid")
.notEmpty()
.withMessage("Email cannot be empty.")
.isEmail()
Expand Down
1 change: 1 addition & 0 deletions frontend/.eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
// "@typescript-eslint/ban-ts-comment": "off",
// "@typescript-eslint/no-explicit-any": "off",
// "@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/no-empty-function": "off",

"@typescript-eslint/no-unsafe-assignment": "warn",

Expand Down
Loading

0 comments on commit dd045fa

Please sign in to comment.