After preparing the API backend and registration page discussed in article part 1. The next step is to create a login controller and create a login page to be able to access the main dashboard or system page.
To be able to follow this article well, you should first read the article CRUD Client Tutorial and Server API Using JQuery And Lumen Part 1
Make a Login Controller
Create a new controller with the name LoginController.php in the folder “app/Http/Controllers”. Copy the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | <?php namespace App\Http\Controllers; use Firebase\JWT\JWT; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Validator; class LoginController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { // } protected function jwt($user, $token) { $payload = [ 'iss' => "lumen-jwt", 'sub' => $user, 'iat' => time(), 'token' => $token, 'exp' => time() + 3 * 60 * 60, ]; return JWT::encode($payload, env('JWT_SECRET')); } public function loginApp(Request $request) { if (!$request->has('user_id') || !$request->has('user_password')) { $res['success']=false; $res['message']= "username or password required"; return response($res, 422); } if ($request->user_id == "" || is_null($request->user_id) || $request->user_password == "" || is_null($request->user_password)) { $res['success']=false; $res['message']= "username or password required"; return response($res, 422); } $id = $request->user_id; $password = $request->user_password; try { $login = DB::select("SELECT m.user_id FROM m_user m WHERE m.user_id = ?", [$id]); if ($login) { if (count($login) > 0) { $hash = DB::select("SELECT m.user_id, m.user_name FROM m_user m WHERE m.user_id = ? AND m.user_password = SHA2( ? ,256)", [$id, $password]); if (count($hash) > 0) { try { $tmc = hash('sha256', $id . time()); $token = $this->jwt($id, $tmc); $create_token = DB::update("UPDATE m_user SET m_user.api_key = ? WHERE m_user.user_id = ?", [$tmc, $id]); $res['success'] = true; $res['message'] = 'Successfull login'; $res['data'] = $hash[0]; $res['token'] = $token; return response($res, 200); } catch (\Illuminate\Database\QueryException $ex) { $res['success'] = false; $res['message'] = $ex->getMessage(); return response($res, 500); } } else { $res['success'] = false; $res['message'] = 'Username and password not found'; return response($res, 400); } } else { $res['success'] = false; $res['message'] = 'Username and password not found'; return response($res, 400); } } else { $res['success'] = false; $res['message'] = 'Username and password not found'; return response($res, 400); } } catch (\Illuminate\Database\QueryException $ex) { $res['success'] = false; $res['message'] = $ex->getMessage(); return response($res, 500); } } } |
Note:
To create a JWT token, some information will be encrypted with the secret key
1 2 3 4 5 6 7 | $payload = [ 'iss' => "lumen-jwt", 'sub' => $user, 'iat' => time(), 'token' => $token, 'exp' => time() + 3 * 60 * 60, ]; |
Note:
iss | : Issuer of the token |
sub | : Subject of the token |
iat | : time when JWT was issued |
token | : secret key token |
exp | : Expiration time |
Create new Routes to access the login page API
Add the following code on “routes web.php”
1 | $router->post('/login','LoginController@loginApp'); |
Make a front-end login page
Please create a new file called index.php in the Restclient folder and copy the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | <?php session_start(); ?> <!DOCTYPE html> <html> <head> <title>Login form</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" > </head> <body> <div class="container"> <div class="row mt-5"> <div class="col-6 align-self-center"> <h2>Login Form</h2> <hr> <form> <div class="form-group"> <div class="form-group row"> <label class="col-sm-2 col-form-label">Username</label> <div class="col-sm-10"> <input type="text" class="form-control" id="txtuser" value=""> </div> </div> </div> <div class="form-group"> <div class="form-group row"> <label class="col-sm-2 col-form-label">Password</label> <div class="col-sm-10"> <input type="password" class="form-control" id="txtpass" value=""> </div> </div> </div> <button type="button" id="btnlogin" class="btn btn-primary mb-2">Login</button> <a role="button" href="register.php" class="btn btn-primary mb-2 float-right active">Register</a> </form> <div class="alert hidden informasi" role="alert" ></div> </div> </div> </div> </body> <script src="https://code.jquery.com/jquery-3.3.1.min.js" ></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" ></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" ></script> <script src="sha256.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#btnlogin").click(function(){ var ajax = { user_id : $("#txtuser").val(), user_password : sha256($("#txtpass").val()) } $.ajax({ url: "http://localhost:8000/login", type: "POST", data: ajax, success: function(data, textStatus, jqXHR) { var ajax = { data : data } $.ajax({ url: "set_authenticate.php", type: "POST", data: ajax, success: function(data, textStatus, jqXHR) { var data = jQuery.parseJSON(data); window.location.replace(data.url); return false; }, error: function (request, textStatus, errorThrown) { console.log(request); } }); }, error: function (request, textStatus, errorThrown) { $(".informasi").removeClass("hidden").addClass('alert-danger').html(request.responseJSON.message); } }); }); }); </script> </html> |
Note:
JQuery will access the API backend to log in the application with the address http://localhost:8000/login. If successful, JQuery will send an ajax request to register the user’s token and data profile into the PHP session in the file “set_authenticate.php”.
Create a file set_authenticate.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?php session_start(); if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) ) { $_SESSION['_session']['user_id'] =$_POST['data']['data']['user_id']; $_SESSION['_session']['user_name'] =$_POST['data']['data']['user_name']; $_SESSION['_session']['token'] =$_POST['data']['token']; $data['result']=$_POST['data']['success']; $data['message']=$_POST['data']['message']; $data['url']='dashboard.php'; echo json_encode($data); } ?> |
Note:
If the login request on Server API has been successful, jQuery will continue to record tokens and user profiles in the PHP session used to handle page authentication in the client application.
If successful, JQuery will redirect the main “page/dashboard”.
Create a file with the name dashboard.php and copy the following code:
1 2 3 4 5 6 7 8 9 | <!DOCTYPE html> <html> <head> <title>Dashboard Page</title> </head> <body> <h1>Welcome to dashboard page</h1> </body> </html> |
Until this section, the creation of the login page has been successful, to run the application please execute the API server with the following code
1 | php -S localhost:8000 -t public |
Then run the front-end application with the following URL
1 | http://localhost/Restclient/ |
If successful, the application will run as shown below
Until this step the login page has been completed, the last step is to create a dashboard page and create a CRUD application for the master item. Do not miss. Hopefully useful
Latest posts by Sigit Prasetya Nugroho (see all)
- How To Insert Ads In The Middle Post Blogspot Blogger - January 26, 2019
- Login Page – Tutorial CRUD Client and API Server Using JQuery And Lumen Part 2 - January 23, 2019
- Tutorial CRUD Client and API Server Using JQuery And Lumen Part 1 - January 4, 2019