Saltar para o conteúdo principal
Versão: Próximo

Session

Os objetos de sessão são retornados pelo comando Session. 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

The following types of sessions are supported by this class:

nota

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

Resumo

.clearPrivileges() : Boolean
removes all the privileges associated to the session and returns True if the execution was successful
.createOTP ( { lifespan : Integer } ) : Text
creates a new OTP (One Time Passcode) for the session and returns its token UUID
.expirationDate : Text
the expiration date and time of the session cookie
.getPrivileges() : Collection
returns a collection of all the privilege names associated to the session
.hasPrivilege( privilege : Text ) : Boolean
returns True if the privilege is associated to the session, and False otherwise
.id : Text
o identificador único (UUID) da sessão do usuário
.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, or the standalone session
.isGuest() : Boolean
returns True if the session is a Guest session (i.e. it has no privileges)
.restore ( token : Text ) : Boolean
replaces the current web user session with their original session corresponding to the token UUID
.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
o nome de usuário associado à sessão

.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

This function does nothing and always returns True with remote client, stored procedure, and standalone sessions.

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

//Invalidate a web user session
var $isGuest : Boolean
var $isOK : Boolean

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

.createOTP()

História
ReleaseMudanças
20 R9Adicionado

.createOTP ( { lifespan : Integer } ) : Text

ParâmetroTipoDescrição
lifespanInteger->Session token lifespan in seconds
ResultadosText<-UUID of the session

Descrição

nota

This function is only available with web user sessions. It returns an empty string in other contexts.

The .createOTP() function creates a new OTP (One Time Passcode) for the session and returns its token UUID. This token is unique to the session in which it was generated.

Para mais informações sobre os tokens OTP, consulte esta seção.

By default, if the lifespan parameter is omitted, the token is created with the same lifespan as the .idleTimeOut of the session. You can set a custom timeout by passing a value in seconds in lifespan (the minimum value is 10 seconds, lifespan is reset to 10 if a smaller value is passed). If an expired token is used to restore a web user session, it is ignored.

The returned token can then be used in exchanges with third-party applications or websites to securely identify the session. For example, the session OTP token can be used with a payment application.

Exemplo

var $token : Text
$token := Session.createOTP( 60 ) //the token is valid for 1 mn

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

Essa propriedade é somente leitura. Ele será automaticamente recalculado se o valor da propriedade .idleTimeout for modificado.

Exemplo

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

.getPrivileges()

História
ReleaseMudanças
20 R6Adicionado

.getPrivileges() : Collection

ParâmetroTipoDescrição
ResultadosCollection<-Coleção de nomes de privilégios (strings)

Descrição

The .getPrivileges() function returns a collection of all the privilege names associated to the session.

With remote client, stored procedure and standalone sessions, this function returns a collection only containing "WebAdmin".

info

Os privilégios são atribuídos a uma sessão usando a função setPrivileges().

Exemplo

O seguinte arquivo roles.json foi definido:

{
"privileges":[
{
"privilege":"simple",
"includes":[

]
},
{
"privilege":"medium",
"includes":[
"simple"
]
}
],
"roles":[
{
"role":"Medium",
"privileges":[
"medium"
]
}
],
"permissions":{
"allowed":[

]
}
}

O papel de sessão é atribuído em uma função de datastore authentify():

  //Datastore Class

exposed Function authentify($role : Text) : Text
Session.clearPrivileges()
Session.setPrivileges({roles: $role})

Assuming the authentify() function is called with the "Medium" role:

var $privileges : Collection
$privileges := Session.getPrivileges()
//$privileges: ["simple","medium"]

Veja também

.setPrivileges()
Permissions – Inspect the privileges in the session for an easy debugging (blog post)

.hasPrivilege()

História
ReleaseMudanças
18 R6Adicionado

.hasPrivilege( privilege : Text ) : Boolean

ParâmetroTipoDescrição
privilegeText->Nome do privilegio a verificar
ResultadosParâmetros<-True se a sessão tiver privilege, False caso contrário

Descrição

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

With remote client, stored procedure and standalone sessions, this function always returns True, whatever the privilege.

Exemplo

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

História
ReleaseMudanças
20 R5Adicionado

.id : Text

Descrição

A propriedade .id contém o identificador único (UUID) da sessão do usuário. With 4D Server, this unique string is automatically assigned by the server for each session and allows you to identify its processes.

tip

Você pode usar essa propriedade para obter o objeto .storage de uma sessão graças ao comando storage.

.idleTimeout

História
ReleaseMudanças

|v18 R6|Adicionado|

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

Quando essa propriedade é definida, a propriedade .expirationDate é atualizada de acordo.

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

Essa propriedade é leitura escrita.

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

This property is only available with remote client, stored procedure, and standalone sessions.

The .info property describes the remote client or stored procedure session on the server, or the standalone session.

nota
  • The .info object is the same object as the one returned in the "session" property by the Process activity command for remote client and stored procedure sessions.
  • O objeto .info é o mesmo objeto retornado pelo comando Session info para uma sessão autônoma.

The .info object contains the following properties:

PropriedadeTipoDescrição
typeTextSession type: "remote", "storedProcedure", "standalone"
userNameTextNome de usuário 4D (o mesmo valor que .userName)
machineNameTextSessões remotas: nome da máquina remota. Stored procedures session: name of the server machine. Standalone session: name of the machine
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 8601Date and time of session creation. Standalone session: date and time of application startup
stateTextEstado da sessão: "ativa", "adiada", "em espera"
IDTextUUID da sessão (mesmo valor que .id)
persistentIDTextRemote sessions: Session's persistent ID
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 False with remote client, stored procedure, and standalone sessions.

The .isGuest() function returns True if the session is a Guest session (i.e. it has no privileges).

Exemplo

No método base On Web Connection:

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

.restore()

História
ReleaseMudanças
20 R9Adicionado

.restore ( token : Text ) : Boolean

ParâmetroTipoDescrição
tokenText->Session token UUID
ResultadosParâmetros<-True if the current session has been successfully replaced by the session in token

Descrição

nota

This function is only available with web user sessions. It returns False in other contexts.

The .restore() function replaces the current web user session with their original session corresponding to the token UUID. Session's storage and privileges are restored.

If the original user session has been correctly restored, the function returns true.

The function returns false if:

  • the session token has already been used,
  • the session token has expired,
  • the session token does not exist,
  • the original session itself has expired.

In this case, the current web user session is left untouched (no session is restored).

Exemplo

In a singleton called by a custom HTTP Request handler:

shared singleton Class constructor()

Function callback($request : 4D.IncomingMessage) : 4D.OutgoingMessage
Session.restore($request.urlQuery.state)

Veja também

.createOTP()

.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

This function does nothing and always returns False with remote client, stored procedure, and standalone 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:

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

    Os privilégios e as funções são definidos no arquivo roles.json do projeto. Para obter mais informações, consulte a seção Privilégios.

    If the privileges or roles property contains a name that is not declared in the roles.json file, it is ignored.

    Como padrão quando não houver um privilégio associado à sessão, a sessão é uma Sessão de convidados.

    A propriedade userName está disponível no nível do objeto de sessão (somente leitura).

    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

    Veja também

    .getPrivileges()

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

    Quando um objeto Session é criado, a propriedade .storage está vazia. 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.

    Essa propriedade é apenas de leitura, mas retorna um objeto de leitura e gravação.

    tip

    You can get the .storage property of a session using the Session storage command.

    Exemplo de sessão na web

    Você deseja armazenar o IP do cliente na propriedade .storage. Você pode escrever no método de banco de dados On Web Authentication:

    If (Session.storage.clientIP=Null) //first access
    Use (Session.storage)
    Session.storage.clientIP:=New shared object("value"; $clientIP)
    End use End if

    Exemplo de sessão remota

    Você deseja compartilhar dados entre processos na mesma sessão:

    Use (Session.storage)
    Session.storage.settings:=New shared object("property"; $value; "property2"; $value2)
    End use

    .userName

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

    .userName : Text

    Descrição

    A propriedade .userName contém o nome de usuário associado à sessão. 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. Ele pode ser definido usando a propriedade privileges da função setPrivileges().
    • With remote and stored procedure sessions, this property returns the same user name as the Current user command.
    • With standalone sessions, this property contains "designer" or the name set with the SET USER ALIAS command.

    Essa propriedade é somente leitura.