Laravel can't read a "recently" created cookie - laravel

I have a project who authenticate the user using cookies like token_ and refreshToken_, and a middleware who intercept my routes and verify if the user is logged or not.
In my middleware, when i need to renew the token_ I have the following code:
namespace App\Http\Middleware\VerifyAccessToken
$cookie_name = "token_";
$cookie_value = $obj->access_token;
$expires_in = $obj->expires_in;
$time = time() + $expires_in; // 3600 = 1 hora
$path = "/";
$domain = env('COOKIE_DOMAIN');
setcookie($cookie_name, $cookie_value, $time, $path, $domain, false, true);
$cookie_name = "refreshToken_";
$cookie_value = $obj->refresh_token;
setcookie($cookie_name, $cookie_value, $time + 3600, $path, $domain, false, true);
return $next($request);
It works apparently fine, but the problem is:
After the middleware intercep my route and renew the cookie, the request proced to his controller, but there, I can't access the cookie using $_COOKIE['token_'] and I get an error, but if I look in the chrome's inspector, the cookie is there and reloading the page (F5) I can access the cookie in controller
Have a method for me access the cookie in controller without need to go to the view before?

To read the value of Cookie in Laravel, do you need to use:
$token = Cookie::queued('token_');
dd($token->getValue());
https://api.symfony.com/3.0/Symfony/Component/HttpFoundation/Cookie.html

Related

Laravel 8 Cookie -> Can't get cookie value

I have annoying problem that I can't fix for hours. Have been trying all google suggestions, so far nothing.
Function for setting/getting cookie right now:
/* Check if user is logged in or else take cookie */
if(Auth::check()){
$user_id = Auth::user()->id;
}else{
if(Cookie::get('user_id') !== null){
$user_id_cookie = Cookie::get('user_id');
}else{
$user_id = Cookie::forever('user_id', Str::random(15));
$user_id_cookie = $user_id;
}
}
/* Check if user is logged in or else take cookie */
Cookie is set, but it doesn't get value back to blade.
For getting cookie value I have tried multiple solutions, for example 2:
$old = Crypt::decryptString(request()->cookie('user_id'))
$cookie_value = explode("|",$old)[1];
Or (As I have another cookie made in same way, and it's working. But I have no idea, why..)
$old= Crypt::decrypt(Cookie::get('user_id'), false);
$cookie_value = substr($old, 41);
But all these solutions shows this error:
Illuminate\Contracts\Encryption\DecryptException
The payload is invalid.

Can't take Laravel cookie that's been set

I have a checkbox in my login form and if it is checked I want to save user's email and password in a cookie so then he'll be automatically logged in. This is the part of my code that checks if the checkbox is checked and sets the cookie.
if ($remember == 'on') {
$array = array(
"email" => $email,
"password" => $password
);
$time = time() + (10 * 365 * 24 * 60 * 60);
Cookie::queue('user', serialize($array), $time);
}
But when I try to get the cookie and print it out it prints "false".
$cookie = Cookie::get('user');
dd(unserialize($cookie));
How can I get the cookie? It shows the cookie that's been set in inspect.
What's the best way to check if the cookie is set so i'll redirect the user to profile view straight away? Do I have to write a middleware for it?
The problem is your dd function call.
Cookies will store in user's browser when he retrieve the response with your Cookies attached (set-cookie headers), and you can read them in the next request that he will send to you.
when you call dd, it breaks the response chain and removes the set-cookie headers.
just remove the dd and in another route write:
dd(unserialize(\Request::cookie('user')));

How to set and retrieve cookies in code igniter

I have tried setting cookies in codeigniter like this, but not working don't know what is the problem
//setting cookie
$this->load->helper('cookie');
if($loaded_position == 'nativelocation' ){
$this->input->set_cookie('nativelocation' , $request_place, '86400');
//echo $this->input->cookie('nativelocation');
}
//retrieving cookie
$this->load->helper('cookie');
$savedlocation = array();
if( $this->input->cookie('addlocation_1') )
{
$savedlocation[]= $this->input->cookie('addlocation_1') ;
}
It looks like you are setting a cookie called "nativelocation" but then you try to retrieve a cookie called "'addlocation_1", and there isn't one. Try:
if( $this->input->cookie('nativelocation') ){
echo $this->input->cookie('nativelocation');
}
Also, know that when setting a cookie, you can not access it on the same "page" you'll need a page refresh, or access the cookie $this->input->cookie('nativelocation') on another page/controller.

Facebook losing logged in user with ajax

I am writing a Facebook app and have used the Facebook php SDK so it can be authorized server side. I can see this is working because after authorization when Facebook redirects back to my app, I have the following code in my index.php...
require_once 'facebook.php';
$facebook = new Facebook(array(
'appId' => '111111111111111',
'secret' => '11111111111111111111111111111111',
'cookie' => true
));
// Get User ID
$user = $facebook->getUser();
...and $user returns not null. So far, so good!
I have a link on my app that loads content via ajax when clicked. Here's the JS:
$.post('my_content.php', {
action: 'render'
}, function(res){
if (res.html.length) {
$('.content').html(res.html);
}
},'json');
The problem is, the my_content.php script seems to be losing the fact the user has logged in and authorized the app.
The code I run in the my_content.php script to check whether the user is logged in is the same as in index.php
require_once 'facebook.php';
$facebook = new Facebook(array(
'appId' => '111111111111111',
'secret' => '11111111111111111111111111111111',
'cookie' => true
));
// Get User ID
$user = $facebook->getUser();
This time though $user = $facebook->getUser() returns null.
Is there a way to check if the user is logged in and authorized when running a PHP script with an AJAX call?
Should I store something in a session variable in my index.php script?
EDIT
After even more reading, I'm wondering if I need to retrieve the access token using the JavaScript SDK and pass it to my_content.php. Does anyone know if that's the correct way to do it?
EDIT 2
Turns out the line giving me the problem isn't $user = $facebook->getUser():
It is this one
$user_profile = $facebook->api('/me');
This line fails with the error 'OAuthException: An active access token must be used to query information about the current user.'
Strangely though, if I do this
$access_token = $facebook->getAccessToken();
$user = $facebook->getUser();
echo $access_token;
echo $user;
I do indeed have an access token and a user ID, so it looks like it may well be the bug reported by CBroe - check comments below.

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.

Resources