I am trying to achieve that after user logs in to my app, I will have to send get request to my servlet, which will respond with servletOutputStream with some sound message like ('Hello User, how are you'). But I want it to be only once, not after the logged user refreshes the page and hears it again.
You can use localStorage as a general solution.
Check if the user already received the message before outputting the message:
if (!localStorage.getItem('messageSent')) {
// 1. create the message for the user here
// 2. make sure user does not get message again
localStorage.setItem('messageSent', 'true'); // any truthy value
}
Clear the localStorage when user logs out:
localStorage.removeItem('messageSent');
Based off your question, it seems you can even avoid the above solution and just output the message in the login logic (after user gets authenticated and logs in). When the user refreshes the page, it shouldn't show the message because the login logic should not run when the user is already logged in.
Set a cookie after the first run, and check for the presence of the cookie before. The cookie should only last the length of the current session, assuming you want the message to appear the next time they log in. A quick search should reveal how to set cookies in JS.
Related
What my code is doing currently is calling a function that calls an api that gives a new access token every time the page gets refreshed, or to be more specific i have a pinia store that has a function that adds the data to the store when called and this function is being called when the page refreshes.
I am doing this because I have a thing that says "logged in as x" on the navbar and to get that info I go check if the refresh token is valid and fetch the username at the same time.
I'm wondering if this is a bad idea and if I should do it some other way, like storing the username in localstorage/cache/cookies
(sorry for bad phrasing)
As part of offline user creation, I wanted to create an account from my back-end server and send out verification mail to user.
But when user clicks on the verification link, I also want to present a screen to set his password.
In the existing web-app, I have individual flows to handle verify and reset-password. but they are separate flows.
From the following doc
I could see that there is a parameter called mode to identify the action. Using this we are currently handling the verify and reset-password actions.
But is there a way to have a custom mode or some means to identify that the user has to be taken to a different screen after verification.
One workaround I can think of is to use the continueUrl (may be with a custom scheme). Not sure if this will work flawlessly.
Can somebody share their thoughts on this.
Using the continueUrl is indeed the correct way. Based on the mode you can decide which action is to be treated and then you can redirect to the continueUrl after the user has executed the corresponding action.
For example, the documentation you refer to shows the following example (note the // TODO: If a continue URL is available... comment):
function handleVerifyEmail(auth, actionCode, continueUrl, lang) {
// Localize the UI to the selected language as determined by the lang
// parameter.
// Try to apply the email verification code.
auth.applyActionCode(actionCode).then(function(resp) {
// Email address has been verified.
// TODO: Display a confirmation message to the user.
// You could also provide the user with a link back to the app.
// TODO: If a continue URL is available, display a button which on
// click redirects the user back to the app via continueUrl with
// additional state determined from that URL's parameters.
}).catch(function(error) {
// Code is invalid or expired. Ask the user to verify their email address
// again.
});
}
so I come to you with a simple question: how is laravel session relay working.
My use Case: I have a laravel site cached with a varnish like so :
every get request is made as the user is not logged in
any user related info if loaded via ajax after the user loaded the page.
My problem is that I need to know in my front end if a user is logged in.
Things that I noticed:
Laravel session is not accessible in js
Laravel session is there even if the user is not logged in
I also tried to set my own cookie on login and unset it in on logout, but it my cookie is randomly diapering while the user is still logged in.
If someone has any idea on how to find out if my user is logged in from the standard cookies I would be so grateful.
You can pass the data to JS like I'm showing in my repo. For example:
<input id="authenticated" type="hidden" value="{{ auth()->check() }}">
And then get the data which will be true or false:
let authenticated = $('#authenticated').val();
Alternatively, you could use an Ajax call and execute auth()->check() in a controller method.
You can use in JS var userCheck= " <?php echo Auth::check();?> "; , then check if userCheck is equal to one then user is logged In otherwise not.
you can generate a token whenever a user is logged in and send it to the front-end and save it in the cookie. The cookie can have and the expiry time of say 5 hours. If during these 5 hours, user sends some requests, then the token is refreshed and 5 hour time starts again. In case, no request comes to the backend it means user is not active and you can log him out.
We want to log the user out when the session ends, so one approach is to have JavaScript redirect the user to the logout script after the time period of the session passes. If the user has multiple tabs open, however, the JavaScript can activate on a tab that isn't visible and log the user out. We can't do an AJAX call because that would reset the session time length. What's a good approach to dealing with logging out a user with multiple tabs open when the session ends?
EDIT: The session expires on the server after a time length. The JavaScript is just there to redirect the user to the logout page so that the content does not stay on the screen.
Expire the session cookie. Cookies can be set to expire at browser close or after a certain period of time. See http://en.wikipedia.org/wiki/HTTP_cookie#Expires_and_Max-Age
You have to poll the server if the user is logged in. You can do it per AJAX or WebSockets. Maybe you can automatically redirect if the cookie is expired but I don't know exactly if you can check the expiry date per JavaScript.
Why do you rely on javascript for this? Log him out on a server and then open tabs don't matter.
I've a MVC application, On successful Login I set a login Storage value in my Layout.cshtml
$(document).ready(function () {
function loginStorageChange(event) {
if(window.localStorage.getItem('loginStorage') === null) {
setTimeout(function() { location.reload(); }, 1000);
}
}
window.localStorage.setItem('loginStorage', true);
window.addEventListener('storage', loginStorageChange, false);
});
On Logout Click, I remove the loginStorage before form submit
function logoutSubmit() {
window.localStorage.removeItem('loginStorage');
$('#logoutForm').submit();
}
So when window detects that loginstorage has been changed so it reloads the page, Server indicates a logout and redirects to login page.
I'm developing a chat module for my application...
I'm opening a window for users to chat, is there way that when users close the chat window, I can update status of that record...i mean event for the closed browser?
I know that default session time is 24mins,
so after 24mins of inactivity, user will be kicked out from the site and will asked to login once again.
How to delete/flush the data in my database, when user has no activity for 24mins (when user is logged out from the session due to inactivity)?
1) You'll need javascript onUnload event for this one. It'll send an asynchronous query to your webserver, setting the offline status of the user. However, you should not rely solely on this event and also set up the 24 mins auto-offline timeout because it is not guaranteed that the user is using javascript.
2) I think your best option here is running a cron job (every 30 mins or so?) that queries your database, identifies the users whose last activity was more than 24 mins ago and then deletes the associated data.
Store every chat entry's timestamp in UNIX_TIMESTAMP. When a new chat entry incoming check every entries timestamp where timestamp is smaller than now - 24 mins. Kick users.
1) use the unload event
2) if you are developing a chat, i guess that you have a periodical function that calls the server constantly to retrieve the messages. Each time this function is called, the inactivity time will be reset, even if the user haven't sent a message. If you want to logout the user when he doesn't write anything in 24min you cant rely on the php sessions.
What you can do is: save in the db, the last time the user wrote a message on the chat, and each time you use your periodical function, validate if the user hasn't wrote anything in the last 24 mins
Use a javascript function for the event
window.onbeforeunload = myLogoutFunction;
Note: This javascript will not work on browser crash.
Have a user_log database table and fill the login and "logout" dates in it.
When there is a user with not updated logoff date, then you can assume there was something wrong with his connection.
$where = " AND `users_id`='".$response['userfound']['id']."'";
$where .= " AND `logoffdatetime`='0000-00-00 00:00:00'";
After 24min php session is gone (default php.ini settings). It wont be much usable. But you can still save into the user_log table.
You should not need the flush database.
Keeping the chat users via database alive is bad idea. Instead use a small file with timestamp in it.
Here some other useful tips
Detect if the user coming back without logout
$user_navigates = false;
if(isset($_SERVER['HTTP_REFERER']) && basename($_SERVER['HTTP_REFERER']) != _PAGE)
$user_navigates = true;
save also page refreshes into session
if(isset($_GET['pagerefreshed']))
$_SESSION['pagerefreshed'] = $_GET['pagerefreshed'];
save the logging out user_id into session, so you can use it restore things. For instance no need to reload page.
$_SESSION['loggedout']['user_id'] == $login->user_id