Skip to content
This repository has been archived by the owner on Nov 2, 2024. It is now read-only.

Commit

Permalink
Chore/token and error updates (#45)
Browse files Browse the repository at this point in the history
* ♻️ chore/token-and-error-updates

* 🔖 3.2.1
  • Loading branch information
Jasper Mayone authored May 27, 2022
1 parent 32e3453 commit 04d82f3
Show file tree
Hide file tree
Showing 13 changed files with 117 additions and 33 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
.env
node_modules
dist.wireit
.wireit/*
.wireit/*
**/.DS_Store
.yarn/*
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "api",
"version": "3.1.0",
"version": "3.2.0",
"author": "Jasper Mayone <jasper@jaspermayone.com>",
"license": "EPL-2.0",
"keywords": [],
Expand All @@ -16,6 +16,7 @@
"cors": "^2.8.5",
"dotenv": "^16.0.0",
"express": "^4.18.1",
"express-correlation-id": "^2.0.1",
"express-ping": "^1.4.0",
"express-rate-limit": "^6.4.0",
"express-validator": "^6.14.0",
Expand Down
7 changes: 6 additions & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import compression from "compression";
import cookieParser from "cookie-parser";
import cors from "cors";
import express from "express";
import correlator from "express-correlation-id";
import health from "express-ping";
import rateLimit from "express-rate-limit";
import helmet from "helmet";
Expand Down Expand Up @@ -33,6 +34,7 @@ app.use(helmet());
app.use(limiter);
app.use(health.ping());
app.use(cors());
app.use(correlator());

app.get("/", (req, res) => {
res.redirect("/docs");
Expand All @@ -50,10 +52,13 @@ app.use("/docs", swaggerUi.serve, swaggerUi.setup(apiSpecs));
// catch all errors
app.use((err, req, res, next) => {
const errorID = uuidv4();
errorLogger(err, errorID);
errorLogger(err, errorID, req);
res.status(500).json({
message:
"Please contact a developer in our discord support server, and provide the information below.",
error: err.message,
errorID,
requestID: req.correlationId(),
});
});

Expand Down
57 changes: 53 additions & 4 deletions src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
/* eslint-disable jsdoc/require-jsdoc */

import axios from "axios";
import jsonwebtoken from "jsonwebtoken";
import "dotenv/config";

const jwt = jsonwebtoken;

const env = process.env.NODE_ENV;
const errorUrl = process.env.ERROR_WEBHOOK_URL;
const avatarUrl = process.env.AVATAR_URL;
Expand All @@ -14,10 +15,22 @@ const username =
: "Heptagram API Development Logger";

// create function to handle error
const errorLogger = (error, errorID) => {
const errorLogger = async (error, errorID, req) => {
// remove error: from error message
const errorMessage = error.message.replace("Error: ", "");

const bearerHeader = req.headers["authorization"];
if (typeof bearerHeader === "undefined") {
return;
}
const bearer = bearerHeader.split(" ");
const bearerToken = bearer[1];

const decoded = await jwt.verify(
bearerToken,
process.env.ACCESS_TOKEN_SECRET
);

axios.request({
url: errorUrl,
method: "POST",
Expand All @@ -31,12 +44,48 @@ const errorLogger = (error, errorID) => {
embeds: [
{
title: "An Error has occurred...",
description: ` \`Error:\` \`${errorMessage}\` \n\n \`ErrorID:\` **\`${errorID}\`**`,
color: 15158332,
fields: [
{
name: "Error:",
value: `\`${errorMessage}\``,
inline: true,
},
{
name: "Error ID:",
value: `\`${errorID}\``,
inline: true,
},
{
name: "Requested Endpoint:",
value: `\`${req.originalUrl}\``,
inline: true,
},
{
name: "Request Id:",
value: `\`${req.correlationId()}\``,
inline: true,
},
{
name: "Request Method:",
value: `\`${req.method}\``,
inline: true,
},
{
name: "User ID:",
value: `\`${decoded.userId}\``,
inline: true,
},
],
timestamp: new Date(),
footer: {
text: "Heptagram API Error Logger",
},
},
],
},
});
console.log(error);
};

export default errorLogger;
6 changes: 4 additions & 2 deletions src/middleware/isAdmin.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import { jsonwebtoken as jwt } from "jsonwebtoken";
import jsonwebtoken from "jsonwebtoken";

import { getToken } from "../utils/getToken";

const jwt = jsonwebtoken;

/**
*
* @param req
* @param res
* @param next
*/
export async function isAdmin(req, res, next) {
const token = getToken(req, res);
const token = getToken(req);

const decodedToken = await jwt.verify(token, process.env.ACCESS_TOKEN_SECRET);

Expand Down
7 changes: 5 additions & 2 deletions src/middleware/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
import { jsonwebtoken as jwt } from "jsonwebtoken";
import jsonwebtoken from "jsonwebtoken";
import { v4 as uuidv4 } from "uuid";

import { getToken } from "../utils/getToken";

const jwt = jsonwebtoken;

/**
*
* @param req
* @param res
* @param next
*/
export function authToken(req, res, next) {
const token = getToken(req, res);
const token = getToken(req);

jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
if (err) {
Expand Down
2 changes: 1 addition & 1 deletion src/routes/api/scam/emails.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ router.post(
return res.status(400).send("Email already flagged!");
}

const user = await getUserInfo(req, res);
const user = await getUserInfo(req);

const email = new ScamEmail({
_id: uuidv4(),
Expand Down
2 changes: 1 addition & 1 deletion src/routes/api/scam/links.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ router.post(
return res.status(400).send("Link already flagged!");
}

const user = await getUserInfo(req, res);
const user = await getUserInfo(req);

const link = new ScamLink({
_id: uuidv4(),
Expand Down
2 changes: 1 addition & 1 deletion src/routes/api/scam/phoneNumbers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ router.post(
return res.status(400).send("Phone Number already flagged!");
}

const user = await getUserInfo(req, res);
const user = await getUserInfo(req);

const phoneNumber = new ScamPhoneNumber({
_id: uuidv4(),
Expand Down
11 changes: 7 additions & 4 deletions src/routes/auth/login.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { bcryptjs as bcrypt } from "bcryptjs";
import bcryptjs from "bcryptjs";
import express from "express";
import { body, validationResult } from "express-validator";
import { jsonwebtoken as jwt } from "jsonwebtoken";
import jsonwebtoken from "jsonwebtoken";

import User from "../../models/User";

const jwt = jsonwebtoken;
const bcrypt = bcryptjs;

const router = express.Router();

/**
Expand Down Expand Up @@ -57,7 +60,7 @@ router.post(
return res.status(400).send("Can not find user");
}

if (await bcrypt.compare(req.body.password, user.password)) {
if (bcrypt.compare(req.body.password, user.password)) {
const accessToken = await jwt.sign(
{ userId: user._id, accountType: user.accountType },
process.env.ACCESS_TOKEN_SECRET
Expand All @@ -67,7 +70,7 @@ router.post(
accessToken: accessToken,
});
} else {
res.send("Not allowed");
res.status(400).send("Not allowed");
}
}
);
Expand Down
18 changes: 8 additions & 10 deletions src/utils/getToken.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
export function getToken(req, res) {
const authHeader = req.headers["authorization"];
const headerToken = authHeader && authHeader.split(" ")[1];

if (headerToken) {
const token = headerToken;
const type = "header";
return token && type;
} else {
return res.status(401).send("No token provided");
export function getToken(req) {
// get berer token from header
const bearerHeader = req.headers["authorization"];
if (typeof bearerHeader !== "undefined") {
const bearer = bearerHeader.split(" ");
const bearerToken = bearer[1];
return bearerToken;
}
return null; // if not found
}
10 changes: 6 additions & 4 deletions src/utils/getUserInfo.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import { jsonwebtoken as jwt } from "jsonwebtoken";
import jsonwebtoken from "jsonwebtoken";

import { getToken } from "./getToken";

const jwt = jsonwebtoken;

/**
*
* @param req
* @param res
*/
export async function getUserInfo(req, res) {
const token = await getToken(req, res);
export async function getUserInfo(req) {
const token = await getToken(req);

const decoded = await jwt.verify(token, process.env.JWT_SECRET);
const decoded = await jwt.verify(token, process.env.ACCESS_TOKEN_SECRET);

const { userId, email, role } = decoded as {
userId: string;
Expand Down
21 changes: 20 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1112,6 +1112,7 @@ __metadata:
eslint-plugin-jsdoc: ^39.2.9
eslint-plugin-prettier: ^4.0.0
express: ^4.18.1
express-correlation-id: ^2.0.1
express-ping: ^1.4.0
express-rate-limit: ^6.4.0
express-validator: ^6.14.0
Expand Down Expand Up @@ -1908,6 +1909,15 @@ __metadata:
languageName: node
linkType: hard

"correlation-id@npm:^4.0.0":
version: 4.0.0
resolution: "correlation-id@npm:4.0.0"
dependencies:
uuid: ^8.3.1
checksum: b0fedee33c7aa7c7f0b99dd4b2454e861afb8f0323a7dece249eaeaf2854dc266456a2fe6b71db8f3f1315a9ddf7e8327aa18501841f68a4bae17189e8579b17
languageName: node
linkType: hard

"cors@npm:^2.8.5":
version: 2.8.5
resolution: "cors@npm:2.8.5"
Expand Down Expand Up @@ -2763,6 +2773,15 @@ __metadata:
languageName: node
linkType: hard

"express-correlation-id@npm:^2.0.1":
version: 2.0.1
resolution: "express-correlation-id@npm:2.0.1"
dependencies:
correlation-id: ^4.0.0
checksum: ff41e8d7e5572fd2478db4d16d0b9ced1da8124183ccc95cca8f5c4216e032c1f34858cdee0ee7f593bb67ad8a2cf595432f23469db10425420e97b5d2754e28
languageName: node
linkType: hard

"express-ping@npm:^1.4.0":
version: 1.4.0
resolution: "express-ping@npm:1.4.0"
Expand Down Expand Up @@ -6627,7 +6646,7 @@ __metadata:
languageName: node
linkType: hard

"uuid@npm:^8.3.2":
"uuid@npm:^8.3.1, uuid@npm:^8.3.2":
version: 8.3.2
resolution: "uuid@npm:8.3.2"
bin:
Expand Down

0 comments on commit 04d82f3

Please sign in to comment.