Compare commits

..

29 Commits

Author SHA1 Message Date
Kayne Ruse 76fdbc0d13 BUG: tracking down a post validation hook bug 2022-07-24 19:01:47 +01:00
Kayne Ruse 39ddd8158a Updated dependencies 2022-07-23 11:48:36 +01:00
Kayne Ruse 50f0996fb7 Updated configure-script.js 2022-06-15 23:38:56 +01:00
Kayne Ruse 89b2b6ed7b Patched a security hole in the validation hooks 2022-06-15 23:33:06 +01:00
Kayne Ruse 8a5957d6b4 Integration test in place 2022-06-11 01:06:48 +01:00
Kayne Ruse 423a4652c1 Chipping away at writing the tests 2022-06-11 00:32:51 +01:00
Kayne Ruse 7f9274eb3f Bumped patch version 2022-06-10 17:25:07 +01:00
Kayne Ruse 4043507e01 Updated dependencies 2022-06-10 17:09:26 +01:00
Kayne Ruse 12fb02484a Fixed usage of fetch API 2022-06-10 17:01:20 +01:00
Kayne Ruse 49179de73b Updated dependencies 2022-05-30 06:49:23 +01:00
Kayne Ruse 89ea67456d Wrote a couple simple tests 2022-03-02 15:35:14 +00:00
Kayne Ruse 46152032bb Added FUNDING.yml 2022-02-13 07:49:06 +11:00
Kayne Ruse 2d92b31272 Dependancy patch 2022-01-27 09:35:06 +11:00
Kayne Ruse f93564931a Updated libraries 2022-01-20 13:45:40 +11:00
Kayne Ruse 2542f3f00f Bumped version number 2022-01-15 02:29:46 +00:00
Kayne Ruse a112e17f59 Patched a potential crash 2022-01-15 02:28:55 +00:00
Kayne Ruse 7af87824e3 Added the TokenProvider as a useful tool 2021-12-23 14:24:13 +00:00
Kayne Ruse 8b91ff8dd3 Cleaned up tools and tests 2021-12-23 13:33:58 +00:00
Kayne Ruse 0aa1e67be9 Updated README.md 2021-12-21 19:37:57 +00:00
Kayne Ruse 353be4662b Bumped version number 2021-12-19 16:07:44 +00:00
Kayne Ruse cc655cd988 Merge remote-tracking branch 'refs/remotes/origin/main' 2021-12-19 16:06:30 +00:00
Kayne Ruse ec3b14e32b Removed excess logging 2021-12-19 16:06:23 +00:00
Kayne Ruse b188c46efd Merge pull request #9 from MatthewEvans91/remove-address-line
omit physical address line from validation email where no physical address provided
2021-12-20 03:04:03 +11:00
Matthew Evans ece3b0253f omit physical address line from validation email where no physical address provided 2021-12-18 18:47:44 -07:00
Kayne Ruse 062bc43f5a BUGFIX: sending account index via post validation hook 2021-12-11 11:54:13 +00:00
Kayne Ruse cc6b7bd7b4 Fixed an import/require problem 2021-12-11 10:11:56 +00:00
Kayne Ruse 9bdf3925a3 Implemented a post-validation hook 2021-12-11 09:59:57 +00:00
Kayne Ruse a299bab794 Preparing for Egg Trainer merge 2021-11-18 14:59:30 +00:00
Kayne Ruse 8460d03181 Updated package-lock.json 2021-11-17 06:14:08 +00:00
26 changed files with 7923 additions and 1568 deletions
+3
View File
@@ -30,3 +30,6 @@ SECRET_ACCESS=access
# Make sure this value is kept secret
SECRET_REFRESH=refresh
# Post-signup hook JSON array (MUST include http:// or https://)
HOOK_POST_VALIDATION_ARRAY=
+5
View File
@@ -0,0 +1,5 @@
# These are supported funding model platforms
patreon: krgamestudios
ko_fi: krgamestudios
custom: ["https://www.paypal.com/donate/?hosted_button_id=73Q82T2ZHV8AA"]
+23
View File
@@ -0,0 +1,23 @@
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
+7 -1
View File
@@ -2,6 +2,8 @@
An API centric auth server. Uses Sequelize and mariaDB by default.
This server is available via docker hub at krgamestudios/auth-server.
# Setup
There are multiple ways to run this app - it can run on it's own via `npm start` (for production) or `npm run dev` (for development). it can also run inside docker using `docker-compose up --build` - run `node configure-script.js` to generate docker-compose.yml and startup.sql.
@@ -26,6 +28,10 @@ Content-Type: application/json
//DOCS: Used for validating the email address specified above
GET /auth/validation?username=example&token=12345678
//DOCS: If the environment variable HOOK_POST_VALIDATION_ARRAY is set to a JSON array of valid URLs, then the server will send a GET message to each URL with the newly created account's index
//DOCS: The GET requests will have a JWT authorization header
HOOK_POST_VALIDATION_ARRAY=["http://example.com", "http://example2.com"]
GET {HOOK_POST_VALIDATION_ARRAY[i]}?accountIndex={index}
###
@@ -119,7 +125,7 @@ POST /auth/recover
Content-Type: application/json
{
"email": "kayneruse@gmail.com"
"email": "example@example.com"
}
+3 -1
View File
@@ -30,11 +30,12 @@ const question = (prompt, def = null) => {
//project configuration
const appName = await question('App Name', 'auth');
const appWebAddress = await question('Web Addr', `${appName}.example.com`);
const postValidationHookArray = await question('Post Validation Hook Array', '');
const resetAddress = await question('Reset Addr', `example.com/reset`);
const appPort = await question('App Port', '3200');
const appDBUser = await question('DB User', appName);
const appDBPass = await question('DB Pass', uuid());
const appDBPass = await question('DB Pass', 'charizard');
const dbRootPass = await question('DB Root Pass');
const appMailSMTP = await question('Mail SMTP', 'smtp.example.com');
@@ -70,6 +71,7 @@ services:
environment:
- WEB_PROTOCOL=https
- WEB_ADDRESS=${appWebAddress}
- HOOK_POST_VALIDATION_ARRAY=${postValidationHookArray}
- WEB_RESET_ADDRESS=${resetAddress}
- WEB_PORT=${appPort}
- DB_HOSTNAME=database
+7196 -1468
View File
File diff suppressed because it is too large Load Diff
+5 -2
View File
@@ -1,12 +1,13 @@
{
"name": "auth-server",
"version": "1.4.4",
"version": "1.4.14",
"description": "An API centric auth server. Uses Sequelize and mariaDB by default.",
"main": "server/server.js",
"scripts": {
"start": "node server/server.js",
"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": {
"type": "git",
@@ -26,10 +27,12 @@
"jsonwebtoken": "^8.5.1",
"mariadb": "^2.5.4",
"node-cron": "^2.0.3",
"node-fetch": "^2.6.6",
"nodemailer": "^6.6.3",
"sequelize": "^6.6.5"
},
"devDependencies": {
"jest": "^27.5.1",
"nodemon": "^2.0.12"
}
}
+6 -4
View File
@@ -13,7 +13,7 @@ const route = async (req, res) => {
//validate the given details
const validateErr = await validateDetails(req.body);
if (validateErr) {
return res.status(401).end(validateErr);
return res.status(401).send(validateErr);
}
//get the existing account
@@ -29,6 +29,7 @@ const route = async (req, res) => {
//compare passwords
const compare = utils.promisify(bcrypt.compare);
const match = await compare(req.body.password, account.hash);
if (!match) {
@@ -47,11 +48,12 @@ const route = async (req, res) => {
return res.status(403).send('this account has been banned');
}
//generate the JWT
const token = tokenGenerate(account.index, account.email, account.username, account.type, account.admin, account.mod);
//generate the JWTs
const tokens = tokenGenerate(account.index, account.email, account.username, account.type, account.admin, account.mod);
//finally
res.status(200).json(token);
res.status(200).json(tokens);
return null;
};
const validateDetails = async (body) => {
+1 -1
View File
@@ -5,7 +5,7 @@ const route = async (req, res) => {
//verify the recovery record exists
const record = await recovery.findOne({
where: {
token: req.query.token
token: req.query.token || ''
}
});
+6 -9
View File
@@ -52,9 +52,6 @@ const validateDetails = async (body) => {
return 'Invalid username';
}
//check for existing (banned)
//TODO: re-add banned email checks
//check for existing email
const emailRecord = await accounts.findOne({
where: {
@@ -107,12 +104,12 @@ const registerPendingSignup = async (body, hash, token) => {
const sendValidationEmail = async (email, username, token) => {
const addr = `${process.env.WEB_PROTOCOL}://${process.env.WEB_ADDRESS}/auth/validation?username=${username}&token=${token}`;
const msg = `Hello ${username}!
Please visit the following link to validate your account: ${addr}
You can contact us directly at our physical mailing address here: ${process.env.MAIL_PHYSICAL}
`;
const msg =
`Hello ${username}!\n\n` +
`Please visit the following link to validate your account: ${addr}\n` +
(process.env.MAIL_PHYSICAL
? `\nYou can contact us directly at our physical mailing address here: ${process.env.MAIL_PHYSICAL}\n`
: ``);
let transporter, info;
+43 -2
View File
@@ -1,4 +1,6 @@
const { pendingSignups, accounts } = require('../database/models');
const fetch = require('node-fetch');
const jwt = require('jsonwebtoken');
//auth/validation
const route = async (req, res) => {
@@ -19,7 +21,7 @@ const route = async (req, res) => {
}
//move data to the accounts table
accounts.create({
const account = await accounts.create({
email: info.email,
username: info.username,
hash: info.hash,
@@ -29,12 +31,51 @@ const route = async (req, res) => {
//delete the pending signup
pendingSignups.destroy({
where: {
username: req.query.username || ''
username: info.username || ''
}
});
//finally
res.status(200).send('Validation succeeded!');
//post-validation hook
if (process.env.HOOK_POST_VALIDATION_ARRAY) {
try {
hooks = JSON.parse(process.env.HOOK_POST_VALIDATION_ARRAY);
if (!Array.isArray(hooks)) {
throw 'isArray() check failed';
}
//authenticate the hooks
const bearer = jwt.sign({ type: 'hook authentication' }, process.env.SECRET_ACCESS, { expiresIn: '5m', issuer: 'auth' });
//promise for each given hook
const promises = hooks.map(async hook => {
if (typeof hook != 'string') {
throw 'hook is not a string';
}
const probe = await fetch(`${hook}?accountIndex=${account.index}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${bearer}`
}
});
if (!probe.ok) {
throw `Could not probe the post validation hook: ${hook} with accountIndex = ${account.index}`;
}
//discard the result
});
await Promise.all(promises);
}
catch(e) {
console.error('HOOK_POST_VALIDATION_ARRAY is not a valid array of strings in JSON format: ' + e);
}
}
};
module.exports = route;
+1 -1
View File
@@ -3,7 +3,7 @@ const jwt = require('jsonwebtoken');
//middleware to authenticate the JWT token
module.exports = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader?.split (' ')[1]; //'Bearer token'
const token = authHeader?.split(' ')[1]; //'Bearer token'
if (!token) {
return res.status(401).send('No token found');
+3 -2
View File
@@ -12,8 +12,9 @@ module.exports = (index, email, username, type, admin, mod) => {
mod,
};
const accessToken = jwt.sign(content, process.env.SECRET_ACCESS, { expiresIn: '10m' });
const refreshToken = jwt.sign(content, process.env.SECRET_REFRESH, { expiresIn: '30d' });
//these are strings
const accessToken = jwt.sign(content, process.env.SECRET_ACCESS, { expiresIn: '10m', issuer: 'auth' });
const refreshToken = jwt.sign(content, process.env.SECRET_REFRESH, { expiresIn: '30d', issuer: 'auth' });
tokens.create({ token: refreshToken, email: email });
+117
View File
@@ -0,0 +1,117 @@
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);
});
});
+98
View File
@@ -0,0 +1,98 @@
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);
});
});
-68
View File
@@ -1,68 +0,0 @@
#Signup
POST https://dev-auth.eggtrainer.com/auth/signup HTTP/1.1
Content-Type: application/json
{
"email": "kayneruse@gmail.com",
"username": "Ratstail91",
"password": "helloworld"
}
###
#Login
POST https://dev-auth.eggtrainer.com/auth/login HTTP/1.1
Content-Type: application/json
{
"email": "kayneruse@gmail.com",
"password": "helloworld"
}
###
#Query data
GET https://dev-auth.eggtrainer.com/auth/account HTTP/1.1
Authorization: Bearer
###
#Logout
DELETE https://dev-auth.eggtrainer.com/auth/logout HTTP/1.1
Authorization: Bearer
{
"token": ""
}
###
#Refresh
POST https://dev-auth.eggtrainer.com/auth/token HTTP/1.1
Content-Type: application/json
{
"token": ""
}
###
#Update account data
PATCH https://dev-auth.eggtrainer.com/auth/update HTTP/1.1
Content-Type: application/json
Authorization: Bearer
{
"contact": "true"
}
###
#Delete account
DELETE https://dev-auth.eggtrainer.com/auth/deletion HTTP/1.1
Authorization: Bearer
Content-Type: application/json
{
"password": "helloworld"
}
+65
View File
@@ -0,0 +1,65 @@
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');
});
});
+87
View File
@@ -0,0 +1,87 @@
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);
});
});
@@ -1,4 +1,4 @@
#use this while debugging
CREATE DATABASE IF NOT EXISTS auth;
CREATE USER IF NOT EXISTS 'auth'@'%' IDENTIFIED BY 'venusaur';
CREATE USER IF NOT EXISTS 'auth'@'%' IDENTIFIED BY 'charizard';
GRANT ALL PRIVILEGES ON auth.* TO 'auth'@'%';
+68
View File
@@ -0,0 +1,68 @@
#Signup
POST https://dev-auth.krgamestudios.com/auth/signup HTTP/1.1
Content-Type: application/json
{
"email": "example@example.com",
"username": "Example",
"password": "helloworld"
}
###
#Login
POST https://dev-auth.krgamestudios.com/auth/login HTTP/1.1
Content-Type: application/json
{
"email": "example@example.com",
"password": "helloworld"
}
###
#Query data
GET https://dev-auth.krgamestudios.com/auth/account HTTP/1.1
Authorization: Bearer
###
#Logout
DELETE https://dev-auth.krgamestudios.com/auth/logout HTTP/1.1
Authorization: Bearer
{
"token": ""
}
###
#Refresh
POST https://dev-auth.krgamestudios.com/auth/token HTTP/1.1
Content-Type: application/json
{
"token": ""
}
###
#Update account data
PATCH https://dev-auth.krgamestudios.com/auth/update HTTP/1.1
Content-Type: application/json
Authorization: Bearer
{
"contact": "true"
}
###
#Delete account
DELETE https://dev-auth.krgamestudios.com/auth/deletion HTTP/1.1
Authorization: Bearer
Content-Type: application/json
{
"password": "helloworld"
}
@@ -3,8 +3,8 @@ POST http://127.0.0.1:3200/auth/signup HTTP/1.1
Content-Type: application/json
{
"email": "kayneruse@gmail.com",
"username": "Ratstail91",
"email": "example@example.com",
"username": "Example",
"password": "helloworld"
}
@@ -15,8 +15,8 @@ POST http://127.0.0.1:3200/auth/login HTTP/1.1
Content-Type: application/json
{
"email": "admin@example.com",
"password": "password"
"email": "example@example.com",
"password": "helloworld"
}
###
+53
View File
@@ -0,0 +1,53 @@
# TokenProvider
The MERN-template utilizes React's `useContext()` hook to share the auth-server's access token, effectively globally. Here is a quick rundown of how it works.
# Enabling TokenProvider
To enable the TokenProvider component, wrap your App component with it, like so:
```jsx
import React from 'react';
import ReactDOM from 'react-dom';
import App from './pages/app';
import TokenProvider from './pages/utilities/token-provider';
ReactDOM.render(
<TokenProvider>
<App />
</TokenProvider>,
document.querySelector('#root')
);
```
# Accessing The Access Token
To access the access token from your app, you simply use the `useContext` hook, like so:
```jsx
import React, { useContext } from 'react';
import { TokenContext } from '../utilities/token-provider';
const Component = props => {
//context
const authTokens = useContext(TokenContext);
//use the access token
console.log(authTokens.accessToken);
return <div />;
};
export default Component;
```
# Most Useful Features Provided
The most useful features provided by TokenProvider are:
* `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
* `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
+124
View File
@@ -0,0 +1,124 @@
import React, { useState, useEffect, createContext } from 'react';
import decode from 'jwt-decode';
export const TokenContext = createContext();
//DOCS: tokenFetch() and tokenCallback() are actually closures here
const TokenProvider = props => {
//state to be used
const [accessToken, setAccessToken] = useState('');
const [refreshToken, setRefreshToken] = useState('');
//make the access and refresh tokens persist between reloads
useEffect(() => {
setAccessToken(localStorage.getItem("accessToken") || '');
setRefreshToken(localStorage.getItem("refreshToken") || '');
}, []);
//update the stored copies
useEffect(() => {
localStorage.setItem("accessToken", accessToken);
localStorage.setItem("refreshToken", refreshToken);
}, [accessToken, refreshToken]);
//wrap the default fetch function
const tokenFetch = async (url, options) => {
//use this?
let bearer = accessToken;
//if expired (10 minutes, normally)
const expired = new Date(decode(accessToken).exp * 1000) < Date.now();
if (expired) {
//BUGFIX: if logging out, just skip over the refresh token
if (url === `${process.env.AUTH_URI}/auth/logout`) {
return fetch(url, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${bearer}`
},
body: JSON.stringify({
token: refreshToken
})
});
}
//ping the auth server for a new token
const response = await fetch(`${process.env.AUTH_URI}/auth/token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
token: refreshToken
})
});
//any errors, throw them
if (!response.ok) {
throw `${response.status}: ${await response.text()}`;
}
//save the new auth stuff (setting bearer as well)
const newAuth = await response.json();
setAccessToken(newAuth.accessToken);
setRefreshToken(newAuth.refreshToken);
bearer = newAuth.accessToken;
}
//finally, delegate to fetch
return fetch(url, {
...(options || {}),
headers: {
...(options || { headers: {} }).headers,
'Authorization': `Bearer ${bearer}`
}
});
};
//access the refreshed token via callback
const tokenCallback = async (cb) => {
//if expired (10 minutes, normally)
const expired = new Date(decode(accessToken).exp * 1000) < Date.now();
if (expired) {
//ping the auth server for a new token
const response = await fetch(`${process.env.AUTH_URI}/auth/token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
token: refreshToken
})
});
//any errors, throw them
if (!response.ok) {
throw `${response.status}: ${await response.text()}`;
}
//save the new auth stuff (setting bearer as well)
const newAuth = await response.json();
setAccessToken(newAuth.accessToken);
setRefreshToken(newAuth.refreshToken);
//finally
return cb(newAuth.accessToken);
} else {
return cb(accessToken);
}
};
return (
<TokenContext.Provider value={{ accessToken, refreshToken, setAccessToken, setRefreshToken, tokenFetch, tokenCallback, getPayload: () => decode(accessToken) }}>
{props.children}
</TokenContext.Provider>
)
};
export default TokenProvider;