cloudroam
2024-12-09 3566668d97d3844d4d4b95c0058a0f5cb9e5db07
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
package com.mzl.flower.web.login;
 
import cn.hutool.core.util.StrUtil;
import com.mzl.flower.base.BaseController;
import com.mzl.flower.base.R;
import com.mzl.flower.base.ReturnDataDTO;
import com.mzl.flower.base.cache.StringCacheClient;
import com.mzl.flower.config.exception.BaseException;
import com.mzl.flower.config.exception.ValidationException;
import com.mzl.flower.config.security.token.PhoneAuthenticationToken;
import com.mzl.flower.config.security.token.SupAuthenticationToken;
import com.mzl.flower.constant.Constants;
import com.mzl.flower.dto.request.UserLoginDTO;
import com.mzl.flower.dto.response.supplier.SupplierDTO;
import com.mzl.flower.entity.supplier.SupplierSub;
import com.mzl.flower.entity.system.User;
import com.mzl.flower.mapper.supplier.SupplierMapper;
import com.mzl.flower.mapper.supplier.SupplierSubMapper;
import com.mzl.flower.service.login.LoginService;
import com.mzl.flower.service.system.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import javax.servlet.http.HttpServletRequest;
 
@Slf4j
@RestController
@RequestMapping("/api")
@Api(value = "供应商登录", tags = "供应商登录")
public class SupplierLoginController extends BaseController {
 
    private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new WebAuthenticationDetailsSource();
 
    @Autowired
    private AuthenticationManager authenticationManager;
 
    @Autowired
    private LoginService loginService;
 
    @Autowired
    private StringCacheClient stringCacheClient;
 
    @Autowired
    private UserService userService;
 
    @Autowired
    private TokenStore tokenStore;
 
    @Autowired
    private SupplierMapper supplierMapper;
 
    @Autowired
    private SupplierSubMapper supplierSubMapper;
 
 
 
    public static final String SMS_CODE_KEY = "SMS-CODE-KEY";
 
    public static final String TOKEN_KEY = "TOKEN-KEY";
 
    public static final String SEPARATOR = ":";
 
    @PostMapping("/login/supplier")
    @ApiOperation(value = "供应商账号密码登录", notes = "供应商账号密码登录")
    public ResponseEntity<ReturnDataDTO<OAuth2AccessToken>> loginPerson(HttpServletRequest request
            , @RequestBody UserLoginDTO loginDTO) {
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();
        if (StringUtils.isBlank(username)) {
            throw new ValidationException("用户名不能为空");
        }
        if (StringUtils.isBlank(password)) {
            throw new ValidationException("密码不能为空");
        }
        User user = userService.findByTel(username, Constants.USER_TYPE.supplier.name());
        if(user == null){
            throw new ValidationException("用户不存在");
        }
        // 子账号校验:1.不存在->放行。
        // 2.存在->校验是否已经禁用。
        // 3.存在且未禁用->校验父级账号是否禁用。
        // 4.父级禁用->提示
        // 5.父级未禁用->保存子账号token并返回
        SupplierSub supplierSub = supplierSubMapper.getCurrentSupplier(user.getId());
        if (supplierSub != null) {
            if (supplierSub.getIsEnabled() == false) {
                throw new ValidationException("子账号已禁用,请联系父级账号");
            }else{
                //这里拿父级供应商ID查询用户ID再校验
                SupplierDTO supplierDTO = supplierMapper.getCurrentSupplier(String.valueOf( supplierSub.getSupplierId()));
                if (supplierDTO != null && supplierDTO.getIsEnabled() == false) {
                    throw new ValidationException("父级账号用户已禁用,请联系管理员");
                }
            }
        }else {
            SupplierDTO supplierDTO = supplierMapper.getCurrentSupplier(user.getId());
            if (supplierDTO != null && supplierDTO.getIsEnabled() == false) {
                throw new ValidationException("用户已禁用,请联系管理员");
            }
        }
        String tokenCache = stringCacheClient.get(TOKEN_KEY + SEPARATOR + user.getId());
        if (StringUtils.isNotBlank(tokenCache))  {
            //强制删除token,下线
            removeToken(tokenCache,user.getId());
        }
        try {
            SupAuthenticationToken authRequest = new SupAuthenticationToken(username, password);
            authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
            Authentication authentication = authenticationManager.authenticate(authRequest);
            OAuth2AccessToken token = loginService.getAccessToken(authentication,Constants.USER_TYPE.supplier.name());
            stringCacheClient.set(TOKEN_KEY + SEPARATOR + user.getId(),token.getValue());
            return returnData(R.SUCCESS.getCode(),token);
        }catch (BadCredentialsException e){
            throw new ValidationException("用户名或密码错误");
        }catch (UsernameNotFoundException e){
            throw new ValidationException("用户不存在");
        }catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BaseException(R.RUNTIME_EXCEPTION.getCode(),"登录错误");
        }
    }
 
    @PostMapping("/login/supplier/phone")
    @ApiOperation(value = "手机验证码登录系统", notes = "手机验证码登录系统")
    public ResponseEntity<ReturnDataDTO<OAuth2AccessToken>>  loginPhone(HttpServletRequest request,
                                                                        @RequestBody UserLoginDTO loginDTO) {
        String tel = loginDTO.getUsername();
        String smsCode = loginDTO.getSmsCode();
        if (StringUtils.isBlank(tel)) {
            throw new ValidationException("手机号码不能为空");
        }
        if (StringUtils.isBlank(smsCode)) {
            throw new ValidationException("手机验证码不能为空");
        }
        //从缓存中获取验证码
        String smsCacheCode = stringCacheClient.get(SMS_CODE_KEY + SEPARATOR + Constants.USER_TYPE.supplier.name() + SEPARATOR + tel);
        if (!StringUtils.equals(smsCode, smsCacheCode)) {
            throw new ValidationException("手机验证码不正确");
        }
        User user = userService.findByTel(tel, Constants.USER_TYPE.supplier.name());
        if(user == null){
            throw new ValidationException("用户不存在");
        }
        // 子账号校验:1.不存在->放行。
        // 2.存在->校验是否已经禁用。
        // 3.存在且未禁用->校验父级账号是否禁用。
        // 4.父级禁用->提示
        // 5.父级未禁用->保存子账号token并返回
        SupplierSub supplierSub = supplierSubMapper.getCurrentSupplier(user.getId());
        if (supplierSub != null) {
            if (supplierSub.getIsEnabled() == false) {
                throw new ValidationException("子账号已禁用,请联系父级账号");
            } else {
                //这里拿父级供应商ID查询用户ID再校验
                SupplierDTO supplierDTO = supplierMapper.getCurrentSupplier(String.valueOf(supplierSub.getSupplierId()));
                if (supplierDTO != null && supplierDTO.getIsEnabled() == false) {
                    throw new ValidationException("父级账号用户已禁用,请联系管理员");
                }
            }
        } else {
            SupplierDTO supplierDTO = supplierMapper.getCurrentSupplier(user.getId());
            if (supplierDTO != null && supplierDTO.getIsEnabled() == false) {
                throw new ValidationException("用户已禁用,请联系管理员");
            }
        }
        String tokenCache = stringCacheClient.get(TOKEN_KEY + SEPARATOR + user.getId());
        if (StringUtils.isNotBlank(tokenCache))  {
            //强制删除token,下线
            removeToken(tokenCache,user.getId());
        }
        try {
            PhoneAuthenticationToken authRequest = new PhoneAuthenticationToken(tel, smsCode, Constants.USER_TYPE.supplier.name());
            authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
            Authentication authentication = authenticationManager.authenticate(authRequest);
            OAuth2AccessToken token = loginService.getAccessToken(authentication, Constants.USER_TYPE.supplier.name());
            //删除缓存中的验证码
            stringCacheClient.delete(SMS_CODE_KEY + SEPARATOR + Constants.USER_TYPE.supplier.name() + SEPARATOR + tel);
            stringCacheClient.set(TOKEN_KEY + SEPARATOR + user.getId(),token.getValue());
            return returnData(R.SUCCESS.getCode(),token);
        }catch (UsernameNotFoundException e){
            throw new ValidationException("手机号未注册");
        }catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BaseException(R.RUNTIME_EXCEPTION.getCode(),"登录错误");
        }
    }
 
    public void removeToken(String token,String userId) {
        if (StringUtils.isNotBlank(token) && StringUtils.isNotBlank(userId))  {
            stringCacheClient.delete(TOKEN_KEY + SEPARATOR + userId);
            String tokenValue = token.replace(OAuth2AccessToken.BEARER_TYPE, StrUtil.EMPTY).trim();
            OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
            if (accessToken != null && StringUtils.isNotBlank(accessToken.getValue())) {
                tokenStore.removeAccessToken(accessToken);
                OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
                tokenStore.removeRefreshToken(refreshToken);
            }
        }
    }
}