/** * logges in a user by his username * @param string $username * @param string $password * @return boolean */ public function login($username, $password) { // query for the password $query = DB::getInstance()->db()->prepare("SELECT id, password FROM users WHERE username=:username LIMIT 1"); $query->execute(['username' => $username]); // fetch data if the user exists if ($query->rowCount()) { $data = $query->fetch(); if (Hash::verifyPassword($password, $data['password'])) { // set the session Session::set($this->session_name, $data['id']); return true; } else { $this->auth_error_message = 'You have entered the wrong password!'; return false; } } else { $this->auth_error_message = 'Invalid login credentials!'; return false; } }
/** * prompts the user to login if it exists in the database, else it prompts for registration */ public function auth() { if (!$this->user->isLoggedIn()) { if ($this->user->exists()) { // load the login template $view = 'admin/login'; // users exist, set up the login verification process // if theres input if (Input::exists()) { // get input values $username = Input::get('username'); $password = Input::get('password'); // check if a unique token is set if (Token::check(Input::get('token'))) { // validate the form $this->validator->validate(['username' => [$username, 'required'], 'password' => [$password, 'required']]); if ($this->validator->passes()) { // log the user in if ($this->user->login($username, $password)) { header('Location: /admin/index'); } } } } // delete the flash message that occurs after registering an account if (Session::exists('success')) { $flash = Session::flash('success'); } } else { // load the registration template $view = 'admin/register'; // no users exist, set up the registration process // if theres input if (Input::exists()) { // get input values $username = Input::get('username'); $password = Input::get('password'); $password_confirmation = Input::get('password_confirmation'); // check if a unique token is set if (Token::check(Input::get('token'))) { // validate the form $this->validator->validate(['username' => [$username, 'required|alnumDash|min(3)|max(25)'], 'password' => [$password, 'required|min(8)'], 'password_confirmation' => [$password_confirmation, 'required|matches(password)']]); if ($this->validator->passes()) { // validation passed, insert a new user to the database $this->user->create($username, Hash::hashPassword($password)); Session::flash('success', 'Your account has been successfully created.'); header('Location: /admin/auth'); } } } } // render the right view $this->view($view, ['flash_message' => isset($flash) ? $flash : '', 'validation_errors' => $this->validator->errors(), 'csrf_token' => Token::generate(), 'user_error' => $this->user->auth_error_message]); } else { // the user is already logged in header('Location: /admin/index'); } }