How can I get notified of user logins and logouts?
First you need to install the LoginScriptExtension (minimum version 2.0 for Appway 8.0).
This extension has two important configuration properties: login.script and logout.script. The values of these properties have to be valid Appway scripts. They are executed whenever a user login or logout is detected.
If the extension is started, it registers itself as event listener for user login and logout events. Whenever the extension is notified about such an event, it executes the script code you have configured for this case.
If the extension is stopped, it unregisters itself as event listener.
When you start the extension the very first time, it deploys two new Primitive Types called UserLoginEvent and UserLogoutEvent. Instances of these types may be used in the script code to access information about the login or logout event (see below).
There are two implicit defined variables you may use in the script code: $event and $user.
$event contains an instance of type UserLoginEvent or UserLogoutEvent, depending on whether it's a login or logout event. Both event types have two important methods:
$event.getUserId() to get the id of the user currently logging in or out
$event.getSessionId() to get the id of the HTTP session of this user
IMPORTANT: getUserId() may return null. A login event is generated whenever a new HTTP session is created, not only if a user is authenticated. Therefore be prepared to get a null value when calling this method.
$user is an instance of type 'User'. It may be null if the login or logout event is for an anonymous user.
Beside the variables described above, you may also use the user-related functions like USER(), USERID(), USERINROLE(...) etc. For anonymous users, these functions will return null or false.
The result of the script code (return value) is ignored.
OnLogin($event, $user)
IF($user != null, $user.setPreference('LoginDate',NOW()), null)
LogSessionCreated($event.getSessionId())