Finished up with remember me middleware.
This commit is contained in:
parent
e00e5a608b
commit
61ec3ffc52
4 changed files with 107 additions and 11 deletions
|
|
@ -81,6 +81,12 @@ rememberMeToken.pre('save', async function (next){
|
|||
next();
|
||||
});
|
||||
|
||||
//Methods
|
||||
rememberMeToken.methods.checkToken = async function(token){
|
||||
//Compare ingested token to saved hash
|
||||
return await hashUtil.compareRememberMeToken(token, this.token);
|
||||
}
|
||||
|
||||
//statics
|
||||
rememberMeToken.statics.genToken = async function(user, pass){
|
||||
//Authenticate user and pull document
|
||||
|
|
@ -104,4 +110,45 @@ rememberMeToken.statics.genToken = async function(user, pass){
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticates an id and token pair
|
||||
* @param {String} id - id of token auth against
|
||||
* @param {String} token - token string to auth against
|
||||
* @param {String} failLine - Line to paste into custom error upon login failure
|
||||
* @returns {Mongoose.Document} - User DB Document upon success
|
||||
*/
|
||||
rememberMeToken.statics.authenticate = async function(id, token, failLine = "Bad Username or Password."){
|
||||
//check for missing pass
|
||||
if(!id || !token){
|
||||
throw loggerUtils.exceptionSmith("Missing id/token.", "validation");
|
||||
}
|
||||
|
||||
//get the token if it exists
|
||||
const tokenDB = await this.findOne({id});
|
||||
|
||||
//if not scream and shout
|
||||
if(!tokenDB){
|
||||
badLogin();
|
||||
}
|
||||
|
||||
//Check our password is correct
|
||||
if(await tokenDB.checkToken(token)){
|
||||
//Populate the user field
|
||||
await tokenDB.populate('user');
|
||||
|
||||
//Return the user doc
|
||||
return tokenDB.user;
|
||||
}else{
|
||||
//Nuke the token for security
|
||||
await tokenDB.deleteOne();
|
||||
//if not scream and shout
|
||||
badLogin();
|
||||
}
|
||||
|
||||
//standardize bad login response so it's unknown which is bad for security reasons.
|
||||
function badLogin(){
|
||||
throw loggerUtils.exceptionSmith(failLine, "unauthorized");
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = mongoose.model("rememberMe", rememberMeToken);
|
||||
Loading…
Add table
Add a link
Reference in a new issue