BaseAuthRequest.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;
7
import me.zhyd.oauth.model.AuthCallback;
8
import me.zhyd.oauth.model.AuthResponse;
9
import me.zhyd.oauth.model.AuthToken;
10
import me.zhyd.oauth.model.AuthUser;
11
import me.zhyd.oauth.url.AbstractUrlBuilder;
12
import me.zhyd.oauth.utils.AuthChecker;
13

14 15 16 17 18 19
/**
 * @author yadong.zhang (yadong.zhang0415(a)gmail.com)
 * @version 1.0
 * @since 1.8
 */
@Data
智布道's avatar
智布道 已提交
20
public abstract class BaseAuthRequest implements AuthRequest {
21
    protected AuthConfig config;
22
    protected AuthSource source;
23
    protected AbstractUrlBuilder urlBuilder;
24

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

35 36 37 38 39
    public BaseAuthRequest(AuthConfig config, AuthSource source, AbstractUrlBuilder urlBuilder) {
        this(config, source);
        this.urlBuilder = urlBuilder;
    }

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);
52
            return AuthResponse.builder().code(ResponseStatus.SUCCESS.getCode()).data(user).build();
53
        } catch (Exception e) {
54
            return this.responseError(e);
55
        }
56 57
    }

58 59 60 61 62 63 64 65
    private AuthResponse responseError(Exception e) {
        int errorCode = ResponseStatus.FAILURE.getCode();
        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 abstract String authorize();
73
}