I am designing a feature to store the last logon date / time in an ASP.Net (MVC) application.
My first instinct was to store the value in the database against the user’s profile record and update the value to the current date/time on successful login. Of course, as soon as I record that value, all pages will display the date and time of this session’s successful logon.
Plan B: A field to record the previous session and one to record this session. On logon, save this session’s date/time to the “current” field and move the value previously found there into the “previous” field (obviously). It is this field that provides my “last logged in on” value.
Is this the best approach or can it be done more elegantly?
Another approach is to, when logging in, read the last login date/time from the user record and save it into the session or a session cookie. Then update the user record with the current date/time. Then on your pages read the value stored in the session/cookie.
The old time will be removed when the session expires which is usually when a user needs to re-login anyway. It also has the advantage of speed and caching as it is reading from the session/cookie.
But it depends on your setup and app whether this is possible for you.
UPDATE
Just to be clear… The current date/time is persisted to the database user table every time the user logs in. But before the date/time is written to the user table, the existing value is read and saved to the session or cookie. You then update the date/time value in the user table with the current timestamp.
If your authentication ticket lasts longer than the session then use the cookie method and set the expiry of the cookie to the same expiry of the authentication ticket.