longz
2026-05-28 aa67b3cb0fe26fab576f7710c978ff3594426cca
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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
111
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
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
434
435
436
437
438
439
440
441
442
443
444
445
446
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
package com.sinata.appointment.service;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sinata.appointment.constants.BizErrorCode;
import com.sinata.appointment.constants.MiniUserType;
import com.sinata.appointment.constants.MpStaffConstants;
import com.sinata.appointment.config.MiniStpUtil;
import com.sinata.appointment.dto.MiniLoginResponse;
import com.sinata.appointment.dto.MiniOfficialLoginResponse;
import com.sinata.appointment.dto.MiniProfileUpdateRequest;
import com.sinata.appointment.dto.MiniWxLoginRequest;
import com.sinata.appointment.entity.MpUser;
import com.sinata.appointment.entity.SysDept;
import com.sinata.appointment.exception.BizException;
import com.sinata.appointment.integration.WechatMiniGateway;
import com.sinata.appointment.integration.WechatOfficialAccountGateway;
import com.sinata.appointment.integration.WxOfficialOAuthResult;
import com.sinata.appointment.integration.WxCode2SessionResult;
import com.sinata.appointment.mapper.SysDeptMapper;
import com.sinata.appointment.mapper.MpUserMapper;
import java.time.Duration;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import com.sinata.appointment.util.PhoneNormalize;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
 
/**
 * 小程序登录:js_code → openId;phoneCode + access_token → 手机号;访客/员工与平台 sys_user 无关联。
 */
@Service
public class MiniAuthApplicationService {
 
    private static final String OFFICIAL_BIND_TOKEN_PREFIX = "official:bind:";
    private static final Duration OFFICIAL_BIND_TOKEN_TTL = Duration.ofMinutes(10);
    private static final String OFFICIAL_OPEN_ID_PLACEHOLDER_PREFIX = "OA_PLACEHOLDER_";
 
    private final MpUserMapper mpUserMapper;
    private final SysDeptMapper sysDeptMapper;
    private final WechatMiniGateway wechatMiniGateway;
    private final WechatOfficialAccountGateway wechatOfficialAccountGateway;
    private final StringRedisTemplate stringRedisTemplate;
 
    public MiniAuthApplicationService(
            MpUserMapper mpUserMapper,
            SysDeptMapper sysDeptMapper,
            WechatMiniGateway wechatMiniGateway,
            WechatOfficialAccountGateway wechatOfficialAccountGateway,
            StringRedisTemplate stringRedisTemplate) {
        this.mpUserMapper = mpUserMapper;
        this.sysDeptMapper = sysDeptMapper;
        this.wechatMiniGateway = wechatMiniGateway;
        this.wechatOfficialAccountGateway = wechatOfficialAccountGateway;
        this.stringRedisTemplate = stringRedisTemplate;
    }
 
    public String buildOfficialOAuthUrl(String redirectUri, String state) {
        return wechatOfficialAccountGateway.buildSilentOAuthUrl(redirectUri, state);
    }
 
    @Transactional(rollbackFor = Exception.class)
    public MiniLoginResponse loginByWx(MiniWxLoginRequest req) {
        WxCode2SessionResult session = wechatMiniGateway.code2Session(req.getWxCode());
        String openId = session.getOpenId();
 
        MpUser user =
                mpUserMapper.selectOne(
                        new LambdaQueryWrapper<MpUser>()
                                .eq(MpUser::getOpenId, openId)
                                .eq(MpUser::getDelFlag, 0));
        if (user == null) {
            if (!StringUtils.hasText(req.getPhoneCode())) {
                throw new BizException(BizErrorCode.MINI_PHONE_AUTH_REQUIRED, "请先授权手机号完成登录");
            }
            String phoneRaw = wechatMiniGateway.getPhoneNumber(req.getPhoneCode());
            String phone = PhoneNormalize.mainland(phoneRaw);
            user = resolveUserByPhoneForWxLogin(openId, session.getUnionId(), phone, phoneRaw);
        }
        assertUserCanLogin(user);
        syncUnionIdIfNeeded(user, session.getUnionId());
        MiniStpUtil.login(user.getId());
        return buildResponse(user);
    }
 
    @Transactional(rollbackFor = Exception.class)
    public MiniOfficialLoginResponse loginByOfficialCode(String code) {
        WxOfficialOAuthResult session = wechatOfficialAccountGateway.exchangeCode(code);
        MpUser user =
                mpUserMapper.selectOne(
                        new LambdaQueryWrapper<MpUser>()
                                .eq(MpUser::getOfficialOpenId, session.getOpenId())
                                .eq(MpUser::getDelFlag, 0)
                                .last("limit 1"));
        if (user == null) {
            return MiniOfficialLoginResponse.builder()
                    .mobileRequired(true)
                    .bindToken(createOfficialBindToken(session.getOpenId(), session.getUnionId()))
                    .login(null)
                    .build();
        }
        assertUserCanLogin(user);
        syncUnionIdIfNeeded(user, session.getUnionId());
        MiniStpUtil.login(user.getId());
        return MiniOfficialLoginResponse.builder()
                .mobileRequired(false)
                .bindToken(null)
                .login(buildResponse(user))
                .build();
    }
 
    @Transactional(rollbackFor = Exception.class)
    public MiniLoginResponse bindOfficialPhoneAndLogin(String bindToken, String mobileRaw) {
        OfficialBindSession session = consumeOfficialBindToken(bindToken);
        String phone = PhoneNormalize.mainland(mobileRaw);
        if (!phone.matches("^\\d{11}$")) {
            throw new BizException(BizErrorCode.AUTH_INVALID_CREDENTIALS, "手机号格式不正确");
        }
        MpUser user = resolveUserByPhoneForOfficialLogin(session.openId(), session.unionId(), phone, mobileRaw);
        assertUserCanLogin(user);
        MiniStpUtil.login(user.getId());
        return buildResponse(user);
    }
 
    @Transactional(rollbackFor = Exception.class)
    public MiniLoginResponse loginByPhone(String mobileRaw) {
        String phone = PhoneNormalize.mainland(mobileRaw);
        if (!phone.matches("^\\d{11}$")) {
            throw new BizException(BizErrorCode.AUTH_INVALID_CREDENTIALS, "手机号格式不正确");
        }
        List<MpUser> users =
                mpUserMapper.selectList(
                        new LambdaQueryWrapper<MpUser>()
                                .eq(MpUser::getDelFlag, 0));
        MpUser user =
                users.stream()
                        .filter(Objects::nonNull)
                        .filter(u -> phone.equals(PhoneNormalize.mainland(u.getMobile())))
                        .sorted(this::compareByLoginPriority)
                        .findFirst()
                        .orElse(null);
        if (user == null) {
            user = registerVisitorForPhoneLogin(mobileRaw);
        }
        assertUserCanLogin(user);
        MiniStpUtil.login(user.getId());
        return buildResponse(user);
    }
 
    private MpUser resolveUserByPhoneForWxLogin(
            String openId, String unionId, String normalizedPhone, String phoneRaw) {
        if (!normalizedPhone.matches("^\\d{11}$")) {
            throw new BizException(BizErrorCode.AUTH_INVALID_CREDENTIALS, "手机号格式不正确");
        }
        List<MpUser> users =
                mpUserMapper.selectList(
                        new LambdaQueryWrapper<MpUser>()
                                .eq(MpUser::getDelFlag, 0));
        MpUser user =
                users.stream()
                        .filter(Objects::nonNull)
                        .filter(u -> normalizedPhone.equals(PhoneNormalize.mainland(u.getMobile())))
                        .sorted(this::compareByLoginPriority)
                        .findFirst()
                        .orElse(null);
        if (user == null) {
            MpUser created = new MpUser();
            created.setOpenId(openId);
            created.setUnionId(unionId);
            created.setUserType(MiniUserType.VISITOR);
            created.setMobile(phoneRaw);
            created.setStatus(1);
            mpUserMapper.insert(created);
            return mpUserMapper.selectById(created.getId());
        }
        assertAccountEnabled(user);
        if (MiniUserType.EMPLOYEE.equals(user.getUserType()) && user.getDeptId() == null) {
            throw new BizException(BizErrorCode.MINI_STAFF_NOT_BOUND, "员工未分配部门");
        }
        bindOpenIdIfNeeded(user, openId, unionId, phoneRaw);
        return mpUserMapper.selectById(user.getId());
    }
 
    private MpUser resolveUserByPhoneForOfficialLogin(
            String officialOpenId, String unionId, String normalizedPhone, String phoneRaw) {
        List<MpUser> users =
                mpUserMapper.selectList(
                        new LambdaQueryWrapper<MpUser>()
                                .eq(MpUser::getDelFlag, 0));
        MpUser user =
                users.stream()
                        .filter(Objects::nonNull)
                        .filter(u -> normalizedPhone.equals(PhoneNormalize.mainland(u.getMobile())))
                        .sorted(this::compareByLoginPriority)
                        .findFirst()
                        .orElse(null);
        if (user == null) {
            MpUser created = new MpUser();
            created.setOpenId(OFFICIAL_OPEN_ID_PLACEHOLDER_PREFIX + UUID.randomUUID());
            created.setOfficialOpenId(officialOpenId);
            created.setUnionId(unionId);
            created.setUserType(MiniUserType.VISITOR);
            created.setMobile(phoneRaw);
            created.setStatus(1);
            mpUserMapper.insert(created);
            return mpUserMapper.selectById(created.getId());
        }
        assertAccountEnabled(user);
        if (MiniUserType.EMPLOYEE.equals(user.getUserType()) && user.getDeptId() == null) {
            throw new BizException(BizErrorCode.MINI_STAFF_NOT_BOUND, "员工未分配部门");
        }
        bindOfficialOpenIdIfNeeded(user, officialOpenId, unionId, phoneRaw);
        return mpUserMapper.selectById(user.getId());
    }
 
    /**
     * 管理端预建档员工(openId 为 PLHD_ 占位):按手机号绑定当前微信 openId。
     */
    private MpUser tryBindPreRegisteredEmployee(
            String openId, String unionId, String normalizedPhone, String phoneRaw) {
        List<MpUser> candidates =
                mpUserMapper.selectList(
                        new LambdaQueryWrapper<MpUser>()
                                .eq(MpUser::getUserType, MiniUserType.EMPLOYEE)
                                .eq(MpUser::getDelFlag, 0)
                                .likeRight(MpUser::getOpenId, MpStaffConstants.PLACEHOLDER_OPEN_ID_PREFIX));
        for (MpUser u : candidates) {
            if (u.getOpenId() == null || !MpStaffConstants.isPlaceholderOpenId(u.getOpenId())) {
                continue;
            }
            String stored = PhoneNormalize.mainland(u.getMobile());
            if (stored.isBlank() || !stored.equals(normalizedPhone)) {
                continue;
            }
            u.setOpenId(openId);
            if (unionId != null) {
                u.setUnionId(unionId);
            }
            syncMpUserMobile(u, phoneRaw);
            mpUserMapper.updateById(u);
            return mpUserMapper.selectById(u.getId());
        }
        return null;
    }
 
    private void syncMpUserMobile(MpUser user, String phoneRaw) {
        boolean needUpdate = false;
        if (user.getMobile() == null || user.getMobile().isBlank()) {
            user.setMobile(phoneRaw);
            needUpdate = true;
        }
        if (needUpdate) {
            mpUserMapper.updateById(user);
        }
    }
 
    private void bindOpenIdIfNeeded(MpUser user, String openId, String unionId, String phoneRaw) {
        if (user == null) {
            return;
        }
        String currentOpenId = user.getOpenId();
        if (StringUtils.hasText(currentOpenId)
                && !Objects.equals(currentOpenId, openId)
                && !MpStaffConstants.isPlaceholderOpenId(currentOpenId)) {
            throw new BizException(BizErrorCode.AUTH_FORBIDDEN, "该手机号已绑定其他微信账号");
        }
        if (MiniUserType.EMPLOYEE.equals(user.getUserType())
                && MpStaffConstants.isPlaceholderOpenId(currentOpenId)) {
            MpUser bound = tryBindPreRegisteredEmployee(openId, unionId, PhoneNormalize.mainland(phoneRaw), phoneRaw);
            if (bound == null) {
                throw new BizException(BizErrorCode.MINI_STAFF_NOT_BOUND, "员工未登记,请联系管理员开通后再登录");
            }
            return;
        }
        boolean needUpdate = false;
        if (!Objects.equals(currentOpenId, openId)) {
            user.setOpenId(openId);
            needUpdate = true;
        }
        if (!StringUtils.hasText(user.getUnionId()) && StringUtils.hasText(unionId)) {
            user.setUnionId(unionId);
            needUpdate = true;
        }
        if (!StringUtils.hasText(user.getMobile()) && StringUtils.hasText(phoneRaw)) {
            user.setMobile(phoneRaw);
            needUpdate = true;
        }
        if (needUpdate) {
            mpUserMapper.updateById(user);
        }
    }
 
    private void bindOfficialOpenIdIfNeeded(
            MpUser user, String officialOpenId, String unionId, String phoneRaw) {
        if (user == null) {
            return;
        }
        String currentOfficialOpenId = user.getOfficialOpenId();
        if (StringUtils.hasText(currentOfficialOpenId)
                && !Objects.equals(currentOfficialOpenId, officialOpenId)) {
            throw new BizException(BizErrorCode.AUTH_FORBIDDEN, "该手机号已绑定其他微信账号");
        }
        boolean needUpdate = false;
        if (!Objects.equals(currentOfficialOpenId, officialOpenId)) {
            user.setOfficialOpenId(officialOpenId);
            needUpdate = true;
        }
        if (!StringUtils.hasText(user.getUnionId()) && StringUtils.hasText(unionId)) {
            user.setUnionId(unionId);
            needUpdate = true;
        }
        if (!StringUtils.hasText(user.getMobile()) && StringUtils.hasText(phoneRaw)) {
            user.setMobile(phoneRaw);
            needUpdate = true;
        }
        if (needUpdate) {
            mpUserMapper.updateById(user);
        }
    }
 
    private String createOfficialBindToken(String openId, String unionId) {
        String token = UUID.randomUUID().toString();
        String value = openId + "\n" + (unionId == null ? "" : unionId);
        stringRedisTemplate.opsForValue()
                .set(OFFICIAL_BIND_TOKEN_PREFIX + token, value, OFFICIAL_BIND_TOKEN_TTL);
        return token;
    }
 
    private OfficialBindSession consumeOfficialBindToken(String bindToken) {
        if (!StringUtils.hasText(bindToken)) {
            throw new BizException(BizErrorCode.AUTH_INVALID_CREDENTIALS, "绑定凭证不能为空");
        }
        String key = OFFICIAL_BIND_TOKEN_PREFIX + bindToken.trim();
        String value = stringRedisTemplate.opsForValue().get(key);
        if (!StringUtils.hasText(value)) {
            throw new BizException(BizErrorCode.AUTH_INVALID_CREDENTIALS, "绑定凭证已失效,请重新登录");
        }
        stringRedisTemplate.delete(key);
        String[] parts = value.split("\\n", 2);
        String openId = parts.length > 0 ? parts[0] : "";
        String unionId = parts.length > 1 ? parts[1] : null;
        if (!StringUtils.hasText(openId)) {
            throw new BizException(BizErrorCode.AUTH_INVALID_CREDENTIALS, "绑定凭证无效,请重新登录");
        }
        return new OfficialBindSession(openId, StringUtils.hasText(unionId) ? unionId : null);
    }
 
    private void assertUserCanLogin(MpUser user) {
        assertAccountEnabled(user);
        if (MiniUserType.EMPLOYEE.equals(user.getUserType()) && user.getDeptId() == null) {
            throw new BizException(BizErrorCode.MINI_STAFF_NOT_BOUND, "员工未分配部门");
        }
    }
 
    private void syncUnionIdIfNeeded(MpUser user, String unionId) {
        if (user == null || !StringUtils.hasText(unionId) || StringUtils.hasText(user.getUnionId())) {
            return;
        }
        user.setUnionId(unionId);
        mpUserMapper.updateById(user);
    }
 
    private void assertAccountEnabled(MpUser user) {
        if (user == null || user.getStatus() == null || user.getStatus() != 0) {
            return;
        }
        if (MiniUserType.EMPLOYEE.equals(user.getUserType())) {
            throw new BizException(BizErrorCode.AUTH_FORBIDDEN, "员工账号已禁用");
        }
        throw new BizException(BizErrorCode.AUTH_FORBIDDEN, "账号已被禁用");
    }
 
    private int compareByLoginPriority(MpUser a, MpUser b) {
        int pa = loginPriority(a);
        int pb = loginPriority(b);
        if (pa != pb) {
            return Integer.compare(pa, pb);
        }
        Long aid = a.getId() == null ? Long.MAX_VALUE : a.getId();
        Long bid = b.getId() == null ? Long.MAX_VALUE : b.getId();
        return Long.compare(aid, bid);
    }
 
    private int loginPriority(MpUser u) {
        if (MiniUserType.EMPLOYEE.equals(u.getUserType())) {
            return 0;
        }
        if (MiniUserType.VISITOR.equals(u.getUserType())) {
            return 1;
        }
        return 2;
    }
 
    private MpUser registerVisitorForPhoneLogin(String mobileRaw) {
        MpUser created = new MpUser();
        created.setUserType(MiniUserType.VISITOR);
        created.setMobile(mobileRaw);
        created.setStatus(1);
        mpUserMapper.insert(created);
        return mpUserMapper.selectById(created.getId());
    }
 
    public MpUser currentMpUser() {
        long id = MiniStpUtil.getLoginIdAsLong();
        MpUser u = mpUserMapper.selectById(id);
        if (u == null || u.getDelFlag() != null && u.getDelFlag() == 1) {
            throw new BizException(BizErrorCode.AUTH_FORBIDDEN, "用户不存在或已禁用");
        }
        assertAccountEnabled(u);
        return u;
    }
 
    @Transactional(rollbackFor = Exception.class)
    public MpUser updateProfile(MiniProfileUpdateRequest request) {
        MpUser user = currentMpUser();
        String nickName = trimRequired(request.getNickName(), "姓名不能为空");
        if (nickName.length() > 30) {
            throw new BizException(BizErrorCode.AUTH_INVALID_CREDENTIALS, "姓名长度不能超过30个字符");
        }
        String gender = trimToNull(request.getGender());
        if (StringUtils.hasText(gender) && !"男".equals(gender) && !"女".equals(gender)) {
            throw new BizException(BizErrorCode.AUTH_INVALID_CREDENTIALS, "性别仅支持男或女");
        }
        String companyName = trimToNull(request.getCompanyName());
        String avatarUrl = trimToNull(request.getAvatarUrl());
        user.setNickName(nickName);
        user.setGender(gender);
        user.setCompanyName(companyName);
        user.setAvatarUrl(avatarUrl);
        mpUserMapper.updateById(user);
        return mpUserMapper.selectById(user.getId());
    }
 
    public void logout() {
        MiniStpUtil.logout();
    }
 
    private MiniLoginResponse buildResponse(MpUser user) {
        String name =
                user.getNickName() != null && !user.getNickName().isBlank()
                        ? user.getNickName()
                        : (MiniUserType.EMPLOYEE.equals(user.getUserType()) ? "员工" : "访客");
        String deptName = null;
        if (MiniUserType.EMPLOYEE.equals(user.getUserType()) && user.getDeptId() != null) {
            SysDept dept = sysDeptMapper.selectById(user.getDeptId());
            deptName = dept == null ? null : dept.getDeptName();
        }
        Boolean leader =
                MiniUserType.EMPLOYEE.equals(user.getUserType())
                        ? Boolean.TRUE.equals(user.getDeptLeaderFlag())
                        : null;
        return MiniLoginResponse.builder()
                .token(MiniStpUtil.getTokenValue())
                .mpUserId(user.getId())
                .userType(user.getUserType())
                .deptId(user.getDeptId())
                .deptName(deptName)
                .deptLeader(leader)
                .avatarUrl(user.getAvatarUrl())
                .companyName(user.getCompanyName())
                .displayName(name)
                .build();
    }
 
    private static String trimToNull(String value) {
        if (!StringUtils.hasText(value)) {
            return null;
        }
        String trimmed = value.trim();
        return trimmed.isEmpty() ? null : trimmed;
    }
 
    private static String trimRequired(String value, String message) {
        String trimmed = trimToNull(value);
        if (!StringUtils.hasText(trimmed)) {
            throw new BizException(BizErrorCode.AUTH_INVALID_CREDENTIALS, message);
        }
        return trimmed;
    }
 
    private record OfficialBindSession(String openId, String unionId) {}
}