generate_token()

public function generate_token(array $data): string

Description

Generates a new Trongate token and stores it in the database. Tokens are 64‑character hexadecimal strings used for user authentication.

This method is typically called during login or when creating API access tokens.

Parameters

Parameter Type Description Default Required
$data array Associative array with token generation parameters:
  • user_id (int) – Required. The user ID to associate with the token.
  • expiry_date (int) – Optional. Unix timestamp for token expiration. Default: 30 days from now.
  • set_cookie (bool) – Optional. If true, sets the token as a browser cookie. Default: false.
  • code (string) – Optional. Custom code for the token (advanced usage).
N/A Yes

Return Value

Type Description
string The generated 64‑character hexadecimal token.

Example Usage

PHP
// Generate token for user #123 (30‑day expiration, set cookie)
$token = $this->trongate_tokens->generate_token([
    'user_id' => 123,
    'expiry_date' => time() + (30 * 24 * 60 * 60),
    'set_cookie' => true
]);

// Generate API token (no cookie)
$api_token = $this->trongate_tokens->generate_token([
    'user_id' => 456,
    'expiry_date' => time() + (365 * 24 * 60 * 60) // 1 year
]);

// Login controller
public function submit_login() {
    $username = post('username', true);
    $password = post('password', true);
    $user = $this->model->validate_credentials($username, $password);
    
    if ($user !== false) {
        $token = $this->trongate_tokens->generate_token([
            'user_id' => $user->id,
            'set_cookie' => true
        ]);
        $_SESSION['trongatetoken'] = $token;
        set_flashdata('Login successful.');
        redirect('members/dashboard');
    } else {
        set_flashdata('Invalid credentials.');
        redirect('members/login');
    }
}

// Create long‑lived API token
public function create_api_key() {
    $user_id = $this->trongate_tokens->get_user_id();
    if ($user_id === false) {
        http_response_code(401);
        die();
    }
    $token = $this->trongate_tokens->generate_token([
        'user_id' => $user_id,
        'expiry_date' => time() + (365 * 24 * 60 * 60),
        'code' => 'api_key'
    ]);
    echo json_encode(['token' => $token]);
}

Notes

  • Calls $this->model->generate_token($data) which creates the token and inserts it into the database.
  • Tokens are stored in the trongate_tokens table with columns: token, user_id, expiry_date, code.
  • Default expiration is 30 days (2,592,000 seconds) if expiry_date is omitted.
  • If set_cookie is true, sets $_COOKIE['trongatetoken'] with a 30‑day lifetime.
  • The code parameter can be used to differentiate token types (e.g., 'api_key', 'password_reset').
  • Use regenerate() to extend an existing token's expiration.