PHP - UserRole - Function - OOP - php

I am trying to make my own custom CMS, I can register users and can login aswel, Now I am trying to make a function for user roles,
File: class.user.php
function getUserrole() {
$username = htmlentities($_SESSION['user_session']);
$stmt = $this->db->prepare('SELECT * FROM users WHERE user_name = :username');
$stmt->bindParam(':user_name', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$userrole = $row['user_role'];
if($userrole == 3) {
return $userrole = 3;
}
if($userrole == 2) {
return $userrole = 2;
}
if($userrole == 1) {
return $userrole = 1;
}
if($userrole == 0) {
return $userrole = 0;
}
}
File: Home.php
<?php
$userrole = getUserrole();
if($userrole == 1) {
echo "Hi Admin";
}
else {
echo "You are not a admin";
}
?>
When I try to do this, the error shows up:
Fatal error: Call to undefined function getUserrole() in /Applications/MAMP/htdocs/test/home.php on line 24
I can see something wrong and I was hoping you guys could help me out here:)
Entire class.user.php :
<?php
class USER
{
private $db;
function __construct($DB_con)
{
$this->db = $DB_con;
}
public function register($uname,$umail,$upass)
{
try
{
$new_password = password_hash($upass, PASSWORD_DEFAULT);
$stmt = $this->db->prepare("INSERT INTO users(user_name,user_email,user_pass)
VALUES(:uname, :umail, :upass)");
$stmt->bindparam(":uname", $uname);
$stmt->bindparam(":umail", $umail);
$stmt->bindparam(":upass", $new_password);
$stmt->execute();
return $stmt;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function login($uname,$umail,$upass)
{
try
{
$stmt = $this->db->prepare("SELECT * FROM users WHERE user_name=:uname OR user_email=:umail LIMIT 1");
$stmt->execute(array(':uname'=>$uname, ':umail'=>$umail));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
if(password_verify($upass, $userRow['user_pass']))
{
$_SESSION['user_session'] = $userRow['user_id'];
return true;
}
else
{
return false;
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function is_loggedin()
{
if(isset($_SESSION['user_session']))
{
return true;
}
}
public function redirect($url)
{
header("Location: $url");
}
public function logout()
{
session_destroy();
unset($_SESSION['user_session']);
return true;
}
function getUserrole() {
$username = htmlentities($_SESSION['user_session']);
$stmt = $this->db->prepare('SELECT * FROM users WHERE user_name = :username');
$stmt->bindParam(':user_name', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$userrole = $row['user_role'];
if($userrole == 3) {
return $userrole = 3;
}
if($userrole == 2) {
return $userrole = 2;
}
if($userrole == 1) {
return $userrole = 1;
}
if($userrole == 0) {
return $userrole = 0;
}
}
}
?>

Require the class within your home.php, init it and than call the function
<?php
require_once 'class.user.php';
$userClass = new USER(<yourdbcon>);
$userrole = $userClass->getUserrole();
if($userrole == 1) {
echo "Hi Admin";
}
else {
echo "You are not a admin";
}
?>

Related

Php check password and password confirmation

I'm making a sort of instagram and therefor I need a register page. I want to check of the password is equal or longer than 8 characters and if password and passwordconfirmation are the samen.
I've tried making a new class Security or a try - catch.
register.php
if ( !empty($_POST)) {
$user = new User();
$user->setFullname($_POST['fullname']);
$user->setUsername($_POST['username']);
$user->setEmail($_POST['email']);
$user->setPassword($_POST['password']);
$user->setPasswordConfirmation($_POST['password_confirmation']);
if( $user->passwordsAreSecure()) {
if($user->register()) {
session_start();
$_SESSION['email'] = $user->getEmail();
header('location: index.php');
} else {
$error = true;
}
} else {
$error2 = true;
}
}
My user class
public function passwordIsStrongEnough(){
if( strlen( $this->password ) <= 8 ){
return false;
}
else {
return true;
}
}
public function passwordsAreEqual(){
if( $this->password == $this->passwordConfirmation ){
return true;
}
else {
return false;
}
}
public function passwordsAreSecure(){
if( $this->passwordIsStrongEnough()
&& $this->passwordsAreEqual() ){
return true;
}
else {
return false;
}
}
function register
public function register() {
$password = Security::hash($this->password);
try {
$conn = Db::getInstance();
$statement = $conn->prepare('INSERT INTO users (fullname, username, email, password) values (:fullname, :username, :email, :password)');
$statement->bindParam(':fullname', $this->fullname);
$statement->bindParam(':username', $this->username);
$statement->bindParam(':email', $this->email);
$statement->bindParam(':password', $password);
$result = $statement->execute();
return($result);
} catch ( Throwable $t ) {
return false;
}
}
I want to get to the if( $user->passwordsAreSecure()) { so there is a session but now the form fields go empty and nothing happens.
I'm not sur to understand where is you problem. You haven't ask any question... But you can do all your code just like this :
if (!empty($_POST)) {
$user = new User();
$user->setFullname($_POST['fullname']);
$user->setUsername($_POST['username']);
$user->setEmail($_POST['email']);
$user->setPassword($_POST['password']);
$user->setPasswordConfirmation($_POST['password_confirmation']);
if ($_POST['password'] == $_POST['password_confirmation']
&& strlen($_POST['password']) > 8) {
if ($user->register()) {
session_start();
$_SESSION['email'] = $user->getEmail();
header('location: index.php');
} else {
$error = true;
}
} else {
$error2 = true;
}
}

php log in. Unable to log in

I am having an issue with login function. For some reason the crypt function is not working. When I try to log in it kept telling me that my username and password are wrong.I am using PHP 5.4.
<?php
class USER
{
private $database;
function __construct($DB_connection)
{
$this->database = $DB_connection;
}
public function register($first_name,$last_name,$username,$email,$password)
{
try
{
$hash_format ="$2y$10$";
$salt = "Salt22Characters0rMore";
$format_and_salt = $hash_format . $salt;
$created_password = crypt($password);
$res = $this->database->prepare("INSERT INTO tb_users(username,email,password)
VALUES(:username, :email, :password)");
$res->bindparam(":username", $username);
$res->bindparam(":email", $email);
$res->bindparam(":password", $created_password);
$res->execute();
return $res;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function login($username,$email,$password, $created_password)
{
try
{
$res = $this->database->prepare("SELECT * FROM tb_users WHERE username=:username OR email=:email LIMIT 1");
$res->execute(array(':username'=>$username, ':email'=>$email));
$userRow=$res->fetch(PDO::FETCH_ASSOC);
if($res->rowCount() > 0)
{
if
(crypt($password, $userRow['password']) == $created_password)
{
$_SESSION['user_session'] = $userRow['user_id'];
return true;
}
else
{
return false;
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function is_loggedin()
{
if(isset($_SESSION['user_session']))
{
return true;
}
}
public function redirect($url)
{
header("Location: $url");
}
public function logout()
{
session_destroy();
unset($_SESSION['user_session']);
return true;
}
}
?>
You will need to change the way you use the class. Try this:
<?php
class USER
{
private $database;
function __construct($DB_connection)
{
$this->database = $DB_connection;
}
public function register($username,$email,$password)
{
try
{
$created_password = $this->saltPassword($password);
$res = $this->database->prepare("INSERT INTO tb_users(username,email,password)
VALUES(:username, :email, :password)");
$res->bindparam(":username", $username);
$res->bindparam(":email", $email);
$res->bindparam(":password", $created_password);
$res->execute();
return $res;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function login($username,$email,$password)
{
try
{
$res = $this->database->prepare("SELECT * FROM tb_users WHERE username=:username OR email=:email LIMIT 1");
$res->execute(array(':username'=>$username, ':email'=>$email));
$userRow=$res->fetch(PDO::FETCH_ASSOC);
if($res->rowCount() > 0)
{
if
($this->saltPassword($password) === $userRow['password'])
{
$_SESSION['user_session'] = $userRow['user_id'];
return true;
}
else
{
return false;
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function is_loggedin()
{
if(isset($_SESSION['user_session']))
{
return true;
}
}
public function redirect($url)
{
header("Location: $url");
}
public function logout()
{
session_destroy();
unset($_SESSION['user_session']);
return true;
}
private function saltPassword($password)
{
$hash_format ="$2y$10$";
$salt = "Salt22Characters0rMore";
$format_and_salt = $hash_format . $salt;
return crypt($password, $format_and_salt);
}
}
?>

Login function only works once

I have the following php functions that process a user logging in. The functions are part of a class User.
/*
* detail() function to get a detail from a database
* exists() function to check if something exists in a database
*/
private function generate($password, $username = null) {
if(is_null($username)) {
$date = '0000-00-00';
} else {
$date = $this->_db->detail('last_active', 'users', 'username', $username);
}
// This is not the real thing but it will do as an example
$salt = md5(strrev($password.$date));
$password = md5($salt.$password.$date).strrev($password);
return $password;
}
public function login($data = array()) {
// Check if the user exists
$username = $data['username'];
if($this->_db->exists('username', 'users', 'username', $username)) {
$password = $this->generate($data['password'], $username);
// If the account is active
if ($this->_db->detail('active', 'users', 'username', $username) === 1) {
$stmt = $this->_db->mysqli->prepare("SELECT `username`, `password` FROM `users` WHERE `username` = ? AND `password` = ? AND `active` = 1");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows >= 1) {
// Function to update last_active
if($this->updateLastActive($username)) {
// Function to update password
if($this->updatePassword($username, $this->generate($password, $username))) {
// Set the session
$this->_session->set('user', $this->_db->detail('id', 'users', 'username', $username));
if($this->_session->exists('user')) {
return true;
} else {
echo 'Logging in went wrong';
return false;
}
} else {
echo 'Editing the password went wrong';
return false;
}
} else {
echo 'Editing last active date went wrong';
return false;
}
} else {
echo 'Wrong username and password combination';
return false;
}
} else {
echo 'Account not active';
return false;
}
} else {
echo 'Username doesn\'t exists';
return false;
}
}
private function updateLastActive($username) {
$date = date('Y-m-d');
$stmt = $this->_db->mysqli->prepare("UPDATE `users` SET `last_active` = ? WHERE `username` = ?");
$stmt->bind_param('ss', $date, $username);
$stmt->execute();
if($stmt->affected_rows >= 1) {
return true;
} else {
return false;
}
}
private function updatePassword($username, $password) {
$stmt = $this->_db->mysqli->prepare("UPDATE `users` SET `password` = ? WHERE `username` = ?");
$stmt->bind_param('ss', $password, $username);
$stmt->execute();
if($stmt->affected_rows >= 1) {
return true;
} else {
return false;
}
}
The user can login with no problem when he just registered. But when the user is logged out and than tries to login again it will fail. The part I get an error on is the following:
$stmt = $this->_db->mysqli->prepare("SELECT `username`, `password` FROM `users` WHERE `username` = ? AND `password` = ? AND `active` = 1");
I tried to find out where the script fails with echo on different places in the functions but I couldn't find the error. The reason why the generate() function has $username = null is because the same function is used for registration.
So all functions are working but they only work once so this leaves me that someting in the generate() function is wrong. I always get the message that there is something wrong with the username / password combination
If someone could point me in the right direction I would be very happy.
Thanks in advance
UPDATE
The detail() and exists() functions are part of a class Database.
public function detail($detail, $table, $column, $value) {
if(is_array($detail)) {
$data = array();
foreach($detail as $key) {
$stmt = $this->mysqli->prepare("SELECT `$key` FROM `$table` WHERE `$column` = ?");
if(is_numeric($value)) {
$stmt->bind_param('i', $value);
} else {
$stmt->bind_param('s', $value);
}
$stmt->execute();
$stmt->bind_result($detail);
$stmt->fetch();
$data[] = $detail;
$stmt = null;
}
return $data;
} else {
$stmt = $this->mysqli->prepare("SELECT `$detail` FROM `$table` WHERE `$column` = ?");
if(is_numeric($value)) {
$stmt->bind_param('i', $value);
} else {
$stmt->bind_param('s', $value);
}
$stmt->execute();
$stmt->bind_result($detail);
$stmt->fetch();
return $detail;
}
}
public function exists($detail, $table, $column, $value) {
$stmt = $this->mysqli->prepare("SELECT `$detail` FROM `$table` WHERE `$column` = ?");
switch(is_numeric($value)) {
case true:
$stmt->bind_param('i', $value);
break;
case false:
$stmt->bind_param('s', $value);
break;
}
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows >= 1) {
return true;
} else {
return false;
}
}
Create a hash field in your table, make it long enough to avoid length issue.
md5() is not acceptable now, you should be using better hash function such as password_hash()
Register:
private function register($username, $password) {
//safer than md5() anyway
$hash = password_hash($password, PASSWORD_DEFAULT);
$sql = 'INSERT INTO table_name (`username`, `hash`) VALUES (?, ?);'
$stmt = $this->_db->mysqli->prepare($sql);
$stmt->bind_param('ss', $username, $hash);
$stmt->execute();
if($stmt->affected_rows >= 1) {
return true;
} else {
return false;
}
}
Login :
public function login($username, $password) {
// Check if the user exists
if($this->_db->exists('username', 'users', 'username', $username)) {
// If the account is active
if ($this->_db->detail('active', 'users', 'username', $username) === 1) {
$sql = 'SELECT `username`, `hash` FROM `users` WHERE `username` = ? AND `active` = 1';
$stmt = $this->_db->mysqli->prepare();
$stmt->bind_param('ss', $username, $hash);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows === 1) {
if (password_verify($password, $hash)) {
// Function to update last_active
if($this->updateLastActive($username)) {
echo 'last active updated, Login successful';
return true;
} else {
echo 'Editing last active date went wrong';
return false;
}
} else {
echo 'Wrong username and password combination';
return false;
}
} else {
echo 'Account not active';
return false;
}
} else {
echo 'Username doesn\'t exists';
return false;
}
}
}
Of course you can still use custom salt, for example
$hash = password_hash($password
,PASSWORD_DEFAULT
,array('salt' =>generate()));//generate() returns the salt

User Registration Alphanumeric issue

I'm having some issues with my user registration system--namely the CheckUsername function inside of it.
This code:
function checkUsername($username) {
if ( preg_match('/\s/',$username)) {
return false;
}
if(!preg_match('/^[\w\-]+$/', $username)) {
return false;
}
if(strlen($username) == 0) {
return false;
}
else {
$sql = "SELECT count(username) FROM users WHERE username = :username LIMIT 1";
$que = $this->db->prepare($sql);
$que->bindParam('username', $username);
try {
$que->execute();
while($row = $que->fetch(PDO::FETCH_BOTH)) {
if($row[0] > 0) {
return false;
}
else {
return true;
}
}
}
catch(PDOException $e) {}
}
}
Isn't working as designed. Users are able to register with names like <script>, which I clearly do not want.
function registerUser($password, $username)
{
if(!$this->checkUsername($username))
{
header('location:index.php');
}
else
{
$password = $this->passwordEncryption($password);
$sql = "INSERT INTO users(username, password) VALUES (:username, :password);";
$sql .= "INSERT INTO bank_accounts(balance, fuel_cell, energy_cell) VALUES (100,100, 100);";
$que = $this->db->prepare($sql);
$que->bindParam('username', $username);
$que->bindParam('password', $password);
try{
$que->execute();
$que->nextRowset();
$this->login($username, $password);
}
catch(PDOException $e){}
}
}
This states if there is not a word character or - so any string that contains a word character or - and anything else is OK:
if(!preg_match('/^[\w\-]+$/', $username)) {
return false;
}
You probably want if there is any character that is not a word character or -
if(preg_match('/[^\w\-]+$/', $username)) {
return false;
}
try the following :)
function checkUsername($username) {
$username = trim("$username");
if ( empty($username) || !preg_match("/^a-z0-9\-]+$/i", $username)) {
return false;
}
$sql = "SELECT count(1) FROM users WHERE username = :username LIMIT 1";
$que = $this->db->prepare($sql);
$que->bindParam('username', $username);
try{
$que->execute();
while($row = $que->fetch(PDO::FETCH_BOTH)) {
if($row[0] > 0) {
return false;
} else {
return true;
}
}
} catch(PDOException $e){}
}

Function which checks if data exist returns false, while the credentials are correct

For some reason validatelogin returns false, while i'm sure the credentials are correct. Is there something wrong with the syntax I'm using? Thanks in advance!
function validateLogin($username, $password)
{
var_dump(func_get_args());
if($stmt = $this->dbh->prepare("SELECT * FROM user WHERE username = ? AND password = ?"))
{
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
if($stmt->num_rows > 0)
{
$user = $stmt->fetch_assoc();
return $user;
}
return false;
}
}
function login()
{
$this->username = $_POST['username'];
$this->password = $_POST['password'];
if(!empty($this->username) && !empty($this->password))
{
$user = $this->userModel->validateLogin($this->username, $this->password);
var_dump($user); //FALSE
if($user){
$this->user = $user;
$_SESSION['user_id'] = $user['id'];
header('Location: http://localhost/cms/user.php?id=' . $_SESSION['user_id']);
}
else
{
echo "user not found";
}
}
else
{
echo "not filled";
}
}
i think your function is returning false because you tell it to return fase within the if $stmt, give this a shot:
function validateLogin($username, $password)
{
var_dump(func_get_args());
if($stmt = $this->dbh->prepare("SELECT * FROM user WHERE username = ? AND password = ?"))
{
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
if($stmt->num_rows > 0)
{
$user = $stmt->fetch_assoc();
return $user;
}
else{
return false;
}
}
else{
return false;
}
}

Categories