Added token, user, userRepository and userSecurity in user folder. This handles creating new users, loging in and creating a user specific token then returning it when logging in.

This commit is contained in:
2017-09-27 16:15:28 +02:00
parent 72654fd465
commit 6ec6c7f9cb
4 changed files with 181 additions and 0 deletions

View File

@@ -0,0 +1,38 @@
const User = require('src/user/user');
const jwt = require('jsonwebtoken');
class Token {
constructor(user) {
this.user = user;
}
/**
* Generate a new token.
* @param {String} secret a cipher of the token
* @returns {String}
*/
toString(secret) {
return jwt.sign({ username: this.user.username }, secret);
}
/**
* Decode a token.
* @param {Token} jwtToken an encrypted token
* @param {String} secret a cipher of the token
* @returns {Token}
*/
static fromString(jwtToken, secret) {
let username = null;
try {
username = jwt.verify(jwtToken, secret).username;
} catch (error) {
throw new Error('The token is invalid.');
}
const user = new User(username);
return new Token(user);
}
}
module.exports = Token;