Bin will be removed on June 1, 2014 in favor of http://gist.github.com. Please save all your pastes before then. So long, and thanks for all the fish!×
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
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
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
196
197
198
199
200
201
202
203
204
205
206
207
208
<?php
// assumes you have a User model with fields 'id', 'username', 'password', 'auth_key', 'admin', 'ip_address'
 
App::import('Security');
 
class PieAuthComponent extends Object {
 
    // do not modify
    var $components = array('Session','Cookie');
 
    // options
    var $cookieTime = '2 weeks';
    var $cookieKey = 'gyPCToKcrdnxkchDbwzpB8X8oR5M4HZdadafNtwAIofgnrB1feni7vZmkU';
    var $cookieName = 'data';
   
    var $recursive = -1;
   
    var $loginRedirect = '/';
    var $logoutRedirect = '/';
    var $authRedirect = '/';
    var $autoRedirect = true;
 
    var $loginError = 'Login failed. Invalid username or password.';
    var $logoutError = 'Logout failed. Invalid/missing logout key.';
    var $authError = 'You are not authorized to access that location.';
 
    var $flashLayout = 'default';
 
    function initialize(&$controller) {
        $this->controller =& $controller;
        $this->referer = $this->controller->referer();
        $this->domain = '.'.$this->getDomain();
        $this->adminPrefix = Configure::read('Routing.admin');
 
        $this->Cookie->name = $this->cookieName;
        $this->Cookie->time = $this->cookieTime;
        $this->Cookie->domain = $this->domain;
        $this->Cookie->secure = false;
        $this->Cookie->key = $this->cookieKey;
        $this->Cookie->path = '/'; 
 
        $this->Session->host = null;
        ini_set('session.cookie_domain', $this->domain);
    }
 
    function startup(&$controller) {
        if($this->controller->action == 'login')
            $this->login();
        if($this->controller->action == 'logout')
            $this->logout();
       
        $this->identify();
        $this->authorize();
    }
 
    function login() {
        if(!empty($this->controller->data)) {
            $model = new User;
           
            $userData = $model->find(
                'first',
                array(
                    'conditions' => array(
                        'username' => $this->controller->data['User']['username'],
                        'password' => $this->hash($this->controller->data['User']['password'])
                    ),
                    'recursive' => -1,
                    'fields' => 'id'
                )
            );
           
            if($userData) {
                $userData['User']['auth_key'] = $this->randstr(32);
                $this->Session->write($userData);
                $this->setLogoutKey();
               
                if($this->controller->data['User']['remember_me']) {
                    $this->Cookie->write($userData, null, true, $this->cookieTime);
                } else {
                    $this->Cookie->destroy();
                }
 
                $userData['User']['ip_address'] = env('REMOTE_ADDR');
                $model->save($userData);
 
                $this->redirect($this->loginRedirect);
            } else {
                $this->setFlash($this->loginError);
            }
        }
    }
 
    function logout() {
        if(isset($this->controller->params['pass'][0]) && $this->controller->params['pass'][0] == $this->Session->read('User.logout_key')) {
            $userData = array(
                'id' => $this->Session->read('User.id'),
                'auth_key' => null
            );
            $model = new User;
            $model->save($userData);
            $this->Session->destroy();
            $this->Cookie->destroy();
        } else {
            $this->setFlash($this->logoutError);
        }
 
        $this->redirect($this->logoutRedirect);
    }
 
    function identify() {
        $this->data['logged_in'] = false;
       
        // login using cookie
        $userCookie = $this->Cookie->read();
        if(!$this->Session->check('User') && !empty($userCookie)) {
            $this->Session->write($userCookie);
            $this->setLogoutKey();
            $this->refreshCookie();
        }
       
        // read user data and set login status
        if($this->Session->check('User')) {
            $model = new User;
 
            $this->data = $model->find(
                'first',
                array(
                    'conditions' => array(
                        'User.id' => $this->Session->read('User.id'),
                        'User.auth_key' => $this->Session->read('User.auth_key'),
                        'User.ip_address' => env('REMOTE_ADDR'),
                    ),
                    'recursive' => $this->recursive
                )
            );
 
            if($this->data) {
                $this->data['logged_in'] = true;
                unset($this->data['User']['password']);
            }
        }
 
        $this->controller->set('PieAuth', $this->data);
    }
 
    function isAuthorized() {
        $controllerActions = array_diff(get_class_methods($this->controller), get_class_methods(get_parent_class($this->controller)));
        if(in_array('isAuthorized', $controllerActions)) {
            return $this->controller->isAuthorized;
        } else {
            if($this->data['logged_in'] && $this->data['User']['admin'])
                return true;
            $allowedActions = array_filter($controllerActions, array(&$this, 'allowedAction'));
            return in_array($this->controller->action, $allowedActions);
        }
    }
 
    function allowedAction($action) {
        return (substr($action,0,6) != $this->adminPrefix.'_') && ($action[0] != '_');
    }
 
    function authorize() {
        if(!$this->isAuthorized()) {
            $this->setFlash($this->authError);
            $this->redirect($this->authRedirect);
        }
    }
 
    function refreshCookie() {
        $this->Cookie->write($this->Cookie->read(), null, true, $this->cookieTime);
    }
 
    function setLogoutKey() {
        $this->Session->write('User.logout_key', $this->randstr(8));
    }
 
    function redirect($url) {
        if(!$this->autoRedirect || empty($this->referer) || $this->referer == $this->controller->here)
            $this->controller->redirect($url);
        else
            $this->controller->redirect($this->referer);
    }
 
    function setFlash($message) {
        $this->Session->setFlash($message, $this->flashLayout, array('class' => 'error message'), 'pieAuth');
    }
 
    function getDomain() {
        preg_match('`[^\.]+\.[^\.]+$`', env('HTTP_HOST'), $matches);
        return $matches[0];
    }
 
    function hash($str) {
        return Security::hash($str, null, true);
    }
 
    function randstr($len=32, $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {
        $i = 0;
        $str = '';
        $randmax = strlen($chars)-1;
 
        for($i=0; $i<$len; ++$i) {
            $str .= $chars[mt_rand(0,$randmax)];
        }
 
        return $str;
    }
}