Skip to content

Commit

Permalink
Merge pull request #58 from martinlaizg/auth
Browse files Browse the repository at this point in the history
Añadido JWT a peticiones y manejo de error
También se han añadido cambios menores:
Quitada conversión a base64 antes de hash
Arreglado problema de dependencia de Repo-Service
Arreglado dato km de distancia a sitio jugando
Cambiada vista de preferencias
Arreglada carga de login
  • Loading branch information
martinlaizg authored Jul 15, 2019
2 parents fb43309 + e590040 commit 04f9973
Show file tree
Hide file tree
Showing 45 changed files with 565 additions and 476 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
public class Preferences {

public static final String USER = "user";
public static final String LOGIN = "login";
public static final String TOKEN = "token";
private static final String LOGIN = "login";

public static User getLoggedUser(SharedPreferences sp) {
String user_string = sp.getString(USER, "");
Expand Down Expand Up @@ -39,4 +40,12 @@ public static Login getLogin(SharedPreferences sp) {
Gson gson = new GsonBuilder().setDateFormat(DateUtils.DATE_FORMAT).create();
return gson.fromJson(login_string, Login.class);
}

public static void setToken(SharedPreferences sp, String token) {
sp.edit().putString(TOKEN, token).apply();
}

public static String getToken(SharedPreferences sp) {
return sp.getString(TOKEN, "");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,18 @@

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class Crypto {
public class Secure {

private static final String TAG = Crypto.class.getSimpleName();
private static final String TAG = Secure.class.getSimpleName();
private static MessageDigest mdSHA512;

public static String hash(String toHash) {
String hashed = null;
toHash = Base64.getEncoder().encodeToString(toHash.getBytes());
try {
if(mdSHA512 == null) {
mdSHA512 = MessageDigest.getInstance("SHA-512");
}
// mdSHA512.update(salt);
byte[] bytes = mdSHA512.digest(toHash.getBytes());
StringBuilder sb = new StringBuilder();
for(byte aByte : bytes) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,54 +17,30 @@
import retrofit2.http.Path;
import retrofit2.http.QueryMap;

// TODO add JavaDoc
public interface RestClient {

//
//
//
//
// Tours

// Get tours with optional filter
@GET("tours")
Call<List<Tour>> getTours(@QueryMap java.util.Map<String, String> params);

@POST("tours")
Call<Tour> createTour(@Body Tour tour);

// Get single tourEntity
@GET("tours/{tour_id}")
Call<Tour> getTour(@Path("tour_id") Integer tour_id);

// Update tourEntity
@PUT("tours/{tour_id}")
Call<Tour> update(@Path("tour_id") Integer tour_id, @Body Tour t);

//
//
//
//
// User requests
@GET("tours/{tour_id}/users/{user_id}/play")
Call<Play> getUserPlay(@Path("tour_id") Integer tour_id, @Path("user_id") Integer user_id);

// Login user
@POST("login")
Call<User> login(@Body Login login);

// Create a user
@POST("users")
Call<User> registry(@Body Login login);

//
//
//
//
// Play requests

// Get user play
@GET("plays")
Call<Play> getUserPlay(@QueryMap Map<String, String> params);

// Create user play
@POST("plays")
Call<Play> createUserPlay(@QueryMap Map<String, String> params);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,29 +1,90 @@
package com.martinlaizg.geofind.data.access.api;

import android.app.Application;
import android.content.SharedPreferences;
import android.util.Log;

import androidx.preference.PreferenceManager;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.martinlaizg.geofind.config.Preferences;
import com.martinlaizg.geofind.data.access.api.service.exceptions.APIException;
import com.martinlaizg.geofind.data.repository.RepositoryFactory;
import com.martinlaizg.geofind.data.repository.UserRepository;
import com.martinlaizg.geofind.utils.DateUtils;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitInstance {

private static final String BASE_URL = "https://geofind1.herokuapp.com/api/";

private static final String TAG = RetrofitInstance.class.getSimpleName();

private static Retrofit retrofitInstance;

public static RestClient getRestClient() {
private static String token;
private static SharedPreferences sp;
private static UserRepository userRepo;

public static RestClient getRestClient(Application application) {
if(userRepo == null) {
userRepo = RepositoryFactory.getUserRepository(application);
}
if(sp == null) {
sp = PreferenceManager.getDefaultSharedPreferences(application.getApplicationContext());
}
Retrofit rf = getRetrofitInstance();
return rf.create(RestClient.class);
}

public static Retrofit getRetrofitInstance() {
if(retrofitInstance == null) {

OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(chain -> {
Request originalRequest = chain.request();
Request newRequest = originalRequest.newBuilder()
.addHeader("Authorization", getBearerToken())
.method(originalRequest.method(), originalRequest.body()).build();

Response response = chain.proceed(newRequest);
if(response.code() == 401) { // Code 401 (Unathorized)
try {
userRepo.reLogin();
} catch(APIException e) {
Log.e(TAG, "Fail relogin", e);
}
newRequest = originalRequest.newBuilder()
.addHeader("Authorization", getBearerToken())
.method(originalRequest.method(), originalRequest.body()).build();
response = chain.proceed(newRequest);
} else {
String newToken = response.header("Authorization");
if(newToken != null && !newToken.isEmpty()) {
Preferences.setToken(sp, newToken);
}
}
return response;
}).build();

Gson gson = new GsonBuilder().setDateFormat(DateUtils.DATE_FORMAT).create();
retrofitInstance = new Retrofit.Builder().baseUrl(BASE_URL)
retrofitInstance = new Retrofit.Builder().baseUrl(BASE_URL).client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(gson)).build();
}

return retrofitInstance;
}

private static String getBearerToken() {
return "Bearer " + token;
}

public static void setToken(String token) {
RetrofitInstance.token = token;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,6 @@ public enum ErrorType {
@SerializedName("provider") PROVIDER,
@SerializedName("provider_login") PROVIDER_LOGIN,
@SerializedName("secure") SECURE,
@SerializedName("auth") AUTH,
@SerializedName("expired") EXPIRED,
COMPLETE,}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.martinlaizg.geofind.data.access.api.service;

import android.app.Application;
import android.util.Log;

import com.martinlaizg.geofind.data.access.api.RestClient;
Expand All @@ -17,28 +18,37 @@

public class PlayService {

private static PlayService locationService;
private static RestClient restClient;

private static PlayService playService;

private final String TAG = PlayService.class.getSimpleName();

public static PlayService getInstance() {
void instantiate(Application application) {
if(restClient == null) {
restClient = RetrofitInstance.getRestClient();
restClient = RetrofitInstance.getRestClient(application);
}
if(locationService == null) {
locationService = new PlayService();
if(playService == null) {
playService = new PlayService();
}
return locationService;
}

/**
* Get the user play
*
* @param user_id
* the user id
* @param tour_id
* the tour id
* @return the play
* @throws APIException
* exception from server
*/
public Play getUserPlay(int user_id, int tour_id) throws APIException {
Response<Play> response;
APIException apiException;
try {
HashMap<String, String> params = new HashMap<>();
params.put("user_id", String.valueOf(user_id));
params.put("tour_id", String.valueOf(tour_id));
response = restClient.getUserPlay(params).execute();
response = restClient.getUserPlay(user_id, tour_id).execute();
if(response.isSuccessful()) {
return response.body();
}
Expand All @@ -50,6 +60,17 @@ public Play getUserPlay(int user_id, int tour_id) throws APIException {
throw apiException;
}

/**
* Create the user play
*
* @param user_id
* the user id
* @param tour_id
* the tour id
* @return the play
* @throws APIException
* exception from server
*/
public Play createUserPlay(int user_id, int tour_id) throws APIException {
Response<Play> response;
APIException apiException;
Expand All @@ -69,6 +90,17 @@ public Play createUserPlay(int user_id, int tour_id) throws APIException {
throw apiException;
}

/**
* Create the place play
*
* @param play_id
* the play id
* @param place_id
* the place id
* @return the play
* @throws APIException
* exception from the server
*/
public Play createPlacePlay(Integer play_id, Integer place_id) throws APIException {
Response<Play> response;
APIException apiException;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.martinlaizg.geofind.data.access.api.service;

import android.app.Application;

public class ServiceFactory {

private static UserService userService;
private static TourService tourService;
private static PlayService playService;

public static UserService getUserService(Application application) {
if(userService == null) {
userService = new UserService();
userService.instantiate(application);
}
return userService;
}

public static TourService getTourService(Application application) {
if(tourService == null) {
tourService = new TourService();
tourService.instantiate(application);
}
return tourService;
}

public static PlayService getPlayService(Application application) {
if(playService == null) {
playService = new PlayService();
playService.instantiate(application);
}
return playService;
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.martinlaizg.geofind.data.access.api.service;

import android.app.Application;
import android.util.Log;

import com.martinlaizg.geofind.data.access.api.RestClient;
Expand All @@ -16,18 +17,19 @@

public class TourService {

private static TourService tourService;
private static RestClient restClient;

private static TourService tourService;

private final String TAG = TourService.class.getSimpleName();

public static TourService getInstance() {
void instantiate(Application application) {
if(restClient == null) {
restClient = RetrofitInstance.getRestClient();
restClient = RetrofitInstance.getRestClient(application);
}
if(tourService == null) {
tourService = new TourService();
}
return tourService;
}

/**
Expand Down
Loading

0 comments on commit 04f9973

Please sign in to comment.