CaiWuXiTong/app/Services/Auth/DingTalkOAuthClient.php
苏木 29d19aaa34 fix(权限): 供应商登录使用钉钉当前组织
供应商登录使用钉钉当前组织部门,HR 副本保留为兼容回退。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-26 14:20:37 +08:00

371 lines
14 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
namespace App\Services\Auth;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use RuntimeException;
class DingTalkOAuthClient
{
private ?string $cachedAppAccessToken = null;
public function isConfigured(): bool
{
return (bool) config('dingtalk.enabled')
&& $this->configuredString('dingtalk.client_id') !== ''
&& $this->configuredString('dingtalk.client_secret') !== ''
&& $this->configuredString('dingtalk.redirect_uri') !== '';
}
public function hasApplicationCredentials(): bool
{
return $this->configuredString('dingtalk.client_id') !== ''
&& $this->configuredString('dingtalk.client_secret') !== '';
}
public function authorizationUrl(string $state): string
{
$this->ensureConfigured();
return rtrim($this->configuredString('dingtalk.authorize_url'), '?') . '?' . http_build_query([
'redirect_uri' => $this->configuredString('dingtalk.redirect_uri'),
'response_type' => 'code',
'client_id' => $this->configuredString('dingtalk.client_id'),
'scope' => 'openid',
'prompt' => 'consent',
'state' => $state,
], '', '&', PHP_QUERY_RFC3986);
}
/**
* @return array{access_token: string, expires_in: int|null}
*/
public function exchangeAuthorizationCode(string $code): array
{
$this->ensureConfigured();
try {
$response = Http::asJson()
->acceptJson()
->timeout($this->timeout())
->post($this->configuredString('dingtalk.token_url'), [
'clientId' => $this->configuredString('dingtalk.client_id'),
'clientSecret' => $this->configuredString('dingtalk.client_secret'),
'code' => $code,
'grantType' => 'authorization_code',
])
->throw();
} catch (RequestException $exception) {
throw new RuntimeException('DingTalk token exchange failed.', 0, $exception);
}
$accessToken = trim((string) $response->json('accessToken'));
if ($accessToken === '') {
throw new RuntimeException('DingTalk token response did not contain an access token.');
}
return [
'access_token' => $accessToken,
'expires_in' => is_numeric($response->json('expireIn')) ? (int) $response->json('expireIn') : null,
];
}
/** @return array{union_id: string, open_id: string|null, nickname: string|null} */
public function currentUser(string $accessToken): array
{
try {
$response = Http::acceptJson()
->withHeaders(['x-acs-dingtalk-access-token' => $accessToken])
->timeout($this->timeout())
->get($this->configuredString('dingtalk.user_url'))
->throw();
} catch (RequestException $exception) {
throw new RuntimeException('DingTalk user lookup failed.', 0, $exception);
}
$unionId = trim((string) $response->json('unionId'));
if ($unionId === '') {
throw new RuntimeException('DingTalk user response did not contain a union id.');
}
return [
'union_id' => $unionId,
'open_id' => $this->nullableString($response->json('openId')),
'nickname' => $this->nullableString($response->json('nick')),
];
}
/**
* Resolve a user through the enterprise application. A personal DingTalk
* account is not considered trusted unless the enterprise application can
* resolve it to an active internal user.
*
* @return array{
* union_id: string,
* open_id: string|null,
* dingtalk_user_id: string,
* nickname: string|null,
* email: string|null,
* mobile: string|null,
* active: bool,
* department_ids: list<string>
* }
*/
public function enterpriseUser(array $oauthProfile): array
{
$unionId = trim((string) ($oauthProfile['union_id'] ?? ''));
if ($unionId === '') {
throw new RuntimeException('DingTalk enterprise lookup requires a union id.');
}
$enterpriseProfile = Cache::remember(
'dingtalk:enterprise-user:v2:' . hash('sha256', $unionId),
now()->addMinutes(max(
1,
(int) config('dingtalk.enterprise_user_cache_minutes', 10),
)),
function () use ($unionId, $oauthProfile): array {
$appToken = $this->appAccessToken();
try {
$userIdResponse = Http::asJson()
->acceptJson()
->timeout($this->timeout())
->withQueryParameters(['access_token' => $appToken])
->post(
$this->configuredString('dingtalk.user_by_union_id_url'),
['unionid' => $unionId],
)
->throw();
} catch (RequestException $exception) {
throw new RuntimeException(
'DingTalk enterprise user lookup failed.',
0,
$exception,
);
}
$userId = trim((string) $userIdResponse->json('result.userid'));
if ((int) $userIdResponse->json('errcode', -1) !== 0 || $userId === '') {
throw new RuntimeException('DingTalk identity is not an enterprise user.');
}
try {
$detailResponse = Http::asJson()
->acceptJson()
->timeout($this->timeout())
->withQueryParameters(['access_token' => $appToken])
->post(
$this->configuredString('dingtalk.user_detail_url'),
['userid' => $userId],
)
->throw();
} catch (RequestException $exception) {
throw new RuntimeException(
'DingTalk enterprise user detail lookup failed.',
0,
$exception,
);
}
$detail = $detailResponse->json('result');
if ((int) $detailResponse->json('errcode', -1) !== 0 || ! is_array($detail)) {
throw new RuntimeException('DingTalk enterprise user detail was unavailable.');
}
$detailUserId = trim((string) ($detail['userid'] ?? ''));
if ($detailUserId !== '' && ! hash_equals($userId, $detailUserId)) {
throw new RuntimeException(
'DingTalk enterprise user identity was inconsistent.',
);
}
$active = filter_var(
$detail['active'] ?? null,
FILTER_VALIDATE_BOOL,
FILTER_NULL_ON_FAILURE,
);
return [
'dingtalk_user_id' => $userId,
'nickname' => $this->nullableString(
$detail['name'] ?? ($oauthProfile['nickname'] ?? null),
),
'email' => $this->nullableString($detail['email'] ?? null),
'mobile' => $this->nullableString($detail['mobile'] ?? null),
'active' => $active === true,
'department_ids' => $this->departmentIds($detail['dept_id_list'] ?? []),
];
},
);
return [
'union_id' => $unionId,
'open_id' => $oauthProfile['open_id'] ?? null,
...$enterpriseProfile,
];
}
/**
* Resolve the current DingTalk department ancestry for a member.
*
* This is separate from the upstream HR replica: supplier organization
* members can appear in DingTalk before HR data catches up.
*
* @param list<int|string> $departmentIds
* @return list<array{Id:int,parent_id:int,name:string,depth:int}>
*/
public function departmentLineage(array $departmentIds): array
{
$departmentIds = array_slice(array_values(array_unique(array_filter(
array_map(static fn (mixed $id): string => trim((string) $id), $departmentIds),
static fn (string $id): bool => ctype_digit($id) && (int) $id > 0,
))), 0, 64);
if ($departmentIds === []) {
return [];
}
$lineage = [];
$seen = [];
$queue = array_map(static fn (string $id): array => [(int) $id, 0], $departmentIds);
while ($queue !== []) {
[$departmentId, $depth] = array_shift($queue);
if (isset($seen[$departmentId])) {
continue;
}
if ($depth >= 20) {
throw new RuntimeException('DingTalk department hierarchy is too deep.');
}
$seen[$departmentId] = true;
$department = $this->departmentDetail($departmentId);
$realDepartmentId = (int) ($department['dept_id'] ?? $departmentId);
$lineage[$realDepartmentId] = [
'Id' => $realDepartmentId,
'parent_id' => (int) ($department['parent_id'] ?? 0),
'name' => trim((string) ($department['name'] ?? '')),
'depth' => $depth,
];
if (count($lineage) > 256) {
throw new RuntimeException('DingTalk department hierarchy is too large.');
}
$parentId = (int) ($department['parent_id'] ?? 0);
if ($parentId > 1 && ! isset($seen[$parentId])) {
$queue[] = [$parentId, $depth + 1];
}
}
return array_values($lineage);
}
public function appAccessToken(): string
{
if ($this->cachedAppAccessToken !== null) {
return $this->cachedAppAccessToken;
}
try {
$response = Http::acceptJson()
->timeout($this->timeout())
->get($this->configuredString('dingtalk.app_token_url'), [
'appkey' => $this->configuredString('dingtalk.client_id'),
'appsecret' => $this->configuredString('dingtalk.client_secret'),
])
->throw();
} catch (RequestException $exception) {
throw new RuntimeException('DingTalk application token lookup failed.', 0, $exception);
}
$token = trim((string) $response->json('access_token'));
if ((int) $response->json('errcode', -1) !== 0 || $token === '') {
throw new RuntimeException('DingTalk application token was unavailable.');
}
return $this->cachedAppAccessToken = $token;
}
protected function ensureConfigured(): void
{
if (! $this->isConfigured()) {
throw new RuntimeException('DingTalk login is not configured.');
}
}
protected function configuredString(string $key): string
{
return trim((string) config($key, ''));
}
protected function timeout(): int
{
return max(3, min(30, (int) config('dingtalk.timeout', 10)));
}
/** @return array<string,mixed> */
private function departmentDetail(int $departmentId): array
{
return Cache::remember(
'dingtalk:department:v1:' . $departmentId,
now()->addMinutes(max(
1,
(int) config('dingtalk.enterprise_user_cache_minutes', 10),
)),
function () use ($departmentId): array {
$appToken = $this->appAccessToken();
try {
$response = Http::asJson()
->acceptJson()
->timeout($this->timeout())
->withQueryParameters(['access_token' => $appToken])
->post(
$this->configuredString('dingtalk.department_detail_url'),
['dept_id' => $departmentId],
)
->throw();
} catch (RequestException $exception) {
throw new RuntimeException(
'DingTalk department detail lookup failed.',
0,
$exception,
);
}
$detail = $response->json('result');
if ((int) $response->json('errcode', -1) !== 0 || ! is_array($detail)) {
throw new RuntimeException('DingTalk department detail was unavailable.');
}
return $detail;
},
);
}
/** @return list<string> */
private function departmentIds(mixed $value): array
{
$parts = is_array($value) ? $value : preg_split(
'/[\[\]\/>,,;;||\s]+/u',
trim((string) $value),
-1,
PREG_SPLIT_NO_EMPTY,
);
return array_values(array_unique(array_filter(array_map(
static fn (mixed $id): string => is_scalar($id) ? trim((string) $id) : '',
is_array($parts) ? $parts : [],
), static fn (string $id): bool => ctype_digit($id) && (int) $id > 0)));
}
protected function nullableString(mixed $value): ?string
{
$value = trim((string) $value);
return $value === '' ? null : $value;
}
}