AuthController.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace App\Controllers;
  3. use App\Core\Application;
  4. use App\Core\Controller;
  5. use App\Core\Form\Form;
  6. use App\Core\Middlewares\AuthMiddleware;
  7. use App\Core\Request;
  8. use App\Core\Response;
  9. use App\Models\AuthModel;
  10. use App\Models\UserModel;
  11. class AuthController extends Controller
  12. {
  13. public function __construct()
  14. {
  15. $this->registerMiddleware(new AuthMiddleware(['profile']));
  16. }
  17. /*
  18. * Renderiza la página de login
  19. * e inicia la sesión de un usuario.
  20. */
  21. public function login(Request $request, Response $response)
  22. {
  23. $authModel = new AuthModel();
  24. $authModel->loadData($request->getBody());
  25. if (! $request->isPost() || ! $authModel->validate() || ! $authModel->login()) {
  26. $form = new Form();
  27. $this->setLayout('auth');
  28. return $this->render('login', [
  29. 'form' => $form,
  30. 'model' => $authModel,
  31. ]);
  32. }
  33. $response->redirect('/');
  34. }
  35. /*
  36. * Renderiza la página de registro
  37. * y registra un nuevo usuario.
  38. */
  39. public function register(Request $request, Response $response)
  40. {
  41. $userModel = new UserModel();
  42. $userModel->loadData($request->getBody());
  43. if (! $request->isPost() || ! $userModel->validate() || ! $userModel->save()) {
  44. $form = new Form();
  45. $this->setLayout('auth');
  46. return $this->render('register', [
  47. 'form' => $form,
  48. 'model' => $userModel,
  49. ]);
  50. }
  51. Application::$app->session->setFlash('success', 'Gracias por registrarse.');
  52. $response->redirect('/');
  53. }
  54. /*
  55. * Cierra la sesión de un usuario.
  56. */
  57. public function logout(Request $request, Response $response)
  58. {
  59. Application::$app->logout();
  60. $response->redirect('/');
  61. }
  62. /*
  63. * Renderiza la página de perfil del usuario.
  64. */
  65. public function profile()
  66. {
  67. return $this->render('profile');
  68. }
  69. }