/**
* Enable the Two-factor Authentication.
*
* @return \Cake\Network\Response|void
*/
public function enable()
{
if (!$this->request->is('post')) {
return $this->redirect(['action' => 'configure']);
}
$this->loadModel('UsersTwoFactorAuth');
$userTfa = $this->UsersTwoFactorAuth->find()->where(['UsersTwoFactorAuth.user_id' => $this->Auth->user('id')])->first();
if (is_null($userTfa) || empty($userTfa->secret) || !isset($this->request->data['code'])) {
$this->Flash->error(__('Two-factor secret verification failed. Please verify your secret and try again.'));
return $this->redirect(['action' => 'configure']);
}
$tfa = new TwoFactorAuth('Xeta');
if ($tfa->verifyCode($userTfa->secret, $this->request->data['code']) === true && $this->request->data['code'] != $userTfa->current_code) {
$this->loadModel('Users');
$user = $this->Users->find()->where(['Users.id' => $this->Auth->user('id')])->select(['id', 'username', 'two_factor_auth_enabled'])->first();
$user->two_factor_auth_enabled = true;
$this->Users->save($user);
$data = ['session' => $this->request->clientIp() . $this->request->header('User-Agent') . gethostbyaddr($this->request->clientIp()), 'current_code' => $this->request->data['code'], 'recovery_code' => $this->_generateNewRecoveryCode($userTfa->username)];
$this->UsersTwoFactorAuth->patchEntity($userTfa, $data);
$this->UsersTwoFactorAuth->save($userTfa);
//Logs Event.
$this->eventManager()->attach(new Logs());
$event = new Event('Log.User', $this, ['user_id' => $user->id, 'username' => $user->username, 'user_ip' => $this->request->clientIp(), 'user_agent' => $this->request->header('User-Agent'), 'action' => '2FA.enabled']);
$this->eventManager()->dispatch($event);
$this->Flash->success(__('Two-factor authentication successfully enabled !'));
$this->set(compact('user', 'userTfa'));
} else {
$this->Flash->error(__('Two-factor secret verification failed. Please verify your secret and try again.'));
return $this->redirect(['action' => 'configure']);
}
}