Newer
Older
Taddeus Kroes
committed
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?php
/**
* Security functions for user authentication and authorization.
*
* Usage example:
* <code>
* try {
* $security = webbasics\Security::getInstance();
*
* // Authentication: can the origin of the request be trusted?
*
* // Verify that a user is logged in
* $security->requireLogin();
*
* // Use a security token to verify that the request originated from a
* // trusted page. This is recommended if, for example, the script makes
* // changes to the database
* $security->requireToken($_REQUEST['token']);
*
* // Authorization: is the user allowed to request this page?
* $security->requireUserRole('admin');
*
* ...
*
* // Pass token to template so that it can be used in a submitted form or
* // AJAX request
* $template->set('token', $auth->generateToken());
*
* ...
*
* } catch(webbasics\AuthenticationFailed $e) {
* die('Get lost hacker!');
* } catch(webbasics\AuthorizationFailed $e) {
* http_response_code(403);
* die('You are not authorized to view this page.');
* }
* </code>
*
* Corresponding login controller example:
* <code>
* // Find the user using ActiveRecord (not part of the WebBasics library)
* $user = User::first(array('username' => $_POST['username']));
*
* if (!$user)
* die('Invalid username');
*
* // Current user is part of the
* $security = webbasics\Security::getInstance();
* $security->setUser($user);
*
* // Simple: use a plain password
* if (!$security->attemptPassword($user, $_POST['password']))
* die('Invalid password');
*
* // More secure: hash the password in a javascript function before
* // submitting the login form
* if (!$security->attemptPasswordHash($user, $_POST['password_hash']))
* die('Invalid password');
* </code>
*
* And the User model implementation used in the example above:
* <code>
Taddeus Kroes
committed
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
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
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
183
184
185
186
187
188
189
190
191
192
193
194
195
* use webbasics\AuthenticatedUser;
* use webbasics\AuthorizedUser;
*
* class User extends Model implements AuthenticatedUser, AuthorizedUser {
* function getUsername() {
* return $this->username;
* }
*
* function getPasswordHash() {
* return $this->password;
* }
*
* function getCookieToken() {
* return $this->cookie_token;
* }
*
* function setCookieToken($token) {
* $this->update_attribute('cookie_token', $token);
* }
*
* function getRegistrationToken() {
* return $this->registration_token;
* }
*
* function setRegistrationToken($token) {
* $this->update_attribute('registration_token', $token);
* }
*
* function getRole() {
* return $this->role;
* }
* }
* </code>
*
* @author Taddeus Kroes
* @date 05-10-2012
*/
namespace webbasics;
require_once 'base.php';
interface AuthenticatedUser {
function getUsername();
function getPasswordHash();
function getCookieToken();
function setCookieToken($token);
function getRegistrationToken();
function setRegistrationToken($token);
}
interface AuthorizedUser {
function getRole();
}
class Security {
const SESSION_TOKEN_NAME = 'auth_token';
const SESSION_NAME_USERDATA = 'auth_userdata';
private static $instance;
private $user;
static function getInstance() {
if (self::$instance === null)
self::$instance = new self;
return self::$instance;
}
private function __construct() {}
function generateToken() {
$session = Session::getInstance();
$token = sha1(self::generateRandomString(10));
$session->set(self::SESSION_TOKEN_NAME, $token);
return $token;
}
function requireToken($request_token) {
if ($request_token != $this->getSavedToken())
throw new AuthenticationFailed('invalid token "%s"', $request_token);
}
private function getSavedToken() {
$session = Session::getInstance();
if (!$session->isRegistered(self::SESSION_TOKEN_NAME))
throw new AuthenticationError('no token saved in session');
return $session->get(self::SESSION_TOKEN_NAME);
}
function sessionDataExists() {
return Session::getInstance()->areRegistered(array(
self::SESSION_TOKEN_NAME, self::SESSION_NAME_USERDATA));
}
function requireLogin() {
}
function requireUserRole() {
}
//function setUser(AuthenticatedUser $user) {
// $this->user = $user;
//}
static function generateRandomString($length) {
$CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUWXYZ01234567890123456789';
$string = '';
srand(time());
for ($i = 0; $i < $length; $i++)
$string .= $CHARS[rand(0, strlen($CHARS) - 1)];
return $string;
}
}
class AuthenticationError extends FormattedException {}
class AuthenticationFailed extends FormattedException {}
class AuthorizationError extends FormattedException {}
class AuthorizationFailed extends FormattedException {}
?>