feat: 完善鉴权和密码功能,添加飞书通知模块

- 完善Token过期/不存在时跳转登录重新认证
- 实现正常的账号密码登录验证(邮箱/手机号+密码)
- 用户初始化密码设为工号(sn)
- 添加修改密码功能(API+前端页面)
- 修复扫码登录后跳转问题(zustand persist格式)
- 创建飞书通知服务 FeishuNotificationService
- 设置页面添加修改密码入口

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
root
2026-02-26 15:19:37 +08:00
parent ba555a59b7
commit 2e5f570b40
26 changed files with 2925 additions and 158 deletions
+263 -32
View File
@@ -12,25 +12,38 @@ use Webman\Http\Response;
class AuthController extends BaseController
{
/**
* 用户登录
* 用户登录(邮箱/手机号 + 密码)
*/
public function login(Request $request): Response
{
$username = $request->post('username');
$password = $request->post('password');
// TODO: 实现真实的登录逻辑
if (!$username || !$password) {
return $this->error('用户名或密码不能为空');
}
// 模拟用户数据(用于测试)
$user = User::first();
// 通过邮箱或手机号查找用户
$user = User::where(function ($query) use ($username) {
$query->where('email', $username)
->orWhere('phone', $username);
})->where('status', 1)
->first();
if (!$user) {
return $this->error('用户不存在');
return $this->error('用户不存在或已被禁用');
}
// 验证密码(如果没有设置密码,提示使用飞书登录)
if (!$user->password) {
return $this->error('该账号未设置密码,请使用飞书登录');
}
if (!password_verify($password, $user->password)) {
return $this->error('密码错误');
}
// 生成 token
$token = JwtUtil::encode([
'user_id' => $user->id,
'company_id' => $user->company_id,
@@ -39,7 +52,7 @@ class AuthController extends BaseController
return $this->success([
'token' => $token,
'user' => $user,
'user' => $user->load('company'),
]);
}
@@ -49,6 +62,7 @@ class AuthController extends BaseController
public function feishuLogin(Request $request): Response
{
$authCode = $request->post('auth_code');
$appId = $request->post('app_id');
$tenantKey = $request->post('tenant_key');
if (!$authCode) {
@@ -58,33 +72,74 @@ class AuthController extends BaseController
try {
$feishuService = new FeishuService();
// 根据 tenant_key 获取公司
$company = $feishuService->getCompanyByTenantKey($tenantKey);
// 方式1: 根据 app_id 查找飞书应用配置(推荐)
if ($appId) {
error_log("🔍 使用 app_id 查找配置: {$appId}");
if (!$company) {
return $this->error('公司不存在');
// 根据 app_id 查找飞书应用
$feishuApp = \app\model\CompanyFeishuApp::where('app_id', $appId)
->where('status', 1)
->first();
if (!$feishuApp) {
return $this->error('飞书应用配置不存在');
}
$companyId = $feishuApp->company_id;
error_log("✅ 找到飞书应用配置: company_id={$companyId}");
$feishuService->setCompany($companyId);
}
// 方式2: 根据 tenant_key 查找(兼容旧版)
elseif ($tenantKey) {
error_log("🔍 使用 tenant_key 查找配置: {$tenantKey}");
$company = $feishuService->getCompanyByTenantKey($tenantKey);
if (!$company) {
return $this->error('公司不存在');
}
$companyId = $company->id;
// 获取默认飞书应用
$feishuApp = \app\model\CompanyFeishuApp::where('company_id', $companyId)
->where('system_id', 1)
->where('status', 1)
->first();
if (!$feishuApp) {
return $this->error('未配置飞书应用');
}
error_log("✅ 找到公司配置: company_id={$companyId}");
$feishuService->setCompany($companyId);
} else {
return $this->error('缺少 app_id 或 tenant_key 参数');
}
// 设置公司并获取用户信息
$feishuService->setCompany($company->id);
// 获取用户信息
$feishuData = $feishuService->getUserInfo($authCode);
error_log("👤 获取到用户信息: " . json_encode($feishuData));
// 创建或更新用户
$user = $feishuService->createOrUpdateUser($feishuData, $company->id);
$user = $feishuService->createOrUpdateUser($feishuData, $companyId);
// 生成 JWT Token
$token = JwtUtil::encode([
'user_id' => $user->id,
'company_id' => $user->company_id,
'feishu_user_id' => $user->feishu_user_id,
'union_id' => $user->union_id,
'union_id' => $user->feishu_union_id,
]);
error_log("✅ 登录成功: user_id={$user->id}, company_id={$user->company_id}");
return $this->success([
'token' => $token,
'user' => $user->load('company'),
]);
} catch (\Exception $e) {
error_log("❌ 登录失败: " . $e->getMessage());
return $this->error($e->getMessage());
}
}
@@ -115,44 +170,75 @@ class AuthController extends BaseController
public function qrcodeLogin(Request $request): Response
{
$tenantKey = $request->post('tenant_key');
$appId = $request->post('app_id');
if (!$tenantKey) {
return $this->error('缺少租户密钥');
}
error_log("📱 qrcodeLogin - tenant_key: {$tenantKey}, app_id: {$appId}");
try {
$feishuService = new \app\service\FeishuService();
$companyId = null;
$feishuApp = null;
// 根据 tenant_key 获取公司
$company = $feishuService->getCompanyByTenantKey($tenantKey);
// 方式1: 根据 app_id 查找飞书应用配置(推荐)
if ($appId) {
$feishuApp = \app\model\CompanyFeishuApp::where('app_id', $appId)
->where('status', 1)
->first();
if (!$company) {
return $this->error('公司不存在');
if (!$feishuApp) {
return $this->error('飞书应用配置不存在');
}
$companyId = $feishuApp->company_id;
error_log("✅ 通过 app_id 找到配置: company_id={$companyId}");
}
// 方式2: 根据 tenant_key 查找(兼容旧版)
elseif ($tenantKey) {
$company = $feishuService->getCompanyByTenantKey($tenantKey);
if (!$company) {
return $this->error('公司不存在');
}
$companyId = $company->id;
// 获取默认飞书应用
$feishuApp = \app\model\CompanyFeishuApp::where('company_id', $companyId)
->where('system_id', 1)
->where('status', 1)
->first();
if (!$feishuApp) {
return $this->error('未配置飞书应用');
}
error_log("✅ 通过 tenant_key 找到配置: company_id={$companyId}");
} else {
return $this->error('缺少 app_id 或 tenant_key 参数');
}
$feishuService->setCompany($company->id);
$feishuService->setCompany($companyId);
// 生成登录会话
$loginSession = \app\model\FeishuLoginSession::create([
'company_id' => $company->id,
'company_id' => $companyId,
'tenant_key' => $tenantKey,
'status' => 'pending',
'expires_at' => date('Y-m-d H:i:s', time() + 300), // 5分钟过期
]);
// 构建扫码登录 URL(使用官方 passport 端点)
$appId = 'cli_a8033d607cba500d';
// 使用固定的 redirect_uri,session_id 通过 state 传递
// 构建扫码登录 URL
$redirectUri = urlencode("https://xsm.dev.hnxinyouhe.com/login/callback");
$authUrl = "https://passport.feishu.cn/suite/passport/oauth/authorize?client_id={$appId}&redirect_uri={$redirectUri}&response_type=code&state={$loginSession->id}";
$authUrl = "https://passport.feishu.cn/suite/passport/oauth/authorize?client_id={$feishuApp->app_id}&redirect_uri={$redirectUri}&response_type=code&state={$loginSession->id}";
error_log("✅ 生成二维码会话: session_id={$loginSession->id}");
// 生成二维码内容(返回 URL,前端生成二维码)
return $this->success([
'session_id' => $loginSession->id,
'auth_url' => $authUrl,
'expires_at' => $loginSession->expires_at,
]);
} catch (\Exception $e) {
error_log("❌ qrcodeLogin 失败: " . $e->getMessage());
return $this->error($e->getMessage());
}
}
@@ -224,46 +310,191 @@ class AuthController extends BaseController
// OAuth 2.0 标准参数是 code
$authCode = $request->get('code');
error_log("🔔 QRCode callback received - session_id: {$sessionId}, code: " . substr($authCode ?? 'null', 0, 20) . "...");
// 如果没有参数,直接返回空页面(可能是 QR SDK 的预检请求)
if (!$sessionId && !$authCode) {
error_log("ℹ️ Callback called without parameters, returning empty page");
return new \Webman\Http\Response(200, ['Content-Type' => 'text/html; charset=utf-8'], '');
}
if (!$sessionId) {
error_log("❌ Callback missing session_id");
return $this->error('缺少会话ID');
}
if (!$authCode) {
error_log("❌ Callback missing auth_code");
return $this->error('缺少授权码');
}
try {
$session = \app\model\FeishuLoginSession::find($sessionId);
error_log("🔍 Session found: " . ($session ? "id={$session->id}, status={$session->status}" : "null"));
if (!$session) {
error_log("❌ Session not found for id: {$sessionId}");
return $this->error('登录会话不存在');
}
// 检查是否过期
if (strtotime($session->expires_at) < time()) {
error_log("⏰ Session expired at: {$session->expires_at}");
$session->status = 'expired';
$session->save();
return $this->error('二维码已过期');
}
error_log("🔄 Processing login for company_id: {$session->company_id}");
// 使用 session 的公司信息
$feishuService = new \app\service\FeishuService();
$feishuService->setCompany($session->company_id);
// 获取用户信息
$feishuData = $feishuService->getUserInfo($authCode);
error_log("👤 Got user info: " . json_encode($feishuData));
// 创建或更新用户
$user = $feishuService->createOrUpdateUser($feishuData, $session->company_id);
error_log("✅ User created/updated: user_id={$user->id}");
// 更新会话状态
$session->status = 'success';
$session->user_id = $user->id;
$session->save();
$saved = $session->save();
error_log("💾 Session save result: " . ($saved ? 'success' : 'failed') . ", new status: {$session->status}");
// 返回极简空白页面(飞书APP内扫码通常不会真正访问此URL)
// 飞书会在APP内直接处理回调,返回到之前的界面
return new \Webman\Http\Response(200, ['Content-Type' => 'text/html; charset=utf-8'], '');
// 生成 JWT Token
$token = \app\util\JwtUtil::encode([
'user_id' => $user->id,
'company_id' => $user->company_id,
'feishu_user_id' => $user->feishu_user_id,
'union_id' => $user->feishu_union_id,
]);
error_log("🎫 Generated token for user: {$user->id}");
// 返回成功页面(包含 token,前端会保存到 localStorage)
$userName = htmlspecialchars($user->name ?? '用户');
// 准备用户数据JSON
$userJson = json_encode([
'id' => $user->id,
'name' => $user->name,
'email' => $user->email,
'avatar' => $user->avatar,
'phone' => $user->phone,
'company_id' => $user->company_id,
'status' => $user->status,
], JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);
$html = <<<HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录成功</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.container {
text-align: center;
padding: 40px;
background: rgba(255,255,255,0.1);
border-radius: 20px;
backdrop-filter: blur(10px);
}
.icon {
font-size: 60px;
margin-bottom: 20px;
}
h1 {
margin: 0 0 10px 0;
font-size: 24px;
}
p {
margin: 10px 0;
opacity: 0.9;
}
.spinner {
width: 40px;
height: 40px;
border: 4px solid rgba(255,255,255,0.3);
border-top-color: white;
border-radius: 50%;
animation: spin 1s linear infinite;
margin: 20px auto;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
</style>
</head>
<body>
<div class="container">
<div class="icon">✅</div>
<h1>登录成功!</h1>
<p>欢迎回来,{$userName}</p>
<p>正在跳转到应用...</p>
<div class="spinner"></div>
</div>
<script>
// 保存 token 到 localStorage
try {
localStorage.setItem('token', '$token');
localStorage.setItem('i18nextLng', 'zh');
console.log('✅ Token saved to localStorage');
// 保存用户信息到 zustand persist storage(正确的格式)
const userState = {
state: {
user: $userJson,
token: '$token',
currentCompany: null,
isLoggedIn: true
},
version: 0
};
localStorage.setItem('user-storage', JSON.stringify(userState));
console.log('✅ User state saved to localStorage:', userState);
// 通知父窗口登录成功(如果在弹窗中)
if (window.opener) {
window.opener.postMessage({
type: 'feishu-login-success',
data: { token: '$token', user: $userJson }
}, '*');
setTimeout(function() {
window.close();
}, 500);
} else {
// 否则跳转到首页
setTimeout(function() {
window.location.href = '/dashboard';
}, 1500);
}
} catch (e) {
console.error('❌ Failed to save data:', e);
// 如果 localStorage 不可用,使用 sessionStorage
sessionStorage.setItem('token', '$token');
setTimeout(function() {
window.location.href = '/dashboard';
}, 1500);
}
</script>
</body>
</html>
HTML;
return new \Webman\Http\Response(200, ['Content-Type' => 'text/html; charset=utf-8'], $html);
} catch (\Exception $e) {
return $this->error($e->getMessage());
}
+41
View File
@@ -60,6 +60,47 @@ class UserController extends BaseController
return $this->success();
}
/**
* 修改密码
*/
public function changePassword(Request $request): Response
{
$userId = $this->getUserId($request);
$user = User::find($userId);
if (!$user) {
return $this->error('用户不存在');
}
$oldPassword = $request->post('old_password');
$newPassword = $request->post('new_password');
$confirmPassword = $request->post('confirm_password');
// 验证参数
if (!$oldPassword || !$newPassword || !$confirmPassword) {
return $this->error('请填写完整信息');
}
if (strlen($newPassword) < 6) {
return $this->error('新密码长度不能少于6位');
}
if ($newPassword !== $confirmPassword) {
return $this->error('两次输入的密码不一致');
}
// 验证旧密码
if ($user->password && !password_verify($oldPassword, $user->password)) {
return $this->error('原密码错误');
}
// 更新密码
$user->password = password_hash($newPassword, PASSWORD_DEFAULT);
$user->save();
return $this->success(null, '密码修改成功');
}
/**
* 获取用户列表(用于选择审批人等)
*/
@@ -0,0 +1,478 @@
<?php
namespace app\service;
use app\model\User;
use app\model\Company;
use app\util\FeishuUtil;
use app\util\HttpClient;
use Exception;
/**
* 飞书通知服务
* 提供多种卡片类型的消息通知功能
*/
class FeishuNotificationService
{
private ?int $companyId = null;
private ?int $appId = null;
/**
* 设置当前操作的公司
*/
public function setCompany(int $companyId): self
{
$this->companyId = $companyId;
return $this;
}
/**
* 设置飞书应用ID(支持多应用)
*/
public function setApp(int $appId): self
{
$this->appId = $appId;
return $this;
}
/**
* 获取飞书应用配置
*/
private function getAppConfig(): array
{
if (!$this->companyId) {
throw new Exception('未设置公司ID');
}
if ($this->appId) {
$app = \app\model\CompanyFeishuApp::find($this->appId);
if (!$app || $app->status !== 1) {
throw new Exception('飞书应用配置不存在');
}
return $app->toArray();
}
$app = \app\model\CompanyFeishuApp::where('company_id', $this->companyId)
->where('system_id', 1)
->where('status', 1)
->orderBy('sort')
->first();
if (!$app) {
throw new Exception('未配置飞书应用');
}
return $app->toArray();
}
/**
* 获取 access_token
*/
private function getAccessToken(): string
{
$app = $this->getAppConfig();
return FeishuUtil::getAppAccessToken($app['id']);
}
/**
* 发送审批通知
*
* @param array $params
* - user_id: 接收人ID
* - title: 通知标题
* - applicant: 申请人姓名
* - type: 申请类型
* - content: 申请内容摘要
* - url: 详情链接
* - approve_url: 通过按钮链接(可选)
* - reject_url: 拒绝按钮链接(可选)
* @return bool
*/
public function sendApprovalNotification(array $params): bool
{
$userId = $params['user_id'] ?? null;
if (!$userId) {
error_log('❌ sendApprovalNotification: 缺少 user_id');
return false;
}
try {
$user = User::find($userId);
if (!$user || !$user->feishu_user_id) {
error_log("❌ sendApprovalNotification: 用户不存在或未绑定飞书, user_id={$userId}");
return false;
}
$card = $this->buildApprovalCard($params);
return $this->sendMessage($user->feishu_user_id, $card);
} catch (Exception $e) {
error_log('❌ sendApprovalNotification 失败: ' . $e->getMessage());
return false;
}
}
/**
* 发送系统通知
*
* @param array $params
* - user_ids: 接收人ID数组
* - title: 通知标题
* - content: 通知内容
* - url: 跳转链接(可选)
* @return array 返回每个用户的发送结果
*/
public function sendSystemNotification(array $params): array
{
$userIds = $params['user_ids'] ?? [];
if (empty($userIds)) {
error_log('❌ sendSystemNotification: 缺少 user_ids');
return [];
}
$results = [];
foreach ($userIds as $userId) {
try {
$user = User::find($userId);
if (!$user || !$user->feishu_user_id) {
$results[$userId] = false;
continue;
}
$card = $this->buildSystemCard($params);
$results[$userId] = $this->sendMessage($user->feishu_user_id, $card);
} catch (Exception $e) {
error_log("❌ sendSystemNotification 失败: user_id={$userId}, error=" . $e->getMessage());
$results[$userId] = false;
}
}
return $results;
}
/**
* 发送提醒通知
*
* @param array $params
* - user_id: 接收人ID
* - title: 提醒标题
* - content: 提醒内容
* - level: 提醒级别 (info/warning/urgent)
* - url: 跳转链接(可选)
* @return bool
*/
public function sendReminderNotification(array $params): bool
{
$userId = $params['user_id'] ?? null;
if (!$userId) {
error_log('❌ sendReminderNotification: 缺少 user_id');
return false;
}
try {
$user = User::find($userId);
if (!$user || !$user->feishu_user_id) {
error_log("❌ sendReminderNotification: 用户不存在或未绑定飞书, user_id={$userId}");
return false;
}
$card = $this->buildReminderCard($params);
return $this->sendMessage($user->feishu_user_id, $card);
} catch (Exception $e) {
error_log('❌ sendReminderNotification 失败: ' . $e->getMessage());
return false;
}
}
/**
* 批量发送通知
*
* @param array $params
* - user_ids: 接收人ID数组
* - type: 通知类型 (approval/system/reminder)
* - 其他参数根据类型不同而不同
* @return array
*/
public function sendBatchNotification(array $params): array
{
$userIds = $params['user_ids'] ?? [];
$type = $params['type'] ?? 'system';
$results = [];
foreach ($userIds as $userId) {
$notifyParams = array_merge($params, ['user_id' => $userId]);
unset($notifyParams['user_ids']);
switch ($type) {
case 'approval':
$results[$userId] = $this->sendApprovalNotification($notifyParams);
break;
case 'reminder':
$results[$userId] = $this->sendReminderNotification($notifyParams);
break;
case 'system':
default:
$results[$userId] = $this->sendSystemNotification(['user_ids' => [$userId]] + $params)[$userId] ?? false;
break;
}
}
return $results;
}
/**
* 构建审批通知卡片
*/
private function buildApprovalCard(array $params): array
{
$title = $params['title'] ?? '新的审批申请';
$applicant = $params['applicant'] ?? '未知';
$type = $params['type'] ?? '申请';
$content = $params['content'] ?? '';
$url = $params['url'] ?? '';
$approveUrl = $params['approve_url'] ?? '';
$rejectUrl = $params['reject_url'] ?? '';
$elements = [
[
'tag' => 'div',
'fields' => [
[
'is_short' => true,
'text' => [
'content' => "**申请人**: {$applicant}",
'tag' => 'lark_md',
],
],
[
'is_short' => true,
'text' => [
'content' => "**申请类型**: {$type}",
'tag' => 'lark_md',
],
],
],
],
];
if ($content) {
$elements[] = [
'tag' => 'div',
'text' => [
'content' => "**申请内容**:\n{$content}",
'tag' => 'lark_md',
],
];
}
// 构建操作按钮
$actions = [];
if ($approveUrl) {
$actions[] = [
'tag' => 'button',
'text' => [
'content' => '通过',
'tag' => 'plain_text',
],
'type' => 'primary',
'url' => $approveUrl,
];
}
if ($rejectUrl) {
$actions[] = [
'tag' => 'button',
'text' => [
'content' => '拒绝',
'tag' => 'plain_text',
],
'type' => 'default',
'url' => $rejectUrl,
];
}
if ($url) {
$actions[] = [
'tag' => 'button',
'text' => [
'content' => '查看详情',
'tag' => 'plain_text',
],
'type' => 'default',
'url' => $url,
];
}
if (!empty($actions)) {
$elements[] = [
'tag' => 'action',
'actions' => $actions,
];
}
return [
'header' => [
'title' => [
'content' => "📋 {$title}",
'tag' => 'plain_text',
],
'template' => 'blue',
],
'elements' => $elements,
];
}
/**
* 构建系统通知卡片
*/
private function buildSystemCard(array $params): array
{
$title = $params['title'] ?? '系统通知';
$content = $params['content'] ?? '';
$url = $params['url'] ?? '';
$elements = [];
if ($content) {
$elements[] = [
'tag' => 'div',
'text' => [
'content' => $content,
'tag' => 'plain_text',
],
];
}
if ($url) {
$elements[] = [
'tag' => 'action',
'actions' => [
[
'tag' => 'button',
'text' => [
'content' => '查看详情',
'tag' => 'plain_text',
],
'type' => 'default',
'url' => $url,
],
],
];
}
return [
'header' => [
'title' => [
'content' => "🔔 {$title}",
'tag' => 'plain_text',
],
'template' => 'gray',
],
'elements' => $elements,
];
}
/**
* 构建提醒通知卡片
*/
private function buildReminderCard(array $params): array
{
$title = $params['title'] ?? '提醒';
$content = $params['content'] ?? '';
$level = $params['level'] ?? 'info'; // info, warning, urgent
$url = $params['url'] ?? '';
// 根据级别选择模板颜色
$templateMap = [
'info' => 'blue',
'warning' => 'orange',
'urgent' => 'red',
];
$template = $templateMap[$level] ?? 'blue';
// 根据级别选择图标
$iconMap = [
'info' => '💡',
'warning' => '⚠️',
'urgent' => '🚨',
];
$icon = $iconMap[$level] ?? '💡';
$elements = [];
if ($content) {
$elements[] = [
'tag' => 'div',
'text' => [
'content' => $content,
'tag' => 'plain_text',
],
];
}
if ($url) {
$elements[] = [
'tag' => 'action',
'actions' => [
[
'tag' => 'button',
'text' => [
'content' => '查看',
'tag' => 'plain_text',
],
'type' => 'primary',
'url' => $url,
],
],
];
}
return [
'header' => [
'title' => [
'content' => "{$icon} {$title}",
'tag' => 'plain_text',
],
'template' => $template,
],
'elements' => $elements,
];
}
/**
* 发送消息到飞书
*/
private function sendMessage(string $feishuUserId, array $card): bool
{
try {
$token = $this->getAccessToken();
$response = HttpClient::httpPost(
"https://open.feishu.cn/open-apis/message/v4/send_messages",
[
'receive_id_type' => 'user_id',
'receive_id' => $feishuUserId,
'msg_type' => 'interactive',
'content' => json_encode(['card' => $card]),
],
[
'Authorization: Bearer ' . $token,
]
);
$code = $response['code'] ?? -1;
$success = $code === 0;
if ($success) {
error_log("✅ 飞书消息发送成功: feishu_user_id={$feishuUserId}");
} else {
error_log("❌ 飞书消息发送失败: feishu_user_id={$feishuUserId}, code={$code}, msg=" . ($response['msg'] ?? ''));
}
return $success;
} catch (Exception $e) {
error_log('❌ sendMessage 异常: ' . $e->getMessage());
return false;
}
}
}
+28 -7
View File
@@ -122,6 +122,7 @@ class FeishuService
/**
* 创建或更新用户
* 注意:同一用户在不同企业的账号是独立的,通过 company_id + union_id 组合查找
*/
public function createOrUpdateUser(array $feishuData, int $companyId): User
{
@@ -135,27 +136,47 @@ class FeishuService
throw new Exception('缺少 union_id');
}
// 查找或创建用户
$user = User::byFeishuUnionId($unionId)->first();
// ⭐ 关键:通过 company_id + union_id 组合查找用户
// 这样同一个 union_id 在不同公司的账号是独立的
$user = User::where('company_id', $companyId)
->where('union_id', $unionId)
->first();
if (!$user) {
error_log("✨ 创建新用户: company={$companyId}, union_id={$unionId}, name={$name}");
// 初始密码使用 sn(工号),如果没有 sn 则使用 union_id 的前6位
$initialPassword = $feishuData['sn'] ?? substr($unionId, 0, 6);
$user = User::create([
'company_id' => $companyId,
'feishu_user_id' => $userId,
'feishu_union_id' => $unionId,
'union_id' => $unionId,
'name' => $name,
'email' => $email,
'avatar' => $avatar,
'status' => 1,
'password' => password_hash($initialPassword, PASSWORD_DEFAULT), // 初始密码加密
'status' => 1, // 新用户默认在职
]);
error_log("🔑 初始密码设置为 sn: {$initialPassword}");
} else {
// 更新用户信息
$user->update([
error_log("🔄 更新用户: id={$user->id}, company={$companyId}, union_id={$unionId}, 当前状态={$user->status}");
// 离职员工禁止登录
if ($user->status == 0) {
error_log("❌ 离职员工尝试登录: id={$user->id}, status=0");
throw new Exception('该员工已离职,无法登录系统');
}
// 更新用户信息(在职员工)
$updateData = [
'feishu_user_id' => $userId,
'name' => $name,
'avatar' => $avatar,
'email' => $email,
]);
];
$user->update($updateData);
}
return $user;
+6 -3
View File
@@ -50,7 +50,8 @@ class FeishuUtil
]);
if ($response['code'] !== 0) {
throw new Exception('获取 app_access_token 失败: ' . ($response['msg'] ?? '未知错误'));
$errorMsg = $response['msg'] ?? $response['message'] ?? '未知错误';
throw new Exception('获取 app_access_token 失败: ' . $errorMsg);
}
$token = $response['tenant_access_token'];
@@ -109,7 +110,8 @@ class FeishuUtil
error_log("📝 获取 user_access_token 响应: " . json_encode($response));
if ($response['code'] !== 0) {
throw new Exception('获取 user_access_token 失败: ' . ($response['msg'] ?? '未知错误'));
$errorMsg = $response['msg'] ?? $response['message'] ?? '未知错误';
throw new Exception('获取 user_access_token 失败: ' . $errorMsg);
}
if (!isset($response['data']['access_token'])) {
@@ -149,7 +151,8 @@ class FeishuUtil
error_log("📝 获取用户信息响应: " . json_encode($response));
if ($response['code'] !== 0) {
throw new Exception('获取用户信息失败: ' . ($response['msg'] ?? '未知错误'));
$errorMsg = $response['msg'] ?? $response['message'] ?? '未知错误';
throw new Exception('获取用户信息失败: ' . $errorMsg);
}
$userInfo = $response['data'] ?? [];
+1
View File
@@ -24,6 +24,7 @@ Route::group('/api/v1/user', function () {
Route::get('/companies', [app\controller\UserController::class, 'companies']);
Route::get('/list', [app\controller\UserController::class, 'list']);
Route::post('/switch-company', [app\controller\UserController::class, 'switchCompany']);
Route::post('/change-password', [app\controller\UserController::class, 'changePassword']);
})->middleware($authMiddleware);
// 审批路由(需要认证)