diff --git a/LOCAL_DEPLOY.md b/LOCAL_DEPLOY.md index ebb3b632..d8b2d776 100644 --- a/LOCAL_DEPLOY.md +++ b/LOCAL_DEPLOY.md @@ -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`,也不得对团队共享系统数据库自行迁移。 diff --git a/app/Http/Controllers/Auth/Login.php b/app/Http/Controllers/Auth/Login.php index fcbae1c5..e77d3516 100644 --- a/app/Http/Controllers/Auth/Login.php +++ b/app/Http/Controllers/Auth/Login.php @@ -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(); diff --git a/app/Http/Middleware/LogoutIfDingTalkBindingRevoked.php b/app/Http/Middleware/LogoutIfDingTalkBindingRevoked.php index 6cced738..258bf0cc 100644 --- a/app/Http/Middleware/LogoutIfDingTalkBindingRevoked.php +++ b/app/Http/Middleware/LogoutIfDingTalkBindingRevoked.php @@ -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(); diff --git a/config/auth.php b/config/auth.php index e2599d74..c4b9d5db 100644 --- a/config/auth.php +++ b/config/auth.php @@ -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 diff --git a/deploy/local-init.sh b/deploy/local-init.sh index a6f9d3e2..b0ba8be8 100644 --- a/deploy/local-init.sh +++ b/deploy/local-init.sh @@ -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 diff --git a/docs/钉钉花名册登录.md b/docs/钉钉花名册登录.md index f013cec2..61044b18 100644 --- a/docs/钉钉花名册登录.md +++ b/docs/钉钉花名册登录.md @@ -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。 +- 钉钉配置缺失时只提示联系系统管理员,不回退到密码或测试账号。 diff --git a/resources/lang/en-GB/auth.php b/resources/lang/en-GB/auth.php index c87b501a..79b0da2c 100644 --- a/resources/lang/en-GB/auth.php +++ b/resources/lang/en-GB/auth.php @@ -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.', diff --git a/resources/lang/zh-CN/auth.php b/resources/lang/zh-CN/auth.php index a06a5cbd..2d4c65aa 100644 --- a/resources/lang/zh-CN/auth.php +++ b/resources/lang/zh-CN/auth.php @@ -49,9 +49,13 @@ return [ 'disabled' => '此账号已被停用。请联系系统管理员。', 'dingtalk' => [ + 'title' => '财务系统登录', + 'only_method' => '本系统仅支持使用钉钉账号登录。', 'login' => '使用钉钉登录', 'or' => '或', - 'unavailable' => '钉钉登录尚未启用,请暂时使用邮箱密码登录。', + 'unavailable' => '钉钉登录尚未配置,请联系系统管理员。', + 'no_password' => '系统已停用账号密码、找回密码和注册登录。如无法通过钉钉登录,请联系财务系统管理员。', + 'credentials_disabled' => '账号密码、找回密码和注册登录均已停用,请返回登录页使用钉钉账号登录。', 'failed' => '钉钉登录未完成,请重新发起授权。', 'denied' => '当前钉钉账号未获财务系统授权,请联系系统管理员。', 'pending' => '钉钉身份已确认,账号绑定申请正在等待管理员审批。审批通过后请重新登录。', diff --git a/resources/views/auth/login/create.blade.php b/resources/views/auth/login/create.blade.php index 1855c21d..17fe6204 100644 --- a/resources/views/auth/login/create.blade.php +++ b/resources/views/auth/login/create.blade.php @@ -7,95 +7,71 @@
Akaunting -

- {{ trans('auth.login_to') }} +

+ {{ trans('auth.dingtalk.title') }}

+

+ {{ trans('auth.dingtalk.only_method') }} +

-
- -
- @if (session('dingtalk_error')) -
+ @endif - -
- - - - -
- @stack('remember_input_start') -
- -
- @stack('remember_input_end') - - @stack('forgotten-password-start') - - {{ trans('auth.forgot_password') }} - - @stack('forgotten-password-end') -
- - - - {{ trans('auth.login') }} - - -
-
- - @if (config('dingtalk.enabled') && config('dingtalk.client_id') && config('dingtalk.client_secret')) - - + @if ($dingtalkAvailable) {{ trans('auth.dingtalk.login') }} + @else + @endif + + @if ($passwordLoginEnabled) + + + +
+ + + + 本机开发登录 + +
+
+ @endif + +

+ {{ $passwordLoginEnabled ? '本机开发登录仅用于私有开发数据库;正式环境只允许钉钉登录。' : trans('auth.dingtalk.no_password') }} +

diff --git a/routes/guest.php b/routes/guest.php index 064d3a06..8dc78b18 100644 --- a/routes/guest.php +++ b/routes/guest.php @@ -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 () { diff --git a/tests/Feature/Auth/DingTalkLoginTest.php b/tests/Feature/Auth/DingTalkLoginTest.php index 781dd9d9..81775ed5 100644 --- a/tests/Feature/Auth/DingTalkLoginTest.php +++ b/tests/Feature/Auth/DingTalkLoginTest.php @@ -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'], diff --git a/tests/Feature/Auth/UsersTest.php b/tests/Feature/Auth/UsersTest.php index 6a878da6..9e6b9ee2 100644 --- a/tests/Feature/Auth/UsersTest.php +++ b/tests/Feature/Auth/UsersTest.php @@ -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(); } diff --git a/tests/Feature/Business/SupplierReconciliationTest.php b/tests/Feature/Business/SupplierReconciliationTest.php index 6e2db9f7..4876232f 100644 --- a/tests/Feature/Business/SupplierReconciliationTest.php +++ b/tests/Feature/Business/SupplierReconciliationTest.php @@ -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() diff --git a/tests/Feature/FeatureTestCase.php b/tests/Feature/FeatureTestCase.php index 329d3164..b096a1ba 100644 --- a/tests/Feature/FeatureTestCase.php +++ b/tests/Feature/FeatureTestCase.php @@ -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) diff --git a/tests/Feature/Installation/BootstrapInstallationTest.php b/tests/Feature/Installation/BootstrapInstallationTest.php index 98ae368e..32a59f26 100644 --- a/tests/Feature/Installation/BootstrapInstallationTest.php +++ b/tests/Feature/Installation/BootstrapInstallationTest.php @@ -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, diff --git a/tests/Feature/SystemSettings/DingTalkBindingsTest.php b/tests/Feature/SystemSettings/DingTalkBindingsTest.php index e83637d2..31f81da2 100644 --- a/tests/Feature/SystemSettings/DingTalkBindingsTest.php +++ b/tests/Feature/SystemSettings/DingTalkBindingsTest.php @@ -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, ]); }