Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class userAuth {
- // create an empty id variable to hold the user id
- private $id;
- private $email;
- private $key = "16FD8C979FC40CCB97457F4AD79B32A73758771B4D1943C379FB3266EECE0C3E";
- // Checks if the user exists in the database
- private function validUser($email, $password) {
- $conn = new mysqli(DBSERVER, DBUSERNAME, DBPASSWORD, DBNAME);
- if ($conn->connect_error) {
- die("Connection failed: " . $conn->connect_error);
- }
- $truepassword = hash('sha256', $password); // password hashing using SHA256
- $query = $conn->query("select * from users where ( username='$email' OR email = '$email') and password='$truepassword'");
- $count = mysqli_num_rows($query);
- if($count == 1) {
- $row = mysqli_fetch_array($query);
- $this->id = $row['id'];
- $this->email = $row['email'];
- return true;
- }else{
- return false;
- }
- }
- private function genJWT() {
- // Make an array for the JWT Payload
- $payload = array(
- "id" => $this->id,
- "email" => $this->email,
- "exp" => time() + (60 * 60)
- );
- // encode the payload using our secretkey and return the token
- return JWT::encode($payload, $this->key);
- }
- public function checkUser($email, $password) {
- // check if the user exists
- if ($this->validUser($email, $password)) {
- // generate JSON web token and store as variable
- $token = $this->genJWT();
- $resultJSON = array(
- 'email' => $this->email,
- 'token' => $token
- );
- return json_encode($resultJSON);
- } else {
- return 'We Couldn't Find You In Our Database. Maybe Wrong Email/Password Combination';
- }
- }
- private function validJWT($token) {
- $res = array(false, '');
- // using a try and catch to verify
- try {
- //$decoded = JWT::decode($token, $this->key, array('HS256'));
- $decoded = JWT::decode($token, $this->key, array('HS256'));
- } catch (Exception $e) {
- return $res;
- }
- $res['0'] = true;
- $res['1'] = (array) $decoded;
- return $res;
- }
- public function validLogin($token) {
- // checks if an email is valid
- $tokenVal = $this->validJWT($token);
- // check if the first array value is true
- if ($tokenVal['0']) {
- // create user session and all that good stuff
- return "Everything went well, time to serve you what you need.";
- } else {
- return "There was an error validating your email. Send another link";
- }
- }
- }
Add Comment
Please, Sign In to add comment