提交 | 用户 | 时间
|
e7c126
|
1 |
package com.iailab.module.system.service.oauth2; |
H |
2 |
|
|
3 |
import cn.hutool.core.util.IdUtil; |
|
4 |
import com.iailab.framework.common.util.date.DateUtils; |
|
5 |
import com.iailab.module.system.dal.dataobject.oauth2.OAuth2CodeDO; |
|
6 |
import com.iailab.module.system.dal.mysql.oauth2.OAuth2CodeMapper; |
|
7 |
import org.springframework.stereotype.Service; |
|
8 |
import org.springframework.validation.annotation.Validated; |
|
9 |
|
|
10 |
import javax.annotation.Resource; |
|
11 |
import java.time.LocalDateTime; |
|
12 |
import java.util.List; |
|
13 |
|
|
14 |
import static com.iailab.framework.common.exception.util.ServiceExceptionUtil.exception; |
|
15 |
import static com.iailab.module.system.enums.ErrorCodeConstants.OAUTH2_CODE_EXPIRE; |
|
16 |
import static com.iailab.module.system.enums.ErrorCodeConstants.OAUTH2_CODE_NOT_EXISTS; |
|
17 |
|
|
18 |
/** |
|
19 |
* OAuth2.0 授权码 Service 实现类 |
|
20 |
* |
|
21 |
* @author iailab |
|
22 |
*/ |
|
23 |
@Service |
|
24 |
@Validated |
|
25 |
public class OAuth2CodeServiceImpl implements OAuth2CodeService { |
|
26 |
|
|
27 |
/** |
|
28 |
* 授权码的过期时间,默认 5 分钟 |
|
29 |
*/ |
|
30 |
private static final Integer TIMEOUT = 5 * 60; |
|
31 |
|
|
32 |
@Resource |
|
33 |
private OAuth2CodeMapper oauth2CodeMapper; |
|
34 |
|
|
35 |
@Override |
|
36 |
public OAuth2CodeDO createAuthorizationCode(Long userId, Integer userType, String clientId, |
|
37 |
List<String> scopes, String redirectUri, String state) { |
|
38 |
OAuth2CodeDO codeDO = new OAuth2CodeDO().setCode(generateCode()) |
|
39 |
.setUserId(userId).setUserType(userType) |
|
40 |
.setClientId(clientId).setScopes(scopes) |
|
41 |
.setExpiresTime(LocalDateTime.now().plusSeconds(TIMEOUT)) |
|
42 |
.setRedirectUri(redirectUri).setState(state); |
|
43 |
oauth2CodeMapper.insert(codeDO); |
|
44 |
return codeDO; |
|
45 |
} |
|
46 |
|
|
47 |
@Override |
|
48 |
public OAuth2CodeDO consumeAuthorizationCode(String code) { |
|
49 |
OAuth2CodeDO codeDO = oauth2CodeMapper.selectByCode(code); |
|
50 |
if (codeDO == null) { |
|
51 |
throw exception(OAUTH2_CODE_NOT_EXISTS); |
|
52 |
} |
|
53 |
if (DateUtils.isExpired(codeDO.getExpiresTime())) { |
|
54 |
throw exception(OAUTH2_CODE_EXPIRE); |
|
55 |
} |
|
56 |
oauth2CodeMapper.deleteById(codeDO.getId()); |
|
57 |
return codeDO; |
|
58 |
} |
|
59 |
|
|
60 |
private static String generateCode() { |
|
61 |
return IdUtil.fastSimpleUUID(); |
|
62 |
} |
|
63 |
|
|
64 |
} |