Blame view

美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/UsAppAuthAppService.cs 22.6 KB
e5c6f343   李曜臣   登陆接口实现
1
2
  using System;
  using System.Collections.Generic;
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
3
  using System.Globalization;
e5c6f343   李曜臣   登陆接口实现
4
5
6
7
8
  using System.IdentityModel.Tokens.Jwt;
  using System.Linq;
  using System.Security.Claims;
  using System.Text;
  using System.Threading.Tasks;
ecb291fd   李曜臣   门店支持优化;标签,产品组件优化
9
  using FoodLabeling.Application.Contracts;
14afbc16   李曜臣   2026-6-22
10
  using FoodLabeling.Application.Contracts.Dtos.AuthScope;
e5c6f343   李曜臣   登陆接口实现
11
12
  using FoodLabeling.Application.Contracts.Dtos.UsAppAuth;
  using FoodLabeling.Application.Contracts.IServices;
83ccb207   杨鑫   最新
13
  using FoodLabeling.Application.Helpers;
e5c6f343   李曜臣   登陆接口实现
14
  using FoodLabeling.Application.Services.DbModels;
83ccb207   杨鑫   最新
15
  using Microsoft.Extensions.Caching.Distributed;
e5c6f343   李曜臣   登陆接口实现
16
17
18
19
20
  using FoodLabeling.Domain.Entities;
  using Lazy.Captcha.Core;
  using Mapster;
  using Microsoft.AspNetCore.Authorization;
  using Microsoft.AspNetCore.Http;
10fd1324   李曜臣   5-17接口优化
21
  using Microsoft.AspNetCore.Mvc;
e5c6f343   李曜臣   登陆接口实现
22
23
24
25
26
27
28
  using Microsoft.Extensions.Options;
  using Microsoft.IdentityModel.Tokens;
  using SqlSugar;
  using Volo.Abp;
  using Volo.Abp.Application.Services;
  using Volo.Abp.EventBus.Local;
  using Volo.Abp.Security.Claims;
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
29
  using Volo.Abp.Uow;
e5c6f343   李曜臣   登陆接口实现
30
  using Volo.Abp.Users;
10fd1324   李曜臣   5-17接口优化
31
32
  using Yi.Framework.Rbac.Application.Contracts.Dtos.Account;
  using Yi.Framework.Rbac.Application.Contracts.IServices;
e5c6f343   李曜臣   登陆接口实现
33
  using Yi.Framework.Rbac.Domain.Entities;
07d5dea2   李曜臣   5-18代码优化
34
  using Yi.Framework.Rbac.Domain.Helpers;
e5c6f343   李曜臣   登陆接口实现
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
  using Yi.Framework.Rbac.Domain.Managers;
  using Yi.Framework.Rbac.Domain.Shared.Consts;
  using Yi.Framework.Rbac.Domain.Shared.Dtos;
  using Yi.Framework.Rbac.Domain.Shared.Etos;
  using Yi.Framework.Rbac.Domain.Shared.Options;
  using Yi.Framework.SqlSugarCore.Abstractions;
  
  namespace FoodLabeling.Application.Services;
  
  /// <summary>
  /// 美国版 App 登录:邮箱 + 密码(与 AccountManager 相同盐值哈希)签发 JWT,并返回 userlocation 绑定门店
  /// </summary>
  public class UsAppAuthAppService : ApplicationService, IUsAppAuthAppService
  {
      private readonly IAccountManager _accountManager;
e5c6f343   李曜臣   登陆接口实现
50
51
52
53
54
55
      private readonly ISqlSugarRepository<UserAggregateRoot, Guid> _userRepository;
      private readonly ISqlSugarDbContext _dbContext;
      private readonly IHttpContextAccessor _httpContextAccessor;
      private readonly ICaptcha _captcha;
      private readonly RbacOptions _rbacOptions;
      private readonly JwtOptions _jwtOptions;
10fd1324   李曜臣   5-17接口优化
56
      private readonly IForgotPasswordByEmailService _forgotPasswordByEmailService;
83ccb207   杨鑫   最新
57
      private readonly IDistributedCache _distributedCache;
e5c6f343   李曜臣   登陆接口实现
58
59
60
61
62
63
64
65
  
      public UsAppAuthAppService(
          IAccountManager accountManager,
          ISqlSugarRepository<UserAggregateRoot, Guid> userRepository,
          ISqlSugarDbContext dbContext,
          IHttpContextAccessor httpContextAccessor,
          ICaptcha captcha,
          IOptions<JwtOptions> jwtOptions,
10fd1324   李曜臣   5-17接口优化
66
          IOptions<RbacOptions> rbacOptions,
83ccb207   杨鑫   最新
67
68
          IForgotPasswordByEmailService forgotPasswordByEmailService,
          IDistributedCache distributedCache)
e5c6f343   李曜臣   登陆接口实现
69
70
71
72
73
74
75
76
      {
          _accountManager = accountManager;
          _userRepository = userRepository;
          _dbContext = dbContext;
          _httpContextAccessor = httpContextAccessor;
          _captcha = captcha;
          _jwtOptions = jwtOptions.Value;
          _rbacOptions = rbacOptions.Value;
10fd1324   李曜臣   5-17接口优化
77
          _forgotPasswordByEmailService = forgotPasswordByEmailService;
83ccb207   杨鑫   最新
78
          _distributedCache = distributedCache;
e5c6f343   李曜臣   登陆接口实现
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
      }
  
      protected ILocalEventBus LocalEventBus => LazyServiceProvider.LazyGetRequiredService<ILocalEventBus>();
  
      /// <summary>
      /// App 登录:签发 Token / RefreshToken,并返回当前账号绑定的门店列表
      /// </summary>
      /// <remarks>
      /// 行为与系统 <c>AccountService.PostLoginAsync</c> 一致(含验证码、登录日志事件)。
      /// 门店数据来自 <c>userlocation</c>  <c>location</c> 表。
      /// </remarks>
      /// <param name="input">邮箱、密码;若系统开启验证码则需传 UuidCode</param>
      /// <returns>TokenRefreshToken 与绑定门店</returns>
      /// <response code="200">登录成功</response>
      /// <response code="400">参数或验证码错误</response>
      /// <response code="500">服务器错误</response>
      [AllowAnonymous]
      public virtual async Task<UsAppLoginOutputDto> LoginAsync(UsAppLoginInputVo input)
      {
          if (string.IsNullOrWhiteSpace(input.Password) || string.IsNullOrWhiteSpace(input.Email))
          {
              throw new UserFriendlyException("请输入合理数据!");
          }
  
          ValidationImageCaptcha(input.Uuid, input.Code);
  
          var user = await FindActiveUserByEmailAsync(input.Email.Trim());
          if (user is null)
          {
              throw new UserFriendlyException("登录失败!邮箱不存在!");
          }
  
07d5dea2   李曜臣   5-18代码优化
111
          if (!UserPasswordHelper.VerifyPlainPassword(user, input.Password))
e5c6f343   李曜臣   登陆接口实现
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
          {
              throw new UserFriendlyException(UserConst.Login_Error);
          }
  
          // App 端不依赖 RBAC 权限体系:允许“无权限账号”登录拿 TokenH5 再做权限控制)
          var accessToken = CreateAppAccessToken(user);
          var refreshToken = _accountManager.CreateRefreshToken(user.Id);
  
          if (_httpContextAccessor.HttpContext is not null)
          {
              var loginEntity = new LoginLogAggregateRoot().GetInfoByHttpContext(_httpContextAccessor.HttpContext);
              var loginEto = loginEntity.Adapt<LoginEventArgs>();
              loginEto.UserName = user.UserName;
              loginEto.UserId = user.Id;
              await LocalEventBus.PublishAsync(loginEto);
          }
  
          var locations = await LoadBoundLocationsAsync(user.Id);
  
          return new UsAppLoginOutputDto
          {
              Token = accessToken,
              RefreshToken = refreshToken,
              Locations = locations
          };
      }
  
10fd1324   李曜臣   5-17接口优化
139
140
141
142
143
144
145
146
147
148
149
150
151
      /// <inheritdoc />
      [AllowAnonymous]
      [HttpPost("us-app-auth/forgot-password/email/send-code")]
      public virtual Task PostSendForgotPasswordCodeByEmailAsync(EmailCaptchaImageDto input) =>
          _forgotPasswordByEmailService.SendForgotPasswordCodeAsync(input);
  
      /// <inheritdoc />
      [AllowAnonymous]
      [UnitOfWork]
      [HttpPost("us-app-auth/forgot-password/email/reset")]
      public virtual Task<string> PostResetPasswordByEmailAsync(RetrievePasswordByEmailDto input) =>
          _forgotPasswordByEmailService.ResetPasswordByEmailAsync(input);
  
e5c6f343   李曜臣   登陆接口实现
152
153
154
155
156
157
158
159
160
161
162
      /// <summary>
      /// 获取当前登录用户已绑定的门店(切换门店时可重新拉取)
      /// </summary>
      [Authorize]
      public virtual async Task<List<UsAppBoundLocationDto>> GetMyLocationsAsync()
      {
          if (!CurrentUser.Id.HasValue)
          {
              throw new UserFriendlyException("用户未登录");
          }
  
83ccb207   杨鑫   最新
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
          var list = await LoadBoundLocationsAsync(CurrentUser.Id.Value);
          if (ReportsRoleHelper.IsAdminRole(CurrentUser))
          {
              var cached = await UsAppAuthScopeHelper.GetAdminScopeCacheAsync(
                  _distributedCache,
                  CurrentUser.Id.Value);
              if (cached?.Location is not null && !string.IsNullOrWhiteSpace(cached.Location.Id))
              {
                  if (list.All(x => x.Id != cached.Location.Id))
                  {
                      list.Insert(0, cached.Location);
                  }
              }
          }
  
          return list;
      }
  
      /// <inheritdoc />
      [Authorize]
      public virtual async Task<List<AuthScopeCompanyOptionDto>> GetAdminScopeCompaniesAsync()
      {
          UsAppAuthScopeHelper.EnsureAdminAppToken(CurrentUser);
          return await UsAppAuthScopeHelper.ListCompaniesAsync(_dbContext.SqlSugarClient);
      }
  
      /// <inheritdoc />
      [Authorize]
      public virtual async Task<List<AuthScopeRegionOptionDto>> GetAdminScopeRegionsAsync(string partnerId)
      {
          UsAppAuthScopeHelper.EnsureAdminAppToken(CurrentUser);
          return await UsAppAuthScopeHelper.ListRegionsAsync(_dbContext.SqlSugarClient, partnerId);
      }
  
      /// <inheritdoc />
      [Authorize]
      public virtual async Task<List<AuthScopeLocationOptionDto>> GetAdminScopeLocationsAsync(
          string partnerId,
          string groupId)
      {
          UsAppAuthScopeHelper.EnsureAdminAppToken(CurrentUser);
          return await UsAppAuthScopeHelper.ListLocationsAsync(
              _dbContext.SqlSugarClient,
              partnerId,
              groupId);
      }
  
      /// <inheritdoc />
      [Authorize]
      public virtual async Task<AuthScopeSelectLocationOutputDto> SelectAdminScopeLocationAsync(
14afbc16   李曜臣   2026-6-22
213
          AuthScopeSelectLocationInputVo input)
83ccb207   杨鑫   最新
214
215
216
217
218
219
220
221
222
223
224
      {
          UsAppAuthScopeHelper.EnsureAdminAppToken(CurrentUser);
          if (!CurrentUser.Id.HasValue)
          {
              throw new UserFriendlyException("用户未登录");
          }
  
          return await UsAppAuthScopeHelper.SelectLocationAsync(
              _dbContext.SqlSugarClient,
              _distributedCache,
              CurrentUser.Id.Value,
14afbc16   李曜臣   2026-6-22
225
226
227
228
229
230
              new UsAppSelectAdminScopeLocationInputVo
              {
                  PartnerId = input.PartnerId,
                  GroupId = input.GroupId,
                  LocationId = input.LocationId
              });
e5c6f343   李曜臣   登陆接口实现
231
232
      }
  
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
233
      /// <summary>
07d5dea2   李曜臣   5-18代码优化
234
      /// 查询单个门店详情(Location 页):地址、门店电话、经营时间、店长(角色含 manager 的绑定用户)
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
235
236
237
238
239
240
241
      /// </summary>
      /// <remarks>
      /// 仅当当前登录用户在 <c>userlocation</c> 中绑定该 <c>locationId</c> 时可查;否则返回业务异常。
      ///
      /// 店长:在同店绑定用户中,取 <c>Role.RoleCode</c>  <c>Role.RoleName</c>(忽略大小写)包含 <c>manager</c> 的第一条;
      /// 若无匹配则店长姓名与电话均为「无」。
      ///
10fd1324   李曜臣   5-17接口优化
242
      /// <c>OperatingHours</c>:读取 <c>location.OperatingHours</c>;为空时返回「无」。
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
      /// </remarks>
      /// <param name="locationId">门店主键(Guid 字符串)</param>
      /// <returns>与原型一致的展示字段</returns>
      /// <response code="200">成功</response>
      /// <response code="400">未登录、门店标识无效、未绑定或门店不存在</response>
      /// <response code="500">服务器错误</response>
      [Authorize]
      public virtual async Task<UsAppLocationDetailOutputDto> GetLocationDetailAsync(string locationId)
      {
          if (!CurrentUser.Id.HasValue)
          {
              throw new UserFriendlyException("用户未登录");
          }
  
          var lid = (locationId ?? string.Empty).Trim();
          if (string.IsNullOrEmpty(lid) || !Guid.TryParse(lid, out var locationGuid))
          {
              throw new UserFriendlyException("无效的门店标识");
          }
  
83ccb207   杨鑫   最新
263
264
265
266
          await UsAppPrintLogScopeHelper.EnsureUserCanAccessLocationAsync(
              CurrentUser,
              _dbContext.SqlSugarClient,
              lid);
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
  
          var locRows = await _dbContext.SqlSugarClient.Queryable<LocationAggregateRoot>()
              .Where(x => !x.IsDeleted && x.Id == locationGuid)
              .ToListAsync();
          var loc = locRows.FirstOrDefault();
          if (loc is null)
          {
              throw new UserFriendlyException("门店不存在或已删除");
          }
  
          var (mgrName, mgrPhone) = await TryResolveStoreManagerAsync(lid);
  
          return new UsAppLocationDetailOutputDto
          {
              LocationId = loc.Id.ToString(),
              LocationName = string.IsNullOrWhiteSpace(loc.LocationName) ? "无" : loc.LocationName.Trim(),
              FullAddress = BuildFullAddress(loc),
              StorePhone = FormatStorePhoneDisplay(loc.Phone),
10fd1324   李曜臣   5-17接口优化
285
              OperatingHours = string.IsNullOrWhiteSpace(loc.OperatingHours) ? "无" : loc.OperatingHours.Trim(),
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
              ManagerName = mgrName,
              ManagerPhone = mgrPhone
          };
      }
  
      /// <inheritdoc />
      [Authorize]
      public virtual async Task<UsAppMyProfileOutputDto> GetMyProfileAsync()
      {
          if (!CurrentUser.Id.HasValue)
          {
              throw new UserFriendlyException("用户未登录");
          }
  
          var userId = CurrentUser.Id.Value;
          var user = await _userRepository.GetByIdAsync(userId);
          if (user is null || user.IsDeleted || !user.State)
          {
              throw new UserFriendlyException("用户不存在或已停用");
          }
  
3ff23c20   李曜臣   修复app端:我的资料,门店信息
307
308
309
310
311
312
313
314
          // 避免 SqlSugar 在该环境下对 Role 关联表达式解析异常(Select 不支持),这里改用显式 SQL 查询角色。
          var roleRows = await _dbContext.SqlSugarClient.Ado.SqlQueryAsync<MyProfileRoleRow>(
              @"SELECT r.RoleName, r.RoleCode
                FROM UserRole ur
                INNER JOIN Role r ON ur.RoleId = r.Id
                WHERE ur.UserId = @UserId AND r.IsDeleted = 0 AND r.State = 1
                ORDER BY r.OrderNum ASC",
              new { UserId = userId });
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
  
          var roleNames = roleRows.Select(x => x.RoleName?.Trim()).Where(x => !string.IsNullOrWhiteSpace(x)).ToList();
          var roleDisplay = roleNames.Count == 0 ? "无" : string.Join(", ", roleNames);
          var primaryCode = roleRows.FirstOrDefault()?.RoleCode?.Trim();
  
          var fullName = !string.IsNullOrWhiteSpace(user.Name?.Trim())
              ? user.Name.Trim()
              : (!string.IsNullOrWhiteSpace(user.Nick?.Trim()) ? user.Nick.Trim() : user.UserName.Trim());
  
          return new UsAppMyProfileOutputDto
          {
              FullName = fullName,
              Email = string.IsNullOrWhiteSpace(user.Email) ? "无" : user.Email.Trim(),
              Phone = FormatPhoneDisplay(user.Phone),
              EmployeeId = string.IsNullOrWhiteSpace(user.UserName) ? "无" : user.UserName.Trim(),
              RoleDisplay = roleDisplay,
              PrimaryRoleCode = string.IsNullOrWhiteSpace(primaryCode) ? null : primaryCode
          };
      }
  
      /// <inheritdoc />
      [Authorize]
      [UnitOfWork]
      public virtual async Task ChangePasswordAsync(UsAppChangePasswordInputVo input)
      {
          if (input is null)
          {
              throw new UserFriendlyException("入参不能为空");
          }
  
          if (!CurrentUser.Id.HasValue)
          {
              throw new UserFriendlyException("用户未登录");
          }
  
          var current = input.CurrentPassword ?? string.Empty;
          var newPwd = input.NewPassword ?? string.Empty;
          var confirm = input.ConfirmNewPassword ?? string.Empty;
  
          if (string.IsNullOrWhiteSpace(current) || string.IsNullOrWhiteSpace(newPwd) || string.IsNullOrWhiteSpace(confirm))
          {
              throw new UserFriendlyException("请填写当前密码、新密码与确认密码");
          }
  
          if (!string.Equals(newPwd, confirm, StringComparison.Ordinal))
          {
              throw new UserFriendlyException("新密码与确认密码不一致");
          }
  
          if (string.Equals(current, newPwd, StringComparison.Ordinal))
          {
              throw new UserFriendlyException("新密码不能与当前密码相同");
          }
  
          ValidateAppPasswordComplexity(newPwd);
  
          var userId = CurrentUser.Id.Value;
          var user = await _userRepository.GetByIdAsync(userId);
          if (user is null || user.IsDeleted || !user.State)
          {
              throw new UserFriendlyException("用户不存在或已停用");
          }
  
          if (!user.JudgePassword(current))
          {
              throw new UserFriendlyException(UserConst.Login_Error);
          }
  
          user.EncryPassword.Password = newPwd;
          user.BuildPassword();
          await _userRepository.UpdateAsync(user);
      }
  
      private static string FormatPhoneDisplay(long? phone)
      {
          if (!phone.HasValue)
          {
              return "无";
          }
  
          var digits = Math.Abs(phone.Value).ToString(CultureInfo.InvariantCulture);
          if (digits.Length == 10)
          {
              return $"+1 ({digits[..3]}) {digits.Substring(3, 3)}-{digits.Substring(6, 4)}";
          }
  
          if (digits.Length == 11 && digits.StartsWith("1", StringComparison.Ordinal))
          {
              return $"+1 ({digits[1..4]}) {digits.Substring(4, 3)}-{digits.Substring(7, 4)}";
          }
  
          return $"+{digits}";
      }
  
      private static string FormatStorePhoneDisplay(string? phone)
      {
          var t = phone?.Trim();
          return string.IsNullOrEmpty(t) ? "无" : t;
      }
  
      private async Task<(string Name, string Phone)> TryResolveStoreManagerAsync(string locationIdTrimmed)
      {
          var userIdStrings = await _dbContext.SqlSugarClient.Queryable<UserLocationDbEntity>()
              .Where(x => !x.IsDeleted && x.LocationId == locationIdTrimmed)
              .Select(x => x.UserId)
              .Distinct()
              .ToListAsync();
  
          var userGuids = userIdStrings
              .Select(s => Guid.TryParse(s, out var g) ? (Guid?)g : null)
              .Where(g => g.HasValue)
              .Select(g => g!.Value)
              .ToList();
  
          if (userGuids.Count == 0)
          {
              return ("无", "无");
          }
  
3ff23c20   李曜臣   修复app端:我的资料,门店信息
434
435
436
437
438
439
440
441
442
443
444
445
446
          var rows = await _dbContext.SqlSugarClient.Ado.SqlQueryAsync<LocationManagerRow>(
              @"SELECT u.Name, u.Nick, u.UserName, u.Phone
                FROM User u
                INNER JOIN UserRole ur ON u.Id = ur.UserId
                INNER JOIN Role r ON ur.RoleId = r.Id
                WHERE u.IsDeleted = 0
                  AND u.State = 1
                  AND r.IsDeleted = 0
                  AND r.State = 1
                  AND (LOWER(r.RoleCode) LIKE '%manager%' OR LOWER(r.RoleName) LIKE '%manager%')
                  AND u.Id IN (@UserIds)
                ORDER BY u.Name ASC",
              new { UserIds = userGuids });
4d328ec2   李曜臣   平台端报表reports,仪表盘D...
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
  
          var row = rows.FirstOrDefault();
          if (row is null)
          {
              return ("无", "无");
          }
  
          var displayName = !string.IsNullOrWhiteSpace(row.Name?.Trim())
              ? row.Name!.Trim()
              : (!string.IsNullOrWhiteSpace(row.Nick?.Trim())
                  ? row.Nick!.Trim()
                  : (row.UserName?.Trim() ?? "无"));
  
          return (displayName, FormatPhoneDisplay(row.Phone));
      }
  
      private static void ValidateAppPasswordComplexity(string password)
      {
          if (password.Length < 8)
          {
              throw new UserFriendlyException("新密码至少 8 位");
          }
  
          if (!password.Any(char.IsUpper))
          {
              throw new UserFriendlyException("新密码需包含大写字母");
          }
  
          if (!password.Any(char.IsLower))
          {
              throw new UserFriendlyException("新密码需包含小写字母");
          }
  
          if (!password.Any(char.IsDigit))
          {
              throw new UserFriendlyException("新密码需包含至少一个数字");
          }
  
          if (!password.Any(c => !char.IsLetterOrDigit(c)))
          {
              throw new UserFriendlyException("新密码需包含至少一个特殊字符");
          }
      }
  
e5c6f343   李曜臣   登陆接口实现
491
492
493
494
495
496
497
498
499
500
501
502
503
504
      private void ValidationImageCaptcha(string? uuid, string? code)
      {
          if (!_rbacOptions.EnableCaptcha)
          {
              return;
          }
  
          if (!_captcha.Validate(uuid, code))
          {
              throw new UserFriendlyException("验证码错误");
          }
      }
  
      /// <summary>
c2e3194d   李曜臣   登陆优化;产品-门店绑定优化
505
      /// 按邮箱或用户名(邮箱形字符串写在 UserName 时)查找未删除且启用的用户;比较忽略大小写,Email 命中优先。
e5c6f343   李曜臣   登陆接口实现
506
507
508
509
510
511
      /// </summary>
      private async Task<UserAggregateRoot?> FindActiveUserByEmailAsync(string email)
      {
          var normalized = email.Trim().ToLowerInvariant();
          var users = await _userRepository._DbQueryable
              .Where(u => !u.IsDeleted && u.State == true)
c2e3194d   李曜臣   登陆优化;产品-门店绑定优化
512
513
514
              .Where(u =>
                  (u.Email != null && SqlFunc.ToLower(u.Email) == normalized) ||
                  SqlFunc.ToLower(u.UserName) == normalized)
e5c6f343   李曜臣   登陆接口实现
515
              .ToListAsync();
c2e3194d   李曜臣   登陆优化;产品-门店绑定优化
516
517
518
519
          return users.FirstOrDefault(u =>
                  u.Email != null &&
                  string.Equals(u.Email.Trim(), normalized, StringComparison.OrdinalIgnoreCase))
              ?? users.FirstOrDefault();
e5c6f343   李曜臣   登陆接口实现
520
521
522
523
524
525
526
527
528
529
      }
  
      private string CreateAppAccessToken(UserAggregateRoot user)
      {
          var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOptions.SecurityKey));
          var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
  
          var claims = new List<Claim>
          {
              new(AbpClaimTypes.UserId, user.Id.ToString()),
ecb291fd   李曜臣   门店支持优化;标签,产品组件优化
530
531
              new(AbpClaimTypes.UserName, user.UserName),
              new(UsAppJwtClaims.ClientKind, UsAppJwtClaims.ClientKindUsApp)
e5c6f343   李曜臣   登陆接口实现
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
          };
  
          if (!string.IsNullOrWhiteSpace(user.Email))
          {
              claims.Add(new Claim(AbpClaimTypes.Email, user.Email));
          }
  
          var token = new JwtSecurityToken(
              issuer: _jwtOptions.Issuer,
              audience: _jwtOptions.Audience,
              claims: claims,
              expires: DateTime.Now.AddMinutes(_jwtOptions.ExpiresMinuteTime),
              notBefore: DateTime.Now,
              signingCredentials: creds);
  
          return new JwtSecurityTokenHandler().WriteToken(token);
      }
  
      private async Task<List<UsAppBoundLocationDto>> LoadBoundLocationsAsync(Guid userId)
      {
          var userIdStr = userId.ToString();
          var links = await _dbContext.SqlSugarClient.Queryable<UserLocationDbEntity>()
              .Where(x => !x.IsDeleted && x.UserId == userIdStr)
              .Select(x => x.LocationId)
              .ToListAsync();
  
          if (links.Count == 0)
          {
              return new List<UsAppBoundLocationDto>();
          }
  
          var wanted = links.Distinct().ToList();
          var locations = (await _dbContext.SqlSugarClient.Queryable<LocationAggregateRoot>()
                  .Where(x => !x.IsDeleted)
                  .Where(x => wanted.Contains(x.Id.ToString()))
                  .ToListAsync())
              .OrderBy(x => x.OrderNum)
              .ThenBy(x => x.LocationName)
              .ToList();
  
          return locations.Select(x => new UsAppBoundLocationDto
          {
              Id = x.Id.ToString(),
              LocationCode = x.LocationCode ?? string.Empty,
              LocationName = x.LocationName ?? string.Empty,
              FullAddress = BuildFullAddress(x),
              State = x.State
          }).ToList();
      }
  
      private static string BuildFullAddress(LocationAggregateRoot loc)
      {
          var street = loc.Street?.Trim();
          var city = loc.City?.Trim();
          var state = loc.StateCode?.Trim();
          var zip = loc.ZipCode?.Trim();
  
          var line2Parts = new List<string>();
          if (!string.IsNullOrEmpty(city))
          {
              line2Parts.Add(city);
          }
  
          if (!string.IsNullOrEmpty(state))
          {
              line2Parts.Add(state);
          }
  
          var line2 = line2Parts.Count > 0 ? string.Join(", ", line2Parts) : string.Empty;
          if (!string.IsNullOrEmpty(zip))
          {
              line2 = string.IsNullOrEmpty(line2) ? zip : $"{line2} {zip}";
          }
  
          var segments = new List<string>();
          if (!string.IsNullOrEmpty(street))
          {
              segments.Add(street);
          }
  
          if (!string.IsNullOrEmpty(line2))
          {
              segments.Add(line2);
          }
  
          return segments.Count == 0 ? "无" : string.Join(", ", segments);
      }
3ff23c20   李曜臣   修复app端:我的资料,门店信息
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
  
      private sealed class MyProfileRoleRow
      {
          public string? RoleName { get; set; }
  
          public string? RoleCode { get; set; }
      }
  
      private sealed class LocationManagerRow
      {
          public string? Name { get; set; }
  
          public string? Nick { get; set; }
  
          public string? UserName { get; set; }
  
          public long? Phone { get; set; }
      }
e5c6f343   李曜臣   登陆接口实现
637
  }