Passed
Push — master ( 2191f6...abcfc0 )
by Wilmer
02:41
created

SiteController   A

Complexity

Total Complexity 37

Size/Duplication

Total Lines 316
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 110
dl 0
loc 316
rs 9.44
c 0
b 0
f 0
wmc 37

14 Methods

Rating   Name   Duplication   Size   Complexity  
A actionIndex() 0 3 1
A actions() 0 9 2
A behaviors() 0 18 1
A actionRequestPasswordReset() 0 20 4
B actionResetPassword() 0 27 8
A sendResetPassword() 0 36 4
A resetPassword() 0 11 1
A actionSignup() 0 14 4
A actionLogout() 0 5 1
A actionAbout() 0 3 1
A login() 0 3 2
A sendContact() 0 8 1
A actionLogin() 0 17 4
A actionContact() 0 12 3
1
<?php
2
3
namespace app\basic\controllers;
4
5
use app\basic\forms\ContactForm;
6
use app\basic\forms\LoginForm;
7
use app\basic\forms\PasswordResetRequestForm;
8
use app\basic\forms\ResetPasswordForm;
9
use app\basic\forms\SignupForm;
10
use app\basic\models\UserModels;
11
use yii\captcha\CaptchaAction;
12
use yii\exceptions\InvalidArgumentException;
13
use yii\base\Model;
14
use yii\mail\MailerInterface;
15
use yii\web\BadRequestHttpException;
16
use yii\web\Controller;
17
use yii\web\ErrorAction;
18
use yii\web\Response;
19
use yii\web\filters\AccessControl;
20
use yii\web\filters\VerbFilter;
21
22
/**
23
 * SiteController is the controller Web Application Basic.
24
 **/
25
class SiteController extends Controller
26
{
27
    private $_User;
28
29
	/**
30
     * behaviors
31
     *
32
	 * @return array behaviors config.
33
	 **/
34
	public function behaviors()
35
	{
36
		return [
37
			'access' => [
38
				'__class' => AccessControl::class,
39
				'only' => ['logout'],
40
				'rules' => [
41
					[
42
						'actions' => ['logout'],
43
						'allow' => true,
44
						'roles' => ['@'],
45
					],
46
				],
47
			],
48
			'verbs' => [
49
				'__class' => VerbFilter::class,
50
				'actions' => [
51
					'logout' => ['POST'],
52
				],
53
			],
54
		];
55
	}
56
57
	/**
58
     * actions
59
     *
60
	 * @return array actions config.
61
	 **/
62
	public function actions()
63
	{
64
		return [
65
			'error' => [
66
				'__class' => ErrorAction::class,
67
			],
68
			'captcha' => [
69
				'__class' => CaptchaAction::class,
70
				'fixedVerifyCode' => (YII_ENV === 'test') ? 'testme' : null,
71
			],
72
		];
73
	}
74
75
	/**
76
     * actionIndex
77
	 * Displays homepage.
78
	 *
79
	 * @return string
80
	 **/
81
	public function actionIndex()
82
	{
83
		return $this->render('index');
84
	}
85
86
	/**
87
     * actionAbout
88
	 * Displays about page.
89
	 *
90
	 * @return string
91
	 **/
92
	public function actionAbout()
93
	{
94
		return $this->render('about');
95
	}
96
97
	/**
98
     * actionContact
99
	 * Displays contact page.
100
	 *
101
	 * @return Response|string
102
	 **/
103
	public function actionContact()
104
	{
105
        $model = new ContactForm();
106
107
		if ($model->load($this->app->request->post()) && $model->validate()) {
108
            $this->sendContact($this->app->params['adminEmail'], $model);
109
			$this->app->session->setFlash('contactFormSubmitted');
110
			return $this->refresh();
111
		}
112
113
		return $this->render('contact', [
114
			'model' => $model,
115
		]);
116
	}
117
118
	/**
119
     * actionSignup
120
	 * Signs user up.
121
	 *
122
	 * @return mixed
123
	 **/
124
	public function actionSignup()
125
	{
126
		$model = new SignupForm();
127
128
		if ($model->load($this->app->request->post())) {
129
			if ($this->_User = $model->signup()) {
130
				if ($this->app->getUser()->login($this->_User)) {
131
					return $this->goHome();
132
				}
133
			}
134
		}
135
136
		return $this->render('signup', [
137
			'model' => $model,
138
		]);
139
	}
140
141
	/**
142
     * actionLogin
143
	 * Login action.
144
	 *
145
	 * @return Response|string
146
	 **/
147
	public function actionLogin()
148
	{
149
		if (!$this->app->user->isGuest) {
150
			return $this->goHome();
151
		}
152
153
		$model = new LoginForm();
154
155
		if ($model->load($this->app->request->post()) && $model->validate()) {
156
            $this->login($model);
157
			return $this->goBack();
158
		}
159
160
		$model->password = '';
161
162
		return $this->render('login', [
163
			'model' => $model,
164
		]);
165
	}
166
167
	/**
168
     * actionLogout
169
	 * Logout action.
170
	 *
171
	 * @return Response
172
	 **/
173
	public function actionLogout()
174
	{
175
		$this->app->user->logout();
176
177
		return $this->goHome();
178
	}
179
180
	/**
181
     * actionRequestPasswordReset
182
	 * Requests password reset.
183
	 *
184
	 * @return mixed
185
	 **/
186
	public function actionRequestPasswordReset()
187
	{
188
		$model = new PasswordResetRequestForm();
189
190
		if ($model->load($this->app->request->post()) && $model->validate()) {
191
			if ($this->sendResetPassword($model)) {
192
				$this->app->session->setFlash(
193
                    'success',
194
                    $this->app->t('basic', 'Check your email for further instructions.')
195
                );
196
				return $this->goHome();
197
			}
198
			$this->app->session->setFlash(
199
                'error',
200
                $this->app->t('basic', 'Sorry, we are unable to reset password for the provided email address.')
201
            );
202
		}
203
204
		return $this->render('requestPasswordResetToken', [
205
			'model' => $model,
206
		]);
207
	}
208
209
	/**
210
     * actionResetPassword
211
	 * Resets password.
212
	 *
213
	 * @param string $token
214
	 * @return mixed
215
	 * @throws BadRequestHttpException
216
	 **/
217
	public function actionResetPassword(string $token)
218
	{
219
        try {
220
			$model = new ResetPasswordForm();
221
		} catch (InvalidArgumentException $e) {
222
			throw new BadRequestHttpException($e->getMessage());
223
		}
224
225
        $user = new UserModels();
226
227
		if (empty($token) || !is_string($token)) {
228
			$this->app->session->setFlash('danger', $this->app->t('basic', 'Password reset token cannot be blank.'));
229
			return $this->goHome();
230
		}
231
          
232
		if (!$user->findByPasswordResetToken($token, $this->app->params['user.passwordResetTokenExpire'])) {
233
			$this->app->session->setFlash('danger', $this->app->t('basic', 'Wrong password reset token.'));
234
			return $this->goHome();
235
		}
236
237
		if ($model->load($this->app->request->post()) && $model->validate() && $this->resetPassword($token, $model)) {
238
			$this->app->session->setFlash('success', $this->app->t('basic', 'New password saved.'));
239
			return $this->goHome();
240
		}
241
242
		return $this->render('resetPassword', [
243
			'model' => $model,
244
		]);
245
    }
246
247
	/**
248
     * login
249
	 * Logs in a user using the provided username and password.
250
     *
251
     * @param Model $model.
252
	 * @return bool whether the user is logged in successfully.
253
	 **/
254
	public function login(Model $model)
255
	{
256
		return $this->app->user->login($model->getUser(), $model->rememberMe ? 3600 * 24 * 30 : 0);
257
	}
258
259
	/**
260
     * resetPassword
261
	 * Resets password.
262
	 *
263
     * @param string $token.
264
     * @param Model $model.
265
	 * @return bool if password was reset.
266
	 **/
267
	public function resetPassword(string $token, Model $model)
268
	{
269
        $this->_User = new UserModels();
270
        $this->_User = $this->_User->findByPasswordResetToken(
271
			$token, 
272
			$this->app->params['user.passwordResetTokenExpire']
273
		);
274
		$this->_User->setPassword($model->password);
275
		$this->_User->removePasswordResetToken();
276
277
		return $this->_User->save(false);
278
	}	
279
280
    /**
281
     * sendContactForm
282
	 * Sends an email to the specified email address using the information collected by this model.
283
     *
284
	 * @param string $email the target email address.
285
     * @param Model $model.
286
	 * @return bool whether the model passes validation.
287
	 **/
288
	public function sendContact(string $email, Model $model)
289
	{
290
		$this->app->mailer->compose()
291
		    ->setTo($email)
292
			->setFrom([$model->email => $model->name])
293
			->setSubject($model->subject)
294
			->setTextBody($model->body)
295
			->send();
296
    }
297
    
298
	/**
299
     * sendResetPassword
300
	 * Sends an email with a link, for resetting the password.
301
     *
302
     * @param Model $model.
303
	 * @return bool whether the email was send.
304
	 **/
305
	public function sendResetPassword(Model $model)
306
	{
307
        $this->_User = new UserModels();
308
309
		$this->_User = $this->_User->findOne([
310
			'status' => $this->_User::STATUS_ACTIVE,
311
			'email' => $model->email,
312
		]);
313
314
		if (!$this->_User) {
315
			return false;
316
		}
317
318
		if (!$this->_User->isPasswordResetTokenValid(
319
            $this->_User->password_reset_token,
320
            $this->app->params['user.passwordResetTokenExpire']
321
        )) {
322
			$this->_User->generatePasswordResetToken();
323
			if (!$this->_User->save()) {
324
				return false;
325
			}
326
		}
327
328
        return $this->app->mailer->compose(
329
			['html' => 'passwordResetToken-html', 'text' => 'passwordResetToken-text'],
330
			['user' => $this->_User]
331
		)
332
		->setFrom(
333
			[
334
				$this->app->params['adminEmail'] => 
335
				$this->app->name . ' - ' . $this->app->t('basic', 'Automatic')
336
			]
337
		)
338
		->setTo($model->email)
339
		->setSubject($this->app->t('basic', 'Password reset for ') . $this->app->name)
340
		->send();
341
	}
342
}
343