Advertisement
dweialim

JWT

Feb 20th, 2023
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 3.57 KB | Source Code | 0 0
  1. <?php
  2.  
  3. namespace App\Http\Controllers;
  4.  
  5. use Illuminate\Http\Request;
  6.  
  7. use App\Models\User;
  8. use Firebase\JWT\JWT;
  9. use Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Facades\Log;
  11. use Illuminate\Support\Facades\Hash;
  12. use Illuminate\Support\Facades\Auth;
  13. use App\Http\Requests\UserRegistrationRequest;
  14. use App\Http\Requests\generateTokenRequest;
  15.  
  16. class ApiAuthController extends Controller{
  17.     private $request;
  18.  
  19.     public function __construct(Request $request) {
  20.         date_default_timezone_set('Asia/Jakarta');
  21.         $this->request = $request;
  22.     }
  23.  
  24.     protected function jwt(User $user) {
  25.         $key = env('JWT_KEY');
  26.         $payload = [
  27.             'iss' => "laravel-JWT", // Issuer of the token
  28.             'uid' => $user->id,
  29.             'iat' => time(),
  30.             'exp' => time() + (60*60), // detik*menit
  31.         ];
  32.         $token = JWT::encode($payload, $key, 'HS256'); // encode token
  33.  
  34.         $timeCur = date('d-m-Y H:i:s',$payload['exp']);
  35.         $start   = strtotime('now');
  36.         $end     = strtotime($timeCur);
  37.         $diff    = $end - $start; // total detik
  38.         $hours   = floor($diff / (60*60) ); // hitung total jam
  39.         $minutes = floor( ($diff-$hours*(60*60)) / 60); // hitung menit(reset perJam)
  40.         return (object)[
  41.             'token'   => $token,
  42.             'hours'   => $hours,
  43.             'minutes' => $minutes,
  44.             'seconds' => $diff,
  45.         ];
  46.     }
  47.  
  48.     public function authenticate(generateTokenRequest $request){
  49.         try{
  50.             $username = $this->request->header('x-username');
  51.             $password = $this->request->header('x-password');
  52.  
  53.             $user = User::where('username',$username)->first();
  54.             if(!$user){
  55.                 return response()->json([
  56.                     'status' => false,
  57.                     'metaData' => [
  58.                         'code' => 400,
  59.                         'messsage' => 'Username not found',
  60.                     ],
  61.                 ],400);
  62.             }
  63.  
  64.             if(Hash::check($password,$user->password)){
  65.                 $token = $this->jwt($user);
  66.                 return response()->json([
  67.                     'status' => true,
  68.                     'metaData' => [
  69.                         'code' => 200,
  70.                         'message' => 'Token generated',
  71.                     ],
  72.                     'datas' => [
  73.                         'token' => $token->token,
  74.                         'expiration' => [
  75.                             'seconds' => $token->seconds,
  76.                             'minutes' => $token->minutes,
  77.                             'hours'   => $token->hours,
  78.                         ],
  79.                     ]
  80.               ], 200);
  81.             }
  82.  
  83.             return response()->json([
  84.                 'status' => false,
  85.                 'metaData' => [
  86.                     'code' => 400,
  87.                     'message' => 'Incorrect username or password',
  88.                 ],
  89.         ], 400);
  90.         }catch(\Throwable $th){
  91.             Log::error($th->getMessage());
  92.             DB::rollback();
  93.             return response()->json([
  94.                 'success' => false,
  95.                 'metaData' => [
  96.                     'code' => 500,
  97.                     'message' => 'Login failed'
  98.                 ]
  99.             ], 500);
  100.         }
  101.     }
  102.  
  103.     public function register(UserRegistrationRequest $request){
  104.         try{
  105.             DB::beginTransaction();
  106.             $user = User::create([
  107.                 'name' => $request->name,
  108.                 'username' => $request->username,
  109.                 'email' => $request->email,
  110.                 'password' => Hash::make($request->password),
  111.             ]);
  112.             DB::commit();
  113.  
  114.             $token = $this->jwt($user);
  115.             return response()->json([
  116.                 'status' => true,
  117.                 'metaData' => [
  118.                     'code' => 201,
  119.                     'message' => 'Registration successful',
  120.                 ],
  121.                 'datas' => [
  122.                     'token' => $token->token,
  123.                     'expiration' => [
  124.                         'seconds' => $token->seconds,
  125.                         'minutes' => $token->minutes,
  126.                         'hours'   => $token->hours,
  127.                     ],
  128.                 ]
  129.             ], 201);
  130.         }catch(\Throwable $th){
  131.             Log::error($th->getMessage());
  132.             DB::rollback();
  133.             return response()->json([
  134.                 'success' => false,
  135.                 'metaData' => [
  136.                     'code' => 500,
  137.                     'message' => 'User registration failed'
  138.                 ]
  139.             ], 500);
  140.         }
  141.     }
  142.  
  143.     public function getUser(Request $request){
  144.         return $request->auth; // getRequestFromMiddleware
  145.     }
  146. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement