对接 https://gateway.gztbyc.com:二维码与「扫码确认」由网关提供,本服务只负责 申请临时码 → 验签收通知 → 落地自己的业务。 - 新增 service/wx_gateway.js + controller/gateway/notify.js(POST /api/wechat-gateway/notify,验签 401 / 会话过期 200 ignored) - 新增 controller/web/wx_gateway.js(登录二维码 / 长轮询 / SVG+GIF / 个人中心绑定与解绑) - 新表 wechat_gateway_bindings(uk(app_key, openid)):一个微信只绑一个账号,解绑是软删, 再绑定走 restore 复用(否则会撞唯一键报 Validation error) - 「这个微信已绑别的账号」策略:原账号正常 → 拒绝并提示对方账号名;原账号禁用/已删 → 直接改绑; 拿不到原账号 → 运维接口 GET/DELETE /api/internal/wechat-bindings 强制解绑 - 主体成员改为「扫码绑定」:管理员出二维码 → 成员微信扫码 → 已有账号直接继承(自动建的临时账号删掉), 没有账号则由服务端建号并绑成其登录方式;subject_members.temp_user_id 记录临时账号 - 废弃自建登录码:删除 GET /api/wechat/login(6 位串码)与 workstations.login_code(迁移 20261028121000), 工作台改扫码登入,成员绑定码与 /wechat?bind= 手机确认页下线 - 前端:登录页/个人中心/主体成员/工作台全部切到网关;桌面端登录窗改网关二维码 + 长轮询 - 测试:wx-gateway.test.js 覆盖登录/绑定/解绑-再绑/禁用账号改绑/运维强制解绑/成员绑定/工作台登入 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
378 lines
12 KiB
C#
378 lines
12 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using System.IO;
|
||
using System.Threading;
|
||
using System.Threading.Tasks;
|
||
using System.Windows;
|
||
using System.Windows.Input;
|
||
using System.Windows.Media.Imaging;
|
||
using YuncangTrace.LocalService.Services;
|
||
|
||
namespace YuncangTrace.LocalService;
|
||
|
||
/// <summary>
|
||
/// 登录窗
|
||
///
|
||
/// - 账号密码登录:`POST /api/web/auth/login` 拿 user JWT(顺带下发主体列表);
|
||
/// - **微信扫码登录**:`POST /api/web/auth/wechat-gateway/qrcode` 申请二维码(微信登录网关)→
|
||
/// 显示二维码(GIF,WPF 可直接显示)→ 长轮询
|
||
/// `GET /api/web/auth/wechat-gateway/login?state=&wait=25`,手机微信确认后直接拿到令牌;
|
||
/// - 本地已有令牌时,先调 `GET /api/web/me` 验证,还有效就直接跳过登录(窗口一闪而过);
|
||
/// - 成功后把令牌存到 `%LOCALAPPDATA%\YuncangTrace\session.json`。
|
||
/// </summary>
|
||
public partial class LoginWindow : Window
|
||
{
|
||
private readonly AppSettings _settings;
|
||
private readonly Session? _saved;
|
||
private bool _busy;
|
||
|
||
/// <summary>微信扫码的长轮询取消源(离开扫码面板 / 关窗口时取消)</summary>
|
||
private CancellationTokenSource? _wechatCts;
|
||
|
||
/// <summary>登录成功后的会话(ShowDialog 返回 true 时可用)</summary>
|
||
public Session? Session { get; private set; }
|
||
|
||
/// <summary>登录用户</summary>
|
||
public ApiUser? User { get; private set; }
|
||
|
||
/// <summary>登录时后端下发的主体列表</summary>
|
||
public IReadOnlyList<ApiSubject> Subjects { get; private set; } = Array.Empty<ApiSubject>();
|
||
|
||
public LoginWindow(AppSettings settings, Session? saved)
|
||
{
|
||
InitializeComponent();
|
||
|
||
_settings = settings;
|
||
_saved = saved;
|
||
|
||
AccountBox.Text = settings.LastAccount;
|
||
RememberBox.IsChecked = settings.RememberAccount;
|
||
|
||
Loaded += OnLoaded;
|
||
Closed += (_, _) => StopWechatPolling();
|
||
}
|
||
|
||
private async void OnLoaded(object sender, RoutedEventArgs e)
|
||
{
|
||
if (_saved is null)
|
||
{
|
||
AccountBox.Focus();
|
||
return;
|
||
}
|
||
|
||
await ResumeAsync();
|
||
}
|
||
|
||
/// <summary>本地有令牌:问一下服务端还在不在,有效就直接进主界面</summary>
|
||
private async Task ResumeAsync()
|
||
{
|
||
SetBusy(true, "正在恢复登录…");
|
||
|
||
try
|
||
{
|
||
var api = new ApiClient(_saved!.ServerBaseUrl);
|
||
var me = await api.MeAsync(_saved.Token);
|
||
|
||
if (me is null)
|
||
{
|
||
AppLog.Write("本地登录态已失效,请重新登录");
|
||
SessionStore.Clear();
|
||
SetBusy(false);
|
||
AccountBox.Focus();
|
||
return;
|
||
}
|
||
|
||
Session = _saved;
|
||
User = me;
|
||
Subjects = await LoadSubjectsSafeAsync(api, _saved.Token);
|
||
AppLog.Write($"已恢复登录:{me.DisplayName}(主体 {Subjects.Count} 个)");
|
||
DialogResult = true;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
AppLog.Write($"恢复登录失败:{ex.Message}");
|
||
SetBusy(false);
|
||
ShowError($"恢复登录失败:{ex.Message}");
|
||
}
|
||
}
|
||
|
||
// ---------------- 账号密码登录 ----------------
|
||
|
||
private void Login_Click(object sender, RoutedEventArgs e) => _ = DoLoginAsync();
|
||
|
||
private void PasswordBox_KeyDown(object sender, KeyEventArgs e)
|
||
{
|
||
if (e.Key == Key.Enter) _ = DoLoginAsync();
|
||
}
|
||
|
||
private async Task DoLoginAsync()
|
||
{
|
||
if (_busy) return;
|
||
|
||
// 服务地址是内部实现(构建时注入的默认值 / 启动参数 --server 覆盖),不在界面上暴露
|
||
var server = AppSettings.Normalize(_settings.ServerBaseUrl);
|
||
var account = AccountBox.Text.Trim();
|
||
var password = PasswordBox.Password;
|
||
|
||
if (account.Length == 0)
|
||
{
|
||
ShowError("请填写账号");
|
||
AccountBox.Focus();
|
||
return;
|
||
}
|
||
if (password.Length == 0)
|
||
{
|
||
ShowError("请填写密码");
|
||
PasswordBox.Focus();
|
||
return;
|
||
}
|
||
|
||
ClearError();
|
||
SetBusy(true, "正在登录…");
|
||
|
||
try
|
||
{
|
||
var api = new ApiClient(server);
|
||
var result = await api.LoginAsync(account, password);
|
||
|
||
result.Session.DisplayName = result.User.DisplayName;
|
||
SessionStore.Save(result.Session);
|
||
|
||
_settings.ServerBaseUrl = server;
|
||
_settings.RememberAccount = RememberBox.IsChecked == true;
|
||
_settings.LastAccount = _settings.RememberAccount ? account : string.Empty;
|
||
_settings.Save();
|
||
|
||
Session = result.Session;
|
||
User = result.User;
|
||
Subjects = result.Subjects;
|
||
|
||
AppLog.Write($"登录成功:{result.User.DisplayName}({server},主体 {Subjects.Count} 个)");
|
||
DialogResult = true;
|
||
}
|
||
catch (ApiException ex)
|
||
{
|
||
ShowError(ex.Message);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
ShowError($"登录失败:{ex.Message}");
|
||
}
|
||
finally
|
||
{
|
||
SetBusy(false);
|
||
}
|
||
}
|
||
|
||
// ---------------- 微信扫码登录 ----------------
|
||
|
||
private void Wechat_Click(object sender, RoutedEventArgs e) => _ = EnterWechatAsync();
|
||
|
||
private void WechatRefresh_Click(object sender, RoutedEventArgs e) => _ = StartWechatTicketAsync();
|
||
|
||
private void Back_Click(object sender, RoutedEventArgs e)
|
||
{
|
||
StopWechatPolling();
|
||
WechatPanel.Visibility = Visibility.Collapsed;
|
||
AccountPanel.Visibility = Visibility.Visible;
|
||
ClearError();
|
||
AccountBox.Focus();
|
||
}
|
||
|
||
private async Task EnterWechatAsync()
|
||
{
|
||
ClearError();
|
||
AccountPanel.Visibility = Visibility.Collapsed;
|
||
WechatPanel.Visibility = Visibility.Visible;
|
||
await StartWechatTicketAsync();
|
||
}
|
||
|
||
private async Task StartWechatTicketAsync()
|
||
{
|
||
StopWechatPolling();
|
||
var cts = new CancellationTokenSource();
|
||
_wechatCts = cts;
|
||
|
||
QrImage.Source = null;
|
||
QrPlaceholder.Visibility = Visibility.Visible;
|
||
QrPlaceholder.Text = "正在生成二维码…";
|
||
QrTip.Text = "请用手机扫码,确认后自动登录";
|
||
|
||
try
|
||
{
|
||
var api = new ApiClient(AppSettings.Normalize(_settings.ServerBaseUrl));
|
||
var ticket = await api.StartWechatLoginAsync(cts.Token);
|
||
|
||
// WPF 不能渲染 SVG,这里拿同一张二维码的 GIF(内容是网关下发的授权页地址)
|
||
var bytes = await api.GetImageAsync(
|
||
$"/api/wechat-gateway/qrcode.gif?state={Uri.EscapeDataString(ticket.State)}", cts.Token);
|
||
|
||
QrImage.Source = ToBitmap(bytes);
|
||
QrPlaceholder.Visibility = Visibility.Collapsed;
|
||
QrTip.Text = "请用手机微信扫码,确认后自动登录";
|
||
|
||
AppLog.Write($"[wechat] 已生成登录二维码:{ticket.State}");
|
||
_ = PollWechatAsync(api, ticket.State, cts.Token);
|
||
}
|
||
catch (OperationCanceledException)
|
||
{
|
||
// 切回账号登录,忽略
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
QrPlaceholder.Text = "二维码生成失败";
|
||
ShowError($"微信登录不可用:{ex.Message}");
|
||
AppLog.Write($"[wechat] 生成二维码失败:{ex.Message}");
|
||
}
|
||
}
|
||
|
||
/// <summary>长轮询:确认了就登录;二维码过期(expired)就换一张继续等</summary>
|
||
private async Task PollWechatAsync(ApiClient api, string state, CancellationToken ct)
|
||
{
|
||
var current = state;
|
||
|
||
while (!ct.IsCancellationRequested)
|
||
{
|
||
try
|
||
{
|
||
var result = await api.PollWechatLoginAsync(current, 25, ct);
|
||
|
||
if (result.Status == "confirmed" && result.Session is not null)
|
||
{
|
||
var session = result.Session;
|
||
session.DisplayName = result.User?.DisplayName ?? session.DisplayName;
|
||
SessionStore.Save(session);
|
||
|
||
_settings.ServerBaseUrl = api.BaseUrl;
|
||
_settings.Save();
|
||
|
||
Session = session;
|
||
User = result.User;
|
||
Subjects = await LoadSubjectsSafeAsync(api, session.Token);
|
||
|
||
AppLog.Write($"[wechat] 扫码登录成功:{session.DisplayName}(主体 {Subjects.Count} 个)");
|
||
|
||
if (!ct.IsCancellationRequested) DialogResult = true;
|
||
return;
|
||
}
|
||
|
||
if (result.Status == "failed")
|
||
{
|
||
// 微信没绑定平台账号等:服务端给了原因,直接告诉用户
|
||
QrTip.Text = result.Message ?? "扫码失败,请重试";
|
||
return;
|
||
}
|
||
|
||
if (result.Status == "expired")
|
||
{
|
||
// 二维码是一次性的:过期就重新申请一张(会话也换成新的)
|
||
try
|
||
{
|
||
var next = await api.StartWechatLoginAsync(ct);
|
||
current = next.State;
|
||
var bytes = await api.GetImageAsync(
|
||
$"/api/wechat-gateway/qrcode.gif?state={Uri.EscapeDataString(current)}", ct);
|
||
QrImage.Source = ToBitmap(bytes);
|
||
QrTip.Text = "二维码已刷新,请重新扫码";
|
||
}
|
||
catch
|
||
{
|
||
QrTip.Text = "二维码刷新失败,可点「刷新二维码」重试";
|
||
}
|
||
}
|
||
}
|
||
catch (OperationCanceledException)
|
||
{
|
||
return;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
QrTip.Text = $"连接中断,正在重试…({ex.Message})";
|
||
try
|
||
{
|
||
await Task.Delay(1200, ct);
|
||
}
|
||
catch (OperationCanceledException)
|
||
{
|
||
return;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
private void StopWechatPolling()
|
||
{
|
||
try
|
||
{
|
||
_wechatCts?.Cancel();
|
||
}
|
||
catch
|
||
{
|
||
// 忽略
|
||
}
|
||
_wechatCts = null;
|
||
}
|
||
|
||
/// <summary>拿主体列表;失败不阻塞登录(主界面里还能再拉)</summary>
|
||
private static async Task<IReadOnlyList<ApiSubject>> LoadSubjectsSafeAsync(ApiClient api, string token)
|
||
{
|
||
try
|
||
{
|
||
return await api.SubjectsAsync(token);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
AppLog.Write($"读取主体列表失败:{ex.Message}");
|
||
return Array.Empty<ApiSubject>();
|
||
}
|
||
}
|
||
|
||
private static BitmapImage? ToBitmap(byte[] bytes)
|
||
{
|
||
if (bytes.Length == 0) return null;
|
||
|
||
using var stream = new MemoryStream(bytes);
|
||
var image = new BitmapImage();
|
||
image.BeginInit();
|
||
image.CacheOption = BitmapCacheOption.OnLoad;
|
||
image.StreamSource = stream;
|
||
image.EndInit();
|
||
image.Freeze();
|
||
return image;
|
||
}
|
||
|
||
// ---------------- 状态 ----------------
|
||
|
||
private void SetBusy(bool busy, string? text = null)
|
||
{
|
||
_busy = busy;
|
||
|
||
LoginButton.IsEnabled = !busy;
|
||
WechatButton.IsEnabled = !busy;
|
||
ExitButton.IsEnabled = !busy;
|
||
AccountBox.IsEnabled = !busy;
|
||
PasswordBox.IsEnabled = !busy;
|
||
RememberBox.IsEnabled = !busy;
|
||
|
||
LoginButton.Content = busy ? (text ?? "请稍候…") : "登录";
|
||
}
|
||
|
||
private void ShowError(string message)
|
||
{
|
||
ErrorText.Text = message;
|
||
ErrorText.Visibility = Visibility.Visible;
|
||
}
|
||
|
||
private void ClearError()
|
||
{
|
||
ErrorText.Text = string.Empty;
|
||
ErrorText.Visibility = Visibility.Collapsed;
|
||
}
|
||
|
||
private void Exit_Click(object sender, RoutedEventArgs e)
|
||
{
|
||
StopWechatPolling();
|
||
DialogResult = false;
|
||
}
|
||
}
|