Membuat Manajemen Hak Akses User dengan Codeigniter

November 6th, 2010 by dr.emi

Membuat Manajemen Hak Akses User dengan Codeigniter malem eni gw akhirnya bisa juga nyolong2 waktu bwat nulis lagi. setelah skian lama pakum. ada tersirat, panggilan jiwa bwat nulis dan sharing lagi. setelah sekian lama males dan sibuk mncari napkah biar dapur ngebul terus. tapi setidaknya gw masih punya keinginan bwat sharing. pgimanepun, gw terlahir dari kalangan berpendidikan, orang tua gw guru smue. gw masih merasa terpanggil bwat sharing dan berbagi ilmu. tanpa banyak bacot, dan masih dalam bahasa gw yang acakadut ini, kite mulai dah tutorial pertama di bulan nopember ini. haahah!! LEGEK PISAN!!

 

kali ini gw mau sharing tentang codeigniter. yey! di dremi.NET codeigniter kali ini menjadi primadona dalam projek projekna. beberapa taon lalu, gw gak sreg banged kalok make framework orang, tapi berbekal elmu dan inspirasi dari mang opik, hasilnya mampu membius gw bwat make ni framework di segala medan tempur yang berbau web based (PHP). cekakakak!!

ni tutorial bakalan ngebahas tentang pgimane mbikin user access bertingkat pada user manager di admin CMS sebagai simulasina. kalok biasana lu pada bikin CMS masih makek 1 tipe user, ada baikna lu pakein dah mulai sekarang. sbtulna script2 ini udah lama gw tanem dalam CMS, tapi beberapa client terkadang meminta bwat menghilangkan nya, yap gw sadar tidak smua client yang mau menggunakannya, mungkin karena keterbatasan nya dalam mempelajari cara penggunaannya. gw pleksibel aja, pgimane permintaan clientna dalam make user manager.

Langkah #1 Nyiepin pael pael penting dan memahami konsepnya

- codeigniter framework
- jquery

Konsepnya:

1. User login via form login
2. Masuk ke halaman admin area, dengan default data-data user
3. Terdapat akses area yang di load dari table module
4. User yang mendapat tipe user “1″ merupakan Super Administrator dan “2″ merupakan “Administrator”
5. Tipe Super Administrator: dapat mengakses smua module area. Dan Administrator dapat mengakses module area sesuai hak akses yang diperoleh user yang sedang login
6. Route akan digunakan dalam mengakses URL tertentu, demi keamanan
7. jQuery akan digunakan bwat manggil live user access dalam form update user
8. Config pada CI akan disesuaikan untuk menghandle Query Strings pada URL


Langkah #2 Buwat Database dengan table tablena

CREATE TABLE `module` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(255) NOT NULL,
`permalink` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;

INSERT INTO `module` VALUES (1, 'Posting', 'posting');
INSERT INTO `module` VALUES (2, 'Banner', 'banner');
INSERT INTO `module` VALUES (3, 'Gallery', 'gallery');
INSERT INTO `module` VALUES (4, 'File Manager', 'filemanager');

CREATE TABLE `user` (
`id` int(11) NOT NULL auto_increment,
`email` varchar(255) NOT NULL,
`password` text NOT NULL,
`user_type` int(2) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;

INSERT INTO `user` VALUES (1, 'dremi@ganteng.com', '5afd3f8890e535868773eb4a351489d9126613d8', 1);
INSERT INTO `user` VALUES (2, 'aku@sang.pangeran.cintah.com', '5afd3f8890e535868773eb4a351489d9126613d8', 2);

CREATE TABLE `user_access` (
`user_id` int(11) NOT NULL,
`access_id` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `user_access` VALUES (2, 3);
INSERT INTO `user_access` VALUES (2, 1);

Langkah #3 Menyesuaikan Config Codeigniter (application/config/config.php)

dibawah ini adalah config yang gw pake untuk menjalankan misi kita kali ini:

$config['base_url'] = "http://localhost/tutorial-programming/ci_class/user_manager_ci_tut/"; //sesuaikan ama path di web serper lu
$config['index_page'] = "index.php/";

$config['uri_protocol'] = "PATH_INFO";

$config['url_suffix'] = "";

$config['language'] = "english";

$config['charset'] = "UTF-8";

$config['enable_hooks'] = FALSE;

$config['subclass_prefix'] = 'MY_';

$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';

/*PENTING BANGED*/

$config['enable_query_strings'] = TRUE;
$config['controller_trigger'] = 'x';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd'; // experimental not currently in use

/*END OF PENTING BANGED*/

$config['log_threshold'] = 0;

$config['log_path'] = '';

$config['log_date_format'] = 'Y-m-d H:i:s';

$config['cache_path'] = '';

$config['encryption_key'] = "NeO5C88iv7uo09U2E20iJFkaHJi0mPDm"; //kite bakalan make library encrypt, jadi ni kudu diisi. bebas key na, tapi berjumlah 32 karakter

$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_encrypt_cookie'] = FALSE;
$config['sess_use_database'] = FALSE;
$config['sess_table_name'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 300;

$config['cookie_prefix'] = "";
$config['cookie_domain'] = "";
$config['cookie_path'] = "/";

$config['global_xss_filtering'] = FALSE;

$config['compress_output'] = FALSE;

$config['time_reference'] = 'local';

$config['rewrite_short_tags'] = FALSE;

$config['proxy_ips'] = '';

Wokeh!!!!! lanjut ke langkah berikutnya

Langkah #4 Menyesuaikan Database Config (application/config/database.php)

$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "password";
$db['default']['database'] = "ci_class";

Langkah #5 Menyesuaikan Autload Config (application/config/autoload.php)

$autoload['libraries'] = array('database', 'session', 'encrypt');

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

Langkah #6 Siapin Template Helper (application/helpers/template_helper.php) => berisi fungsi – fungsi bwat menghandle kebutuhan di controller maupun viewer

< ?php

/**
* @author dr.emi
* @copyright 2010
*/

function loginTrigger()
{
$_this = & get_Instance();
if($_this->session->userdata('isLogin') == '')
{
redirect('user/login');
}
}

function CustomPassword($password)
{
$_this = & get_Instance();
return sha1($password.$_this->config->item('encryption_key'));
}

function get_table_fld($table){

$_this = & get_Instance();
$sql = "show columns from $table ";

$res = $_this->db->query($sql);
$rows = $res->result();
foreach($rows as $r){
$fld[] = $r->Field;
}
$fld = implode(';',$fld);

return ($fld);

}

function make_array_key($str){
$ar = array();
$key = explode(';',$str);
foreach($key as $k){
$t = array($k=>'');
$ar = array_merge($ar,$t);
}
return $ar;
}

function post2data($str){
$_this = & get_Instance();
$key = explode(';',$str);
foreach($key as $k){
if($_this->input->post($k)=='' ) continue;
$data[$k] = ltrim(rtrim($_this->input->post($k)));
}
return $data;
}

function store_data($table,& $data,$id){
$_this = & get_Instance();
$result=0;
if($_this->input->post($id)==''){
if($_this->db->insert($table,$data)) {
//$data[$id] = mysql_insert_id();
$result = mysql_insert_id();
}
} else {
$_this->db->where($id,$_this->input->post($id));
if($_this->db->update($table,$data)) //update($table = '', $set = NULL, $where = NULL, $limit = NULL)
$result = $_this->input->post($id);
}
return $result;
}

function delete_data($table,$key,$id)
{
$_this = & get_Instance();
$_this->db->query("delete from ".$table." where ".$key." ='".$id."'");
}

function getFieldValue($tbl='', $field='', $param='', $value='')
{
$_this = & get_Instance();
$sql = $_this->db->query("SELECT * FROM $tbl WHERE $param = '$value'");
if($sql->num_rows() !=0)
{
$r = $sql->row();
return $r->$field;
}
else
{
return false;
}
}

function getModuleAccessForm($query, $uid = '')
{
$_this = & get_Instance();
$per_column = 2;
$count = 0;
$return = '';
foreach($query->result() as $row)
{
$count ++;
$return .= '<div style="margin:0 10px 10px 0; float: left">';
if($uid != '')
{
$sql = $_this->db->query("select * from user_access WHERE user_id = '".$uid."' AND access_id = '".$row->id."'");
if($sql->num_rows() == 1)
{
$return .= form_checkbox('module_id[]', $row->id, TRUE) . $row->name;
}
else
{
$return .= form_checkbox('module_id[]', $row->id) . $row->name;
}
}
else
{
$return .= form_checkbox('module_id[]', $row->id) . $row->name;
}
$return .= '</div>';
if($count % $per_column == 0) { $return .= '<div style="clear:both; height: 1px;">&nbsp;</div>'; }
}
return $return;
}

function getModuleAccess($userID=0)
{
if($userID != 0)
{
$_this = & get_Instance();
$sql = $_this->db->query("select * from user_access where user_id = '".$userID."'");
if($sql->num_rows() != 0)
{
echo "<ul style='margin:10px 0 0 30px;padding:0'>";
foreach($sql->result_array() as $row)
{
echo "<li style='margin:0 0 10px 0;padding:0'>".getFieldValue('module', 'name', 'id', $row['access_id'])."</li>";
}
echo "</ul>";
}
}
}

function getModuleLink()
{
$_this = & get_Instance();
$sql = $_this->db->query("SELECT * FROM module ORDER BY name");
if($sql->num_rows() !=0)
{
foreach($sql->result() as $row)
{
echo anchor('admin/'.$row->permalink, $row->name) . ' | ';
}
}
else
{
return false;
}
}

function accessTrigger() {
$_this = & get_Instance();
if($_this->session->userdata('level')!=1) {
$modID = getFieldValue('module', 'id', 'permalink', $_this->uri->segment(2));
$sql = $_this->db->query("select * from user_access where user_id = '".$_this->session->userdata('user_id')."' AND access_id = '".$modID."' LIMIT 1");

//let's skip general access area to checked'
$skipped_area = array('','update','delete','save','access_area.php');

if($sql->num_rows() == 1 || in_array($_this->uri->segment(2), $skipped_area))
{
return true;
}
else
{
die('You don\'t have access to this area. Please contact your Super Administrator.');
}
}
}
?>

Langkah #7 Siapin Controller (application/controllers/)

Disini gw gak make model, karena mnurut gw mbikin ribet aja. Jadi kebanyakan bakalan gw tulis keperluan modelnya di HELPER bwatan sndiri.

Langkah #7.1 User (application/controllers/user.php) => User login controller

< ?php

class User extends Controller {

function User()
{
parent::Controller();
}

function index()
{
loginTrigger();
}

function login()
{
$this->load->view('login');
}

function doLogin()
{
$email = $this->input->post('email');
$password = $this->input->post('password');

$enc_pass = CustomPassword($password);

$sql = $this->db->query("SELECT * FROM user WHERE email='".$email."' AND password='".$enc_pass."' LIMIT 1");
if($sql->num_rows() == 1)
{
$row = $sql->row();
$data = array (
'isLogin' => 'yes',
'user_id' => $row->id,
'level' => $row->user_type
);
$this->session->set_userdata($data);
redirect('admin');
}
else
{
redirect('user/login');
}
}

function doLogout()
{
$data_session = array(
'isLogin' => $this->session->userdata('isLogin'),
'user_id' => $this->session->userdata('user_id'),
'level' => $this->session->userdata('level')
);
$this->session->unset_userdata($data_session);
redirect('user/login');
}
}

/* End of file welcome.php */
/* Location: ./system/application/controllers/welcome.php */

Langkah #7.2 Admin (application/controllers/admin.php) => Admin controller

fungsi- fungsi penting:

Update: satu fungsi ini bakalan menghandle form user. Trigger form nya adalah uri segment ke – 3, dengan ketentuan, kalok input user baru maka uri segment 3 kosong, sdangkan kalok mau update user dengan tujuan mengedit record, uri segment ke – 3 ini akan dikasi value berupa id record yang bersangkutan.

pada template_helper.php terdapat fungsi get_table_fld(), make_array_key(), post2data(), store_data(), dan delete_data()

fungsi fungsi tersebut bakalan dibutin di cotroller admin ini, bwat mempermudah aja berok!!

get_table_fld() => mengambil nama nama colom pada table di database

make_array_key() => menyajikan hasil keluaran fungsi get_table_fld() ke dalam array

post2data() => mengkonvert inputan post form ke dalam data yang akan dibutuhkan saat fungsi store_data() dipanggil

store_data() => menyimpan data kedalam table di database, dimana sesuai trigger form yang didapat yakni jika inputan post id / sesuai key dalam table bernilai kosong, maka data akan di insert ke dalam table. sedangkan jika tidak bernilai kosong, maka record bersangkutan akan diupdate pada tablenya.

delete_data() => menghapus data record bersangkutan

setelah komentar /*MODULE ACCESS*/ pada controller dibawah ini, gw mengeksekusi beberapa baris perintah. diantaranya bwat memvalidasi jika form digunakan sebagai update data bersangkutan / input data baru.

semua action dalam module access ini, pada akhirnya akan menghapus record akses user sebelumnya. jika form digunakan sebagai update data bersangkutan, maka user id yang akan mengakses module diambil dari post data id user, sdangkan jika form digunakan sebagai input data baru, maka user id yang akan mengakses module diambil dari user id terakhir yang diinsert pada table user.

/*MODULE ACCESS*/
if($this->input->post('id') != '')
{
$lastUserID = $this->input->post('id');
}
else
{
//get last id of user
$sqlLastUserID = $_this->db->query("SELECT * FROM user ORDER BY id DESC LIMIT 1");
$rowUserID = $sqlLastUserID->row();
$lastUserID = $rowUserID->id;
}
delete_data('user_access','user_id',$lastUserID);

berikut ini baris bwat menghandle data array dari checkbox yang bernilai module id

$i=0;
foreach($this->input->post('module_id') as $mod_id)
{
$i++;
//echo $mod_id;
//let's check record of access area user. if record == 0, we will insert new access, and if >= 1 let's delete the old record before then replace it with new isert record
//it's will protect user to have double or more than one access in same module

$sqlCheck = $this->db->query("SELECT * FROM user_access WHERE user_id = '".$lastUserID."' AND access_id = '".$mod_id."'");
if($sqlCheck->num_rows() == 0)
{
$this->db->query("INSERT INTO user_access(user_id, access_id) VALUES('".$lastUserID."', '".$mod_id."')");
}
else
{
delete_data('user_access','user_id',$lastUserID);
$this->db->query("INSERT INTO user_access(user_id, access_id) VALUES('".$lastUserID."', '".$mod_id."')");
}
}

Sedangkan bwat proses pergantian tipe user ke super administrator, kite perlu ngapus data aksesnya di table user_access, karena kita udah gak perlu lagi ngecek hak akses nya di table tersebut.

if($this->input->post('user_type') == 1)
{
delete_data('user_access','user_id',$this->input->post('id'));
}

dan ini file controller admin selengkapna

< ?php

class Admin extends Controller {

function Admin()
{
parent::Controller();
loginTrigger();
accessTrigger();
}

function index()
{
$sql = $this->db->get('user');
$data = array (
'query' => $sql
);
$this->load->view('admin', $data);
}

function update()
{
// Get Table Fields
$fields = get_table_fld('user');
$data = make_array_key($fields);

$this->db->where('id',$this->uri->segment(3));
$sql = $this->db->get('user');
$row = (array) $sql->row();

//query suplied for update template
$sql = $this->db->get('module');
$data_module = array ('query' => $sql);
//end of query suplied for update template

$data = array_merge($data,$data_module,$row);

$this->load->view('admin_update',$data);
}

function save()
{
if($this->input->post('id') != '')
{
if(!valid_email($this->input->post('email')))
{
$this->session->set_flashdata('message','Valid email field required!');
redirect("admin/update/".$this->input->post('id'),301);
exit();
}
}
else
{
if(!valid_email($this->input->post('email')))
{
$this->session->set_flashdata('message','Valid email field required!');
redirect("admin/update/",301);
exit();
}
elseif($this->input->post('password') == '')
{
$this->session->set_flashdata('message','Password field required!');
redirect("admin/update/",301);
exit();
}
}
$tabledata = get_table_fld('user');
$data = post2data($tabledata);
if($this->input->post('password') != '')
{
$data['password'] = CustomPassword($this->input->post('password'));
}

$id = store_data('user',$data,'id');

/*Let's process access area module here'*/
if($this->input->post('module_id') != '')
{
/*MODULE ACCESS*/
if($this->input->post('id') != '')
{
$lastUserID = $this->input->post('id');
}
else
{
//get last id of user
$sqlLastUserID = $_this->db->query("SELECT * FROM user ORDER BY id DESC LIMIT 1");
$rowUserID = $sqlLastUserID->row();
$lastUserID = $rowUserID->id;
}
delete_data('user_access','user_id',$lastUserID);

$i=0;
foreach($this->input->post('module_id') as $mod_id)
{
$i++;
//echo $mod_id;
//let's check record of access area user. if record == 0, we will insert new access, and if >= 1 let's delete the old record before then replace it with new isert record
//it's will protect user to have double or more than one access in same module

$sqlCheck = $this->db->query("SELECT * FROM user_access WHERE user_id = '".$lastUserID."' AND access_id = '".$mod_id."'");
if($sqlCheck->num_rows() == 0)
{
$this->db->query("INSERT INTO user_access(user_id, access_id) VALUES('".$lastUserID."', '".$mod_id."')");
}
else
{
delete_data('user_access','user_id',$lastUserID);
$this->db->query("INSERT INTO user_access(user_id, access_id) VALUES('".$lastUserID."', '".$mod_id."')");
}
}
}
##remove access rule to set all access trigger (set user as super administrator)##
if($this->input->post('user_type') == 1)
{
delete_data('user_access','user_id',$this->input->post('id'));
}
/*end of access area module*/

$this->session->set_flashdata('message','Data has been Updated/Saved Successfull!');

redirect("admin",301);
}

function delete()
{
delete_data('user','id',$this->uri->segment(3));
$this->session->set_flashdata('message','Data has been Deleted Successfull!');
redirect("admin",301);
}

/*Let's create sample of access area'*/
function banner()
{
$this->load->view('dummy');
}

function filemanager()
{
$this->load->view('dummy');
}

function gallery()
{
$this->load->view('dummy');
}

function posting()
{
$this->load->view('dummy');
}
}

/* End of file welcome.php */
/* Location: ./system/application/controllers/welcome.php */

Langkah #7.3 Access (application/controllers/access.php) => Access controller

controller ini berfungsi bwat menghadle live user access pada form user. agak sdikit beda pada controller ini. konsepnya kita bakalan manggil live user access berdasarkan routes config, yakni:

$route['admin/access_area.php'] = "access/index"; //harus ditambahkan pada application/config/routes.php

kite langsung aja ke controller nya:

< ?php

class Access extends Controller {

function Access()
{
parent::Controller();
loginTrigger();
accessTrigger();
}

function index()
{
//get the values
$access_id = preg_replace("/[^0-9]/", "", $this->input->get('access_id'));
$uid = preg_replace("/[^0-9]/", "", $this->input->get('uid'));

$sql = $this->db->get('module');
$data = array (
'query' => $sql,
'access_id' => $access_id,
'uid' => $uid
);
$this->load->view('access', $data);
}
}

/* End of file welcome.php */
/* Location: ./system/application/controllers/welcome.php */

baris ini bergungsi memparsing string inputan pada url:

$access_id = preg_replace("/[^0-9]/", "", $this->input->get('access_id'));
$uid = preg_replace("/[^0-9]/", "", $this->input->get('uid'));

dimana access_id dan uid bernilai 0-9, yang diambil dari parameter URL admin/access_area.php?access_id={int_value}&uid={int_value}

nah, dengan menggunakan routes $route['admin/access_area.php'] = “access/index”; kita nantinya bisa ngakses URL menggunakan admin/access_area.php?access_id={int_value}&uid={int_value} pada form live user access. nanti bakalan dibahas pada langkah pembuatan form user.

disinilah fungsinya mengenable query string dan menggunakan PATH_INFO pada sebagai uri protocol pada config.php

$config['enable_query_strings'] = TRUE;

$config['controller_trigger'] = 'x';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd'; // experimental not currently in use

$config['uri_protocol'] = "PATH_INFO";

dengan demikian kita bisa mengambil parameter URL access_id dan uid

Langkah #8 Siapin Viewer (application/views)

Langkah #8.1 Login viewer (application/views/login.php) => bwat nampilin form login user

< ?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?>
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<meta name="author" content="dr.emi" />
<link href="<? echo base_url(); ?>system/application/views/css/style.css" rel="stylesheet" type="text/css" />
<title>Login Form</title>
</link></head>

<body>

<div id="stylized" class="myform">
<form id="form" name="form" method="post" action="<?php echo site_url(); ?>user/doLogin">
<h1>Sign-in form</h1>
<p>Silakan login untuk mengakses user manager</p>

<label>Email</label>
<input type="text" name="email" id="email" class="input" />

<label>Password</label>
<input type="password" name="password" id="password" class="input" />

<input type="submit" name="submit" value="Sign-in" class="submit" />
<div class="spacer"></div>

</form>
</div>

</body>
</html>

Langkah #8.2 Admin viewer (application/views/admin.php) => bwat nampilin data data user

< ?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?>
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<meta name="author" content="dr.emi" />
<link href="<? echo base_url(); ?>system/application/views/css/style.css" rel="stylesheet" type="text/css" />
<title>Admin Area</title>
</link></head>

<body>

<h3>< ?php echo anchor('user/doLogout', 'Sign-out'); ?> | < ?php echo anchor('admin', 'User Manager'); ?> | < ?php getModuleLink(); ?>
</h3>
<p>< ?php echo anchor('admin/update', '+ Add New Data'); ?></p>
< ?php if($this->session->flashdata('message') != '') { echo '<p style="color:green">'.$this->session->flashdata('message').'</p>'; } ?>
<table border="0" cellpadding="4" cellspacing="1" bgcolor="gray">
<tr bgcolor="silver">
<td>No.</td>
<td>Email</td>
<td>Access Area</td>
<td>Option</td>
</tr>
< ?php
$i = 0;
foreach($query->result() as $row)
{
$i++;
?>
<tr bgcolor="white">
<td>< ?php echo $i; ?></td>
<td>< ?php echo $row->email; ?></td>
<td>
< ?php
if($row->user_type == 1)
{
$hakAkses = 'Super Administrator';
}
else
{
$hakAkses = 'Administrator';
}
?>
<h4>< ?php echo $hakAkses; ?></h4>
< ?php getModuleAccess($row->id); ?>
</td>
<td>
< ?php echo anchor('admin/update/'.$row->id, 'Edit'); ?>
<a href="javascript: void(0);" onclick="cf=confirm('Click OK to delete data: <?php echo "No. ".$i; ?>');if(cf)window.location='< ?php echo site_url().'admin/delete/'.$row->id; ?>';return false;" title="Delete < ?php echo "No. ".$i; ?>">
Delete
</a>
</td>
</tr>
< ?php
}
?>
</table>
</body>
</html>

Langkah #8.3 Admin_update viewer (application/views/admin_update.php) => bwat nampilin form user. Dimana bergungsi sebagai form input data baru dan edit data

Yang perlu diperhatiin adalah: penggunaan jQuery bwat mengakses live access user, konsepnya adalah: ketika user merubah pilihan pada select form Access Area maka hasil HTML akan ditampilkan pada DIV ID html_access_areajavasc

dimana html_access_area ini berisikan checkbox data data module yang tersedia dalam table module.

$(document).ready(function(){

$("#user_type").change(onRelectChange);
function onRelectChange(){
var pilih = $("#user_type option:selected");
if(pilih.val() != 0){
$().ajaxStart(function() {
$('#loading').show();
})
$.ajax({
type: "POST",
url: "< ?php echo site_url(); ?>admin/access_area.php?access_id="+pilih.val()+"&uid=< ?php echo $id; ?>",
success: function(data) {
//alert(pilih.val())
$("#toBeHidden").hide();
$("#html_access_area").html(data);
}
});
}
}
});

Gw perjelas lagi disni. penambahan routes $route['admin/access_area.php'] = “access/index”; berguna pada url dibawah ini:

url: "< ?php echo site_url(); ?>admin/access_area.php?access_id="+pilih.val()+"&uid=< ?php echo $id; ?>",

OK BRAD ??!!

jadi lengkapnye kayak gini:

< ?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?>
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<meta name="author" content="dr.emi" />
<link href="<? echo base_url(); ?>system/application/views/css/style.css" rel="stylesheet" type="text/css" />
<title>Admin Area &radic; Update Data</title>
<script src="<? echo base_url(); ?>system/application/views/js/jquery-1.4.2.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function(){

$("#user_type").change(onRelectChange);
function onRelectChange(){
var pilih = $("#user_type option:selected");
if(pilih.val() != 0){
$().ajaxStart(function() {
$('#loading').show();
})
$.ajax({
type: "POST",
url: "< ?php echo site_url(); ?>admin/access_area.php?access_id="+pilih.val()+"&uid=< ?php echo $id; ?>",
success: function(data) {
//alert(pilih.val())
$("#toBeHidden").hide();
$("#html_access_area").html(data);
}
});
}
}
});
</script>
</link></head>

<body>

<div id="stylized" class="myform">
< ?php if($this->session->flashdata('message') != '') { echo '<p style="color:red">'.$this->session->flashdata('message').'</p>'; } ?>
< ?php
$f_attributes = array('name' => 'form', 'id' => 'form');
echo form_open(site_url().'admin/save', $f_attributes);
?>
<input type="hidden" name="id" id="id" value="<?php echo $id; ?/>" />
<h1>User update form</h1>
<p>Dibawah ini merupakan form update data user</p>

<label>Email</label>
<input type="text" name="email" id="email" class="input" value="<?php echo $email; ?/>" />

<label>Password
<span class="small">Biarkan kosong jika tidak ingin dirubah</span>
</label>
<input type="password" name="password" id="password" class="input" />

<label>Access Area</label>
< ?php
$options = array(
'1' => 'Super Admin',
'2' => 'Admin'
);
$s_attributes = 'id = "user_type" class = "input"';
if($user_type == 1)
{
echo form_dropdown('user_type', $options, '1', $s_attributes);
$setAccessInfo = 'All access';
}
else
{
echo form_dropdown('user_type', $options, '2', $s_attributes);
$setAccessInfo = getModuleAccessForm($query, $id);
}
?>
<label>Module</label>
<div class="loaderBlock">
< ?php
if($id != '')
{
?>
<div id="loading" style="display:none"><em>Loading...</em></div><div id="toBeHidden">< ?php echo $setAccessInfo; ?></div><div id="html_access_area"></div>
< ?php
}
?>
<div id="loading" style="display:none"><em>Loading...</em></div><div id="html_access_area"></div>
</div>
<input type="submit" name="submit" value="Save" class="submit" />
<div class="spacer"></div>

< ?php echo form_close(); ?>
</div>

</body>
</html>

Langkah #8.4 Access viewer (application/views/access.php) => bwat nampilin checkbox module akses yang di load via controller Access

< ?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?>
< ?php
if($access_id != 1)
{
echo getModuleAccessForm($query, $uid);
}
else
{
echo "All access";
}
?>

Langkah #8.5 Dummy viewer (application/views/dummy.php) => ni mah bwat dummy aja, diload ketika module pada uri segment 2 diakses.

< ?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?>
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<meta name="author" content="dr.emi" />
<link href="<? echo base_url(); ?>system/application/views/css/style.css" rel="stylesheet" type="text/css" />
<title>< ?php echo $this->uri->segment(2); ?></title>
</link></head>

<body>

<div id="stylized" class="myform">
Helloo.... you are in < ?php echo $this->uri->segment(2); ?> area. So, you have access to do something here.
</div>

</body>
</html>

SEDIKIT PENJELASAN PADA FUNGSI accessTrigger() di file template_helper.php

//let's skip general access area to checked'
$skipped_area = array('','update','delete','save','access_area.php');

if($sql->num_rows() == 1 || in_array($_this->uri->segment(2), $skipped_area))
{
return true;
}
else
{
die('You don\'t have access to this area. Please contact your Super Administrator.');
}

baris ini dimaksudkan, untuk menskip/mengabaikan uri segment ke 2 yang tidak dikehendaki bwat dicek sebagai module akses user

$skipped_area = array('','update','delete','save','access_area.php');

kedepannya bisa lu kembangin, jadi si user bisa dibagi bagi lagi menjadi user yang bisa edit / delete saja atau cuma bisa liat data record.

OK BEROK!!! AYE LOM TIDUR NIH, lu pelajarin, smoga beruntung cekakakakaaka

KLIK DEMO DAN DOWNLOAD bwat yang berminat bwat belajar lebih lanjut.

Popularity: 100% [?]

Download Demo
Bookmark Subscribe
Hello my fox! Glad to see you today!

If you love my tutorial, please chose any action from the left button.

40 Comments

Hariez Said:  

PERTAMAX Gan..!!1
Whuah…cocok berokkkk…
ini yang ane cari-cari…. ampe ane bingung bikin ACL kaya gini…
ni buktinya :
http://cahsleman.com/access-control-list.html

izin sedot brur……..

Al-k Said:  

jadi inget dulu … waktu saya masih muda :D

dr.emi Said:  

@al-k inget naon kituk :D cekakakakak

Al-k Said:  

2 kata kang, rajin jeung ganteng … :-”

dr.emi Said:  

@hariez sikat aja berur :D cekakakakak

dr.emi Said:  

ganteng mah hanya untuk urang atuh!!!! :D

elmizan Said:  

ini dia yang gw tunggu2, thanks kang

dr.emi Said:  

@elmizan
ok mas berok

andrea Said:  

nice share… thx nambah ilmu

dr.emi Said:  

@andrea makasi kmbali

Gilank Said:  

Keren Bossss……….

Ijin Copas Ya…
:)
hehe

dr.emi Said:  

@Gilank
ok mas berok

yuke Said:  

izin donlod nggih

fandi Said:  

dr.waktu modul nya sya isi data kok ini yg keluar
“A PHP Error was encountered

Severity: Notice

Message: Undefined variable: query

Filename: views/angkatan.php

Line Number: 34

mohon pencerahanya

dr.emi Said:  

@fandi
silahkan di cek pada file views/angkatan.php line 34, seperti notice yang tampil di browser saat error. pesan Undefined variable: query biasanya menunjukkan variable query belum terdefinisi. pendefinisian, disesuaikan dengan script yang kamu buat, bisa di controller atau view. coba cek baris yang berkaitan dengan pembuatan variable query di controller/model nya, bisa jadi ada pada proses pemanggilan query SQL nya. karena view hanya mengeluarkan hasil nya saja.

fandi Said:  

tmbhin tutot bwt ci nya dr,soalnya tutot dari dremi mudh d pljrin,sy pgn ngrt soal ci

dr.emi Said:  

@fandi
ok mas bero….

dr.emi Said:  

@all : silakan dicek tutorial CI terbarunya

milen Said:  

bos, gimana caranya bikin wallpost macam FB dimana kalau kita masukin alamat web atau video dari youtube maka muncullah thumbnail dari web atau video tsb?? buat tutorialnya dong…Please…

Siregar Said:  

Kog ga bisa ane donlot ya.,page nya balek2. Paadahal keren tutorial ne.,

dr.emi Said:  

@Siregar

masih bisa didownload bero…, dan demonya juga masih bisa dicoba. mungkin kmarin pas server sedang gangguan. silahkan dicoba lagi..

thanks

Adi Saputra Said:  

Artikel yang bagus, sangat membantu…

nitip link gan..
http://tuto-rial.com/
salam

ade wahyu Said:  

mas itu cara buat menu kategori di samping kanan webnya pake apa ya??
bagi donggggg????
tengkyu

Ndeso Said:  

menarik gan…..trima kasih ilmunya……:-)

Mustikaning Karana Said:  

mau tanya mas remi. gmana bikin level user managemen. misal bikin user dengan hak akses yang bisa ditentukan dengan cek box. misal ada form1, form2, form3. jadi setiap user berbeda tergantung dengan yang dicek.

ieennu Said:  

akhir’y nemu juga tutor manajemen hak akses user T_T. belum dicoba sih, tapi mau ijin unduh. hatur nuhun~~ :D b

erny Said:  

kereeennn… makasiihhh… kapan2 balik lg! hehehe. :D

dr.emi Said:  

ma sama….. mas berok

ahmad Said:  

misi om dr.emi..,
mw nanya donk., koq saya terapkan di ci 2.1 ndak bisa ya.,,
munculnya gini nih.,

” The page isn’t redirecting properly.

Firefox has detected that the server is redirecting the request for this address in a way that will never complete.

* This problem can sometimes be caused by disabling or refusing to accept cookies. ”

apa butuh penyesuaian yg banyak ya biar bisa di ci 2.1

thx atas responnya.,

dr.emi Said:  

@ahmad

pada tutorial, menggunakan CI ver.1.7.2
pastikan htaccess pada webserver sudah aktif, dan cek configurasi lebih lanjutnya disini:

http://codeigniter.com/forums/viewthread/151471/#870482

Shafana Said:  

mkasi,sangat mmbantu.. :)
tpi ko databasenya ngga ya pas ak donlot mas,
hehe

Shafana Said:  

ngga databasenya mas, :)

dr.emi Said:  

@shafana
db nya bisa di create dengan mengeksekusi sintax sql di langkah 2

didi Said:  

Kebeloooooonnnn aran kk gagah

laguk at perajahan doang :D

dr.emi Said:  

@didi
ao, perajahin wah :D

dudu Said:  

tutorialnya sangat membantu, ijin copas mas

zir Said:  

weeeesss manteb.

Hi.. ! Wanna say anything about my tutorial ?
Just say it with fill the comment form.
Comment Form
 

 
 
 
 
 
Category
stack

Switch to our mobile site