[PHP] 纯文本查看 复制代码 require 'flight/Flight.php';
// 设置数据库连接信息
Flight::register('db', 'PDO', array('mysql:host=localhost;dbname=test', 'username', 'password'));
// 注册路由
Flight::route('POST /register', function(){
$username = Flight::request()->data['username'];
$password = Flight::request()->data['password'];
// 检查用户名是否已存在
$db = Flight::db();
$stmt = $db->prepare('SELECT * FROM users WHERE username = :username');
$stmt->execute(array(':username' => $username));
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user) {
// 用户名已存在
Flight::json(array('status' => 'error', 'message' => 'Username already exists'));
} else {
// 创建新用户
$stmt = $db->prepare('INSERT INTO users (username, password) VALUES (:username, :password)');
$stmt->execute(array(':username' => $username, ':password' => $password));
// 注册成功
Flight::json(array('status' => 'success', 'message' => 'Registration successful'));
}
});
// 登录路由
Flight::route('POST /login', function(){
$username = Flight::request()->data['username'];
$password = Flight::request()->data['password'];
// 查询数据库验证用户名和密码
$db = Flight::db();
$stmt = $db->prepare('SELECT * FROM users WHERE username = :username AND password = :password');
$stmt->execute(array(':username' => $username, ':password' => $password));
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user) {
// 生成Token
$token = generateToken($user['id']);
// 返回Token
Flight::json(array('status' => 'success', 'token' => $token));
} else {
// 登录失败
Flight::json(array('status' => 'error', 'message' => 'Invalid username or password'));
}
});
// 注销路由
Flight::route('POST /logout', function(){
// 实现注销逻辑,如删除Token等
// ...
// 注销成功
Flight::json(array('status' => 'success', 'message' => 'Logout successful'));
});
// 受保护的路由,需要Token验证
Flight::route('GET /protected', function(){
// 验证Token
$token = getTokenFromHeader();
if (validateToken($token)) {
// Token验证通过,返回受保护的资源
Flight::json(array('status' => 'success', 'message' => 'Protected resource'));
} else {
// Token验证失败
Flight::json(array('status' => 'error', 'message' => 'Invalid token'));
}
});
// 生成Token
function generateToken($userId) {
// 构建JWT的Header
$header = array(
'alg' => 'HS256',
'typ' => 'JWT'
);
// 构建JWT的Payload
$payload = array(
'user_id' => $userId,
'exp' => time() + 3600 // 设置Token的过期时间为1小时
);
// 编码Header和Payload为Base64字符串
$encodedHeader = base64UrlEncode(json_encode($header));
$encodedPayload = base64UrlEncode(json_encode($payload));
// 构建JWT的签名
$signature = hash_hmac('sha256', $encodedHeader . '.' . $encodedPayload, 'secret_key', true);
$encodedSignature = base64UrlEncode($signature);
// 构建完整的JWT
$token = $encodedHeader . '.' . $encodedPayload . '.' . $encodedSignature;
return $token;
}
// 验证Token
function validateToken($token) {
// 拆分Token为Header、Payload和Signature
$parts = explode('.', $token);
$encodedHeader = $parts[0];
$encodedPayload = $parts[1];
$encodedSignature = $parts[2];
// 解码Header和Payload
$header = json_decode(base64UrlDecode($encodedHeader), true);
$payload = json_decode(base64UrlDecode($encodedPayload), true);
// 验证签名
$signature = hash_hmac('sha256', $encodedHeader . '.' . $encodedPayload, 'secret_key', true);
$encodedSignatureCheck = base64UrlEncode($signature);
// 验证Token是否过期
if ($payload['exp'] < time()) {
return false;
}
// 验证签名是否匹配
if ($encodedSignature !== $encodedSignatureCheck) {
return false;
}
// 验证用户是否存在
$db = Flight::db();
$stmt = $db->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute(array(':id' => $payload['user_id']));
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user) {
return true;
} else {
return false;
}
}
// 从请求头中获取Token
function getTokenFromHeader() {
$headers = apache_request_headers();
if (isset($headers['Authorization'])) {
$authHeader = $headers['Authorization'];
$token = str_replace('Bearer ', '', $authHeader);
return $token;
} else {
return null;
}
}
// Base64 URL编码
function base64UrlEncode($data) {
$base64 = base64_encode($data);
$urlSafe = strtr($base64, '+/', '-_');
return rtrim($urlSafe, '=');
}
// Base64 URL解码
function base64UrlDecode($data) {
$urlSafe = strtr($data, '-_', '+/');
$base64 = base64_decode($urlSafe);
return $base64;
}
// 启动FlightPHP框架
Flight::start();
|