AuthDefaultRequest.java 2.4 KB
Newer Older
1 2 3 4
package me.zhyd.oauth.request;

import lombok.Data;
import me.zhyd.oauth.config.AuthConfig;
5
import me.zhyd.oauth.config.AuthSource;
智布道's avatar
智布道 已提交
6
import me.zhyd.oauth.exception.AuthException;
智布道's avatar
智布道 已提交
7 8
import me.zhyd.oauth.model.*;
import me.zhyd.oauth.url.AuthDefaultUrlBuilder;
9
import me.zhyd.oauth.utils.AuthChecker;
10

11
/**
智布道's avatar
智布道 已提交
12 13
 * 默认的request处理类
 *
14 15 16 17 18
 * @author yadong.zhang (yadong.zhang0415(a)gmail.com)
 * @version 1.0
 * @since 1.8
 */
@Data
智布道's avatar
智布道 已提交
19
public abstract class AuthDefaultRequest implements AuthRequest {
20
    protected AuthConfig config;
21
    protected AuthSource source;
智布道's avatar
智布道 已提交
22
    protected AuthDefaultUrlBuilder urlBuilder;
23

智布道's avatar
智布道 已提交
24
    public AuthDefaultRequest(AuthConfig config, AuthSource source) {
25
        this.config = config;
26
        this.source = source;
27
        if (!AuthChecker.isSupportedAuth(config, source)) {
智布道's avatar
智布道 已提交
28
            throw new AuthException(AuthResponseStatus.PARAMETER_INCOMPLETE);
智布道's avatar
智布道 已提交
29
        }
30
        // 校验配置合法性
31
        AuthChecker.checkConfig(config, source);
32
    }
33

智布道's avatar
智布道 已提交
34
    public AuthDefaultRequest(AuthConfig config, AuthSource source, AuthDefaultUrlBuilder urlBuilder) {
35 36
        this(config, source);
        this.urlBuilder = urlBuilder;
智布道's avatar
智布道 已提交
37
        this.urlBuilder.setAuthConfig(config);
38 39
    }

40
    protected abstract AuthToken getAccessToken(AuthCallback authCallback);
41

42
    protected abstract AuthUser getUserInfo(AuthToken authToken);
43 44

    @Override
45
    public AuthResponse login(AuthCallback authCallback) {
46
        try {
智布道's avatar
智布道 已提交
47
            AuthChecker.checkCode(source == AuthSource.ALIPAY ? authCallback.getAuth_code() : authCallback.getCode());
48 49 50
            AuthChecker.checkState(authCallback.getState(), config.getState());

            AuthToken authToken = this.getAccessToken(authCallback);
51
            AuthUser user = this.getUserInfo(authToken);
智布道's avatar
智布道 已提交
52
            return AuthResponse.builder().code(AuthResponseStatus.SUCCESS.getCode()).data(user).build();
53
        } catch (Exception e) {
54
            return this.responseError(e);
55
        }
56 57
    }

58
    private AuthResponse responseError(Exception e) {
智布道's avatar
智布道 已提交
59
        int errorCode = AuthResponseStatus.FAILURE.getCode();
60 61 62 63 64 65
        if (e instanceof AuthException) {
            errorCode = ((AuthException) e).getErrorCode();
        }
        return AuthResponse.builder().code(errorCode).msg(e.getMessage()).build();
    }

66 67 68 69 70
    /**
     * 返回认证url,可自行跳转页面
     *
     * @return 返回授权地址
     */
71
    @Override
72
    public String authorize() {
智布道's avatar
智布道 已提交
73
        return this.urlBuilder.getAuthorizeUrl();
74
    }
75
}