AuthMiRequest.java 4.4 KB
Newer Older
1 2 3 4 5 6
package me.zhyd.oauth.request;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
7
import lombok.extern.slf4j.Slf4j;
8
import me.zhyd.oauth.config.AuthConfig;
9
import me.zhyd.oauth.config.AuthSource;
10
import me.zhyd.oauth.exception.AuthException;
11
import me.zhyd.oauth.model.*;
智布道's avatar
智布道 已提交
12
import me.zhyd.oauth.url.AuthMiUrlBuilder;
13
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
14 15 16 17 18 19 20 21 22 23

import java.text.MessageFormat;

/**
 * 小米登录
 *
 * @author yangkai.shen (https://xkcoding.com)
 * @version 1.5
 * @since 1.5
 */
24
@Slf4j
智布道's avatar
智布道 已提交
25
public class AuthMiRequest extends AuthDefaultRequest {
26 27 28
    private static final String PREFIX = "&&&START&&&";

    public AuthMiRequest(AuthConfig config) {
智布道's avatar
智布道 已提交
29
        super(config, AuthSource.MI, new AuthMiUrlBuilder());
30 31 32
    }

    @Override
33
    protected AuthToken getAccessToken(AuthCallback authCallback) {
智布道's avatar
智布道 已提交
34
        String accessTokenUrl = this.urlBuilder.getAccessTokenUrl(authCallback.getCode());
35 36 37 38 39 40
        return getToken(accessTokenUrl);
    }

    private AuthToken getToken(String accessTokenUrl) {
        HttpResponse response = HttpRequest.get(accessTokenUrl).execute();
        String jsonStr = StrUtil.replace(response.body(), PREFIX, StrUtil.EMPTY);
智布道's avatar
智布道 已提交
41
        JSONObject accessTokenObject = JSONObject.parseObject(jsonStr);
42

智布道's avatar
智布道 已提交
43 44
        if (accessTokenObject.containsKey("error")) {
            throw new AuthException(accessTokenObject.getString("error_description"));
45 46 47
        }

        return AuthToken.builder()
智布道's avatar
智布道 已提交
48 49 50 51 52 53 54 55
                .accessToken(accessTokenObject.getString("access_token"))
                .expireIn(accessTokenObject.getIntValue("expires_in"))
                .scope(accessTokenObject.getString("scope"))
                .tokenType(accessTokenObject.getString("token_type"))
                .refreshToken(accessTokenObject.getString("refresh_token"))
                .openId(accessTokenObject.getString("openId"))
                .macAlgorithm(accessTokenObject.getString("mac_algorithm"))
                .macKey(accessTokenObject.getString("mac_key"))
56 57 58 59 60 61
                .build();
    }

    @Override
    protected AuthUser getUserInfo(AuthToken authToken) {
        // 获取用户信息
62 63 64 65
        HttpResponse userResponse = HttpRequest.get(this.urlBuilder.getUserInfoUrl(AuthUserInfoEntity.builder()
                .clientId(config.getClientId())
                .accessToken(authToken.getAccessToken())
                .build()))
66 67 68
                .execute();

        JSONObject userProfile = JSONObject.parseObject(userResponse.body());
69
        if ("error".equalsIgnoreCase(userProfile.getString("result"))) {
70 71 72 73 74 75 76 77 78 79 80
            throw new AuthException(userProfile.getString("description"));
        }

        JSONObject user = userProfile.getJSONObject("data");

        AuthUser authUser = AuthUser.builder()
                .uuid(authToken.getOpenId())
                .username(user.getString("miliaoNick"))
                .nickname(user.getString("miliaoNick"))
                .avatar(user.getString("miliaoIcon"))
                .email(user.getString("mail"))
智布道's avatar
智布道 已提交
81
                .gender(AuthUserGender.UNKNOW)
82 83 84 85 86 87 88 89 90 91
                .token(authToken)
                .source(AuthSource.MI)
                .build();

        // 获取用户邮箱手机号等信息
        String emailPhoneUrl = MessageFormat.format("{0}?clientId={1}&token={2}", "https://open.account.xiaomi.com/user/phoneAndEmail", config
                .getClientId(), authToken.getAccessToken());

        HttpResponse emailResponse = HttpRequest.get(emailPhoneUrl).execute();
        JSONObject userEmailPhone = JSONObject.parseObject(emailResponse.body());
92
        if (!"error".equalsIgnoreCase(userEmailPhone.getString("result"))) {
93 94
            JSONObject emailPhone = userEmailPhone.getJSONObject("data");
            authUser.setEmail(emailPhone.getString("email"));
95 96
        } else {
            log.warn("小米开发平台暂时不对外开放用户手机及邮箱信息的获取");
97 98 99 100 101 102 103 104 105 106 107 108 109
        }

        return authUser;
    }

    /**
     * 刷新access token (续期)
     *
     * @param authToken 登录成功后返回的Token信息
     * @return AuthResponse
     */
    @Override
    public AuthResponse refresh(AuthToken authToken) {
智布道's avatar
智布道 已提交
110
        String miRefreshUrl = this.urlBuilder.getRefreshUrl(authToken.getRefreshToken());
111

智布道's avatar
智布道 已提交
112
        return AuthResponse.builder().code(AuthResponseStatus.SUCCESS.getCode()).data(getToken(miRefreshUrl)).build();
113 114
    }
}