save user session in localstorage in React server side application - javascript

In my app I want to save the user session_id in local storage. My app is written with React and Redux ( With server side rendering ). I fetch user session_id from Api. I want to save session_id while user is logged in to my app ?
How is the best solution for this ?

Can you share the code you currently have to understand your question a little better. From what I understood you want to maybe try the code below. In the else statement make the api request for the session id and then setItem with the session id that came from the api request. You will then have access to it with a variable called currentSessionId.
var currentSessionId;
if(localStorage.getItem('session_id')){
currentSessionId = localStorage.getItem('session_id');
} else {
localStorage.setItem('session_id','<session id>');
currentSessionId = localStorage.getItem('session_id');
}
Hope this helps!

Just save the session_id to local storage when you receive it from the server. Then in your application initialization file check if the local storage contains any session_id. If so, use that id to fetch user data.
As local storage is client side (browser) feature, you can't use it in backend.
Another option could be to save your session_id into cookie and read that cookie in server side. That way you could authenticate the user already in server side.

Related

Laravel : Get id from localstorage

I have an application using for backend Laravel and in frontend React.
In React, to retrieve the data of the logged user I use :
const user = JSON.parse(localStorage.getItem("userData"));
In laravel's web.php to get the logged user_id I use Auth::user()->id.
Since I'm using React for authentification and Laravel to serve the APIs, I can't use Auth::user()->id directly to read the logged user's id in JS.
I understand that I can't pass directly localstorage as it's something stored locally in the browser. I tried setting a token for the logged user using Laravel Passport and it's working. But how to retrieve the data of the logged user in web.php or a Controller ?
You can use Laravel Sanctum. Doc
In Laravel Sanctum your application use session & cookies instead of tokens for user authentication. So you can retrieve user data anywhere you want.

How to restore state while changing window.location.href

After a user enters credentials on the login page, a post request is sent to the web server, which sends a cookie (if successful). On the client side, simultaneously, write the user details to my global redux store. On successful authentication from the server, I call window.location.href = 'newURL'. This call reloads my app. Now the user info I stored to the global store is lost, and I am not able to display username which was enetred by the user. How can I access the user credentials?
Thanks in advance :)
As mentioned in comments.
You need to use either localStorage or sessionStorage to keep the data alive.
For eg
localStorage.setItem("user", {"name": "abc"});
Now, though you logged out your data will be there in localStorage and you get the data using
localStorage.getItem("user");
If you want to remove then
localStorage.removeItem("user") or window.localStorage.removeItem('user');
Same applies to sessionStorage as well

accessing session object in html 5

I would like to know - how to implement a login in HTML5 where I want Login to be shown if session doesn't exists on first load and if any session with user data exists i want 'name' to be displayed instead of 'login'.
You cannot manage sessions without a server side language like PHP, Ruby, etc. HTML5 and JavaScript can only manage things on the user's side.
You should look at HTML5 Local Storage
https://www.w3schools.com/html/html5_webstorage.asp first. If this is not what you want then you have to use a server side language.
For using session object for login, you can do something like(PHP example):
1.Store the user's details in session object when user logs in via xyz.com/login
$_SESSION["username"] = "username";
2.When the user visits xyz.com next time, check if a value of a session object already exists.
if(isset($_SESSION["username"])){
// redirect to user profile etc.
}
else{
// show login page - xyz.com/login
}
For more info: https://www.w3schools.com/php/php_sessions.asp

Share module function with client side script nodejs

I made a function to check if someone is logged in on the site in the user controller module:
exports.isLoggedIn = function(req, res, next) {
if (req.user) {
return true;
} else {
return false;
}
};
I have no idea how I want to use this in a imported script on the client side. I couldn't find a good solution on the web so I thought I would ask the question myself.
If I import the script in the .html I get an error that says it doesnt know the require() function that node has.
I hope someone can help me :)
If you want client access to some data that is only available on the server, then you need to send an ajax call from the client to your server and you need to create a route on your server to respond to that ajax call.
Client code runs only on the client and has no direct access to any data on the server.
Server code runs only on the server and has no direct access to any data on the client.
To communicate between the two, you have to send a request from one to the other and then return a response. Usually this is done with an Ajax call sent from client to server. You could also establish a webSocket connection between the two and then either client or server could send data to the other.
The server also has the opportunity, when creating the original page content, to embed settings or values in the page itself, either as Javascript variables, as HTML values or even as a cookie. This obviously has to be done ahead of time when the page is rendered so it can't be a request that the client comes up with later after the page has been rendered to the client.
FYI, in the particular example you show, it is common for a client to be able to tell if it is logged in via some state in the page (either the presence of a particular cookie) or something else embedded in the page by the server. This isn't necessarily secure and isn't the way the server would tell if a request was logged in, but it usually suffices for client-side logic to decide how it wants to behave.

Make cookie presistent even after browser shutdown/restart using Angular.js

I am using Angular for my project, and got into a problem with authentication. On successfull authentication user retrive a token from server, and as long user have this token he can access all the places where he need authentication (i thought its a best way to do this since i use MVC web API as backend, and i dont have sessions). Everything works fine, until i close down my browser, and start it up again $cookieStore and $cookies are empty after restart.
Does anyone have any idea how to make cookie presistent, or are there any smarter way of doing this?
Ive created a test controller with a testview where i have 2 buttons which set and load $cookie before restart it works, if i open a new window while the other one is still up its works too, but as soon i close everything down, coockies is empty.
$scope.Set = function () {
$scope.LoadedData = "test";
$cookies.myFavorite = 'oatmeal';
}
$scope.Load = function () {
var b = $cookies.myFavorite;
console.log("testasdasd" + $cookies);
$scope.LoadedData = $cookies.myFavorite;
}
There are 2 types of cookies: session cookie and persistent cookie.
Session cookie is in memory and only survives until you close the browser.
Persistent cookie will be saved into disc and will be expired based on the Expires property.
The decision to save the cookie as session or persistent is server side, not your client side javascript.
When you use .NET Forms authentication, you can use FormsAuthentication.GetAuthCookie to create a cookie, the second parameter determines if this is a session or a persistent cookie.
I know this question was already answered, but actually you CAN manage cookies persistence client side. Just $cookieStore.
Persistent cookie:
// from your controller
$cookieStore.put('auth_token', token);
// in your module
$http.defaults.headers.common.Authorization = $cookieStore.get('auth_token');
In the module, we are telling angular that we want to use this session everytime any page of our website it's loaded.
EDIT: You may be interested in HTML5 localstorage instead of cookies.

Categories