All files / controllers oauth.js

40% Statements 34/85
33.33% Branches 28/84
50% Functions 4/8
39.28% Lines 33/84

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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325                                7x                                                     7x   7x 1x 6x 2x   2x           2x 2x       2x 1x 1x               1x 4x 1x 3x 1x     2x 2x   2x   2x           2x 2x 1x 1x                       1x         1x       1x         1x       2x       2x     2x                                                                                                                                                                                                               1x                                                                                                                                                                                      
import moment from 'moment-timezone';
import APIError from '../helpers/error';
import { t } from '../helpers/i18n';
 
import { passwordSHA256 } from '../helpers/validators/password';
import OauthCreate from '../source/oauth/create';
import OauthInformation from '../source/oauth/information';
import OauthUpdate from '../source/oauth/update';
import OauthClientInformation from '../source/oauth_client/information';
import OauthRefreshCreate from '../source/oauth_refresh/create';
import OauthRefreshInformation from '../source/oauth_refresh/information';
import OauthRefreshUpdate from '../source/oauth_refresh/update';
import UserInformation from '../source/users/information';
import UserUpdate from '../source/users/update';
 
async function getUserFromCrentials(login, pwd) {
  const user = await UserInformation.getUser(
    {
      login: login.trimEnd(),
    },
    {
      attributes: [
        'id',
        'login',
        'name',
        'type',
        'email',
        'department',
        'status',
        'passValid',
        'printer',
        'userFunction',
        'workShift',
        'accessProfile',
        'userBranches',
        'attempt',
        'lastDateLogged',
        'mainBranch',
        'password',
      ],
    }
  );
 
  const hashPassword = passwordSHA256(pwd);
 
  if (!user) {
    throw new APIError('', t('BEE1077' /* Usuário ou senha incorretos ! */));
  } else if (hashPassword !== user.password) {
    const attempt = (user.attempt || 0) + 1;
    const quantityAttempt =
      (user.branchUser &&
        (user.branchUser.company
          ? user.branchUser.company.quantityAttempt
          : 0)) ||
      0;
 
    Eif (quantityAttempt) {
      await UserUpdate.updateAttempt(user.id, {
        attempt,
        lastDateLogged: moment().format(),
      });
      if (attempt > quantityAttempt) {
        await UserUpdate.updateStatus(user.id, false, user.id);
        throw new APIError(
          '',
          t(
            'BEE3263' /* Limite máximo de tentativas excedido: acesso bloqueado. */
          )
        );
      }
    }
    throw new APIError('', t('BEE1077' /* Usuário ou senha incorretos ! */));
  } else if (!user.status) {
    throw new APIError('', t('BEE456' /* Usuário Desativado */));
  } else if (user.type !== 4 && moment().isAfter(user.passValid, 'day')) {
    throw new APIError('EXPIRED_PASSWORD');
  }
 
  const lastDateLogged = moment(user.lastDateLogged);
  const currentDate = moment();
 
  const daysWithoutUsing = currentDate.diff(lastDateLogged, 'days');
  const daysWithouUsingSystem =
    (user.branchUser &&
      (user.branchUser.company
        ? user.branchUser.company.daysWithoutUsing
        : 0)) ||
    0;
 
  Eif (daysWithouUsingSystem) {
    if (daysWithoutUsing > daysWithouUsingSystem) {
      await UserUpdate.updateStatus(user.id, false, user.id);
      throw new APIError(
        '',
        t(
          'BEE3264',
          {
            0: daysWithoutUsing,
          } /* Conta bloqueada após %{0} dias sem acesso. Contate o seu superior imediato. */
        )
      );
    }
  }
 
  await UserUpdate.updateAttempt(user.id, {
    attempt: 0,
    lastDateLogged: moment().format(),
  });
 
  return user;
}
 
async function getClientFromCrentials(clientId, clientSecret) {
  const client = await OauthClientInformation.getClient({
    clientId: Buffer.from(clientId).toString('base64'),
    clientSecret: Buffer.from(clientSecret).toString('base64'),
  });
 
  return client;
}
 
async function getUserIDFromBearerToken(token, callback) {
  const userToken = await OauthInformation.getUserToken({
    token,
  });
 
  Iif (callback) {
    callback(userToken || null);
  }
  return userToken || null;
}
 
async function getUserIDFromBearerRefreshToken(token, callback) {
  const userToken = await OauthRefreshInformation.getUserToken({
    token,
  });
 
  if (callback) {
    callback(userToken || null);
  }
 
  return userToken || null;
}
 
async function saveToken(token, client, user) {
  const userToken = await OauthInformation.getUserToken({
    userId: user.id,
    clientId: client.clientId,
  });
  const userRefreshToken = await OauthRefreshInformation.getUserToken({
    userId: user.id,
    clientId: client.clientId,
  });
  const proms = [];
 
  let isMultiSession = false;
 
  switch (user.type) {
    case 1:
      isMultiSession = !['MOBILE'].includes(client.clientName);
      break;
    case 2:
      isMultiSession = !['MOBILE'].includes(client.clientName);
      break;
    case 3:
      isMultiSession = false;
      break;
    case 4:
      isMultiSession = !['MOBILE'].includes(client.clientName);
      break;
    default:
      isMultiSession = false;
      break;
  }
 
  // Tipo 4 - Integração / Login somente API
  if (user && user.type === 4 && !['API'].includes(client.clientName)) {
    if (user.passValid && moment().isAfter(user.passValid, 'day')) {
      throw new APIError('EXPIRED_PASSWORD');
    } else {
      throw new APIError(
        '',
        t('BEE3754' /* Acesso não permitido para contas de serviço. */)
      );
    }
  }
 
  // ACCESS TOKEN - UPDATE REALIZADO SOMENTE PARA OS CLIENTES  QUE "NAO" ESTAO NO ARRAY ABAIXO ( SINGLE ACCESS )
  if (userToken && !isMultiSession) {
    proms.push(
      OauthUpdate.updateUserToken(userToken.id, {
        token: token.accessToken,
        clientId: client.clientId,
        expires: token.accessTokenExpiresAt,
      })
    );
  } else {
    proms.push(
      OauthCreate.createUserToken({
        token: token.accessToken,
        clientId: client.clientId,
        userId: user.id,
        expires: token.accessTokenExpiresAt,
      })
    );
  }
 
  // REFRESH TOKEN - UPDATE REALIZADO SOMENTE PARA OS CLIENTES  QUE "NAO" ESTAO NO ARRAY ABAIXO ( SINGLE ACCESS )
  if (userRefreshToken && !isMultiSession) {
    proms.push(
      OauthRefreshUpdate.updateUserToken(userRefreshToken.id, {
        token: token.refreshToken,
        clientId: client.clientId,
        expires: token.refreshTokenExpiresAt,
      })
    );
  } else {
    proms.push(
      OauthRefreshCreate.createUserToken({
        token: token.refreshToken,
        clientId: client.clientId,
        userId: user.id,
        expires: token.refreshTokenExpiresAt,
      })
    );
  }
 
  await Promise.all(proms);
 
  return { ...token, client, user };
}
 
async function revokeToken(token) {
  Eif (!token) return false;
 
  const proms = [];
 
  if (token.accessToken) {
    proms.push(
      OauthUpdate.updateUserTokenForQuery(
        { token: token.accessToken },
        { expires: new Date() }
      )
    );
  }
 
  if (token.refreshToken) {
    proms.push(
      OauthRefreshUpdate.updateUserTokenForQuery(
        { token: token.refreshToken },
        { expires: new Date() }
      )
    );
  }
 
  return Promise.all(proms);
}
 
async function revoke(req, res) {
  const { accessToken } = req.oauth;
  const refreshToken = req.body.refresh_token;
 
  await revokeToken({ accessToken, refreshToken });
 
  const response = {
    success: true,
  };
 
  res.json(response);
}
 
async function getUser(req, res) {
  const { userId } = req;
 
  if (userId) {
    const user = await UserInformation.getUser({
      id: userId,
    });
 
    const data = {
      id: user.id,
      login: user.login,
      name: user.name,
      type: user.type,
      email: user.email,
      department: user.department,
      departmentName: user.departmentUser ? user.departmentUser.name : '',
      status: user.status,
      passValid: user.passValid,
      printer: user.printer,
      userFunction: user.userFunction,
      userFunctionName: user.functionUser ? user.functionUser.name : '',
      workShift: user.workShift,
      workShiftName: user.workShiftUser ? user.workShiftUser.name : '',
      mainBranch: user.mainBranch,
      mainBranchName: user.branchUser ? user.branchUser.name : '',
      mainBranchData: user.branchUser ? user.branchUser : null,
      accessProfile: user.accessProfileUser ? user.accessProfileUser.name : '',
    };
 
    const response = {
      success: true,
      data,
    };
    res.json(response);
  } else {
    const response = {
      success: false,
    };
 
    res.json(response);
  }
}
 
export default {
  getUserFromCrentials,
  getClientFromCrentials,
  saveToken,
  getUserIDFromBearerToken,
  getUserIDFromBearerRefreshToken,
  revokeToken,
  revoke,
  getUser,
};