LoginController.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use Illuminate\Support\Facades\Validator;
  5. use Illuminate\Support\Facades\DB;
  6. use Illuminate\Support\Facades\Hash;
  7. use Illuminate\Support\Carbon;
  8. use Firebase\JWT\JWT;
  9. use Firebase\JWT\Key;
  10. use Exception;
  11. class LoginController extends Controller{
  12. private $responseController;
  13. private $encryptionController;
  14. private $functionsController;
  15. private $secretKey = "ydl27x22cNsNY0z6o3Fr6XZoUvsX0QMZx6MaiwN+KCnM6APS4Xbb7GDfudOYD5uD/r8TzQElh4d4HIal5Os0XA==";
  16. private $publicKey = "zOgD0uF22+xg37nTmA+bg/6/E80BJYeHeByGpeTrNFw=";
  17. public function __construct(){
  18. $this->responseController = new ResponseController();
  19. $this->encryptionController = new EncryptionController();
  20. $this->functionsController = new FunctionsController;
  21. }
  22. public function login(Request $request){
  23. DB::enableQueryLog();
  24. $validator = Validator::make($request->all(), [
  25. 'email' => 'required|string|email',
  26. 'password' => 'required|string',
  27. 'linea' => 'required|integer|max: 2',
  28. 'lugarConexion' => "required|json"
  29. ]);
  30. if($validator->fails()){
  31. return $this->responseController->makeResponse(
  32. true,
  33. "Se encontraron uno o más errores.",
  34. $this->responseController->makeErrors(
  35. $validator->errors()->messages()
  36. ),
  37. 401
  38. );
  39. }
  40. $login = $request->all();
  41. $usr = DB::table('S002V01TUSUA')->where('USUA_COEL', '=', $login['email'])->first();
  42. if(is_null($usr)){
  43. return $this->responseController->makeResponse(true, "El correo electrónico no está registrado.", [], 404);
  44. }else if($usr->USUA_ESTA != 'Activo'){
  45. $statusStr = strtolower($usr->USUA_ESTA);
  46. return $this->responseController->makeResponse(true, "El usuario se encuentra $statusStr, por favor contacte al administrador para solucionarlo.", [], 401);
  47. }
  48. $now = Carbon::now('America/Mexico_city');
  49. $nowStr = $now->toDateTimeString();
  50. $contra = $login['password'];
  51. $contra = $this->encryptionController->decrypt($contra);
  52. if(!$contra){
  53. return $this->responseController->makeResponse(true, 'La contraseña no fue encriptada correctamente.', [], 400);
  54. }
  55. $usrContra = $usr->USUA_CONT;
  56. if(!Hash::check($contra, $usrContra)){
  57. $attempts = $usr->USUA_ININ + 1;
  58. $status = $attempts >= 10 ? 'Inactivo' : 'Activo';
  59. DB::table('S002V01TUSUA')->where('USUA_IDUS', '=', $usr->USUA_IDUS)->update([
  60. "USUA_ININ" => $attempts,
  61. "USUA_ESTA" => $status
  62. ]);
  63. return $this->responseController->makeResponse(true, "La contraseña es incorrecta, intento $attempts de 10.", [], 401);
  64. }
  65. DB::table('S002V01TUSUA')->where('USUA_IDUS', '=', $usr->USUA_IDUS)->update([
  66. "USUA_ININ" => 0,
  67. "USUA_ESTA" => 'Activo'
  68. ]);
  69. $iat = $now->timestamp;
  70. $cad = $now->addDay()->timestamp;
  71. $ipv = $request->ip();
  72. try{
  73. $ulco = DB::table('S002V01TBIAC')->insertGetId([
  74. 'BIAC_NULI' => $login['linea'],
  75. 'BIAC_IDUS' => $usr->USUA_IDUS,
  76. 'BIAC_DIIP' => $ipv,
  77. 'BIAC_LUCO' => $login['lugarConexion'],
  78. 'BIAC_FECO' => $nowStr
  79. ]);
  80. DB::table('S002V01TUSUA')->where('USUA_COEL', '=', $login['email'])->update(['USUA_ULCO' => $ulco]);
  81. }catch(PDOException $e){
  82. return $this->responseController->makeResponse(true, "Hubo un error al intentar actualizar la última conexión.", [], 500);
  83. }
  84. //Antes de crear el token revisamos los permisos de su perfil
  85. $profile = DB::table('S002V01TPERF')->where('PERF_IDPE', '=', $usr->USUA_PERF)->get()->first();
  86. $permissions = $this->encryptionController->encrypt($profile->PERF_PERM);
  87. $payload = [
  88. "iss" => $login['email'],
  89. "aud" => "dominio.syp.mx",
  90. "iat" => $iat,
  91. "cad" => $cad
  92. ];
  93. $token = JWT::encode($payload, $this->secretKey, 'EdDSA');
  94. //Antes de realizar el return obtenemos todas las acciones realizadas en la base de datos
  95. $actions = DB::getQueryLog();
  96. $this->functionsController->registerActivity($actions, $usr->USUA_IDUS, $nowStr, $login['linea']);
  97. return $this->responseController->makeResponse(false, "EXITO.", [
  98. "IDUSUARIO" => $this->encryptionController->encrypt($usr->USUA_IDUS),
  99. "NOMBREUSUARIO" => $this->encryptionController->encrypt($usr->USUA_NOMB),
  100. "CORREO" => $this->encryptionController->encrypt($usr->USUA_COEL),
  101. "PERMISOS" => $permissions,
  102. "TOKEN" => $token,
  103. ]);
  104. }
  105. public function verifyToken(Request $request){
  106. DB::enableQueryLog();
  107. $validator = Validator::make($request->all(), [
  108. 'token' => 'required|string',
  109. ]);
  110. if($validator->fails()){
  111. return $this->responseController->makeResponse(
  112. true,
  113. "Se encontraron uno o más errores.",
  114. $this->responseController->makeErrors(
  115. $validator->errors()->messages()
  116. ),
  117. 401
  118. );
  119. }
  120. $tokenInfo = $request->all();
  121. try{
  122. $decoded = JWT::decode($tokenInfo['token'], new Key($this->publicKey, 'EdDSA'));
  123. }catch(Exception $e){
  124. return $this->responseController->makeResponse(false, "Token inválido", [
  125. "validToken" => false
  126. ]);
  127. }
  128. $usr = DB::table('S002V01TUSUA')->where('USUA_COEL', '=', $decoded->iss)->first();
  129. if(is_null($usr)){
  130. return $this->responseController->makeResponse(false, "El usuario que generó el token no está registrado en la base.", [
  131. "validToken" => false
  132. ]);
  133. }
  134. if($decoded->aud != "dominio.syp.mx"){
  135. return $this->responseController->makeResponse(false, "El token enviado fue generado en un sitio diferente.", [
  136. "validToken" => false
  137. ]);
  138. }
  139. $now = Carbon::now('America/Mexico_city')->timestamp;
  140. if($now > $decoded->cad){
  141. return $this->responseController->makeResponse(false, "Token expirado.", [
  142. "validToken" => false
  143. ]);
  144. }
  145. $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
  146. $actions = DB::getQueryLog();
  147. $this->functionsController->registerActivity($actions, $usr->USUA_IDUS, $nowStr, 1);
  148. return $this->responseController->makeResponse(false, "Token válido.", [
  149. "validToken" => true
  150. ]);
  151. }
  152. public function createPasword(Request $request){
  153. $pass = $request->only('pass');
  154. $uuid = $this->functionsController->uuidv5('1546058f-5a25-4334-85ae-e68f2a44bbaf', 'jose.b@ittec.mx');
  155. return $this->responseController->makeResponse(false, $uuid, []);
  156. }
  157. }