Skip to content

Commit

Permalink
feat: add jwt login mechanism
Browse files Browse the repository at this point in the history
- Use jwt instead of session when configuring disable session
- Return token in response when configuring disable session
- Store token after login
  • Loading branch information
Chinlinlee committed Jun 8, 2022
1 parent 5cc8696 commit 848c613
Show file tree
Hide file tree
Showing 4 changed files with 109 additions and 43 deletions.
64 changes: 62 additions & 2 deletions plugins/login/middleware/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,26 @@
const path = require("path");
const _ = require("lodash");
const { pluginsConfig } = require("../../config");
const mongoose = require("mongoose");
const jwt = require("jsonwebtoken");

async function isLogin(req, res, next) {

if (!pluginsConfig.login.session) {
try {
await checkToken(req);
} catch (e) {
console.error(e);
return res.status(401).render(
path.join(
__dirname + "../../../../public/html/errors/",
"401.html"
)
);
}
}


function isLogin(req, res, next) {
let username = _.get(req, "user.user");
console.log(req.isAuthenticated() + " " + username + " Is LoggedIn");
let isNormalLogin = req.isAuthenticated();
Expand All @@ -15,7 +34,47 @@ function isLogin(req, res, next) {
);
}

function isAdmin(req, res, next) {
/**
*
* @param {import("express").Request} req
*/
function checkToken(req) {
return new Promise(async (resolve, reject) => {
let tokenInHeader = _.get(req.headers, "authorization", "");
let token = tokenInHeader.replace("Bearer ", "");
if (!token) return reject(new Error("Invalid token"));
let userDoc = await mongoose.model("users").findOne({
token: token
});
if (userDoc) {
jwt.verify(
token,
pluginsConfig.login.jwt.secretOrKey,
(err, decoded) => {
if (err) return reject(err);
return resolve(decoded);
}
);
}
return reject(new Error("Token not found"));
});

}

async function isAdmin(req, res, next) {

if (!pluginsConfig.login.session) {
try {
let tokenDecoded = await checkToken(req);
if (tokenDecoded.sub === "admin") {
return next();
}
return res.render("html/errors/403.html");
} catch (e) {
return res.render("html/errors/401.html");
}
}

let userType = _.get(req, "user.userType", "");
if (userType.toLowerCase() !== "admin") {
return res.status(403).render("html/errors/403.html");
Expand All @@ -25,3 +84,4 @@ function isAdmin(req, res, next) {

module.exports.isLogin = isLogin;
module.exports.isAdmin = isAdmin;
module.exports.checkToken = checkToken;
38 changes: 24 additions & 14 deletions plugins/login/route/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,23 +44,26 @@ router.post("/login", function (req, res, next) {
passport.authenticate(
"local-login",
{
session: true
session: loginPlugin.session
},
async function (err, user, info) {
if (!user) {
return res.status(401).json({
message: info.message,
code: 2
code: 2,
token: undefined
});
}
req.login(user, async (err) => {
if (err) return next(err);

await generateToken(req.user.user);
return res.json({
let token = await generateToken(req.user);
let resMessage = {
message: "authenticate successful",
code: 1
});
};
if (!pluginsConfig.login.session) _.set(resMessage, "token", token);
return res.json(resMessage);
});
}
)(req, res, next);
Expand All @@ -71,22 +74,28 @@ router.post("/login/token", function(req, res, next) {
session: false
}, function(err, user) {
if (err) return next(err);
if (user) return res.json({
message: "authenticate successful",
code: 1
});
return res.status(401).json({
if (!user) return res.status(401).json({
message: "Invalid token",
code: 2
});

return res.json({
message: "authenticate successful",
code: 1
});
})(req, res, next);
});

async function generateToken(username) {
async function generateToken(user) {
try {
let token = jwt.sign({ sub: username }, loginPlugin.jwt.secretOrKey, {
expiresIn: loginPlugin.jwt.expiresIn
});
let username = user.user;
let token = jwt.sign(
{ sub: username, userType: user.userType },
loginPlugin.jwt.secretOrKey,
{
expiresIn: loginPlugin.jwt.expiresIn
}
);
await mongoose.model("users").findOneAndUpdate(
{
account: username
Expand All @@ -97,6 +106,7 @@ async function generateToken(username) {
}
}
);
return token;
} catch (e) {
throw e;
}
Expand Down
27 changes: 17 additions & 10 deletions public/scripts/config.template.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,27 @@
var envConfig = {
QIDO: {
hostName: '127.0.0.1',
port: '9090',
api: 'dicom-web',
hostName: "127.0.0.1",
port: "9090",
api: "dicom-web",
http: "http"
},
WADO: {
hostName: '127.0.0.1',
port: '9090',
api: 'dicom-web',
hostName: "127.0.0.1",
port: "9090",
api: "dicom-web",
http: "http"
},
FHIR: {
hostName: '127.0.0.1',
port: '9090',
api: 'api/fhir',
hostName: "127.0.0.1",
port: "9090",
api: "api/fhir",
http: "http"
},
/**
* *If true, get token from localStorage and add headers for every requests
*/
jwt: false,
backend: {
baseUrl: "http://localhost:8081"
}
}
};
23 changes: 6 additions & 17 deletions public/scripts/login/login.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,13 @@
let loginApp = angular.module("loginApp", []);
loginApp.controller("loginCtrl", function ($scope, $q,loginService) {
$scope.login = function () {
loginService.getToken($scope).then(function (res) {
let data = res.data;
if (data.token) {
localStorage.setItem('MicalaToken' , data.token);
loginService.login($scope).then(function (res) {
location.reload();
});
} else {
let pError = document.getElementById('pError');
pError.style.display = 'block';
pError.innerText = data.message;
}
});
}

$scope.localLogin = function () {
loginService.localLogin($scope).then(function(res) {
let data = res.data;
if (res.status === 200) {
storeToken(data);
location.reload();
} else {
console.log(res);
let pError = document.getElementById("pError");
pError.style.display = "block";
pError.innerText = data.message;
Expand Down Expand Up @@ -73,4 +58,8 @@ loginApp.service('loginService', function ($http) {
});



function storeToken(data) {
if (data["token"]) {
localStorage.setItem("raccoon_token", data["token"]);
}
}

0 comments on commit 848c613

Please sign in to comment.