Saltar al contenido principal
Versión: 20 R5 BETA

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:

nota

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
LanzamientoModificaciones
20 R5Soporte de cliente remoto y sesiones de procedimientos almacenados
18 R6Añadidos

Session : 4D.Session

ParámetrosTipoDescripción
Result4D.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:

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, and On 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 and On 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 y On 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, and On 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
LanzamientoModificaciones
18 R6Añadidos

.clearPrivileges() : Boolean

ParámetrosTipoDescripción
ResultBoolean<-True si la ejecución se ha realizado correctamente

Descripción

nota

Since privileges are only supported in web user sessions, this function does nothing and always returns False in other session types.

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

//Invalidar una sesión
var $isGuest : Boolean
var $isOK : Boolean

$isOK:=Session.clearPrivileges()
$isGuest:=Session.isGuest() //$isGuest es True

.expirationDate

Historia
LanzamientoModificaciones
18 R6Añadidos

.expirationDate : Text

Descripción

nota

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
LanzamientoModificaciones
18 R6Añadidos

.hasPrivilege( privilege : Text ) : Boolean

ParámetrosTipoDescripción
privilegeText<-Nombre del privilegio a verificar
ResultBoolean<-True if session has privilege, False otherwise

Descripción

nota

Since privileges are only supported in web user sessions, this function does nothing and always returns False in other session types.

The .hasPrivilege() function returns True if the privilege is associated to the session, and False otherwise.

Ejemplo

Quiere comprobar si el privilegio "WebAdmin" está asociado a la sesión:

If (Session.hasPrivilege("WebAdmin"))
//Access is granted, do nothing
Else
//Display an authentication page

End if

.id

Historia
LanzamientoModificaciones
20 R5Añ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
LanzamientoModificaciones
18 R6Añadidos

.idleTimeout : Integer

Descripción

nota

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
LanzamientoModificaciones
20 R5Añadidos

.info : Object

Descripción

nota

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:

PropiedadTipoDescripción
typeTextTipo de sesión: "remote" o "storedProcedure"
userNameText4D user name (same value as .userName)
machineNameTextSesiones remotas: nombre de la máquina remota. Sesión de procedimientos almacenados: nombre del equipo servidor
systemUserNameTextSesiones remotas: nombre de la sesión del sistema abierta en la máquina remota.
IPAddressTextDirección IP de la máquina remota
hostTypeTextTipo de host: "windows" o "mac"
creationDateTimeDate ISO 8601Fecha y hora de creación de la sesión
stateTextEstado de la sesión: "active", "postponed", "sleeping"
IDTextSession UUID (same value as .id)
persistentIDTextID persistente de la sesión
nota

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
LanzamientoModificaciones
18 R6Añadidos

.isGuest() : Boolean

ParámetrosTipoDescripción
ResultBoolean<-True si la sesión es una sesión Guest, False en caso contrario

Descripción

nota

This function always returns True 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
LanzamientoModificaciones
19 R8Compatibilidad con la propiedad "roles" en Settings
18 R6Añadidos

.setPrivileges( privilege : Text ) : Boolean
.setPrivileges( privileges : Collection )
.setPrivileges( settings : Object ) : Boolean

ParámetrosTipoDescripción
privilegeText->Nombre del privilegio
privilegesCollection->Colección de nombres de privilegios
settingsObject->Objeto con una propiedad "privilegios" (cadena o colección)
ResultBoolean<-True si la ejecución se ha realizado correctamente

Descripción

nota

Since privileges are only supported in web user sessions, this function does nothing and always returns False in other session types.

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:

PropiedadTipoDescripción
privilegesText o Collection
  • String containing a privilege name, or
  • Collection of strings containing privilege names
  • rolesText o Collection
  • String containing a role, or
  • Collection of strings containing roles
  • userNameTextNombre de usuario para asociar a la sesión (opcional)
    nota

    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
    LanzamientoModificaciones
    20 R5Soporte de cliente remoto y sesiones de procedimientos almacenados
    18 R6Añ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.

    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

    .userName

    Historia
    LanzamientoModificaciones
    20 R5Soporte de cliente remoto y sesiones de procedimientos almacenados
    18 R6Añ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 the setPrivileges() function.
    • With remote and stored procedure sessions, this property returns the same user name as the Current user command.

    This property is read only.