Saltar para o conteúdo principal
Versão: 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 sessão

Três tipos de sessões são suportados por essa classe:

nota

The availability of properties and functions in the Session object depend on the session type.

Resumo

.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

História
ReleaseMudanças
20 R5Support of remote client and stored procedure sessions
18 R6Adicionado

Session : 4D.Session

ParâmetroTipoDescrição
Resultados4D. Session<-Objecto Session

Descrição

The Session command returns the Session object corresponding to the current user session.

Dependendo do processo a partir do qual o comando é chamado, a sessão atual do usuário pode 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.

Sessões 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 processado a través das etiquetas 4D nas páginas semidinâmicas (4DTEXT, 4DHTML, 4DEVAL, 4DSCRIPT/, 4DCODE)
  • os métodos projeto com o atributo "Available through 4D tags and URLs (4DACTION...)" e chamados atravé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.

Sessões cliente remoto

The Session object of remote client sessions is available from:

  • Project methods that have the Execute on Server attribute (they are executed in the "twinned" process of the client process),
  • Triggers,
  • On Server Open Connection and On Server Shutdown Connection database methods.

For more information on remote user sessions, please refer to the Remote client user sessions paragraph.

a sessão de procedimentos armazenados

Todos os processos de procedimento armazenado compartilham a mesma sessão de usuário virtual. 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.

Exemplo

You have defined the action_Session method with attribute "Available through 4D tags and URLs". Pode chamar ao método introduzindo a URL abaixo no 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()

História
ReleaseMudanças
18 R6Adicionado

.clearPrivileges() : Boolean

ParâmetroTipoDescrição
ResultadosParâmetros<-True se a execução for bem-sucedida

Descrição

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, a sessão torna-se automaticamente uma sessão de convidado.

Exemplo

//Invalidar uma sessão
var $isGuest : Boolean
var $isOK : Boolean

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

.expirationDate

História
ReleaseMudanças
18 R6Adicionado

.expirationDate : Text

Descrição

nota

Essa propriedade só está disponível com sessões de usuário da 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.

This property is read-only. It is automatically recomputed if the .idleTimeout property value is modified.

Exemplo

var $expiration : Text
$expiration:=Session.expirationDate //por exemplo "2021-11-05T17:10:42Z"

.hasPrivilege()

História
ReleaseMudanças
18 R6Adicionado

.hasPrivilege( privilege : Text ) : Boolean

ParâmetroTipoDescrição
privilegeText<-Nome do privilegio a verificar
ResultadosParâmetros<-True if session has privilege, False otherwise

Descrição

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.

Exemplo

Se quiser comprovar se o privilégio "WebAdmin" está associado à sessão:

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

End if

.id

História
ReleaseMudanças
20 R5Adicionado

.id : Text

Descrição

The .id property contains the unique identifier (UUID) of the session on the server. Esta string única é automaticamente atribuída pelo servidor para cada sessão e permite que você identifique seus processos.

.idleTimeout

História
ReleaseMudanças
18 R6Adicionado

.idleTimeout : Integer

Descrição

nota

Essa propriedade só está disponível com sessões de usuário da Web.

The .idleTimeout property contains the inactivity session timeout (in minutes), after which the session is automatically closed by 4D.

Se não se definir esta propriedade, o valor padrão é 60 (1h).

When this property is set, the .expirationDate property is updated accordingly.

O valor não pode ser inferior a 60: se definir um valor inferior, o tempo de espera se eleva até 60.

This property is read write.

Exemplo

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

História
ReleaseMudanças
20 R5Adicionado

.info : Object

Descrição

nota

Essa propriedade só está disponível com sessões de procedimento armazenado e cliente remoto.

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:

PropriedadeTipoDescrição
typeTextTipo de sessão: "remote" ou "storedProcedure"
userNameText4D user name (same value as .userName)
machineNameTextSessões remotas: nome da máquina remota. Sessão de procedimentos armazenados: nome da máquina do servidor
systemUserNameTextSessões remotas: nome da sessão do sistema aberta na máquina remota.
IPAddressTextEndereço IP da máquina remota
hostTypeTextTipo de host: "windows" ou "mac"
creationDateTimeDate ISO 8601Data e hora de criação da sessão
stateTextEstado da sessão: "ativa", "adiada", "em espera"
IDTextSession UUID (same value as .id)
persistentIDTextID persistente da sessão
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()

História
ReleaseMudanças
18 R6Adicionado

.isGuest() : Boolean

ParâmetroTipoDescrição
ResultadosParâmetros<-True se a sessão for uma sessão Guest, False caso contrário

Descrição

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).

Exemplo

In the On Web Connection database method:

If (Session.isGuest())
//Do something for Guest user
End if

.setPrivileges()

História
ReleaseMudanças
19 R8Suporte da propriedade "roles" das Settings
18 R6Adicionado

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

ParâmetroTipoDescrição
privilegeText->Nome do privilégio
privilegesCollection->Collection de nomes de privilégios
settingsObject->Objetos com as propriedades "privilégios" (string ou collection)
ResultadosParâmetros<-True se a execução for bem-sucedida

Descrição

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:

PropriedadeTipoDescrição
privilegesText ou Collection
  • String containing a privilege name, or
  • Collection of strings containing privilege names
  • rolesText ou Collection
  • String containing a role, or
  • Collection of strings containing roles
  • userNameTextNome de usuário associado à sessão (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).

    Exemplo

    Em um método de autenticação personalizado, deve estabecer o privilégio "WebAdmin" ao usuário:

    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

    História
    ReleaseMudanças
    20 R5Support of remote client and stored procedure sessions
    18 R6Adicionado

    .storage : Object

    Descrição

    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.

    Você deseja armazenar o IP do cliente na propriedade .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

    História
    ReleaseMudanças
    20 R5Support of remote client and stored procedure sessions
    18 R6Adicionado

    .userName : Text

    Descrição

    The .userName property contains the user name associated to the session. Pode usá-la para identificar o usuário dentro de seu código.

    • Com sessões da Web, essa propriedade é uma cadeia de caracteres vazia por padrão. 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.