Validating and Fetching User Data
Once a token is generated, you need to validate it on protected pages and fetch information about the authenticated user. This page covers token validation and data retrieval.
Validating Tokens
Use the method to check if a user has a valid token.
Method Signature
public function attempt_get_valid_token(int|array|null $user_levels = null): string|boolParameters
- $user_levels (optional) - Filter by user level:
null- Accept any user level (default)int- Accept only one specific user levelarray- Accept multiple user levels
Return Value
Returns the token string if valid, or false if no valid token is found.
How It Works
The method searches for tokens in this order:
- Cookies -
$_COOKIE['trongatetoken'] - Session -
$_SESSION['trongatetoken']
The first valid token found is returned. A token is considered valid if:
- It exists in the
trongate_tokensdatabase table - Its
expiry_dateis greater than the current time - The user's level matches the specified
$user_levels(if provided)
Example 1: Any User Level
Accept any authenticated user, regardless of their level:
public function dashboard(): void {
$token = $this->trongate_tokens->attempt_get_valid_token();
if ($token === false) {
redirect('login');
}
// User is authenticated
$data['view_file'] = 'dashboard';
$this->templates->members_area($data);
}This example assumes you have a members_area template created.
Example 2: Specific User Level
Only allow users with a specific user level (e.g., admin only):
public function manage_users(): void {
// Only allow admin (user level 1)
$token = $this->trongate_tokens->attempt_get_valid_token(1);
if ($token === false) {
redirect('login');
}
// User is admin
$data['view_file'] = 'manage_users';
$this->templates->admin($data);
}This example assumes you have an admin template created.
Example 3: Multiple User Levels
Allow multiple user levels (e.g., admin or moderator):
public function moderate_content(): void {
// Allow admin (1) or moderator (3)
$token = $this->trongate_tokens->attempt_get_valid_token([1, 3]);
if ($token === false) {
redirect('login');
}
// User is admin or moderator
$data['view_file'] = 'moderate_content';
$this->templates->admin($data);
}Fetching User Data
Once you've validated a token, you often need information about the user. The Trongate_tokens module provides three methods for this.
Method 1: get_user_id()
Retrieve the Trongate User ID (the id from the trongate_users table):
public function get_user_id(?string $token = null): int|falseExample:
$user_id = $this->trongate_tokens->get_user_id();
if ($user_id === false) {
redirect('login');
}
echo "Trongate User ID: " . $user_id;If no token parameter is provided, the method automatically searches cookies and session for a token.
Method 2: get_user_obj()
Retrieve a complete user object with all token and user level information:
public function get_user_obj(?string $token = null): object|falseThe returned object contains:
- trongate_user_code - The
codefromtrongate_users - user_level_id - The numeric user level ID
- user_level - The user level title (e.g., "admin", "member")
- token - The validated token string
- trongate_user_id - The user's ID from
trongate_users - expiry_date - Unix timestamp of token expiration
Example:
$user = $this->trongate_tokens->get_user_obj();
if ($user === false) {
redirect('login');
}
echo "Welcome, User #" . $user->trongate_user_id;
echo "Your level: " . $user->user_level;
echo "Token expires: " . date('Y-m-d H:i:s', $user->expiry_date);Method 3: get_user_level()
Retrieve just the user level title:
public function get_user_level(?string $token = null): string|boolExample:
$level = $this->trongate_tokens->get_user_level();
if ($level === false) {
redirect('login');
}
if ($level === 'admin') {
echo "You have admin privileges";
} else {
echo "You are a: " . $level;
}Practical Example: Displaying User Info
Here's a complete example showing how to fetch and display user information:
<?php
class Members extends Trongate {
public function profile(): void {
// Validate token (any level)
$token = $this->trongate_tokens->attempt_get_valid_token();
if ($token === false) {
redirect('login');
}
// Get complete user object
$user = $this->trongate_tokens->get_user_obj();
// Fetch member details from members table
$sql = 'SELECT * FROM members WHERE trongate_user_id = ?';
$member = $this->db->query_bind($sql, [$user->trongate_user_id], 'object');
$member = $member[0] ?? null;
if (!$member) {
redirect('login');
}
// Pass data to view
$data['first_name'] = $member->first_name;
$data['last_name'] = $member->last_name;
$data['username'] = $member->username;
$data['user_level'] = $user->user_level;
$data['view_file'] = 'profile';
$this->templates->members_area($data);
}
}This example assumes you have a members table with columns: id, username, first_name, last_name, and trongate_user_id.
Using Constructor for Protection
If you want to protect an entire controller, add validation in the constructor:
<?php
class Members extends Trongate {
public function __construct(?string $module_name = null) {
parent::__construct($module_name);
// Require valid token for ALL methods
$token = $this->trongate_tokens->attempt_get_valid_token(2); // level 2 = member
if ($token === false) {
redirect('login');
}
}
public function dashboard(): void {
// Already protected by constructor
$data['view_file'] = 'dashboard';
$this->templates->members_area($data);
}
public function profile(): void {
// Already protected by constructor
$data['view_file'] = 'profile';
$this->templates->members_area($data);
}
}Now every method in the controller requires a valid member token.
When to Use Each Method
| Method | Use Case |
|---|---|
attempt_get_valid_token() |
Quick validation - just checking if user is authenticated |
get_user_id() |
Need to link to application tables (e.g., fetch from members table) |
get_user_obj() |
Need multiple pieces of user info (level, code, expiry, etc.) |
get_user_level() |
Need to check or display user's role/level only |
Common Patterns
Pattern 1: Simple Protection
public function dashboard(): void {
$token = $this->trongate_tokens->attempt_get_valid_token();
if ($token === false) {
redirect('login');
}
// Show page
}Pattern 2: Admin-Only Page
public function admin_panel(): void {
$token = $this->trongate_tokens->attempt_get_valid_token(1); // admin only
if ($token === false) {
redirect('login');
}
// Show admin page
}Pattern 3: Fetch and Display User Info
public function profile(): void {
$user = $this->trongate_tokens->get_user_obj();
if ($user === false) {
redirect('login');
}
$data['user'] = $user;
$data['view_file'] = 'profile';
$this->templates->members_area($data);
}Security Notes
- Always validate on protected pages - Never assume a user is authenticated
- Use specific user levels when needed - Don't allow admin pages to accept any user level
- Redirect on failure - Always redirect to login when validation fails
- Check token expiry - The framework handles this automatically, but be aware tokens can expire mid-session
What's Next
The final page in this chapter covers:
- Destroying tokens on logout
- Cleaning up expired tokens
- Complete logout workflow
We're continually improving the Trongate documentation. If anything is incorrect, unclear, incomplete, or could be better, we'd genuinely appreciate your input.
Share your thoughts in the Documentation Feedback.