Skip to content

Commit

Permalink
feat: implement JWT authorization and login method
Browse files Browse the repository at this point in the history
  • Loading branch information
varijkapil13 committed Jan 17, 2019
1 parent 752a917 commit 296c4e0
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 5 deletions.
25 changes: 25 additions & 0 deletions server/auth/authorization.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import * as jwt from 'jsonwebtoken';
import crypto from 'crypto';
const jwtSecret = 'aJWTSecret13121992for13121992jwtTokenInTheRequest13121992';
class AuthorizationController {
static login(req, res) {
try {
const refreshId = req.body.userId + jwtSecret;
const salt = crypto.randomBytes(16).toString('base64');
const hash = crypto
.createHmac('sha512', salt)
.update(refreshId)
.digest('base64');
req.body.refreshKey = salt;
const accessToken = jwt.sign(req.body, jwtSecret);
const refreshToken = Buffer.from(hash).toString('base64');
const {userId, name, email, roles, provider} = req.body;
const responseData = {accessToken, refreshToken, userId, name, email, roles, provider};
res.status(201).send(responseData);
} catch (err) {
res.status(500).send({errors: err});
}
}
}

export default AuthorizationController;
9 changes: 5 additions & 4 deletions server/controllers/user.controller.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import model from '../models';
import crypto from 'crypto';
import user from '../models/user';

const {User, Avatar} = model;

Expand Down Expand Up @@ -86,7 +85,7 @@ class UserController {
.catch(error => res.status(400).send(error));
}

static login(req, res) {
static login(req, res, next) {
const {email, password} = req.body;

User.findAll({
Expand All @@ -108,13 +107,15 @@ class UserController {
// passwords are same, user authenticated
Avatar.findByPk(user[0].avatarId)
.then(avatar => {
return res.status(200).send({
req.body = {
userId: user[0].id,
email: user[0].email,
roles: user[0].roles,
provider: 'email',
name: avatar.first_name + ' ' + avatar.last_name
});
};

return next();
})
.catch(error => {
res.status(400).send(error);
Expand Down
3 changes: 2 additions & 1 deletion server/routes/user.route.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import express from 'express';
import UserController from '../controllers/user.controller';
import AuthorizationController from '../auth/authorization.controller';

const routes = express.Router();

// sign ip with avatar id
routes.post('/signup/:avatarId', UserController.signUpWithAvatar);
routes.post('/signup', UserController.signUp);
routes.post('/login', UserController.login);
routes.post('/login', [UserController.login, AuthorizationController.login]);

export default routes;

0 comments on commit 296c4e0

Please sign in to comment.