Testing setting she session used in the intended()-method in Laravel - laravel

Laravel has a intended()-method used for redirecting users after a login. It uses the session key url.intended, as seen here. However, when testing it, doesn't seem to work. I set the session like this: session(['url.intended' => url()->previous()]);
Then this is how I test the session:
$this->app['session']->setPreviousUrl('some-url');
$response = $this->get(route('login'));
$response->assertSuccessful();
$response->assertSessionHas('url', 'some-url'); //fails
$response->assertSessionHas(['url' => ['intended' => 'some-url']]); //fails
When not using dot-notation as key, it works. Meaning, I can assert a session with key urlIntended exists.
How do I go about this?

I just realized that using the intended()-method actually returns AND removes the session since it is using pull().
Here is how it is used more specifically: $path = $this->session->pull('url.intended', $default);

Related

Acessing auth user attribute

I am in the guzzle controller making a request to an external api.
I wanna use an id from the user who is logged in.
I have been doing the request with a static id, but now i want it dynamically.
I tried like this:
$science = Auth::user()->science_id;
$client = new Client(['headers' => ['Accept' => 'application/json']]);
$request = $client->get(
'https://url_to_the_api/'.$science.'/degree',
[
'auth' => ['client', 'secret'],
]
);
$data = $request->getBody()->getContents();
return $data;
And i have the error
500(internal server error)
and this message:
"Trying to get property 'science_id' of non-object"
What am i missing?
Thanks for your time
If you are using it in web app then make sure you first check if user is already authenticated by using auth middleware or manually by using Auth::check() function.
Or
If you are trying to hit this by api that will not work here because session will not be maintained in that case. That's why JWT tokens were introduced to maintain the state of an application.
I've solved it like this:
$science = auth('api')->user()->science_id;
Thanks for the help!

How to Check if Session is set in Laravel 5.7

<?php
$request = request();
// if (empty($request)) return false; .// That does not work
$loggedUserAccessGroups = $request->session()->get('loggedUserAccessGroups');
$logged_user_ip = $request->session()->get('logged_user_ip');
In my Laravel 5.7 application, I want to check if the user has the right access level in the session. It works ok but I made automatic tests and got the error:
local.ERROR: Session store not set on request.
I added checks to see if the session is set and it fails to return false.
Which is the correct way? Thanks!
You may also use the global session PHP function to retrieve and store data in the session as outlined here:
// Retrieve a piece of data from the session with the global session helper...
$loggedUserAccessGroups = session('loggedUserAccessGroups');
$logged_user_ip = session('logged_user_ip');
// Store a piece of data in the session...
session(['key' => 'value']);
For more information look at the section of The Global Session Helper in the official documentation.

remember me for laravel5.2

Hello guys I want to make the remember me checkbox and I want to save the user info into cookies so next time when try to login he find the user name and password in their fields I try to use :
$rememberMe = false;
if(isset($req->remember_me)) {
$rememberMe = true;
}
if(Sentinel::authenticate($req->all(), $rememberMe)) {
$slug = Sentinel::getUser()->roles()->first()->slug();
}
The cookies was set, I see it in the chrome settings but it does not do as I expect
I'm using laravel 5.2
You can use Cookies
cookie, is a small piece of data sent from a website and stored in a user's web browser while the user is browsing that website. Every time the user loads the website, the browser sends the cookie back to the server to notify the website of the user's previous activity
To create:
$response->withCookie(Cookie::make('name', 'value', $minutes));
To retrieve
$value = Cookie::get('name');
Your question is not to remember the user login.. The question is how to fill the inputs based on saved auth information. You can do that if you print the authentication values in the input value attribute while loading the page.
larval Cookies Docs
Also Laravel has it's own implementation of "Remember Me"
if (Auth::attempt(array('email' => $email, 'password' => $password), true))
{
// The user is being remembered...
}
if (Auth::viaRemember())
{
//
}
More information about https://laravel.com/docs/5.4/authentication#remembering-users
There is two main thing need to taken care:
1) You must pass a bool value as second parameter to the method, make sure you cast it before passing it to the method. - In your code, it's perfect
$credentials = $req->only('LOGINNAME', 'PASSNAME')
if(Sentinel::authenticate($credentials , $req->has('remember_me'))){
//Other stuff
}
2) you can verify it works by ensuring a cookie is set with the key cartalyst_sentinel?
So first change as per 1) option and then check the 2) option, may be this is your answer.

remember me functionality in codeigniter

I have implemented remember me functionality as this question
How to create "remember me checkbox" using Codeigniter session library?
first answer.
I created a cookie with a random number code as value and it stored in db(user table). On login, db code checks with cookie value.It works fine on my localhost server. But in live server which has a subdomain url has problem.Also I tested it with another server with ip address as url. There also it is not working. In both cases cookie created but cant read the cookie. Please help me.
cookie set by
$auto_login_hash_code = uniqid();
$domain = $_SERVER['SERVER_NAME'];
$cookie = array(
'name' => 'rememberMe',
'value' => $auto_login_hash_code,
'expire' => 31536000,
'domain' => $domain,
'path' => '/'
);
$this->input->set_cookie($cookie);
and reading cookie by
if (get_cookie('rememberMe')) {
$hashcode = $this->CI->input->cookie('rememberMe');
$this->CI->load->model('loginmodel', '', true);
$username = $this->CI->loginmodel->get_username_by_hashcode($hashcode);//in this function setting session variables
}
Thanks in advance
iijb
you are getting library for that on github.
search remember me on github, load it and just follow below steps.
Verify cookie if token is present in database go to home page
$this->load->library('rememberme');
$cookie_user = $this->rememberme->verifyCookie();
if ($cookie_user)
{
$this->load->view('search_view');
}
else
{
// If checkbox is checked it return true either false
$checked = (isset($_POST['Checkbox1']))?true:false;
if($checked== true)
{
//$this->load->view('tested');
$this->load->library('rememberme');
$this->rememberme->setCookie($this->input->post('loginemil'));
//$this->rememberme->setCookie('set cookie here');
}
else{
dont set anything
}
}
Also this can be done by editing/extending system Session library.
First: In user login function add remember me check-
if($remember)
{
$data['new_expiration'] = 60*60*24*30;//30 days
$this->session->sess_expiration = $data['new_expiration'];
}
$this->session->set_userdata($data);
Second: Edit system Session library [I am not sure whether extending Session will work or not]
Go to this line in sess_read() method
if (($session['last_activity'] + $this->sess_expiration) < $this->now)
Before that line add following code
if(isset($session['new_expiration'])){
$this->sess_expiration = $session['new_expiration'];
}
This works fine for me.

Session data gone after redirect in CI

i need your help.
I used the session to record the user selected business type in CI. For example,$this->ci->session->set_userdata('biztype','food'). When user login,it works ok. However, once the user logout, session will be destroyed in the function logout().So i set the userdata again in the function logout().You can view the code below:
function logout()
{
$biztype = $this->ci->session->userdata('biztype');
$this->delete_autologin();
$this->ci->session->set_userdata(array('user_id' => '', 'username' => '', 'status' => ''));
$this->ci->session->sess_destroy();
$this->ci->session->set_userdata('biztype',$biztype);
//echo $this->ci->session->userdata('biztype'); //here, i can get biztype that i want
}
However,when i logout and redirect to homepage, i cant get the userdata('biztype') and my session_id have changed.
Thanks for the help.
This is straight from CodeIgniter User Guide:
Destroying a Session
To clear the current session:
$this->session->sess_destroy();
Note: This function should be the last one called, and even flash
variables will no longer be available. If you only want some items
destroyed and not all, use unset_userdata().
So no, you cannot destroy a session then add user_data to it, you need to reload / redirect then once the NEW session is established add data.
Try using cookies for peristance, or use the mentioned unset_userdata() fn.
$this->session->sess_destroy() ;
This function should be called only at the end of the execution. For unsetting data (as you're trying to do) it's better to use unset_userdata method. See how you should implement that:
$unset_items = array('user_id' => '', 'username' => '', 'status' => '') ;
$this->ci->session->unset_userdata( $unset_items ) ;
$email = "abc#gmail.com";
///set the session
use the set_userdata function and include the session library
$this->load->library('session');
$this->session->set_userdata('session name',Value);
i.e.
$this->session->set_userdata('email', $email);
//unset the session
$this->session->unset_userdata('session name');
i.e.
$this->session->unset_userdata('email');

Resources