I am developing a web application with Vapor 4. It would be useful to persist client-made data on the server side for a few minutes at a time in between requests. I want to use sessions to do this. However, I am a bit confused on how the best way to automatically destroy this data after a set time. Should I make a job and have it check periodically? Or is there an easy way to set an expiry time on session creation?
I have used a bit of Middleware to achieve this for some months and it is very reliable.
It compares the timestamp now to the value from the immediate previous request. If the difference is greater than the allowed session timeout, it forces a logout.
I had to give a bit of thought to initialising the timestamp and "BAD" ensures a nil gets returned from trying to initialise a Double, which then gets the current timestamp to start the session 'timer'. I think this is safe as the user can't log in without having made at least one route call beforehand and I have other Middleware that checks to make sure the user is logged in. Try this:
struct SessionTimeoutMiddleware:Middleware
{
func respond(to request:Request, chainingTo next:Responder) -> EventLoopFuture<Response>
{
let lastRequestTimeStamp = Double(request.session.data["lastRequest"] ?? "BAD") ?? Date().timeIntervalSince1970
request.session.data["lastRequest"] = String(Date().timeIntervalSince1970)
if Date().timeIntervalSince1970 - lastRequestTimeStamp > 300.0 // seconds
{
request.auth.logout(User.self)
return request.eventLoop.makeSucceededFuture(request.redirect(to:"/somewhere/safe"))
}
return next.respond(to:request)
}
}
Then, register in configure.swift using:
let userAuthSessionsMW = User.authenticator()
let sessionTimeoutMW = SessionTimeoutMiddleware()
let timed = app.grouped(C.URI.Users).grouped(userAuthSessionsMW, sessionTimeoutMW)
try SecureRoutes(timed)
Related
I have created an API using .NETCore 2.0 ; This API is connected to an oracle database to retrieve needed data; One of the functions takes too much time so I decided to use caching in order to retrieve data faster;
Function description: Get ranking
Caching period: Data should be renewed in cache memory each Monday
I am using IMemoryCache, but the problem is that data is not being cached for multiple days; It lasts only for one hour, after that data is being retrieved from database and takes too much time (10 s.); Below is my code:
var dateNow = DateTime.Now;
int diff = 7; // if today is Monday then should add 7 days to get next Monday date
if (dateNow.DayOfWeek != DayOfWeek.Monday) {
var daysToStartWeek = dateNow.DayOfWeek - DayOfWeek.Monday;
diff = (7 - (daysToStartWeek)) % 7;
}
var nextMonday = dateNow.AddDays(diff).Date;
var totalDays = (nextMonday - dateNow).TotalDays;
if (_cache.TryGetValue("GetRanking", out IEnumerable<GetRankingStruct> objRanking))
{
return Ok(objRanking);
}
var dp = new DataProvider(Configuration);
var response = dp.GetRanking(userName, asAtDate);
_cache.Set("GetRanking", response, TimeSpan.FromDays(diff));
return Ok(response);
Could be related to the token life Time since it's only 1 hour?
Firstly - have you tried checking to see if your worker process is being restarted? You don't specify how you are hosting your application but, obviously, if the application (worker process) is restarted your memory cache will be empty.
If your worker process / process is restarting then you could load the cache on start up.
Secondly - I believe that the implementation may choose to empty the cache due to inactivity or memory constraints. You can set the priority to never remove - https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.caching.memory.cacheitempriority?view=dotnet-plat-ext-3.1
I believe you can set this by passing a MemoryCacheOptions object to the constructor of the memory cache https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.caching.memory.memorycache.-ctor?view=dotnet-plat-ext-3.1#Microsoft_Extensions_Caching_Memory_MemoryCache__ctor_Microsoft_Extensions_Options_IOptions_Microsoft_Extensions_Caching_Memory_MemoryCacheOptions__.
Finally - I assume you've made your _cache object static so it is shared by all instances of your class. (Or made the controller, if that's what it is, a singleton).
These are my suggestions.
Good luck.
on windows vista & above,
currently, I am enumerating all windows sessions, then once I find an active session, WTSQueryUserToken() is called which gives me the token of current user.
This token is used to launch a process with his privileges / inside his desktop.
Problem I am facing is that there is not reliable way to get the active session / interactive session. I have to wait (check its presence every few millsecs) until explorer.exe is spawned.
I am not preferring notifications like those from SENS (system notification service) that user has logged on.
Edit
On receiving SERVICE_CONTROL_SESSIONCHANGE / logon event I call WTSGetActiveConsoleSessionId() to get the current session then I use this session ID with WTSQueryUserToken() to get token.
WTSGetActiveConsoleSessionId() sometimes returns me session 0. Thus I end up with token of session 0 when I want token from session of currently logged-in user.
It depends on timing of WTSGetActiveConsoleSessionId() call.
By experimenting I came up with idea to wait for explorer.exe and only after it comes up call WTSGetActiveConsoleSessionId(), this seems to guarantee that I always get session 1 or above and thus corresponding token.
Seeking a cleaner approach.
On receiving SERVICE_CONTROL_SESSIONCHANGE / logon event I call WTSGetActiveConsoleSessionId() to get the current session then I use this session ID with WTSQueryUserToken() to get token.
You should be using the session ID that is reported by SERVICE_CONTROL_SESSIONCHANGE itself. The lpEventData parameter will be a pointer to a WTSSESSION_NOTIFICATION structure, which contains a dwSessionId field.
WTSGetActiveConsoleSessionId() sometimes returns me session 0.
WTSGetActiveConsoleSessionId() returns the session that is attached to the physical console (mouse/keyboard/monitor) of the local machine. It can NEVER report session 0 in Vista and later (due to session 0 isolation), but it can in XP (where the first interactive user to login uses session 0). However, even if it could report session 0, that is not guaranteed to be the correct session that is associated with the user who logged in. There are other ways to log in to a computer than through its physical console. Remote Desktop, for example.
Thus I end up with token of session 0 when I want token from session of currently logged-in user.
You need to query the session that the user actually logged into. SERVICE_CONTROL_SESSIONCHANGE tells you the actual session ID, which will never be 0 on Vista and later (due to Session 0 isolation).
By experimenting I came up with idea to wait for explorer.exe and only after it comes up call WTSGetActiveConsoleSessionId(), this seems to guarantee that I always get session 1 or above and thus corresponding token.
But that is not a guarantee that that active console session is the correct session to query.
Seeking a cleaner approach.
Use the session ID that the notification explicitly tells you. Don't hunt for it.
I know this is an old question, but just for future reference, and to clarify Remy Lebeau's answer...
If we assume your Service Control Handler is called ServiceControlHandler then you want to do the following:
DWORD ServiceControlHandler(DWORD dwControl, DWORD dwEventType, LPVOID lpEventData, LPVOID lpContext)
{
DWORD retval = ERROR_CALL_NOT_IMPLEMENTED;
switch (dwControl)
{
case SERVICE_CONTROL_INTERROGATE: // All services should handle this message
retval = NO_ERROR;
break;
case SERVICE_CONTROL_SESSIONCHANGE: // Assumes you registered for these when you created the service
{
auto data = reinterpret_cast<WTSSESSION_NOTIFICATION*>(lpEventData);
if (data)
{
DWORD sessionId = data->dwSessionId; // Now you have the actual session ID
retval = NO_ERROR; // indicates we handled the message.
switch (dwEventType)
{
case WTS_CONSOLE_CONNECT:
// TODO: Do what you wish
break;
case WTS_CONSOLE_DISCONNECT:
// TODO: Do what you wish
break;
case WTS_REMOTE_CONNECT:
// TODO: Do what you wish
break;
case WTS_REMOTE_DISCONNECT:
// TODO: Do what you wish
break;
case WTS_SESSION_LOGON:
// TODO: Do what you wish
break;
case WTS_SESSION_LOGOFF:
// TODO: Do what you wish
break;
case WTS_SESSION_LOCK:
// TODO: Do what you wish
break;
case WTS_SESSION_UNLOCK:
// TODO: Do what you wish
break;
case WTS_SESSION_REMOTE_CONTROL:
// TODO: Do what you wish
break;
case WTS_SESSION_CREATE: // (0xA) Reserved for future use.
case WTS_SESSION_TERMINATE: // (0xB) Reserved for future use.
default:
break; // do nothing
}
}
else
{
// NOTE: should never happen
}
}
break;
// TODO: Handle other control types here
default:
retval = ERROR_CALL_NOT_IMPLEMENTED; // must always return this if not handled
break;
};
return retval;
}
As Remy says, this way you use the session ID that the notification explicitly tells you, rather than going looking for it and getting the wrong one.
I am working on a project using Parse where I need some information calculated for each user and updated when they update their account. I created a Cloud Code trigger that does what I need whenever a user account is updated, and that is working well. However, I have about two thousand accounts that are already created that I need to update as well. After hours of trying to get a Cloud Job to work, I decided to try to simplify it. I wrote the following job to simply count the user accounts. To reiterate; I'm not actually trying to count the users, there are much more efficient ways to do that, I am trying to verify that I can query and loop over the existing user accounts. (The option to useMasterKey is in there because I will need that later.)
Parse.Cloud.job("getUserStatistics", function(request, status) {
// Set up to modify user data
Parse.Cloud.useMasterKey();
// Query for all users
var query = new Parse.Query(Parse.User);
var counter = 0;
query.each(function(user) {
counter = counter+1;
}).then(function() {
// Set the job's success status
status.success("Counted all User Accounts.");
}, function(error) {
// Set the job's error status
status.error("Failed to Count User Accounts.");
});
console.log('Found '+counter+' users.');
});
When I run the code, I get:
I2015-07-09T17:29:10.880Z]Found 0 users.
I2015-07-09T17:29:12.863Z]v99: Ran job getUserStatistics with:
Input: "{}"
Result: Counted all User Accounts.
Even more baffling to me, if I add:
query.limit(10);
...the query itself actually fails! (I would expect it to count 10 users.)
That said, if there is a simpler way to trigger an update on all the users in a Parse application, I'd love to hear it!
The reference actually says that:
The query may not have any sort order, and may not use limit or skip.
https://parse.com/docs/js/api/symbols/Parse.Query.html#each
So forget about "query.limit(10)", that's not relevant here.
Anyways, by their example for a background job, it seems you might have forgotten to put return in your "each" function. Plus, you called console.log('Found '+counter+' users.'); out side of your asynchronous task, that makes sense why you get 0 results. maybe you try:
query.each(function(user) {
counter = counter+1;
// you'll want to save your changes for each user,
// therefore, you will need this
return user.save();
}).then(function() {
// Set the job's success status
status.success("Counted all User Accounts.");
// console.log inside the asynchronous scope
console.log('Found '+counter+' users.');
}, function(error) {
// Set the job's error status
status.error("Failed to Count User Accounts.");
});
You can check again Parse's example of writing this cloud job.
https://parse.com/docs/js/guide#cloud-code-advanced-writing-a-background-job
How to use Cache.getOrElse(java.lang.String key, java.util.concurrent.Callable block, int expiration)
Could someone give me a example?
My point is how to use “expiration",I know it means expire time.
By the way:
I want save some object to cache,and set a expire time.
when the expire time,I can reset the object to the cache.
Thanks.
Let's assume that, you want to set User object on cache, for that you set userId as key and user object as value. If need set expiration time, for sample i set it as 30secs.
cache.set(userId, userObject, 30);
At some point of time, if you want to get user object from cache, which you set earlier using userId as key, you might try the following way to get the user object from cache.
User user = cache.get(userId);
Above will return you the user object, if you access within 30secs, otherwise it will return NULL. This will be perfect for case like validating the session.
In some case, you frequently need to retrieve value from cache, for that following is the best approach.
User user = cache.getOrElse(userId, () -> User.get(userId), 30);
cache will check, whether it has given userId as key, if available then straight away return the user object and update the expiration time to 30secs further.
If given userId not available, then callable block gets invoked and set userId as key, user object fetched from db as value and expiration time as 30secs.
Expiration is the number of seconds that the Object would be hold in the Cache. If you pass 0 as expiration the Cache doesn't expire and you would have to control it by hand.
What getOrElse does is check the Cache, if the Object is not there then call the callable block that you are passing and adds the result to the cache for the number of seconds that you are passing as expiration time.
I based my comment in the Play Framework Cache Javadoc.
I use getOrElse in controllers when I have dynamic and static content to display. Cache the static and then render it together with the dynamic part:
try {
Html staticHtml = Cache.getOrElse("static-content", () -> staticView.render(), 60 * 60);
Html rendered = dynamicPage.render(arg1, arg2, staticHtml);
return ok(rendered);
} catch (Exception e) {
e.printStackTrace();
return internalServerError();
}
staticView.render() returns some html from a view. This view should not call any other pages which are dynamic or you stash something you do not really want to stash.
60*60 means I want to store it for one hour (60 seconds times 60 minutes... ok you can write 3600 if you want)
I should add that getOrElse gets the Object from the cache with the specified key (in this example the key is static-content) but if it cannot find it, then it calls the function which returns an object which is then stored for the specified amount of time in the cache with that key. Pretty neat.
Then you can call some other (dynamic) page and pass the html to it.
The dynamic stuff will stay dynamic :)
I'm currently trying to display all online users on my webpage using the php session variables. To do this, whenever a user logs in or out, a column in a database gets set to "online" or "offline".. However this doesn't entirely work since the database doesn't get updated when the user closes their browser (and therefor destroys the session).
So is there another way of checking if a certain sessionid is set??
Currently I am setting the session like this:
session_start();
$_SESSION['username']="Example Username";
To check from the current users page if there is a session variable set we can simply use:
if(isset($_SESSION['username']))
{
//username is set
}
But if we need to check if a specific user is online, how do we get for instance an array of all the session variables that have been set? e.g.
//Get all $_SESSION['username'] vars
//loop through array and check for specific $_SESSION
for($i=0; ... )
{
if( $_SESSION['username'][$i] == "User 1" )
{
//do something
}
}
From all that I've read so far, there doesn't seem to be a way to get an array of all sessions on your page..
So is there a better way of doing it, e.g. how do facebook, twitter, etc handle this stuff?
Thanks for your help!
One solution is to store a timestamp in your database in addition to the online/offline flag that records the last time a user accessed any of your website resources. Then you might just consider them offline after 15 minutes or some other constant value.
The other solution is to play with the callbacks here http://php.net/manual/en/function.session-set-save-handler.php where I think you can handle the gc callback and set the offline flag in your database.
If you search on that page for class SessionDB or go here it looks like somebody has implemented some version of this already in a custom class!
you can use a simple update query
for example you have a table users and in that you have a column called status(online/offline)
on your login.php use
<?php
//your user verification code
if(variable that holds your sql query){
$user_status=('UPDATE user SET status= online WHERE email="'your user email selector'")
}
then on the logout do a similar script just change the online value to offline
You could try this:
foreach ($_SESSION as $sessionKey => $sessionValue)
{
if( $sessionKey == 'username' ) && ( $sessionValue == 'User 1' )
{
//do something
}
}