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')));
Related
I'm trying to set a httpOnly cookie for token but it's not saving cookie.
I'm trying to login users via OTP and when user entered correct OTP, I'll sign them in app and so far I've done it like below :
$user = User::where('mobile_number', $request->mobileNumber)->first();
if ($user) {
Auth::login($user);
$token = $user->createToken('authToken')->accessToken;
$cookie = cookie('token', $token, 60 * 24 * 24); // 24 day
return response([
'status' => 'success',
'message' => 'loggedIn',
'user' => auth()->user(),
])->withCookie($cookie);
}else{
return response()->json([
'status' => 'success',
'message' => 'notExist'
], 200);
}
User will successfully login and if I refresh the page I should login again, and when I check Application\Storage\Cookies in Firefox and Storage\Cookies in chrome there's no sign of returned cookie(even if I don't refresh the page cookies won't be saved at all).
I'm using Laravel Passport, and so far, i don't think there should be any problem related to VUE side, since cookies not even saving in browser.
I've also tried to add more cookies to just test if everything work, but same problem happened again and nothing saved in browser.
I've also tried other solutions in Stackoverflow but they didn't worked.
Edit 01 : Removed refresh page...
Edit 02 : Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse and Queue tested.
Well, i found it, looks like problem was from VUE side actually. app URL was 127.0.0.1 for default in env file, but in VUE it was calling API via Localhost, and it was working but cookie wasn't saving due to this conflict, and when i changed it to 127.0.0.1 as default baseURL in axios, it worked.
Add cookie name in $except.
/app/Http/Middleware/EncryptCookies.php
Use the Cookie Facade that Laravel provides:
use Illuminate\Support\Facades\Cookie;
Cookie::queue('token', $token, 60 * 24 * 24);
In your Kernel.php, search for AddQueuedCookiesToResponse and uncomment it if it's commented.
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
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.
When the user clicks add to cart I create an new cart and add the product to the cookie of the user. But how do I set the cookie on an ajax response. Im trying:
//set the values for the view make
$cartId = 'someval i set earlyer'
$cookie = Cookie::forever('cartid', $cartId);
$currentCart = Cart::findOrFail($cartId);
$items = CartItem::where('cart_id','=',$currentCart->id)->get();
//this function also check the $request on a valid cookie
$total = $this->calculateCartTotal($request);
return Response::json(View::make('front.cart.render',compact('items', 'total'))->withCookie($cookie)->render());
But the value is never set, I tryd refreshing the page but there is still no cookie for cartid. How can I set a cookie for an ajax reponse
Try this:
return Response::json(
View::make('front.cart.render',compact('items', 'total'))->render()
)->withCookie($cookie);
rendor belongs to View
withCookie belongs to Response
Check Response headers.
Set-Cookie:cartid=...
I have this in my beforeroute() of a controller
public function beforeroute()
{
new \DB\SQL\Session($this->db);
$mapper = new \DB\SQL\Mapper($this->db, 'users');
$auth = new \Auth($mapper, array(
'id' => 'username',
'pw' => 'password'
));
if (!$auth->login('validuser', '1234')) {
die('username or password wrong');
} else {
echo ($csrf = $this->db->exec('SELECT csrf FROM sessions')[0]['csrf']);
}
}
After I hit the page, I have different values for csrf in database and what's been echoed out on page. Why is that?
The csrf token is renewed on every request. You see different values on the page and in the database, because the value in the database was updated after your page has rendered.
To be more specific, the SQL Session handler replaces the default php session handler, and that's why the call to session_commit within the unload method https://github.com/bcosca/fatfree-core/blob/master/base.php#L1903 (is called when the framework shut down) will update your session database table with the new value.
To have a way to reuse that single csrf token for your purpose, just put it back into the session itself:
$s = new \DB\SQL\Session($f3->get('DB'));
// old value from last request
echo $f3->get('SESSION.csrf');
// remember current value for next request
$f3->set('SESSION.csrf',$s->csrf());
Maybe there`s an easier way, but I haven't figured it out yet.