UserController   B
last analyzed

Complexity

Total Complexity 36

Size/Duplication

Total Lines 234
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 12

Importance

Changes 0
Metric Value
wmc 36
c 0
b 0
f 0
lcom 1
cbo 12
dl 0
loc 234
rs 8.8

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A indexAction() 0 7 2
C loginAction() 0 44 8
A logoutAction() 0 14 3
C authenticateAction() 0 39 8
C registerAction() 0 64 14
1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the MIT license.
17
 */
18
19
namespace ZfcUser\Controller;
20
21
use Zend\Form\Form;
22
use Zend\Mvc\Controller\AbstractActionController;
23
use Zend\Stdlib\ResponseInterface as Response;
24
use Zend\Stdlib\Parameters;
25
use Zend\View\Model\ViewModel;
26
use ZfcUser\Service\User as UserService;
27
use ZfcUser\Options\UserControllerOptionsInterface;
28
29
class UserController extends AbstractActionController
30
{
31
    const ROUTE_LOGIN        = 'zfcuser/login';
32
    const ROUTE_REGISTER     = 'zfcuser/register';
33
34
    const CONTROLLER_NAME    = 'zfcuser';
35
36
    /**
37
     * @var UserService
38
     */
39
    protected $userService;
40
41
    /**
42
     * @var Form
43
     */
44
    protected $loginForm;
45
46
    /**
47
     * @var Form
48
     */
49
    protected $registerForm;
50
51
    /**
52
     * @todo Make this dynamic / translation-friendly
53
     * @var string
54
     */
55
    protected $failedLoginMessage = 'Authentication failed. Please try again.';
56
57
    /**
58
     * @var string
59
     */
60
    protected $loginNamespace = 'zfcuser-login-form';
61
62
    /**
63
     * @var UserControllerOptionsInterface
64
     */
65
    protected $options;
66
67
    public function __construct($userService, $options, $registerForm, $loginForm)
68
    {
69
        $this->userService = $userService;
70
        $this->options = $options;
71
        $this->registerForm = $registerForm;
72
        $this->loginForm = $loginForm;
73
    }
74
    
75
    /**
76
     * User page
77
     */
78
    public function indexAction()
79
    {
80
        if (!$this->zfcUserAuthentication()->hasIdentity()) {
81
            return $this->redirect()->toRoute(static::ROUTE_LOGIN);
82
        }
83
        return new ViewModel();
84
    }
85
86
    /**
87
     * Login form
88
     */
89
    public function loginAction()
90
    {
91
        if ($this->zfcUserAuthentication()->hasIdentity()) {
92
            return $this->redirect()->toRoute($this->options->getLoginRedirectRoute());
93
        }
94
95
        $request = $this->getRequest();
96
        $post    = $request->getPost();
97
98
        $form    = $this->loginForm;
99
        $fm = $this->flashMessenger()->setNamespace($this->loginNamespace)->getMessages();
100
        if (isset($fm[0])) {
101
            $this->loginForm->setMessages(
102
                array('identity' => array($fm[0]))
103
            );
104
        }
105
106
        if ($this->options->getUseRedirectParameterIfPresent()) {
107
            $redirect = $request->getQuery()->get('redirect', (!empty($post['redirect'])) ? $post['redirect'] : false);
108
        } else {
109
            $redirect = false;
110
        }
111
112
        if (!$request->isPost()) {
113
            return array(
114
                'loginForm' => $form,
115
                'redirect'  => $redirect,
116
                'enableRegistration' => $this->options->getEnableRegistration(),
117
            );
118
        }
119
120
        $form->setData($post);
121
122
        if (!$form->isValid()) {
123
            $this->flashMessenger()->setNamespace($this->loginNamespace)->addMessage($this->failedLoginMessage);
124
            return $this->redirect()->toUrl($this->url()->fromRoute(static::ROUTE_LOGIN).($redirect ? '?redirect='. rawurlencode($redirect) : ''));
125
        }
126
127
        // clear adapters
128
        $this->zfcUserAuthentication()->getAuthAdapter()->resetAdapters();
129
        $this->zfcUserAuthentication()->getAuthService()->clearIdentity();
130
131
        return $this->forward()->dispatch(static::CONTROLLER_NAME, array('action' => 'authenticate'));
132
    }
133
134
    /**
135
     * Logout and clear the identity
136
     */
137
    public function logoutAction()
138
    {
139
        $this->zfcUserAuthentication()->getAuthAdapter()->resetAdapters();
140
        $this->zfcUserAuthentication()->getAuthAdapter()->logoutAdapters();
141
        $this->zfcUserAuthentication()->getAuthService()->clearIdentity();
142
143
        $redirect = $this->params()->fromPost('redirect', $this->params()->fromQuery('redirect', false));
144
145
        if ($this->options->getUseRedirectParameterIfPresent() && $redirect) {
146
            return $this->redirect()->toRoute($redirect);
147
        }
148
149
        return $this->redirect()->toRoute($this->options->getLogoutRedirectRoute());
150
    }
151
152
    /**
153
     * General-purpose authentication action
154
     */
155
    public function authenticateAction()
156
    {
157
        if ($this->zfcUserAuthentication()->hasIdentity()) {
158
            return $this->redirect()->toRoute($this->options->getLoginRedirectRoute());
159
        }
160
161
        $adapter = $this->zfcUserAuthentication()->getAuthAdapter();
162
        $redirect = $this->params()->fromPost('redirect', $this->params()->fromQuery('redirect', false));
163
164
        $result = $adapter->prepareForAuthentication($this->getRequest());
165
166
        // Return early if an adapter returned a response
167
        if ($result instanceof Response) {
168
            return $result;
169
        }
170
171
        $auth = $this->zfcUserAuthentication()->getAuthService()->authenticate($adapter);
172
173
        if (!$auth->isValid()) {
174
            $this->flashMessenger()->setNamespace($this->loginNamespace)->addMessage($this->failedLoginMessage);
175
            $adapter->resetAdapters();
176
            return $this->redirect()->toUrl(
177
                $this->url()->fromRoute(static::ROUTE_LOGIN) .
178
                ($redirect ? '?redirect='. rawurlencode($redirect) : '')
179
            );
180
        }
181
182
        if ($this->options->getUseRedirectParameterIfPresent() && $redirect) {
183
            return $this->redirect()->toRoute($redirect);
184
        }
185
186
        $route = $this->options->getLoginRedirectRoute();
187
188
        if (is_callable($route)) {
189
            $route = $route($this->zfcUserAuthentication()->getIdentity());
190
        }
191
192
        return $this->redirect()->toRoute($route);
193
    }
194
195
    /**
196
     * Register new user
197
     */
198
    public function registerAction()
199
    {
200
        // if the user is logged in, we don't need to register
201
        if ($this->zfcUserAuthentication()->hasIdentity()) {
202
            // redirect to the login redirect route
203
            return $this->redirect()->toRoute($this->options->getLoginRedirectRoute());
204
        }
205
        // if registration is disabled
206
        if (!$this->options->getEnableRegistration()) {
207
            return array('enableRegistration' => false);
208
        }
209
210
        $request = $this->getRequest();
211
        $service = $this->userService;
212
        $form = $this->registerForm;
213
214
        if ($this->options->getUseRedirectParameterIfPresent() && $request->getQuery()->get('redirect')) {
215
            $redirect = $request->getQuery()->get('redirect');
216
        } else {
217
            $redirect = false;
218
        }
219
220
        $redirectUrl = $this->url()->fromRoute(static::ROUTE_REGISTER)
221
            . ($redirect ? '?redirect=' . rawurlencode($redirect) : '');
222
        $prg = $this->prg($redirectUrl, true);
223
224
        if ($prg instanceof Response) {
225
            return $prg;
226
        } elseif ($prg === false) {
227
            return array(
228
                'registerForm' => $form,
229
                'enableRegistration' => $this->options->getEnableRegistration(),
230
                'redirect' => $redirect,
231
            );
232
        }
233
234
        $post = $prg;
235
        $user = $service->register($post);
236
237
        $redirect = isset($prg['redirect']) ? $prg['redirect'] : null;
238
239
        if (!$user) {
240
            return array(
241
                'registerForm' => $form,
242
                'enableRegistration' => $this->options->getEnableRegistration(),
243
                'redirect' => $redirect,
244
            );
245
        }
246
247
        if ($service->getOptions()->getLoginAfterRegistration()) {
248
            $identityFields = $service->getOptions()->getAuthIdentityFields();
249
            if (in_array('email', $identityFields)) {
250
                $post['identity'] = $user->getEmail();
251
            } elseif (in_array('username', $identityFields)) {
252
                $post['identity'] = $user->getUsername();
253
            }
254
            $post['credential'] = $post['password'];
255
            $request->setPost(new Parameters($post));
256
            return $this->forward()->dispatch(static::CONTROLLER_NAME, array('action' => 'authenticate'));
257
        }
258
259
        // TODO: Add the redirect parameter here...
260
        return $this->redirect()->toUrl($this->url()->fromRoute(static::ROUTE_LOGIN) . ($redirect ? '?redirect='. rawurlencode($redirect) : ''));
261
    }
262
}
263