hello i am working on a project where user and admin have different logins
I want to set different sessions for user and admin
here is I how set admin session
$this->session->set('adminData', [
'id' => $teacher['id'],
'name' => $teacher['name'],
'email' => $teacher['email'],
'new_email' => $teacher['new_email']
]);
user's session data as follows
$this->session->set('userData', [
'id' => $teacher['id'],
'name' => $teacher['name'],
'email' => $teacher['email'],
'new_email' => $teacher['new_email']
]);
but when validating user
if ($this->session->isLoggedIn) {
return redirect()->to('admin');
}
the only problem I am facing that either I can login as admin or user not both
when I try to login as user when I am already logged as admin, it redirects me to user/account.
Is there any method that i can set isAdminLoggedIn for admin and can use isLoggedIn for user?
you can set isAdminLoggedIn before or after adminData.
$this->session->set('isAdminLoggedIn', true);
and can destroy the session when you logged out
$this->session->remove(['isAdminLoggedIn']);
or together with
$this->session->remove(['isAdminLoggedIn', 'adminData']);
Related
I have time in seconds when the session should end. If the user has not selected the checkbox "remember_me" - the session will last 2 hours. When the checkbox is selected - should last - 48 hours. I have a loginСontroller, where I react - to the login result and if the validation is successful and checkbox = "on" you need to change the session time. I tried to change by looking at the documentation, and spent a lot of time looking for a solution. Maybe someone can help me. Thank you very much in advance[enter image description here]
here is my file config/app.php
'Session' => [
'defaults' => 'php',
'ini' => [
'session.cookie_lifetime' => 7200,
]
],
and here is my loginController
`public function index()
{
$this->viewBuilder()->setLayout('main');
$this->set("title", "");
$this->set("description", "description");
$this->request->allowMethod(['get', 'post']);
$result = $this->Authentication->getResult();
// regardless of POST or GET, redirect if user is logged in
if ($result->isValid()) {
if ($this->request->getData('remember') == 'on') {
///// the solution should be here
}
$redirect = [
'controller' => 'Main',
'action' => 'index',
];
return $this->redirect($redirect);
}
// display error if user submitted and authentication failed
if ($this->request->is('post') && !$result->isValid()) {
$this->Flash->saved_error(__('Invalid email or password'));
}
}`
You most likely shouldn't do it that way, your controller code shouldn't have to know about such details if it can be avoided.
The authentication plugin ships with a cookie based authenticator that you can use in addition to the session authenticator, that way you can extend authentication beyond the default session lifetime, I'd suggest that you look into that instead.
$service->loadAuthenticator('Authentication.Cookie', [
'fields' => $fields,
'loginUrl' => $loginUrl,
'cookie' => [
// cookie expires in 2 days from now
'expires' => \Cake\Chronos\Chronos::now()->addDays(2)
],
]);
By default the authenticator looks up a field named remember_me, so either rename that in your template, like:
echo $this->Form->control('remember_me', ['type' => 'checkbox']);
or configure the authenticator's rememberMeField option with the custom field name that you're using in your form.
See also
Authentication Cookbook > Authenticators > Cookie Authenticator
I used Laravel's guide to authenticating users manually at this link:
https://laravel.com/docs/7.x/authentication#remembering-users
and now I want to log every login's browser, version, platform, and ip.
My function on login:
public function store(Request $request)
{
$this->validate($request, [
'username' => 'required',
'password' => 'required'
]);
if (Auth::guard('admin')->attempt(['username' => $request->username, 'password' => $request->password, 'status' => 1], $request->remember)) {
$browserDetails = get_browser($request->header('User-Agent'), true);
LoginHistory::create([
'user_id' => auth()->guard('admin')->user()->id,
'user_type' => '2', // Admin = 2
'browser' => $browserDetails['browser'],
'browser_version' => $browserDetails['version'],
'platform' => $browserDetails['platform'],
'ip_address' => $request->ip()
]);
return redirect()->route('admin.dashboard');
}
return redirect()->back()->withErrors('Username or password incorrect.');
}
but I am getting:
ErrorException
Trying to get property 'id' of non-object
on this line:
'user_id' => auth()->guard('admin')->user()->id,
What should I do? The authentication works if I try to access login it will redirect me to dashboard so the session is created, but why can I not access the user id inside this function? It works on the edit admins page showing user id and all information.
use auth()->user()->id. when attempt () is executed and this is successful it performs the authentication
We are building a webshop based on Codeigniter. Products are saved in a shopping cart with help of Codeigniters' Cart Class.
When a visitor logs in with it's account, all products which are already in their cart are removed because a new session started when the user logged in.
How can we keep the products in the cart at this point?
if($query->num_rows() == 1)
{
$user = $query->row_array();
$data = array(
'userid' => $user['id'],
'email' => $user['email'],
'validated' => true
);
$this->session->set_userdata($data);
return true;
}
You have to create new table in base, like shoppingcarts, and pass all items from that Chart class in that table, and user ID, then when user log in just query that table with his ID and ID of row now you got all products.But when user bye just delete that rows in base and unset cart class
$data = array(
'id' => 'sku_123ABC',
'qty' => 1,
'price' => 39.95,
'name' => 'T-Shirt',
'options' => array('Size' => 'L', 'Color' => 'Red'
'user_id => '45')
);
$this->cart->insert($data);
$chart = $this->cart->contents();
$this->db->insert('shoppingcarts',$chart);
This is just simple example, how to do that :)
If users have account, you need to save data in DB.
If users don't have an account and you want to keep his chart (based on browser), then you don't need to destroy session when user close the window. You need to keep it on session until he clear his chart. You can do it on config.php file.
I have a mongo db structure for users with "username" and "password". I am trying to use the Auth in cakephp login but it seems like its not working for me. I tried removing the $this->data but still it did not work.
My password is hashed using Security::hash($this->data['User']['password'])
if(!empty($this->data))
{
if($this->Auth->login($this->data))
{
echo "yes";
}
else{
echo "no";
}
}
In my app controller I have this:
public $components = array('DebugKit.Toolbar', 'Session', 'Auth' => array(
'loginAction' => array(
'controller' => 'pages',
'action' => 'home'
),
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'username', 'password' => 'password')
)
)
));
Here is the result when I debug the login method:
array(
'User' => array(
'password' => '*****',
'username' => 'test#test.com',
'remember' => '0',
'auto_login' => '0'
)
)
I don't know why I cannot use Auth with mongodb. Thanks for the help in advance.
EDIT:
When i tried and take away the layout, it shows me a query at the bottom of the page saying:
db.users.find( {"username":"test#test.com","password":"2fdf49ffc396453960802df8fc2417655d1e8fca"}, [] ).sort( [] ).limit( 1 ).skip( 0 )
The hashed value of the password that I inputted from the form is different from the hash value that is being queried. The hashed value should be "a2374c309ab7823dcd9b4e21dae7511f7a9c7ec5". Why is it that cakephp is converting the password into another hash value?
There are two ways of using $this->Auth->login(). The CakePHP API documentation explains it:
If a $user is provided that data will be stored as the logged in user. If $user is empty or not specified, the request will be used to identify a user.
The manual also mentions:
In 2.0 $this->Auth->login($this->request->data) will log the user in with whatever data is posted ...
So for the login method of the users controller you shouldn't pass anything:
if($this->Auth->login()) {
// user is now logged in
}
Should you need to manually login a user you can pass the user data as an array:
if($this->Auth->login($this->request->data['User'])) {
// user is now logged in
}
Where $this->request->data['User'] is something like:
array(
'id' => 1,
'username' => 'admin',
'password' => '1234',
);
Note: In both cases you don't need to hash the password as it is done automatically.
I was able to find out the answer. Its because cakephp is automatically hashing the password when searching in the database.
The problem that I had was when I was saving the users' password, I am was using
Security::hash($this->data['User']['password'])
I should have used this one instead:
AuthComponent::password($this->data['User']['password'])
Thank you for all the help especially to #xgalvin
I want to test login function if it works propperly and only lets valid and active users in.
My user fixture contains:
array(
'password' => '*emptyPasswordHash*', // empty password
'username' => 'Lorem',
'balance' => 0,
'currency' => 'USD',
'id' => 1,
'user_group_id' => 3, //Customer
'active' => 1,
'hash' => 'LoremHash'
),
My test function looks like this:
function testLogin() {
//test valid login
$result = $this->testAction('/users/login', array(
'data' => array(
'User' => array(
'username' => 'Lorem',
'pass' => '',
'remember' => true
)),
'method' => 'post',
'return' => 'view'
));
debug($result);
}
The login form has 3 inputs: username, password and remember
I have set $this->Auth->autoRedirect = false; in the UsersController::beforeFilter and I am doing some cookie setting stuff
when I debug($this->data); in UsersController::login() it shows the exact same data when testing and when logging normaly. But while testing the login fails and I get $this->Auth->loginError message instead of a login.
How do I test login action propperly?
if you use cakes Auth component and dont hack it up you dont need to...
https://github.com/cakephp/cakephp/blob/master/cake/tests/cases/libs/controller/components/auth.test.php#L545
and if you really want to, look at how the pro's do it :)
Did you also set your custom function, like described in The CakePHP manual:
Normally, the AuthComponent will
attempt to verify that the login
credentials you've entered are
accurate by comparing them to what's
been stored in your user model.
However, there are times where you
might want to do some additional work
in determining proper credentials. By
setting this variable to one of
several different values, you can do
different things.