LoginController.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. class LoginController extends Controller{
  11. private $responseController;
  12. private $encryptionController;
  13. private $secretKey = "ydl27x22cNsNY0z6o3Fr6XZoUvsX0QMZx6MaiwN+KCnM6APS4Xbb7GDfudOYD5uD/r8TzQElh4d4HIal5Os0XA==";
  14. public function __construct(
  15. $responseController = new ResponseController(),
  16. $encryptionController = new EncryptionController(),
  17. ){
  18. $this->responseController = $responseController;
  19. $this->encryptionController = $encryptionController;
  20. }
  21. public function login(Request $request){
  22. $validator = Validator::make($request->all(), [
  23. 'email' => 'required|string|email',
  24. 'password' => 'required|string'
  25. ]);
  26. if($validator->fails()){
  27. return $this->responseController->makeResponse(
  28. true,
  29. "Se encontraron uno o más errores.",
  30. $this->responseController->makeErrors(
  31. $validator->errors()->messages()
  32. ),
  33. 401
  34. );
  35. }
  36. $login = $request->all();
  37. $usr = DB::table('samusua')->where('USUA_EMAI', '=', $login['email'])->first();
  38. if(is_null($usr)){
  39. return $this->responseController->makeResponse(true, "El correo electrónico no está registrado.", [], 404);
  40. }
  41. $contra = $usr->USUA_CONT;
  42. if(!Hash::check($login['password'], $contra)){
  43. return $this->responseController->makeResponse(true, "La contraseña es incorrecta.", [], 401);
  44. }
  45. $now = Carbon::now('America/Mexico_city');
  46. $iat = $now->timestamp;
  47. $cad = $now->addDay()->timestamp;
  48. $payload = [
  49. "iss" => $login['email'],
  50. "aud" => "dominio.syp.mx",
  51. "iat" => $iat,
  52. "cad" => $cad
  53. ];
  54. $token = JWT::encode($payload, $this->secretKey, 'EdDSA');
  55. return $this->responseController->makeResponse(false, "EXITO.", [
  56. "IDUSUARIO" => $this->encryptionController->encrypt($usr->USUA_IDUS),
  57. "NOMREUSUARIO" => $this->encryptionController->encrypt($usr->USUA_NOMB),
  58. "CORREO" => $this->encryptionController->encrypt($usr->USUA_EMAI),
  59. "TOKEN" => $token,
  60. ]);
  61. }
  62. }