-1

When I call the two line below from index.php it is supposed to set the current id of the model to 999. When I check the database it is 0.

Whoever if I change the value of the variable from within the Model class source code it shows up in the database.

If included all the source code from the two files. If you can spot the reason why I can't use the setCurrentUserId function of the model class I would appreciate it.

  $model = Model::getInstance();
  $model->setCurrentUserId(999);
public function setCurrentUserId($user_id) {
   $this->currentuserid = $user_id;   
}

index.php

<?php
    include_once("Globals.php");
    include_once("Model.php");

    session_start();
    $msg = "";

    if(isset($_POST['login'])){
        $username = $_POST['username'];
        $password = $_POST['password'];
        $password = sha1($password);
        $userType = $_POST['userType'];
        global $conn;
        $sql = "SELECT * FROM `user` WHERE `username`=? AND `password`=? AND `user_type`=?";
        $stmt=$conn->prepare($sql);
        $stmt->bind_param("sss", $username, $password, $userType);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();

        session_regenerate_id();
        $_SESSION['username'] = $row['username'];
        $_SESSION['role'] = $row['user_type'];
        $_SESSION['doctor_id'] = $row['doctor_id'];
        $_SESSION['patient_id'] = $row['patient_id'];
        $_SESSION['care_giver_id'] = $row['care_giver_id'];
        $_SESSION['admin_id'] = $row['admin_id'];



        if($result->num_rows == 1 && $_SESSION['role'] == "doctor"){
            header("location:DoctorDashboardView.php");
        } else if($result->num_rows == 1 && $_SESSION['role'] == "caregiver"){
            $model = Model::getInstance();
            $model->setCurrentUserId(999);
            header("location:CaregiverCODetailView.php");
        } else if($result->num_rows == 1 && $_SESSION['role'] == "admin"){
            header("location:AdminDashboardView.php");
        } else{
            $msg = "Username or Password is Incorrect!";
        }
        session_write_close();
    }
?>


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Log in</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.7 -->
<link rel="stylesheet" href="../../bower_components/bootstrap/dist/css/bootstrap.min.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="../../bower_components/font-awesome/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="../../bower_components/Ionicons/css/ionicons.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="../../dist/css/AdminLTE.min.css">
<!-- iCheck -->
<link rel="stylesheet" href="../../plugins/iCheck/square/blue.css">

<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->

<!-- Google Font -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic">
</head>
<body class="hold-transition login-page">
<div class="login-box">
    <div class="login-box-body justify-content-center" >
        <p class="login-box-msg">User Login</p>

        <!-- Lets redirect the users to a page based on their role-->
        <form action="<?= $_SERVER['PHP_SELF'] ?>" method="post">
            <div class="form-group has-feedback">
                <input type="text" name="username" class="form-control" placeholder="USERNAME" required>
                <span class="glyphicon glyphicon-envelope form-control-feedback"></span>
            </div>
            <div class="form-group has-feedback">
                <input type="password" name="password" class="form-control" placeholder="PASSWORD" required>
                <span class="glyphicon glyphicon-envelope form-control-feedback"></span>
            </div>
            <div class="form-group">
                <label for="UserType">I am a :</label>
                <input type = "radio" name= "userType" value="caregiver" class="custom-radio" required>&nbsp;Caregiver |
                <input type = "radio" name= "userType" value="doctor" class="custom-radio" required>&nbsp;Doctor |
                <input type = "radio" name= "userType" value="admin" class="custom-radio" required>&nbsp;Admin
            </div>

            <div class="row d-flex justify-content-center">
                <!-- /.col -->
                <div class="col-xs-4 ">
                <input type="submit" name="login" class="btn btn-primary btn-block btn-flat"></button>
                </div>
                <!-- /.col -->
            </div>
            <h5 class="text-danger text-center"><?= $msg; ?></h5>
        </form>    
    <!-- /.social-auth-links -->
    </div>
<!-- /.login-box-body -->
</div>
<!-- /.login-box -->

<!-- jQuery 3 -->
<script src="../../bower_components/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap 3.3.7 -->
<script src="../../bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- iCheck -->
<script src="../../plugins/iCheck/icheck.min.js"></script>
<script>
$(function () {
$('input').iCheck({
checkboxClass: 'icheckbox_square-blue',
radioClass: 'iradio_square-blue',
increaseArea: '20%' /* optional */
});
});
</script>
</body>
</html>


Model.php

<?php
class Model{
    private static $instance = null;
    private $currentview = "";
    private $currentauthorizationlevel = 0;
    //0 for admin ,1 doctor, 2 for patient, 3 for caregiver
    private static $currentuserid = 0;

    private function __construct() {

    }

    public static function getInstance(){
        if (self::$instance == null){
        self::$instance = new Model();
        }
        return self::$instance;
    }



    public function authenticateAdmin($uname, $pin_submitted){        

        global $model;
        global $conn;
        global $message;
        $sql = "SELECT * from admin WHERE username = '$uname'";
        $result = $conn->query($sql);
        $row = $result -> fetch_array();
        $real_pin = $row['pin'];

        if($pin_submitted == $real_pin){
            return true;
        }else{
            $message = "Invalid username or password!";
            return false;
        }
    }

    public function addDoctorUser($user_name, $pin, $first, $last, $active) {

        global $conn;
        global $userModel;
        $userModel = new ModelUser();
        $doctor_id = $userModel->addDoctor($first, $last, $active);

        if($doctor_id > 0){

            $sql = "INSERT INTO user (username, pin, doctor_id, patient_id, care_giver_id , active) values('$user_name' ,'$pin', '$doctor_id', NULL, NULL,'$active')";

            if(!mysqli_query($conn, $sql)){
                return false;
            }else{
                return true;
            }

        }else{
            return false;
        }
    }

    public function removeDoctorUser($user_name) {

        global $conn;
        global $userModel;
        $userModel = new UserModel();

        $sql = "SELECT doctor_id from user WHERE username = '$user_name'";
        $result = $conn->query($sql);
        $row = $result -> fetch_array();
        $doctor_id = $row['doctor_id'];
        $num = $userModel->removeDoctor($doctor_id);

        if($num == 1){

            $sql = "UPDATE user SET active = 0 WHERE username = '$user_name'";
            if(!mysqli_query($conn, $sql)){
                return false;
            }else{
                return true;
            }
        }else{
            return false;
        }
    }

    public function activateDoctorUser($user_name) {

        global $conn;
        global $userModel;
        $userModel = new UserModel();

        $sql = "SELECT doctor_id from user WHERE username = '$user_name'";
        $result = $conn->query($sql);
        $row = $result -> fetch_array();
        $doctor_id = $row['doctor_id'];
        $num = $userModel->activateDoctor($doctor_id);

        if($num == 1){

            $sql = "UPDATE user SET active = 1 WHERE username = '$user_name'";
            if(!mysqli_query($conn, $sql)){
                return false;
            }else{
                return true;
            }
        }else{
            return false;
        }
    }

    public function addPatientUser($user_name, $pin, $first, $last, $date_of_birth, $active) {

        global $conn;
        global $userModel;
        $userModel = new UserModel();
        $patient_id = $modelUser->addPatient($first, $last, $date_of_birth, $active);

        if($patient_id > 0){

            $sql = "INSERT INTO user (username, pin, doctor_id, patient_id, care_giver_id , active) values('$user_name' ,'$pin', NULL, '$patient_id', NULL,'$active')";

            if(!mysqli_query($conn, $sql)){
                return false;
            }else{
                return true;
            }

        }else{
            return false;
        }
    }

    public function removePatientUser($user_name) {

        global $conn;
        global $userModel;
        $userModel = new UserModel();

        $sql = "SELECT patient_id from user WHERE username = '$user_name'";
        $result = $conn->query($sql);
        $row = $result -> fetch_array();
        $patient_id = $row['patient_id'];
        $num = $userModel->removePatient($patient_id);

        if($num == 1){

            $sql = "UPDATE user SET active = 0 WHERE username = '$user_name'";
            if(!mysqli_query($conn, $sql)){
                return false;
            }else{
                return true;
            }
        }else{
            return false;
        }
    }

    public function activatePatientUser($user_name) {

        global $conn;
        global $userModel;
        $userModel = new UserModel();

        $sql = "SELECT patient_id from user WHERE username = '$user_name'";
        $result = $conn->query($sql);
        $row = $result -> fetch_array();
        $patient_id = $row['patient_id'];
        $num = $userModel->activatePatient($patient_id);

        if($num == 1){

            $sql = "UPDATE user SET active = 1 WHERE username = '$user_name'";
            if(!mysqli_query($conn, $sql)){
                return false;
            }else{
                return true;
            }
        }else{
            return false;
        }
    }

    public function addCareGiverUser($user_name, $pin, $first, $last, $is_nurse, $active) {

        global $conn;
        global $userModel;
        $userModel = new UserModel();
        $care_giver_id = $userModel->addCareGiver($first, $last, $is_nurse, $active);

        if($care_giver_id > 0){

            $sql = "INSERT INTO user (username, pin, doctor_id, patient_id, care_giver_id , active) values('$user_name' ,'$pin', NULL, NULL, '$care_giver_id', '$active')";

            if(!mysqli_query($conn, $sql)){
                return false;
            }else{
                return true;
            }

        }else{
            return false;
        }
    }

    public function removeCaregiverUser($user_name) {

        global $conn;
        global $userModel;
        $userModel = new UserModel();

        $sql = "SELECT care_giver_id from user WHERE username = '$user_name'";
        $result = $conn->query($sql);
        $row = $result -> fetch_array();
        $care_giver_id = $row['care_giver_id'];
        $num = $userModel->removeCaregiver($care_giver_id);

        if($num == 1){

            $sql = "UPDATE user SET active = 0 WHERE username = '$user_name'";
            if(!mysqli_query($conn, $sql)){
                return false;
            }else{
                return true;
            }
        }else{
            return false;
        }
    }

    public function activateCaregiverUser($user_name) {

        global $conn;
        global $userModel;
        $userModel = new UserModel();

        $sql = "SELECT care_giver_id from user WHERE username = '$user_name'";
        $result = $conn->query($sql);
        $row = $result -> fetch_array();
        $care_giver_id = $row['care_giver_id'];
        $num = $userModel->activateCaregiver($care_giver_id);

        if($num == 1){

            $sql = "UPDATE user SET active = 1 WHERE username = '$user_name'";
            if(!mysqli_query($conn, $sql)){
                return false;
            }else{

                return true;
            }
        }else{
            return false;
        }
    }

    public function updateUserUsername($username, $newusername) {

        global $conn;
        $sql = "UPDATE user SET  username = '$newusername' WHERE username = $username";
        if(!mysqli_query($this->conn, $sql)){
            return false;
        }else{
            return true;    
        }
    }

    public function updateUserPin($username, $pin) {

        global $conn;
        $sql = "UPDATE user SET  pin = '$pin' WHERE username = $username";
        if(!mysqli_query($this->conn, $sql)){
            return false;
        }else{
            return true;    
        }
    }

    /**
    * Method creates an Order using the form where Doctor enters in parameters
    */
    public function doctorCreatesOrder($order_id,$doctor_id, $patient_id) {

        global $conn;

        //notice care_giver_id is hardcoded to 0000, there is no caregiver with
        //this id number. It represents NULL. Which means we havent assigned a
        //care_giver yet.

        $sql = "INSERT INTO `order` (`order_id`,`doctor_id`, `patient_id`, `care_giver_id`, `date`) VALUES ('$order_id','$doctor_id', '$patient_id', '0000', CURDATE())";
        if(!mysqli_query($conn, $sql)){
           return false;
        }else{
           return true;
        }
    }

    /**
    * Methods adds medications to an Order
    */
    public function addMeds2Order($order_id , $med_id, $med_qty){
        global $conn;

        //administertime is blank, when an order doesnt have a caregiver yet
        $sql = "INSERT INTO break_down(order_id, medication_id, quantity, administer_time) values('$order_id', '$med_id', '$med_qty', '')";

        if(!mysqli_query($conn, $sql)){
            return false;
        }else{
            return true;   
        }

    }



    public function setCurrentView($newView) {

        $model->currentView = $newView;

        if($newView == "AdminLoginView"){
            header("Location: AdminLoginView.php");
        }else if($newView == "HomeView"){
            header("Location: index.php");
        }else if($newView == "DoctorDisplaysOrders"){     //redirect to list of all orders, after new order is made
            header("Location: DoctorDisplaysOrders.php");
        }else if($newView =="CaregiverView"){
            header("Location: CaregiverClaimsOrderView.php");
        }else if($newView =="AdminDashboardView"){
            header("Location: AdminDashboardView.php");
        }else{
            header("Location: fail.php");
        }
    }

    public function getCurrentView() {
        return($this->currentview);
    }

    public function setCurrentAuthorizationLevel($auth_num) {
        $this->currentauthorizationlevel = $auth_num;   
    }

    public function getCurrentAuthorizationLevel() {
        return($this->currentauthorizationlevel);
    }

     public function setCurrentUserId($user_id) {
        $this->currentuserid = $user_id;   
    }

    public function getCurrentUserId() {
        return($this->currentuserid);
    }
}


?>
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Isse Nur
  • 53
  • 8
  • `$currentuserid` within your `Model` class should not be `static`. Also, the `$currentuserid` value is never used – Phil Apr 22 '20 at 01:18
  • **Never store passwords in clear text or using MD5/SHA1!** Only store password hashes created using PHP's [`password_hash()`](https://php.net/manual/en/function.password-hash.php), which you can then verify using [`password_verify()`](https://php.net/manual/en/function.password-verify.php). Take a look at this post: [How to use password_hash](https://stackoverflow.com/q/30279321/1839439) and learn more about [bcrypt & password hashing in PHP](https://stackoverflow.com/a/6337021/1839439) – Dharman Apr 22 '20 at 01:35
  • What do you mean you can't use the setCurrentUserId? What debugging have you done? What is the purpose of this awful Model class? Why are you showing us all your code? Which part of it is not working and what should we focus on? – Dharman Apr 22 '20 at 01:37
  • I would advice to learn OOP and refactor your code. This is a spaghetti code, which will be difficult to maintain and it is a terrible idea to write such class. – Dharman Apr 22 '20 at 01:39
  • @Dharman, I did two test cases with the code. I tried setting the currentuserid field of the Model class and I tested it. It works perfectly. Then I tried the same test again but this time I set the value for the currentuserid from the index.php and it did not work – Isse Nur Apr 22 '20 at 02:00

1 Answers1

0

I tried the following at the start of index.php:

include_once("Globals.php");
include_once("Model.php");
$m = Model::getInstance();
echo $m->setCurrentUserId(1);
echo $m->getCurrentUserId(1);

It echoes expected "1" in "php -S localhost: Expected output

It may seem obvious but, are you using a Post request when checking for the value? Also, does it have a login parameter? username? password?, I would rather check that those conditionals are working since de function may be called successfully at the start of the code.

LuisE
  • 553
  • 3
  • 18
  • What made you answer this question? This is not a very good question to answer and it won't bring you any reputation. If you want to get back to answering, I would recommend focusing on questions which are clear and should be answered. – Dharman Apr 22 '20 at 01:42
  • I think I may not be aware of current rules of StackOverflow, and I lack understanding on which questions are worthy of answers. Should I have replied as a comment instead? Was it wrong for me to answer it? or maybe it is just useless? – LuisE Apr 22 '20 at 01:47
  • Yes, your answer does not provide a useful solution. It would be better as a comment under the question. We answer only if we think the solution will be useful for future readers. In this case the question is unclear and lack debugging details, so it should be closed instead. Of course you are free to disagree and I can't force you to answer or don't. It's your choice. My advice would be to focus on questions where you can share your knowledge and experience and where it will be appreciated more. – Dharman Apr 22 '20 at 01:52
  • I kindly accept your suggestion since you seem to be an active user and I would like to follow convention on what to answer and what not to answer. Thank you very much for taking some of your time to answer my inquiry. – LuisE Apr 22 '20 at 01:54
  • @LuisE yes I am using post request. The login works fine but within the login process, I am supposed to set the current user id of the Model class to the user_id associated with whichever user logged in. So just to test it I put 999 as the user id. There is a class in the middle that uses that number(999) to run an insert query into the database. It doesn't work, but it also doesn't throw an error. – Isse Nur Apr 22 '20 at 02:06