/var/www/vhosts/ihelp.ro/httpdocs/src/Controller
Edit: /var/www/vhosts/ihelp.ro/httpdocs/src/Controller/UsersController.php (22846B)
Authentication->addUnauthenticatedActions(['login', 'add', 'verifyAccountExistBeforeLogIn', 'activate', 'forgotPassword', 'resetPassword', 'changePassword']);
}
public function initialize(): void
{
parent::initialize();
$this->loadComponent('UserConnect');
}
/**
* syncCart method
*/
public function syncCart()
{
// update user_id after login
$session = $this->request->getSession();
if ($session->check('cart_identifier')) {
$cart_identifier = $session->read('cart_identifier');
$this->loadModel('Carts');
$cart = $this->Carts->find('all')
->contain(['CartProducts'])
->where(['uuid' => $cart_identifier, 'Carts.is_active' => true])
->first();
if ($cart && $cart->user_id == null) {
if (!empty($cart->cart_products)) {
$this->Carts->updateAll(
[ // fields
'is_active' => false,
],
[ // conditions
'is_active' => true,
'user_id' => $this->userAuth->id
]
);
$this->Carts->id = $cart->id;
$this->Carts->saveField('user_id', $this->userAuth->id);
}
}
}
}
/**
* syncFavorite method
*/
public function syncFavorite()
{
// update user_id after login
$session = $this->request->getSession();
if ($session->check('favorite_identifier')) {
$favorite_identifier = $session->read('favorite_identifier');
$this->loadModel('ProductFavorites');
$productFavorites = $this->ProductFavorites->find('list', [
'keyField' => 'product_id',
'valueField' => 'product_id'
])
->where(['ProductFavorites.user_id' => $this->userAuth->id])
->toArray();
if (!empty($favorite_identifier) && !empty($productFavorites)) {
$this->ProductFavorites->updateAll(
[ // fields
'user_id' => $this->userAuth->id
],
[ // conditions
'uuid' => $favorite_identifier,
'product_id NOT IN ' => $productFavorites
]
);
$this->ProductFavorites->deleteAll(
[ // conditions
'uuid' => $favorite_identifier,
'user_id IS ' => NULL
]
);
} elseif (!empty($favorite_identifier)) {
$this->ProductFavorites->updateAll(
[ // fields
'user_id' => $this->userAuth->id
],
[ // conditions
'uuid' => $favorite_identifier,
]
);
}
}
}
/**
* Login method
*/
public function login($connect = null)
{
$this->viewBuilder()->setLayout('login');
if ($this->UserAuth->isLogged()) {
if ($connect && !in_array($connect, ['facebook'])) {
$this->render('popup');
} else {
$this->redirect(['prefix' => 'Dashboard', 'controller' => 'Profiles', 'action' => 'view']);
}
}
if ($connect == 'facebook') {
$fbData = $this->request->getData();
$this->login_facebook($fbData);
//$this->render('popup');
} else if ($connect == 'gmail') {
$this->login_gmail();
$this->render('popup');
} else {
if ($this->getRequest()->is('post')) {
$formdata = $this->getRequest()->getData();
$errorMsg = "";
$result = $this->Authentication->getResult();
$user = [];
$isValid = false;
if ($result->isValid()) {
$user = $this->Users->findByEmail($formdata['email'])->first();
if (!empty($user)) {
if ($user['is_active']) {
if ($user['is_email_verified']) {
$isValid = true;
} else {
$errorMsg = __('Adresa dumneavoastră de email nu a fost confirmată.', true);
}
} else {
$errorMsg = __('Contul dumneavoastră nu este activ.', true);
}
} else {
$errorMsg = __('Email sau parolă greșite', true);
}
} else {
$errorMsg = __('Email sau parolă greșite', true);
}
if ($isValid) {
$redirect = $this->request->getQuery('redirect', [
'prefix' => 'Dashboard',
'controller' => 'Profiles',
'action' => 'view',
]);
$this->syncCart();
$this->syncFavorite();
return $this->redirect($redirect);
} else {
if (!empty($errorMsg)) {
$this->Flash->error($errorMsg);
}
$this->UserAuth->logOut();
}
}
}
}
/**
* add_social_user method
*/
private function add_social_user($socialData)
{
$userForLogin = [];
$userEntity = $this->Users->newEmptyEntity();
$dataUser = [];
$dataUser['role_id'] = DEFAULT_GROUP_ID;
$password = $this->UserAuth->generatePassword();
$dataUser['password'] = $this->UserAuth->makeHashedPassword($password);
$dataUser['profile']['first_name'] = $socialData['first_name'];
$dataUser['profile']['last_name'] = $socialData['last_name'];
$dataUser['is_active'] = 1;
$dataUser['gdpr_active'] = 1;
if (!empty($socialData['email'])) {
$dataUser['email'] = $socialData['email'];
if (isset($socialData['verifiedEmail']) && $socialData['verifiedEmail']) {
$dataUser['is_email_verified'] = 1;
}
}
$dataUser['ip_address'] = $this->getRequest()->clientIp();
if (!empty($socialData['picture'])) {
$path = WWW_ROOT . 'img/uploads/Profiles/' . $this->UserAuth->updateProfilePic($socialData['picture']);
$dataUser['profile']['image_path'] = pathinfo($path, PATHINFO_BASENAME);
}
$this->Users->Profiles->removeBehavior('Upload');
$userEntity = $this->Users->patchEntity($userEntity, $dataUser, ['validate' => false, 'associated' => ['Profiles' => ['validate' => false]]]);
if ($this->Users->save($userEntity)) {
$userId = $userEntity->id;
if (!empty($socialData['id']) && !empty($socialData['email'])) {
$this->loadModel('UserSocials');
$this->UserSocials->add_social_account($socialData, $userId);
}
$userForLogin = $this->Users->getUserById($userId);
}
return $userForLogin;
}
/**
* login_social_user method
*/
private function login_social_user($userForLogin, $socialData)
{
if (!empty($userForLogin)) {
if ($userForLogin['is_active']) {
$photoPath = WWW_ROOT . "uploads" . DS . "profile" . DS . $userForLogin['photo'];
if ((empty($userForLogin['photo']) || !file_exists($photoPath)) && !empty($socialData['picture'])) {
$userForLogin['photo'] = $this->UserAuth->updateProfilePic($socialData['picture']);
}
$this->Users->save($userForLogin, ['validate' => false]);
$this->UserAuth->login($userForLogin);
return true;
} else {
$this->Flash->info(__('Sorry your account is not active, please contact to support'));
return false;
}
}
}
/**
* login_facebook method
*/
private function login_facebook($me)
{
$response = ['status' => 'fail', 'redirect' => Router::url(['prefix' => 'Dashboard', 'controller' => 'Profiles', 'action' => 'view'], true)];
$this->viewBuilder()->disableAutoLayout();
if (!empty($me['name'])) {
if (strpos($me['name'], ' ') === false) {
$first_name = $me['name'];
$last_name = '';
} else {
list($first_name, $last_name) = explode(' ', $me['name'], 2);
}
} else {
$first_name = !empty($me['first_name']) ? $me['first_name'] : '';
$last_name = !empty($me['last_name']) ? $me['last_name'] : '';
}
$fbData = [
'platform' => 'facebook',
'id' => $me['id'],
'first_name' => $first_name,
'last_name' => $last_name,
'email' => !empty($me['email']) ? $me['email'] : '',
];
if (!empty($fbData['redirectURL'])) {
$this->redirect($fbData['redirectURL']);
} else {
if (!empty($fbData['id'])) {
$this->loadModel('UserSocials');
$fbData['type'] = 'FACEBOOK';
$userByFbId = $userByFbEmail = $userForLogin = [];
$userSocial = $this->UserSocials->find()->where(['UserSocials.type' => $fbData['type'], 'UserSocials.socialid' => $fbData['id']])->first();
if (!empty($fbData['email'])) {
$userByFbEmail = $this->Users->getUserByEmail($fbData['email']);
}
if (!empty($userSocial)) {
//$userSocial['access_token'] = $fbData['access_token'];
$this->UserSocials->save($userSocial, ['validate' => false]);
$userByFbId = $this->Users->getUserById($userSocial['user_id']);
} else if (!empty($userByFbEmail)) {
$this->UserSocials->add_social_account($fbData, $userByFbEmail['id']);
}
if (!empty($userByFbId) && !empty($userByFbEmail)) {
$userForLogin = $userByFbId;
} else if (!empty($userByFbId)) {
if (empty($userByFbId['email']) && !empty($fbData['email'])) {
$userByFbId['email'] = $fbData['email'];
}
$userForLogin = $userByFbId;
} else if (!empty($userByFbEmail)) {
$userForLogin = $userByFbEmail;
} else {
$userForLogin = $this->add_social_user($fbData);
}
if ($this->login_social_user($userForLogin, $fbData)) {
$response = ['status' => 'success', 'redirect' => Router::url(['prefix' => 'Dashboard', 'controller' => 'Profiles', 'action' => 'view'], true)];
}
} else {
if (!empty($fbData['error']) && Configure::read('debug')) {
$this->Flash->error($fbData['error'] . ' UserConnectComponent line number ' . $fbData['line_number']);
} else {
$this->Flash->error(__('Something went wrong, please try again or use other login options'));
}
}
}
echo json_encode($response);
die();
}
/**
* login_gmail method
*/
private function login_gmail()
{
$this->viewBuilder()->disableAutoLayout();
$gmailData = $this->UserConnect->gmail_connect();
if (!empty($gmailData['redirectURL'])) {
$this->redirect($gmailData['redirectURL']);
} else {
if (!empty($gmailData['email'])) {
$gmailData['type'] = 'GMAIL';
$userForLogin = $this->Users->getUserByEmail($gmailData['email']);
if (empty($userForLogin)) {
$userForLogin = $this->add_social_user($gmailData);
}
$this->login_social_user($userForLogin, $gmailData);
} else {
if (!empty($gmailData['error']) && Configure::read('debug')) {
$this->Flash->error($gmailData['error'] . ' UserConnectComponent line number ' . $gmailData['line_number']);
} else {
$this->Flash->error(__('Something went wrong, please try again or use other login options'));
}
}
}
}
/**
* Logout method
*/
public function logout()
{
$result = $this->Authentication->getResult();
// regardless of POST or GET, redirect if user is logged in
if ($result->isValid()) {
$session = $this->request->getSession();
$session->delete('cart_identifier');
$session->delete('favorite_identifier');
$this->Authentication->logout();
$this->Flash->success(__('LogOut'));
return $this->redirect(['controller' => 'Pages', 'action' => 'home']);
}
}
/**
* Add method
*/
public function add()
{
$this->viewBuilder()->setLayout('login');
$this->loadComponent('MailHelp');
$user = $this->Users->newEmptyEntity();
if ($this->request->is('post')) {
$to = [];
$activationCode = Security::hash(Security::randomBytes(20));
$randomKey = Security::hash(Security::randomBytes(20));
$getUserEmail = $this->request->getData('email');
$getLastName = $this->request->getData('profile.last_name');
$to['email'] = $getUserEmail;
$to['name'] = $getLastName;
$user = $this->Users->patchEntity($user, $this->request->getData(), ['associated' => ['Profiles']]);
$user->activation_code = $activationCode;
$user->role_id = USER;
if ($this->Users->save($user)) {
$aLink = Router::url(['prefix' => null, 'controller' => 'Users', 'action' => 'activate', $activationCode, $randomKey], true);
try {
$this->MailHelp->sendRegister($to, $aLink);
} catch (\Exception $e) {
//$this->Flash->error($e->getMessage());
return $this->redirect(['prefix' => null, 'controller' => 'Users', 'action' => 'register']);
}
$this->Flash->success(__('Contul a fost creat. Un email a fost trimis cu link-ul de confirmare cont'));
// return $this->redirect(['prefix' => 'Dashboard', 'controller' => 'Users', 'action' => 'login']);
return $this->redirect(['prefix' => false, 'plugin' => null, 'controller' => 'Users', 'action' => 'login']);
}
$this->Flash->error(__('Utilizatorul nu a putut fi salvat. Vă rugăm să încercați din nou.'));
}
$roles = $this->Users->Roles->find('list', ['limit' => 200]);
$this->set(compact('user'));
}
/**
* activate method
*/
public function activate($activationCode = '', $randomKey = '')
{
if (trim($activationCode) != "" && $randomKey != "") {
$activationCode = filter_var($activationCode, FILTER_SANITIZE_STRING);
$user = $this->Users->find()
->where(['activation_code' => $activationCode, 'is_email_verified' => 0])
->first();
if (!empty($user)) {
$user->is_email_verified = 1;
$user->is_active = 1;
$user->activation_code = null;
if ($this->Users->save($user)) {
$this->Flash->success(__('Contul tau a fost activat cu succes. va rugam sa va logati'));
return $this->redirect(['prefix' => false, 'controller' => 'Users', 'action' => 'login']);
}
} else {
$this->Flash->error('Ne pare rau, link-ul a expirat.');
}
}
}
/**
* changePassword method
*/
public function changePassword($token = '', $randomKey = '')
{
$this->autoRender = false;
$token = filter_var($token, FILTER_SANITIZE_STRING);
if ($this->request->is('get')) {
if (trim($token) != "" && $randomKey != "") {
$user = $this->Users->find()
->where(['token_change_password' => $token])
->first();
if (!empty($user)) {
$user->status_change_password = true;
$user->password = $user->new_password;
$user->token_change_password = null;
if ($this->Users->save($user)) {
$this->Authentication->logout();
$this->Flash->success('Parola a fost schimbata.');
return $this->redirect(['prefix' => false, 'controller' => 'Users', 'action' => 'login']);
}
} else {
$this->Authentication->logout();
$this->Flash->error('Ne pare rau, link-ul a expirat.');
return $this->redirect(['prefix' => false, 'controller' => 'Users', 'action' => 'login']);
}
}
}
}
/**
* verify method
*/
public function verifyAccountExistBeforeLogIn()
{
if ($this->UserAuth->isLogged()) {
$this->redirect(['prefix' => 'Dashboard', 'controller' => 'Products', 'action' => 'add']);
}
$this->viewBuilder()->setLayout('login');
$session = $this->request->getSession();
$session->delete('UserVerify');
$user = $this->Users->newEntity($this->request->getData(), ['validate' => 'verifyEmail']);
if ($this->request->is(['patch', 'post', 'put'])) {
$email = $this->request->getData('email');
$userExists = $this->Users->find()
->where(['email' => $email])
->first();
if (!empty($userExists)) {
$session->write('UserVerify.emailLogin', $email);
$this->set(compact('user'));
return $this->redirect(['prefix' => false, 'controller' => 'Users', 'action' => 'login']);
} else {
if (empty($user->getErrors())) {
$this->Flash->error('Nu aveți cont. Vă rugăm să vă înregistrați.');
$session->write('UserVerify.emailRegister', $email);
return $this->redirect(['prefix' => false, 'controller' => 'Users', 'action' => 'add']);
}
}
}
$this->set(compact('user'));
}
/**
* forgotPassword method
*/
public function forgotPassword()
{
$this->viewBuilder()->setLayout('login');
$this->loadComponent('MailHelp');
$user = $this->Users->newEntity($this->request->getData(), ['validate' => 'verifyEmail']);
if ($this->request->is(['patch', 'post', 'put'])) {
$to = [];
$email = $this->request->getData('email_send_forgort_password');
$token = Security::hash(Security::randomBytes(25));
$randomKey = Security::hash(Security::randomBytes(25));
$userExists = $this->Users->find()
->where(['email' => $email])
->first();
if (!empty($userExists)) {
$user = $this->Users->patchEntity($userExists, $this->request->getData(), ['validate' => 'verifyEmail']);
$user->token_recovery_password = $token;
if ($this->Users->save($user)) {
$to['email'] = $email;
$aLink = Router::url(['prefix' => null, 'controller' => 'Users', 'action' => 'resetPassword', $token, $randomKey], true);
$this->MailHelp->sendResetPassword($to, $aLink);
$this->Flash->success('Dacă există un cont asociat acestei adrese de email vei primi un email cu pașii de urmat pentru a recupera parola. Multumim');
}
} else {
if (empty($user->getErrors())) {
$this->Flash->success('Dacă există un cont asociat acestei adrese de email vei primi un email cu pașii de urmat pentru a recupera parola. Multumim');
}
}
}
$this->set(compact('user'));
}
/**
* resetPassword method
*/
public function resetPassword($token = '', $randomKey = '')
{
$user = $this->Users->newEntity($this->request->getData(), ['validate' => 'resetPassword']);
$this->viewBuilder()->setLayout('login');
$token = filter_var($token, FILTER_SANITIZE_STRING);
$user = $this->Users->find()
->where(['token_recovery_password' => $token])
->first();
if ($this->request->is(['patch', 'post', 'put'])) {
$password = $this->request->getData('password');
if (trim($token) != "" && $randomKey != "") {
if (!empty($user)) {
$user = $this->Users->patchEntity($user, $this->request->getData(), ['validate' => 'resetPassword']);
$user->token_recovery_password = null;
if ($this->Users->save($user)) {
$this->Flash->success('Vă rugăm să vă logați cu noua parolă.');
return $this->redirect(['prefix' => null, 'controller' => 'Users', 'action' => 'login']);
}
} else {
$this->Flash->error('Ne pare rău, link-ul a expirat.');
return $this->redirect(['prefix' => null, 'controller' => 'Users', 'action' => 'forgotPassword']);
}
}
}
$this->set(compact('user'));
}
}