刘光辉
15 小时以前 34981c30a78e8bbd7791131059a9210f9928b62c
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
package jnpf.service.impl;
 
import jnpf.base.ActionResult;
import jnpf.base.LogApi;
import jnpf.base.UserInfo;
import jnpf.base.model.logmodel.WriteLogModel;
import jnpf.constant.MsgCode;
import jnpf.exception.LoginException;
import jnpf.exception.TenantDatabaseException;
import jnpf.exception.TenantInvalidException;
import jnpf.granter.TokenGranter;
import jnpf.granter.TokenGranterBuilder;
import jnpf.model.LoginVO;
import jnpf.model.logout.LogoutResultModel;
import jnpf.service.AuthService;
import jnpf.util.RedisUtil;
import jnpf.util.StringUtil;
import jnpf.util.TenantProvider;
import jnpf.util.UserProvider;
import jnpf.utils.LoginHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
 
import java.util.Map;
 
/**
 * 登录与退出服务 其他服务调用
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {
 
    @Lazy
    private final TokenGranterBuilder tokenGranterBuilder;
 
    private final LogApi logApi;
 
    private final RedisUtil redisUtil;
 
    /**
     * 登录
     * @param parameters {grant_type}
     * @return
     * @throws LoginException
     */
    @Override
    public ActionResult<LoginVO> login(Map<String, String> parameters) throws LoginException{
        long millis = System.currentTimeMillis();
        TokenGranter tokenGranter = tokenGranterBuilder.getGranter(parameters.getOrDefault("grant_type", ""));
        ActionResult<LoginVO> result;
        UserInfo userInfo = new UserInfo();
        try {
            String account = parameters.get("account");
            userInfo.setUserAccount(account);
            UserProvider.setLocalLoginUser(userInfo);
            result = tokenGranter.granter(parameters);
            //写入日志
            if (userInfo.getUserId() != null && !UserProvider.isTempUser(userInfo)) {
                logApi.writeLogAsync(WriteLogModel.builder()
                        .userId(userInfo.getUserId())
                        .userInfo(userInfo)
                        .userName(userInfo.getUserName() + "/" + userInfo.getUserAccount())
                        .abstracts(MsgCode.OA015.get())
                        .loginMark(1)
                        .requestDuration(System.currentTimeMillis() - millis).build());
            }
        } catch (TenantDatabaseException tdex){
            throw tdex;
        } catch (Exception e){
            if(!(e instanceof LoginException || e instanceof TenantInvalidException)){
                String msg = e.getMessage();
                if(msg == null){
                    msg = MsgCode.OA007.get();
                }
                log.error(MsgCode.OA007.get()+", Account: {}, Error: {}", parameters.getOrDefault("account", ""), e.getMessage(), e);
                throw new LoginException(msg);
            }
            String userName = StringUtil.isNotEmpty(userInfo.getUserName()) ? userInfo.getUserName()+"/"+userInfo.getUserAccount() : userInfo.getUserAccount();
            logApi.writeLogAsync(WriteLogModel.builder()
                    .userId(userInfo.getUserId())
                    .userName(userName)
                    .abstracts(e.getMessage())
                    .userInfo(userInfo)
                    .loginMark(0)
                    .requestDuration(System.currentTimeMillis()-millis).build());
            throw e;
        }finally{
            LoginHolder.clearUserEntity();
            TenantProvider.clearBaseSystemIfo();
            // 请求之后就删除验证码 不论结果
            String imgCode = parameters.get("timestamp");
            if(StringUtil.isNotEmpty(imgCode)) {
                redisUtil.remove(imgCode);
            }
        }
        return result;
    }
 
 
    /**
     * 踢出用户, 用户将收到Websocket下线通知
     * 执行流程:认证服务退出用户->用户踢出监听->消息服务发送Websocket推送退出消息
     * @param tokens
     */
    @Override
    public ActionResult<Object> kickoutByToken(String... tokens){
        UserProvider.kickoutByToken(tokens);
        return ActionResult.success();
    }
 
    /**
     * 踢出用户, 用户将收到Websocket下线通知
     * 执行流程:认证服务退出用户->用户踢出监听->消息服务发送Websocket推送退出消息
     * @param userId
     * @param tenantId
     */
    @Override
    public ActionResult<Object> kickoutByUserId(String userId, String tenantId){
        UserProvider.kickoutByUserId(userId, tenantId);
        return ActionResult.success();
    }
 
    /**
     * 退出登录
     * @param grandtype
     * @return
     */
    @Override
    public ActionResult<LogoutResultModel> logout(String grandtype) {
        long millis = System.currentTimeMillis();
        TokenGranter tokenGranter = tokenGranterBuilder.getGranterByLogin(grandtype);
        if(tokenGranter != null){
            UserInfo userInfo = UserProvider.getUser();
            logApi.writeLogAsync(WriteLogModel.builder()
                    .userId(userInfo.getUserId())
                    .userName(userInfo.getUserName() + "/" + userInfo.getUserAccount())
                    .abstracts("退出登录")
                    .userInfo(userInfo)
                    .loginMark(1)
                    .loginType(1)
                    .requestDuration(System.currentTimeMillis()-millis).build());
            return tokenGranter.logout();
        }
        return ActionResult.success();
    }
}