Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict';
- import profileModel from './profile.model.es6';
- import jsonwebtoken from 'jsonwebtoken';
- import {UnauthorizedError, ForbiddenError} from '@agiliumlabs/express-microservice/lib/errorHandler/errorHandler';
- profileService.$inject = ['authorization'];
- /**
- * Implements profile REST API
- * @param {Authorization} authorization authorization service
- * @return {ProfileService} profile API service
- */
- export default function profileService(authorization) {
- return new ProfileService(authorization);
- }
- /**
- * Profile service
- */
- export class ProfileService {
- /**
- * Profile service constructor
- * @param {Authorization} authorization authorization service
- */
- constructor(authorization) {
- this._authorization = authorization;
- }
- /**
- * Returns endpoint which returns current user
- * @returns {Function(req, res, next)} Returns endpoint which returns current user
- */
- get getCurrentUser() {
- return this._getCurrentUser.bind(this);
- }
- /**
- * Returns endpoint which authenticates user by email and password
- * @returns {Function(req, res, next)} endpoint which authenticates user by email and password
- */
- get signIn() {
- return this._signin.bind(this);
- }
- _getCurrentUser(req, res, next) {
- let user = this._authorization.getUser();
- user.password = undefined;
- user.salt = undefined;
- user.resetPasswordKey = undefined;
- res.json(user);
- }
- _signin(req, res, next) {
- profileModel.Profile.findByEmail(req.params.email)
- .then((user) => {
- if (!user || (profileModel.Profile.generateHashedPassword(req.body.password, user.salt) !== user.password)) {
- throw new UnauthorizedError('Wrong credentials');
- }
- if (user.locked === true) {
- throw new ForbiddenError('User is locked');
- } else {
- let responseWithToken = {
- token: this._authorization.createToken({_id: user._id})
- };
- res.json(responseWithToken);
- }
- })
- .catch(next);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement