All files / app/routes/auth/login login-controller.ts

100% Statements 23/23
100% Branches 4/4
100% Functions 4/4
100% Lines 23/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 471x 1x 1x 1x 1x 1x     1x 1x               1x 8x   7x 2x 2x   5x   5x     5x 3x 3x 3x     2x 2x         5x       1x  
import {User, UserDto} from '@models';
import ModelToDtoConverter from '@util/model-to-dto-converter';
import bcrypt from 'bcrypt';
import debug from 'debug';
import {InvalidLoginError} from '@errors';
import {convertUserToJwtPayload} from '@app/routes/auth/jwt/jwt-util';
import {RequestHandler} from 'express';
 
const log = debug('group-car:login:controller:log');
const error = debug('group-car:login:controller:error');
 
/**
 * Login controller
 * @param username - Username of the login request
 * @param password - Password of the login request
 * @returns Whether or not the login was successful
 */
const loginController: RequestHandler = (req, res, next) => {
  User.findByUsername(req.body.username)
      .then((user: User | null) => {
        if (user === null) {
          error('User "%s" doesn\'t exist', req.body.username);
          throw new InvalidLoginError();
        } else {
          log('Found user "%s"', req.body.username);
          // Compare password
          return bcrypt.compare(req.body.password, user.password)
              .then((result) => {
                // Check if sent password is equal to stored user password
                if (result) {
                  log('Login successful for IP %s', req.ip);
                  res.setJwtToken(convertUserToJwtPayload(user), user.username);
                  res.send(ModelToDtoConverter
                      .convertSequelizeModel(user, UserDto));
                } else {
                  error('Invalid password for IP %s', req.ip);
                  throw new InvalidLoginError();
                }
              });
        }
      }).catch((err) => {
        next(err);
      });
};
 
export default loginController;