You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
2.4 KiB

package dev.garrettmills.starship.hyperlink.util;
import android.content.SharedPreferences;
import dev.garrettmills.starship.hyperlink.Hyperlink;
public class APIv1 {
/**
* Given an API endpoint, resolve the fully qualified URL using the stored server address.
* Example:
* resolveEndpoint("/auth/redeem") // => "https://hyperlink.url/api/v1/auth/redeem"
* @param endpoint un-qualified api endpoint
* @return The resolved string.
*/
public static String resolveEndpoint(String endpoint) {
if ( !endpoint.startsWith("/") ) {
endpoint = "/" + endpoint;
}
String server = Hyperlink.preferences.getString(Hyperlink.SERVER_ADDR, "");
if ( server.endsWith("/") ) {
server = server.substring(0, server.length() - 1);
}
return server + "/api/v1" + endpoint;
}
public static boolean isAuthenticated() {
return !Hyperlink.preferences.getString(Hyperlink.SERVER_ADDR, "").equals("")
&& !Hyperlink.preferences.getString(Hyperlink.ACCESS_TOKEN, "").equals("");
}
public static AccessToken getToken() throws NotAuthenticatedException {
if ( !isAuthenticated() ) {
throw new NotAuthenticatedException();
}
return new AccessToken(
Hyperlink.preferences.getString(Hyperlink.SERVER_ADDR, ""),
Hyperlink.preferences.getString(Hyperlink.ACCESS_TOKEN, "")
);
}
public static void logout() {
SharedPreferences.Editor editor = Hyperlink.preferences.edit();
editor.putString(Hyperlink.SERVER_ADDR, "");
editor.putString(Hyperlink.ACCESS_TOKEN, "");
editor.apply();
}
public static AccessToken login(LoginToken login) {
AccessToken token = redeemLoginToken(login);
SharedPreferences.Editor editor = Hyperlink.preferences.edit();
editor.putString(Hyperlink.SERVER_ADDR, token.getServer());
editor.putString(Hyperlink.ACCESS_TOKEN, token.getToken());
editor.apply();
return token;
}
/**
* @fixme this is a stub placeholder. Replace with actual implementation
* @param login the LoginToken from the user
* @return the AccessToken redeemed from the server
*/
protected static AccessToken redeemLoginToken(LoginToken login) {
return new AccessToken(login.getServer(), login.getToken());
}
}