PageRenderTime 27ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/app/Plugin/Usermgmt/Model/User.php

https://gitlab.com/manuperazafa/elsartenbackend
PHP | 393 lines | 262 code | 8 blank | 123 comment | 5 complexity | 20f9bc032724d74fd7a4dca2ffc7889c MD5 | raw file
  1. <?php
  2. /*
  3. This file is part of UserMgmt.
  4. Author: Chetan Varshney (http://ektasoftwares.com)
  5. UserMgmt is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. UserMgmt is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with Foobar. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. App::uses('UserMgmtAppModel', 'Usermgmt.Model');
  17. App::uses('CakeEmail', 'Network/Email');
  18. class User extends UserMgmtAppModel {
  19. /**
  20. * This model belongs to following models
  21. *
  22. * @var array
  23. */
  24. var $belongsTo = array('Usermgmt.UserGroup');
  25. /**
  26. * This model has following models
  27. *
  28. * @var array
  29. */
  30. var $hasMany = array('LoginToken'=>array('className'=>'Usermgmt.LoginToken','limit' =>1));
  31. //var $hasOne = 'Vendedore' => array('className' => 'Vendedore','foreignKey' => 'vendedor_id');
  32. /**
  33. * model validation array
  34. *
  35. * @var array
  36. */
  37. var $validate = array();
  38. /**
  39. * UsetAuth component object
  40. *
  41. * @var object
  42. */
  43. var $userAuth;
  44. /**
  45. * model validation array
  46. *
  47. * @var array
  48. */
  49. function LoginValidate() {
  50. $validate1 = array(
  51. 'email'=> array(
  52. 'mustNotEmpty'=>array(
  53. 'rule' => 'notEmpty',
  54. 'message'=> 'Please enter email or username')
  55. ),
  56. 'password'=>array(
  57. 'mustNotEmpty'=>array(
  58. 'rule' => 'notEmpty',
  59. 'message'=> 'Please enter password')
  60. )
  61. );
  62. $this->validate=$validate1;
  63. return $this->validates();
  64. }
  65. /**
  66. * model validation array
  67. *
  68. * @var array
  69. */
  70. function RegisterValidate() {
  71. $validate1 = array(
  72. "user_group_id" => array(
  73. 'rule' => array('comparison', '!=', 0),
  74. 'message'=> 'Please select group'),
  75. 'username'=> array(
  76. 'mustNotEmpty'=>array(
  77. 'rule' => 'notEmpty',
  78. 'message'=> 'Please enter username',
  79. 'last'=>true),
  80. 'mustUnique'=>array(
  81. 'rule' =>'isUnique',
  82. 'message' =>'This username already taken',
  83. 'last'=>true),
  84. 'mustBeLonger'=>array(
  85. 'rule' => array('minLength', 4),
  86. 'message'=> 'Username must be greater than 3 characters',
  87. 'last'=>true),
  88. ),
  89. 'first_name'=> array(
  90. 'mustNotEmpty'=>array(
  91. 'rule' => 'notEmpty',
  92. 'message'=> 'Please enter first name')
  93. ),
  94. 'last_name'=> array(
  95. 'mustNotEmpty'=>array(
  96. 'rule' => 'notEmpty',
  97. 'on' => 'create',
  98. 'message'=> 'Please enter last name')
  99. ),
  100. 'email'=> array(
  101. 'mustNotEmpty'=>array(
  102. 'rule' => 'notEmpty',
  103. 'message'=> 'Please enter email',
  104. 'last'=>true),
  105. 'mustBeEmail'=> array(
  106. 'rule' => array('email'),
  107. 'message' => 'Please enter valid email',
  108. 'last'=>true),
  109. 'mustUnique'=>array(
  110. 'rule' =>'isUnique',
  111. 'message' =>'This email is already registered',
  112. )
  113. ),
  114. 'oldpassword'=>array(
  115. 'mustNotEmpty'=>array(
  116. 'rule' => 'notEmpty',
  117. 'message'=> 'Please enter old password',
  118. 'last'=>true),
  119. 'mustMatch'=>array(
  120. 'rule' => array('verifyOldPass'),
  121. 'message' => 'Please enter correct old password'),
  122. ),
  123. 'password'=>array(
  124. 'mustNotEmpty'=>array(
  125. 'rule' => 'notEmpty',
  126. 'message'=> 'Please enter password',
  127. 'on' => 'create',
  128. 'last'=>true),
  129. 'mustBeLonger'=>array(
  130. 'rule' => array('minLength', 6),
  131. 'message'=> 'Password must be greater than 5 characters',
  132. 'on' => 'create',
  133. 'last'=>true),
  134. 'mustMatch'=>array(
  135. 'rule' => array('verifies'),
  136. 'message' => 'Both passwords must match'),
  137. //'on' => 'create'
  138. ),
  139. 'captcha'=>array(
  140. 'mustMatch'=>array(
  141. 'rule' => array('recaptchaValidate'),
  142. 'message' => ''),
  143. )
  144. );
  145. $this->validate=$validate1;
  146. return $this->validates();
  147. }
  148. /**
  149. * Used to validate captcha
  150. *
  151. * @access public
  152. * @return boolean
  153. */
  154. public function recaptchaValidate() {
  155. App::import("Vendor", "Usermgmt.recaptcha/recaptchalib");
  156. $recaptcha_challenge_field = (isset($_POST['recaptcha_challenge_field'])) ? $_POST['recaptcha_challenge_field'] : "";
  157. $recaptcha_response_field = (isset($_POST['recaptcha_response_field'])) ? $_POST['recaptcha_response_field'] : "";
  158. $resp = recaptcha_check_answer(PRIVATE_KEY_FROM_RECAPTCHA, $_SERVER['REMOTE_ADDR'], $recaptcha_challenge_field, $recaptcha_response_field);
  159. $error = $resp->error;
  160. if(!$resp->is_valid) {
  161. $this->validationErrors['captcha'][0]=$error;
  162. }
  163. return true;
  164. }
  165. /**
  166. * Used to match passwords
  167. *
  168. * @access public
  169. * @return boolean
  170. */
  171. public function verifies() {
  172. return ($this->data['User']['password']===$this->data['User']['cpassword']);
  173. }
  174. /**
  175. * Used to match old password
  176. *
  177. * @access public
  178. * @return boolean
  179. */
  180. public function verifyOldPass() {
  181. $userId = $this->userAuth->getUserId();
  182. $user = $this->findById($userId);
  183. $oldpass=$this->userAuth->makePassword($this->data['User']['oldpassword'], $user['User']['salt']);
  184. return ($user['User']['password']===$oldpass);
  185. }
  186. /**
  187. * Used to send registration mail to user
  188. *
  189. * @access public
  190. * @param array $user user detail array
  191. * @return void
  192. */
  193. public function sendRegistrationMail($user) {
  194. // send email to newly created user
  195. $userId=$user['User']['id'];
  196. $email = new CakeEmail();
  197. $fromConfig = EMAIL_FROM_ADDRESS;
  198. $fromNameConfig = EMAIL_FROM_NAME;
  199. $email->from(array( $fromConfig => $fromNameConfig));
  200. $email->sender(array( $fromConfig => $fromNameConfig));
  201. $email->to($user['User']['email']);
  202. $email->subject('Your registration is complete');
  203. //$email->transport('Debug');
  204. $body="Welcome ".$user['User']['first_name'].", Thank you for your registration on ".SITE_URL." \n\n Thanks,\n".EMAIL_FROM_NAME;
  205. try{
  206. $result = $email->send($body);
  207. } catch (Exception $ex) {
  208. // we could not send the email, ignore it
  209. $result="Could not send registration email to userid-".$userId;
  210. }
  211. $this->log($result, LOG_DEBUG);
  212. }
  213. /**
  214. * Used to send email verification mail to user
  215. *
  216. * @access public
  217. * @param array $user user detail array
  218. * @return void
  219. */
  220. public function sendVerificationMail($user) {
  221. $userId=$user['User']['id'];
  222. $email = new CakeEmail();
  223. $fromConfig = EMAIL_FROM_ADDRESS;
  224. $fromNameConfig = EMAIL_FROM_NAME;
  225. $email->from(array( $fromConfig => $fromNameConfig));
  226. $email->sender(array( $fromConfig => $fromNameConfig));
  227. $email->to($user['User']['email']);
  228. $email->subject('Email Verification Mail');
  229. $activate_key = $this->getActivationKey($user['User']['password']);
  230. $link = Router::url("/userVerification?ident=$userId&activate=$activate_key",true);
  231. $body="Hi ".$user['User']['first_name'].", Click the link below to complete your registration \n\n ".$link;
  232. try{
  233. $result = $email->send($body);
  234. } catch (Exception $ex){
  235. // we could not send the email, ignore it
  236. $result="Could not send verification email to userid-".$userId;
  237. }
  238. $this->log($result, LOG_DEBUG);
  239. }
  240. /**
  241. * Used to generate activation key
  242. *
  243. * @access public
  244. * @param string $password user password
  245. * @return hash
  246. */
  247. public function getActivationKey($password) {
  248. $salt = Configure::read ( "Security.salt" );
  249. return md5(md5($password).$salt);
  250. }
  251. /**
  252. * Used to send forgot password mail to user
  253. *
  254. * @access public
  255. * @param array $user user detail
  256. * @return void
  257. */
  258. public function forgotPassword($user) {
  259. $userId=$user['User']['id'];
  260. $email = new CakeEmail();
  261. $email->config('default');
  262. $fromConfig = EMAIL_FROM_ADDRESS;
  263. $fromNameConfig = EMAIL_FROM_NAME;
  264. $email->from(array( $fromConfig => $fromNameConfig));
  265. $email->sender(array( $fromConfig => $fromNameConfig));
  266. $email->to($user['User']['email']);
  267. $email->subject(EMAIL_FROM_NAME.': Request to Reset Your Password');
  268. $activate_key = $this->getActivationKey($user['User']['password']);
  269. $link = Router::url("/activatePassword?ident=$userId&activate=$activate_key",true);
  270. $body= "Welcome ".$user['User']['first_name'].", let's help you get signed in
  271. You have requested to have your password reset on ".EMAIL_FROM_NAME.". Please click the link below to reset your password now :
  272. ".$link."
  273. If above link does not work please copy and paste the URL link (above) into your browser address bar to get to the Page to reset password
  274. Choose a password you can remember and please keep it secure.
  275. Thanks,\n".
  276. EMAIL_FROM_NAME;
  277. try{
  278. $result = $email->send($body);
  279. } catch (Exception $ex){
  280. // we could not send the email, ignore it
  281. $result="Could not send forgot password email to userid-".$userId;
  282. }
  283. $this->log($result, LOG_DEBUG);
  284. }
  285. /**
  286. * Used to mark cookie used
  287. *
  288. * @access public
  289. * @param string $type
  290. * @param string $credentials
  291. * @return array
  292. */
  293. public function authsomeLogin($type, $credentials = array()) {
  294. switch ($type) {
  295. case 'guest':
  296. // You can return any non-null value here, if you don't
  297. // have a guest account, just return an empty array
  298. return array();
  299. case 'cookie':
  300. $loginToken=false;
  301. if(strpos($credentials['token'], ":") !==false) {
  302. list($token, $userId) = split(':', $credentials['token']);
  303. $duration = $credentials['duration'];
  304. $loginToken = $this->LoginToken->find('first', array(
  305. 'conditions' => array(
  306. 'user_id' => $userId,
  307. 'token' => $token,
  308. 'duration' => $duration,
  309. 'used' => false,
  310. 'expires <=' => date('Y-m-d H:i:s', strtotime($duration)),
  311. ),
  312. 'contain' => false
  313. ));
  314. }
  315. if (!$loginToken) {
  316. return false;
  317. }
  318. $loginToken['LoginToken']['used'] = true;
  319. $this->LoginToken->save($loginToken);
  320. $conditions = array(
  321. 'User.id' => $loginToken['LoginToken']['user_id']
  322. );
  323. break;
  324. default:
  325. return array();
  326. }
  327. return $this->find('first', compact('conditions'));
  328. }
  329. /**
  330. * Used to generate cookie token
  331. *
  332. * @access public
  333. * @param integer $userId user id
  334. * @param string $duration cookie persist life time
  335. * @return string
  336. */
  337. public function authsomePersist($userId, $duration) {
  338. $token = md5(uniqid(mt_rand(), true));
  339. $this->LoginToken->create(array(
  340. 'user_id' => $userId,
  341. 'token' => $token,
  342. 'duration' => $duration,
  343. 'expires' => date('Y-m-d H:i:s', strtotime($duration)),
  344. ));
  345. $this->LoginToken->save();
  346. return "${token}:${userId}";
  347. }
  348. /**
  349. * Used to get name by user id
  350. *
  351. * @access public
  352. * @param integer $userId user id
  353. * @return string
  354. */
  355. public function getNameById($userId) {
  356. $res = $this->findById($userId);
  357. $name=(!empty($res)) ? ($res['User']['first_name'].' '.$res['User']['last_name']) : '';
  358. return $name;
  359. }
  360. /**
  361. * Used to check users by group id
  362. *
  363. * @access public
  364. * @param integer $groupId user id
  365. * @return boolean
  366. */
  367. public function isUserAssociatedWithGroup($groupId) {
  368. $res = $this->find('count', array('conditions'=>array('User.user_group_id'=>$groupId)));
  369. if(!empty($res)) {
  370. return true;
  371. }
  372. return false;
  373. }
  374. }