Files
ClassManager/frontend/api/save_session.php
2026-04-13 19:23:06 +08:00

118 lines
2.8 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
/**
* 班级操行分管理系统 - Session 保存接口
*
* 开发者: Canglan
* 联系方式: admin@sea-studio.top
* 版权归属: Sea Network Technology Studio
* 许可证: MIT License
*
* 版权所有 © Sea Network Technology Studio
*
* 说明:登录成功后,前端调用此接口将用户信息同步到 PHP Session
*/
// 引入配置文件以初始化 Session
require_once __DIR__ . '/../config.php';
// 设置响应头
header('Content-Type: application/json; charset=utf-8');
// 允许跨域(如果需要)
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
// 处理预检请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit();
}
// 只允许 POST 请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode([
'success' => false,
'message' => '仅支持 POST 请求'
]);
exit();
}
// 获取原始输入
$input = file_get_contents('php://input');
if (empty($input)) {
http_response_code(400);
echo json_encode([
'success' => false,
'message' => '请求数据为空'
]);
exit();
}
// 解析 JSON 数据
$data = json_decode($input, true);
if (json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
echo json_encode([
'success' => false,
'message' => 'JSON 解析失败: ' . json_last_error_msg()
]);
exit();
}
// 验证必要字段
$requiredFields = ['user_id', 'user_type', 'username'];
$missingFields = [];
foreach ($requiredFields as $field) {
if (!isset($data[$field]) || empty($data[$field])) {
$missingFields[] = $field;
}
}
if (!empty($missingFields)) {
http_response_code(400);
echo json_encode([
'success' => false,
'message' => '缺少必要字段: ' . implode(', ', $missingFields)
]);
exit();
}
// 验证 user_type 是否合法
$validUserTypes = ['student', 'parent', 'admin'];
if (!in_array($data['user_type'], $validUserTypes)) {
http_response_code(400);
echo json_encode([
'success' => false,
'message' => '无效的用户类型'
]);
exit();
}
// 设置 Session 变量
$_SESSION['user_id'] = $data['user_id'];
$_SESSION['user_type'] = $data['user_type'];
$_SESSION['username'] = $data['username'];
$_SESSION['real_name'] = $data['real_name'] ?? '';
$_SESSION['role'] = $data['role'] ?? ''; // 添加 role 字段
$_SESSION['login_time'] = time();
// 如果是学生,额外设置 student_id与 user_id 相同)
if ($data['user_type'] === 'student') {
$_SESSION['student_id'] = $data['user_id'];
}
// 保存 Session
session_write_close();
// 返回成功响应
http_response_code(200);
echo json_encode([
'success' => true,
'message' => 'Session 保存成功'
]);
exit();