Top Banner
http://www.dremi.info/tutorials/php/membuat-manajemen- hak-akses-user-dengan-codeigniter.html Membuat Manajemen Hak Akses User dengan Codeigniter November 6th, 2010 by dr.emi 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
23

acl hak akses di ci

Nov 11, 2014

Download

Documents

hazan komara

hak akses di ci
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: acl hak akses di ci

http://www.dremi.info/tutorials/php/membuat-manajemen-

hak-akses-user-dengan-codeigniter.html

Membuat Manajemen Hak Akses User dengan Codeigniter

November 6th, 2010 by dr.emi

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

Page 2: acl hak akses di ci

- 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

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

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, '[email protected]', '5afd3f8890e535868773eb4a351489d9126613d8', 1); INSERT INTO `user` VALUES (2, '[email protected]', '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);

Page 3: acl hak akses di ci

28

29

30

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

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

1 $config['base_url'] = "http://localhost/tutorial-

programming/ci_class/user_manager_ci_tut/"; //sesuaikan ama path di web

serper lu 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

$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;

Page 4: acl hak akses di ci

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

$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)

1

2

3

4

$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)

1

2

3

$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

1

2

3

4

5

6

< ?php

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

Page 5: acl hak akses di ci

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

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)==''){

Page 6: acl hak akses di ci

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

96

97

98

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; }

Page 7: acl hak akses di ci

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

} 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."'

Page 8: acl hak akses di ci

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

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

Page 9: acl hak akses di ci

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

< ?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'); }

Page 10: acl hak akses di ci

47

48

49

50

51

52

53

54

55

56

57

58

} /* 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.

Page 11: acl hak akses di ci

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

/*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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

$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.

Page 12: acl hak akses di ci

1

2

3

4

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

dan ini file controller admin selengkapna

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

< ?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'))) {

Page 13: acl hak akses di ci

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

$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

Page 14: acl hak akses di ci

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

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'); }

Page 15: acl hak akses di ci

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

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:

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

application/config/routes.php

kite langsung aja ke controller nya:

1

2

3

4

5

6

7

8

9

10

11

12

< ?php class Access extends Controller {

function Access() { parent::Controller(); loginTrigger(); accessTrigger(); } function index() { //get the values

Page 16: acl hak akses di ci

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

$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:

1

2 $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

1

2

3

4

5

6

7

$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)

Page 17: acl hak akses di ci

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

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

< ?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

1

2

3

4

5

6

7

8

9

< ?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" />

Page 18: acl hak akses di ci

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

<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>

Page 19: acl hak akses di ci

56

57

58

59

60

</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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

$(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:

1 url: "< ?php echo site_url();

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

OK BRAD ??!!

jadi lengkapnye kayak gini:

Page 20: acl hak akses di ci

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

< ?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; ?/>" />

Page 21: acl hak akses di ci

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

<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>

Page 22: acl hak akses di ci

93

Langkah #8.4 Access viewer (application/views/access.php) => bwat nampilin checkbox

module akses yang di load via controller Access

1

2

3

4

5

6

7

8

9

10

11

< ?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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

< ?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

1

2

3

4

//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),

Page 23: acl hak akses di ci

5

6

7

8

9

10

11

$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

1 $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.