fix: 财务系统仅允许钉钉账号登录 (#1068)

登录页仅保留钉钉入口;停用密码、找回密码、重置密码和邀请注册登录;旧密码会话立即失效。
This commit is contained in:
chenxi 2026-11-11 11:02:49 +08:00
parent 0754045003
commit fcfc401eff
16 changed files with 296 additions and 251 deletions

View File

@ -54,6 +54,8 @@ bash deploy/local-init.sh
这个账号只存在于本机临时数据库中。系统数据库切换完成后,请使用系统数据库里属于自己的账号登录,不要继续把临时账号当作团队共享账号。
`local-init.sh` 会在本机 `runtime/.env` 写入 `AUTH_PASSWORD_LOGIN_ENABLED=true`,仅用于私有开发库和自动登录助手。代码默认关闭这一开关,并且配置层只允许 `APP_ENV=local` 时生效;正式环境始终只开放钉钉登录。已有开发机拉取本次代码后需重新执行一次 `bash deploy/local-init.sh`。
初始化中断后,Codex 直接重新执行 `bash deploy/local-init.sh`。脚本会根据 Dockerfile、依赖锁文件、前端源码和静态资源生成镜像指纹:输入未变化时复用镜像,发生变化或缺少必要静态资源时自动重建,并从数据库初始化阶段继续。`--build` 只用于强制重建;`--skip-build` 仅允许镜像指纹和静态资源均已通过校验时使用。
拉取新代码后再次运行该脚本时,本机临时引导库会自动更新;连接团队共享系统数据库后,这项自动更新会安全跳过。普通开发者任何时候都不需要执行 `php artisan migrate`,也不得对团队共享系统数据库自行迁移。

View File

@ -5,6 +5,7 @@ namespace App\Http\Controllers\Auth;
use App\Abstracts\Http\Controller;
use App\Http\Requests\Auth\Login as Request;
use App\Models\Common\Contact;
use App\Services\Auth\DingTalkOAuthClient;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
@ -13,11 +14,6 @@ class Login extends Controller
{
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = '/';
/**
@ -30,108 +26,79 @@ class Login extends Controller
$this->middleware('guest', ['except' => 'destroy']);
}
public function create()
public function create(DingTalkOAuthClient $client)
{
return view('auth.login.create');
return view('auth.login.create', [
'dingtalkAvailable' => $client->isConfigured(),
'passwordLoginEnabled' => (bool) config('auth.password_login_enabled', false),
]);
}
public function store(Request $request)
{
// Attempt to login
if (! auth()->attempt($request->only('email', 'password'), $request->get('remember', false))) {
if (! config('auth.password_login_enabled', false)) {
return $this->credentialsDisabled();
}
if (! auth()->attempt($request->only('email', 'password'), false)) {
return $this->respondLoginFailed();
}
// Get user object
$request->session()->forget(['dingtalk_identity_id', 'dingtalk_roster_checked_at']);
$user = user();
// Check if user is enabled
if (! $user->enabled) {
$this->logout();
// Security (CWE-204): avoid distinct error messages that would
// allow valid email enumeration. Log the real reason server-side
// for administrators/auditing without leaking it to the client.
Log::info('Login denied: account disabled', [
'email' => $request->email,
]);
Log::info('Local login denied: account disabled');
return $this->respondLoginFailed();
}
$company = $user->withoutEvents(function () use ($user) {
return $user->companies()->enabled()->first();
});
// Logout if no company assigned
$company = $user->withoutEvents(fn () => $user->companies()->enabled()->first());
if (! $company) {
$this->logout();
// Security (CWE-204): do not expose "no company" message to the
// client; log it server-side instead.
Log::info('Login denied: no company assigned', [
'email' => $request->email,
]);
Log::info('Local login denied: no company assigned');
return $this->respondLoginFailed();
}
// Redirect to portal if is customer
if ($user->isCustomer()) {
$path = session('url.intended', '');
$portalHome = $user->contact instanceof Contact
&& $user->contact->type === Contact::VENDOR_TYPE
? route('portal.supplier-reconciliation.index', ['company_id' => $company->id])
: route('portal.dashboard', ['company_id' => $company->id]);
// Path must start with company id and 'portal' prefix
if (!Str::startsWith($path, $company->id . '/portal')) {
$path = session('url.intended', '');
if (! Str::startsWith($path, $company->id.'/portal')) {
$path = $portalHome;
}
if (! $request->expectsJson()) {
return redirect()->to($path);
}
return $request->expectsJson()
? response()->json([
'status' => null,
'success' => true,
'error' => false,
'message' => trans('auth.login_redirect'),
'data' => null,
'redirect' => url($path),
])
: redirect()->to($path);
}
return response()->json([
$url = route($user->landing_page, ['company_id' => $company->id]);
$request->session()->forget('url.intended');
return $request->expectsJson()
? response()->json([
'status' => null,
'success' => true,
'error' => false,
'message' => trans('auth.login_redirect'),
'data' => null,
'redirect' => url($path),
]);
}
// Redirect to landing page if is user
$url = route($user->landing_page, ['company_id' => $company->id]);
// 登录后固定回到首页(财务驾驶舱),不再回跳上次打开/被拦截的业务页面。
$request->session()->forget('url.intended');
if (! $request->expectsJson()) {
return redirect()->to($url);
}
return response()->json([
'status' => null,
'success' => true,
'error' => false,
'message' => trans('auth.login_redirect'),
'data' => null,
'redirect' => url($url),
]);
'redirect' => url($url),
])
: redirect()->to($url);
}
/**
* Build the generic failed-login JSON response.
*
* Security (CWE-204): every rejected login returns the same message and
* response shape so an unauthenticated attacker cannot distinguish
* "email does not exist" from "disabled" or "no company" and enumerate
* valid registered email addresses.
*/
protected function respondLoginFailed()
{
$request = app('Illuminate\Http\Request');
@ -152,6 +119,16 @@ class Login extends Controller
]);
}
/**
* Credential-based entry points are intentionally kept as redirects so
* old bookmarks and invitation emails reach the DingTalk-only notice.
*/
public function credentialsDisabled()
{
return redirect()->route('login')
->with('dingtalk_error', trans('auth.dingtalk.credentials_disabled'));
}
public function destroy()
{
$this->logout();

View File

@ -7,6 +7,7 @@ use App\Services\Auth\DingTalkClosedAccess;
use App\Services\Auth\FinanceRoster;
use App\Services\Auth\SupplierPortalAccess;
use Closure;
use Illuminate\Support\Facades\Auth;
use Throwable;
class LogoutIfDingTalkBindingRevoked
@ -16,18 +17,16 @@ class LogoutIfDingTalkBindingRevoked
$identityId = $request->session()->get('dingtalk_identity_id');
$user = $request->user();
if (! $identityId) {
if (! $user || ! in_array($user->created_from, [
'dingtalk_roster',
'dingtalk_roster_limited',
SupplierPortalAccess::CREATED_FROM,
], true)) {
if (! $user) {
return $next($request);
}
// A password reset must not bypass HR eligibility for provisioned
// accounts. Apply the same boundary after every sign-in method.
$identityId = $user->dingtalkIdentity?->id;
$request->session()->put('dingtalk_identity_id', $identityId);
$request->session()->forget('dingtalk_roster_checked_at');
if (config('auth.password_login_enabled', false)) {
return $next($request);
}
// Every web session must originate from the DingTalk callback.
// Reject legacy or direct password sessions before serving data.
return $this->revoke($request, $user, null, 'dingtalk_login_required');
}
$identity = $user ? DingTalkIdentity::query()->whereKey($identityId)->where('user_id', $user->id)->first() : null;
@ -52,14 +51,25 @@ class LogoutIfDingTalkBindingRevoked
}
}
app(DingTalkClosedAccess::class)->audit('session_revoked', 'denied', $user?->id, null, $identity?->union_id, $request, [
'reason' => ! $user?->enabled
return $this->revoke(
$request,
$user,
$identity,
! $user?->enabled
? 'local_account_ineligible'
: (! $identity
? 'binding_revoked'
: (SupplierPortalAccess::isSupplierUser($user) ? 'outside_supplier_roster' : 'outside_finance_roster')),
: (SupplierPortalAccess::isSupplierUser($user) ? 'outside_supplier_roster' : 'outside_finance_roster'))
);
}
private function revoke($request, $user, ?DingTalkIdentity $identity, string $reason)
{
app(DingTalkClosedAccess::class)->audit('session_revoked', 'denied', $user?->id, null, $identity?->union_id, $request, [
'reason' => $reason,
]);
auth()->logout();
cookie()->queue(cookie()->forget(Auth::guard()->getRecallerName()));
$request->session()->invalidate();
$request->session()->regenerateToken();

View File

@ -18,6 +18,11 @@ return [
'passwords' => 'users',
],
// Production is DingTalk-only. Local bootstrap may explicitly opt in so
// local-init and the browser helper can reach the private dev database.
'password_login_enabled' => (bool) env('AUTH_PASSWORD_LOGIN_ENABLED', false)
&& env('APP_ENV', 'production') === 'local',
/*
|--------------------------------------------------------------------------
| Authentication Guards

View File

@ -159,12 +159,16 @@ QUEUE_CONNECTION=sync
SYSTEM_DATABASE_MODE=bootstrap
UPSTREAM_STORED_CONFIG_ENABLED=false
UPSTREAM_LOCAL_CONFIG_ENABLED=false
AUTH_PASSWORD_LOGIN_ENABLED=true
EOF
chmod 600 "$environment_file" 2>/dev/null || true
echo "==> 已生成本机私有 runtime/.env(不会提交到 Git)。"
fi
# 正式环境默认关闭密码登录;本机初始化只为本机引导库和浏览器助手显式开启。
set_env_value AUTH_PASSWORD_LOGIN_ENABLED true
image_exists=0
if docker image inspect "$app_image" >/dev/null 2>&1; then
image_exists=1

View File

@ -15,8 +15,12 @@
## 用户流程
财务系统网页只开放钉钉登录。登录页不再显示邮箱、账号密码、记住我或找回密码入口;旧密码登录、找回密码、重置密码和邀请注册地址只返回钉钉登录提示,不能建立会话。旧版本遗留的密码会话在访问业务页时会立即失效并要求重新钉钉登录。
首次钉钉授权成功后,系统用企业 `userid` 对应 HR 花名册中的 `flowerNameId`,核验人员状态和组织归属,自动创建普通用户、绑定钉钉身份并登录。不要求填写注册表、设置密码或等待账号绑定审批。
仅在本机私有开发环境运行 `deploy/local-init.sh` 时,脚本会显式写入 `AUTH_PASSWORD_LOGIN_ENABLED=true`,供本机引导库和自动登录助手使用;生产配置默认值为 `false`,不得开启。
准入组织为负责人确认的两棵子树:
- `22848291`:江苏简尚品牌管理有限公司 / 财务中心,包含财务部及其他下级部门。
@ -65,8 +69,10 @@
- OAuth state 同时绑定浏览器会话,并校验数据库中的过期和一次性消费状态。跨浏览器和重放均不能兑换授权码。
- 正式回调默认是 `APP_URL/auth/dingtalk/callback`。旧 IP 回调先跳回固定应用域名,再核验域名下的会话,不接受外部跳转目标。
- OAuth 响应采用 `no-store` 和 `no-referrer`。钉钉登录不签发长期 remember cookie,并清除浏览器中的旧 remember cookie。
- 所有网页业务会话必须带钉钉回调写入的身份标记;没有该标记的密码会话即使所属账号已启用也会被撤销,不能继续访问业务数据。
- 新钉钉会话每次请求核验账号启用状态和绑定记录。解绑或停用后,下一次请求失效;花名册离职或调离财务范围在下一次 5 分钟复核时失效。
- 自动开户账号即使改用密码登录,也须经过同样的花名册检查,不能通过密码重置绕过准入。
- 账号密码、忘记密码、重置密码和邀请注册均不能登录。钉钉登录未配置时页面只显示“联系管理员”,不会回退到密码或测试账号。
- 本机密码登录由独立的运行时开关控制,只在 `APP_ENV=local` 且明确开启时可用;它不是生产回退路径。
- 开户、登录拒绝、登录成功、解绑和会话失效有审计;不记录授权码、访问令牌、随机密码或完整 HR 响应。
## 配置与发布边界
@ -75,7 +81,7 @@
1. 发布已合并的 main,并重建应用配置缓存。
2. 将生产 `DINGTALK_REDIRECT_URI` 设置为 `https://caiwu.jiansuntuzhi.cn:8442/auth/dingtalk/callback`,核对钉钉开放平台对应应用的回调配置。2026-09-08 的只读检查确认生产 `APP_URL` 已是正式域名,但回调变量仍为旧 IP 地址;不能只改代码默认值就宣称生产已切换。
3. 首次切换须处理旧版已签发的会话与 remember 令牌。旧会话没有钉钉身份标记,不能可靠区分密码登录与钉钉登录;在备份后统一失效旧登录态会要求用户重新登录,须纳入生产授权。当前生产 session driver 为 `file`。回滚旧镜像无法恢复已失效的浏览器登录态。
3. 发布后,旧会话在首个业务请求时自动失效并要求重新钉钉登录,无需手工删除 session 文件;回滚旧镜像也无法恢复这些已失效的浏览器登录态。
4. `DINGTALK_COMPANY_ID` 不配置时只允许唯一启用公司;2026-09-08 只读检查确认生产仅公司 ID 1 启用。若新增公司,需明确配置自动开户的目标公司,不取任意第一条。
5. 两个财务根部门可通过 `DINGTALK_FINANCE_DEPARTMENT_IDS` 显式配置。扩大组织范围属于权限变更。
@ -90,3 +96,10 @@
- `0743f29` 已发布;生产 3 名花名册有效样本判断通过,原 11 个账号保留,10 个旧 remember 令牌已失效,使用新 session cookie 名隔离旧会话(旧会话文件保留于备份)。
- 真实扫码发现钉钉开放平台尚未登记域名回调,且当前平台登录账号没有开发者权限。已恢复旧 IP 回调配置;Nginx 必须先通过 302 跳回 HTTPS 域名,不能将旧 IP 请求伪装成域名请求交给 Laravel,否则无法取得浏览器会话。域名登记后再切换生产回调变量。
- 自动开户的真实扫码验收仍在进行,不能用只读样本或登录页跳转代替最终开户证据。
## 单一登录入口变更(2026-11-11)
- 登录页只保留钉钉入口,不再渲染邮箱、密码、记住我和找回密码控件。
- `POST /auth/login`、忘记密码、重置密码、邀请注册和旧注册链接均只跳回钉钉登录页,不会校验密码或签发会话。
- 网页中间件要求所有已登录业务会话必须来自钉钉回调;遗留密码会话会被撤销并清除 remember cookie。
- 钉钉配置缺失时只提示联系系统管理员,不回退到密码或测试账号。

View File

@ -49,9 +49,13 @@ return [
'disabled' => 'This account is disabled. Please, contact the system administrator.',
'dingtalk' => [
'title' => 'Finance system sign-in',
'only_method' => 'This system supports DingTalk sign-in only.',
'login' => 'Sign in with DingTalk',
'or' => 'or',
'unavailable' => 'DingTalk sign-in is not enabled. Please use email and password.',
'unavailable' => 'DingTalk sign-in is not configured. Please contact the system administrator.',
'no_password' => 'Password sign-in, password recovery and registration are disabled. If you cannot sign in with DingTalk, contact the finance system administrator.',
'credentials_disabled' => 'Password sign-in, password recovery and registration are disabled. Return to the sign-in page and use your DingTalk account.',
'failed' => 'DingTalk sign-in did not complete. Please start the authorization again.',
'denied' => 'This DingTalk account is not authorized for the finance system. Contact the system administrator.',
'pending' => 'Your DingTalk identity is verified. Account binding is awaiting administrator approval. Sign in again after approval.',

View File

@ -49,9 +49,13 @@ return [
'disabled' => '此账号已被停用。请联系系统管理员。',
'dingtalk' => [
'title' => '财务系统登录',
'only_method' => '本系统仅支持使用钉钉账号登录。',
'login' => '使用钉钉登录',
'or' => '或',
'unavailable' => '钉钉登录尚未启用,请暂时使用邮箱密码登录。',
'unavailable' => '钉钉登录尚未配置,请联系系统管理员。',
'no_password' => '系统已停用账号密码、找回密码和注册登录。如无法通过钉钉登录,请联系财务系统管理员。',
'credentials_disabled' => '账号密码、找回密码和注册登录均已停用,请返回登录页使用钉钉账号登录。',
'failed' => '钉钉登录未完成,请重新发起授权。',
'denied' => '当前钉钉账号未获财务系统授权,请联系系统管理员。',
'pending' => '钉钉身份已确认,账号绑定申请正在等待管理员审批。审批通过后请重新登录。',

View File

@ -7,95 +7,71 @@
<div>
<img src="{{ asset('public/img/akaunting-logo-gold.svg') }}" class="w-16" alt="Akaunting" />
<h1 class="text-lg my-3">
{{ trans('auth.login_to') }}
<h1 class="text-xl my-3 font-semibold text-black-700">
{{ trans('auth.dingtalk.title') }}
</h1>
<p class="text-sm leading-6 text-black-500">
{{ trans('auth.dingtalk.only_method') }}
</p>
</div>
<div :class="(form.response.success) ? 'w-full bg-green-100 text-green-600 p-3 rounded-sm font-semibold text-xs' : 'hidden'"
v-if="form.response.success"
v-html="form.response.message"
v-cloak
></div>
<div :class="(form.response.error) ? 'w-full bg-red-100 text-red-600 p-3 rounded-sm font-semibold text-xs' : 'hidden'"
v-if="form.response.error"
v-html="form.response.message"
v-cloak
></div>
@if (session('dingtalk_error'))
<div class="w-full border border-red-200 bg-red-50 text-red-700 p-3 rounded-lg font-semibold text-xs my-3">
<div class="w-full border border-red-200 bg-red-50 text-red-700 p-3 rounded-lg font-semibold text-xs my-3" role="alert">
{{ session('dingtalk_error') }}
</div>
@endif
<x-form id="auth" route="login">
<div class="grid sm:grid-cols-6 gap-x-8 gap-y-6 my-3.5 lg:h-64">
<x-form.group.email
name="email"
label="{{ trans('general.email') }}"
placeholder="{{ trans('general.email') }}"
form-group-class="sm:col-span-6"
input-group-class="input-group-alternative"
/>
<x-form.group.password
name="password"
label="{{ trans('auth.password.pass') }}"
placeholder="{{ trans('auth.password.pass') }}"
form-group-class="sm:col-span-6"
input-group-class="input-group-alternative"
/>
<div class="sm:col-span-6 flex flex-row justify-between items-center">
@stack('remember_input_start')
<div>
<x-form.input.checkbox
name="remember"
label="{{ trans('auth.remember_me') }}"
value="1"
v-model="form.remember"
id="checkbox-remember"
class="text-purple focus:outline-none focus:ring-purple focus:border-purple"
/>
</div>
@stack('remember_input_end')
@stack('forgotten-password-start')
<x-link href="{{ route('forgot') }}" class="text-black-400 hover:text-black-700 text-sm" override="class">
{{ trans('auth.forgot_password') }}
</x-link>
@stack('forgotten-password-end')
</div>
<x-button
type="submit"
::disabled="form.loading"
class="relative flex items-center justify-center bg-green hover:bg-green-700 text-white px-6 py-1.5 text-base rounded-lg disabled:bg-green-100 sm:col-span-6"
override="class"
>
<x-button.loading>
{{ trans('auth.login') }}
</x-button.loading>
</x-button>
</div>
</x-form>
@if (config('dingtalk.enabled') && config('dingtalk.client_id') && config('dingtalk.client_secret'))
<div class="flex items-center gap-3 my-5" aria-hidden="true">
<span class="h-px flex-1 bg-gray-200"></span>
<span class="text-xs text-gray-500">{{ trans('auth.dingtalk.or') }}</span>
<span class="h-px flex-1 bg-gray-200"></span>
</div>
@if ($dingtalkAvailable)
<a href="{{ route('login.dingtalk') }}"
class="w-full h-9 inline-flex items-center justify-center gap-2 border border-[#856632] bg-white text-[#856632] hover:bg-[#F7F0DE] focus:outline-none focus:ring-2 focus:ring-[#856632]/20 rounded-lg text-sm font-semibold"
class="w-full min-h-11 inline-flex items-center justify-center gap-2 border border-[#856632] bg-[#856632] text-white hover:bg-[#6A5129] focus:outline-none focus:ring-2 focus:ring-[#856632]/25 rounded-lg text-sm font-semibold"
>
<span class="material-icons-outlined text-base" aria-hidden="true">qr_code_scanner</span>
{{ trans('auth.dingtalk.login') }}
</a>
@else
<div class="w-full border border-amber-200 bg-amber-50 text-amber-800 p-3 rounded-lg text-xs" role="alert">
{{ trans('auth.dingtalk.unavailable') }}
</div>
@endif
@if ($passwordLoginEnabled)
<div class="flex items-center gap-3 my-3" aria-hidden="true">
<span class="h-px flex-1 bg-gray-200"></span>
<span class="text-xs text-gray-500">本机开发登录</span>
<span class="h-px flex-1 bg-gray-200"></span>
</div>
<x-form id="auth" route="login">
<div class="grid sm:grid-cols-6 gap-x-8 gap-y-4">
<x-form.group.email
name="email"
label="{{ trans('general.email') }}"
placeholder="{{ trans('general.email') }}"
form-group-class="sm:col-span-6"
input-group-class="input-group-alternative"
/>
<x-form.group.password
name="password"
label="{{ trans('auth.password.pass') }}"
placeholder="{{ trans('auth.password.pass') }}"
form-group-class="sm:col-span-6"
input-group-class="input-group-alternative"
/>
<x-button
type="submit"
::disabled="form.loading"
class="relative flex items-center justify-center bg-black hover:bg-black-700 text-white px-6 py-1.5 text-base rounded-lg disabled:bg-gray-300 sm:col-span-6"
override="class"
>
<x-button.loading>本机开发登录</x-button.loading>
</x-button>
</div>
</x-form>
@endif
<p class="text-xs leading-5 text-black-400">
{{ $passwordLoginEnabled ? '本机开发登录仅用于私有开发数据库;正式环境只允许钉钉登录。' : trans('auth.dingtalk.no_password') }}
</p>
</x-slot>
<x-script folder="auth" file="common" />

View File

@ -15,15 +15,14 @@ Route::group(['prefix' => 'auth'], function () {
Route::get('dingtalk', 'Auth\DingTalkLogin@redirect')->middleware('throttle:10,1')->name('login.dingtalk');
Route::get('dingtalk/callback', 'Auth\DingTalkLogin@callback')->middleware('throttle:20,1')->name('login.dingtalk.callback');
Route::get('forgot', 'Auth\Forgot@create')->name('forgot');
Route::post('forgot', 'Auth\Forgot@store')->name('forgot.store');
Route::get('forgot', 'Auth\Login@credentialsDisabled')->name('forgot');
Route::post('forgot', 'Auth\Login@credentialsDisabled')->name('forgot.store');
//Route::get('reset', 'Auth\Reset@create');
Route::get('reset/{token}', 'Auth\Reset@create')->name('reset');
Route::post('reset', 'Auth\Reset@store')->name('reset.store');
Route::get('reset/{token}', 'Auth\Login@credentialsDisabled')->name('reset');
Route::post('reset', 'Auth\Login@credentialsDisabled')->name('reset.store');
Route::get('register/{token}', 'Auth\Register@create')->name('register');
Route::post('register', 'Auth\Register@store')->name('register.store');
Route::get('register/{token}', 'Auth\Login@credentialsDisabled')->name('register');
Route::post('register', 'Auth\Login@credentialsDisabled')->name('register.store');
});
Route::get('/', function () {

View File

@ -48,15 +48,64 @@ class DingTalkLoginTest extends FeatureTestCase
$this->mock(SupplierPortalAccess::class)->shouldReceive('resolveAll')->andReturn([])->byDefault();
}
public function test_login_page_shows_dingtalk_entry_without_password_binding_fields(): void
public function test_login_page_only_shows_the_dingtalk_entry(): void
{
$this->get(route('login'))
->assertOk()
->assertSeeText(trans('auth.dingtalk.title'))
->assertSeeText(trans('auth.dingtalk.only_method'))
->assertSeeText(trans('auth.dingtalk.login'))
->assertSeeText(trans('auth.dingtalk.no_password'))
->assertDontSee('name="email"', false)
->assertDontSee('name="password"', false)
->assertDontSee('name="remember"', false)
->assertDontSeeText(trans('auth.forgot_password'))
->assertDontSee('name="dingtalk_binding"', false)
->assertDontSeeText('首次使用钉钉登录,请输入现有财务系统账号和密码完成绑定');
}
public function test_legacy_password_and_account_recovery_entry_points_cannot_sign_in(): void
{
$this->post(route('login'), [
'email' => $this->user->email,
'password' => 'password',
])->assertRedirect(route('login'))
->assertSessionHas('dingtalk_error', trans('auth.dingtalk.credentials_disabled'));
$this->assertGuest();
$this->withHeaders(['Accept' => 'application/json'])
->post(route('login'), [
'email' => $this->user->email,
'password' => 'password',
])->assertRedirect(route('login'));
$this->assertGuest();
$this->get(route('forgot'))
->assertRedirect(route('login'));
$this->post(route('forgot.store'))
->assertRedirect(route('login'));
$this->get(route('reset', ['token' => 'legacy-token']))
->assertRedirect(route('login'));
$this->post(route('reset.store'))
->assertRedirect(route('login'));
$this->get(route('register', ['token' => 'legacy-token']))
->assertRedirect(route('login'));
$this->post(route('register.store'))
->assertRedirect(route('login'));
$this->assertGuest();
}
public function test_unconfigured_dingtalk_never_falls_back_to_password_login(): void
{
config(['dingtalk.enabled' => false]);
$this->get(route('login'))
->assertOk()
->assertSeeText(trans('auth.dingtalk.unavailable'))
->assertDontSeeText(trans('auth.dingtalk.login'))
->assertDontSee('name="password"', false);
}
public function test_redirect_creates_hashed_state_and_uses_domain_callback(): void
{
$response = $this->get(route('login.dingtalk'))->assertRedirect();
@ -699,6 +748,21 @@ class DingTalkLoginTest extends FeatureTestCase
$this->assertGuest();
}
public function test_legacy_password_session_is_rejected_even_for_an_unbound_account(): void
{
$this->actingAs($this->user)
->getJson(route('dashboard', ['company_id' => $this->company->id]))
->assertUnauthorized();
$this->assertGuest();
$this->assertDatabaseHas('dingtalk_auth_audits', [
'event' => 'session_revoked',
'outcome' => 'denied',
'user_id' => $this->user->id,
'metadata->reason' => 'dingtalk_login_required',
]);
}
public function test_roster_outage_during_session_recheck_serves_no_business_data(): void
{
$identity = DingTalkIdentity::create(['user_id' => $this->user->id, 'union_id' => 'union-recheck', 'dingtalk_user_id' => 'ding-recheck']);
@ -719,7 +783,7 @@ class DingTalkLoginTest extends FeatureTestCase
$created = auth()->user();
$this->assertNull(SidebarPermissions::allowedKeys($created));
auth()->logout(); session()->invalidate();
$this->actingAs($this->user)->get(route('system-settings.sidebar.edit', ['subject' => 'user_'.$created->id]))
$this->loginAs($this->user)->get(route('system-settings.sidebar.edit', ['subject' => 'user_'.$created->id]))
->assertOk()->assertSee('value="user_'.$created->id.'"', false);
$this->patch(route('system-settings.sidebar.update'), [
'subject' => 'user_'.$created->id, 'permissions' => ['store-management/basic-information'],

View File

@ -120,10 +120,10 @@ class UsersTest extends FeatureTestCase
{
$this->get(route('login'))
->assertOk()
->assertSeeText(trans('auth.login_to'));
->assertSeeText(trans('auth.dingtalk.only_method'));
}
public function testItShouldLoginUser()
public function testItShouldRejectPasswordLogin()
{
$request = $this->getRequest();
@ -131,55 +131,37 @@ class UsersTest extends FeatureTestCase
$this->withHeaders(['X-Requested-With' => 'XMLHttpRequest', 'Accept' => 'application/json'])
->post(route('login'), ['email' => $user->email, 'password' => $user->password])
->assertOk();
->assertRedirect(route('login'));
$this->isAuthenticated($user->user);
$this->assertGuest();
}
public function testItShouldRedirectNativeLogin()
public function testItShouldRejectNativePasswordLogin()
{
$request = $this->getRequest();
$user = $this->dispatch(new CreateUser($request));
$this->post(route('login'), ['email' => $user->email, 'password' => $user->password])
->assertRedirect();
$this->isAuthenticated($user->user);
}
public function testItShouldLandOnTheHomePageAfterLoginInsteadOfTheLastOpenedBusinessPage()
{
// 未登录访问业务页面时,框架会记录 intended;登录后不应该再回跳到该页面。
$this->withExceptionHandling()->get(route('business.pages.show', [
'company_id' => $this->company->id,
'section' => 'courier-payables',
'page' => 'freight-reconciliation',
]));
$response = $this->post(route('login'), [
'email' => $this->user->email,
'password' => '123456',
]);
$response->assertRedirect();
$this->assertTrue(auth()->check());
$this->assertStringNotContainsString('/workspace/', (string) $response->headers->get('Location'));
}
public function testItShouldNotLoginUser()
{
$request = $this->getRequest();
$user = $this->dispatch(new CreateUser($request));
$this->withHeaders(['X-Requested-With' => 'XMLHttpRequest', 'Accept' => 'application/json'])
->post(route('login'), ['email' => $user->email, 'password' => $this->faker->password()])
->assertOk();
->assertRedirect(route('login'));
$this->assertGuest();
}
public function testItShouldAllowTheExplicitLocalDevelopmentPasswordLogin()
{
config(['auth.password_login_enabled' => true]);
$request = $this->getRequest();
$user = $this->dispatch(new CreateUser($request));
$this->post(route('login'), [
'email' => $user->email,
'password' => $request['password'],
])->assertRedirect();
$this->isAuthenticated($user->user);
}
public function testItShouldLogoutUser()
{
$request = $this->getRequest();
@ -194,28 +176,19 @@ class UsersTest extends FeatureTestCase
$this->assertGuest();
}
public function testItShouldSeeRegisterPage()
public function testItShouldRedirectInvitationRegistrationToDingTalkLogin()
{
$request = $this->getRequest();
$user = $this->dispatch(new CreateUser($request));
$this->get(route('register', ['token' => $user->invitation->token]))
->assertOk();
->assertRedirect(route('login'));
$this->assertGuest();
}
public function testItShouldNotSeeRegisterPage()
{
$this->withExceptionHandling()
->get(route('register', ['token' => $this->faker->uuid]))
->assertForbidden();
$this->assertGuest();
}
public function testItShouldRegisterUser()
public function testItShouldRejectInvitationRegistration()
{
$request = $this->getRequest();
@ -230,32 +203,9 @@ class UsersTest extends FeatureTestCase
];
$this->post(route('register.store'), $data)
->assertOk()
->assertJson([
'redirect' => url('/'),
]);
$this->assertFlashLevel('success');
$this->assertSoftDeleted('user_invitations', ['user_id' => $user->id]);
$this->isAuthenticated($user->user);
}
public function testItShouldNotRegisterUser()
{
$password = $this->faker->password;
$data = [
'token' => $this->faker->uuid,
'password' => $password,
'password_confirmation' => $password,
];
$this->withExceptionHandling()
->post(route('register.store'), $data)
->assertForbidden();
->assertRedirect(route('login'));
$this->assertDatabaseHas('user_invitations', ['user_id' => $user->id]);
$this->assertGuest();
}

View File

@ -1169,7 +1169,8 @@ class SupplierReconciliationTest extends FeatureTestCase
'email' => $vendor->email,
'password' => 'portal-password',
])
->assertRedirect($portalUrl);
->assertRedirect(route('login'));
$this->assertGuest();
$this->loginAs($vendor)->get($portalUrl)
->assertOk()

View File

@ -2,8 +2,10 @@
namespace Tests\Feature;
use App\Models\Auth\DingTalkIdentity;
use App\Models\Common\Company;
use Faker\Factory as Faker;
use Illuminate\Support\Str;
use Tests\TestCase;
abstract class FeatureTestCase extends TestCase
@ -47,7 +49,20 @@ abstract class FeatureTestCase extends TestCase
app('url')->defaults(['company_id' => company_id()]);
return $this->actingAs($user);
$identity = DingTalkIdentity::query()->firstOrCreate(
['user_id' => $user->id],
[
'union_id' => 'test-session-'.Str::random(16),
'dingtalk_user_id' => 'test-ding-user-'.$user->id,
]
);
$this->actingAs($user);
return $this->withSession([
'dingtalk_identity_id' => $identity->id,
'dingtalk_roster_checked_at' => now()->timestamp,
]);
}
public function assertFlashLevel($excepted)

View File

@ -2,6 +2,7 @@
namespace Tests\Feature\Installation;
use App\Models\Auth\DingTalkIdentity;
use App\Utilities\Installer;
use Database\Seeds\Permissions;
use Illuminate\Foundation\Testing\RefreshDatabase;
@ -39,6 +40,11 @@ class BootstrapInstallationTest extends BaseTestCase
);
$user = user_model_class()::where('email', 'local-bootstrap@caiwu.test')->firstOrFail();
$identity = DingTalkIdentity::query()->create([
'user_id' => $user->id,
'union_id' => 'install-bootstrap-dingtalk-identity',
'dingtalk_user_id' => 'install-bootstrap-user',
]);
$role = $user->roles()->where('name', 'super_admin')->firstOrFail();
$this->assertTrue($role->hasPermission('read-admin-panel'));
@ -68,7 +74,10 @@ class BootstrapInstallationTest extends BaseTestCase
route('dashboard'),
route('system-settings.databases.index'),
] as $url) {
$response = $this->actingAs($user)->get($url);
$response = $this->actingAs($user)->withSession([
'dingtalk_identity_id' => $identity->id,
'dingtalk_roster_checked_at' => now()->timestamp,
])->get($url);
$this->assertNotSame(
403,

View File

@ -14,6 +14,18 @@ class DingTalkBindingsTest extends FeatureTestCase
public function test_super_admin_can_review_masked_pending_requests_and_bind_existing_user(): void
{
$bindingRequest = $this->pendingRequest();
$target = User::query()->create([
'name' => '待绑定用户',
'email' => 'pending-binding-target@example.test',
'password' => 'KnownPassword123!',
'locale' => 'zh-CN',
'enabled' => true,
'landing_page' => 'dashboard',
'created_by' => $this->user->id,
'created_from' => 'system_settings',
]);
$target->roles()->attach(Role::where('name', SystemAccess::USER)->firstOrFail()->id);
$target->companies()->attach($this->company->id);
$this->loginAs()
->get(route('system-settings.dingtalk-bindings.index'))
@ -25,24 +37,24 @@ class DingTalkBindingsTest extends FeatureTestCase
->assertDontSee('13800138000');
$this->post(route('system-settings.dingtalk-bindings.approve', $bindingRequest->id), [
'user_id' => $this->user->id,
'user_id' => $target->id,
])->assertRedirect(route('system-settings.dingtalk-bindings.index'));
$this->assertDatabaseHas('dingtalk_identities', [
'user_id' => $this->user->id,
'user_id' => $target->id,
'union_id' => 'union-pending-admin',
'bound_by' => $this->user->id,
]);
$this->assertDatabaseHas('dingtalk_binding_requests', [
'id' => $bindingRequest->id,
'status' => DingTalkBindingRequest::APPROVED,
'matched_user_id' => $this->user->id,
'matched_user_id' => $target->id,
'reviewed_by' => $this->user->id,
]);
$this->assertDatabaseHas('dingtalk_auth_audits', [
'event' => 'binding_admin_approved',
'outcome' => 'success',
'user_id' => $this->user->id,
'user_id' => $target->id,
'actor_user_id' => $this->user->id,
]);
}