Session Doctrine in REST API - php

I need to control a session in a REST API. My REST API is implemented with slim and doctrine and within the routes.php file I have defined the POST request of the login:
session_start();
$app->post('/login', function ($request, $response) {
$em = getEntityManager();
$args = $request->getParsedBody() ?? json_decode($request->getBody(), true);
$user = $em->getRepository(Usuario::class)->findOneByUsername($args['username']);
if (null == $user) {
echo "<script language='javascript'>alert('User not found'); window.location='App.php'</script>" ;
} else {
if ($user->getPassword() == $args['password']){
$_SESSION['id'] = $user->getId();
$_SESSION['username'] = $user->getUsername();
if($user->getAdmin() && $user->getEnabled()){
echo "<script language='javascript'>window.location='Admin.php'</script>" ;
} else if($user->getEnabled()){
echo "<script language='javascript'>window.location='Comparator.php'</script>" ;
} else {
echo "<script language='javascript'>alert('Account
inabilited'); window.location='App.php'</script>" ;
}
} else {
echo "<script language='javascript'>alert('Incorrect Password'); window.location='App.php'</script>" ;
}
}
});
I have 3 page .php. In page App.php I have an access form. I want to do is that when any user wants to enter the Admin or Comparator page, he can not enter without logging in previously.
For this I have added the following code to the pages previously named:
<?php if (session_status() != "PHP_SESSION_ACTIVE" && session_status() != 2) { ?>
<script>window.location='App.php'</script>
<?php }?>
But when entering a valid username and password I get the following error:
It's very weird because the field username in the class Usuario exists.
Any solutions?

Related

redirect to profile page if user logged in

I have a login form on RedBean PHP. I need to implement redirection to profile if user was logged and just closed page, but when I open my start page I need to type email and password again and again. How to redirect user immediately to profile page if he did not log out.
I tried to use if($_SESSION['logged_user'] = $user) {header('Location: /profile');, but it did not work. Please assist. I use OpenServer Panel.
Code:
$data = $_POST;
if(isset($data['do_login'])) {
$user = R::findOne('users', 'email = ?', array($data['email']));
if($user) {
// var_dump($user);
if(password_verify($data['password'], $user->password)) {
$_SESSION['logged_user'] = $user;
header('Location: /profile');
// echo '<div style="color: green;">You are authorized! Go to Profile page</div>';
}else {
$errors[] = 'Password is not correct!';
}
} else {
$errors[] = "User with such email doesn't exist!";
}
if(!empty($errors)) {
echo '<div style="color: red;">'.array_shift($errors).'</div>';
}
}
if($_SESSION['logged_user'] = $user) {
header('Location: /profile');
}
You incorrectly write your condition.== instead of =
if($_SESSION['logged_user'] == $user) {
header('Location: /profile');
}
Let me know,if this solve your problem
I solved it by add this code:
if(isset($_SESSION['logged_user'])) {
header('Location: /profile');
}

How to use session for different users from different classes?

I'm able to successfully create sessions and run them and it works fine in pages exclusive to those particular users.
For example, if there are 8 pages for admin then those 8 pages will contain the code which checks only for the admin session from the admin class.
But if there is a page where all three have the user permission to, which will be the login page I'm unable to handle three sessions together for three separate users. When I am already logged in to the system using any one of the users and then try to go to the login page it should automatically redirect me to that user's exclusive home page. But instead it asks me to enter the login credentials again.
My PHP code:
<?php
if(isset($_SESSION['p_login'])){
header("location:login_tests/Patient.php");
}
else if(isset($_SESSION['d_login'])){
header("location:login_tests/Doctor.php");
}
else if(isset($_SESSION['a_login'])){
header("location:admin/Dashboard.php");
}
// Login functionalities
if(isset($_POST['submit1'])){
// Patient login
if($_POST['users']=="patient"){
session_start();
include_once 'classes/patient.php';
$patient = new Patient();
if ($patient->p_session())
{
header("location:login_tests/Patient.php");
}
$patient = new Patient();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$login = $patient->p_login($_REQUEST['username'],$_REQUEST['password']);
if($login){
header("location:login_tests/Patient.php");
}
else
{
echo "<script>alert('Login Failed!');</script>";
}
}
}
// Doctor login
else if($_POST['users']=="doctor"){
session_start();
include_once 'classes/doctor.php';
$doctor = new Doctor();
if ($doctor->d_session())
{
header("location:login_tests/Doctor.php");
}
$doctor = new Doctor();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$login = $doctor->d_login($_REQUEST['username'],$_REQUEST['password']);
if($login){
header("location:login_tests/Doctor.php");
}
else
{
echo "<script>alert('Login Failed!');</script>";
}
}
}
// Admin login
else{
session_start();
include_once 'classes/admin.php';
$admin = new Admin();
if ($admin->a_session())
{
header("location:admin/Dashboard.php");
}
$admin = new Admin();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$login = $admin->a_login($_REQUEST['username'],$_REQUEST['password']);
if($login){
header("location:admin/Dashboard.php");
}
else
{
echo "<script>alert('Login Failed!');</script>";
}
}
}
}
// Registration functionalities
else if(isset($_POST['submit2'])){
include_once 'classes/patient.php';
$patient = new Patient();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$register = $patient->p_register($_REQUEST['name'],$_REQUEST['gender'], $_REQUEST['dob'], $_REQUEST['nic'], $_REQUEST['address'],$_REQUEST['email'], $_REQUEST['username'], $_REQUEST['password']);
if($register){
echo "<script>alert('Registration Successful!');</script>";
}
else
{
echo "<script>alert('Entered email address or username already exists!');</script>";
}
}
}
?>
If I understand you correct, your problem is the 3 session variables $_SESSION['p_login'], $_SESSION['d_login'] and $_SESSION['a_login'].
There is no need to use 3 separate variables, use 1: $_SESSION['user'] = value.
Give it a value according to permission (e.g. patient=1, docter=2, admin=3). Then you only have to test:
if( $_SESSION['user'] < 2 ) only permission for patient pages.
if( $_SESSION['user'] < 3 ) permission for patient pages + docter pages.
if( $_SESSION['user'] < 4 ) permission for all pages.

Only one user can open admin.ctp file

I want to do a page, and this page can open only one user. I want to do something like this: If user id = 1 then its opening else its throwing error.
I already tried this :
if (in_array($this->action, array('controller' => 'users', 'action' => 'admin'))) {
$postId = (int) $this->request->params['pass'][0];
if ($this->User->isOwnedBy($postId, $users['id'] = 1)) {
return true;
}else{echo "You are not admin!";}
}
Then I thinked, maybe this is a little bit easier ?
public function admin($id = null) {
$this->User->id = $id;
if ($id == 1) {
echo 'You are admin';
}
else {
throw new NotFoundException(__('You are not admin !'));
}
}
But its not working, How I get this user id in to this if. This second solution throwing only this error, but I dont want it, I want access if user id is 1.
Here is users picture
Thank you for any clue or solution.
Try this-
public function admin($id = null) {
$currentUserId = $this->Auth->user(id);
//$isAdmin = $this->User->hasAny(
//array('User.id' => $currentUserId)
//);
//if ($isAdmin) {
if ($currentUserId == 1)
echo 'You are admin';
} else {
throw new NotFoundException(__('You are not admin !'));
}
}
For logged in users.
The recommended approach for getting logged in user data is via the AuthComponent itself:
// in any controller
$userId = $this->Auth->user('id');
See Accessing the logged in userAccessing the logged in user in the Auth section of the CakePHP Book.
Better Option:-
use role id for admins, this will help you for multiple admins. and give negative id to admin:-
like add role_id column in user table and give value to -1
public function admin($id = null) {
$role = $this->Session->read('Auth.User.role_id');
if ($role < 0)
echo 'You are admin';
} else {
throw new NotFoundException(__('You are not admin !'));
}
}
so you want to check if the user ID is 1 ??
//Fetch the user informations from database and stock it into $user
if(is_admin($user[id])){
echo 'You are admin';
}
else{
echo 'You are not admin';
}
function is_admin($id = NULL){
if($id == 1){
return true;
}
else{
return false;
}
}
tell me if I misunderstood
Edit :
According to our chat, try this :
//Fetch the ID of the user and stock it in $user_id
if($user_id == 1){
echo 'You are admin';
}
else{
echo 'You are not admin';
}

Codeigniter 2.2 failed create session

I use CI 2.2 to build a simple login system. But I get problem when I try to generate session. Of course I have properly set up libraries (database, session) and User_M. When I retrieve data from database (without session), that's work fine. This is my Controller code:
public function verify()
{
// Define variable
$user = $this->input->post('username');
$pass = $this->input->post('password');
// Check input data
if (!empty($user) AND !empty($pass))
{
// Check match data from db
$checks = $this->User_M->check_user($user, $pass);
if($checks->num_rows() == 1)
{
foreach ($checks->result() as $check)
{
$sess = array (
'username' => $check->username,
'logged_in' => TRUE
);
$rest = $this->session->set_userdata($sess);
if ($rest)
{
echo "working";
} else {
echo "not working";
}
}
} else {
echo "Not found";
}
} else {
echo "You've empty field";
}
}
Additional explain, I check the result with if ($rest)...bla..bla..bla, that's echoing Not Working. Please let me know where's my mistakes?
Thank in advance
I think the problem is with this statement
$rest = $this->session->set_userdata($sess);
the set_userdata() does not return anything, so according to your condition it will always execute the else part.
Try to change your condition like this
if (!empty($this->session->userdata("username"))){
echo "Working";
}else{
echo "Not Working";
}

PHP and AJAX Log in validation

I need some help troubleshooting my code that's used for Log In validation. It's a combo of AJAX and PHP.
Here's the AJAX code that's directly in the login page.
<script language="javascript">
$(document).ready(function()
{
$("#login_form").submit(function()
{
$("#msgbox").removeClass().addClass('messagebox').text('Validating....').fadeIn(1000);
$.post("/ajax_login.php",{ user_name:$('#username').val(),password:$('#password').val()
,rand:Math.random() } ,function(data)
{
if (data=='no')
{
$("#msgbox").fadeTo
(200,0.1,function()
{
$(this).html('Incorrect Username or Password.')
.addClass('messageboxerror').fadeTo(900,1);
}
);
}
else if(data=='yes')
{
$("#msgbox").fadeTo
(200,0.1,function()
{
$(this).html('Logging in.....').addClass('messageboxok').fadeTo
(900,1, function()
{
document.location='/mainpage.php';
}
);
}
);
}
else
{
$("#msgbox").fadeTo
(200,0.1,function()
{
$(this).html('User is already logged in.').
addClass('messageboxerror').fadeTo(900,1);
}
);
}
});
return false;
});
$("#password").blur(function()
{
$("#login_form").trigger('submit');
});
});
</script>
PHP CODE:
<?
//Log In credentials
if ($rehash==$dboPW && $user_name == $dboUN && $logged=='Y'){echo "alreadyLogged"; exit;}
if ($rehash==$dboPW && $user_name == $dboUN && $logged=='N')
{
echo "yes";
$_SESSION['login'] = $username;
$_SESSION['password'] = $rehash;
$loggedUpdate=mysql_query("UPDATE Users SET LOGGED='Y' WHERE username='$user_name'");
exit;
}
else
{echo "no";}
?>
To summarize this process, someone logs in and the PHP script checks
if the username and password is valid AND that the person is NOT logged in already - returns value of 'yes'
if the username and password is valid AND that the person IS logged in already - returns value of 'alreadyLogged'
Invalid username or password - returns value of 'no'
This gets passed to AJAX, which SHOULD display the correct messages based on the return values from the php script. For reference (using the above summary):
AJAX should return: Logging in...
AJAX should return: User is already logged in.
AJAX should return: Invalid Username or Password.
The problem is this: If someone logs in correctly and IS NOT already logged in, message 2 appears instead of message 1. (I think that message 1 may appear but it disappears so fast).
I think the culprit is AJAX but unfortunately I'm not as familiar with it as I am with PHP.
I think the problem is with your php code.Your ajax code looks fine
try this
if ($rehash==$dboPW && $user_name == $dboUN && $logged=='Y')
{
echo "alreadyLogged"; exit;
}
elseif ($rehash==$dboPW && $user_name == $dboUN && $logged=='N')
{
}
I think it is the php problem,it occur an error and return the error message. if ajax_login.php does not return "yes" or "no" it will show the second message, whatever it returns.
Just need modify your PHP. try this :
//Log In credentials
// check if post if (isset($_POST)) {
// must initially to use check if on loggin
session_start();
// set variable post
$username = $_POST['user_name'];
$password = $_POST['password']; // change if use sha1 or md5
$rand = $_POST['rand'];
// check query database
$query = mysql_query("SELECT * FROM Users WHERE username='$username' AND password='$password'");
$user = mysql_fetch_array($query);
$row = mysql_num_rows($query);
if ($row > 0) {
if ($user['LOGGED'] == 'Y') {
echo "yes";
$_SESSION['login'] = $username;
$_SESSION['password'] = $rehash;
$loggedUpdate = mysql_query("UPDATE Users SET LOGGED='Y' WHERE username='$user_name'");
exit;
} elseif ($user['LOGGED'] == 'N') { // you can use 'else'
echo "alreadyLogged";
exit;
}
} else {
// invalid value password and username
echo "no";
exit;
} }

Categories