Nov 29, 2016

Multi-level User Login From Different Table Using Codeigniter 3

  No comments
https://cdn.elegantthemes.com/blog/wp-content/uploads/2014/01/user-roles-thumb.jpg

Pada kesempatan ini saya mau share bagaimana cara membuat hak akses user pada CodeIgniter dengan menggunakan banyak tabel. Sebagai contoh disini saya membuat dua buah tabel yaitu Admin dan Member.

Disini saya hanya akan menjelaskan point-point pentingnya saja, sisanya silahkan download source code yang sudah di sediakan di bawah.

Tabel Admin

CREATE TABLE `admin` (
  `admin_id` int(10) NOT NULL,
  `admin_user` char(30) NOT NULL,
  `admin_pass` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `admin`
  ADD PRIMARY KEY (`admin_id`),
  ADD UNIQUE KEY `admin_user` (`admin_user`);

 Tabel Member

CREATE TABLE `member` (
  `member_id` int(10) NOT NULL,
  `member_user` char(20) NOT NULL,
  `member_pass` varchar(255) NOT NULL,
  `member_nama` varchar(255) NOT NULL,
  `member_alamat` text NOT NULL,
  `member_ttl` date NOT NULL,
  `member_email` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `member`
  ADD PRIMARY KEY (`member_id`),
  ADD UNIQUE KEY `member_user` (`member_user`);

Buat file Controller Utama - C_Main

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class C_Main extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('M_Main');
}
public function index()
{
//Check session
if($this->session->userdata('admin_user'))
{
$this->load->view('admin/V_dashboard');
}
elseif($this->session->userdata('member_user'))
{
$this->load->view('member/V_dashboard');
}
else
{
$this->load->view('V_Login');
}
}
public function login()
{
$username  = $this->input->post('username');
$password  = md5($this->input->post('password'));
$cek_admin = $this->M_Main->get_admin($username,$password);
$cek_member = $this->M_Main->get_member($username,$password);
if($cek_admin->num_rows() == 1)
{
foreach($cek_admin->result_array() as $row)
{
$pass_auth = $row['admin_pass'];
if($password == $pass_auth)
{
$row_data = array(
'admin_id' => $row['admin_id'],
'admin_user' => $row['admin_user']
);
$this->session->set_userdata($row_data);
redirect('admin/C_Admin');
}
else
{
//if wrong password
$this->load->view('V_Login');
}
}
}
elseif($cek_member->num_rows() == 1)
{
foreach($cek_member->result_array() as $row)
{
$pass_auth = $row['member_pass'];
if($password == $pass_auth)
{
$row_data = array(
'member_id'   => $row['member_id'],
'member_user' => $row['member_user']
);
$this->session->set_userdata($row_data);
redirect('member/C_Member');
}
else
{
//if wrong password
$this->load->view('V_Login');
}
}
}
else
{
//if wrong username
$this->load->view('V_Login');
}
}
    public function logout(){
        $this->session->unset_userdata('admin_id');
        $this->session->unset_userdata('admin_user');
        $this->session->unset_userdata('member_id');
        $this->session->unset_userdata('member_user');
        redirect(site_url(''));
    }
}

Buat file Model Utama - M_Main

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class M_Main extends CI_Model
{
public function get_admin($username,$password)
{
$query = $this->db->query("SELECT * FROM admin WHERE admin_user='$username' AND admin_pass='$password' ");
return $query;
}
public function get_member($username,$password)
{
$query = $this->db->query("SELECT * FROM member WHERE member_user='$username' AND member_pass='$password' ");
return $query;
}
}

Untuk melakukan cek session pada setiap controller, kita membutuhkan sebuah file helper. Maka buatlah file pada folder application/helpers


sessions_helper.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
function admin_logged_in()
{
    $CI =& get_instance();
    $is_logged_in = $CI->session->userdata('admin_user');
    if(!isset($is_logged_in) || $is_logged_in != true)
    {
        redirect('C_Main');
    }    
}
function member_logged_in()
{
    $CI =& get_instance();
    $is_logged_in = $CI->session->userdata('member_user');
    if(!isset($is_logged_in) || $is_logged_in != true)
    {
        redirect('C_Main');
    }
}

Lalu buka file autoload.php pada folder application/config dan ubah bagian helper menjadi seperti ini


$autoload['helper'] = array('url','form','sessions');


Nanti di setiap Controller baik Admin maupun Member tambahkan helper session tadi untuk melakukan pengecekan user yang login

Controller Admin - C_Admin

class C_Admin extends CI_Controller
{
public function __construct()
{
parent::__construct();
admin_logged_in();
}


Controller Member - C_Member

class C_Member extends CI_Controller
{
public function __construct()
{
parent::__construct();
member_logged_in();
}


Selesai.. bagaimana mudah bukan?

Untuk source codenya silahkan buka Github saya klik disini

Selamat mencoba


Nov 19, 2016

Membuat Enkripsi Password di Database Menggunakan Cipher (PHP Mcrypt)

  No comments


1) Buat file library cipher.php dengan isi seperti berikut
<?php
/**
 * Cipher
 *
 * Simple mcrypt interface.
 *
 * Cipher is a simple class for working with mcrypt.
 *
 * @package     Cipher
 * @author      Nathan Lucas <nathan@gimpstraw.com>
 * @link        http://www.gimpstraw.com/
 * @copyright   Copyright (c) 2008, Nathan Lucas
 * @version     2.0.0
 *
 * Added $iv to both encrypt() and decrypt() allowing you to use preset IVs
 * while encrypting/decrypting data.
 *
 * Also added getIV(), which returns the instance's current IV in base64
 * allowing you to store this IV for use on other instances of Cipher.
 */
class Cipher {

    /**
     * Algorithm to use.
     *
     * @access  private
     * @var     string
     */
    private $algo;

    /**
     * Encryption mode.
     *
     * @access  private
     * @var     string
     */
    private $mode;

    /**
     * Randomization source.
     *
     * @access  private
     * @var     integer
     */
    private $source;

    /**
     * Initialization vector.
     *
     * @access  private
     * @var     string
     */
    private $iv = null;

    /**
     * Encryption key.
     *
     * @access  private
     * @var     string
     */
    private $key = null;

    /**
     * Cipher($algo, $mode, $source)
     *
     * Cipher constructor. Sets the algorithm being used, the encryption
     * mode, and the IV.
     *
     * @param   string $algo
     * @param   string $mode
     * @param   integer $source (randomization source)
     * @access  public
     * @return  void
     */
    public function __construct($algo = MCRYPT_3DES, $mode = MCRYPT_MODE_CBC, $source = MCRYPT_RAND) {
        $this->algo = $algo;
        $this->mode = $mode;
        $this->source = $source;

        if (is_null($this->algo) || (strlen($this->algo) == 0)) {
            $this->algo = MCRYPT_3DES;
        }
        if (is_null($this->mode) || (strlen($this->mode) == 0)) {
            $this->mode = MCRYPT_MODE_CBC;
        }
    }

    /**
     * encrypt($data, $key, $iv)
     *
     * Returns encrpyted $data, base64 encoded. $key must be specified at
     * least once, it can be changed at any point.
     *
     * @param   string $data
     * @param   mixed $key
     * @param   string $iv
     * @access  public
     * @return  string
     */
    public function encrypt($data, $key = null, $iv = null) {
        $key = (strlen($key) == 0) ? $key = null : $key;

        $this->setKey($key);
        $this->setIV($iv);

        $out = mcrypt_encrypt($this->algo, $this->key, $data, $this->mode, $this->iv);
        return base64_encode($out);
    }

    /**
     * decrypt($data, $key, $iv)
     *
     * Returns decrypted $data. $key must be specified at least once, it can
     * be changed at any point.
     *
     * @param   mixed $data
     * @param   mixed $key
     * @param   string $iv
     * @access  public
     * @return  string
     */
    public function decrypt($data, $key = null, $iv = null) {
        $key = (strlen($key) == 0) ? $key = null : $key;

        $this->setKey($key);
        $this->setIV($iv);

        $data = base64_decode($data);
        $out = mcrypt_decrypt($this->algo, $this->key, $data, $this->mode, $this->iv);
        return trim($out);
    }

    /**
     * getIV()
     *
     * Returns the IV used for encryption so you can use it again in another
     * Cipher instance to decrypt data.
     *
     * @access  public
     * @return  string
     */
    public function getIV() {
        return base64_encode($this->iv);
    }

    /**
     * setIV($iv)
     *
     * Sets IV. If $iv is specified, the instance IV will be set to this. If not,
     * the instance will generate an IV.
     *
     * @param   string $iv
     * @access  private
     * @return  void
     */
    private function setIV($iv) {
        if (!is_null($iv)) {
            $this->iv = base64_decode($iv);
        }
        if (is_null($this->iv)) {
            $iv_size = mcrypt_get_iv_size($this->algo, $this->mode);
            $this->iv = mcrypt_create_iv($iv_size, $this->source);
        }
    }

    /**
     * setKey($data, $key)
     *
     * Sets Cipher::key. This will be the key used for the encrypt and decrypt
     * methods until another $key is specified. This will trigger an error if
     * no initial key is set.
     *
     * @param   mixed $key
     * @access  private
     * @return  void
     */
    private function setKey($key) {
        if (!is_null($key)) {
            $key_size = mcrypt_get_key_size($this->algo, $this->mode);
            $this->key = hash("sha256", $key, true);
            $this->key = substr($this->key, 0, $key_size);
        }
        if (is_null($this->key)) {
            trigger_error("You must specify a key at least once in either Cipher::encrpyt() or Cipher::decrypt().", E_USER_ERROR);
        }
    }
}
?>

2)  Misal digunakan untuk membuat user baru maka penggunaannya seperti berikut

a. Buat file form untuk menambahkan user
<form method="post" action="create_user.php">
<input type="text" name="username" required>
<input type="password" name="password" required>
<button type="submit" name="add_user">Tambah User</button>
</form>
b. Buat file action create_user.php 
<?php
 include 'koneksi.php'; //ganti dengan file koneksi anda
 require_once("cipher.php");
 $cipher = new Cipher(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
 $key   = "%^$%^&%*UBAHDISINI";
 $username = $_POST['username'];
 $password = $cipher->encrypt($_POST['password'], $key);
 if(isset($_POST['add_user'])){
  $query = mysqli_query($conn,"INSERT INTO tb_user VALUES('$username', '$password')");
    if($query){
   echo "Berhasil Tambah User";
  }
  else{
   echo "Gagal Tambah User";
  }
 }
?>

*Pada bagian UBAHDISINI bisa diganti dengan KEY yang diinginkan, misal QWERT123  atau 94XYZ dsb.


3) Misal digunakan untuk form login maka penggunaannya seperti berikut

a. Buat file form untuk login
<form method="post" action="login_proses.php">
<input type="text" name="username" required>
<input type="password" name="password" required>
<button type="submit">Login</button>
</form>

b. Buat file login_proses.php
<?php
@session_start();
include 'koneksi.php'; //ganti dengan file koneksi anda
require_once("cipher.php");
$cipher = new Cipher(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
$key   = "%^$%^&%*UBAHDISINI";
$username = $_POST['username'];
$password = $cipher->encrypt($_POST['password'], $key);
if($username&&$password) {
$get_user = mysqli_query($conn,"SELECT * FROM tb_user WHERE username='$username'");
$cek_user = mysqli_num_rows($get_user);
if($cek_user!=0){
while($row = mysqli_fetch_assoc($get_user)){
$dbusername = $row['username '];
$dbpassword = $row['password'];
}
if($username==$dbusername&&$password==$dbpassword){
$_SESSION['username']=$username;
header("location:/dashboard.php");
}
else{
header("location:/login.php");
}
}
?>

4) Selanjutnya kode tersebut tinggal di terapkan pada sistem yang kamu buat

Selamat mencoba!

Multi-level User Login with PHP & MySQLi

  No comments

Disini dimisalkan sebuah sistem yang memiliki 3 level user berbeda.

Contoh:
 - Admin
 - Dosen
 - Mahasiswa


1) Pertama buat halaman loginnya

<h1> FORM LOGIN </h1>
<form action="proses_login.php" method="post">
<input type="text" name="username" required>
<input type="password" name="password" required>
<button type="submit">LOGIN</button>
</form>

2) Lalu buat file actionnya (proses_login.php)
<?php
@session_start();
include 'koneksi.php'; //ganti dengan koneksi database anda
$username = $_POST['username'];
$password = $_POST['password'];
if($username&&$password){
//cek data admin
$get_admin = mysqli_query($conn,"SELECT * FROM tb_admin WHERE user_admin='$username'");
$cek_admin = mysqli_num_rows($get_admin);
if($cek_admin!=0){
while($row = mysqli_fetch_assoc($get_admin)){
$dbusername = $row['user_admin'];
$dbpassword = $row['pass_admin'];
}
if($username==$dbusername&&$password==$dbpassword){
$_SESSION['user_admin']=$username;
header("location:./admin/dashboard");
}
else{
header("location:/index.php");
}
}
//jika data admin tidak ada, cek data dosen
else{
$get_dosen = mysqli_query($conn,"SELECT * FROM tb_dosen WHERE user_dosen='$username'");
$cek_dosen = mysqli_num_rows($get_dosen);
if($cek_dosen!=0){
while($row = mysqli_fetch_assoc($get_dosen)){
$dbusername = $row['user_dosen'];
$dbpassword = $row['pass_dosen'];
}
if($username==$dbusername&&$password==$dbpassword){
$_SESSION['user_dosen']=$username;
header("location:./dosen/dashboard");
}
else{
header("location:/index.php");
}
}
//jika data dosen tidak ada, cek data mahasiswa
else{
$get_mhs = mysqli_query($conn,"SELECT * FROM tb_mhs WHERE user_mhs='$username'");
$cek_mhs = mysqli_num_rows($get_mhs);
if($cek_mhs!=0){
while($row = mysqli_fetch_assoc($get_mhs)){
$dbusername = $row['user_mhs'];
$dbpassword = $row['pass_mhs'];
}
if($username==$dbusername&&$password==$dbpassword){
$_SESSION['user_mhs']=$username;
header("location:./mahasiswa/dashboard");
}
else{
header("location:/index.php");
}
}
}
}
}
else{
header("location:/index.php");
}
?>

3) File proses_login.php tersebut melakukan cek satu-persatu menggunakan IF-ELSE sederhana
kamu bisa menambahkan lagi sesuai jumlah kebutuhan hak akses dengan cara yang sama

4) Selanjutnya kode tersebut tinggal di terapkan pada sistem yang kamu buat

Selamat mencoba!