File size: 5,923 Bytes
0dff816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
<?php
// models/TokenManager.php
require_once '../../db.php';

class TokenManager {
    private $conn;
    private $table_tokens = "access_tokens";
    private $table_usage = "token_usage_logs";
    
    public function __construct() {
        $database = new Database();
        $this->conn = $database->getConnection();
        
        // Create tables if they don't exist
        $this->createTablesIfNotExist();
    }
    
    private function createTablesIfNotExist() {
        try {
            // Create access_tokens table
            $query = "CREATE TABLE IF NOT EXISTS access_tokens (
                id INT PRIMARY KEY AUTO_INCREMENT,
                user_id INT NOT NULL,
                token_name VARCHAR(100) NOT NULL,
                token_value VARCHAR(255) UNIQUE NOT NULL,
                permissions JSON NOT NULL,
                ip_restrictions TEXT,
                expires_at TIMESTAMP NULL,
                is_active BOOLEAN DEFAULT TRUE,
                last_used TIMESTAMP NULL,
                usage_count INT DEFAULT 0,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )";
            $this->conn->exec($query);
            
            // Create token_usage_logs table
            $query = "CREATE TABLE IF NOT EXISTS token_usage_logs (
                id INT PRIMARY KEY AUTO_INCREMENT,
                token_id INT NOT NULL,
                user_id INT NOT NULL,
                endpoint VARCHAR(100) NOT NULL,
                ip_address VARCHAR(45),
                user_agent TEXT,
                request_method VARCHAR(10),
                response_code INT,
                processing_time_ms INT,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )";
            $this->conn->exec($query);
            
        } catch (PDOException $e) {
            error_log("Table creation error: " . $e->getMessage());
        }
    }
    
    private function generateToken() {
        return 'jm_' . bin2hex(random_bytes(24));
    }
    
    public function createToken($user_id, $token_name, $permissions, $expires_in_days = 30, $ip_restrictions = null) {
        try {
            $token_value = $this->generateToken();
            
            $expires_at = null;
            if ($expires_in_days > 0) {
                $expires_at = date('Y-m-d H:i:s', strtotime("+{$expires_in_days} days"));
            }
            
            $query = "INSERT INTO {$this->table_tokens} 
                     (user_id, token_name, token_value, permissions, ip_restrictions, expires_at) 
                     VALUES (:user_id, :token_name, :token_value, :permissions, :ip_restrictions, :expires_at)";
            
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(":user_id", $user_id);
            $stmt->bindParam(":token_name", $token_name);
            $stmt->bindParam(":token_value", $token_value);
            $stmt->bindParam(":permissions", json_encode($permissions));
            $stmt->bindParam(":ip_restrictions", $ip_restrictions);
            $stmt->bindParam(":expires_at", $expires_at);
            
            if ($stmt->execute()) {
                return [
                    'success' => true,
                    'token' => $token_value,
                    'id' => $this->conn->lastInsertId()
                ];
            }
        } catch (PDOException $e) {
            error_log("Token creation error: " . $e->getMessage());
        }
        
        return ['success' => false, 'message' => 'Failed to create token'];
    }
    
    public function getUserTokens($user_id) {
        try {
            $query = "SELECT * FROM {$this->table_tokens} 
                     WHERE user_id = :user_id AND is_active = TRUE 
                     ORDER BY created_at DESC";
            
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(":user_id", $user_id);
            $stmt->execute();
            
            $tokens = [];
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $row['permissions'] = json_decode($row['permissions'], true) ?? [];
                $row['is_expired'] = $row['expires_at'] && strtotime($row['expires_at']) < time();
                $tokens[] = $row;
            }
            
            return $tokens;
        } catch (PDOException $e) {
            error_log("Get tokens error: " . $e->getMessage());
            return [];
        }
    }
    
    public function revokeToken($token_id, $user_id) {
        try {
            $query = "UPDATE {$this->table_tokens} SET is_active = FALSE 
                     WHERE id = :token_id AND user_id = :user_id";
            
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(":token_id", $token_id);
            $stmt->bindParam(":user_id", $user_id);
            
            return $stmt->execute();
        } catch (PDOException $e) {
            error_log("Revoke token error: " . $e->getMessage());
            return false;
        }
    }
    
    public function getRealtimeStats($user_id, $hours = 24) {
        try {
            $query = "SELECT 
                        COUNT(*) as total_calls,
                        AVG(processing_time_ms) as avg_response_time
                     FROM {$this->table_usage} 
                     WHERE user_id = :user_id 
                     AND created_at >= DATE_SUB(NOW(), INTERVAL :hours HOUR)";
            
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(":user_id", $user_id);
            $stmt->bindParam(":hours", $hours);
            $stmt->execute();
            
            return $stmt->fetch(PDO::FETCH_ASSOC) ?: ['total_calls' => 0, 'avg_response_time' => 0];
        } catch (PDOException $e) {
            error_log("Stats error: " . $e->getMessage());
            return ['total_calls' => 0, 'avg_response_time' => 0];
        }
    }
}
?>