/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
			
9
			//Load required libraries
10
			$this->load->database();
11
			$this->load->library('session');
12
		}
13
14
		//Queries the DB and for a matching username and password. Returns result or false.
15
		/*
16
		 *	Constructor
17
		 */ 
18
		public function login($username, $password)
19
		{			
20
			//Generate a salted hash
21
			$hash = $this->getSaltedHash($password);
22
	
23
			//Query-structure
24
			$this->db->select('userName, name, passwd, userType, ssn');
25
			$this->db->from('Users');
26
			$this->db->where('userName', $username);
27
			$this->db->where('passwd', $hash);
28
			$this->db->limit(1);
29
			
30
			//Execute query
31
			$query = $this->db->get();
32
			$result = $query->result();
33
			
34
			//If a matching DB record is found.
35
			if($result) {
36
				//Prepare session data
37
				$userDetails = array();
38
				foreach($result as $row) {
39
					$userDetails = array(
40
						'username' => $row->userName,
41
						'name' => $row->name,
42
						'usertype' => $row->userType,
43
						'ssn' => $row->ssn
44
					);
45
				}
46
				
47
				//Set session data
48
				$this->session->set_userdata('authenticated', $userDetails);
49
				
50
				//Return success
51
				return TRUE;
52
			} else {
53
				//Return fail
54
				return FALSE;
55
			}	
56
		}
57
58
59
		/*
60
		 *	This function logs the user out.
61
		 */ 
62
		public function logout() {		
63
			//Unset session data
64
			$this->session->unset_userdata('authenticated');
65
		}
66
		
67
68
		/*
69
		 *	This function return TRUE if the user is logged in and FALSE otherwise.
70
		 */ 
71
		public function isLoggedIn() {	
72
			if ($this->session->userdata('authenticated')) {
73
				return TRUE;
74
			} else {
75
				return FALSE;
76
			}
77
		}
78
		
79
		
80
		//Generates a password hash using a user-unique salt.
81
		private function getSaltedHash($pwd)
82
		{	
83
			/* Salt algorithm:
84
			 * Step 1: Get encryption key
85
			 * Step 2: Salt is set to password (reversed)
86
			 * Step 3: Salt is encrypted with MD5
87
			 * Step 4: Salt is reversed (again)
88
			 * Step 5: Salt is encrypted with SHA1
89
			 */
90
			
91
			$salt = '';
92
			
93
			//UNCOMMENT TO ACTIVATE SALT LATER IN DEVELOPMENT!!!
94
			//$salt = sha1(strrev(md5(strrev($this->config->item('encryption_key')))));
95
			
96
			//Generate SHA1 hash using salt
97
			$hash = sha1($salt.$pwd);
98
			
99
			return $hash;
100
		}
101
	}
102
?>