Skip to content

Instantly share code, notes, and snippets.

@nhalstead
Last active April 14, 2018 18:51
Show Gist options
  • Save nhalstead/377daa433ef680229eac753b0fe4160e to your computer and use it in GitHub Desktop.
Save nhalstead/377daa433ef680229eac753b0fe4160e to your computer and use it in GitHub Desktop.
Update Deniz
<?php
require_once("db_config.php");
class User {
protected $db;
public $id = null;
private static $instance = null;
/**
* Create an Instace of the User Class and Return it.
* @return User
*/
public static function getInstance(){
if(self::$instance == null){
self::$instance = new User();
}
return self::$instance;
}
/**
* Get the Currrent User Session and return the User Data.
* @return array|bool Array of the User Data or false if none exists.
*/
public static function getUser($i = null){
// If Given a User Session, Check and Use it.
if($i !== null && $i instanceof User){
$use = $i;
}
else{
$use = self::getInstance();
}
// If the Session is Valid, Pull the User Data otherwise return false.
if(isset($_SESSION['uid'])){
return $use->get_user_by_id($_SESSION['uid']);
}
else {
return false;
}
}
/**
* Override the current Value of the Instance.
*/
public static function setInstance($i){
self::$instance = $i;
}
/**
* Check the Instance Var in the Class.
* @return bool If Instance is defined.
*/
public static function hasInstance(){
if(isset(self::$instance) && self::$instance !== null){
return true;
}
return false;
}
/**
* Update User Account Details
* @return bool If the Update was Good.
*/
public static function updateUser($uid, $fname, $lname, $username, $email, $password) {
$i = self::getInstance();
return $i->update_user($uid, $fname, $lname, $username, $email, $password);
}
/**
* Update User Account Profile Details
* @return bool If the Update was Good.
*/
public static function updateProfile($uid, $fname, $lname, $email, $address, $zipcode, $city, $phone) {
$i = self::getInstance();
return $i->update_profile($uid, $fname, $lname, $email, $address, $zipcode, $city, $phone);
}
public static function has_session(){
if(session_status() == PHP_SESSION_NONE){
session_start();
}
if( !isset($_SESSION['login']) || !isset($_SESSION['uid']) ){
return false;
}
return true;
}
public function __construct(){
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if(!class_exists("DB_con")){
throw new Exception('DB_con Class does NOT Exist! Please Load the Class to Operate!');
}
$this->db = new DB_con();
$this->db = $this->db->ret_obj();
}
protected function cleanMyStuff(&$in = ""){
$in = mysqli_real_escape_string($this->db, $in);
}
/**
* For Registration, Create new User
* @return bool If the User was Created
*/
public function reg_user($fname, $lname, $username, $email, $password){
$this->cleanMyStuff($fname);
$this->cleanMyStuff($lname);
$this->cleanMyStuff($username);
$this->cleanMyStuff($email);
$this->cleanMyStuff($password);
$password = sha1($password);
// Check if the Username or Email is already in use by another User.
$query = "SELECT * FROM `users` WHERE `uname`='$username' OR `uemail`='$email'";
$result = $this->db->query($query) or die($this->db->error);
$count_row = $result->num_rows;
// If the Username & the Email are not used already then register the account.
if($count_row == 0){
$query = "INSERT INTO `users` SET `fname` = '$fname', `lname` = '$lname', `uname` = '$username', `upass` = '$password', `uemail` = '$email'";
$result = $this->db->query($query) or die($this->db->error);
return true;
} else {
return false;
}
}
/**
* For Admins, Update the User Account
* @see reg_user
* @return bool If the User was Updated
*/
public function update_profile($uid, $fname, $lname, $email, $address, $zipcode, $city, $phone){
$this->cleanMyStuff($uid);
$this->cleanMyStuff($fname);
$this->cleanMyStuff($lname);
$this->cleanMyStuff($email);
$this->cleanMyStuff($address);
$this->cleanMyStuff($zipcode);
$this->cleanMyStuff($city);
$this->cleanMyStuff($phone);
$password = sha1($password);
// Check if the UID is registerd.
$query = "SELECT * FROM `users` WHERE `uid`='$uid'";
$result = $this->db->query($query) or die($this->db->error);
$count_row = $result->num_rows;
// If the Username & the Email are not used already then register the account.
if($count_row !== 0){
$query = "UPDATE `users` SET `fname` = '$fname', `lname` = '$lname', `uname` = '$username', `upass` = '$password', `uemail` = '$email' WHERE `uid` ='$uid'";
$result = $this->db->query($query) or die($this->db->error);
return true;
} else {
return false;
}
}
/**
* For Users, Update Profile
* @see reg_user
* @return bool If the User was Updated
*/
public function update_user($uid, $fname, $lname, $username, $email){
$this->cleanMyStuff($uid);
$this->cleanMyStuff($fname);
$this->cleanMyStuff($lname);
$this->cleanMyStuff($username);
$this->cleanMyStuff($email);
// Check if the UID is registerd.
$query = "SELECT * FROM `users` WHERE `uid`='$uid'";
$result = $this->db->query($query) or die($this->db->error);
$count_row = $result->num_rows;
// If the Username & the Email are not used already then register the account.
if($count_row !== 0){
$query = "UPDATE `users` SET `fname` = '$fname', `lname` = '$lname', `uname` = '$username', `uemail` = '$email' WHERE `uid` ='$uid'";
$result = $this->db->query($query) or die($this->db->error);
return true;
} else {
return false;
}
}
/**
* For Users, Update Password
* @see reg_user
* @return bool If the User was Updated
*/
public function update_password($uid, $password){
$this->cleanMyStuff($password);
$password = sha1($password);
// Check if the UID is registerd.
$query = "SELECT * FROM `users` WHERE `uid`='$uid'";
$result = $this->db->query($query) or die($this->db->error);
$count_row = $result->num_rows;
// If the Username & the Email are not used already then register the account.
if($count_row !== 0){
$query = "UPDATE `users` SET `upass` = '".$password."' WHERE `uid` ='$uid'";
$result = $this->db->query($query) or die($this->db->error);
return true;
} else {
return false;
}
}
/**
* For Users, Check if Passwords Match
* @return bool If the Password Matched
*/
public function match_password($uid, $password){
$this->cleanMyStuff($uid);
$this->cleanMyStuff($username);
$this->cleanMyStuff($password);
$password = sha1($password);
// Check if the UID is registerd.
$query = "SELECT * FROM `users` WHERE `uid`='$uid'";
$result = $this->db->query($query) or die($this->db->error);
$count_row = $result->num_rows;
// If the Username & the Email are not used already then register the account.
if($count_row !== 0){
$query = "SELECT `uid` FROM `users` WHERE `uid`='$uid' AND `upass`='$password'";
$result = $this->db->query($query) or die($this->db->error);
return true;
} else {
return false;
}
}
/**
* For Login Processes, Create the Session and store it.
* @return bool If User can Login
*/
public function check_login($emailusername, $password){
$this->cleanMyStuff($emailusername);
$this->cleanMyStuff($password);
$password = sha1($password);
$query = "SELECT `uid` FROM `users` WHERE `uemail`='$emailusername' OR `uname`='$emailusername' AND `upass`='$password'";
$result = $this->db->query($query) or die($this->db->error);
$user_data = $result->fetch_array(MYSQLI_ASSOC);
$count_row = $result->num_rows;
if ($count_row == 1) {
unset($_SESSION['permissions']);
$_SESSION['login'] = true; // this login var will use for the session thing
$_SESSION['uid'] = $user_data['uid'];
return true;
}
else{
return false;
}
}
/**
* Return the Current Status of the User's Profile
* @see fetch_role
* @return string User Highest Role
*/
public function get_status($uid){
$this->cleanMyStuff($uid);
$query = "SELECT * FROM `roles` INNER JOIN `roles_and_permissions` ON
`roles_and_permissions`.`permission_id` = `roles`.`role_id` WHERE
`uid` = ".$uid." ORDER BY `roles`.`order` DESC LIMIT 0 , 30";
$result = $this->db->query($query) or die($this->db->error);
$user_data = $result->fetch_array(MYSQLI_ASSOC);
if ($user_data) {
$role = $user_data['role_name'];
} else {
$role = 'NONE';
}
return $role;
}
/**
* Apply the User Roles based on input from the form. Auto: Add, Remove.
* @return bool true
*/
public function update_roles($uid, $roles) {
$user_roles = $this->fetch_roles_order($uid); // Get all User Roles.
//$user_roles = array_column($user_roles, "role_id"); // PHP new than 5.5
$user_roles = array_map(function($item) {
return $item["role_id"];
}, $user_roles);
$all_roles = $this->fetch_all_roles();
$all_roles = array_map(function($item) {
return $item["role_id"];
}, $all_roles);
// Loop through all of the Role IDs passed in
foreach($roles as $index => $roleId){
if(in_array($roleId, $user_roles)){
// Already in the User's Account.
continue;
}
else {
// Role is not not in the User's Account.
$this->add_role($uid, $roleId);
}
}
$remove = array_diff($all_roles, $roles);
foreach($remove as $index => $roleId){
$this->remove_role($uid, $roleId);
}
//exit();
return true;
}
/**
* Gets the Primary Role of the User's Account
* @return string User Highest Role (In Upper Format)
*/
public function fetch_role($uid) {
$this->cleanMyStuff($udi);
// User Session Exists
$query = "SELECT * FROM `roles` INNER JOIN `roles_and_permissions` ON
`roles_and_permissions`.`permission_id` = `roles`.`role_id` WHERE
`uid` = ".$uid." ORDER BY `roles`.`order` DESC LIMIT 0 , 30";
$result = $this->db->query($query) or die($this->db->error);
$user_data = $result->fetch_array(MYSQLI_ASSOC);
if(!empty($user_data)){
return strtoupper($user_data['role_name']);
} else {
return "NONE";
}
}
/**
* Get All of the Roles the User has Assigned to them.
* @return array Role List
*/
public function fetch_roles($uid) {
$user_data = array();
$query = "SELECT * FROM `roles` INNER JOIN `roles_and_permissions` ON
`roles_and_permissions`.`permission_id` = `roles`.`role_id` WHERE
`uid` = ".$uid." ORDER BY `roles`.`order` DESC LIMIT 0 , 30";
// User Session Exists
$result = $this->db->query($query) or die($this->db->error);
while($tmp = $result->fetch_array(MYSQLI_ASSOC)){
$user_data[] = strtoupper($tmp['role_name']);
}
// RUN THE MYSQL QUERY TO FETCH THE USER, SAVE INTO $row
if(!empty($user_data)){
return $user_data;
} else {
return array();
}
}
/**
* Get all of the Roles that are for the User raw from the DB.
* @return array Role List
*/
public function fetch_roles_order($uid) {
$user_data = array();
$query = "SELECT * FROM `roles_and_permissions` INNER JOIN `roles` ON
`roles_and_permissions`.`permission_id` = `roles`.`role_id` WHERE
`roles_and_permissions`.`uid` = ".$uid." ORDER BY `roles`.`order` DESC LIMIT 0 , 30";
$result = $this->db->query($query) or die($this->db->error);
while($tmp = $result->fetch_array(MYSQLI_ASSOC)){
$user_data[] = $tmp;
}
return $user_data;
}
/**
* Get All of the Users in the Database.
* @return array $users
*/
public function fetch_all_users() {
$users = array();
$query = "SELECT * FROM `users`WHERE `uid` != 0 ORDER BY `uid` DESC LIMIT 0 , 30";
// User Session Exists
$result = $this->db->query($query) or die($this->db->error);
while($tmp = $result->fetch_array(MYSQLI_ASSOC)){
unset($tmp['upass']); // Make it safe
$users[] = $tmp;
}
return $users;
}
/**
* Get All of the Roles in the Database.
* @return array $all_roles
*/
public function fetch_all_roles() {
$all_roles = array();
$query = "SELECT * FROM `roles` ORDER BY `order` DESC LIMIT 0 , 30";
// User Session Exists
$result = $this->db->query($query) or die($this->db->error);
while($tmp = $result->fetch_array(MYSQLI_ASSOC)){
unset($tmp['upass']); // Make it safe
$all_roles[] = $tmp;
}
return $all_roles;
}
/**
* Get All of the Users in the Database THAT HAVE ROLES.
* @return array $user_data
*/
public function fetch_all_users_wr() {
$user_data = array();
$query = "SELECT * FROM `users` INNER JOIN `roles_and_permissions` ON
`roles_and_permissions`.`uid` = `users`.`uid` WHERE
`users`.`uid` != 0 ORDER BY `roles`.`order` DESC LIMIT 0 , 30";
// User Session Exists
$result = $this->db->query($query) or die($this->db->error);
while($tmp = $result->fetch_array(MYSQLI_ASSOC)){
$user_data[] = $tmprole_name;
}
return $user_data;
}
/**
* Check to See if the User has a Specific Role
* @return bool in_array
*/
public function has_role($uid, $roleIn = NULL){
if($roleIn == NULL || $uid == "") { return false; }
if(is_array($roleIn)){
$rolesGet = $this->fetch_roles($uid);
foreach($roleIn as $r){
if(in_array($r, $rolesGet)) {
return true;
}
}
return false;
}
else{
$rolesGet = $this->fetch_roles($uid);
return in_array($roleIn, $rolesGet);
}
}
/**
* Add a Role Property to the User's Account.
* @return bool True
*/
public function add_role($uid, $roleId) {
$user_data = array();
$query = "INSERT INTO `login_profile`.`roles_and_permissions` (`uid`, `permission_id`) VALUES ('".$uid."', '".$roleId."');";
$result = $this->db->query($query) or die($this->db->error);
return true;
}
/**
* Remove a Role Property to the User's Account.
* @return bool True
*/
public function remove_role($uid, $roleId) {
$user_data = array();
$query = "DELETE FROM `login_profile`.`roles_and_permissions` WHERE `uid` = '".$uid."' AND `permission_id` = '".$roleId."'";
$result = $this->db->query($query) or die($this->db->error);
return true;
}
/**
* Get the User By Id.
* @return array MySQL Profile
*/
public function get_user_by_id($id){
$query = "SELECT * FROM `users` WHERE `uid` = " . (int) $id . " LIMIT 1";
$result = $this->db->query($query) or die($this->db->error);
return $result->fetch_assoc();
}
/**
* Connect to the Database and Delete the User Matching the UID.
* @return bool True
*/
public function delete_user($uid){
$queryUser = "DELETE FROM `users` WHERE `uid` = '".$uid."'";
$result = $this->db->query($queryUser) or die($this->db->error);
$queryPerms = "DELETE FROM `roles_and_permissions` WHERE `uid` = '".$uid."'";
$result = $this->db->query($queryPerms) or die($this->db->error);
return true;
}
/**
* Starting the Session
* @return bool false
* @return string User Login
*/
public function get_session(){
if(isset($_SESSION['login'])){
return $_SESSION['login'];
}
else {
return false;
}
}
/**
* Gets the Session uid
* @return String The User's Session Id.
*/
public function get_uid(){
if(isset($_SESSION['uid'])){
return $_SESSION['uid'];
}
else {
return false;
}
}
/**
* Do a Cleanup of the Session
*/
public function user_logout() {
$_SESSION['login'] = FALSE;
unset($_SESSION['man_redirect']);
unset($_SESSION);
session_destroy();
}
}
function clean($in = ""){
global $mysqli;
return mysqli_real_escape_string($mysqli, $in);
}
function c($in = ""){ return clean($in); }
?>
<?php
session_start();
require_once('include/class.user.php');
$user = User::getInstance();
if ($user->get_session() && !isset($_GET['q'])){
echo "User is Logged in.";
echo "Click <a href=\"?q\">Here</a> to Logout!";
exit();
}
if (isset($_GET['q'])){
$user->user_logout();
header( "Refresh:2; url=login.php", true, 303);
echo "Ok, You are OUT! Bye, See you next time!";
exit();
}
function i(&$i, $n = "Data") { if(isset($i) && $i !== "") { return $i; } else { die("Missing ".$n."!"); } }
if (isset($_POST['submit'])) {
$P = $_POST;
$login = $user->check_login( i($P['emailusername']), i($P['password']) );
if($login == true) {
if($user->has_role($uid = $user->get_uid(), "ADMIN")){
header("Location: adminPage.php");
} else {
header("Location: home.php");
}
} else {
// Login Failed
echo 'Wrong username or password';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>OOP Login Module</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="assets/css/custom.css">
</head>
<body>
<div class="container">
<h1>Login Here</h1>
<center>Admin: Name: spar - Code spar</center>
<center>Member: Name: hej - Code 1234</center>
<center>Member2: Name: test - Code 1234</center>
<form action="" method="POST" name="login">
<table class="table " width="400">
<tr>
<th>UserName or Email:</th>
<td>
<input type="text" name="emailusername" required>
</td>
</tr>
<tr>
<th>Password:</th>
<td>
<input type="password" name="password" required>
</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>
Remember me&nbsp;&nbsp;<input id="checkBox" type="checkbox"></input><br>
<div class="ned">
<form action="adminPage.php">
<input class="btn" type="submit" name="submit" value="Login" onclick="return(submitlogin());">
</form>
<a class="hoejre" href="forgotpassword.php">forgot password?</a>
</div>
</td>
</tr>
<tr>
<td>&nbsp;</td>
<td><a href="registration.php">Register new user</a></td>
</tr>
</table>
</form>
</div>
</body>
</html>
<?php
require_once('include/class.user.php');
$user = new User();
$user->get_session();
$uid = $user->get_uid();
define("GENERAL_ERROR", "Field can not be blank!");
define("INVALID_ERROR", "Field is invalid!");
define("LENGTH_ERROR", "Field must be longer!");
$error = array(
"fname" => "",
"lname" => "",
"uname" => "",
"uemail" => "",
"upass" => ""
);
$values = array(
"fname" => "",
"lname" => "",
"uname" => "",
"uemail" => "",
"upass" => ""
);
if (isset($_POST['submit'])){
$values['fname'] = strip_tags(filter_input(INPUT_POST, 'fname', FILTER_SANITIZE_STRING));
$values['lname'] = strip_tags(filter_input(INPUT_POST, 'lname', FILTER_SANITIZE_STRING));
$values['uname'] = strip_tags(filter_input(INPUT_POST, 'uname', FILTER_SANITIZE_STRING));
$values['uemail'] = strip_tags(filter_input(INPUT_POST, 'uemail', FILTER_SANITIZE_EMAIL));
$values['upass'] = strip_tags(filter_input(INPUT_POST, 'upass', FILTER_SANITIZE_STRING));
$registerSuccess = false; // Registration Failed, Default Value
if($values['fname'] == "" || $values['lname'] == ""){
$errors['fname'] = GENERAL_ERROR;
$errors['lname'] = GENERAL_ERROR;
}
else if($values['uname'] == ""){
$error['uname'] = GENERAL_ERROR;
}
else if(strlen($values['uname']) < 6 ){
$error['uname'] = LENGTH_ERROR;
}
else if($values['upass'] == ""){
$error['upass'] = GENERAL_ERROR;
}
else if(strlen($values['upass']) < 6 ){
$error['upass'] = LENGTH_ERROR;
}
else if($values['uemail'] == "" || $values['uemail'] == false){
$error['uemail'] = INVALID_ERROR;
}
else {
// Do Registration
$registerSuccess = $user->reg_user($values['fname'], $values['lname'], $values['uname'], $values['uemail'], $values['upass']);
}
if ($registerSuccess){
// Registration Success
echo "<div class='textcenter'>Registration successful <a href='login.php'>Click here</a> to login</div>";
if(isset($_POST['man_redirect'])){
$r = $_POST['man_redirect'];
header("Location: ".$r);
}
} else {
// Registration Failed
if(isset($_SESSION['man_redirect'])){
$_SESSION['man_redirect'] = isset($_POST['man_redirect'])?$_POST['man_redirect']:"index.php"; // Set the Redirect
}
else {
unset($_SESSION['man_redirect']);
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Register</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css" />
<link rel="stylesheet" href="assets/css/custom.css" />
</head>
<body>
<?php
if(User::has_session() == true){
$navItm = "";
// Offer the Admin Page if Admin
echo '<link rel="stylesheet" href="assets/css/custom_admin.css"/>';
if( $user->has_role($uid, array("ADMIN", "MODERATOR") )){
$navItm = '<a class="navbar-left" href="adminPage.php">Mgr Page</a>';
}
echo '<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<a class="navbar-left" href="home.php">Home</a>'.
$navItm
.'<a class="navbar-right" href="home.php?q=logout">LOGOUT</a>
</div>
</nav>';
}
?>
<div class="container">
<h1>Registration Here</h1>
<form action="" method="POST" name="reg">
<table class="table">
<tr>
<th>First Name:</th>
<td>
<div><input type="text" name="fname" value="<?php echo $values['fname'] ?>" required></div>
<span class="error"><?php echo $error['fname']; ?></span>
</td>
</tr>
<tr>
<th>Last Name:</th>
<td>
<div><input type="text" name="lname" value="<?php echo $values['lname'] ?>" required></div>
<span class="error"><?php echo $error['lname']; ?></span>
</td>
</tr>
<tr>
<th>User Name:</th>
<td>
<div><input type="text" name="uname" value="<?php echo $values['uname'] ?>" required></div>
<span class="error"><?php echo $error['uname']; ?></span>
</td>
</tr>
<tr>
<th>Email:</th>
<td>
<div><input type="email" name="uemail" value="<?php echo $values['uemail'] ?>" required></div>
<span class="error"><?php echo $error['uemail']; ?></span>
</td>
</tr>
<tr>
<th>Password:</th>
<td>
<div><input type="password" name="upass" value="<?php echo $values['upass'] ?>" required></div>
<span class="error"><?php echo $error['upass']; ?></span>
</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>
<input class="btn" type="submit" onclick="window.onbeforeunload = null;" name="submit" value="Register" onclick="return(submitreg());">
</td>
</tr>
<?php
if(!isset($_SESSION['man_redirect'])){
echo '<tr>
<td>&nbsp;</td>
<td><a href="login.php">Already registered? Click Here!</a></td>
</tr>';
}
else {
echo '<tr>';
echo '<td>&nbsp;</td><td>';
echo '(You are Creating a new User, <b>Don\'t Refresh</b>)';
echo '<input type="hidden" name="man_redirect" value="'.$_SESSION['man_redirect'].'">';
unset($_SESSION['man_redirect']); // Unset the Session Var.
echo '<script>/* Enable navigation prompt*/ window.onbeforeunload = function() { return false; };</script>';
echo '</td></tr>';
}
?>
</table>
</form>
</div>
<script>
function submitreg() {
var form = document.reg;
if (form.name.value == "") {
alert("Enter Name!");
return false;
}
else if (form.uname.value == "") {
alert("Enter a Username!");
return false;
}
else if (form.upass.value == "") {
alert("Enter a Password!");
return false;
}
else if (form.uemail.value == "") {
alert("Enter an Email Addresss!");
return false;
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment