zhanghua
2023-11-02 46251c20b66bb1ca05058ae63a92a195e5543b90
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
package com.ycl.utils.auth;
 
import cn.hutool.core.util.StrUtil;
import com.ycl.entity.auth.AuthInfo;
import com.ycl.enums.common.ResultCode;
import com.ycl.exception.ApiException;
import com.ycl.service.redis.RedisService;
import com.ycl.utils.JwtTokenUtil;
import com.ycl.utils.common.LiveTimeMillisecond;
import com.ycl.utils.common.NetworkUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
 
/**
 * @author Lyq
 * @version 1.0
 * @date 2022/9/9
 */
@Component("userAuthUtil")
public class UserAuthUtil {
    @Resource
    private JwtTokenUtil jwtTokenUtil;
    @Resource
    private RedisService redisService;
 
    @Value("${jwt.tokenHead}")
    private String tokenHead;
 
    public void saveUser(Long userId, String token, String redisKey) {
        redisService.set(redisKey.concat(userId.toString()), token, LiveTimeMillisecond.s2592000.time);
    }
 
    /**
     * 获取操作员id
     *
     * @param request
     * @return
     */
    public long fetchUserId(HttpServletRequest request) {
        String accessToken = NetworkUtil.getAccessToken(request);
        if (StrUtil.isBlank(accessToken)) {
            throw new ApiException(ResultCode.NOT_LOGGED);
        }
        String authToken = accessToken.substring(this.tokenHead.length());// The part after "Bearer "
        AuthInfo authInfo = jwtTokenUtil.parseToken(authToken);
        return authInfo.getUserId();
    }
 
    /**
     * 获取操作员姓名
     *
     * @param request
     * @return
     */
    public String fetchUserName(HttpServletRequest request) {
        String accessToken = NetworkUtil.getAccessToken(request);
        if (StrUtil.isBlank(accessToken)) {
            throw new ApiException(ResultCode.NOT_LOGGED);
        }
        String authToken = accessToken.substring(this.tokenHead.length());// The part after "Bearer "
        AuthInfo authInfo = jwtTokenUtil.parseToken(authToken);
//        AuthInfo authInfo = jwtTokenUtil.parseToken(accessToken);
        return authInfo.getUsername();
    }
}