diff --git a/app/src/main/java/core/notevault/sync/ApiClient.java b/app/src/main/java/core/notevault/sync/ApiClient.java index 34a95f8..17aa6b5 100644 --- a/app/src/main/java/core/notevault/sync/ApiClient.java +++ b/app/src/main/java/core/notevault/sync/ApiClient.java @@ -1,6 +1,9 @@ package core.notevault.sync; import android.content.Context; +import android.content.SharedPreferences; +import core.notevault.sync.auth.AuthInterceptor; +import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; @@ -9,8 +12,14 @@ public class ApiClient { public static Retrofit getRetrofitInstance(Context context) { if (retrofit == null) { + SharedPreferences sharedPreferences = context.getSharedPreferences("app_prefs", Context.MODE_PRIVATE); + OkHttpClient client = new OkHttpClient.Builder() + .addInterceptor(new AuthInterceptor(sharedPreferences)) + .build(); + retrofit = new Retrofit.Builder() .baseUrl("http://192.168.178.30:8080/") + .client(client) .addConverterFactory(GsonConverterFactory.create()) .build(); } diff --git a/app/src/main/java/core/notevault/sync/auth/AuthInterceptor.java b/app/src/main/java/core/notevault/sync/auth/AuthInterceptor.java new file mode 100644 index 0000000..2836fa4 --- /dev/null +++ b/app/src/main/java/core/notevault/sync/auth/AuthInterceptor.java @@ -0,0 +1,31 @@ +package core.notevault.sync.auth; + +import android.content.SharedPreferences; +import okhttp3.Interceptor; +import okhttp3.Request; +import okhttp3.Response; + + +import java.io.IOException; + +public class AuthInterceptor implements Interceptor { + private SharedPreferences sharedPreferences; + + public AuthInterceptor(SharedPreferences sharedPreferences) { + this.sharedPreferences = sharedPreferences; + } + + @Override + public Response intercept(Chain chain) throws IOException { + Request originalRequest = chain.request(); + + String token = sharedPreferences.getString("jwt_token", null); + if (token == null) { + return chain.proceed(originalRequest); + } + + Request authenticatedRequest = originalRequest.newBuilder() + .header("Authorization", "Bearer " + token).build(); + return chain.proceed(authenticatedRequest); + } +}