/lenasys/trunk

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/lenasys/trunk
36.3.1 by Daniel Hermansson
Added login functionality
1
<?php
2
	Class User extends CI_Model {
3
		/*
4
		 *	Constructor
5
		 */
6
		function __construct() {
7
			parent::__construct();
8
			
53.2.2 by Daniel Hermansson
Activated hash salting, and cleaned up some code.
9
			//Load required libraries and drivers
36.3.1 by Daniel Hermansson
Added login functionality
10
			$this->load->database();
11
			$this->load->library('session');
12
		}
13
53.2.2 by Daniel Hermansson
Activated hash salting, and cleaned up some code.
14
15
		/*
16
		 *	This function returns the users password hint (or FALSE if user isn't logged in).
17
		 *  RESTRICTED-LEVEL: None
18
		 */ 
19
		public function getPasswordHint($user) {
20
			//Query-structure
21
			$this->db->select('passwdHint');
22
			$this->db->from('Users');
23
			$this->db->where('userName', $user);
24
			$this->db->limit(1);
25
			
26
			//Execute query
27
			$query = $this->db->get();
28
			$result = $query->result();
29
			
30
			//If a matching DB record is found.
31
			if($result) {
32
			    foreach($result as $row) {
33
			    	$hint = $row->passwdHint;
34
			    	
35
			    	//Return hint
36
			    	return $hint;
37
			    }
38
			}
39
			
40
			//No such user
41
			return FALSE;
42
		}
43
44
36.3.1 by Daniel Hermansson
Added login functionality
45
		/*
52.1.1 by b11johgu
Added controllers for examplepage, templatelayout.
46
		 *	This function logs the user in (returns FALSE on fail).
53.2.2 by Daniel Hermansson
Activated hash salting, and cleaned up some code.
47
		 *  RESTRICTED-LEVEL: None
62.1.1 by Daniel Hermansson
Cleaned code and added logging of logins
48
		 */
49
		public function login($username, $password) {			
36.3.1 by Daniel Hermansson
Added login functionality
50
			//Generate a salted hash
51
			$hash = $this->getSaltedHash($password);
52
	
53
			//Query-structure
54
			$this->db->select('userName, name, passwd, userType, ssn');
55
			$this->db->from('Users');
56
			$this->db->where('userName', $username);
57
			$this->db->where('passwd', $hash);
58
			$this->db->limit(1);
59
			
60
			//Execute query
61
			$query = $this->db->get();
62
			$result = $query->result();
63
			
64
			//If a matching DB record is found.
65
			if($result) {
66
				//Prepare session data
67
				$userDetails = array();
68
				foreach($result as $row) {
69
					$userDetails = array(
70
						'username' => $row->userName,
71
						'name' => $row->name,
72
						'usertype' => $row->userType,
73
						'ssn' => $row->ssn
74
					);
75
				}
76
				
77
				//Set session data
78
				$this->session->set_userdata('authenticated', $userDetails);
79
				
62.1.1 by Daniel Hermansson
Cleaned code and added logging of logins
80
				//Log attempt as valid
81
				$this->logLogin($username, 1);
82
				
36.3.1 by Daniel Hermansson
Added login functionality
83
				//Return success
84
				return TRUE;
52.1.1 by b11johgu
Added controllers for examplepage, templatelayout.
85
			}
86
62.1.1 by Daniel Hermansson
Cleaned code and added logging of logins
87
			//Log attempt as invalid
88
			$this->logLogin($username, 0);
89
52.1.1 by b11johgu
Added controllers for examplepage, templatelayout.
90
			//Return fail
62.1.1 by Daniel Hermansson
Cleaned code and added logging of logins
91
			return FALSE;
36.3.1 by Daniel Hermansson
Added login functionality
92
		}
93
94
95
		/*
96
		 *	This function logs the user out.
53.2.2 by Daniel Hermansson
Activated hash salting, and cleaned up some code.
97
		 *  RESTRICTED-LEVEL: Self
36.3.1 by Daniel Hermansson
Added login functionality
98
		 */ 
99
		public function logout() {		
100
			//Unset session data
101
			$this->session->unset_userdata('authenticated');
102
		}
103
		
104
105
		/*
52.1.1 by b11johgu
Added controllers for examplepage, templatelayout.
106
		 *	This function changes the users password.
53.2.2 by Daniel Hermansson
Activated hash salting, and cleaned up some code.
107
		 *  RESTRICTED-LEVEL: Self
52.1.1 by b11johgu
Added controllers for examplepage, templatelayout.
108
		 */ 
109
		public function changePassword($pwdOld, $pwdNew, $pwdHint) {
110
			//Check that a user is logged in.
111
			if($this->isLoggedIn()) {
112
				$user = $this->getUserName();
113
				$oldHash = $this->getSaltedHash($pwdOld);
114
				$newHash = $this->getSaltedHash($pwdNew);
115
				
53.2.2 by Daniel Hermansson
Activated hash salting, and cleaned up some code.
116
				//Validate input with database
52.1.1 by b11johgu
Added controllers for examplepage, templatelayout.
117
				$this->db->select('userName');
118
				$this->db->from('Users');
119
				$this->db->where('userName', $user);
120
				$this->db->where('passwd', $oldHash);
121
				$this->db->limit(1);
122
				$query = $this->db->get();
123
				$result = $query->result();
124
				
53.2.2 by Daniel Hermansson
Activated hash salting, and cleaned up some code.
125
				//If a matching DB record is found, update database.
52.1.1 by b11johgu
Added controllers for examplepage, templatelayout.
126
				if($result) {
127
					$data = array(
128
						'passwd' => $newHash,
129
						'passwdHint' => $pwdHint
130
					);
131
					
132
					$this->db->where('userName', $user);
133
					$this->db->update('Users', $data);
134
					
135
					//Return Success!
136
					return TRUE;							
137
				}
138
			}
139
			
140
			//Return error
141
			return FALSE;
142
		}
143
53.2.2 by Daniel Hermansson
Activated hash salting, and cleaned up some code.
144
145
		/*
146
		 *	This function registers user into the database.
147
		 *  RESTRICTED-LEVEL: Teacher
148
		 */
149
		public function addUser($userName, $name, $ssn, $password, $userType, $pwdHint) {
150
			//Check that a user is logged in and has the right privileges (is teacher)
151
			if($this->isLoggedIn() && $this->getUserType() === 'Teacher') {
152
				//Generate a salted hash
153
				$hash = $this->getSaltedHash($password);
154
				
155
				//Query-structure (All values are escaped automatically by codeigninte, producing safer queries.)
156
				$this->db->set('userName', $userName);
157
				$this->db->set('name', $name);
158
				$this->db->set('ssn', $ssn);
159
				$this->db->set('passwd', $password);
160
				$this->db->set('userType', $userType);
161
				$this->db->set('passwdHint', $pwdHint);
162
				$result = $this->db->insert('Users');
163
				
164
				//Check for my-sql error
165
				if($result) {
166
					//Return success
167
					return TRUE;
168
				} 
169
			}
170
			
171
			//Return error
172
			return FALSE;
173
		}
174
		
52.1.1 by b11johgu
Added controllers for examplepage, templatelayout.
175
		
176
		/*
177
		 *	This function removes users from the database.
53.2.2 by Daniel Hermansson
Activated hash salting, and cleaned up some code.
178
		 *  RESTRICTED-LEVEL: Teacher
52.1.1 by b11johgu
Added controllers for examplepage, templatelayout.
179
		 */ 
180
		public function removeUser($userName) {
181
			//Check that a user is logged in, has the right privileges (is teacher) and not is the users own username.
182
			if($this->isLoggedIn() && $this->getUserType() === 'Teacher' && $this->getUserName() != $userName) {
183
				//Query-structure
184
				$this->db->where('userName', $userName);
185
				$result = $this->db->delete('Users');		 
186
				
187
				//Check for my-sql error
188
				if($result) {
189
					//Return success
190
					return TRUE;
191
				} 
192
			}
193
			
194
			//Return error
195
			return FALSE;
196
		}
197
		
62.1.2 by Daniel Hermansson
Added functionality for resetting a users password
198
		
199
		/*
200
		 *	This reset the password for the user.
201
		 *  RESTRICTED-LEVEL: Teacher
202
		 */
203
		public function resetUser($userName) {
204
			//Check that a user is logged in, has the right privileges (is teacher) and not is the users own username.
205
			if($this->isLoggedIn() && $this->getUserType() === 'Teacher' && $this->getUserName() != $userName) {
206
				//Check user type
207
				$this->db->select('userName, userType, ssn, email');
208
				$this->db->from('Users');
209
				$this->db->where('userName', $username);
210
				$this->db->limit(1);
211
				$query = $this->db->get();
212
				$result = $query->result();
213
				
214
				//If a matching DB record is found.
215
				if($result) {
216
					//Prepare new hash depending on user-type
217
					$newPwdHash = '';
218
					
219
					if ($row->userType == 'Student') {
220
						$newPwdHash = $this->getSaltedHash($row->ssn);
221
					}
222
					else if ($row->userType == 'Teacher') {
223
						//$newPwdHash = $this->getSaltedHash($row->email);
224
						$newPwdHash = $this->getSaltedHash($row->email);
225
					}
226
					
227
					//Execute reset
228
					$data = array(
229
						'passwd' => $newPwdHash,
230
						'passwdHint' => 'default'
231
					);
232
					
233
					$this->db->where('userName', $userName);
234
					$this->db->update('Users', $data);
235
					
236
					//Return Success!
237
					return TRUE;
238
				}
239
			}
240
			
241
			//Return error
242
			return FALSE;
243
		}
244
		
62.1.3 by Daniel Hermansson
Added functionality for parsing a user list from ladok into a user array (for future use)
245
		
246
		/*
247
		 *	This parses a user list from ladok and returns an array with users.
248
		 *  RESTRICTED-LEVEL: Teacher
249
		 */
250
		public function parseLadok($string) {
251
			//Check that a user is logged in and has the right privileges (is teacher).
252
			if($this->isLoggedIn() && $this->getUserType() === 'Teacher') {
253
				$userArray = array();
254
				
255
				//Populate array with users from ladok
256
				$ladokUsers = preg_split( '/\r\n|\r|\n/', $string);
257
				
258
				//Trim lines
259
				foreach ($ladokUsers as $key => &$value) {
260
					$ladokUsers[$key] = trim($ladokUsers[$key]);
261
				}
262
				
263
				//Split after last name
264
				foreach ($ladokUsers as $key => &$value) {
265
					$ladokUsers[$key] = explode(',', trim($ladokUsers[$key]));
266
				}
267
				
268
				//Replace whitespaces and tabs with divider.
269
				foreach ($ladokUsers as $key => &$value) {
270
					foreach ($ladokUsers[$key] as $key2 => &$value2) {
271
						$ladokUsers[$key][$key2] = preg_replace('/\s+/', ' ', trim($ladokUsers[$key][$key2]));
272
					}
273
				}
274
				
275
				//Explode on whitespace on second split
276
				foreach ($ladokUsers as $key => &$value) {
277
					$ladokUsers[$key][1] = explode(' ', trim($ladokUsers[$key][1]));
278
				}	
279
				
280
				//Generate user array
281
				$i = 0;
282
				foreach ($ladokUsers as $key => $value) {
283
					$userArray[$i]['ssn'] = substr($ladokUsers[$key][0], 0, 11);
284
					$userArray[$i]['lastname'] = substr($ladokUsers[$key][0], 12, strlen($ladokUsers[$key][0]));
285
					$userArray[$i]['firstname'] = $ladokUsers[$key][1][0];
286
					$userArray[$i]['email'] = $ladokUsers[$key][1][3];
287
					$i++;
288
				}
289
				
290
				//Return parsed user array
291
				return $userArray;
292
			}
293
			
294
			//If not authed
295
			return FALSE;
296
		}
297
		
52.1.1 by b11johgu
Added controllers for examplepage, templatelayout.
298
299
		/*
53.2.2 by Daniel Hermansson
Activated hash salting, and cleaned up some code.
300
		 *	Generates a salted password hash, encrypted with sha1.
62.1.1 by Daniel Hermansson
Cleaned code and added logging of logins
301
		 *  RESTRICTED-LEVEL: System
302
		 */
53.2.2 by Daniel Hermansson
Activated hash salting, and cleaned up some code.
303
		private function getSaltedHash($pwd) {
304
			//Salt = CodeIgniters encryption-key from config
305
			$salt = $this->config->item('encryption_key');
36.3.1 by Daniel Hermansson
Added login functionality
306
			
307
			//Generate SHA1 hash using salt
308
			$hash = sha1($salt.$pwd);
309
			
310
			return $hash;
311
		}
62.1.1 by Daniel Hermansson
Cleaned code and added logging of logins
312
313
314
		/*
315
		 *	Log the login attempt.
316
		 *  RESTRICTED-LEVEL: System
317
		 */
318
		private function logLogin($userName, $valid) {
319
			$data = array(
320
				'userName' => $userName,
321
				'userAgent' => $this->session->userdata('user_agent'),
322
				'userIP' => $this->session->userdata('ip_address'),
323
				'browserID' => $this->session->userdata('session_id'), //TODO: change later?
324
				'success' => $valid
325
			);
326
			
327
			$this->db->insert('logUserLoginAttempts', $data);
328
		}
53.2.2 by Daniel Hermansson
Activated hash salting, and cleaned up some code.
329
		
330
		
331
		/*
332
		 *	This function return TRUE if the user is logged in and FALSE otherwise.
333
		 *  RESTRICTED-LEVEL: System
334
		 */ 
335
		public function isLoggedIn() {	
336
			if ($this->session->userdata('authenticated')) {
337
				return TRUE;
338
			}
339
			
340
			return FALSE;
341
		}
342
		
343
		
344
		/*
345
		 *	This function returns the users type (or FALSE if user isn't logged in).
346
		 *  RESTRICTED-LEVEL: System
347
		 */ 
348
		public function getUserType() {	
349
			if($this->isLoggedIn()) {
350
				$temp = $this->session->userdata('authenticated');
351
				return $temp['usertype'];
352
			}
353
			
354
			return FALSE;
355
		}
356
		
357
		
358
		/*
62.1.4 by Daniel Hermansson
Added method for checking if its the first time a user logs on or not (to know when to require them to change password)
359
		 *	This function returns a boolean containing information if it is the first login.
360
		 *  RESTRICTED-LEVEL: System
361
		 */
362
		public function isFirstLogin() {
363
			if($this->isLoggedIn()) {
364
				$temp = $this->session->userdata('authenticated');
365
				if ($temp['firstLogin'] == 1) {
366
					return TRUE;
367
				}
368
			}
369
			
370
			return FALSE;
371
		}
372
		
373
		
374
		/*
53.2.2 by Daniel Hermansson
Activated hash salting, and cleaned up some code.
375
		 *	This function returns the username (or FALSE if user isn't logged in).
376
		 *  RESTRICTED-LEVEL: System
377
		 */ 
378
		public function getUserName() {	
379
			if($this->isLoggedIn()) {
380
				$temp = $this->session->userdata('authenticated');
381
				return $temp['username'];
382
			}
383
			
384
			return FALSE;
385
		}
36.3.1 by Daniel Hermansson
Added login functionality
386
	}
387
?>