public function loginUser() { try { $min_data = ['email', 'password']; $form = $this->getApp()->request()->post(); foreach ($min_data as $required_field) { if (!isset($form[$required_field])) { throw new \Exception("Missing required field " . $required_field . ". Required fields are " . implode(",", $min_data)); } } $email = $form["email"]; //-- In order to check the user password we need to retrieve the row by email and compare encoded passwords $user_auth = UserAuth::getByUserName($email); if (is_null($user_auth)) { throw new \Exception("No user with that email address"); } //-- Ok, we have the user_auth info, lets check the password $salt = $user_auth->getSalt(); $salt = base64_decode($salt); $password = $form["password"] . $salt; if (sha1($password) != $user_auth->getPassword()) { throw new \Exception("Wrong password"); } $user_auth->setLastSuccessfulLogin(Utilities::now()); $user_auth->persist(); $token_info = ["user_id" => $user_auth->getUserId(), "user_name" => $user_auth->getUserName(), "created" => Utilities::now(), "env_secret" => _TOKEN_SECRET]; $token = Utilities::generate_signed_request($token_info, _ENCODING_SECRET); $response_data = $user_auth->toArray(); $response_data["token"] = $token; $this->getApp()->render(200, ['data' => $response_data]); } catch (\Exception $e) { $this->getApp()->render(200, ['error' => $e->getMessage()]); } }
private static function createFromDb($resource) { if (!is_null($resource)) { $user = new UserAuth(); $user->setUserId($resource["user_id"]); $user->setUserName($resource["user_name"]); $user->setSalt($resource["salt"]); $user->setPassword($resource["password"]); $user->setLastSuccessfulLogin($resource["last_successful_login"]); return $user; } return null; }