Conn2Flow
Docs navigation

Reference / Libraries

autenticacao.php library

The login token signed with the site's RSA key, RSA encryption of secrets, per-IP attempt control (login, sign-up, password recovery) and credential validation for the distributed channel.

Path in the Gestor bibliotecas/autenticacao.php

Four topics: the RSA JWT token the Gestor uses in the login cookie and in the API, encrypting and decrypting values with the site's RSA keys, per-IP attempt control and the distributed channel credentials. The keys live in autenticacoes/<domain>/chaves/gestor/ (privada.key, protected by OPENSSL_PASSWORD, and publica.key), see global variables.

The RSA token

It is not a standard JWT (RS256): the header says "alg": "RSA", and the "signature" is the header.payload itself encrypted with the private key (openssl_private_encrypt, in 245-byte blocks, each block base64-encoded and the whole again base64-encoded). Validating means decrypting with the public key and comparing with the received header.payload.

  • autenticacao_gerar_jwt_chave_privada(['host', 'expiration', 'pubID', 'chavePrivada', 'chavePrivadaSenha', 'payload' => optional]) builds the token. Without payload, it uses {iss: host, exp: expiration, sub: pubID}. It issues the API tokens; the login cookie uses the same format, built by usuario_gerar_token_autorizacao() (usuario.php) and validated by gestor_permissao_validar_jwt().

  • autenticacao_validar_jwt_chave_publica(['token', 'chavePublica', 'retornarPayloadCompleto']) checks the signature, requires exp and sub and rejects expired tokens. It returns the sub (the pubID), the whole payload or false.

Validating the token is only the first step: gestor_permissao_token() still checks the pubID in usuarios_tokens with the USUARIO_HASH_PASSWORD HMAC (request lifecycle).

The inverted variants autenticacao_gerar_jwt_chave_publica() and autenticacao_validar_jwt_chave_privada(), and autenticacao_cliente_gerar_jwt() / autenticacao_cliente_gerar_token_validacao() (from the multi-host mode), have no callers.

Encrypting secrets

Function Encrypts with Decrypts with
autenticacao_encriptar_chave_privada() / autenticacao_decriptar_chave_publica() private public
autenticacao_encriptar_chave_publica() / autenticacao_decriptar_chave_privada() public private

The first pair is the one used to store API keys (AI servers): it hides the value from someone who only sees the database, but whoever has the database and the public key recovers it. For real confidentiality, encrypt with the public key and decrypt with the private one.

autenticacao_openssl_gerar_chaves() generates a 2048-bit RSA pair; autenticacao_gerar_senha() and autenticacao_crypto_rand_secure() generate passwords and random numbers. None of the three has callers in the core (the installer has its own key generator).

Per-IP attempt control

The acessos table keeps, per IP (from ip_get()) and type (login, signup, forgot-password), the count, the status and the block.

Function When to call
autenticacao_acesso_verificar(['tipo']) Before showing/processing the form: permitido, status (livre, antispam, bloqueado) and tempo_bloqueio
autenticacao_acesso_falha(['tipo']) Wrong password
autenticacao_acesso_confirmar(['tipo']) Successful login: resets the count
autenticacao_acesso_cadastrar(['tipo', 'antispam']) Each sign-up or recovery request

Limits from the .env: at login, up to ACESSOS_MAXIMO_LOGINS_SIMPLES (3) failures the status is livre, up to ACESSOS_MAXIMO_FALHAS_LOGINS (10) it is antispam, and then bloqueado. For sign-ups, ACESSOS_MAXIMO_CADASTROS_* and ACESSOS_MAXIMO_CADASTROS_SIMPLES_* per type. Each block lasts blocks × ACESSOS_TEMPO_BLOQUEIO_IP seconds (growing with each repeat), and the record disappears after ACESSOS_TEMPO_DESBLOQUEIO_IP without activity. autenticacao_acessos_limpeza() runs on every check and applies both rules.

In perfil-usuario, the status decides the CAPTCHA: with reCAPTCHA, it is only required from antispam on; with Turnstile, always.

Distributed channel

Used by the central side of the distributed architecture:

  • autenticacao_distribuido_gerar_tokens($id_usuarios): OAuth2 tokens with the distributed scope;

  • autenticacao_distribuido_verificar_permissao_modulo(): the user's profile has the target module;

  • autenticacao_distribuido_token_ativo(): the channel access token is valid.

Channel credential validation does not go through the attempt control.

Functions

Generated from gestor/bibliotecas/autenticacao.php · 21 functions

21 of 21

autenticacao_crypto_rand_secure

view source · line 33 ↗
autenticacao_crypto_rand_secure(int $min, int $max): int

Gera um número aleatório criptograficamente seguro.

Parameters

$minint
Valor mínimo (inclusivo).
$maxint
Valor máximo (inclusivo).

Returns

int
Número aleatório seguro entre $min e $max.

autenticacao_cliente_gerar_jwt

view source · line 69 ↗
autenticacao_cliente_gerar_jwt(array|false $params = false): string|false

Gera um token JWT assinado com chave RSA para autenticação de cliente.

Parameters

$paramsarray|false
Parâmetros da função.

Returns

string|false
Token JWT completo ou false em caso de erro.

autenticacao_openssl_gerar_chaves

view source · line 145 ↗
autenticacao_openssl_gerar_chaves(array|false $params = false): array|false

Gera par de chaves pública e privada OpenSSL com algoritmo RSA.

Parameters

$paramsarray|false
Parâmetros da função.

Returns

array|false
Array com 'publica' e 'privada', ou false em erro.

autenticacao_gerar_senha

view source · line 298 ↗
autenticacao_gerar_senha(int $length = 32): string

Gera uma senha aleatória segura com caracteres variados.

Parameters

$lengthint
Comprimento da senha (padrão: 32 caracteres).

Returns

string
Senha aleatória gerada.

autenticacao_gerar_jwt_chave_publica

view source · line 343 ↗
autenticacao_gerar_jwt_chave_publica(array|false $params = false): string|false

Gera JWT assinado com chave pública RSA.

Parameters

$paramsarray|false
Parâmetros (host, expiration, pubID, chavePublica obrigatórios).

Returns

string|false
Token JWT ou false em erro.

autenticacao_gerar_jwt_chave_privada

view source · line 408 ↗
autenticacao_gerar_jwt_chave_privada(array|false $params = false): string|false

Gera JWT assinado com chave privada RSA.

Parameters

$paramsarray|false
Parâmetros (host, expiration, pubID, chavePrivada, chavePrivadaSenha obrigatórios; payload opcional).

Returns

string|false
Token JWT ou false em erro.

autenticacao_validar_jwt_chave_publica

view source · line 480 ↗
autenticacao_validar_jwt_chave_publica(array|false $params = false): array|string|false

Valida JWT usando chave pública RSA.

Parameters

$paramsarray|false
Parâmetros (token, chavePublica obrigatórios; retornarPayloadCompleto opcional).

Returns

array|string|false
Payload decodificado, pubID ou false se inválido.

autenticacao_validar_jwt_chave_privada

view source · line 569 ↗
autenticacao_validar_jwt_chave_privada(array|false $params = false): array|false

Valida JWT usando chave privada RSA.

Parameters

$paramsarray|false
Parâmetros (token, chavePrivada, chavePrivadaSenha obrigatórios).

Returns

array|false
Payload decodificado ou false se inválido.

autenticacao_acesso_verificar

view source · line 725 ↗
autenticacao_acesso_verificar(array|false $params = false): array

Verifica estado de acesso do usuário com proteção anti-spam.

Parameters

$paramsarray|false
Parâmetros (tipo obrigatório).

Returns

array
Estado do acesso com 'permitido', 'status' e 'mensagem' opcional.

autenticacao_encriptar_chave_publica

view source · line 1116 ↗
autenticacao_encriptar_chave_publica(array|false $params = false): string|false

Encripta valor usando chave pública RSA.

Parameters

$paramsarray|false
Parâmetros (valor, chavePublica obrigatórios).

Returns

string|false
Valor encriptado em base64 ou false em erro.

autenticacao_encriptar_chave_privada

view source · line 1164 ↗
autenticacao_encriptar_chave_privada(array|false $params = false): string|false

Encripta valor usando chave privada RSA.

Parameters

$paramsarray|false
Parâmetros (valor, chavePrivada, chavePrivadaSenha obrigatórios).

Returns

string|false
Valor encriptado em base64 ou false em erro.

autenticacao_decriptar_chave_publica

view source · line 1212 ↗
autenticacao_decriptar_chave_publica(array|false $params = false): string|false

Decripta valor usando chave pública RSA.

Parameters

$paramsarray|false
Parâmetros (criptografia, chavePublica obrigatórios).

Returns

string|false
Valor decriptado ou false em erro.

autenticacao_decriptar_chave_privada

view source · line 1266 ↗
autenticacao_decriptar_chave_privada(array|false $params = false): string|false

Decripta valor usando chave privada RSA.

Parameters

$paramsarray|false
Parâmetros (criptografia, chavePrivada, chavePrivadaSenha obrigatórios).

Returns

string|false
Valor decriptado ou false em erro.

autenticacao_distribuido_gerar_tokens

view source · line 1326 ↗
autenticacao_distribuido_gerar_tokens(int $id_usuarios): array|false

Gera os tokens de acesso e renovação (OAuth2) para o canal distribuído.

Parameters

$id_usuariosint
ID do usuário já validado.

Returns

array|false
Tokens (access_token, refresh_token, expires_in, ...) ou false.

autenticacao_distribuido_verificar_permissao_modulo

view source · line 1356 ↗
autenticacao_distribuido_verificar_permissao_modulo(int $id_usuarios, string $modulo): bool

Verifica se o usuário tem permissão de acesso ao módulo alvo (controle por perfil).

Parameters

$id_usuariosint
ID do usuário já autenticado.
$modulostring
Slug do módulo alvo (ex.: 'modulos-grupos-distribuido').

Returns

bool
true se o usuário pode acessar o módulo.

The Future is Hybrid: Human + AI.

Conn2Flow is the tool. If you need the Architect to design your company's strategy using this technology...

Hire Specialized Consulting