This commit is contained in:
gpu 2026-01-20 20:35:32 +08:00
parent 8a0dabb03c
commit 4b130472b8
2 changed files with 58 additions and 15 deletions

View File

@ -52,8 +52,11 @@ public class AuthService : IAuthService
/// </summary>
public async Task<LoginResult> WechatMiniProgramLoginAsync(string code, int? pid, string? clickId)
{
_logger.LogInformation("[AuthService] 微信登录开始code={Code}, pid={Pid}, clickId={ClickId}", code, pid, clickId);
if (string.IsNullOrWhiteSpace(code))
{
_logger.LogWarning("[AuthService] 微信登录失败code为空");
return new LoginResult
{
Success = false,
@ -65,22 +68,31 @@ public class AuthService : IAuthService
{
// 1.6 防抖机制 - 3秒内不允许重复登录
var debounceKey = $"{LoginDebounceKeyPrefix}wechat:{code}";
_logger.LogInformation("[AuthService] 检查防抖锁: {Key}", debounceKey);
var lockAcquired = await _redisService.TryAcquireLockAsync(debounceKey, "1", TimeSpan.FromSeconds(DebounceSeconds));
if (!lockAcquired)
{
_logger.LogWarning("Login debounce triggered for code: {Code}", code);
_logger.LogWarning("[AuthService] 防抖触发,拒绝重复登录请求: {Code}", code);
return new LoginResult
{
Success = false,
ErrorMessage = "请勿频繁登录"
};
}
_logger.LogInformation("[AuthService] 防抖锁获取成功");
// 1.1 调用微信API获取openid和unionid
_logger.LogInformation("[AuthService] 开始调用微信API获取openid...");
var wechatResult = await _wechatService.GetOpenIdAsync(code);
_logger.LogInformation("[AuthService] 微信API调用完成Success={Success}, OpenId={OpenId}, UnionId={UnionId}, Error={Error}",
wechatResult.Success,
wechatResult.OpenId ?? "null",
wechatResult.UnionId ?? "null",
wechatResult.ErrorMessage ?? "null");
if (!wechatResult.Success)
{
_logger.LogWarning("WeChat API failed: {Error}", wechatResult.ErrorMessage);
_logger.LogWarning("[AuthService] 微信API调用失败: {Error}", wechatResult.ErrorMessage);
return new LoginResult
{
Success = false,
@ -95,16 +107,21 @@ public class AuthService : IAuthService
User? user = null;
if (!string.IsNullOrWhiteSpace(unionId))
{
_logger.LogInformation("[AuthService] 尝试通过unionid查找用户: {UnionId}", unionId);
user = await _userService.GetUserByUnionIdAsync(unionId);
_logger.LogInformation("[AuthService] unionid查找结果: {Found}", user != null ? $"找到用户ID={user.Id}" : "未找到");
}
if (user == null)
{
_logger.LogInformation("[AuthService] 尝试通过openid查找用户: {OpenId}", openId);
user = await _userService.GetUserByOpenIdAsync(openId);
_logger.LogInformation("[AuthService] openid查找结果: {Found}", user != null ? $"找到用户ID={user.Id}" : "未找到");
}
if (user == null)
{
// 1.3 用户不存在,创建新用户
_logger.LogInformation("[AuthService] 用户不存在,开始创建新用户...");
var createDto = new CreateUserDto
{
OpenId = openId,
@ -116,25 +133,30 @@ public class AuthService : IAuthService
};
user = await _userService.CreateUserAsync(createDto);
_logger.LogInformation("New user created via WeChat login: UserId={UserId}, OpenId={OpenId}", user.Id, openId);
_logger.LogInformation("[AuthService] 新用户创建成功: UserId={UserId}, OpenId={OpenId}", user.Id, openId);
}
else
{
// 1.4 用户存在更新unionid如果之前为空
if (string.IsNullOrWhiteSpace(user.UnionId) && !string.IsNullOrWhiteSpace(unionId))
{
_logger.LogInformation("[AuthService] 更新用户unionid: UserId={UserId}", user.Id);
await _userService.UpdateUserAsync(user.Id, new UpdateUserDto { UnionId = unionId });
_logger.LogInformation("Updated unionid for user: UserId={UserId}", user.Id);
_logger.LogInformation("[AuthService] unionid更新成功");
}
}
// 1.5 生成JWT Token
_logger.LogInformation("[AuthService] 开始生成JWT Token: UserId={UserId}", user.Id);
var token = _jwtService.GenerateToken(user);
_logger.LogInformation("[AuthService] JWT Token生成成功长度={Length}", token?.Length ?? 0);
// 3.6 同时在数据库UserAccount表中存储account_token用于兼容旧系统
_logger.LogInformation("[AuthService] 更新UserAccount表...");
await CreateOrUpdateAccountTokenAsync(user.Id, token);
_logger.LogInformation("[AuthService] UserAccount更新成功");
_logger.LogInformation("WeChat login successful: UserId={UserId}", user.Id);
_logger.LogInformation("[AuthService] 微信登录成功: UserId={UserId}", user.Id);
return new LoginResult
{
@ -145,7 +167,8 @@ public class AuthService : IAuthService
}
catch (Exception ex)
{
_logger.LogError(ex, "WeChat login failed for code: {Code}", code);
_logger.LogError(ex, "[AuthService] 微信登录异常: code={Code}, Message={Message}, StackTrace={StackTrace}",
code, ex.Message, ex.StackTrace);
return new LoginResult
{
Success = false,

View File

@ -45,9 +45,11 @@ public class WechatService : IWechatService
/// </summary>
public async Task<WechatAuthResult> GetOpenIdAsync(string code)
{
_logger.LogInformation("[微信登录] 开始处理code={Code}", code);
if (string.IsNullOrWhiteSpace(code))
{
_logger.LogWarning("GetOpenIdAsync called with empty code");
_logger.LogWarning("[微信登录] code为空");
return new WechatAuthResult
{
Success = false,
@ -57,16 +59,28 @@ public class WechatService : IWechatService
try
{
// 记录配置信息(脱敏)
var maskedAppId = _wechatSettings.AppId?.Length > 8
? $"{_wechatSettings.AppId.Substring(0, 4)}****{_wechatSettings.AppId.Substring(_wechatSettings.AppId.Length - 4)}"
: "未配置";
var maskedSecret = string.IsNullOrEmpty(_wechatSettings.AppSecret)
? "未配置"
: $"{_wechatSettings.AppSecret.Substring(0, 4)}****";
_logger.LogInformation("[微信登录] 配置信息: AppId={AppId}, AppSecret={AppSecret}", maskedAppId, maskedSecret);
var url = $"{WechatCodeToSessionUrl}?appid={_wechatSettings.AppId}&secret={_wechatSettings.AppSecret}&js_code={code}&grant_type=authorization_code";
_logger.LogInformation("Calling WeChat API to get openid for code: {Code}", code);
_logger.LogInformation("[微信登录] 调用微信API: {Url}", WechatCodeToSessionUrl);
var response = await _httpClient.GetAsync(url);
var content = await response.Content.ReadAsStringAsync();
_logger.LogInformation("[微信登录] 微信API响应状态码: {StatusCode}", response.StatusCode);
_logger.LogInformation("[微信登录] 微信API响应内容: {Content}", content);
if (!response.IsSuccessStatusCode)
{
_logger.LogError("WeChat API returned error status {StatusCode}: {Content}", response.StatusCode, content);
_logger.LogError("[微信登录] 微信API返回HTTP错误 {StatusCode}: {Content}", response.StatusCode, content);
return new WechatAuthResult
{
Success = false,
@ -81,7 +95,7 @@ public class WechatService : IWechatService
if (root.TryGetProperty("errcode", out var errCode) && errCode.GetInt32() != 0)
{
var errMsg = root.TryGetProperty("errmsg", out var msg) ? msg.GetString() : "未知错误";
_logger.LogWarning("WeChat API returned error: {ErrorCode} - {ErrorMessage}", errCode.GetInt32(), errMsg);
_logger.LogWarning("[微信登录] 微信API返回业务错误: errcode={ErrorCode}, errmsg={ErrorMessage}", errCode.GetInt32(), errMsg);
return new WechatAuthResult
{
Success = false,
@ -92,10 +106,16 @@ public class WechatService : IWechatService
// 提取openid和unionid
var openId = root.TryGetProperty("openid", out var openIdProp) ? openIdProp.GetString() : null;
var unionId = root.TryGetProperty("unionid", out var unionIdProp) ? unionIdProp.GetString() : null;
var sessionKey = root.TryGetProperty("session_key", out var sessionKeyProp) ? sessionKeyProp.GetString() : null;
_logger.LogInformation("[微信登录] 解析结果: openid={OpenId}, unionid={UnionId}, session_key={SessionKey}",
openId ?? "null",
unionId ?? "null",
string.IsNullOrEmpty(sessionKey) ? "null" : "已获取");
if (string.IsNullOrEmpty(openId))
{
_logger.LogError("WeChat API response missing openid");
_logger.LogError("[微信登录] 微信API响应中缺少openid");
return new WechatAuthResult
{
Success = false,
@ -103,7 +123,7 @@ public class WechatService : IWechatService
};
}
_logger.LogInformation("Successfully retrieved openid from WeChat API");
_logger.LogInformation("[微信登录] 成功获取openid: {OpenId}", openId);
return new WechatAuthResult
{
@ -114,7 +134,7 @@ public class WechatService : IWechatService
}
catch (HttpRequestException ex)
{
_logger.LogError(ex, "HTTP request error when calling WeChat API");
_logger.LogError(ex, "[微信登录] HTTP请求异常: {Message}", ex.Message);
return new WechatAuthResult
{
Success = false,
@ -123,7 +143,7 @@ public class WechatService : IWechatService
}
catch (JsonException ex)
{
_logger.LogError(ex, "JSON parsing error when processing WeChat API response");
_logger.LogError(ex, "[微信登录] JSON解析异常: {Message}", ex.Message);
return new WechatAuthResult
{
Success = false,
@ -132,7 +152,7 @@ public class WechatService : IWechatService
}
catch (Exception ex)
{
_logger.LogError(ex, "Unexpected error when calling WeChat API");
_logger.LogError(ex, "[微信登录] 未知异常: {Message}", ex.Message);
return new WechatAuthResult
{
Success = false,