Advertisement
Guest User

Untitled

a guest
Jun 14th, 2016
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. 'use strict';
  2.  
  3. import profileModel from './profile.model.es6';
  4. import jsonwebtoken from 'jsonwebtoken';
  5. import {UnauthorizedError, ForbiddenError} from '@agiliumlabs/express-microservice/lib/errorHandler/errorHandler';
  6.  
  7. profileService.$inject = ['authorization'];
  8.  
  9. /**
  10. * Implements profile REST API
  11. * @param {Authorization} authorization authorization service
  12. * @return {ProfileService} profile API service
  13. */
  14. export default function profileService(authorization) {
  15. return new ProfileService(authorization);
  16. }
  17.  
  18. /**
  19. * Profile service
  20. */
  21. export class ProfileService {
  22.  
  23. /**
  24. * Profile service constructor
  25. * @param {Authorization} authorization authorization service
  26. */
  27. constructor(authorization) {
  28. this._authorization = authorization;
  29. }
  30.  
  31. /**
  32. * Returns endpoint which returns current user
  33. * @returns {Function(req, res, next)} Returns endpoint which returns current user
  34. */
  35. get getCurrentUser() {
  36. return this._getCurrentUser.bind(this);
  37. }
  38.  
  39. /**
  40. * Returns endpoint which authenticates user by email and password
  41. * @returns {Function(req, res, next)} endpoint which authenticates user by email and password
  42. */
  43. get signIn() {
  44. return this._signin.bind(this);
  45. }
  46.  
  47. _getCurrentUser(req, res, next) {
  48. let user = this._authorization.getUser();
  49. user.password = undefined;
  50. user.salt = undefined;
  51. user.resetPasswordKey = undefined;
  52. res.json(user);
  53. }
  54.  
  55. _signin(req, res, next) {
  56. profileModel.Profile.findByEmail(req.params.email)
  57. .then((user) => {
  58. if (!user || (profileModel.Profile.generateHashedPassword(req.body.password, user.salt) !== user.password)) {
  59. throw new UnauthorizedError('Wrong credentials');
  60. }
  61. if (user.locked === true) {
  62. throw new ForbiddenError('User is locked');
  63. } else {
  64. let responseWithToken = {
  65. token: this._authorization.createToken({_id: user._id})
  66. };
  67. res.json(responseWithToken);
  68. }
  69. })
  70. .catch(next);
  71. }
  72.  
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement