use laravel session value from function to another in the same controller in api or web route - laravel

When i'm trying to set session value in function then using this value it's fine but when i'm trying to reuse the same value which saved in the session with it's key i got undefined key in the array of the session why that's happen and how to handle that i tried to set middleware in the route but it gave me the same error
note: i redirect from my domain to another domain i know that's the problem occur after redirecting how to handle that i need standard solution i used $_cookie and it's worked but i want to use session ???
I'm tring to use the session values from function to another in the same controller after redirecting to another domain and back to my domain can someone tell me how to handle that and you must know that i don't controll the response from the external domain and this domain don't return the data that i want ???
the question here i need session to not expired if i go to this domain then back to my domain ?
try to capture the id after the creation
public function setCaptureOrderId($id) {
Session::put('catpureId', $id);
Session::save();
}
can use this getCaptureOrderId function
public function getCaptureOrderId() {
return $_SESSION['orderID'];
}
then redirect
public function http_create(){
return Redirect::to($url);
}
finally after the redirecting
getCaptureOrderId don't return anything and undefined key

Related

Laravel Auth::id() return null after login

I have a login form to access to my web page.
In my local computer everything works fine. But now I upload my project to my server and when I login the directive #auth() is null.
I put in my controller this: dd(Auth::id()); and in my local server returns a Id but in the production server returns null...
in web.php I have tis code:
Route::group(['middleware' => 'role:admin' OR 'role:user'], function () {
Route::get('/users/inicio', function(){
dd(Auth::id());
return view('frontend.dashboardUser');});
});
This return null
Can you help me?
Thank you
I think there might be some session problem, It might not be maintaining the session state.
My suggestion:
Try echo session_id() multiple times, If every time different id is generated then there will be some problem with the session on server otherwise not.
Have you registered a new user after you pushed your code to the production? I mean have you logged in using an existing user on production? I believe your production and local Database is different and the user who exists on local does not exist on production DB.
Register a new user and login as the new user and then try accessing the route to see if you get the auth id.
For a security reason, you can't access the login user or any other session into the web.php file as well as a constructor of the class.
To archive this you can use middleware something like this:
public function __construct() {
$this->middleware(function (Request $request, $next) {
if (!\Auth::check()) {
return redirect('/login');
}
$this->userId = \Auth::id(); // you can access user id here
return $next($request);
});
}
This link can help you more. Good luck!!!

View Share doesn't return updated data, how then to share live data?

I currently have a model which access data like so:
$currentSessionID = session()->getId();
$displayCart = Cart::where('session_id', $currentSessionID)->get();
return view('layouts.cart')->with('cartDetails', $displayCart);
This model correctly retrieves the data in a current session.
To access this same data in a header file I'm using View::Share in the AppServiceProvider like so:
public funciton boot()
{
$currentSessionID = session()->getId();
$inCartDetails = Cart::where('session_id', $currentSessionID)->get();
View::share('inCartDetails', $inCartDetails);
}
In my blade the $inCartDetails returns empty. I get [].
My suspicion is that this function ONLY gets called at boot. Hence the name :) and that it's empty cause at the time of starting the session it's empty since user hasn't selected anything. If this is correct how would I then pass live data to multiple views?
The session is not available in the boot method of the service providers. You should create a middleware for this. Check out this answer here: How to retrieve session data in service providers in laravel?

Laravel 5 Unable to access currently logged in user id from custom helper

In AppServiceProvider, I called a function from a custom helper as follows:
public function boot()
{
View::share('tree', customhelper::generateSiteTree(0));
}
The custom helper file is calling the database function as below:
$children = UserPermission::getLeftNavByUserId($startAt);
In the custom helper function, I want to pass the current logged in user ID however, dd(Auth::user()) is returning null.
How can I pass the Auth::user()->id with the method
getLeftNavByUserId($startAt, Auth::user()->id);
The variable (or Facade) isn't available yet. One way to solve this is by using a view composer.
View::composer('my.view.with.children', function(View $view){
$view->with('children', UserPermission::getLeftNavByUserId($startAt, Auth::id()));
});
Ofcourse you need to add a check if the user is logged in or not etc.
Custom helper function will be initialized in application instance before the Auth middleware therfore it will always be null, if you want to use the auth user bind it from middlware instead.

Can I store an access Cookie in a Laravel session?

I am working with a remote API that is normally accessed directly via JavaScript. In the normal flow, The user authenticates by sending Auth headers and in return is granted a cookie.
What I am trying to do is send auth headers from a laravel app, authenticate in the app controller, and provide API access through laravel controller functions.
I was hoping this would be as simple as authenticating and sending my subsequent API calls, hoping that the cookie given to the PHP server would continue to grant authentication.
Well that doesn't work and thats fine, but now I am thinking that I need to store my access cookie in the Session, and send it in the headers for future API calls.
Will this work/how can I go about this? My supervisors don't want to implement OAuth type tokens on the remote server and to me that seems like the best route, so I am a bit stuck.
Cookies cannot be shared across multiple hosts. The cookie (on the client) is only valid for path which set it.
EDIT - ADDING ADDITION AUTH DETAIL
Setting up remember me in Laravel
When migrating (creating) you User table add $table->rememberToken()
to create that column in your User table.
When user signs up to your service add a check box to allow them to
make the decision OR you can just set it true if you don’t to offer
the user the option as described in step 3
< input type="checkbox" name="remember" >
In your controller you add the following code:
if (Auth::attempt(['email' => $email, 'password' => $password], $remember)) {
// The user is being remembered...
}
Users table must include the string remember_token column per 1. , now assuming you have added the token column to your User table you can pass a boolean value as the second argument to the attempt method, which will keep the user authenticated indefinitely, or until they manually logout. i.e. Auth::attempt([$creditentials], true);
Side note: the Illuminate\Contracts\Auth\UserProvider contract, public function updateRememberToken(Authenticatable $user, $token) uses the user’s UID and token stored in the User table to store the session auth.
AUTH ONCE:
Laravel has once method to log a user into the application for a single request. No sessions or cookies. Used with stateless API.
if (Auth::once($credentials)) {
//
}
OTHER NOTES
The remember cookie doesn't get unset automatically when user logs out. However using the cookie as I explained below in cookies example you could add this to your logout function in your controller just before you return the redirect response after logout.
public function logout() {
// your logout code e.g. notfications, DB updates, etc
// Get remember_me cookie name
$rememberCookie = Auth::getRecallerName();
// Forget the cookie
$forgetCookie = Cookie::forget($rememberCookie);
// return response (in the case of json / JS) or redirect below will work
return Redirect::to('/')->withCookie($forgetCookie);
OR you could q$ueue it up for later if you are elsewhere and cannot return a response immediately
Cookie::queue(forgetCookie);
}
Basic general cookie example that might help you. There are better approaches to do this using a Laravel Service provider
// cookie key
private $myCookieKey = 'myAppCookie';
// example of cookie value but can be any string
private $cookieValue = 'myCompany';
// inside of a controller or a protected abstract class in Controller,
// or setup in a service ... etc.
protected function cookieExample(Request $request)
{
// return true if cookie key
if ($request->has($this->myCookieKey)) {
$valueInsideOfCookie = Cookie::get($this->myCookieKey);
// do something with $valueInsideOfCookie
} else {
// queue a cookie with the next response
Cookie::queue($this->myCookieKey, $this->cookieValue);
}
}
public function exampleControllerFunction(Request $request)
{
$this->cookieExample($request);
// rest of function one code
}
public function secondControllerFunction(Request $request)
{
$this->cookieExample($request);
// rest of function two code
}

CodeIgniter sess_destroy does not delete user_data session?

I am creating test case for my CodeIgniter app. However I just found something that I thought should not be happen :
in login.php controller :
public function logout()
{
$this->session->sess_destroy();
redirect('/');
}
So I just created a test to just make sure that session is really destroyed :
public function test_logout()
{
$this->CI = set_controller('login');
// make sure that all session is destroyed
$this->CI->session->set_userdata('test_session', 'some_value');
$this->CI->logout();
// userdata 'test_session' should be removed!
$this->assertTrue(($this->CI->session->userdata('test_session')==null || $this->CI->session->userdata('test_session')==''));
}
However I find that upon running the test case, my test case fails! Upon debug on the last line of test case, I found that the userdata is still exist with value = 'some_value'. I thought that sess_destroy should also delete all the set user data, as per what they described in their website documentation:
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().
I am using Kenji's CIUnit for unit testing.
Is this the correct behaviour or is there something that I missed?
Just found that CIUnit routes the Session to CIU_Session instead of original CodeIgniter's CI_Session. It miss a line that CI_Session does :
$this->userdata = array();
So turns out this is CIUnit's issue instead of CodeIgniter's. Create an issue in their bitbucket page.

Resources