123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118 |
- <?php
- namespace App\Controllers\Web;
- use App\Utils\Api;
- use App\Utils\Url;
- use PH7\JustHttp\StatusCode;
- class AuthController
- {
-
- private function getFormFields()
- {
- return ['nickname', 'password'];
- }
-
- private function getCookieOptions()
- {
- return [
- 'path' => '/',
- 'httpOnly' => true
- ];
- }
-
- public function loginView($req, $res)
- {
- $values = [];
- $validations = [];
- $error = $req->session['error'] ?? null;
-
- foreach ($this->getFormFields() as $field) {
- $values[$field] = $req->session['values'][$field] ?? null;
- $validations[$field] = $req->session['validations'][$field] ?? null;
- }
- foreach (['values', 'validations', 'error'] as $key) {
- unset($req->session[$key]);
- }
- $res->render('auth/login', [
- 'app' => $req->app,
- 'values' => $values,
- 'validations' => $validations,
- 'error' => $error
- ]);
- }
-
- public function loginAction($req, $res)
- {
- $data = [];
-
- foreach ($this->getFormFields() as $field) {
- $data[$field] = $req->body[$field] ?? null;
- }
- $client = Api::client();
-
- $response = $client->post('v1/auth/login', [], $data);
- $body = json_decode($response->body ?? '', true);
- $token = $body['data']['token'] ?? null;
-
- if (empty($response->success) || empty($token)) {
- $req->session['values'] = $data;
-
- if (!empty($body['validations'])) {
- $req->session['validations'] = $body['validations'];
- }
-
- $req->session['error'] = $body['error'] ?? 'Could not login';
- $res->redirect(Url::build('login'), StatusCode::FOUND);
- }
- $cookieOptions = $this->getCookieOptions();
-
- $cookieOptions['expire'] = strtotime('tomorrow');
-
- $res->cookie('userAuth', $token, $cookieOptions);
- $res->redirect(Url::build('notes'), StatusCode::FOUND);
- }
-
- public function logout($req, $res)
- {
- $res->clearCookie('userAuth', $this->getCookieOptions());
- $res->redirect(Url::build('login'), StatusCode::FOUND);
- }
- }
|