Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 406345ada1 | |||
| d79a70d66f | |||
| cec30620ec | |||
| 763efb75bf | |||
| 77260d5d30 | |||
| 157bb5dd90 | |||
| 20657fda22 | |||
| 168bc695b6 | |||
| a197073bb1 | |||
| 35d1a48f02 | |||
| 2b2e65d43e | |||
| 678d55779d | |||
| 76fdbc0d13 | |||
| 39ddd8158a |
@@ -2,6 +2,7 @@ WEB_PROTOCOL=http
|
|||||||
WEB_ADDRESS=localhost
|
WEB_ADDRESS=localhost
|
||||||
WEB_RESET_ADDRESS=localhost/reset
|
WEB_RESET_ADDRESS=localhost/reset
|
||||||
WEB_PORT=3200
|
WEB_PORT=3200
|
||||||
|
WEB_ORIGIN=http://localhost:3001
|
||||||
|
|
||||||
DB_HOSTNAME=database
|
DB_HOSTNAME=database
|
||||||
DB_DATABASE=auth
|
DB_DATABASE=auth
|
||||||
|
|||||||
@@ -1,23 +0,0 @@
|
|||||||
name: Node.js CI
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [ main ]
|
|
||||||
pull_request:
|
|
||||||
branches: [ main ]
|
|
||||||
jobs:
|
|
||||||
build:
|
|
||||||
name: Run test suites
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
strategy:
|
|
||||||
matrix:
|
|
||||||
node-version: [16.x]
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v2
|
|
||||||
- name: Use Node.js ${{ matrix.node-version }}
|
|
||||||
uses: actions/setup-node@v2
|
|
||||||
with:
|
|
||||||
node-version: ${{ matrix.node-version }}
|
|
||||||
cache: 'npm'
|
|
||||||
- run: npm ci
|
|
||||||
- run: npm run build --if-present
|
|
||||||
- run: npm test
|
|
||||||
+1
-2
@@ -1,5 +1,4 @@
|
|||||||
|
FROM node:18
|
||||||
FROM node:16
|
|
||||||
WORKDIR "/app"
|
WORKDIR "/app"
|
||||||
COPY package*.json ./
|
COPY package*.json ./
|
||||||
RUN npm install --production
|
RUN npm install --production
|
||||||
|
|||||||
@@ -46,41 +46,35 @@ Content-Type: application/json
|
|||||||
}
|
}
|
||||||
|
|
||||||
//DOCS: Result (access token's value is your authorization key below)
|
//DOCS: Result (access token's value is your authorization key below)
|
||||||
|
Set-Cookie: refreshToken
|
||||||
|
|
||||||
{
|
{
|
||||||
"accessToken": "abcde",
|
"accessToken": "abcde"
|
||||||
"refreshToken": "fghij"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
###
|
###
|
||||||
|
|
||||||
|
|
||||||
//DOCS: Replace an expired authToken pair with new values
|
//DOCS: Replace an expired accessToken with a new value
|
||||||
POST /auth/token
|
POST /auth/token
|
||||||
Content-Type: application/json
|
Cookie: refreshToken
|
||||||
|
|
||||||
{
|
|
||||||
"token": "refreshToken"
|
|
||||||
}
|
|
||||||
|
|
||||||
//DOCS: Result
|
//DOCS: Result
|
||||||
|
Set-Cookie: refreshToken
|
||||||
|
|
||||||
{
|
{
|
||||||
"accessToken": "abcde",
|
"accessToken": "abcde"
|
||||||
"refreshToken": "fghij"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
###
|
###
|
||||||
|
|
||||||
|
|
||||||
//DOCS: After this is called, the refresh route will no longer work
|
//DOCS: After this is called, the /auth/token route will no longer work
|
||||||
DELETE /auth/logout
|
DELETE /auth/logout
|
||||||
Authorization: Bearer accessToken
|
Authorization: Bearer accessToken
|
||||||
|
Cookie: refreshToken
|
||||||
{
|
|
||||||
"token": "refreshToken"
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
###
|
###
|
||||||
|
|
||||||
|
|||||||
+5
-2
@@ -29,7 +29,9 @@ const question = (prompt, def = null) => {
|
|||||||
(async () => {
|
(async () => {
|
||||||
//project configuration
|
//project configuration
|
||||||
const appName = await question('App Name', 'auth');
|
const appName = await question('App Name', 'auth');
|
||||||
|
const appWebProtocol = await question('Web Protocol', 'https');
|
||||||
const appWebAddress = await question('Web Addr', `${appName}.example.com`);
|
const appWebAddress = await question('Web Addr', `${appName}.example.com`);
|
||||||
|
const appWebOrigin = await question('Web Origin', `${appWebProtocol}://example.com`); //TODO: clean these up properly
|
||||||
const postValidationHookArray = await question('Post Validation Hook Array', '');
|
const postValidationHookArray = await question('Post Validation Hook Array', '');
|
||||||
const resetAddress = await question('Reset Addr', `example.com/reset`);
|
const resetAddress = await question('Reset Addr', `example.com/reset`);
|
||||||
const appPort = await question('App Port', '3200');
|
const appPort = await question('App Port', '3200');
|
||||||
@@ -69,7 +71,8 @@ services:
|
|||||||
- "traefik.http.routers.${appName}router.service=${appName}service@docker"
|
- "traefik.http.routers.${appName}router.service=${appName}service@docker"
|
||||||
- "traefik.http.services.${appName}service.loadbalancer.server.port=${appPort}"
|
- "traefik.http.services.${appName}service.loadbalancer.server.port=${appPort}"
|
||||||
environment:
|
environment:
|
||||||
- WEB_PROTOCOL=https
|
- WEB_PROTOCOL=${appWebProtocol}
|
||||||
|
- WEB_ORIGIN=${appWebOrigin}
|
||||||
- WEB_ADDRESS=${appWebAddress}
|
- WEB_ADDRESS=${appWebAddress}
|
||||||
- HOOK_POST_VALIDATION_ARRAY=${postValidationHookArray}
|
- HOOK_POST_VALIDATION_ARRAY=${postValidationHookArray}
|
||||||
- WEB_RESET_ADDRESS=${resetAddress}
|
- WEB_RESET_ADDRESS=${resetAddress}
|
||||||
@@ -130,7 +133,7 @@ networks:
|
|||||||
`;
|
`;
|
||||||
|
|
||||||
const dockerfile = `
|
const dockerfile = `
|
||||||
FROM node:16
|
FROM node:18
|
||||||
WORKDIR "/app"
|
WORKDIR "/app"
|
||||||
COPY package*.json ./
|
COPY package*.json ./
|
||||||
RUN npm install --production
|
RUN npm install --production
|
||||||
|
|||||||
Generated
+196
-9309
File diff suppressed because it is too large
Load Diff
+12
-13
@@ -1,13 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "auth-server",
|
"name": "auth-server",
|
||||||
"version": "1.4.14",
|
"version": "1.7.0",
|
||||||
"description": "An API centric auth server. Uses Sequelize and mariaDB by default.",
|
"description": "An API centric auth server. Uses Sequelize and mariaDB by default.",
|
||||||
"main": "server/server.js",
|
"main": "server/server.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "node server/server.js",
|
"start": "node server/server.js",
|
||||||
"dev": "npm run watch:server",
|
"dev": "npm run watch:server",
|
||||||
"watch:server": "nodemon . --ext js,jsx,json --ignore 'node_modules/*'",
|
"watch:server": "nodemon . --ext js,jsx,json --ignore 'node_modules/*'"
|
||||||
"test": "jest --coverage --collectCoverageFrom=server/**/*.{js,jsx}"
|
|
||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
@@ -21,18 +20,18 @@
|
|||||||
"homepage": "https://github.com/krgamestudios/auth-server#readme",
|
"homepage": "https://github.com/krgamestudios/auth-server#readme",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"bcryptjs": "^2.4.3",
|
"bcryptjs": "^2.4.3",
|
||||||
|
"cookie-parser": "^1.4.6",
|
||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
"dotenv": "^8.6.0",
|
"dotenv": "^16.0.3",
|
||||||
"express": "^4.17.1",
|
"express": "^4.18.2",
|
||||||
"jsonwebtoken": "^8.5.1",
|
"jsonwebtoken": "^9.0.0",
|
||||||
"mariadb": "^2.5.4",
|
"mariadb": "^3.0.2",
|
||||||
"node-cron": "^2.0.3",
|
"node-cron": "^3.0.2",
|
||||||
"node-fetch": "^2.6.6",
|
"node-fetch": "^2.6.7",
|
||||||
"nodemailer": "^6.6.3",
|
"nodemailer": "^6.8.0",
|
||||||
"sequelize": "^6.6.5"
|
"sequelize": "^6.25.8"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"jest": "^27.5.1",
|
"nodemon": "^2.0.20"
|
||||||
"nodemon": "^2.0.12"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ module.exports = async () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (adminRecord == null) {
|
if (adminRecord == null) {
|
||||||
const webAddress = process.env.WEB_ADDRESS == 'localhost' ? 'example.com' : process.env.WEB_ADDRESS; //can't log in as "localhost"
|
const webAddress = process.env.WEB_ADDRESS == 'localhost:3000' ? 'example.com' : process.env.WEB_ADDRESS; //can't log in as "localhost"
|
||||||
await accounts.create({
|
await accounts.create({
|
||||||
email: `${process.env.ADMIN_DEFAULT_USERNAME}@${webAddress}`,
|
email: `${process.env.ADMIN_DEFAULT_USERNAME}@${webAddress}`,
|
||||||
username: `${process.env.ADMIN_DEFAULT_USERNAME}`,
|
username: `${process.env.ADMIN_DEFAULT_USERNAME}`,
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ const utils = require('util');
|
|||||||
const bcrypt = require('bcryptjs');
|
const bcrypt = require('bcryptjs');
|
||||||
|
|
||||||
const { accounts } = require('../database/models');
|
const { accounts } = require('../database/models');
|
||||||
const tokenGenerate = require('../utilities/token-generate');
|
const tokenGenerateRefresh = require('../utilities/token-generate-refresh');
|
||||||
|
|
||||||
//utilities
|
//utilities
|
||||||
const validateEmail = require('../utilities/validate-email');
|
const validateEmail = require('../utilities/validate-email');
|
||||||
@@ -49,10 +49,13 @@ const route = async (req, res) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//generate the JWTs
|
//generate the JWTs
|
||||||
const tokens = tokenGenerate(account.index, account.email, account.username, account.type, account.admin, account.mod);
|
const { accessToken, refreshToken } = tokenGenerateRefresh(account.index, account.email, account.username, account.type, account.admin, account.mod);
|
||||||
|
|
||||||
|
//set the cookie
|
||||||
|
res.cookie('refreshToken', refreshToken, { path: '/', httpOnly: true, secure: true, sameSite: 'none', maxAge: 60 * 60 * 24 * 30 * 1000 }); //30 days
|
||||||
|
|
||||||
//finally
|
//finally
|
||||||
res.status(200).json(tokens);
|
res.status(200).send(accessToken);
|
||||||
return null;
|
return null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,10 @@ const tokenDestroy = require('../utilities/token-destroy');
|
|||||||
|
|
||||||
//auth/logout
|
//auth/logout
|
||||||
const route = (req, res) => {
|
const route = (req, res) => {
|
||||||
tokenDestroy(req.body.token);
|
//stored in the cookie
|
||||||
|
tokenDestroy(req.cookies.refreshToken);
|
||||||
|
|
||||||
|
res.clearCookie('refreshToken');
|
||||||
|
|
||||||
return res.status(200).end();
|
return res.status(200).end();
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,13 +4,14 @@ const tokenRefresh = require('../utilities/token-refresh');
|
|||||||
|
|
||||||
//auth/token
|
//auth/token
|
||||||
module.exports = async (req, res) => {
|
module.exports = async (req, res) => {
|
||||||
const refreshToken = req.body.token;
|
return tokenRefresh(req.cookies.refreshToken || '', (err, accessToken, refreshToken) => {
|
||||||
|
|
||||||
return tokenRefresh(refreshToken, (err, token) => {
|
|
||||||
if (err) {
|
if (err) {
|
||||||
return res.status(err).end();
|
return res.status(err).end();
|
||||||
}
|
}
|
||||||
|
|
||||||
return res.status(200).send(token);
|
//set the cookie
|
||||||
|
res.cookie('refreshToken', refreshToken, { path: '/', httpOnly: true, secure: true, sameSite: 'none', maxAge: 60 * 60 * 24 * 30 * 1000 }); //30 days
|
||||||
|
|
||||||
|
return res.status(200).send({ accessToken });
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -64,13 +64,13 @@ const route = async (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (!probe.ok) {
|
if (!probe.ok) {
|
||||||
throw `Could not probe the post validation hook: ${hook}`;
|
throw `Could not probe the post validation hook: ${hook} with accountIndex = ${account.index}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
//discard the result
|
//discard the result
|
||||||
});
|
});
|
||||||
|
|
||||||
Promise.all(promises);
|
await Promise.all(promises);
|
||||||
}
|
}
|
||||||
catch(e) {
|
catch(e) {
|
||||||
console.error('HOOK_POST_VALIDATION_ARRAY is not a valid array of strings in JSON format: ' + e);
|
console.error('HOOK_POST_VALIDATION_ARRAY is not a valid array of strings in JSON format: ' + e);
|
||||||
|
|||||||
+21
-1
@@ -6,10 +6,19 @@ const express = require('express');
|
|||||||
const app = express();
|
const app = express();
|
||||||
const server = require('http').Server(app);
|
const server = require('http').Server(app);
|
||||||
const cors = require('cors');
|
const cors = require('cors');
|
||||||
|
const cookieParser = require('cookie-parser');
|
||||||
|
|
||||||
//config
|
//config
|
||||||
app.use(express.json());
|
app.use(express.json());
|
||||||
app.use(cors());
|
|
||||||
|
app.use(cors({
|
||||||
|
credentials: true,
|
||||||
|
origin: [`${process.env.WEB_ORIGIN}`],
|
||||||
|
allowedHeaders: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'Authorization', 'Set-Cookie'],
|
||||||
|
exposedHeaders: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'Authorization', 'Set-Cookie'],
|
||||||
|
}));
|
||||||
|
|
||||||
|
app.use(cookieParser());
|
||||||
|
|
||||||
//database connection
|
//database connection
|
||||||
const database = require('./database');
|
const database = require('./database');
|
||||||
@@ -27,6 +36,17 @@ app.get('*', (req, res) => {
|
|||||||
|
|
||||||
//startup
|
//startup
|
||||||
server.listen(process.env.WEB_PORT || 3200, async (err) => {
|
server.listen(process.env.WEB_PORT || 3200, async (err) => {
|
||||||
|
//BUGFIX: clear out old refresh tokens
|
||||||
|
const { Op } = require('sequelize');
|
||||||
|
const { tokens } = require('./database/models');
|
||||||
|
tokens.destroy({
|
||||||
|
where: {
|
||||||
|
createdAt: {
|
||||||
|
[Op.lt]: new Date(new Date().setDate(new Date().getDate() - 30))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
await database.sync();
|
await database.sync();
|
||||||
console.log(`listening to localhost:${process.env.WEB_PORT || 3200}`);
|
console.log(`listening to localhost:${process.env.WEB_PORT || 3200}`);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -3,13 +3,13 @@ const jwt = require('jsonwebtoken');
|
|||||||
//middleware to authenticate the JWT token
|
//middleware to authenticate the JWT token
|
||||||
module.exports = (req, res, next) => {
|
module.exports = (req, res, next) => {
|
||||||
const authHeader = req.headers['authorization'];
|
const authHeader = req.headers['authorization'];
|
||||||
const token = authHeader?.split(' ')[1]; //'Bearer token'
|
const accessToken = authHeader?.split(' ')[1]; //'Bearer token'
|
||||||
|
|
||||||
if (!token) {
|
if (!accessToken) {
|
||||||
return res.status(401).send('No token found');
|
return res.status(401).send('No access token found');
|
||||||
}
|
}
|
||||||
|
|
||||||
return jwt.verify(token, process.env.SECRET_ACCESS, (err, user) => {
|
return jwt.verify(accessToken, process.env.SECRET_ACCESS, (err, user) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
return res.status(403).send(err);
|
return res.status(403).send(err);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
const { tokens } = require('../database/models');
|
const { tokens } = require('../database/models');
|
||||||
|
|
||||||
module.exports = (token) => {
|
module.exports = (refreshToken) => {
|
||||||
tokens.destroy({
|
tokens.destroy({
|
||||||
where: {
|
where: {
|
||||||
token: token || ''
|
token: refreshToken || ''
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -1,17 +1,17 @@
|
|||||||
const jwt = require('jsonwebtoken');
|
const jwt = require('jsonwebtoken');
|
||||||
const { tokens } = require('../database/models');
|
const { tokens } = require('../database/models');
|
||||||
|
|
||||||
const generate = require('./token-generate');
|
const generate = require('./token-generate-refresh');
|
||||||
const destroy = require('./token-destroy');
|
const destroy = require('./token-destroy');
|
||||||
|
|
||||||
module.exports = async (token, callback) => {
|
module.exports = async (oldRefreshToken, callback) => {
|
||||||
if (!token) {
|
if (!oldRefreshToken) {
|
||||||
return callback(401);
|
return callback(401);
|
||||||
}
|
}
|
||||||
|
|
||||||
const tokenRecord = await tokens.findOne({
|
const tokenRecord = await tokens.findOne({
|
||||||
where: {
|
where: {
|
||||||
token: token || ''
|
token: oldRefreshToken || ''
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -19,15 +19,15 @@ module.exports = async (token, callback) => {
|
|||||||
return callback(403);
|
return callback(403);
|
||||||
}
|
}
|
||||||
|
|
||||||
jwt.verify(token, process.env.SECRET_REFRESH, (err, user) => {
|
jwt.verify(oldRefreshToken, process.env.SECRET_REFRESH, (err, user) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
return callback(403);
|
return callback(403);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = generate(user.index, user.email, user.username, user.type, user.admin, user.mod);
|
const { accessToken, refreshToken } = generate(user.index, user.email, user.username, user.type, user.admin, user.mod);
|
||||||
|
|
||||||
destroy(token);
|
destroy(oldRefreshToken);
|
||||||
|
|
||||||
return callback(null, result);
|
return callback(null, accessToken, refreshToken);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -1,117 +0,0 @@
|
|||||||
describe('POST /auth/login', () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
jest.resetModules();
|
|
||||||
|
|
||||||
//fix util with jest (used by bcrypt's compare)
|
|
||||||
jest.doMock('util', () => ({
|
|
||||||
promisify: f => async () => f()
|
|
||||||
}));
|
|
||||||
|
|
||||||
//mock out bcrypt
|
|
||||||
jest.doMock('bcryptjs', () => ({
|
|
||||||
genSalt: async amount => {
|
|
||||||
expect(amount).toBe(11);
|
|
||||||
return 'salt';
|
|
||||||
},
|
|
||||||
hash: async (password, salt) => {
|
|
||||||
expect(password).toBe('password');
|
|
||||||
return 'hashed-password';
|
|
||||||
},
|
|
||||||
compare: (lhs, rhs) => {
|
|
||||||
return lhs === rhs;
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
|
|
||||||
//mock out jsonwebtoken
|
|
||||||
jest.doMock('jsonwebtoken', () => ({
|
|
||||||
sign: (content, secretAccess, opts) => {
|
|
||||||
return JSON.stringify(content);
|
|
||||||
},
|
|
||||||
|
|
||||||
verify: (token, secretAccess, callback) => {
|
|
||||||
return callback(null, JSON.parse(token));
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
|
|
||||||
//mock out the sequelize library
|
|
||||||
jest.doMock('sequelize', () => {
|
|
||||||
return {
|
|
||||||
Op: {
|
|
||||||
//
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
//mock out the database object
|
|
||||||
jest.doMock('../../server/database', () => {
|
|
||||||
const mSequelize = {
|
|
||||||
authenticate: jest.fn(),
|
|
||||||
define: jest.fn(),
|
|
||||||
};
|
|
||||||
|
|
||||||
const actualSequelize = jest.requireActual('sequelize');
|
|
||||||
return { Sequelize: jest.fn(() => mSequelize), DataTypes: actualSequelize.DataTypes };
|
|
||||||
});
|
|
||||||
|
|
||||||
//mock out the database models
|
|
||||||
jest.doMock('../../server/database/models', () => ({
|
|
||||||
accounts: {
|
|
||||||
findOne: async (config) => { //can't find any (signup state)
|
|
||||||
expect(config?.where?.email).toBe('email@example.com');
|
|
||||||
return {
|
|
||||||
index: 0,
|
|
||||||
email: config?.where?.email,
|
|
||||||
username: 'username',
|
|
||||||
type: 'alpha',
|
|
||||||
admin: false,
|
|
||||||
mod: false,
|
|
||||||
};
|
|
||||||
},
|
|
||||||
|
|
||||||
update: async (values, config) => {
|
|
||||||
//Do nothing
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
tokens: {
|
|
||||||
create: async (record) => {
|
|
||||||
//Do nothing
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('Basic valid login attempt', async () => {
|
|
||||||
//arguments
|
|
||||||
const req = {
|
|
||||||
body: {
|
|
||||||
email: 'email@example.com',
|
|
||||||
password: 'password',
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const res = {
|
|
||||||
status: code => {
|
|
||||||
expect(code).toBe(200);
|
|
||||||
return {
|
|
||||||
json: tokens => {
|
|
||||||
//decode and analyze the JWT payload
|
|
||||||
const accessToken = JSON.parse(tokens.accessToken);
|
|
||||||
|
|
||||||
expect(accessToken.email).toBe('email@example.com');
|
|
||||||
expect(accessToken.username).toBe('username');
|
|
||||||
},
|
|
||||||
send: msg => { throw msg; },
|
|
||||||
end: () => null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//test
|
|
||||||
const route = require('../../server/auth/login');
|
|
||||||
|
|
||||||
const result = await route(req, res);
|
|
||||||
|
|
||||||
expect(result).toBe(null);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
describe('POST /auth/signup', () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
jest.resetModules();
|
|
||||||
|
|
||||||
//mock out bcrypt
|
|
||||||
jest.doMock('bcryptjs', () => ({
|
|
||||||
genSalt: async amount => {
|
|
||||||
expect(amount).toBe(11);
|
|
||||||
return 'salt';
|
|
||||||
},
|
|
||||||
hash: async (password, salt) => {
|
|
||||||
expect(password).toBe('password');
|
|
||||||
return 'hashed-password';
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
|
|
||||||
//mock out nodemailer
|
|
||||||
jest.doMock('nodemailer', () => ({
|
|
||||||
createTransport: jest.fn(config => {
|
|
||||||
//TODO: test config?
|
|
||||||
return { //return a fake transport object
|
|
||||||
sendMail: async email => {
|
|
||||||
expect(email.to).toBe('email@example.com');
|
|
||||||
return { //return a fake info object
|
|
||||||
accepted: [ email.to ]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
}));
|
|
||||||
|
|
||||||
//mock out the sequelize library
|
|
||||||
jest.doMock('sequelize', () => {
|
|
||||||
return {
|
|
||||||
Op: {
|
|
||||||
//
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
//mock out the database object
|
|
||||||
jest.doMock('../../server/database', () => {
|
|
||||||
const mSequelize = {
|
|
||||||
authenticate: jest.fn(),
|
|
||||||
define: jest.fn(),
|
|
||||||
};
|
|
||||||
|
|
||||||
const actualSequelize = jest.requireActual('sequelize');
|
|
||||||
return { Sequelize: jest.fn(() => mSequelize), DataTypes: actualSequelize.DataTypes };
|
|
||||||
});
|
|
||||||
|
|
||||||
//mock out the database models
|
|
||||||
jest.doMock('../../server/database/models', () => ({
|
|
||||||
accounts: {
|
|
||||||
findOne: () => null //can't find any (signup state)
|
|
||||||
},
|
|
||||||
|
|
||||||
pendingSignups: {
|
|
||||||
upsert: jest.fn(async record => {
|
|
||||||
expect(record.email).toBe('email@example.com');
|
|
||||||
expect(record.username).toBe('username');
|
|
||||||
expect(record.hash).toBe('hashed-password');
|
|
||||||
expect(record.contact).toBe(true);
|
|
||||||
//token is a random UUID
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('Basic valid signup attempt', async () => {
|
|
||||||
//arguments
|
|
||||||
const req = {
|
|
||||||
body: {
|
|
||||||
email: 'email@example.com',
|
|
||||||
username: 'username',
|
|
||||||
password: 'password',
|
|
||||||
contact: true
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const res = {
|
|
||||||
status: code => {
|
|
||||||
expect(code).toBe(200);
|
|
||||||
return {
|
|
||||||
send: msg => expect(msg).toBe('Validation email sent!'),
|
|
||||||
end: () => null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//test
|
|
||||||
const route = require('../../server/auth/signup');
|
|
||||||
|
|
||||||
const result = await route(req, res);
|
|
||||||
|
|
||||||
expect(result).toBe(null);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
describe('Integration Test Suite', () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
jest.resetModules();
|
|
||||||
|
|
||||||
//mock dotenv
|
|
||||||
jest.doMock('dotenv', () => ({
|
|
||||||
config: () => null
|
|
||||||
}));
|
|
||||||
|
|
||||||
//mock express
|
|
||||||
jest.doMock('express', () => {
|
|
||||||
const express = () => ({
|
|
||||||
identity: 'app',
|
|
||||||
use: () => null,
|
|
||||||
get: () => null,
|
|
||||||
});
|
|
||||||
|
|
||||||
express.Router = () => ({
|
|
||||||
identity: 'Router',
|
|
||||||
use: () => null,
|
|
||||||
get: () => null,
|
|
||||||
post: () => null,
|
|
||||||
patch: () => null,
|
|
||||||
delete: () => null,
|
|
||||||
});
|
|
||||||
|
|
||||||
express.json = () => 'json';
|
|
||||||
|
|
||||||
return express;
|
|
||||||
});
|
|
||||||
|
|
||||||
//mock http
|
|
||||||
jest.doMock('http', () => ({
|
|
||||||
Server: app => {
|
|
||||||
expect(app.identity).toBe('app');
|
|
||||||
|
|
||||||
return {
|
|
||||||
listen: (port, cb) => cb()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
|
|
||||||
//mock sequelize
|
|
||||||
class Seq {
|
|
||||||
sync() {}
|
|
||||||
define() {}
|
|
||||||
static INTEGER() {}
|
|
||||||
};
|
|
||||||
|
|
||||||
jest.doMock('sequelize', () => {
|
|
||||||
return Seq;
|
|
||||||
});
|
|
||||||
|
|
||||||
//mock node-cron
|
|
||||||
jest.doMock('node-cron', () => {
|
|
||||||
return {
|
|
||||||
schedule: () => null
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('Start The Server', () => {
|
|
||||||
const serv = require('../server/server');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,87 +0,0 @@
|
|||||||
describe('token-auth', () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
jest.resetModules();
|
|
||||||
|
|
||||||
//mock out jsonwebtoken
|
|
||||||
jest.doMock('jsonwebtoken', () => ({
|
|
||||||
verify: (token, secretAccess, callback) => {
|
|
||||||
if (token != 'invalid') {
|
|
||||||
expect(token).toBe('testtoken');
|
|
||||||
return callback(null, { username: 'username' });
|
|
||||||
} else {
|
|
||||||
expect(token).toBe('invalid');
|
|
||||||
return callback('Misc. error');
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('Required Functionality', () => {
|
|
||||||
const tokenAuth = require('../../server/utilities/token-auth');
|
|
||||||
|
|
||||||
const req = {
|
|
||||||
headers: {
|
|
||||||
authorization: 'Bearer testtoken'
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const res = {
|
|
||||||
status: code => {
|
|
||||||
expect(code).toBe(null);
|
|
||||||
return msg => { throw msg; };
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
tokenAuth(req, res, () => null);
|
|
||||||
|
|
||||||
expect(req.user.username).toBe('username');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('Missing Token', () => {
|
|
||||||
const tokenAuth = require('../../server/utilities/token-auth');
|
|
||||||
|
|
||||||
const req = {
|
|
||||||
headers: {
|
|
||||||
//
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const res = {
|
|
||||||
status: code => {
|
|
||||||
expect(code).toBe(401);
|
|
||||||
return {
|
|
||||||
send: msg => {
|
|
||||||
expect(msg).toBe('No token found');
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
tokenAuth(req, res, () => null);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('Invalid Token', () => {
|
|
||||||
const tokenAuth = require('../../server/utilities/token-auth');
|
|
||||||
|
|
||||||
const req = {
|
|
||||||
headers: {
|
|
||||||
authorization: 'Bearer invalid'
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const res = {
|
|
||||||
status: code => {
|
|
||||||
expect(code).toBe(403);
|
|
||||||
return {
|
|
||||||
send: msg => {
|
|
||||||
expect(msg).toBe('Misc. error');
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
tokenAuth(req, res, () => null);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -47,7 +47,7 @@ export default Component;
|
|||||||
The most useful features provided by TokenProvider are:
|
The most useful features provided by TokenProvider are:
|
||||||
|
|
||||||
* `tokenFetch()`, which wraps the `fetch()` API to ensure that your access token is valid
|
* `tokenFetch()`, which wraps the `fetch()` API to ensure that your access token is valid
|
||||||
* `tokenCallback()`, which passes the authTokens as a parameter to any function passed into it
|
* `tokenCallback()`, which passes the accessToken as a parameter to any function passed into it
|
||||||
* `getPayload()`, which returns the payload of the accessToken (including as "email", "username", "admin", and "mod")
|
* `getPayload()`, which returns the payload of the accessToken (including as "email", "username", "admin", and "mod")
|
||||||
* `accessToken`, this will be falsy if the user is not logged in
|
* `accessToken`, this will be falsy if the user is not logged in
|
||||||
|
|
||||||
|
|||||||
@@ -8,19 +8,22 @@ export const TokenContext = createContext();
|
|||||||
const TokenProvider = props => {
|
const TokenProvider = props => {
|
||||||
//state to be used
|
//state to be used
|
||||||
const [accessToken, setAccessToken] = useState('');
|
const [accessToken, setAccessToken] = useState('');
|
||||||
const [refreshToken, setRefreshToken] = useState('');
|
|
||||||
|
|
||||||
//make the access and refresh tokens persist between reloads
|
//force a logout under certain conditions
|
||||||
|
const forceLogout = () => {
|
||||||
|
localStorage.removeItem("accessToken");
|
||||||
|
setAccessToken("");
|
||||||
|
};
|
||||||
|
|
||||||
|
//make the access token persist between reloads
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setAccessToken(localStorage.getItem("accessToken") || '');
|
setAccessToken(localStorage.getItem("accessToken") || '');
|
||||||
setRefreshToken(localStorage.getItem("refreshToken") || '');
|
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
//update the stored copies
|
//update the stored copies
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
localStorage.setItem("accessToken", accessToken);
|
localStorage.setItem("accessToken", accessToken);
|
||||||
localStorage.setItem("refreshToken", refreshToken);
|
}, [accessToken]);
|
||||||
}, [accessToken, refreshToken]);
|
|
||||||
|
|
||||||
//wrap the default fetch function
|
//wrap the default fetch function
|
||||||
const tokenFetch = async (url, options) => {
|
const tokenFetch = async (url, options) => {
|
||||||
@@ -36,28 +39,23 @@ const TokenProvider = props => {
|
|||||||
return fetch(url, {
|
return fetch(url, {
|
||||||
method: 'DELETE',
|
method: 'DELETE',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'Authorization': `Bearer ${bearer}`
|
'Authorization': `Bearer ${bearer}`
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
credentials: 'include'
|
||||||
token: refreshToken
|
|
||||||
})
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
//ping the auth server for a new token
|
//ping the auth server for a new access token
|
||||||
const response = await fetch(`${process.env.AUTH_URI}/auth/token`, {
|
const response = await fetch(`${process.env.AUTH_URI}/auth/token`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
credentials: 'include'
|
||||||
'Content-Type': 'application/json'
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
token: refreshToken
|
|
||||||
})
|
|
||||||
});
|
});
|
||||||
|
|
||||||
//any errors, throw them
|
//any errors, throw them
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
|
if (response.status == 403) {
|
||||||
|
forceLogout();
|
||||||
|
}
|
||||||
throw `${response.status}: ${await response.text()}`;
|
throw `${response.status}: ${await response.text()}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -65,7 +63,6 @@ const TokenProvider = props => {
|
|||||||
const newAuth = await response.json();
|
const newAuth = await response.json();
|
||||||
|
|
||||||
setAccessToken(newAuth.accessToken);
|
setAccessToken(newAuth.accessToken);
|
||||||
setRefreshToken(newAuth.refreshToken);
|
|
||||||
bearer = newAuth.accessToken;
|
bearer = newAuth.accessToken;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -75,7 +72,8 @@ const TokenProvider = props => {
|
|||||||
headers: {
|
headers: {
|
||||||
...(options || { headers: {} }).headers,
|
...(options || { headers: {} }).headers,
|
||||||
'Authorization': `Bearer ${bearer}`
|
'Authorization': `Bearer ${bearer}`
|
||||||
}
|
},
|
||||||
|
credentials: 'include'
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -88,16 +86,14 @@ const TokenProvider = props => {
|
|||||||
//ping the auth server for a new token
|
//ping the auth server for a new token
|
||||||
const response = await fetch(`${process.env.AUTH_URI}/auth/token`, {
|
const response = await fetch(`${process.env.AUTH_URI}/auth/token`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
credentials: 'include'
|
||||||
'Content-Type': 'application/json'
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
token: refreshToken
|
|
||||||
})
|
|
||||||
});
|
});
|
||||||
|
|
||||||
//any errors, throw them
|
//any errors, throw them
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
|
if (response.status == 403) {
|
||||||
|
forceLogout();
|
||||||
|
}
|
||||||
throw `${response.status}: ${await response.text()}`;
|
throw `${response.status}: ${await response.text()}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -105,7 +101,6 @@ const TokenProvider = props => {
|
|||||||
const newAuth = await response.json();
|
const newAuth = await response.json();
|
||||||
|
|
||||||
setAccessToken(newAuth.accessToken);
|
setAccessToken(newAuth.accessToken);
|
||||||
setRefreshToken(newAuth.refreshToken);
|
|
||||||
|
|
||||||
//finally
|
//finally
|
||||||
return cb(newAuth.accessToken);
|
return cb(newAuth.accessToken);
|
||||||
@@ -115,7 +110,7 @@ const TokenProvider = props => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<TokenContext.Provider value={{ accessToken, refreshToken, setAccessToken, setRefreshToken, tokenFetch, tokenCallback, getPayload: () => decode(accessToken) }}>
|
<TokenContext.Provider value={{ accessToken, setAccessToken, tokenFetch, tokenCallback, getPayload: () => decode(accessToken) }}>
|
||||||
{props.children}
|
{props.children}
|
||||||
</TokenContext.Provider>
|
</TokenContext.Provider>
|
||||||
)
|
)
|
||||||
|
|||||||
Reference in New Issue
Block a user