Skip to content

Commit

Permalink
[Temp] #43, create and validate json web token
Browse files Browse the repository at this point in the history
  • Loading branch information
Type-Style committed Mar 4, 2024
1 parent 6ebece8 commit 5087ae2
Show file tree
Hide file tree
Showing 5 changed files with 163 additions and 11 deletions.
109 changes: 105 additions & 4 deletions package-lock.json

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

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"@types/express": "^4.17.21",
"@types/hpp": "^0.2.5",
"@types/jest": "^29.5.11",
"@types/jsonwebtoken": "^9.0.6",
"@types/node": "^20.10.6",
"@types/toobusy-js": "^0.5.4",
"@typescript-eslint/eslint-plugin": "^6.18.1",
Expand All @@ -50,6 +51,7 @@
"express-validator": "^7.0.1",
"helmet": "^7.1.0",
"hpp": "^0.2.3",
"jsonwebtoken": "^9.0.2",
"module-alias": "^2.2.3",
"toobusy-js": "^0.5.1"
},
Expand Down
54 changes: 51 additions & 3 deletions src/controller/read.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@ import express, { Request, Response, NextFunction } from 'express';
import * as file from '@src/scripts/file';
import { create as createError } from '@src/middleware/error';
import { validationResult, query } from 'express-validator';
import jwt from 'jsonwebtoken';
import logger from '@src/scripts/logger';
import { create } from 'domain';

const router = express.Router();

router.get('/',
isLoggedIn,
[query('index').isInt().withMessage("not an integer")
.isLength({ max: 3 }).withMessage("not in range")
.toInt()],
Expand All @@ -32,8 +35,6 @@ router.get('/',
});



// TODO will be converted to middleware
// TODO write test for checking the limit on request body
router.get("/login/", async function login(req: Request, res: Response) {
logger.log("login was called");
Expand All @@ -46,7 +47,54 @@ router.post("/login/", async function postLogin(req: Request, res: Response) {
logger.log("post login was called");
logger.log(req.body);
res.locals.text = "post recieved";
res.render("login-form");

// TODO login authentication here
const validLogin = true;
if (!validLogin) {
return res.redirect("/read/login");
} else {
createToken(req, res);
res.render("login-form"); // TODO Send Token only
}
});

function isLoggedIn(req: Request, res: Response) {
const result = validateToken(req, res);
if (!result) {
return res.redirect("/read/login");
}
}


function validateToken(req: Request, res: Response) {
const key = process.env.KEYB;
const header = req.header('Authorization');
const [type, token] = header ? header.split(' ') : "";
let payload: string | jwt.JwtPayload = "";
if (type === 'Bearer' && typeof token !== 'undefined' && key) {
try {
payload = jwt.verify(token, key);
res.status(200).send({ code: 0, message: `all good` });
} catch (err) {
res.status(401).send({ code: 123, message: 'Invalid or expired token.' });
}
console.log("payload: " + payload + " _ " + !!payload);
return !!payload;
} else {
return false;
}
}


function createToken(req: Request, res: Response) {
const key = process.env.KEYB;
if (!key) { throw new Error('KEYA is not defined in the environment variables'); }
const id = Math.random().toString(36).substring(2, 8);
const payload = {
_id: id
};
const token = jwt.sign(payload, key, { expiresIn: 60 * 1 });
res.locals.token = token;
}

export default router;
7 changes: 3 additions & 4 deletions src/models/entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,13 +118,12 @@ export function checkTime(value: string) {


function checkKey(value: string) {
if (process.env.NODE_ENV != "production" && value == "test") {
return true; // dev testing convenience
}

if (!value) {
throw new Error('Key required');
}
if (process.env.NODE_ENV != "production" && value == "test") {
return true; // dev testing convenience
}

value = decodeURIComponent(value);

Expand Down
2 changes: 2 additions & 0 deletions views/login-form.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
<input name="password" type="password" class="login__input" placeholder="Password">
<button type="submit">Submit</button>
<textarea name="text"></textarea>
<input type="hidden" name="token" value="<%= locals.token %>">
<p>Token: <%= locals.token %></p>
</form>
</body>

Expand Down

0 comments on commit 5087ae2

Please sign in to comment.