All files / middlewares oauthValidations.js

100% Statements 34/34
100% Branches 26/26
100% Functions 5/5
100% Lines 32/32

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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81        1x 7x 7x 1x     6x 6x 6x     6x                           6x 5x 1x 4x 3x   1x     5x 1x     5x   5x       1x 4x 1x     4x 4x 1x     3x 3x 3x       1x 4x 3x     4x 3x                    
import { models } from '../../config/database';
import { oauthServer } from '../routes/auth/config';
import UserInformation from '../source/users/information';
 
const authenticate = async (req, res) => {
  await oauthServer.authenticate()(req, res, (err) => {
    if (err) {
      throw err;
    }
 
    req.oauth = res.locals.oauth.token;
    req.userId = req.oauth.user.id;
    req.clientId = req.oauth.client.id;
  });
 
  const user = await UserInformation.getUserPermissions(
    { id: req.userId },
    {
      include: [
        {
          required: false,
          model: models.Branch,
          as: 'branchUser',
          attributes: ['serialControlDeposit'],
        },
      ],
    }
  );
 
  if (user) {
    if (user.userBranches && user.userBranches !== '') {
      req.userBranches = user.userBranches.split(',');
    } else if (user.mainBranch && user.mainBranch !== '') {
      req.userBranches = [user.mainBranch];
    } else {
      req.userBranches = [];
    }
 
    if (user.type === 1) {
      req.userBranches.push('*');
    }
 
    if (user.mainBranch) req.userMainBranch = user.mainBranch;
 
    if (user.branchUser) req.userBranchUser = user.branchUser;
  }
};
 
const apiAuthenticate = async (req, res) => {
  if (req.body.token) {
    req.headers.authorization = `Bearer ${req.body.token}`;
  }
 
  await oauthServer.authenticate()(req, res, (err) => {
    if (err) {
      throw err;
    }
 
    req.oauth = res.locals.oauth.token;
    req.userId = req.oauth.user.id;
    req.clientId = req.oauth.client.id;
  });
};
 
const apiInitialLogin = async (req) => {
  if (!req.body.grant_type) {
    req.body.grant_type = 'password';
  }
 
  if (!req.headers.Authorization) {
    req.headers.Authorization =
      'Basic YmVlc3RvY2thcGk6YmVlc3RvY2thcGlkZXNlbnZvbHZpZG9wb3JzenNvbHVjb2Vz';
  }
};
 
export default {
  authenticate,
  apiInitialLogin,
  apiAuthenticate,
};