ny
昨天 b6f169fe43a2b13f351aefc152374fc7f0bc8cb7
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
package jnpf.controller;
 
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.text.StrPool;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jnpf.base.*;
import jnpf.base.model.logmodel.WriteLogModel;
import jnpf.config.ConfigValueUtil;
import jnpf.config.JnpfOauthConfig;
import jnpf.constant.JnpfConst;
import jnpf.constant.MsgCode;
import jnpf.constant.PermissionConst;
import jnpf.consts.AuthConsts;
import jnpf.consts.DeviceType;
import jnpf.consts.LoginTicketStatus;
import jnpf.consts.ScanCodeTicketStatus;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.exception.LoginException;
import jnpf.granter.UserDetailsServiceBuilder;
import jnpf.model.*;
import jnpf.model.login.MeInfoVO;
import jnpf.model.login.PcUserVO;
import jnpf.model.login.UserSystemVO;
import jnpf.model.logout.LogoutResultModel;
import jnpf.oauth.AuthApi;
import jnpf.permission.SocialsUserApi;
import jnpf.permission.UserApi;
import jnpf.permission.entity.UserEntity;
import jnpf.permission.model.socails.SocialsUserVo;
import jnpf.permission.model.user.UserUpdateModel;
import jnpf.service.AuthService;
import jnpf.service.LoginService;
import jnpf.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
 
import java.io.IOException;
import java.util.*;
 
import static jnpf.consts.AuthConsts.PARAMS_JNPF_TICKET;
 
/**
 * 登录控制器
 *
 * @author JNPF开发平台组
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司
 * @date 2019年9月26日 上午9:18
 */
@Tag(name = "登陆数据", description = "oauth")
@Slf4j
@RestController
@Tag(name = "登陆数据", description = "Login")
public class LoginController implements AuthApi {
 
    @Autowired
    private UserApi userApi;
    @Autowired
    private LoginService loginService;
    @Autowired
    private AuthService authService;
    @Autowired
    private ConfigValueUtil configValueUtil;
    @Autowired
    private JnpfOauthConfig oauthConfig;
    @Autowired
    private SysConfigApi sysConfigApi;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SocialsUserApi socialsUserApi;
    @Autowired
    private UserDetailsServiceBuilder userDetailsServiceBuilder;
 
    /**
     * 登陆
     *
     * @param parameters 登录参数
     * @return
     * @throws LoginException 登录异常
     */
    @Override
    @Operation(summary = "登陆")
    @Parameters({
            @Parameter(name = "parameters", description = "登录参数", required = true)
    })
    @RequestMapping(value = "/Login/**", method = {RequestMethod.GET, RequestMethod.POST})
    @NoDataSourceBind
    public ActionResult<LoginVO> login(@RequestParam Map<String, String> parameters) throws LoginException {
        return authService.login(parameters);
    }
 
 
    /**
     * 验证密码
     *
     * @param loginForm 登录模型
     * @return
     * @throws LoginException 登录异常
     */
    @Operation(summary = "锁屏解锁登录")
    @Parameters({
            @Parameter(name = "loginForm", description = "登录模型", required = true)
    })
    @PostMapping("/LockScreen")
    public ActionResult lockScreen(@RequestBody LoginForm loginForm) throws LoginException {
        UserEntity userEntity = userApi.getInfoByAccount(loginForm.getAccount());
        if (userEntity == null) {
            UserInfo userInfo = UserProvider.getUser();
            if (userInfo.getUserId() != null) {
                UserProvider.logoutByUserId(userInfo.getUserId());
            }
            throw new LoginException(MsgCode.FA001.get());
        }
        if (!Md5Util.getStringMd5(loginForm.getPassword().toLowerCase() + userEntity.getSecretkey().toLowerCase()).equals(userEntity.getPassword())) {
            throw new LoginException(MsgCode.OA020.get());
        }
        return ActionResult.success(MsgCode.SU005.get());
    }
 
    /**
     * 登录注销
     *
     * @param grandtype 登录类型
     * @return
     */
    @NoDataSourceBind
    @Operation(summary = "登录注销")
    @Parameters({
            @Parameter(name = "grandtype", description = "登录类型", required = true)
    })
    @RequestMapping(value = {"/Logout", "/Logout/{grandtype}"}, method = {RequestMethod.GET, RequestMethod.POST})
    public ActionResult<LogoutResultModel> logout(@PathVariable(value = "grandtype", required = false) String grandtype) {
        return authService.logout(grandtype);
    }
 
    /**
     * 踢出指定用户, 推送Websocket用户被强制下线
     *
     * @param tokens   token集合
     * @param userId   租户id
     * @param tenantId 租户id
     */
    @NoDataSourceBind
    @Operation(summary = "踢出指定用户")
    @Parameters({
            @Parameter(name = "tokens", description = "token集合"),
            @Parameter(name = "userId", description = "租户id"),
            @Parameter(name = "tenantId", description = "租户id"),
    })
    @PostMapping(value = {"/KickoutToken"})
    public void kickoutByToken(@RequestParam(value = "tokens", required = false) String[] tokens, @RequestParam(name = "userId", required = false) String userId, @RequestParam(name = "tenantId", required = false) String tenantId) {
        if (StringUtil.isNotEmpty(tokens)) {
            authService.kickoutByToken(tokens);
        } else {
            authService.kickoutByUserId(userId, tenantId);
        }
    }
 
    /**
     * 获取用户登录信息
     *
     * @param type Web/App
     * @return
     * @throws LoginException 登录异常
     */
    @Operation(summary = "获取用户登录信息")
    @Parameters({
            @Parameter(name = "type", description = "Web/App")
    })
    @GetMapping("/CurrentUser")
    public ActionResult<PcUserVO> currentUser(String type, String systemCode, @RequestParam(value = "isBackend", required = false) Integer isBackend) throws LoginException {
        type = StringUtil.isEmpty(type) ? JnpfConst.WEB : JnpfConst.APP;
 
        if (!Objects.equals(isBackend, 1)) {
            isBackend = 0;
        }
        UserInfo userInfo = UserProvider.getUser();
        if (DeviceType.TEMPUSERLIMITED.getDevice().equals(userInfo.getLoginDevice())) {
            throw new LoginException(MsgCode.OA022.get());
        }
        PcUserVO pcUserVO = loginService.getCurrentUser(type, systemCode, isBackend);
        if (pcUserVO == null) {
            throw new LoginException(MsgCode.LOG001.get());
        }
        //自动切身份
        if (StringUtil.isEmpty(pcUserVO.getCurrentSystemId()) && JnpfConst.APP.equals(type)
                && CollectionUtil.isNotEmpty(pcUserVO.getUserInfo().getStandingList())) {
            List<UserSystemVO> standingList = pcUserVO.getUserInfo().getStandingList();
            //先切使用者
            UserSystemVO userSystemVO = standingList.stream().filter(t -> PermissionConst.USER.equals(t.getEnCode())).findFirst().orElse(null);
            if (userSystemVO != null) {
                UserEntity user = new UserEntity();
                user.setId(userInfo.getUserId());
                user.setAppStanding(userSystemVO.getId());
                boolean update = userApi.updateById(new UserUpdateModel(user, userInfo.getTenantId()));
                if (update) {
                    pcUserVO = loginService.getCurrentUser(type, systemCode, isBackend);
                }
            }
            //没有使用者遍历其他身份
            if (userSystemVO == null || StringUtil.isEmpty(pcUserVO.getCurrentSystemId())) {
                for (UserSystemVO standVo : standingList) {
                    if (!standVo.isCurrentStanding()) {
                        UserEntity user = new UserEntity();
                        user.setId(userInfo.getUserId());
                        user.setAppStanding(standVo.getId());
                        boolean update = userApi.updateById(new UserUpdateModel(user, userInfo.getTenantId()));
                        if (update) {
                            pcUserVO = loginService.getCurrentUser(type, systemCode, isBackend);
                        }
                        if (!StringUtil.isEmpty(pcUserVO.getCurrentSystemId())) break;
                    }
                }
            }
 
            //身份切换后还是没有系统报错
            if (StringUtil.isEmpty(pcUserVO.getCurrentSystemId())) {
                throw new LoginException(MsgCode.LOG004.get());
            }
        }
        pcUserVO.setCurrentSystemId(null);
        //当前身份没有菜单信息时,直接提示权限不足
        if (pcUserVO.getMenuList().isEmpty() && StringUtil.isNotEmpty(systemCode)) {
            if (Objects.equals(isBackend, 1)) {
                throw new LoginException(MsgCode.LOG013.get());
            }
            throw new LoginException(MsgCode.LOG004.get());
        }
        //app没有身份和权限的时候直接退出
        if (JnpfConst.APP.equals(type)
                && CollectionUtil.isEmpty(pcUserVO.getUserInfo().getStandingList())
                && pcUserVO.getMenuList().isEmpty()) {
//            userApi.logoutUser(MsgCode.LOG004.get(), Arrays.asList(userInfo.getUserId()));
            return ActionResult.fail(ActionResultCode.SessionOverdue.getCode(), MsgCode.LOG004.get());
        }
        return ActionResult.success(pcUserVO);
    }
 
    /**
     * 修改密码信息发送
     */
    @Operation(summary = "修改密码信息发送")
    @PostMapping("/updatePasswordMessage")
    public ActionResult updatePasswordMessage() {
        loginService.updatePasswordMessage();
        return ActionResult.success();
    }
 
    /**
     * 图形验证码
     *
     * @param codeLength 验证码长度
     * @param timestamp  验证码标识
     */
    @NoDataSourceBind()
    @Operation(summary = "图形验证码")
    @Parameters({
            @Parameter(name = "codeLength", description = "验证码长度", required = true),
            @Parameter(name = "timestamp", description = "验证码标识", required = true)
    })
    @GetMapping("/ImageCode/{codeLength}/{timestamp}")
    public void imageCode(@PathVariable("codeLength") Integer codeLength, @PathVariable("timestamp") String timestamp) {
        DownUtil.downCode(codeLength);
        redisUtil.insert(timestamp, ServletUtil.getSession().getAttribute(CodeUtil.RANDOMCODEKEY), 300);
    }
 
    /**
     * 注销用户
     *
     * @return
     */
    @Operation(summary = "注销用户")
    @PostMapping("/logoutCurrentUser")
    public ActionResult logoutCurrentUser() {
        UserInfo userInfo = UserProvider.getUser();
        if (userInfo.getIsAdministrator() != null && UserProvider.getUser().getIsAdministrator()) {
            return ActionResult.fail(MsgCode.OA023.get());
        }
        if (userInfo.getIsAdministrator() != null) {
            if (!userInfo.getIsAdministrator()) {
                userApi.delete(userApi.getInfoById(userInfo.getUserId()));
                UserProvider.kickoutByUserId(userInfo.getUserId(), TenantHolder.getDatasourceId());
            }
        }
        return ActionResult.success(MsgCode.OA014.get());
    }
 
    /**
     * 判断是否需要验证码
     *
     * @param account 账号
     */
    @NoDataSourceBind()
    @Operation(summary = "判断是否需要验证码")
    @Parameters({
            @Parameter(name = "account", description = "账号", required = true)
    })
    @GetMapping("/getConfig/{account}")
    public ActionResult<LoginModel> check(@PathVariable("account") String account) throws LoginException {
        LoginModel loginModel = new LoginModel();
        String tenantId = "0" ;
        if (configValueUtil.isMultiTenancy()) {
            LoginForm loginForm = new LoginForm();
            loginForm.setAccount(account);
            UserInfo userInfo = new UserInfo();
            userInfo.setUserAccount(loginForm.getAccount());
            userInfo = loginService.getTenantAccount(userInfo);
            tenantId = userInfo.getTenantId();
        }
        // 获取配置
        BaseSystemInfo sysConfigInfo = sysConfigApi.getSysInfo(tenantId);
        // 是否开启验证码
        if (Objects.nonNull(sysConfigInfo) && "1".equals(String.valueOf(sysConfigInfo.getEnableVerificationCode()))) {
            loginModel.setEnableVerificationCode(1);
            Integer verificationCodeNumber = sysConfigInfo.getVerificationCodeNumber();
            loginModel.setVerificationCodeNumber(verificationCodeNumber == null ? 4 : verificationCodeNumber);
            return ActionResult.success(loginModel);
        }
        loginModel.setEnableVerificationCode(0);
        return ActionResult.success(loginModel);
    }
 
    /**
     * 获取登录配置, 是否需要跳转、第三方登录信息
     *
     * @return {re}
     * @throws LoginException 登录异常
     */
    @NoDataSourceBind()
    @Operation(summary = "获取登录配置")
    @GetMapping("/getLoginConfig")
    public ActionResult<LoginConfigModel> getLoginConfig() {
        LoginConfigModel loginConfigModel = new LoginConfigModel();
        if (oauthConfig.getSsoEnabled()) {
            String url = oauthConfig.getLoginPath() + StrPool.SLASH + oauthConfig.getDefaultSSO();
            loginConfigModel.setRedirect(true);
            loginConfigModel.setUrl(url);
            loginConfigModel.setTicketParams(PARAMS_JNPF_TICKET);
        } else {
            //追加第三方登录配置
            List<SocialsUserVo> loginList = socialsUserApi.getLoginList(PARAMS_JNPF_TICKET.toUpperCase());
            if (CollectionUtil.isNotEmpty(loginList)) {
                loginConfigModel.setSocialsList(loginList);
                loginConfigModel.setRedirect(false);
                loginConfigModel.setTicketParams(PARAMS_JNPF_TICKET);
            }
        }
        return ActionResult.success(loginConfigModel);
    }
 
 
    /**
     * 获取登录票据
     *
     * @return {msg:有效期, data:票据}
     */
    @NoDataSourceBind()
    @Operation(summary = "获取登录票据")
    @GetMapping("/getTicket")
    public ActionResult<String> getTicket() {
        LoginTicketModel ticketModel = new LoginTicketModel();
        ticketModel.setTicketTimeout(System.currentTimeMillis() + oauthConfig.getTicketTimeout() * 1000);
        String ticket = TicketUtil.createTicket(ticketModel, oauthConfig.getTicketTimeout());
        return ActionResult.success(ticketModel.getTicketTimeout().toString(), ticket);
    }
 
    /**
     * 检测票据登录状态
     *
     * @return {re}
     * @throws LoginException
     */
    @NoDataSourceBind()
    @Operation(summary = "获取登录状态")
    @GetMapping("/getTicketStatus/{ticket}")
    public ActionResult<LoginTicketModel> getTicketStatus(@PathVariable("ticket") String ticket) {
        LoginTicketModel ticketModel = TicketUtil.parseTicket(ticket);
        if (ticketModel == null) {
            ticketModel = new LoginTicketModel().setStatus(LoginTicketStatus.Invalid.getStatus()).setValue("票据失效!");
        } else {
            if (ticketModel.getStatus() != LoginTicketStatus.UnLogin.getStatus()
                    && ticketModel.getStatus() != LoginTicketStatus.UnBind.getStatus()
                    && ticketModel.getStatus() != LoginTicketStatus.UnBindMes.getStatus()
                    && ticketModel.getStatus() != LoginTicketStatus.Multitenancy.getStatus()) {
                TicketUtil.deleteTicket(ticket);
            }
        }
        return ActionResult.success(ticketModel);
    }
 
    /**
     * 官网重置密码专用
     *
     * @return
     */
    @NoDataSourceBind()
    @Operation(summary = "官网重置密码专用")
    @GetMapping("/resetOfficialPassword/{mobile}/{code}")
    public ActionResult resetOfficialPassword(@PathVariable("mobile") String mobile, @PathVariable("code") String code) throws LoginException {
        //校验验证码
        TenantDataSourceUtil.checkOfficialSmsCode(mobile, code, 2);
        //切换租户
        LoginForm loginForm = new LoginForm();
        loginForm.setAccount(mobile);
        UserInfo userInfo = new UserInfo();
        userInfo.setUserAccount(loginForm.getAccount());
        try {
            userInfo = loginService.getTenantAccount(userInfo);
        } catch (Exception e) {
            return ActionResult.fail(MsgCode.LOG105.get());
        }
 
        // 重置密码 123456
        UserEntity userEntity = userDetailsServiceBuilder.getUserDetailService(AuthConsts.USERDETAIL_ACCOUNT).loadUserEntity(userInfo);
        userEntity.setPassword("e10adc3949ba59abbe56e057f20f883e");
        userEntity.setPassword(Md5Util.getStringMd5(userEntity.getPassword().toLowerCase() + userEntity.getSecretkey().toLowerCase()));
        boolean result = userApi.updateById(new UserUpdateModel(userEntity, userInfo.getTenantId()));
        if (result) {
            return ActionResult.success(MsgCode.LOG205.get());
        } else {
            return ActionResult.fail(MsgCode.LOG206.get());
        }
    }
 
    /**
     * 生成扫码凭证
     *
     * @return
     */
    @NoDataSourceBind()
    @Operation(summary = "生成扫码凭证")
    @GetMapping("/codeCertificate")
    public ActionResult codeCertificate() throws LoginException {
        ScanCodeLoginConfigModel ticketModel = new ScanCodeLoginConfigModel();
        ticketModel.setTicketTimeout(System.currentTimeMillis() + configValueUtil.getCodeCertificateTimeout() * 1000);
        String ticket = TicketUtil.createTicket(ticketModel, configValueUtil.getCodeCertificateTimeout());
        return ActionResult.success(ticketModel.getTicketTimeout().toString(), ticket);
    }
 
    /**
     * 获取扫码凭证状态
     *
     * @param ticket
     * @return
     * @throws LoginException
     */
    @NoDataSourceBind()
    @Operation(summary = "获取扫码凭证状态")
    @GetMapping("/codeCertificateStatus/{ticket}")
    public ActionResult codeCertificateStatus(@PathVariable("ticket") String ticket) throws LoginException {
        ScanCodeLoginConfigModel ticketModel = TicketUtil.parseTicket(ticket);
        if (ticketModel == null) {
            ticketModel = new ScanCodeLoginConfigModel();
            ticketModel.setStatus(ScanCodeTicketStatus.Invalid.getStatus());
        }
        return ActionResult.success(ticketModel);
    }
 
    /**
     * 确认登录
     *
     * @param ticket
     * @return
     * @throws LoginException
     */
    @NoDataSourceBind()
    @Operation(summary = "确认登录")
    @GetMapping("/confirmLogin/{ticket}")
    public ActionResult confirmLogin(@PathVariable("ticket") String ticket) throws LoginException {
        ScanCodeLoginConfigModel ticketModel = TicketUtil.parseTicket(ticket);
        if (ticketModel == null || !Objects.equals(ticketModel.getStatus(), 1)) {
            ticketModel = new ScanCodeLoginConfigModel();
            ticketModel.setStatus(ScanCodeTicketStatus.Invalid.getStatus());
            return ActionResult.success(ticketModel);
        }
        ticketModel.setStatus(ScanCodeTicketStatus.Success.getStatus());
        Map<String, String> parameters = new HashMap<>();
        parameters.put("grant_type", "scancode");
        parameters.put("token", UserProvider.getToken());
        ticketModel.setValue(authService.login(parameters).getData().getToken());
        TicketUtil.updateTicket(ticket, ticketModel, null);
        return ActionResult.success(ticketModel);
    }
 
    /**
     * 更改扫码凭证状态
     *
     * @param ticket
     * @return
     * @throws LoginException
     */
    @NoDataSourceBind()
    @Operation(summary = "更改扫码凭证状态")
    @GetMapping("/setCodeCertificateStatus/{ticket}/{status}")
    public ActionResult setCodeCertificateStatus(@PathVariable("ticket") String ticket, @PathVariable("status") Integer status) throws LoginException {
        ScanCodeLoginConfigModel ticketModel = TicketUtil.parseTicket(ticket);
        if (ticketModel == null) {
            ticketModel = new ScanCodeLoginConfigModel();
            ticketModel.setStatus(ScanCodeTicketStatus.Invalid.getStatus());
        } else {
            ticketModel.setStatus(status);
        }
        ticketModel.setTicketTimeout(System.currentTimeMillis() + configValueUtil.getCodeCertificateTimeout() * 1000);
        TicketUtil.updateTicket(ticket, ticketModel, configValueUtil.getCodeCertificateTimeout());
        return ActionResult.success(ticketModel);
    }
 
 
    /**
     * 获取用户登录信息
     *
     * @return
     * @throws LoginException 登录异常
     */
    @Operation(summary = "获取用户基本信息")
    @GetMapping("/me")
    public ActionResult<MeInfoVO> me() throws LoginException {
        UserInfo userInfo = UserProvider.getUser();
        MeInfoVO meInfoVO = new MeInfoVO()
                .setUserName(userInfo.getUserName())
                .setUserId(userInfo.getUserId())
                .setUserAccount(userInfo.getUserAccount())
                .setTenantId(userInfo.getTenantId());
        return ActionResult.success(meInfoVO);
    }
 
    @GetMapping("/white/jumpIndex")
    @NoDataSourceBind
    @Operation(summary = "跳转前端首页, 判断桌面端或者移动端跳转至不同的地址")
    public void jumpIndex() throws IOException {
        boolean isMobile = ServletUtil.getIsMobileDevice();
        if (isMobile) {
            ServletUtil.getResponse().sendRedirect(configValueUtil.getAppDomain());
        } else {
            ServletUtil.getResponse().sendRedirect(configValueUtil.getFrontDomain());
        }
    }
 
}