Session
Session objects are returned by the Session
command. These objects provide the developer with an interface allowing to manage the current user session and execute actions such as store contextual data, share information between session processes, launch session-related preemptive processes, or (web only) manage privileges.
Tipos de sesiones
Esta clase admite tres tipos de sesiones:
- Web user sessions: Web user sessions are available when scalable sessions are enabled in your project. Se utilizan para conexiones Web y REST, y se les pueden asignar privilegios.
- Remote client user sessions: In client/server applications, remote users have their own sessions managed on the server.
- Stored procedures session: All stored procedures executed on the server share the same virtual user session.
The availability of properties and functions in the Session
object depend on the session type.
Resumen
.clearPrivileges() : Boolean removes all the privileges associated to the session and returns True if the execution was successful |
.expirationDate : Text the expiration date and time of the session cookie |
.hasPrivilege( privilege : Text ) : Boolean returns True if the privilege is associated to the session, and False otherwise |
.id : Text the unique identifier (UUID) of the session on the server |
.idleTimeout : Integer the inactivity session timeout (in minutes), after which the session is automatically closed by 4D |
.info : Object describes the remote client or stored procedure session on the server |
.isGuest() : Boolean returns True if the session is a Guest session (i.e. it has no privileges) |
.setPrivileges( privilege : Text ) : Boolean .setPrivileges( privileges : Collection ) .setPrivileges( settings : Object ) : Boolean associates the privilege(s) and/or role(s) defined in the parameter to the session and returns True if the execution was successful |
.storage : Object a shared object that can be used to store information available to all processes of the session |
.userName : Text the user name associated to the session |
Session
Historia
Lanzamiento | Modificaciones |
---|---|
20 R5 | Soporte de cliente remoto y sesiones de procedimientos almacenados |
18 R6 | Añadidos |
Session : 4D.Session
Parámetros | Tipo | Descripción | |
---|---|---|---|
Result | 4D.Session | <- | Objeto Session |
Descripción
The Session
command returns the Session
object corresponding to the current user session.
Dependiendo del proceso desde el que se llame al comando, la sesión de usuario actual puede ser:
- a web session (when scalable sessions are enabled),
- una sesión de cliente remoto,
- la sesión de procedimientos almacenados.
For more information, see the Session types paragraph.
If the command is called from a non supported context (single-user application, scalable sessions disabled...), it returns Null.
Sesiones web
The Session
object of web sessions is available from any web process:
On Web Authentication
,On Web Connection
, andOn REST Authentication
database methods,- código procesado a través de las etiquetas 4D en las páginas semidinámicas (4DTEXT, 4DHTML, 4DEVAL, 4DSCRIPT/, 4DCODE)
- los métodos proyecto con el atributo "Available through 4D tags and URLs (4DACTION...)" y llamados a través de 4DACTION/ urls,
On Mobile App Authentication
andOn Mobile App Action
database methods for mobile requests,- ORDA functions called with REST requests.
For more information on web user sessions, please refer to the Web Server Sessions section.
Sesiones de cliente remoto
The Session
object of remote client sessions is available from:
- Métodos proyecto que tienen el atributo Ejecutar en el Servidor (se ejecutan en el proceso "twinned" del proceso cliente),
- Triggers,
- Los métodos base
On Server Open Connection
yOn Server Shutdown Connection
de la base de datos.
For more information on remote user sessions, please refer to the Remote client user sessions paragraph.
Sesión de procedimientos almacenados
Todos los procesos de procedimientos almacenados comparten la misma sesión virtual de usuario. The Session
object of stored procedures is available from:
- methods called with the
Execute on server
command, On Server Startup
,On Server Shutdown
,On Backup Startup
,On Backup Shutdown
, andOn System event
database methods
For information on stored procedures virtual user session, please refer to the 4D Server and the 4D Language page.
Ejemplo
You have defined the action_Session
method with attribute "Available through 4D tags and URLs". Se llama al método introduciendo la siguiente URL en el navegador:
IP:port/4DACTION/action_Session
//action_Session method
Case of
:(Session#Null)
If(Session.hasPrivilege("WebAdmin")) //calling the hasPrivilege function
WEB SEND TEXT("4DACTION --> Session is WebAdmin")
Else
WEB SEND TEXT("4DACTION --> Session is not WebAdmin")
End if
Else
WEB SEND TEXT("4DACTION --> Session is null")
End case
.clearPrivileges()
Historia
Lanzamiento | Modificaciones |
---|---|
18 R6 | Añadidos |
.clearPrivileges() : Boolean
Parámetros | Tipo | Descripción | |
---|---|---|---|
Result | Boolean | <- | True si la ejecución se ha realizado correctamente |
Descripción
This function does nothing and always returns False with remote client and stored procedure sessions.
The .clearPrivileges()
function removes all the privileges associated to the session and returns True if the execution was successful. Como resultado, la sesión se convierte automáticamente en una sesión de invitado.
Ejemplo
//Invalidate a web user session
var $isGuest : Boolean
var $isOK : Boolean
$isOK:=Session.clearPrivileges()
$isGuest:=Session.isGuest() //$isGuest is True
.expirationDate
Historia
Lanzamiento | Modificaciones |
---|---|
18 R6 | Añadidos |
.expirationDate : Text
Descripción
Esta propiedad sólo está disponible con sesiones de usuario web.
The .expirationDate
property contains the expiration date and time of the session cookie. The value is expressed as text in the ISO 8601 format: YYYY-MM-DDTHH:MM:SS.mmmZ
.
Esta propiedad es de solo lectura. It is automatically recomputed if the .idleTimeout
property value is modified.
Ejemplo
var $expiration : Text
$expiration:=Session.expirationDate //eg "2021-11-05T17:10:42Z"
.hasPrivilege()
Historia
Lanzamiento | Modificaciones |
---|---|
18 R6 | Añadidos |
.hasPrivilege( privilege : Text ) : Boolean
Parámetros | Tipo | Descripción | |
---|---|---|---|
privilege | Text | <- | Nombre del privilegio a verificar |
Result | Boolean | <- | True if session has privilege, False otherwise |
Descripción
The .hasPrivilege()
function returns True if the privilege is associated to the session, and False otherwise.
With remote client and stored procedure sessions, this function always returns True, whatever the privilege.
Ejemplo
You want to check if the "WebAdmin" privilege is associated to the web user session:
If (Session.hasPrivilege("WebAdmin"))
//Access is granted, do nothing
Else
//Display an authentication page
End if
.id
Historia
Lanzamiento | Modificaciones |
---|---|
20 R5 | Añadidos |
.id : Text
Descripción
The .id
property contains the unique identifier (UUID) of the session on the server. Esta cadena única es asignada automáticamente por el servidor para cada sesión y permite identificar sus procesos.
.idleTimeout
Historia
Lanzamiento | Modificaciones |
---|---|
18 R6 | Añadidos |
.idleTimeout : Integer
Descripción
Esta propiedad sólo está disponible con sesiones de usuario web.
The .idleTimeout
property contains the inactivity session timeout (in minutes), after which the session is automatically closed by 4D.
Si no se define esta propiedad, el valor por defecto es 60 (1h).
When this property is set, the .expirationDate
property is updated accordingly.
El valor no puede ser inferior a 60: si se define un valor inferior, el tiempo de espera se eleva hasta 60.
This property is read write.
Ejemplo
If (Session.isGuest())
// A Guest session will close after 60 minutes of inactivity
Session.idleTimeout:=60
Else
// Other sessions will close after 120 minutes of inactivity
Session.idleTimeout:=120
End if
.info
Historia
Lanzamiento | Modificaciones |
---|---|
20 R5 | Añadidos |
.info : Object
Descripción
Esta propiedad sólo está disponible con sesiones de cliente remoto y procedimientos almacenados.
The .info
property describes the remote client or stored procedure session on the server.
The .info
object is the same object as the one returned by the Get process activity
command for remote client and stored procedure sessions.
The .info
object contains the following properties:
Propiedad | Tipo | Descripción |
---|---|---|
type | Text | Tipo de sesión: "remote" o "storedProcedure" |
userName | Text | 4D user name (same value as .userName ) |
machineName | Text | Sesiones remotas: nombre de la máquina remota. Sesión de procedimientos almacenados: nombre del equipo servidor |
systemUserName | Text | Sesiones remotas: nombre de la sesión del sistema abierta en la máquina remota. |
IPAddress | Text | Dirección IP de la máquina remota |
hostType | Text | Tipo de host: "windows" o "mac" |
creationDateTime | Date ISO 8601 | Fecha y hora de creación de la sesión |
state | Text | Estado de la sesión: "active", "postponed", "sleeping" |
ID | Text | Session UUID (same value as .id ) |
persistentID | Text | ID persistente de la sesión |
Since .info
is a computed property, it is recommended to call it once and then to store it in a local variable if you want to do some processing on its properties.
.isGuest()
Historia
Lanzamiento | Modificaciones |
---|---|
18 R6 | Añadidos |
.isGuest() : Boolean
Parámetros | Tipo | Descripción | |
---|---|---|---|
Result | Boolean | <- | True si la sesión es una sesión Guest, False en caso contrario |
Descripción
This function always returns False with remote client and stored procedure sessions.
The .isGuest()
function returns True if the session is a Guest session (i.e. it has no privileges).
Ejemplo
In the On Web Connection
database method:
If (Session.isGuest())
//Do something for Guest user
End if
.setPrivileges()
Historia
Lanzamiento | Modificaciones |
---|---|
19 R8 | Compatibilidad con la propiedad "roles" en Settings |
18 R6 | Añadidos |
.setPrivileges( privilege : Text ) : Boolean
.setPrivileges( privileges : Collection )
.setPrivileges( settings : Object ) : Boolean
Parámetros | Tipo | Descripción | |
---|---|---|---|
privilege | Text | -> | Nombre del privilegio |
privileges | Collection | -> | Colección de nombres de privilegios |
settings | Object | -> | Objeto con una propiedad "privilegios" (cadena o colección) |
Result | Boolean | <- | True si la ejecución se ha realizado correctamente |
Descripción
This function does nothing and always returns False with remote client and stored procedure sessions.
The .setPrivileges()
function associates the privilege(s) and/or role(s) defined in the parameter to the session and returns True if the execution was successful.
In the privilege parameter, pass a string containing a privilege name (or several comma-separated privilege names).
In the privileges parameter, pass a collection of strings containing privilege names.
In the settings parameter, pass an object containing the following properties:
Propiedad | Tipo | Descripción |
---|---|---|
privileges | Text o Collection | |
roles | Text o Collection | |
userName | Text | Nombre de usuario para asociar a la sesión (opcional) |
Privileges and roles are defined in roles.json
file of the project. For more information, please refer to the Privileges section.
If the privileges
or roles
property contains a name that is not declared in the roles.json
file, it is ignored.
By default when no privilege or role is associated to the session, the session is a Guest session.
The userName
property is available at session object level (read-only).
Ejemplo
En un método de autenticación personalizado, se establece el privilegio "WebAdmin" para el usuario:
var $userOK : Boolean
... //Authenticate the user
If ($userOK) //The user has been approved
var $info : Object
$info:=New object()
$info.privileges:=New collection("WebAdmin")
Session.setPrivileges($info)
End if
.storage
Historia
Lanzamiento | Modificaciones |
---|---|
20 R5 | Soporte de cliente remoto y sesiones de procedimientos almacenados |
18 R6 | Añadidos |
.storage : Object
Descripción
The .storage
property contains a shared object that can be used to store information available to all processes of the session.
When a Session
object is created, the .storage
property is empty. Since it is a shared object, this property will be available in the Storage
object of the server.
Like the
Storage
object of the server, the.storage
property is always "single": adding a shared object or a shared collection to.storage
does not create a shared group.
This property is read only itself but it returns a read-write object.
- Web session example
- Remote session example
Desea almacenar la IP del cliente en la propiedad .storage
. You can write in the On Web Authentication
database method:
If (Session.storage.clientIP=Null) //first access
Use (Session.storage)
Session.storage.clientIP:=New shared object("value"; $clientIP)
End use
End if
You want to share data between processes in the same session:
Use (Session.storage)
Session.storage.settings:=New shared object("property"; $value; "property2"; $value2)
End use
.userName
Historia
Lanzamiento | Modificaciones |
---|---|
20 R5 | Soporte de cliente remoto y sesiones de procedimientos almacenados |
18 R6 | Añadidos |
.userName : Text
Descripción
The .userName
property contains the user name associated to the session. Puede utilizarlo para identificar al usuario dentro de su código.
- Con las sesiones web, esta propiedad es una cadena vacía por defecto. It can be set using the
privileges
property of thesetPrivileges()
function. - With remote and stored procedure sessions, this property returns the same user name as the
Current user
command.
This property is read only.