Advertisement
Guest User

Untitled

a guest
Mar 7th, 2019
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.17 KB | None | 0 0
  1. namespace MyAppControllers;
  2.  
  3. class Login extends Controller
  4. {
  5. public function forgotPassword()
  6. {
  7. if (Input::exists()) {
  8.  
  9. if (Token::check(Input::get('token'))) {
  10.  
  11. $validation = Validation::check($_POST, array(
  12. 'account_number' => array(
  13. 'required' => true,
  14. 'min' => 3,
  15. 'max' => 30
  16. ),
  17. 'email' => array(
  18. 'required' => true,
  19. 'email' => true
  20. )
  21. ));
  22.  
  23. if ($validation['passed']) {
  24. $this->user->forgotPassword();
  25. $this->user->userForgotPassword->set(Input::get('account_number'), Input::get('email'));
  26. $this->user->userForgotPassword->apply();
  27. }
  28.  
  29. General::toJson([ 'status' => true, 'msg' => 'An Email has been sent to your inbox. Please follow the steps and reset your password.' ]);
  30. }
  31. }
  32. else {
  33. General::toJson(['status' => false, 'msg' => 'Please enter your Account number and Email.' ]);
  34. }
  35. }
  36.  
  37.  
  38. public function resetPasswordValidation()
  39. {
  40. if (Input::exists()) {
  41.  
  42. if (Token::check(Input::get('token')) ) {
  43.  
  44. $validation = Validation::check($_POST, array(
  45. 'account_number' => array(
  46. 'required' => true,
  47. 'min' => 3,
  48. 'max' => 30
  49. ),
  50. 'fptoken' => array(
  51. 'required' => true,
  52. 'min' => 60,
  53. 'max' => 60,
  54. 'bcrypt' => true
  55. )
  56. ));
  57.  
  58. if ( $validation['passed'] ) {
  59.  
  60. $this->user->resetPassword();
  61.  
  62. if ($this->user->userResetPassword->validate(Input::get('account_number'), Input::get('fptoken')))
  63. General::toJson(['status' => true]);
  64. }
  65. }
  66. }
  67.  
  68. namespace MyAppModels;
  69.  
  70. class User
  71. {
  72.  
  73. public $id;
  74. public $firstName;
  75. public $lastName;
  76. public $userName;
  77. public $email;
  78. public $lastLogin;
  79. public $salt;
  80. public $accountNumber;
  81. public $password;
  82. public $ip;
  83. public $loginTimestamp;
  84. public $isLoggedIn;
  85. public $changePass;
  86. public $forgotPasswordToken;
  87. public $forgotPasswordTimeStamp;
  88.  
  89. # @obj user Login data (a template for a login insert)
  90. public $userLogin;
  91. # @obj user profile information (fullname, email, last_login, profile picture, etc')
  92. public $userDetatils;
  93. # @obj user Authenticator object
  94. public $userAuthenticator;
  95. # @obj Handle user Sessions (Sets user sessions, Check if sessions are set, Check timeout, ect')
  96. public $userSessions;
  97. # @obj Handle user Updates
  98. public $userUpdates;
  99. # @obj Handle user forgot password
  100. public $userForgotPassword;
  101. # @obj Handle user reset password
  102. public $userResetPassword;
  103.  
  104.  
  105.  
  106. public function forgotPassword()
  107. {
  108. # Create systemUserDedatils obj
  109. if ( !$this->systemUserForgotPassword instanceof UserForgotPassword )
  110. $this->userForgotPassword = new MyAppModelsUserUserForgotPassword($this);
  111.  
  112. return $this->userForgotPassword;
  113. }
  114.  
  115.  
  116.  
  117. public function resetPassword()
  118. {
  119. # Create userDedatils obj
  120. if ( !$this->userResetPassword instanceof UserResetPassword )
  121. $this->userResetPassword = new MyAppModelsUserUserResetPassword($this);
  122.  
  123. return $this->userResetPassword;
  124. }
  125.  
  126.  
  127.  
  128. }
  129.  
  130. <?php
  131. namespace MyAppModelsUser;
  132.  
  133. use MyAppModelsBaseDatabase as Base;
  134. use MyAppModelsUser;
  135. use MyAppModelsAccount;
  136. use MyAppCoreExceptionHandlerForgotPasswordException;
  137.  
  138. /**
  139. *
  140. * User Forgot Password class
  141. *
  142. */
  143. class UserForgotPassword extends Base
  144. {
  145.  
  146. /*=================================
  147. = Variables =
  148. =================================*/
  149.  
  150. private $Account;
  151. private $User;
  152. private $token;
  153.  
  154. /*===============================
  155. = Methods =
  156. ===============================*/
  157.  
  158. public function __construct(User $User)
  159. {
  160. parent::__construct();
  161. $this->User = $User;
  162. $this->Account = Account::getInstance();
  163. }
  164.  
  165.  
  166. /**
  167. *
  168. * Set data to the User object
  169. * @param $AccountNumber Str Account Name
  170. * @param $email Str Email
  171. *
  172. */
  173. public function set(String $AccountNumber,String $email)
  174. {
  175. $this->User->AccountNumber = $AccountNumber;
  176. $this->User->email = $email;
  177. }
  178.  
  179.  
  180. /**
  181. *
  182. * Apply Forgot Password
  183. * 1. Check if all data is ready to generate a "forgot password" token.
  184. * 2. Updates the User row with new "forgot password" token and sets a timestamp.
  185. * 3. Sends an email with a "reset password" link
  186. *
  187. */
  188. public function apply()
  189. {
  190. if ( $this->check() ) {
  191.  
  192. # Insert data to dashboard_users
  193. $this->tableInserts();
  194.  
  195. # Send email
  196. $this->sendResetEmail();
  197. }
  198. else {
  199. return false;
  200. }
  201. }
  202.  
  203.  
  204. /**
  205. *
  206. * Check if data for password renewal is valid:
  207. * 1. Check if data is set properly
  208. * 2. Fetch Account from backofice
  209. * 3. Connect to the Account DB
  210. * 4. Validate user email exist and set data to the object
  211. * @return Bool True/False
  212. *
  213. */
  214. private function check()
  215. {
  216. try
  217. {
  218. # Check that data is set properly to the user obj
  219. if ( !isset($this->User->AccountNumber) || !isset($this->User->email) )
  220. throw new ForgotPasswordException('ForgotPassword: Account Name or Email are missing');
  221.  
  222. # Fetch Account
  223. if (!$this->Account->getAccoundByNumber($this->User->AccountNumber))
  224. throw new ForgotPasswordException('ForgotPassword: Account "'. $this->User->AccountNumber .'" set doesn't exist or might be fake!');
  225.  
  226. # Connect to Account
  227. if (!$this->db->account_connect($this->Account->host, $this->Account->dbName))
  228. throw new ForgotPasswordException('ForgotPassword: Cannot connect to the database');
  229.  
  230. # Get User object data by email
  231. if (!$this->User->getByEmail())
  232. throw new ForgotPasswordException('ForgotPassword: Email "'. $this->User->email .'" set doesn't exist or might be fake!');
  233.  
  234.  
  235. return true;
  236. } # Catch so the code wont break, but print errors in log:
  237. catch (ForgotPasswordException $e) {
  238.  
  239. # Do something to catch the errors:
  240. //
  241.  
  242. # Log the error and return false.
  243. $e->log($e);
  244. return false;
  245. }
  246. }
  247.  
  248.  
  249. /**
  250. *
  251. * Handle inserts to the Users database row
  252. * 1. Generates a token
  253. * 2. Handles the counter column (future feature)
  254. * 3. Fetches current time stamp
  255. * 4. Inserts 'fotgot_password_token', 'fotgot_password_ts' & 'fotgot_password_counter' to row
  256. *
  257. */
  258. private function tableInserts()
  259. {
  260. # Generate token
  261. $this->token = $this->generateToken();
  262.  
  263. # Counter (check/append in database)
  264. // Future Feature !
  265.  
  266. # Current timestamp
  267. $date = time();
  268. $date = strtotime('+1 day', $date);
  269.  
  270. # Update system users row
  271. $this->db->row("UPDATE dashboard_users SET forgot_password_token = :forgotPasswordToken, forgot_password_ts = :forgotPasswordTimeStamp WHERE system_user_id = :UserId", array('forgotPasswordToken' => $this->token, 'forgotPasswordTimeStamp' => date("Y-m-d H:i:s", $date), 'UserId' => $this->User->id));
  272. }
  273.  
  274.  
  275. /**
  276. *
  277. * Generate token - will use the User:
  278. * ID, Last Name, Email, Last Login, Account name, and a string manually set
  279. * @return Str Hashed BCRYPT token
  280. *
  281. */
  282. private function generateToken()
  283. {
  284. $string = $this->User->id . $this->User->lastName . $this->User->email . $this->User->lastLogin . $this->User->AccountNumber . 'this user forgot his password';
  285. return MyAppHelpersHash::create($string, $this->User->salt);
  286. }
  287.  
  288.  
  289. /**
  290. *
  291. * Send Reset Link (via email)
  292. *
  293. */
  294. private function sendResetEmail()
  295. {
  296. $this->User->resetPassword();
  297. return $this->User->UserResetPassword->sendResetEmail();
  298. }
  299.  
  300. }
  301.  
  302. <?php
  303. namespace MyAppModelsUser;
  304.  
  305. use MyAppModelsBaseDatabase as Base;
  306. use MyAppModelsUser;
  307. use MyAppModelsAccount;
  308. use MyAppCoreConfig;
  309. use MyAppCoreExceptionHandlerResetPasswordException;
  310.  
  311. /**
  312. *
  313. * User Forgot Password class
  314. *
  315. */
  316. class UserResetPassword extends Base
  317. {
  318.  
  319. /*=================================
  320. = Variables =
  321. =================================*/
  322.  
  323. private $Account;
  324. private $User;
  325. private $token;
  326.  
  327. /*===============================
  328. = Methods =
  329. ===============================*/
  330.  
  331. public function __construct(User $User)
  332. {
  333. parent::__construct();
  334. $this->User = $User;
  335. $this->Account = Account::getInstance();
  336. }
  337.  
  338.  
  339. /**
  340. *
  341. * Validates Token
  342. * @param $AccountNumber String Account name
  343. * @param $token String Forgot password token
  344. * @return Bool True if:
  345. * 1. Account exists
  346. * 2. User exists
  347. * 3. User requested to reset his/her password
  348. * 4. User token didn't expire
  349. *
  350. */
  351. public function validate(String $AccountNumber, String $token)
  352. {
  353. try {
  354.  
  355. # Fetch Account
  356. if (!$this->Account->getAccountByName($AccountNumber))
  357. throw new ForgotPasswordException('Reset Passord: Account "'. $AccountNumber .'" set doesn't exist or might be fake!');
  358.  
  359. # Connect to Account
  360. if (!$this->db->Account_connect($this->Account->host, $this->Account->dbName))
  361. throw new ForgotPasswordException('Reset Passord: Cannot connect to the database. Host: ' . $this->Account->host . 'Account: ' . $this->Account->dbName);
  362.  
  363. # Check if token exists & fetch SysteUser data
  364. if ( !$this->isToken($token) )
  365. throw new ForgotPasswordException('Reset Passord: Token expired or doesn't exist in the User table.');
  366.  
  367. return true;
  368. }
  369. finally {
  370. }
  371. }
  372.  
  373.  
  374. /**
  375. *
  376. * Check if token is valid
  377. * @param $token String Forgot Password Token
  378. * @return Bool
  379. *
  380. */
  381. private function isToken(String $token)
  382. {
  383. # Search for the token in the dashboard_users table
  384. $result = $this->db->row("SELECT system_user_id FROM dashboard_users WHERE forgot_password_token = :token AND forgot_password_ts > NOW()", array('token' => $token));
  385.  
  386. if ($result)
  387. return true;
  388. }
  389.  
  390.  
  391. /**
  392. *
  393. * Send Reset Link (via email)
  394. *
  395. */
  396. public function sendResetEmail()
  397. {
  398. $email = new MyAppHelpersEmail();
  399.  
  400. $email->addAddress($this->User->email);
  401.  
  402. $email->Subject = 'Reset Password';
  403. $email->Body = $this->generateEmailMessage();
  404.  
  405. return $email->send();
  406. }
  407.  
  408.  
  409. /**
  410. *
  411. * Generates an email message
  412. *
  413. */
  414. private function generateEmailMessage()
  415. {
  416. return html_entity_decode("Dear Account, <br/> You are getting this email because you requested to reset your password. <br/>Please follow <a href='" . Config::WEB_URL . "?account_number={$this->User->AccountNumber}&fptoken={$this->token}'>this link</a> to proceed. <br/><br/> <b>Myapp</b>");
  417. }
  418. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement