AuthBaiduRequest.java 2.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
package me.zhyd.oauth.request;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.*;
import me.zhyd.oauth.utils.UrlBuilder;

/**
12 13
 * 百度账号登录
 *
14 15 16 17 18 19 20 21 22 23 24
 * @author yadong.zhang (yadong.zhang0415(a)gmail.com)
 * @version 1.0
 * @since 1.8
 */
public class AuthBaiduRequest extends BaseAuthRequest {

    public AuthBaiduRequest(AuthConfig config) {
        super(config, AuthSource.BAIDU);
    }

    @Override
25
    protected AuthToken getAccessToken(String code) {
26 27 28 29 30 31 32
        String accessTokenUrl = UrlBuilder.getBaiduAccessTokenUrl(config.getClientId(), config.getClientSecret(), code, config.getRedirectUri());
        HttpResponse response = HttpRequest.post(accessTokenUrl).execute();
        JSONObject accessTokenObject = JSONObject.parseObject(response.body());
        AuthBaiduErrorCode errorCode = AuthBaiduErrorCode.getErrorCode(accessTokenObject.getString("error"));
        if (!AuthBaiduErrorCode.OK.equals(errorCode)) {
            throw new AuthException(errorCode.getDesc());
        }
33 34 35
        return AuthToken.builder()
                .accessToken(accessTokenObject.getString("access_token"))
                .build();
36 37 38
    }

    @Override
39 40
    protected AuthUser getUserInfo(AuthToken authToken) {
        String accessToken = authToken.getAccessToken();
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
        HttpResponse response = HttpRequest.get(UrlBuilder.getBaiduUserInfoUrl(accessToken)).execute();
        String userInfo = response.body();
        JSONObject object = JSONObject.parseObject(userInfo);
        AuthBaiduErrorCode errorCode = AuthBaiduErrorCode.getErrorCode(object.getString("error"));
        if (!AuthBaiduErrorCode.OK.equals(errorCode)) {
            throw new AuthException(errorCode.getDesc());
        }
        return AuthUser.builder()
                .username(object.getString("username"))
                .nickname(object.getString("username"))
                .gender(AuthUserGender.getRealGender(object.getString("sex")))
                .accessToken(accessToken)
                .source(AuthSource.BAIDU)
                .build();
    }

    @Override
58 59
    public AuthResponse revoke(AuthToken authToken) {
        String accessToken = authToken.getAccessToken();
60 61 62 63 64 65 66 67
        HttpResponse response = HttpRequest.get(UrlBuilder.getBaiduRevokeUrl(accessToken)).execute();
        String userInfo = response.body();
        JSONObject object = JSONObject.parseObject(userInfo);
        ResponseStatus status = object.getIntValue("result") == 1 ? ResponseStatus.SUCCESS : ResponseStatus.FAILURE;
        return AuthResponse.builder().code(status.getCode()).msg(status.getMsg()).build();
    }

}