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
@@ -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;