Membuat Halaman Login Web Admin (Tutorial CodeIgniter 4 #Part 2)

Membuat Halaman Login Web Admin (Tutorial CodeIgniter 4 #Part 2)

Membuat Halaman Login Web Admin (Tutorial CodeIgniter 4 #Part 2)


Karna Tutorial kali ini membuat halaman login, maka kita membutuhkan data user di database. Pada tutorial part 1 kita telah membuat database dengan nama ci4-project. Tambahkan tabel dengan struktur seperti dibawah :

 

CREATE TABLE `users` (
  `user_id` int(12) NOT NULL,
  `user_level` int(5) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(100) NOT NULL,
  `active` enum('Y','N') NOT NULL DEFAULT 'N'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

Jadikan user_id sebagai primary_key atau indeks

 

ALTER TABLE `users`
  ADD PRIMARY KEY (`user_id`);
COMMIT;

 

Dumping data untuk table users

 

INSERT INTO `users` (`user_id`, `user_level`, `username`, `password`, `active`) VALUES
(1594613248, 1, 'admin', '21232f297a57a5a743894a0e4a801fc3', 'Y');

 

Maka di tabel users akan ditemukan sebuah user dengan username : admin dan password : admin.

 

Pastikan anda telah mengikuti tutorial Membuat Web Administrator Dengan CodeIgniter 4 (Tutorial CodeIgniter 4 #Part 1) karna tutorial ini saling berkaitan.

 

Buat file di folder app/views/admin dengan nama login.php dan isikan kode berikut :

 

<?php include ('./include/admin/login.php');?>

 

Buat file di folder public/include/admin dengan nama login.php dan isikan kode berikut :

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Bootstrap Login Form with Avatar Image</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<style>
body {
	color: #fff;
	background: #d47677;
}
.form-control {
	min-height: 41px;
	background: #fff;
	box-shadow: none !important;
	border-color: #e3e3e3;
}
.form-control:focus {
	border-color: #70c5c0;
}
.form-control, .btn {        
	border-radius: 2px;
}
.login-form {
	width: 350px;
	margin: 0 auto;
	padding: 100px 0 30px;		
}
.login-form form {
	color: #7a7a7a;
	border-radius: 2px;
	margin-bottom: 15px;
	font-size: 13px;
	background: #ececec;
	box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
	padding: 30px;	
	position: relative;	
}
.login-form h2 {
	font-size: 22px;
	margin: 35px 0 25px;
}
.login-form .avatar {
	position: absolute;
	margin: 0 auto;
	left: 0;
	right: 0;
	top: -50px;
	width: 95px;
	height: 95px;
	border-radius: 50%;
	z-index: 9;
	background: #70c5c0;
	padding: 15px;
	box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.1);
}
.login-form .avatar img {
	width: 100%;
}	
.login-form input[type="checkbox"] {
	position: relative;
	top: 1px;
}
.login-form .btn, .login-form .btn:active {        
	font-size: 16px;
	font-weight: bold;
	background: #70c5c0 !important;
	border: none;
	margin-bottom: 20px;
}
.login-form .btn:hover, .login-form .btn:focus {
	background: #50b8b3 !important;
}    
.login-form a {
	color: #fff;
	text-decoration: underline;
}
.login-form a:hover {
	text-decoration: none;
}
.login-form form a {
	color: #7a7a7a;
	text-decoration: none;
}
.login-form form a:hover {
	text-decoration: underline;
}
.login-form .bottom-action {
	font-size: 14px;
}
</style>
</head>
<body>
<div class="login-form">
    <form action="/examples/actions/confirmation.php" method="post">
		<div class="avatar">
			<img src="/examples/images/avatar.png" alt="Avatar">
		</div>
        <h2 class="text-center">Member Login</h2>   
        <div class="form-group">
        	<input type="text" class="form-control" name="username" placeholder="Username" required="required">
        </div>
		<div class="form-group">
            <input type="password" class="form-control" name="password" placeholder="Password" required="required">
        </div>        
        <div class="form-group">
            <button type="submit" class="btn btn-primary btn-lg btn-block">Sign in</button>
        </div>
		<div class="bottom-action clearfix">
            <label class="float-left form-check-label"><input type="checkbox"> Remember me</label>
            <a href="#" class="float-right">Forgot Password?</a>
        </div>
    </form>
    <p class="text-center small">Don't have an account? <a href="#">Sign up here!</a></p>
</div>
</body>
</html>

 

ganti

<title>Bootstrap Login Form with Avatar Image</title>

menjadi

<title><?=$title;?></title>

ganti

body {
	color: #fff;
	background: #d47677;
}

menjadi

body {
	color: #fff;
	background: #737373;
}

ganti

<form action="/examples/actions/confirmation.php" method="post">

menjadi

<?=form_open('admin/login');?>

ganti

<img src="/examples/images/avatar.png" alt="Avatar">

menjadi

<li style="font-size:63px;color:white;margin-left:10px" class="fa fa-user text-center"></li>

Buat sebuah library di folder app/libraries dengan nama Notification.php isikan kode berikut :

 

<?php namespace App\Libraries;

class Notification {

	public function __construct()
	{
		$this->session = session();
    }
    
	public function message($msg, $type) {
		if ($type == "info") {
			$message = '<div id="msgalert" class="alert alert-info alert-dismissible">
				<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
				<i class="icon fa fa-check"></i> ' . $msg . '</div>';
		} elseif ($type == "danger") {
			$message = '<div id="msgalert" class="alert alert-danger alert-dismissible">
				<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
				<i class="icon fa fa-ban"></i>  ' . $msg . '</div>';
		} elseif ($type == "warning") {
			$message = '<div id="msgalert" class="alert alert-warning alert-dismissible">
				<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
				<i class="icon fa fa-close"></i> ' . $msg . '</div>';
		}
		
		$this->session->setTempdata('message', $message);
	}
	
}

 

Fungsinya untuk menampilkan notifikasi bootstrap.

 

Selanjutnya membuat model untuk users, buat sebuah file di folder app/models dengan nama ModUsers.php dan isikan kode berikut :

 

<?php namespace App\Models;

use CodeIgniter\Model;

class ModUsers extends Model
{
    protected $table = "users";
    protected $primaryKey = 'user_id';

	public function __construct()
	{	
    }
	
}

 

Buka file controllers app/controllers/Admin.php yang telah dibuat pada tutorial Membuat Web Administrator Dengan CodeIgniter 4 (Tutorial CodeIgniter 4 #Part 1).

 

Load library Notification.php

use App\Libraries\Notification;

 

Load helper, session dan request Tambahkan kode berikut kedalam class Admin extends Controller 

protected $helpers = ['form','date'];
protected $session = null;
protected $request = null;

 

Tambakan kode berikut kedalam public function __construct() 

$this->session = session();
$this->request = \Config\Services::request();
$this->notif = new Notification();
$this->moduser = model('App\Models\ModUsers');

 

Tambahkan kode berikut kedalam public function index() letakkan di bagian atas.

if ($this->session->has('message')) {
	$dataIndex['message'] = $this->session->get('message');
} else {
	$dataIndex['message'] = "";
};

if (!isset($_SESSION['admin_logged_in'])) {
	$dataIndex['title'] = "Login - Administrator";
	$this->session->removeTempdata('message');
	return view('admin/login', $dataIndex);
}

$this->session->get('message'); diambil dari session yang diterapkan oleh library Notification.php sebagai alert yang akan ditampilkan di view.

(!isset($_SESSION['admin_logged_in'])) Jika sesi login admin tidak ada maka yang ditampilkanadalah  halaman login.

 

Buat function login.

public function login()
{
	$username = $this->request->getPost('username');
	$password = $this->request->getPost('password');

	if (isset($_SESSION['admin_logged_in'])) {
		return redirect()->to(base_url('admin'));
	}

	if (!isset($_SESSION['admin_logged_in']) && (empty($username) || empty($password))){
		$this->notif->message('Data login tidak lengkap', 'danger');
		return redirect()->to(base_url('admin'));
	}

	if (!isset($_SESSION['admin_logged_in']) && isset($username) && isset($password)) {
		$datauser = [
			'username' => $username,
			'password' => md5($password)
		];
		$user = $this->moduser->asObject()->where($datauser)->limit(1)->find();
		if (count($user) > 0) {
			if ($user[0]->active === 'N') {
				$this->notif->message('Akun anda tidak aktif', 'danger');
				return redirect()->to(base_url('admin'));
			} elseif ($user[0]->user_level !== '1') {
				$this->notif->message('Akun anda bukan Admin, dan tidak memiliki akses ke halaman ini', 'danger');
				return redirect()->to(base_url('admin'));
			} else {
				$data_session = array(
					'admin_user_id' => $user[0]->user_id,
					'admin_username' => $user[0]->username,
					'admin_level' => $user[0]->user_level,
					'admin_logged_in' => TRUE
				);
				$this->session->set($data_session);
				return redirect()->to(base_url('admin'));
			}
		} else {
			$this->notif->message('username atau password anda salah', 'danger');
			return redirect()->to(base_url('admin'));
		}
	}
	
}

Buat function logout

public function logout(){
	$array_items = array('admin_user_id','admin_username','admin_level','admin_logged_in');
	$this->session->remove($array_items);
	return redirect()->to(base_url('admin'));
}

 

.Sehingga hasil keseluruhan untul file Admin.php seperti berikut.

<?php namespace App\Controllers;
use CodeIgniter\Controller;

use App\Libraries\Notification;

class Admin extends Controller
{
    protected $helpers = ['form','date'];
	protected $session = null;
	protected $request = null;

	public function __construct()
	{
		$this->session = session();
		$this->request = \Config\Services::request();
		$this->notif = new Notification();
		$this->moduser = model('App\Models\ModUsers');
	}


	public function index()
	{
		if ($this->session->has('message')) {
			$dataIndex['message'] = $this->session->get('message');
		} else {
			$dataIndex['message'] = "";
		};

        if (!isset($_SESSION['admin_logged_in'])) {
			$dataIndex['title'] = "Login - Administrator";
			$this->session->removeTempdata('message');
			return view('admin/login', $dataIndex);
		}

        $dataIndex['header'] = view("admin/header");
        $dataIndex['sidebar'] = view("admin/sidebar");
        $dataIndex['menu'] = view("admin/menu");
        $dataIndex['footer'] = view("admin/footer");
        //$dataIndex['content'] = view("admin/content");
		$this->session->removeTempdata('message');
		return view('admin/index', $dataIndex);
        
	}

	public function login()
	{
		$username = $this->request->getPost('username');
		$password = $this->request->getPost('password');

		if (isset($_SESSION['admin_logged_in'])) {
			return redirect()->to(base_url('admin'));
		}

		if (!isset($_SESSION['admin_logged_in']) && (empty($username) || empty($password))){
			$this->notif->message('Data login tidak lengkap', 'danger');
			return redirect()->to(base_url('admin'));
		}

		if (!isset($_SESSION['admin_logged_in']) && isset($username) && isset($password)) {
			$datauser = [
				'username' => $username,
				'password' => md5($password)
			];
			$user = $this->moduser->asObject()->where($datauser)->limit(1)->find();;
			if (count($user) > 0) {
        		if ($user[0]->active === 'N') {
					$this->notif->message('Akun anda tidak aktif', 'danger');
					return redirect()->to(base_url('admin'));
				} elseif ($user[0]->user_level !== '1') {
					$this->notif->message('Akun anda bukan Admin, dan tidak memiliki akses ke halaman ini', 'danger');
					return redirect()->to(base_url('admin'));
				} else {
					$data_session = array(
						'admin_user_id' => $user[0]->user_id,
						'admin_username' => $user[0]->username,
						'admin_level' => $user[0]->user_level,
						'admin_logged_in' => TRUE
					);
					$this->session->set($data_session);
					return redirect()->to(base_url('admin'));
				}
			} else {
				$this->notif->message('username atau password anda salah', 'danger');
				return redirect()->to(base_url('admin'));
			}
		}
        
	}

	public function logout(){
		$array_items = array('admin_user_id','admin_username','admin_level','admin_logged_in');
		$this->session->remove($array_items);
		return redirect()->to(base_url('admin'));
	}


}

 

Selanjutnya membuat menu Logout di Halaman admin. Buka file public/include/admin/Header.php dan cari kode :

<div tabindex="-1" role="menu" aria-hidden="true" class="dropdown-menu dropdown-menu-right">

 

Tambahkan kode berikut di bawah menu bahasa yang telah dibuat di tutorial Membuat Web Administrator Dengan CodeIgniter 4 (Tutorial CodeIgniter 4 #Part 1).

<div tabindex="-1" class="dropdown-divider"></div>
<a href="<?=base_url('admin/logout');?>" type="button" tabindex="0" class="dropdown-item">Logout</a>

 

buka http://localhost:8080/admin dengan  data login :

 

Usename : admin
Password : admin

 

Sekian tutorial Membuat Halaman Login Web Admin (Tutorial CodeIgniter 4 #Part 2) wink

 

Bagikan


Artikel Dipost Oleh Hariadi

Seorang freelancer website and software developer, gemar dengan ilmu seputar IT serta penuh semangat untuk belajar.


15 Komentar

Yosia Yosia 02 Jun 2023
terimkasih atas ilmunya pertama belajar CI 4 bisa ngikutin pelan2
Devi arum sari Devi arum sari Member 28 Agu 2021
Error sama seperti Cepy Mr, setelah memasukkan user : admin n password : admin muncul error method_exists(): Argument #1 ($object_or_class) must be of type object|string, null given.. kenapa ya suhu?
Cepy Mr Cepy Mr Member 01 Agu 2021
mohon bantunnya suhu erorr method_exists(): Argument #1 ($object_or_class) must be of type object|string, null given
Lukman Lukman 30 Mar 2021
kok pas login muncul kayak gini gan? method_exists(): Argument #1 ($object_or_class) must be of type object|string, null given SYSTEMPATH\BaseModel.php at line 1770 1763 * 1764 * @return $this|null 1765 */ 1766 public function __call(string $name, array $params) 1767 { 1768 $result = null; 1769 1770 if (method_exists($this->db, $name)) 1771 { 1772 $result = $this->db->{$name}(...$params); 1773 } 1774 1775 return $result; 1776 } 1777
komara setio komara setio 09 Feb 2021
done min...penyebabnya database nya tidak di seting dulu
komara setio komara setio 09 Feb 2021
kalau errornya seperti ini kenapa min..malum masih pemula.. APPPATH\Views\errors\html\error_exception.php at line 100
komara setio komara setio 08 Feb 2021
min..setelah klik login tidak masuk ke page admin si...ada pesan "Whoops! We seem to have hit a snag. Please try again later..."

Berikan komentar ...