• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
seegatesite header

Seegatesite.com

Seegatesite.com - Programming Tutorial , Sharing , How and Learn Together

  • TOOLS
    • Bootstrap Navbar Online Generator
    • Customize Sidebar Menu Bootstrap 3
    • Bootstrap Demo
  • ADVERTISE
  • CATEGORIES
    • Android
    • Blogging Tips
    • Database
    • CSS
    • Info Gadget
    • Javascript
    • Linux
    • PHP
    • Various
    • WordPress
  • Q&A
  • PHP
  • JAVASCRIPT
  • JQUERY
  • ANGULAR
  • WORDPRESS
  • SEO
  • REACT
🏠 » Javascript » Login Page – Tutorial CRUD Client and API Server Using JQuery And Lumen Part 2

Login Page – Tutorial CRUD Client and API Server Using JQuery And Lumen Part 2

By Sigit Prasetya Nugroho ∙ January 23, 2019 ∙ Javascript, PHP ∙ 2 Comments

Share : TwitterFacebookTelegramWhatsapp

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

Table of Contents

  • 1 Make a Login Controller
    • 1.1 Create new Routes to access the login page API
    • 1.2 Make a front-end login page
    • 1.3 Create a file set_authenticate.php

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' =&gt; "lumen-jwt",
            'sub' =&gt; $user,  
            'iat' =&gt; time(),
            'token' =&gt; $token,
            'exp' =&gt; 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

Create Login Page With Jquery And Lumen Laravel Backend API Server

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

Another Javascript Related Post :

  • Adept Using Datatables Plugin In 10 Minutes For Beginners (Tutorial)
  • The Using Of Reactstrap And React-Table, Suitable For Beginners
  • Tutorial Create Simple Block UI Using React JS
  • How To Implement Login Page And Protected Route ReactJS
  • Complete Tutorial React Router Dom For Beginners (Easy-To-Understand)
  • The Right Way Understanding React Lifecycle For Beginners

Avatar for Sigit Prasetya Nugroho

About Sigit Prasetya Nugroho

This site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.

Reader Interactions

Comments

  1. Avatar for johnjohn says

    February 19, 2019 at 3:32 pm

    Great tutorial man… awesome…
    now , i have more understanding about lumen concept…….

    Reply
  2. Avatar for ruchitaruchita says

    February 12, 2020 at 5:53 pm

    Waiting for part 3

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Welcome to my Home,

Avatar for ruchitaThis site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.



Popular Articles

Checked checkbox AdminLTE Bootstrap in Jquery

November 4, 2014 By Sigit Prasetya Nugroho 7 Comments

Simple create date format validation with jqueryUI

December 21, 2014 By Sigit Prasetya Nugroho Leave a Comment

Create Simple Progress Bar for Fake Online Generator with Jquery

January 10, 2015 By Sigit Prasetya Nugroho Leave a Comment

22+ Coolest Free Jquery Plugin For Premium Theme

October 3, 2015 By Sigit Prasetya Nugroho Leave a Comment

Easy Build Your Anti Copy Paste Plugin

October 6, 2015 By Sigit Prasetya Nugroho Leave a Comment

Popular Tags

adminlte (15) adsense (13) adsense tips (4) affiliate amazon (13) amazon (12) Android (8) angular (16) angular 4 (12) angular 5 (4) asin grabber (3) Bootstrap (27) codeigniter (5) create wordpress theme (5) crud (8) css (6) free wordpress theme (7) google adsense (4) imacros (4) increase traffic (6) jquery (34) laravel (10) laravel 5 (5) learn android (5) modal dialog (5) mysql (6) nodeJs (4) optimize seo (4) pdo (6) php (30) plugin (53) pos (7) Publisher Tips (5) react (3) Reactjs (7) SEO (37) theme (17) tutorial angular (5) tutorial angular 4 (6) tutorial javascript (10) tutorial javascript beginners (4) twitter (3) widget (3) wordpress (18) wordpress plugin (13) XMLRPC (5)




  • About
  • Contact Us
  • Disclaimer
  • Privacy Policy
  • Terms and Conditions

©2021 Seegatesite.com