Advertisement
Raditio_123

login 2

Apr 13th, 2022
1,231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.  
  3.  namespace App\Controllers;
  4.  
  5.  use CodeIgniter\RESTful\ResourceController;
  6.  use CodeIgniter\API\ResponseTrait;
  7.  use App\Models\UserModel;
  8.  use Firebase\JWT\JWT;
  9.  use Firebase\JWT\Key;
  10.  
  11.  class Login extends ResourceController
  12.  {
  13.      /**
  14.       * Return an array of resource objects, themselves in array format
  15.       *
  16.       * @return mixed
  17.       */
  18.      use ResponseTrait;
  19.      public function index()
  20.      {
  21.          helper(['form']);
  22.          $rules = [
  23.              'email' => 'required|valid_email',
  24.              'password' => 'required|min_length[6]'
  25.          ];
  26.          if(!$this->validate($rules)) return $this->fail($this->validator->getErrors());
  27.          $model = new UserModel();
  28.          $user = $model->where("email", $this->request->getVar('email'))->first();
  29.          if(!$user) return $this->failNotFound('Email Not Found');
  30.  
  31.          $verify = password_verify($this->request->getVar('password'), $user['password']);
  32.          if(!$verify) return $this->fail('Wrong Password');
  33.  
  34.          $key = getenv('TOKEN_SECRET');
  35.          $payload = array(
  36.              "iat" => 1356999524,
  37.              "nbf" => 1357000000,
  38.              "uid" => $user['id_users'],
  39.              "email" => $user['email']
  40.          );
  41.  
  42.          $token = JWT::encode($payload, $key, 'HS256');
  43.         //  $token_decoded = JWT::decode($token, new Key($key, 'HS256'));
  44.  
  45.         //  /**
  46.         //  * contoh error
  47.         //  */
  48.         // $data_error = [
  49.         //     'success' => false,
  50.         //     'error' => 'email tidak bisa digunakan.'
  51.         // ];
  52.         // return $this->response->setStatusCode(400)->setJSON($data_error);
  53.  
  54.          /**
  55.           * contoh sukses
  56.           */
  57.          $data = [
  58.             "status"=> 200,
  59.             "messages"=> "Sukses login",
  60.             "data" => [
  61.                 "token" => $token,
  62.                 // "token_decoded" => $token_decoded,
  63.             ]
  64.          ];
  65.          return $this->response->setJSON($data);
  66.  
  67.      }
  68.  }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement