liurunyu
2 天以前 1cf88d43994ec7ec403319032a9d118b39fe3571
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
package com.dy.sso.busi;
 
import com.dy.common.aop.SsoVo;
import com.dy.common.multiDataSource.DataSourceContext;
import com.dy.common.util.MD5;
import com.dy.common.webUtil.BaseResponse;
import com.dy.common.webUtil.BaseResponseUtils;
import com.dy.common.webUtil.ResultCodeMsg;
import com.dy.pipIrrGlobal.pojoBa.BaUser;
import com.dy.pipIrrGlobal.util.Org;
import com.mysql.cj.util.StringUtils;
import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
 
import java.util.*;
 
/**
 * 注解Tag 在API中显示: Tag 注解, 给整个接口起了个名字与描述"
 * 注解ApiResponses 和 注解ApiResponse 用来配置响应;
 * 注解Operation 用来设置接口名称和描述;
 * 注解Parameter 用来设置请求参数的描述、是否必填和示例。
 */
@Slf4j
@Tag(name = "用户登录", description = "单点登录系统(sso)")
@RestController
@RequestMapping(path="sso")
@SuppressWarnings("unchecked")//java版本越高,对泛型约束越严,所以配置SuppressWarnings("unchecked")
public class SsoCtrl {
 
    //在属性上注解@Autowired时,会警告 Field injection is not recommended(不再推荐使用字段注入)
    private SsoSv sv ;
 
    //private KaptchaConfig kaptchaConfig;
    //@Autowired
    //private CacheManager cacheManager ;
 
    @Autowired
    public void setSv(SsoSv sv ){
        this.sv = sv ;
    }
 
    //@Autowired
    //public void setKaptchaConfig(KaptchaConfig kaptchaConfig) {
    //    this.kaptchaConfig = kaptchaConfig;
    //}
 
    /**
     * 客户端请求得到所有组织机构
     * @return 所有组织机构数据
     */
    @Operation(summary = "所有组织机构", description = "返回所有所有组织机构数据")
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = ResultCodeMsg.RsCode.SUCCESS_CODE,
                    description = "返回所有组织机构数据(BaseResponse.content:[ { \"tag\":\"ym\", \"name\":\"元谋\" }, { \"tag\":\"片角\", \"name\":\"片角镇\" }])",
                    content = {@Content(mediaType = MediaType.APPLICATION_JSON_VALUE,
                            schema = @Schema(implementation = Org.class))}
            )
    })
    @GetMapping(path = "allOrg")
    public BaseResponse<List<Org.OrgVo>> allOrg(){
        //List<Org> list = Arrays.asList(Org.Ym, Org.Pj) ;
        return BaseResponseUtils.buildSuccess(Org.OrgList);
    }
 
    /**
     * 客户端请求用户登录,客户端提交Json数据
     * @param vo 用户登录值对象
     * @param bindingResult 输入验证
     * @return 登录用户值对象
     */
    @Operation(summary = "单点登录", description = "提交登录用户值对象(json格式),进行单点登录")
    /*
    //下面这个不起作用,通过@RequestBody=直接显示LoginVo的API
    @io.swagger.v3.oas.annotations.parameters.RequestBody(
            //required = true,
            description = "form值对象",
            content = {@Content(mediaType = "application/json",
                    schema = @Schema(implementation = LoginVo.class))}
    )
    */
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = ResultCodeMsg.RsCode.SUCCESS_CODE,
                    description = "返回登录用户值对象(数据基类的content)",
                    content = {@Content(mediaType = MediaType.APPLICATION_JSON_VALUE,
                            schema = @Schema(implementation = UserVo.class))}
            )
    })
    @PostMapping(path = "loginJson", consumes = MediaType.APPLICATION_JSON_VALUE)
    public BaseResponse<UserVo> loginJson(HttpServletRequest request, @RequestBody @Parameter(description = "登录json数据", required = true) @Valid LoginVo vo,  @Parameter(hidden = true) BindingResult bindingResult) {
        if(bindingResult != null && bindingResult.hasErrors()){
            return BaseResponseUtils.buildErrorMsg(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        if(!vo.phone.equals("admin")){
            if(vo.phone.length() != 11){
                return BaseResponseUtils.buildErrorMsg("手机号(长度不是11位)不正确");
            }
        }
        if(vo.orgTag == null || vo.orgTag.trim().length() == 0){
            return BaseResponseUtils.buildErrorMsg("未选择组织单位");
        }
        if(vo.token == null || vo.token.trim().length() == 0){
            return BaseResponseUtils.buildErrorMsg("无token");
        }
        if(vo.code == null || vo.code.trim().length() == 0){
            return BaseResponseUtils.buildErrorMsg("请输入验证码");
        }
        //把组织单位标签作为数据源名称
        DataSourceContext.set(vo.orgTag);
 
        // 从数据库获取验证码
        Map map = sv.getCodeByToken(vo.token);
        Long expiration = Long.parseLong(map.get("expiration").toString());
        Long currentTimestamp = System.currentTimeMillis();
        if(currentTimestamp > expiration) {
            return BaseResponseUtils.buildErrorMsg("验证码已超时");
        }
        String localCode = map.get("code").toString();
        if(!vo.code.equals(localCode)) {
            return BaseResponseUtils.buildErrorMsg("验证码错误");
        }
 
        if(!sv.existPhone(vo.phone)){
            return BaseResponseUtils.buildErrorMsg("账号不存在");
        }
 
        String uuid4Token = null;
        BaUser userPo = null ;
        try {
            uuid4Token = UUID.randomUUID().toString();
            if(!StringUtils.isNullOrEmpty(vo.password)){
                /*
                如果前端进行了base64加密
                po.password = new String(Base64.getDecoder().decode(po.password)) ;
                */
                vo.password = MD5.encrypt(vo.password) ;
            }
            userPo = this.sv.loginWithMapperXml(uuid4Token, vo.phone, vo.password);
        } catch (Exception e) {
            log.error("用户登录异常", e);
            return BaseResponseUtils.buildException(e.getMessage()) ;
        }
 
        if(userPo != null){
            UserVo uVo = UserVoMapper.INSTANCT.po2vo(userPo);
            uVo.token = uuid4Token ;
            return BaseResponseUtils.buildSuccess(uVo);
        }else{
            return BaseResponseUtils.buildErrorMsg("登录失败");
        }
    }
 
    /**
     * 客户端请求用户登录,客户端提交form表单
     * @param vo 登录用户form表单对象
     * @return 登录用户值对象
     */
    @Operation(summary = "单点登录", description = "提交登录用户数据(form表单),进行单点登录")
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = ResultCodeMsg.RsCode.SUCCESS_CODE,
                    description = "返回登录用户值对象(数据基类的content)",
                    content = {@Content(mediaType = MediaType.APPLICATION_JSON_VALUE,
                            schema = @Schema(implementation = UserVo.class))}
            )
    })
    @PostMapping(path = "loginForm", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public BaseResponse<UserVo> loginForm(@Parameter(description = "form表单数据", required = true) @Valid LoginVo vo,  @Parameter(hidden = true) BindingResult bindingResult){
        if(bindingResult != null && bindingResult.hasErrors()){
            return BaseResponseUtils.buildErrorMsg(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        if(vo.orgTag == null || vo.orgTag.trim().length() == 0){
            return BaseResponseUtils.buildErrorMsg("未选择组织单位");
        }
        //把组织单位标签作为数据源名称
        DataSourceContext.set(vo.orgTag);
 
        String uuid ;
        BaUser userPo ;
        try {
            //Boolean flag = cacheManager.getCacheNames().isEmpty() ;
            uuid = UUID.randomUUID().toString();
            if(!StringUtils.isNullOrEmpty(vo.password)){
                /*
                如果前端进行了base64加密
                po.password = new String(Base64.getDecoder().decode(po.password)) ;
                */
                vo.password = MD5.encrypt(vo.password) ;
            }
            userPo = this.sv.loginWithMapperXml(uuid, vo.phone, vo.password);
        } catch (Exception e) {
            log.error("用户登录异常", e);
            return BaseResponseUtils.buildException(e.getMessage()) ;
        }
 
        if(userPo != null){
            UserVo uVo = UserVoMapper.INSTANCT.po2vo(userPo);
            uVo.token = uuid ;
            return BaseResponseUtils.buildSuccess(uVo);
        }else{
            return BaseResponseUtils.buildErrorMsg("登录失败");
        }
    }
 
    /**
     * 通过UUID退出登录,因为参数是uuid,所以此调用必须是后端相关代码调用,因为前端得不到cookie中的uuid
     * @param hr HttpServletRequest
     * @return 正常退出登录返回true,否则返回false
     */
    @Operation(summary = "单点登出", description = "提交token(在header中),进行单点登出")
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = ResultCodeMsg.RsCode.SUCCESS_CODE,
                    description = "返回处理结果(成功true,失败false)(数据基类的content)",
                    content = {@Content(mediaType = MediaType.TEXT_PLAIN_VALUE,
                            schema = @Schema(implementation = Boolean.class))}
            )
    })
    @GetMapping(path = "logout")
    public BaseResponse<Boolean> logout(@Parameter(hidden = true) HttpServletRequest hr){
        String token = hr.getHeader("token") ;
        if(token != null){
            this.sv.logout(token) ;
            return BaseResponseUtils.buildSuccess(true);
        }else{
            return BaseResponseUtils.buildErrorMsg("未从header中得到token");
        }
    }
 
    /**
     * 此方法供子模块系统调用,所以不公开在API接口中
     * 方法功能:得到登录用户id,否则返回null
     * @param token 登录用户token
     * @return 登录用户ID
     */
    @Hidden
    @GetMapping(path = "loginUserId")
    public Long loginUserId(String token){
        BaUser userPo = this.sv.getByUuid(token) ;
        return userPo == null ? null : userPo.id ;
    }
    /**
     * 此方法供子模块系统调用,所以不公开在API接口中
     * 方法功能:验证是否已经登录
     * @param token 登录用户token
     * @return SsoVo
     */
    @Hidden
    @GetMapping(path = "ssoCheck")
    public SsoVo ssoCheck(String token){
        BaUser userPo = this.sv.getByUuid(token) ;
        SsoVo vo = new SsoVo();
        if(userPo != null){
            vo.dataSourceName = userPo.orgTag ;
            vo.logined = true ;
            vo.hasPower = true ;//默认有权限。2023-12-21 经商议,由前端鉴权
        }else{
            vo.logined = false ;
            vo.hasPower = true ;//默认有权限。2023-12-21 经商议,由前端鉴权
        }
        return vo ;
    }
    /**
     * 此方法供子模块系统调用,所以不公开在API接口中
     * 方法功能:验证是否已经登录,如果登录了,再验证权限
     * @param token 登录用户token
     * @param privilege 验证一个权限
     * @param allPrivilege 验证所有权限
     * @param anyPrivilege 验证任何一个权限
     * @return SsoVo
     */
    @Hidden
    @GetMapping(path = "ssoPowerCheck")
    public SsoVo ssoPowerCheck(String token, String privilege, String[] allPrivilege, String[] anyPrivilege){
        BaUser userPo = this.sv.getByUuid(token) ;
        SsoVo vo = new SsoVo();
        if(userPo != null){
            vo.dataSourceName = userPo.orgTag ;
            vo.logined = true ;
            vo.hasPower = false ;//默认是无权限
            if(userPo.supperAdmin != null && userPo.supperAdmin == 1){
                vo.hasPower = true ;
            }else{
                if(privilege.equals("-1")){
                    //无需权限验证
                    vo.hasPower = true ;
                }else{
                    if(userPo.privileges != null && userPo.privileges.size() > 0){
                        vo.hasPower = this.hasOnePrivilege(privilege, userPo) ;
                        if(!vo.hasPower){
                            vo.hasPower = this.hasAllPrivilege(allPrivilege, userPo) ;
                            if(!vo.hasPower){
                                vo.hasPower = this.hasAnyPrivilege(anyPrivilege, userPo) ;
                            }
                        }
                    }
                }
            }
        }else{
            vo.logined = false ;
            vo.hasPower = false ;
        }
        return vo ;
    }
 
    /**
     * 获得当前登录用户
     * @param token 登录用户token
     * @return SsoVo
     */
    @Hidden
    @GetMapping(path = "ssoCurUser")
    public CurUserVo ssoCurUser(String token){
        BaUser userPo = this.sv.getByUuid(token) ;
        CurUserVo vo = new CurUserVo();
        if(userPo != null){
            vo.id = userPo.id ;
            vo.name = userPo.userName;
        }
        return vo ;
    }
    /////////////////////////////////////////////////////////////////
    //
    // 以下私有方法
    //
    /////////////////////////////////////////////////////////////////
    /**
     * 判断登录用户是否拥有指定的一个权限
     * @param privilege 指定的一个权限
     * @param userPo 当前登录用户
     * @return 是否有权限
     */
    private boolean hasOnePrivilege(String privilege, BaUser userPo){
        boolean hasPrivilege  = false ;
        if (privilege != null && !privilege.trim().equals("")) {
            int intPri = Integer.parseInt(privilege);
            for (Integer pri : userPo.privileges) {
                if (pri == intPri) {
                    hasPrivilege = true;
                    break;
                }
            }
        }
        return hasPrivilege ;
    }
 
    /**
     * 判断登录用户是否拥有指定的多个权限
     * @param allPrivilege 指定的多个权限
     * @param userPo 当前登录用户
     * @return 是否有权限
     */
    private boolean hasAllPrivilege(String[] allPrivilege, BaUser userPo){
        boolean hasPrivilege  = false ;
        if(allPrivilege != null && allPrivilege.length > 0){
            int intPri ;
            int count = 0 ;
            for(String strPri : allPrivilege){
                intPri = Integer.parseInt(strPri) ;
                for(Integer pri : userPo.privileges){
                    if(pri == intPri){
                        count++ ;
                        break ;
                    }
                }
            }
            if(count  == allPrivilege.length){
                hasPrivilege = true ;
            }
        }
        return hasPrivilege ;
    }
 
 
    /**
     * 判断登录用户是否拥有指定的某个权限
     * @param anyPrivilege 指定的多个权限
     * @param userPo 当前登录用户
     * @return 是否有权限
     */
    private boolean hasAnyPrivilege(String[] anyPrivilege, BaUser userPo){
        boolean hasPrivilege  = false ;
        int intPri ;
        if(anyPrivilege != null && anyPrivilege.length > 0){
            for(String strPri : anyPrivilege){
                intPri = Integer.parseInt(strPri) ;
                for(Integer pri : userPo.privileges){
                    if(pri == intPri){
                        hasPrivilege = true ;
                        break ;
                    }
                }
                if(hasPrivilege){
                    break ;
                }
            }
        }
        return hasPrivilege ;
    }
 
 
}