不在 BilibiliSecurityHelper 中判断 API 返回值

This commit is contained in:
czp 2018-02-01 14:57:54 +08:00
parent 08454d48ff
commit ef04b65984
5 changed files with 100 additions and 99 deletions

View File

@ -128,6 +128,25 @@ public class BilibiliAPI implements BilibiliServiceProvider, LiveClientProvider
username,
password
);
//判断返回值
switch (loginResponseEntity.getCode()) {
case ServerErrorCode.Common.OK: {
}
break;
case ServerErrorCode.Passport.USERNAME_OR_PASSWORD_INVALID: {
throw new LoginException("username or password invalid");
}
case ServerErrorCode.Passport.CANT_DECRYPT_RSA_PASSWORD: {
throw new LoginException("password error or hash expired");
}
case ServerErrorCode.Passport.CAPTCHA_NOT_MATCH: {
throw new LoginException(loginResponseEntity.getMessage());
}
default: {
throw new IOException(loginResponseEntity.getMessage());
}
}
bilibiliAccount.copyFrom(loginResponseEntity.toBilibiliAccount());
LOGGER.info("Login succeed with username: {}", username);
return loginResponseEntity;
@ -140,6 +159,21 @@ public class BilibiliAPI implements BilibiliServiceProvider, LiveClientProvider
bilibiliAccount.getAccessToken(),
bilibiliAccount.getRefreshToken()
);
switch (refreshTokenResponseEntity.getCode()) {
case ServerErrorCode.Common.OK: {
}
break;
case ServerErrorCode.Passport.NO_LOGIN: {
throw new LoginException("access token invalid");
}
case ServerErrorCode.Passport.REFRESH_TOKEN_NOT_MATCH: {
throw new LoginException("access token and refresh token mismatch");
}
default: {
throw new IOException(refreshTokenResponseEntity.getMessage());
}
}
bilibiliAccount.copyFrom(refreshTokenResponseEntity.toBilibiliAccount());
LOGGER.info("RefreshToken succeed with userId: {}", bilibiliAccount.getUserId());
return refreshTokenResponseEntity;
@ -149,6 +183,18 @@ public class BilibiliAPI implements BilibiliServiceProvider, LiveClientProvider
LOGGER.info("Logout attempting with userId '{}'", bilibiliAccount.getUserId());
Long userId = bilibiliAccount.getUserId();
LogoutResponseEntity logoutResponseEntity = BilibiliSecurityHelper.logout(this, bilibiliAccount.getAccessToken());
switch (logoutResponseEntity.getCode()) {
case ServerErrorCode.Common.OK: {
}
break;
case ServerErrorCode.Passport.NO_LOGIN: {
throw new LoginException("access token invalid");
}
default: {
throw new IOException(logoutResponseEntity.getMessage());
}
}
bilibiliAccount.reset();
LOGGER.info("Logout succeed with userId: {}", userId);
return logoutResponseEntity;

View File

@ -10,7 +10,6 @@ import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.security.auth.login.LoginException;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
@ -25,7 +24,7 @@ import java.util.stream.Collectors;
public class BilibiliSecurityHelper {
public static LoginResponseEntity login(BilibiliServiceProvider bilibiliServiceProvider,
String username,
String password) throws IOException, LoginException {
String password) throws IOException {
PassportService passportService = bilibiliServiceProvider.getPassportService();
KeyEntity keyEntity = passportService.getKey().execute().body();
//服务器返回异常错误码
@ -62,70 +61,23 @@ public class BilibiliSecurityHelper {
throw new IOException("get broken RSA public key");
}
//发起登录请求
LoginResponseEntity loginResponseEntity = passportService.login(
username, cipheredPassword
).execute().body();
//判断返回值
switch (loginResponseEntity.getCode()) {
case ServerErrorCode.Common.OK: {
return loginResponseEntity;
}
case ServerErrorCode.Passport.USERNAME_OR_PASSWORD_INVALID: {
throw new LoginException("username or password invalid");
}
case ServerErrorCode.Passport.CANT_DECRYPT_RSA_PASSWORD: {
throw new LoginException("password error or hash expired");
}
case ServerErrorCode.Passport.CAPTCHA_NOT_MATCH: {
throw new LoginException(loginResponseEntity.getMessage());
}
default: {
//其他错误码
throw new IOException(loginResponseEntity.getMessage());
}
}
return passportService.login(username, cipheredPassword)
.execute()
.body();
}
public static RefreshTokenResponseEntity refreshToken(BilibiliServiceProvider bilibiliServiceProvider,
String accessToken,
String refreshToken) throws IOException, LoginException {
RefreshTokenResponseEntity refreshTokenResponseEntity = bilibiliServiceProvider.getPassportService()
.refreshToken(
accessToken,
refreshToken
).execute()
String refreshToken) throws IOException {
return bilibiliServiceProvider.getPassportService().refreshToken(accessToken, refreshToken)
.execute()
.body();
switch (refreshTokenResponseEntity.getCode()) {
case ServerErrorCode.Common.OK: {
return refreshTokenResponseEntity;
}
case ServerErrorCode.Passport.NO_LOGIN: {
throw new LoginException("access token invalid");
}
case ServerErrorCode.Passport.REFRESH_TOKEN_NOT_MATCH: {
throw new LoginException("access token and refresh token mismatch");
}
default: {
//其他错误码
throw new IOException(refreshTokenResponseEntity.getMessage());
}
}
}
public static LogoutResponseEntity logout(BilibiliServiceProvider bilibiliServiceProvider,
String accessToken) throws IOException, LoginException {
LogoutResponseEntity logoutResponseEntity = bilibiliServiceProvider.getPassportService().logout(accessToken).execute().body();
switch (logoutResponseEntity.getCode()) {
case ServerErrorCode.Common.OK: {
return logoutResponseEntity;
}
case ServerErrorCode.Passport.NO_LOGIN: {
throw new LoginException("access token invalid");
}
default: {
//其他错误码
throw new IOException(logoutResponseEntity.getMessage());
}
}
String accessToken) throws IOException {
return bilibiliServiceProvider.getPassportService().logout(accessToken)
.execute()
.body();
}
}

View File

@ -1,11 +1,14 @@
package com.hiczp.bilibili.api.interceptor;
import com.google.gson.*;
import com.hiczp.bilibili.api.ServerErrorCode;
import okhttp3.Interceptor;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@ -13,6 +16,7 @@ import java.nio.charset.StandardCharsets;
//由于服务器返回错误时的 data 字段类型不固定, 会导致 json 反序列化出错.
//该拦截器将在返回的 code 不为 0 , response 转换为包含一个空 data json 字符串.
public class ErrorResponseConverterInterceptor implements Interceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(ErrorResponseConverterInterceptor.class);
private static final JsonParser JSON_PARSER = new JsonParser();
private static final Gson GSON = new Gson();
@ -34,9 +38,16 @@ public class ErrorResponseConverterInterceptor implements Interceptor {
return response;
}
//code 0
if (code.getAsInt() == 0) {
if (code.getAsInt() == ServerErrorCode.Common.OK) {
return response;
}
//打印 body
LOGGER.error("Get error response below: \n{}",
new GsonBuilder()
.setPrettyPrinting()
.create()
.toJson(jsonObject)
);
//data 字段不存在
if (jsonObject.get("data") == null) {
return response;

View File

@ -1,5 +1,7 @@
package com.hiczp.bilibili.api.test;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hiczp.bilibili.api.BilibiliAPI;
import com.hiczp.bilibili.api.BilibiliSecurityHelper;
import com.hiczp.bilibili.api.passport.entity.LoginResponseEntity;
@ -8,69 +10,56 @@ import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.security.auth.login.LoginException;
public class SecurityHelperTest {
private static final Logger LOGGER = LoggerFactory.getLogger(SecurityHelperTest.class);
private static final Config CONFIG = Config.getInstance();
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
@Test
public void normalLogin() throws Exception {
LOGGER.info("Login attempt with username {}", CONFIG.getUsername());
LoginResponseEntity loginResponseEntity = BilibiliSecurityHelper.login(
new BilibiliAPI(),
CONFIG.getUsername(),
CONFIG.getPassword()
);
LOGGER.info("Login succeed with username {}", CONFIG.getUsername());
LOGGER.info("{}", GSON.toJson(loginResponseEntity));
BilibiliSecurityHelper.logout(new BilibiliAPI(), loginResponseEntity.getData().getAccessToken());
}
@Test
public void loginWithWrongUsername() throws Exception {
final String username = "bilibili_account";
final String password = "bilibili_password";
LOGGER.info("Login attempt with username {}, password {}", username, password);
try {
BilibiliSecurityHelper.login(
new BilibiliAPI(),
username,
password
);
} catch (LoginException e) {
e.printStackTrace();
}
LoginResponseEntity loginResponseEntity = BilibiliSecurityHelper.login(
new BilibiliAPI(),
"bilibili_account",
"bilibili_password"
);
LOGGER.info("{}", loginResponseEntity.getMessage());
}
@Test
public void normalRefreshToken() throws Exception {
LOGGER.info("Login attempt with username {}", CONFIG.getUsername());
LoginResponseEntity loginResponseEntity = BilibiliSecurityHelper.login(
new BilibiliAPI(),
CONFIG.getUsername(),
CONFIG.getPassword()
);
LOGGER.info("Login succeed with access token {}", loginResponseEntity.getData().getAccessToken());
RefreshTokenResponseEntity refreshTokenResponseEntity = BilibiliSecurityHelper.refreshToken(
new BilibiliAPI(),
loginResponseEntity.getData().getAccessToken(),
loginResponseEntity.getData().getRefreshToken()
);
LOGGER.info("Refresh token succeed with new access token {}", refreshTokenResponseEntity.getData().getAccessToken());
LOGGER.info("{}", GSON.toJson(refreshTokenResponseEntity));
BilibiliSecurityHelper.logout(new BilibiliAPI(), refreshTokenResponseEntity.getData().getAccessToken());
}
@Test
public void refreshTokenWithWrongToken() throws Exception {
try {
RefreshTokenResponseEntity refreshTokenResponseEntity = BilibiliSecurityHelper.refreshToken(
new BilibiliAPI(),
"token",
"refreshToken"
);
} catch (LoginException e) {
e.printStackTrace();
}
RefreshTokenResponseEntity refreshTokenResponseEntity = BilibiliSecurityHelper.refreshToken(
new BilibiliAPI(),
"token",
"refreshToken"
);
LOGGER.info("{}", refreshTokenResponseEntity.getMessage());
}
@Test
@ -81,15 +70,11 @@ public class SecurityHelperTest {
CONFIG.getPassword()
);
String accessToken = loginResponseEntity.getData().getAccessToken();
LOGGER.info("Login succeed with access token {}", accessToken);
try {
RefreshTokenResponseEntity refreshTokenResponseEntity = BilibiliSecurityHelper.refreshToken(
new BilibiliAPI(),
accessToken,
"refreshToken"
);
} catch (LoginException e) {
e.printStackTrace();
}
RefreshTokenResponseEntity refreshTokenResponseEntity = BilibiliSecurityHelper.refreshToken(
new BilibiliAPI(),
accessToken,
"refreshToken"
);
LOGGER.info("{}", refreshTokenResponseEntity.getMessage());
}
}

View File

@ -3,11 +3,14 @@ package com.hiczp.bilibili.api.test;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hiczp.bilibili.api.BilibiliAPI;
import com.hiczp.bilibili.api.ServerErrorCode;
import com.hiczp.bilibili.api.passport.entity.InfoEntity;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.naming.AuthenticationException;
public class UserInfoTest {
private static final Logger LOGGER = LoggerFactory.getLogger(UserInfoTest.class);
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
@ -19,6 +22,10 @@ public class UserInfoTest {
.getInfo(BILIBILI_API.getBilibiliAccount().getAccessToken())
.execute()
.body();
LOGGER.debug("UserInfo below: \n{}", GSON.toJson(infoEntity));
if (infoEntity.getCode() == ServerErrorCode.Common.OK) {
LOGGER.info("UserInfo below: \n{}", GSON.toJson(infoEntity));
} else {
throw new AuthenticationException(infoEntity.getMessage());
}
}
}