Skip to content

Instantly share code, notes, and snippets.

@cklanac
Last active January 17, 2019 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cklanac/068ba76001bf75e4b8a78dec98050103 to your computer and use it in GitHub Desktop.
Save cklanac/068ba76001bf75e4b8a78dec98050103 to your computer and use it in GitHub Desktop.
Custom Auth middleware (alternative to Passport's local and jwt strategies)
const createError = require("http-errors");
const debug = require("debug")("app:auth:jwt");
const jwtHelper = require("../helpers/jwt");
function jwtAuth(req, res, next) {
const auth = req.header("Authorization");
if (!auth) {
debug("'Authorization' header not found");
const err = createError(401, "Unauthorized");
return next(err);
}
const scheme = auth.split(" ")[0]; // "Bearer"
const token = auth.split(" ")[1]; // "token"
debug("scheme %o", scheme);
debug("token %o", token);
if (scheme !== "Bearer" || !token) {
debug("no token found");
const err = createError(401, "No 'Bearer' token found");
return next(err);
}
jwtHelper.verifyToken(token)
.then(payload => {
req.user = payload.user;
debug("authorized %o", req.user);
next();
})
.catch((e) => {
const err = createError(401, "Unauthorized");
return next(err);
});
}
module.exports = jwtAuth;
const bcrypt = require("bcryptjs");
const createError = require("http-errors");
const debug = require("debug")("app:auth:local");
const User = require("../models/user.model");
function localAuth(req, res, next) {
const { username, password } = req.body;
let user;
if (!username || !password) {
debug("missing provided");
const err = createError(400, "Bad Request");
next(err);
}
debug("authenticate %o", username);
return User.findOne({ username })
.then(_user => {
user = _user;
if (!user) {
debug("username '%o' not found ", username);
const err = createError(401, "Invalid credentials");
err.location = "username";
next(err);
}
return bcrypt.compare(password, user.password);
})
.then(isValid => {
if (!isValid) {
debug("password for '%0' not valid", username);
const err = createError(401, "Invalid credentials");
err.location = "password";
next(err);
}
req.user = user;
debug("authenticated %o", req.user);
next();
})
.catch((err) => {
next(err);
});
}
module.exports = localAuth;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment