Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion api/main_endpoints/routes/Auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,14 @@ router.post('/login', async (req, res) => {
details: { email: user.email }
}).catch(logger.error);

res.cookie('jwtToken', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
path: '/',
maxAge: 2 * 60 * 60 * 1000
});

res.json({ token: `JWT ${token}` });

} catch (error) {
Expand All @@ -209,7 +217,21 @@ router.post('/verify', async function(req, res) {
if (decoded.status !== OK) {
return res.sendStatus(decoded.status);
}
res.status(OK).json(decoded.token);
// Return the cookie's token in the body so the React app can keep
// attaching Authorization: Bearer headers for API calls. External
// callers using a header to authenticate get back their own token.
const cookieToken = req.cookies && req.cookies.jwtToken;
const headerToken = req.headers.authorization
&& req.headers.authorization.startsWith('Bearer ')
? req.headers.authorization.split('Bearer ')[1]
: null;
const rawToken = cookieToken || headerToken;
res.status(OK).json({ ...decoded.token, token: rawToken ? `JWT ${rawToken.replace(/^JWT\s/, '')}` : undefined });
});

router.post('/logout', function(req, res) {
res.clearCookie('jwtToken', { path: '/' });
res.sendStatus(OK);
});

router.post('/generateHashedId', async (req, res) => {
Expand Down
9 changes: 8 additions & 1 deletion api/main_endpoints/util/passport.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,16 @@ const ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('../models/User');
const { secretKey } = require('../../config/config.json');

const cookieOrHeaderExtractor = function(req) {
if (req && req.cookies && req.cookies.jwtToken) {
return req.cookies.jwtToken;
}
return ExtractJwt.fromAuthHeaderWithScheme('jwt')(req);
};

module.exports = function(passport) {
const options = {};
options.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt');
options.jwtFromRequest = cookieOrHeaderExtractor;
options.secretOrKey = secretKey;

passport.use(
Expand Down
2 changes: 2 additions & 0 deletions api/main_endpoints/util/token-functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ async function decodeToken(request, requiredAccessLevel = membershipState.NON_ME
try {
if (request.headers.authorization && request.headers.authorization.startsWith('Bearer ')) {
token = request.headers.authorization.split('Bearer ')[1];
} else if (request.cookies && request.cookies.jwtToken) {
token = request.cookies.jwtToken;
} else if (request.query && request.query.token) {
token = request.query.token;
}
Expand Down
39 changes: 39 additions & 0 deletions api/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"axios": "^0.21.2",
"bcryptjs": "^2.4.3",
"bluebird": "^3.7.2",
"cookie-parser": "^1.4.7",
"cors": "^2.8.5",
"express": "^4.17.1",
"form-data": "^4.0.0",
Expand Down
2 changes: 2 additions & 0 deletions api/util/SceHttpServer.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const cors = require('cors');
const http = require('http');
const mongoose = require('mongoose');
Expand Down Expand Up @@ -35,6 +36,7 @@ class SceHttpServer {
this.app.locals.email = 'test@test.com';

this.app.use(cors());
this.app.use(cookieParser());
this.app.use(
bodyParser.json({
// support JSON-encoded request bodies
Expand Down
46 changes: 30 additions & 16 deletions src/APIFunctions/Auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ export async function loginUser(email, password) {
try {
const res = await fetch(url.href, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json'
},
Expand All @@ -88,37 +89,50 @@ export async function loginUser(email, password) {
}

/**
* Checks if the user is signed in by evaluating a jwt token in local storage.
* Checks if the user is signed in by verifying the auth cookie with the API.
* @returns {UserApiResponse} Containing information for
* whether the user is signed or not
*/
export async function checkIfUserIsSignedIn() {
let status = new UserApiResponse();

const token = window.localStorage
? window.localStorage.getItem('jwtToken')
: '';

// If there is not token in local storage,
// we cant do anything and return
if (!token) {
status.error = true;
return status;
}

const url = new URL('/api/Auth/verify', BASE_API_URL);
try {
const res = await fetch(url.href, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
'Content-Type': 'application/json'
}
});
if (res.ok) {
const result = await res.json();
status.responseData = result;
const { token, ...rest } = await res.json();
status.responseData = rest;
status.token = token;
} else {
status.error = true;
}
} catch(err) {
status.error = true;
status.responseData = err;
}
return status;
}

/**
* Logs the user out by calling the backend to clear the auth cookie.
* @returns {ApiResponse} Whether the logout call succeeded.
*/
export async function logoutUser() {
let status = new ApiResponse();
const url = new URL('/api/Auth/logout', BASE_API_URL);
try {
const res = await fetch(url.href, {
method: 'POST',
credentials: 'include'
});
if (!res.ok) {
status.error = true;
}
} catch(err) {
status.error = true;
Expand Down
5 changes: 3 additions & 2 deletions src/Components/Navbar/AdminNavbar.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React from 'react';
import { useSCE } from '../context/SceContext';
import { membershipState } from '../../Enums';
import { logoutUser } from '../../APIFunctions/Auth';

export default function UserNavBar(props) {
const { user, setAuthenticated } = useSCE();
Expand All @@ -15,9 +16,9 @@ export default function UserNavBar(props) {
return className;
};

function handleLogout() {
async function handleLogout() {
setAuthenticated(false);
window.localStorage.removeItem('jwtToken');
await logoutUser();
window.location.reload();
}

Expand Down
5 changes: 3 additions & 2 deletions src/Components/Navbar/NavBarWrapper.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import React from 'react';
import UserNavbar from './UserNavbar';
import AdminNavbar from './AdminNavbar';
import { useSCE } from '../context/SceContext';
import { logoutUser } from '../../APIFunctions/Auth';

function NavBarWrapper({
enableAdminNavbar = false,
Expand All @@ -10,10 +11,10 @@ function NavBarWrapper({
}) {
const { user, setUser, setAuthenticated } = useSCE();

function handleLogout() {
async function handleLogout() {
setAuthenticated(false);
setUser({});
window.localStorage.removeItem('jwtToken');
await logoutUser();
window.location.reload();
}

Expand Down
1 change: 0 additions & 1 deletion src/Pages/Login/Login.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ export default function Login() {
const loginStatus = await loginUser(email, password);
if (!loginStatus.error) {
setAuthenticated(true);
window.localStorage.setItem('jwtToken', loginStatus.token);
if (queryParams.get('redirect')) {
window.location.href = queryParams.get('redirect');
return;
Expand Down
3 changes: 2 additions & 1 deletion src/Pages/Overview/Overview.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const svg = require('./SVG');
import { getAllUsers, deleteUserByID, getNewPaidMembersThisSemester } from '../../APIFunctions/User';
import { formatFirstAndLastName } from '../../APIFunctions/Profile';
import { getAllUsersValidVerifiedAndSubscribed } from '../../APIFunctions/User';
import { logoutUser } from '../../APIFunctions/Auth';
// import { membershipState } from '../../Enums';
import ConfirmationModal from
'../../Components/DecisionModal/ConfirmationModal.js';
Expand Down Expand Up @@ -39,7 +40,7 @@ export default function Overview() {
}
if (userToDel._id === user._id) {
// logout
window.localStorage.removeItem('jwtToken');
await logoutUser();
window.location.reload();
return window.alert('Self-deprecation is an art');
}
Expand Down
5 changes: 3 additions & 2 deletions src/Pages/Profile/MemberView/DeleteAccountModal.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React from 'react';
import { deleteUserByID } from '../../../APIFunctions/User';
import { logoutUser } from '../../../APIFunctions/Auth';
import { useSCE } from '../../../Components/context/SceContext';

export default function DeleteAccountModal(props) {
Expand All @@ -14,8 +15,8 @@ export default function DeleteAccountModal(props) {

if (!apiResponse.error) {
bannerCallback('Account Deleted', 'success');
setTimeout(() => {
window.localStorage.removeItem('jwtToken');
setTimeout(async () => {
await logoutUser();
window.location.reload();
}, 2000);
} else {
Expand Down
5 changes: 5 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ import { checkIfUserIsSignedIn } from './APIFunctions/Auth';
import { SceContext } from './Components/context/SceContext';
import SearchModal from './Components/ShortcutKeyModal/SearchModal';

// Auth migrated from localStorage to httpOnly cookies; sweep any stale entry.
if (typeof window !== 'undefined' && window.localStorage) {
window.localStorage.removeItem('jwtToken');
}

function App() {
const [authenticated, setAuthenticated] = useState(false);
const [isAuthenticating, setIsAuthenticating] = useState(true);
Expand Down
Loading