郑永安
2023-06-19 f65443d8abeaedc9d102324565e8368e7c9d90c8
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
package com.gk.firework.Controller;
 
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gk.firework.Config.Oauth2.IRedisService;
import com.gk.firework.Config.Oauth2.OauthRole;
import com.gk.firework.Config.Oauth2.RedisKeyEnum;
import com.gk.firework.Domain.AuthorizationInfo;
import com.gk.firework.Domain.Log.JsonParams;
import com.gk.firework.Domain.Utils.CommonUtil;
import com.gk.firework.Domain.Utils.Msg;
import com.gk.firework.Domain.Utils.StringUtils;
import com.gk.firework.Domain.Vo.UserVo;
import com.gk.firework.Service.AuthorizationService;
import com.gk.firework.Service.EnterpriseService;
import com.gk.firework.Service.UserService;
import com.google.common.base.Strings;
import com.google.common.net.HttpHeaders;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.map.SingletonMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
 
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.*;
 
@Api(tags = "登录登出接口")
@RequestMapping("/auth")
@RestController
public class LoginController {
    @Autowired
    IRedisService redisService;
    @Autowired
    UserService userService;
    @Autowired
    AuthorizationService authorizationService;
    @Autowired
    EnterpriseService enterpriseService;
    @Value("${host}")
    private String host;
    /**
     * login  produces = "application/json"
     *
     * @param jsonParam {"username":"用户名","password":"密码"}
     * @return User
     */
    @PostMapping("/login")
    @JsonParams
    @ApiOperation(value = "管理端登录授权", notes = "登录授权接口,获取token")
    public Msg login(@ApiParam(value = "username,password") @RequestParam String encryptStr) {
        String jsonStr = new String(Base64.getDecoder().decode(encryptStr), StandardCharsets.UTF_8);
        JSONObject jsonParam = JSON.parseObject(jsonStr);
 
        String username = jsonParam.getString("username");
        String password = jsonParam.getString("password");
 
        Msg msg = new Msg();
        msg.setCode("200");
        msg.setMessage("success");
        try {
            //query user
            UserVo user = userService.selectUserVoByName(username);
            if (null == user) {
                msg.setCode("100");
                msg.setMessage("用户不存在");
                return msg;
            }
 
            if (user.getIssale() == 1) {
                msg.setCode("100");
                msg.setMessage("用户不存在");
                return msg;
            }
 
            if (StringUtils.isNotBlank(user.getCompanynumber()) && enterpriseService.isLogOut(user.getCompanynumber())) {
                msg.setCode("166");
                msg.setMessage("用户已注销");
                return msg;
            }
            // 疆外日期判断
            Date now = new Date();
            if (user.getDeadline() != null) {
                if (user.getDeadline().before(now)){
                    // 当前已经疆外用户已经超期使用 需要缴费
                    msg.setCode("200");
                    msg.setMessage("疆外用户已过期,请及时联系续期");
                    msg.setResult(new SingletonMap<>("deadline",user.getDeadline()));
                    return msg;
                }
 
            }
 
 
            //Call login interface
            String rs = HttpRequest.post( host + "/oauth/token")
                    .setConnectionTimeout(10000)
                    .setReadTimeout(10000)
                    .header("Authorization", "Basic dWFhLXNlcnZpY2U6MTIzNDU2")
                    .form(Dict.create()
                            .set("username", username)
                            .set("password", password)
                            .set("grant_type", "password")
                            .set("auth_type", "")
                    ).execute().body();
            Map map = JSON.parseObject(rs, Map.class);
            Object access_token = map.get("access_token");
            //Verify that the access_token is empty
            if (ObjectUtil.isNull(access_token)) {
                msg.setCode("103");
                msg.setMessage("密码不正确");
                return msg;
            }
            user.setToken("Bearer "+access_token);
            //add redis
            String token_key = StrUtil.format(RedisKeyEnum.AUTH_TOKEN.getKey(), map.get("jti"));
            redisService.set(token_key, user, 60L*60L*18L);
 
            user.setTokenexpired(60L*60L*18L);
            /** 登录成功刷新用户 */
            List<OauthRole> roleByUser = userService.selectRoleByUser(1);
            if (null != user.getType()&& user.getType() == 1){
                OauthRole oauthRole = new OauthRole("","超级管理员","super_admin","");
                roleByUser.add(oauthRole);
                user.setRoles(roleByUser);
            }else {
                roleByUser = userService.selectRoleByUser(user.getId().intValue());
                user.setRoles(roleByUser);
            }
            user.setPassword(null);
            msg.setResult(user);
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode("102");
            msg.setMessage("登录失败请稍后重试");
        }
        return msg;
    }
 
    @PostMapping("/salelogin")
    @ApiOperation(value = "销售端登录授权", notes = "登录授权接口,获取token")
    public Msg Salelogin(@ApiParam(value = "username,password") @RequestBody JSONObject jsonParam) {
        String username = jsonParam.getString("username");
        String password = jsonParam.getString("password");
 
        Msg msg = new Msg();
        msg.setCode("200");
        msg.setMessage("success");
        try {
            //query user
            UserVo user = userService.selectUserVoByName(username);
            if (null == user) {
                msg.setCode("100");
                msg.setMessage("用户不存在");
                return msg;
            }
 
            if (user.getIssale() == 0) {
                msg.setCode("100");
                msg.setMessage("用户不存在");
                return msg;
            }
 
            if (user.getStatus()!=null && user.getStatus() != 1){
                msg.setCode("100");
                msg.setMessage("用户已失效");
                return msg;
            }
 
            if (user.getExpiredate() != null && user.getExpiredate().getTime() < System.currentTimeMillis()){
                msg.setCode("100");
                msg.setMessage("用户已失效");
                return msg;
            }
 
            // 疆外日期判断
            Date now = new Date();
            if (user.getDeadline() != null) {
                if (user.getDeadline().before(now)) {
                    // 当前已经疆外用户已经超期使用 需要缴费
                    msg.setCode("166");
                    msg.setMessage("疆外用户已过期,请及时联系续期");
                    return msg;
                }
 
            }
            //Call login interface
            String rs = HttpRequest.post( host + "/oauth/token")
                    .setConnectionTimeout(10000)
                    .setReadTimeout(10000)
                    .header("Authorization", "Basic dWFhLXNlcnZpY2U6MTIzNDU2")
                    .form(Dict.create()
                            .set("username", username)
                            .set("password", password)
                            .set("grant_type", "password")
                            .set("auth_type", "")
                    ).execute().body();
            Map map = JSON.parseObject(rs, Map.class);
            Object access_token = map.get("access_token");
            //Verify that the access_token is empty
            if (ObjectUtil.isNull(access_token)) {
                msg.setCode("103");
                msg.setMessage("密码不正确");
                return msg;
            }
            user.setToken("Bearer "+access_token);
            //add redis
            String token_key = StrUtil.format(RedisKeyEnum.AUTH_TOKEN.getKey(), map.get("jti"));
            redisService.set(token_key, user, 60L*60L*18L);
            user.setTokenexpired(60L*60L*18L);
            user.setPassword(null);
            msg.setResult(user);
        } catch (Exception e) {
            msg.setCode("102");
            msg.setMessage("登录失败请稍后重试");
        }
        return msg;
    }
 
    @GetMapping("/verify")
    @ApiOperation(value = "登录验证", notes = "登录验证:flag【true 成功】,【false 失败】", response = Msg.class)
    public Msg verifyLogin(@ApiIgnore HttpServletRequest request) {
        Msg msg = new Msg();
        msg.setCode("200");
        UserVo userVo = new UserVo();
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        //解析token
        Claims claims = CommonUtil.parseJWT(token);
        if (null != claims){
            String tokenKey = StrUtil.format(RedisKeyEnum.AUTH_TOKEN.getKey(), claims.getId());
            Object userInfo = redisService.get(tokenKey);
            if (null != userInfo){
                Map map = JSON.parseObject(userInfo.toString(), Map.class);
 
                userVo = userService.selectUserVoByName(map.get("username").toString());
                if (null == userVo) {
                    msg.setCode("100");
                    msg.setMessage("用户不存在");
                    return msg;
                }
 
                if (userVo.getIssale() == 1){
                    if (userVo.getStatus()!=null && userVo.getStatus() != 1){
                        msg.setCode("100");
                        msg.setMessage("用户已失效");
                        return msg;
                    }
 
                    if (userVo.getExpiredate() != null && userVo.getExpiredate().getTime() < System.currentTimeMillis()){
                        msg.setCode("100");
                        msg.setMessage("用户已失效");
                        return msg;
                    }
 
                    Object loginObj =  map.get("logintime");
                    Object authObj =  map.get("auth");
                    if (loginObj != null && authObj != null){
                        //通过auth查询授权码最后登录时间
                        AuthorizationInfo authInfo = authorizationService.selectByUser(userVo.getCompanynumber(),authObj.toString());
                        if (authInfo == null){
                            msg.setCode("100");
                            msg.setMessage("授权码无效");
                            return msg;
                        }
 
                        if (authInfo.getLasttime().getTime() > Long.parseLong(loginObj.toString())){
                            redisService.set(tokenKey, userInfo, 0L);
                            msg.setCode("100");
                            msg.setMessage("登录失效,请重新登录");
                            return msg;
                        }
                    }
                    userVo.setAuth(map.get("auth").toString());
                }
                else {
                    /** 登录成功刷新用户 */
                    List<OauthRole> roleByUser = userService.selectRoleByUser(1);
                    if (null != userVo.getType()&& userVo.getType() == 1){
                        OauthRole oauthRole = new OauthRole("","超级管理员","super_admin","");
                        roleByUser.add(oauthRole);
                        userVo.setRoles(roleByUser);
                    }else {
                        roleByUser = userService.selectRoleByUser(userVo.getId().intValue());
                        userVo.setRoles(roleByUser);
                    }
                }
                userVo.setToken(map.get("token").toString());
                userVo.setTokenexpired(60L*60L*18L);
                userVo.setPassword(null);
                //更新登录超时时间
                redisService.set(tokenKey, userInfo, 60L*60L*18L);
            }else {
                msg.setCode("100");
                msg.setMessage("登录失效,请重新登录");
                return msg;
            }
        }
        msg.setResult(userVo);
        return msg;
    }
 
    /**
     * logout
     *
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation(value = "退出登录", notes = "退出登录接口", produces = "application/json", response = Msg.class)
    public Msg logout(@ApiIgnore HttpServletRequest request) {
        Msg msg = new Msg();
        msg.setCode("200");
        msg.setMessage("success");
        /** 解析token */
        String header = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (header != null && !header.equals("undefined")) {
            Claims claims = CommonUtil.parseJWT(header);
            Optional.ofNullable(claims).ifPresent(cl -> {
                String token_key = "auth:token:" + cl.getId();
                redisService.remove(token_key);
            });
        }
        return msg;
    }
 
    @PostMapping("/saleauthlogin")
    @JsonParams
    @ApiOperation(value = "销售端授权码登录授权", notes = "登录授权接口,获取token")
    public Msg SaleAuthlogin(@ApiParam(value = "username,password,authcode") @RequestParam String encryptStr) {
//        System.out.println("BASE64明文: "+encryptStr);
        String jsonStr = new String(Base64.getDecoder().decode(encryptStr), StandardCharsets.UTF_8);
//        System.out.println("解密后参数: "+jsonStr);
        JSONObject jsonParam = JSON.parseObject(jsonStr);
        String username = jsonParam.getString("username");
        String password = jsonParam.getString("password");
        String auth = jsonParam.getString("authcode");
 
//        System.out.println("name: "+username+" ,pwd: "+password+" ,auth:"+auth);
 
        Msg msg = new Msg();
        msg.setCode("200");
        msg.setMessage("success");
        try {
            //query user
            UserVo user = userService.selectUserVoByName(username);
            if (null == user) {
                msg.setCode("100");
                msg.setMessage("用户不存在");
                return msg;
            }
 
            if (user.getIssale() == 0) {
                msg.setCode("100");
                msg.setMessage("用户不存在");
                return msg;
            }
 
            if (user.getStatus()!=null && user.getStatus() != 1){
                msg.setCode("100");
                msg.setMessage("用户已失效");
                return msg;
            }
 
            if (user.getExpiredate() == null ||(user.getExpiredate() != null && user.getExpiredate().getTime() < System.currentTimeMillis())){
                msg.setCode("100");
                msg.setMessage("用户已失效");
                return msg;
            }
 
            // 疆外日期判断
            Date now = new Date();
            if (user.getDeadline() != null) {
                if (user.getDeadline().before(now)) {
                    // 当前已经疆外用户已经超期使用 需要缴费
                    msg.setCode("166");
                    msg.setMessage("疆外用户已过期,请及时联系续期");
                    return msg;
                }
 
            }
 
            //验证auth是否存在
            AuthorizationInfo authInfo = authorizationService.selectByUser(user.getCompanynumber(),auth);
            if (authInfo == null){
                msg.setCode("100");
                msg.setMessage("授权码无效");
                return msg;
            }
 
            Date logintime = new Date();
            //Call login interface
            String rs = HttpRequest.post( host + "/oauth/token")
                    .setConnectionTimeout(10000)
                    .setReadTimeout(10000)
                    .header("Authorization", "Basic dWFhLXNlcnZpY2U6MTIzNDU2")
                    .form(Dict.create()
                            .set("username", username)
                            .set("password", password)
                            .set("auth", auth)
                            .set("grant_type", "password")
                            .set("auth_type", "")
                    )
                    .execute()
                    .body();
            Map map = JSON.parseObject(rs, Map.class);
            Object access_token = map.get("access_token");
            //Verify that the access_token is empty
            if (ObjectUtil.isNull(access_token)) {
                msg.setCode("103");
                msg.setMessage("密码不正确");
                return msg;
            }
            user.setToken("Bearer "+access_token);
            user.setAuth(auth);
            user.setLogintime(logintime.getTime());
            //add redis
            String token_key = StrUtil.format(RedisKeyEnum.AUTH_TOKEN.getKey(), map.get("jti"));
            redisService.set(token_key, user, 60L*60L*18L);
            user.setTokenexpired(60L*60L*18L);
            user.setPassword(null);
            msg.setResult(user);
 
            //更新auth最后登录时间
            authInfo.setLasttime(logintime);
            authorizationService.updateById(authInfo);
        } catch (Exception e) {
            msg.setCode("102");
            msg.setMessage("登录失败请稍后重试");
        }
        return msg;
    }
 
 
}