Browse Source

Modifications for testing facilitation

master
Apostolos Fanakis 6 years ago
parent
commit
96ba02ff91
  1. 2
      UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/activities/main/MainActivity.java
  2. 34
      UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/base/BaseActivity.java
  3. 9
      UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/base/BaseApplication.java
  4. 208
      UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/session/SessionManager.java
  5. BIN
      release.apk

2
UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/activities/main/MainActivity.java

@ -284,7 +284,7 @@ public class MainActivity extends BaseActivity {
} }
@Override @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == LOCATION_PERMISSIONS_REQUEST_CODE_FOR_DISTANCE_FILTER) { if (requestCode == LOCATION_PERMISSIONS_REQUEST_CODE_FOR_DISTANCE_FILTER) {
MainTask mainTask = new MainTask(); MainTask mainTask = new MainTask();
mainTask.execute(); mainTask.execute();

34
UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/base/BaseActivity.java

@ -1,13 +1,16 @@
package gr.auth.databases.flavours.base; package gr.auth.databases.flavours.base;
import android.Manifest; import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.text.InputType;
import android.view.View; import android.view.View;
import android.widget.EditText;
import com.mikepenz.fontawesome_typeface_library.FontAwesome; import com.mikepenz.fontawesome_typeface_library.FontAwesome;
import com.mikepenz.google_material_typeface_library.GoogleMaterial; import com.mikepenz.google_material_typeface_library.GoogleMaterial;
@ -22,6 +25,7 @@ import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IProfile; import com.mikepenz.materialdrawer.model.interfaces.IProfile;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar; import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat; import androidx.core.content.ContextCompat;
@ -40,6 +44,7 @@ import static gr.auth.databases.flavours.activities.profile.ProfileActivity.BUND
import static gr.auth.databases.flavours.activities.profile.ProfileActivity.BUNDLE_USER_NAME; import static gr.auth.databases.flavours.activities.profile.ProfileActivity.BUNDLE_USER_NAME;
public abstract class BaseActivity extends AppCompatActivity { public abstract class BaseActivity extends AppCompatActivity {
public static final String PREF_BASE_SERVER_IP = "PREF_BASE_SERVER_IP";
// Client & Cookies // Client & Cookies
protected static OkHttpClient client; protected static OkHttpClient client;
@ -52,6 +57,7 @@ public abstract class BaseActivity extends AppCompatActivity {
protected Toolbar toolbar; protected Toolbar toolbar;
protected Drawer drawer; protected Drawer drawer;
private boolean isBaseIPSetDialogShown = false;
private boolean isMainActivity; private boolean isMainActivity;
@Override @Override
@ -78,6 +84,11 @@ public abstract class BaseActivity extends AppCompatActivity {
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
updateDrawer(); updateDrawer();
String baseServerIP = sharedPreferences.getString(PREF_BASE_SERVER_IP, null);
if ((baseServerIP == null || baseServerIP.isEmpty()) && !isBaseIPSetDialogShown) {
isBaseIPSetDialogShown = true;
showBaseIPSetDialog();
}
} }
@Override @Override
@ -328,4 +339,27 @@ public abstract class BaseActivity extends AppCompatActivity {
updateDrawer(); updateDrawer();
} }
} }
private void showBaseIPSetDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(getThemedContext());
final EditText serverIPInput = new EditText(this);
serverIPInput.setInputType(InputType.TYPE_CLASS_PHONE);
builder.setTitle("Base server IP address")
.setView(serverIPInput)
.setMessage("Please provide the base IP of the server (xxx.xxx.xxx.xxx) to be used in the requests.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(PREF_BASE_SERVER_IP, serverIPInput.getText().toString()).apply();
SessionManager.setBaseServerUrl(serverIPInput.getText().toString());
isBaseIPSetDialogShown = false;
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
} }

9
UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/base/BaseApplication.java

@ -13,12 +13,15 @@ import java.io.IOException;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.preference.PreferenceManager;
import gr.auth.databases.flavours.session.SessionManager; import gr.auth.databases.flavours.session.SessionManager;
import okhttp3.Interceptor; import okhttp3.Interceptor;
import okhttp3.OkHttpClient; import okhttp3.OkHttpClient;
import okhttp3.Request; import okhttp3.Request;
import okhttp3.Response; import okhttp3.Response;
import static gr.auth.databases.flavours.base.BaseActivity.PREF_BASE_SERVER_IP;
public class BaseApplication extends Application { public class BaseApplication extends Application {
public static final String CSRF_TOKEN = "CSRF_TOKEN"; public static final String CSRF_TOKEN = "CSRF_TOKEN";
@ -62,7 +65,6 @@ public class BaseApplication extends Application {
final Request authorized = original.newBuilder() final Request authorized = original.newBuilder()
.addHeader("X-CSRFToken", csrfToken) .addHeader("X-CSRFToken", csrfToken)
.build(); .build();
return chain.proceed(authorized); return chain.proceed(authorized);
} }
@ -70,7 +72,10 @@ public class BaseApplication extends Application {
client = builder.build(); client = builder.build();
sessionManager = new SessionManager(client, cookieJar, sharedPrefs);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
String baseServerIP = sharedPreferences.getString(PREF_BASE_SERVER_IP, null);
sessionManager = new SessionManager(client, cookieJar, sharedPrefs, baseServerIP);
DisplayMetrics displayMetrics = getApplicationContext().getResources().getDisplayMetrics(); DisplayMetrics displayMetrics = getApplicationContext().getResources().getDisplayMetrics();
dpWidth = displayMetrics.widthPixels / displayMetrics.density; dpWidth = displayMetrics.widthPixels / displayMetrics.density;

208
UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/session/SessionManager.java

@ -48,39 +48,38 @@ public class SessionManager {
} }
//Generic constants //Generic constants
private static final String baseServerUrl = "http://83.212.109.171:8181/"; private static String baseServerUrl = "http://0.0.0.0:8181/";
private static final String loginUrl = baseServerUrl + "api/rest-auth/login/"; public static String restaurantsUrl = baseServerUrl + "api/restaurant/";
private static final String signupUrl = baseServerUrl + "api/rest-auth/registration/"; public static String restaurantsUserViewUrl = baseServerUrl + "api/restaurantUserView/";
private static final String logoutUrl = baseServerUrl + "api/rest-auth/logout/"; public static String getUserDietsUrl = baseServerUrl + "api/userDiets/";
private static final String setUserBirthday = baseServerUrl + "api/setUserBirthday/"; public static String rateDrinkUrl = baseServerUrl + "api/userratesdrink/";
public static final String restaurantsUrl = baseServerUrl + "api/restaurant/"; public static String rateFoodUrl = baseServerUrl + "api/userratesfood/";
public static final String restaurantsUserViewUrl = baseServerUrl + "api/restaurantUserView/"; public static String rateRestaurantUrl = baseServerUrl + "api/userratesrestaurant/";
public static final String getUserDietsUrl = baseServerUrl + "api/userDiets/"; public static String foodsUserViewUrl = baseServerUrl + "api/foodUserView/";
public static final String rateDrinkUrl = baseServerUrl + "api/userratesdrink/"; public static String drinksUserViewUrl = baseServerUrl + "api/drinkUserView/";
public static final String rateFoodUrl = baseServerUrl + "api/userratesfood/"; public static String profileUserViewUrl = baseServerUrl + "api/profileUserView/";
public static final String rateRestaurantUrl = baseServerUrl + "api/userratesrestaurant/"; public static String addFoodUrl = baseServerUrl + "api/addFood/";
public static final String foodsUserViewUrl = baseServerUrl + "api/foodUserView/"; public static String addDrinkUrl = baseServerUrl + "api/addDrink/";
public static final String drinksUserViewUrl = baseServerUrl + "api/drinkUserView/"; public static String dietsUserViewUrl = baseServerUrl + "api/dietUserView/";
public static final String profileUserViewUrl = baseServerUrl + "api/profileUserView/"; public static String ingredientsUserViewUrl = baseServerUrl + "api/ingredientUserView/";
public static final String addFoodUrl = baseServerUrl + "api/addFood/"; public static String prohibitIngredientUrl = baseServerUrl + "api/prohibitIngredient/";
public static final String addDrinkUrl = baseServerUrl + "api/addDrink/"; public static String followDietUrl = baseServerUrl + "api/followDiet/";
public static final String dietsUserViewUrl = baseServerUrl + "api/dietUserView/"; public static String addIngredientUrl = baseServerUrl + "api/ingredient/";
public static final String ingredientsUserViewUrl = baseServerUrl + "api/ingredientUserView/"; public static String addDietUrl = baseServerUrl + "api/addDiet/";
public static final String prohibitIngredientUrl = baseServerUrl + "api/prohibitIngredient/"; public static String addIngredientToFoodUrl = baseServerUrl + "api/foodhasingredient/";
public static final String followDietUrl = baseServerUrl + "api/followDiet/"; public static String addIngredientToDrinkUrl = baseServerUrl + "api/drinkhasingredient/";
public static final String addIngredientUrl = baseServerUrl + "api/ingredient/"; public static String acceptRestaurantUrl = baseServerUrl + "api/acceptRestaurant/";
public static final String addDietUrl = baseServerUrl + "api/addDiet/"; public static String acceptFoodUrl = baseServerUrl + "api/acceptFood/";
public static final String addIngredientToFoodUrl = baseServerUrl + "api/foodhasingredient/"; public static String acceptDrinkUrl = baseServerUrl + "api/acceptDrink/";
public static final String addIngredientToDrinkUrl = baseServerUrl + "api/drinkhasingredient/"; public static String acceptDietUrl = baseServerUrl + "api/acceptDiet/";
public static final String acceptRestaurantUrl = baseServerUrl + "api/acceptRestaurant/"; private static String loginUrl = baseServerUrl + "api/rest-auth/login/";
public static final String acceptFoodUrl = baseServerUrl + "api/acceptFood/"; private static String signupUrl = baseServerUrl + "api/rest-auth/registration/";
public static final String acceptDrinkUrl = baseServerUrl + "api/acceptDrink/"; private static String logoutUrl = baseServerUrl + "api/rest-auth/logout/";
public static final String acceptDietUrl = baseServerUrl + "api/acceptDiet/"; private static String setUserBirthday = baseServerUrl + "api/setUserBirthday/";
// Client & Cookies // Client & Cookies
private final OkHttpClient client; private final OkHttpClient client;
private final PersistentCookieJar cookieJar; private final PersistentCookieJar cookieJar;
//private final SharedPrefsCookiePersistor cookiePersistor;
//Shared Preferences & its keys //Shared Preferences & its keys
private final SharedPreferences sharedPrefs; private final SharedPreferences sharedPrefs;
@ -91,56 +90,50 @@ public class SessionManager {
private static final String LOGIN_SCREEN_AS_DEFAULT = "LoginScreenAsDefault"; private static final String LOGIN_SCREEN_AS_DEFAULT = "LoginScreenAsDefault";
//Constructor //Constructor
public SessionManager(OkHttpClient client, PersistentCookieJar cookieJar, SharedPreferences sharedPrefs) { public SessionManager(OkHttpClient client, PersistentCookieJar cookieJar, SharedPreferences sharedPrefs, String baseServerIP) {
this.client = client; this.client = client;
this.cookieJar = cookieJar; this.cookieJar = cookieJar;
this.sharedPrefs = sharedPrefs; this.sharedPrefs = sharedPrefs;
}
public int login(String... strings) { if (baseServerIP != null && !baseServerIP.isEmpty()) {
//Builds the login request for each case setBaseServerUrl(baseServerIP);
Request request;
clearSessionData();
String username = strings[0];
String password = strings[1];
RequestBody formBody = new FormBody.Builder()
.add("username", username)
.add("password", password)
.build();
request = new Request.Builder()
.url(loginUrl)
.post(formBody)
.build();
try {
//Makes request & handles response
Response response = client.newCall(request).execute();
setPersistentCookieSession(loginUrl); //Store cookies
ResponseBody responseBody = response.body();
assert responseBody != null;
JSONObject jsonResponse = new JSONObject(responseBody.string());
JSONObject jsonUser = jsonResponse.getJSONObject("user");
int extractedUserId = jsonUser.getInt("id");
int extractedRole = jsonUser.getInt("role");
//Edit SharedPreferences, save session's data
SharedPreferences.Editor editor = sharedPrefs.edit();
setLoginScreenAsDefault(false);
editor.putBoolean(LOGGED_IN, true);
editor.putString(USERNAME, username);
editor.putInt(USER_ID, extractedUserId);
editor.putInt(USER_TYPE, extractedRole);
editor.apply();
return 0;
} catch (Exception e) {
return 2;
} }
} }
public static void setBaseServerUrl(String baseServerIP) {
// Sets base url
SessionManager.baseServerUrl = "http://" + baseServerIP + ":8181/";
// Sets all other api point urls
loginUrl = baseServerUrl + "api/rest-auth/login/";
signupUrl = baseServerUrl + "api/rest-auth/registration/";
logoutUrl = baseServerUrl + "api/rest-auth/logout/";
setUserBirthday = baseServerUrl + "api/setUserBirthday/";
restaurantsUrl = baseServerUrl + "api/restaurant/";
restaurantsUserViewUrl = baseServerUrl + "api/restaurantUserView/";
getUserDietsUrl = baseServerUrl + "api/userDiets/";
rateDrinkUrl = baseServerUrl + "api/userratesdrink/";
rateFoodUrl = baseServerUrl + "api/userratesfood/";
rateRestaurantUrl = baseServerUrl + "api/userratesrestaurant/";
foodsUserViewUrl = baseServerUrl + "api/foodUserView/";
drinksUserViewUrl = baseServerUrl + "api/drinkUserView/";
profileUserViewUrl = baseServerUrl + "api/profileUserView/";
addFoodUrl = baseServerUrl + "api/addFood/";
addDrinkUrl = baseServerUrl + "api/addDrink/";
dietsUserViewUrl = baseServerUrl + "api/dietUserView/";
ingredientsUserViewUrl = baseServerUrl + "api/ingredientUserView/";
prohibitIngredientUrl = baseServerUrl + "api/prohibitIngredient/";
followDietUrl = baseServerUrl + "api/followDiet/";
addIngredientUrl = baseServerUrl + "api/ingredient/";
addDietUrl = baseServerUrl + "api/addDiet/";
addIngredientToFoodUrl = baseServerUrl + "api/foodhasingredient/";
addIngredientToDrinkUrl = baseServerUrl + "api/drinkhasingredient/";
acceptRestaurantUrl = baseServerUrl + "api/acceptRestaurant/";
acceptFoodUrl = baseServerUrl + "api/acceptFood/";
acceptDrinkUrl = baseServerUrl + "api/acceptDrink/";
acceptDietUrl = baseServerUrl + "api/acceptDiet/";
}
public int signup(String... strings) { public int signup(String... strings) {
//Builds the signup request //Builds the signup request
Request request; Request request;
@ -206,18 +199,6 @@ public class SessionManager {
} }
} }
public void validateSession() {
if (isLoggedIn()) {
int loginResult = login();
if (loginResult != 1)
return;
} else if (isLoginScreenDefault())
return;
setLoginScreenAsDefault(true);
clearSessionData();
}
public int logout() { public int logout() {
RequestBody requestBody = RequestBody.create(null, new byte[]{}); RequestBody requestBody = RequestBody.create(null, new byte[]{});
@ -252,6 +233,51 @@ public class SessionManager {
return UserType.fromInteger(sharedPrefs.getInt(USER_TYPE, -1)); return UserType.fromInteger(sharedPrefs.getInt(USER_TYPE, -1));
} }
public int login(String... strings) {
//Builds the login request for each case
Request request;
clearSessionData();
String username = strings[0];
String password = strings[1];
RequestBody formBody = new FormBody.Builder()
.add("username", username)
.add("password", password)
.build();
request = new Request.Builder()
.url(loginUrl)
.post(formBody)
.build();
try {
//Makes request & handles response
Response response = client.newCall(request).execute();
setPersistentCookieSession(loginUrl); //Store cookies
ResponseBody responseBody = response.body();
assert responseBody != null;
JSONObject jsonResponse = new JSONObject(responseBody.string());
JSONObject jsonUser = jsonResponse.getJSONObject("user");
int extractedUserId = jsonUser.getInt("id");
int extractedRole = jsonUser.getInt("role");
//Edit SharedPreferences, save session's data
SharedPreferences.Editor editor = sharedPrefs.edit();
setLoginScreenAsDefault(false);
editor.putBoolean(LOGGED_IN, true);
editor.putString(USERNAME, username);
editor.putInt(USER_ID, extractedUserId);
editor.putInt(USER_TYPE, extractedRole);
editor.apply();
return 0;
} catch (Exception e) {
e.printStackTrace();
return 2;
}
}
public boolean isLoggedIn() { public boolean isLoggedIn() {
return sharedPrefs.getBoolean(LOGGED_IN, false); return sharedPrefs.getBoolean(LOGGED_IN, false);
} }
@ -264,9 +290,21 @@ public class SessionManager {
HttpUrl httpUrl = HttpUrl.parse(forUrl); HttpUrl httpUrl = HttpUrl.parse(forUrl);
assert httpUrl != null; assert httpUrl != null;
List<Cookie> cookieList = cookieJar.loadForRequest(httpUrl); List<Cookie> cookieList = cookieJar.loadForRequest(httpUrl);
String csrfToken = "";
int maxLength = 0;
SharedPreferences.Editor editor = sharedPrefs.edit(); SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString(CSRF_TOKEN, cookieList.get(0).value());
for (int cookieIndex = 0; cookieIndex < cookieList.size(); ++cookieIndex) {
Cookie cookie = cookieList.get(cookieIndex);
if (!cookie.value().contains("Successfully signed in") && cookie.value().length() > maxLength) {
// The longest one is the CSRF token
csrfToken = cookie.value();
maxLength = csrfToken.length();
}
}
editor.putString(CSRF_TOKEN, csrfToken);
editor.apply(); editor.apply();
} }

BIN
release.apk

Binary file not shown.
Loading…
Cancel
Save