From 09c929803fceafd0fe41a687f0df6ec4e0ff8ef5 Mon Sep 17 00:00:00 2001 From: GiuseppeS Date: Mon, 6 May 2024 18:39:52 +0200 Subject: [PATCH] Implementata login OAuth --- app/build.gradle | 3 + .../core/rest/HttpInterceptor.java | 16 +- .../rest/consumers/SystemRESTConsumer.java | 11 +- .../core/rest/model/NativeSqlRequestDTO.java | 11 +- .../core/settings/SettingsModel.java | 57 ++++--- .../gest/login/LoginActivity.java | 71 ++++----- .../gest/login/dto/AuthTokenClaimsDTO.java | 146 ++++++++++++++++++ .../gest/login/dto/LoginJwtResponseDTO.java | 48 ++++++ .../gest/login/dto/LoginRequestDTO.java | 20 +++ .../gest/login/rest/LoginRESTConsumer.java | 53 +++++-- .../login/rest/LoginRESTConsumerService.java | 11 +- .../gest/login/viewmodel/LoginViewModel.java | 125 +++++++++++---- 12 files changed, 440 insertions(+), 132 deletions(-) create mode 100644 app/src/main/java/it/integry/integrywmsnative/gest/login/dto/AuthTokenClaimsDTO.java create mode 100644 app/src/main/java/it/integry/integrywmsnative/gest/login/dto/LoginJwtResponseDTO.java diff --git a/app/build.gradle b/app/build.gradle index 3d9d3a2b..1aed56c4 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -182,6 +182,9 @@ dependencies { // RxJava is also required. implementation 'io.reactivex.rxjava2:rxjava:2.1.12' implementation 'io.reactivex.rxjava2:rxandroid:2.0.2' + + //JWTUtils + implementation 'com.auth0.android:jwtdecode:2.0.2' } repositories { diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/HttpInterceptor.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/HttpInterceptor.java index 17f82459..1f071272 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/rest/HttpInterceptor.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/HttpInterceptor.java @@ -1,7 +1,5 @@ package it.integry.integrywmsnative.core.rest; -import android.util.Base64; - import java.io.IOException; import it.integry.integrywmsnative.core.settings.SettingsManager; @@ -20,25 +18,19 @@ public class HttpInterceptor implements Interceptor { public Response intercept(Chain chain) throws IOException { final String PROFILE_DB = SettingsManager.i().getUserSession() == null ? null : SettingsManager.i().getUserSession().getProfileDB(); - final String USERNAME = SettingsManager.i().getUser().getUsername(); - final String PASSWORD = SettingsManager.i().getUser().getPassword(); - final String DEVICE_ID = SettingsManager.i().getUserSession().getDeviceId(); + final String ACCESS_TOKEN = SettingsManager.i().getUserSession().getAccessToken(); final Request request = chain.request(); final HttpUrl url = request.url().newBuilder() .addQueryParameter("profileDb", PROFILE_DB) .build(); - String string = "Basic " + Base64.encodeToString((USERNAME + ":" + PASSWORD).getBytes(), Base64.NO_WRAP); - final Request newRequest = chain.request().newBuilder() - .addHeader("Authorization", string) + .addHeader("Authorization", "Bearer " + ACCESS_TOKEN) .addHeader("Content-Type", "application/json") .addHeader("Accept", "*/*") - .addHeader("username", USERNAME != null ? USERNAME : "") - .addHeader("password", PASSWORD != null ? PASSWORD : "") - .addHeader("device_id", DEVICE_ID != null ? DEVICE_ID : "") - .url(url).build(); + .url(url) + .build(); return chain.proceed(newRequest); } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/SystemRESTConsumer.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/SystemRESTConsumer.java index fd8bbbda..e08c4594 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/SystemRESTConsumer.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/SystemRESTConsumer.java @@ -4,9 +4,6 @@ import android.text.TextUtils; import android.util.Log; import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonParseException; import com.orhanobut.logger.Logger; import java.io.ByteArrayInputStream; @@ -15,7 +12,6 @@ import java.io.InputStreamReader; import java.io.Reader; import java.lang.reflect.Type; import java.net.ConnectException; -import java.util.Date; import java.util.List; import javax.inject.Singleton; @@ -31,7 +27,6 @@ import it.integry.integrywmsnative.core.rest.model.NativeSqlRequestDTO; import it.integry.integrywmsnative.core.rest.model.ServiceRESTResponse; import it.integry.integrywmsnative.core.rest.model.system.RegisterDeviceRequestDTO; import it.integry.integrywmsnative.core.settings.SettingsManager; -import it.integry.integrywmsnative.core.utility.UtilityDate; import it.integry.integrywmsnative.core.utility.UtilityGson; import it.integry.integrywmsnative.core.utility.UtilityString; import retrofit2.Call; @@ -63,8 +58,8 @@ public class SystemRESTConsumer extends _BaseRESTConsumer { } public void processSql(String nativeSql, final Type clazz, final RunnableArgs onComplete, final RunnableArgs onFailed) { - NativeSqlRequestDTO nativeSqlDTO = new NativeSqlRequestDTO(); - nativeSqlDTO.nativeSql = nativeSql; + NativeSqlRequestDTO nativeSqlDTO = new NativeSqlRequestDTO() + .setNativeSql(nativeSql); SystemRESTConsumerService service = RESTBuilder.getService(SystemRESTConsumerService.class); service @@ -104,7 +99,7 @@ public class SystemRESTConsumer extends _BaseRESTConsumer { service.getAvailableCodMdeps().enqueue(new Callback<>() { @Override public void onResponse(Call>> call, Response>> response) { - analyzeAnswer(response, "CodMdepsAvailable", onSuccess, onFailed); + analyzeAnswer(response, "getAvailableCodMdeps", onSuccess, onFailed); } @Override diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/model/NativeSqlRequestDTO.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/model/NativeSqlRequestDTO.java index 5684b5a9..3af6b4af 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/rest/model/NativeSqlRequestDTO.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/model/NativeSqlRequestDTO.java @@ -2,6 +2,15 @@ package it.integry.integrywmsnative.core.rest.model; public class NativeSqlRequestDTO { - public String nativeSql; + private String nativeSql; + + public String getNativeSql() { + return nativeSql; + } + + public NativeSqlRequestDTO setNativeSql(String nativeSql) { + this.nativeSql = nativeSql; + return this; + } } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/settings/SettingsModel.java b/app/src/main/java/it/integry/integrywmsnative/core/settings/SettingsModel.java index 027d4eb1..a8cb448b 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/settings/SettingsModel.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/settings/SettingsModel.java @@ -1,5 +1,7 @@ package it.integry.integrywmsnative.core.settings; +import java.time.LocalDateTime; + import it.integry.integrywmsnative.core.rest.model.AvailableCodMdepsDTO; public class SettingsModel { @@ -62,28 +64,9 @@ public class SettingsModel { } public static class User { - private String username; - private String password; + private String fullname; - public String getUsername() { - return username; - } - - public User setUsername(String username) { - this.username = username; - return this; - } - - public String getPassword() { - return password; - } - - public User setPassword(String password) { - this.password = password; - return this; - } - public String getFullname() { return fullname; } @@ -95,18 +78,50 @@ public class SettingsModel { } public static class UserSession { + + private String accessToken; + private String refreshToken; + private LocalDateTime refreshTokenExpiryDate; private String deviceId; private String profileDB; private AvailableCodMdepsDTO depo; private Integer defaultOrdinamentoPickingAccettazione = 0; private Integer defaultOrdinamentoPickingAccettazioneBolle = 0; + public String getAccessToken() { + return accessToken; + } + + public UserSession setAccessToken(String accessToken) { + this.accessToken = accessToken; + return this; + } + + public String getRefreshToken() { + return refreshToken; + } + + public UserSession setRefreshToken(String refreshToken) { + this.refreshToken = refreshToken; + return this; + } + + public LocalDateTime getRefreshTokenExpiryDate() { + return refreshTokenExpiryDate; + } + + public UserSession setRefreshTokenExpiryDate(LocalDateTime refreshTokenExpiryDate) { + this.refreshTokenExpiryDate = refreshTokenExpiryDate; + return this; + } + public String getDeviceId() { return deviceId; } - public void setDeviceId(String deviceId) { + public UserSession setDeviceId(String deviceId) { this.deviceId = deviceId; + return this; } public String getProfileDB() { diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/login/LoginActivity.java b/app/src/main/java/it/integry/integrywmsnative/gest/login/LoginActivity.java index 18e36266..190cfa64 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/login/LoginActivity.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/login/LoginActivity.java @@ -18,6 +18,7 @@ import it.integry.integrywmsnative.SplashActivity; import it.integry.integrywmsnative.core.di.BindableBoolean; import it.integry.integrywmsnative.core.di.BindableString; import it.integry.integrywmsnative.core.expansion.BaseActivity; +import it.integry.integrywmsnative.core.expansion.RunnableArgs; import it.integry.integrywmsnative.core.rest.consumers.SystemRESTConsumer; import it.integry.integrywmsnative.core.settings.SettingsManager; import it.integry.integrywmsnative.core.utility.UtilityWindow; @@ -104,18 +105,39 @@ public class LoginActivity extends BaseActivity implements LoginViewModel.Listen } @Override - public void onLoginCompleted(String protocol, String host, int port, String fullName, List availableProfiles) { + public void onLoginCompleted(String fullName) { this.onLoadingEnded(); runOnUiThread(() -> DialogSimpleMessageView.makeSuccessDialog( - "Benvenuto", - Html.fromHtml("Ciao " + fullName + ", la Integry le augura di svolgere al meglio il suo lavoro"), - null, - () -> showProfileDBSelectionDialog(protocol, host, port, availableProfiles)) + "Benvenuto", + Html.fromHtml("Ciao " + fullName + ", la Integry le augura di svolgere al meglio il suo lavoro"), + null, + this::startSplashActivity) .show(getSupportFragmentManager(), "tag")); } + @Override + public void requestProfileSelection(List availableProfiles, RunnableArgs onComplete) { + // setup the alert builder + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setTitle(R.string.action_choose_profile_db); + + // add a list + String[] profiles = new String[availableProfiles.size()]; + profiles = availableProfiles + .toArray(profiles); + + builder.setItems(profiles, (dialog, which) -> { + //SettingsManager.i().getUserSession().setProfileDB(availableProfiles.get(which)); + onComplete.run(availableProfiles.get(which)); + }); + + // create and show the alert dialog + AlertDialog dialog = builder.create(); + dialog.show(); + } + @Override public void onError(Exception ex) { @@ -123,45 +145,6 @@ public class LoginActivity extends BaseActivity implements LoginViewModel.Listen loginButtonEnabled.set(true); } - private void showProfileDBSelectionDialog(final String protocol, final String host, final int port, final List availableProfiles) { - Runnable onComplete = () -> { - - FirebaseInstallations.getInstance().getId().addOnCompleteListener(fid -> { - SettingsManager.i().getUserSession().setDeviceId(fid.getResult()); - SettingsManager.update(); - - systemRESTConsumer.registerDevice(this::startSplashActivity, this::onError); - }); - }; - - loginButtonEnabled.set(true); - - if (availableProfiles != null && availableProfiles.size() == 1) { - SettingsManager.i().getUserSession().setProfileDB(availableProfiles.get(0)); - - mViewmodel.loadDepo(codAzienda.get(), protocol, host, port, username.get(), password.get(), onComplete); - } else { - - // setup the alert builder - AlertDialog.Builder builder = new AlertDialog.Builder(this); - builder.setTitle(R.string.action_choose_profile_db); - - // add a list - String[] profiles = new String[availableProfiles.size()]; - profiles = availableProfiles - .toArray(profiles); - - builder.setItems(profiles, (dialog, which) -> { - SettingsManager.i().getUserSession().setProfileDB(availableProfiles.get(which)); - - mViewmodel.loadDepo(codAzienda.get(), protocol, host, port, username.get(), password.get(), onComplete); - }); - - // create and show the alert dialog - AlertDialog dialog = builder.create(); - dialog.show(); - } - } private void startSplashActivity() { finish(); diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/login/dto/AuthTokenClaimsDTO.java b/app/src/main/java/it/integry/integrywmsnative/gest/login/dto/AuthTokenClaimsDTO.java new file mode 100644 index 00000000..ea3e4c01 --- /dev/null +++ b/app/src/main/java/it/integry/integrywmsnative/gest/login/dto/AuthTokenClaimsDTO.java @@ -0,0 +1,146 @@ +package it.integry.integrywmsnative.gest.login.dto; + +import java.util.HashMap; + +public class AuthTokenClaimsDTO { + + private long deviceId; + private User userDTO; + private HashMap profilesData; + + public long getDeviceId() { + return deviceId; + } + + public AuthTokenClaimsDTO setDeviceId(long deviceId) { + this.deviceId = deviceId; + return this; + } + + public User getUserDTO() { + return userDTO; + } + + public AuthTokenClaimsDTO setUserDTO(User userDTO) { + this.userDTO = userDTO; + return this; + } + + public HashMap getProfilesData() { + return profilesData; + } + + public AuthTokenClaimsDTO setProfilesData(HashMap profilesData) { + this.profilesData = profilesData; + return this; + } + + public class User { + private String username; + private Object email; + private String fullname; + private int keyGroup; + private boolean attivo; + private String type; + + public String getUsername() { + return username; + } + + public User setUsername(String username) { + this.username = username; + return this; + } + + public Object getEmail() { + return email; + } + + public User setEmail(Object email) { + this.email = email; + return this; + } + + public String getFullname() { + return fullname; + } + + public User setFullname(String fullname) { + this.fullname = fullname; + return this; + } + + public int getKeyGroup() { + return keyGroup; + } + + public User setKeyGroup(int keyGroup) { + this.keyGroup = keyGroup; + return this; + } + + public boolean isAttivo() { + return attivo; + } + + public User setAttivo(boolean attivo) { + this.attivo = attivo; + return this; + } + + public String getType() { + return type; + } + + public User setType(String type) { + this.type = type; + return this; + } + } + + public static class AuthTokenProfileDetails { + private AuthTokenDepoDetails defaultDepo; + + public AuthTokenDepoDetails getDefaultDepo() { + return defaultDepo; + } + + public AuthTokenProfileDetails setDefaultDepo(AuthTokenDepoDetails defaultDepo) { + this.defaultDepo = defaultDepo; + return this; + } + } + + public static class AuthTokenDepoDetails { + private String codMdep; + private String descrizione; + private String codJfas; + + public String getCodMdep() { + return codMdep; + } + + public AuthTokenDepoDetails setCodMdep(String codMdep) { + this.codMdep = codMdep; + return this; + } + + public String getDescrizione() { + return descrizione; + } + + public AuthTokenDepoDetails setDescrizione(String descrizione) { + this.descrizione = descrizione; + return this; + } + + public String getCodJfas() { + return codJfas; + } + + public AuthTokenDepoDetails setCodJfas(String codJfas) { + this.codJfas = codJfas; + return this; + } + } +} diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/login/dto/LoginJwtResponseDTO.java b/app/src/main/java/it/integry/integrywmsnative/gest/login/dto/LoginJwtResponseDTO.java new file mode 100644 index 00000000..1440c75e --- /dev/null +++ b/app/src/main/java/it/integry/integrywmsnative/gest/login/dto/LoginJwtResponseDTO.java @@ -0,0 +1,48 @@ +package it.integry.integrywmsnative.gest.login.dto; + +import java.time.LocalDateTime; + +public class LoginJwtResponseDTO { + + private String accessToken; + private String refreshToken; + private LocalDateTime expiryDate; + private long expireIn; + + + public String getAccessToken() { + return accessToken; + } + + public LoginJwtResponseDTO setAccessToken(String accessToken) { + this.accessToken = accessToken; + return this; + } + + public String getRefreshToken() { + return refreshToken; + } + + public LoginJwtResponseDTO setRefreshToken(String refreshToken) { + this.refreshToken = refreshToken; + return this; + } + + public LocalDateTime getExpiryDate() { + return expiryDate; + } + + public LoginJwtResponseDTO setExpiryDate(LocalDateTime expiryDate) { + this.expiryDate = expiryDate; + return this; + } + + public long getExpireIn() { + return expireIn; + } + + public LoginJwtResponseDTO setExpireIn(long expireIn) { + this.expireIn = expireIn; + return this; + } +} diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/login/dto/LoginRequestDTO.java b/app/src/main/java/it/integry/integrywmsnative/gest/login/dto/LoginRequestDTO.java index 440dbdc1..55fd7b4e 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/login/dto/LoginRequestDTO.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/login/dto/LoginRequestDTO.java @@ -4,6 +4,8 @@ public class LoginRequestDTO { private String username; private String password; + private String profileDb; + private String deviceId; public String getUsername() { return username; @@ -22,4 +24,22 @@ public class LoginRequestDTO { this.password = password; return this; } + + public String getProfileDb() { + return profileDb; + } + + public LoginRequestDTO setProfileDb(String profileDb) { + this.profileDb = profileDb; + return this; + } + + public String getDeviceId() { + return deviceId; + } + + public LoginRequestDTO setDeviceId(String deviceId) { + this.deviceId = deviceId; + return this; + } } diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/login/rest/LoginRESTConsumer.java b/app/src/main/java/it/integry/integrywmsnative/gest/login/rest/LoginRESTConsumer.java index 67a9070e..974a4aad 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/login/rest/LoginRESTConsumer.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/login/rest/LoginRESTConsumer.java @@ -2,6 +2,8 @@ package it.integry.integrywmsnative.gest.login.rest; import android.util.Log; +import java.util.List; + import javax.inject.Singleton; import it.integry.integrywmsnative.core.CommonConst; @@ -10,7 +12,7 @@ import it.integry.integrywmsnative.core.rest.RESTBuilder; import it.integry.integrywmsnative.core.rest.consumers._BaseRESTConsumer; import it.integry.integrywmsnative.core.rest.model.ServiceRESTResponse; import it.integry.integrywmsnative.gest.login.dto.LoginAziendaDTO; -import it.integry.integrywmsnative.gest.login.dto.LoginResponseDTO; +import it.integry.integrywmsnative.gest.login.dto.LoginJwtResponseDTO; import it.integry.integrywmsnative.gest.login.dto.LoginRequestDTO; import retrofit2.Call; import retrofit2.Callback; @@ -42,26 +44,49 @@ public class LoginRESTConsumer extends _BaseRESTConsumer { } - public void authenticate(String protocol, String host, int port, String username, String password, RunnableArgs onComplete, RunnableArgs onFailed) { + public void authenticate(String protocol, String host, int port, String username, String password, String profileDb, String deviceSalt, RunnableArgs onComplete, RunnableArgs onFailed) { LoginRESTConsumerService service = RESTBuilder.getService(LoginRESTConsumerService.class, protocol, host, port, false); LoginRequestDTO loginRequestDTO = new LoginRequestDTO() .setUsername(username) - .setPassword(password); + .setPassword(password) + .setProfileDb(profileDb) + .setDeviceId(deviceSalt); - service.login(loginRequestDTO).enqueue(new Callback<>() { + service + .loginNew(loginRequestDTO) + .enqueue(new Callback<>() { - @Override - public void onResponse(Call> call, Response> response) { - analyzeAnswer(response, "Login", onComplete, onFailed); - } + @Override + public void onResponse(Call> call, Response> response) { + analyzeAnswer(response, "Login", onComplete, onFailed); + } - @Override - public void onFailure(Call> call, final Throwable t) { - Log.e("Login", t.toString()); - onFailed.run(new Exception(t)); - } - }); + @Override + public void onFailure(Call> call, final Throwable t) { + Log.e("Login", t.toString()); + onFailed.run(new Exception(t)); + } + }); + } + + + public void retrieveAvailableProfiles(String protocol, String host, int port, String username, RunnableArgs> onComplete, RunnableArgs onFailed) { + LoginRESTConsumerService service = RESTBuilder.getService(LoginRESTConsumerService.class, protocol, host, port, false); + + service.retreiveAvailableProfiles(username) + .enqueue(new Callback<>() { + @Override + public void onResponse(Call>> call, Response>> response) { + analyzeAnswer(response, "retrieveAvailableProfiles", onComplete, onFailed); + } + + @Override + public void onFailure(Call>> call, Throwable t) { + Log.e("Login", t.toString()); + onFailed.run(new Exception(t)); + } + }); } diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/login/rest/LoginRESTConsumerService.java b/app/src/main/java/it/integry/integrywmsnative/gest/login/rest/LoginRESTConsumerService.java index f2cfb277..f8825d19 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/login/rest/LoginRESTConsumerService.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/login/rest/LoginRESTConsumerService.java @@ -1,10 +1,13 @@ package it.integry.integrywmsnative.gest.login.rest; +import java.util.List; + import it.integry.integrywmsnative.core.rest.model.ServiceRESTResponse; import it.integry.integrywmsnative.gest.login.dto.LoginAziendaDTO; -import it.integry.integrywmsnative.gest.login.dto.LoginResponseDTO; +import it.integry.integrywmsnative.gest.login.dto.LoginJwtResponseDTO; import it.integry.integrywmsnative.gest.login.dto.LoginRequestDTO; +import it.integry.integrywmsnative.gest.login.dto.LoginResponseDTO; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.GET; @@ -20,4 +23,10 @@ public interface LoginRESTConsumerService { @POST("loginWeb") Call> login(@Body LoginRequestDTO loginRequestDTO); + @POST("auth/login") + Call> loginNew(@Body LoginRequestDTO loginRequestDTO); + + @GET("users/availableProfiles") + Call>> retreiveAvailableProfiles(@Query("username") String username); + } diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/login/viewmodel/LoginViewModel.java b/app/src/main/java/it/integry/integrywmsnative/gest/login/viewmodel/LoginViewModel.java index 32e2709c..bf3d6035 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/login/viewmodel/LoginViewModel.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/login/viewmodel/LoginViewModel.java @@ -1,18 +1,23 @@ package it.integry.integrywmsnative.gest.login.viewmodel; -import com.annimon.stream.Stream; +import com.auth0.android.jwt.JWT; +import com.google.firebase.installations.FirebaseInstallations; import java.net.MalformedURLException; import java.net.URL; import java.util.List; +import java.util.stream.Collectors; import javax.inject.Inject; +import it.integry.integrywmsnative.core.expansion.RunnableArgs; +import it.integry.integrywmsnative.core.expansion.RunnableArgsss; import it.integry.integrywmsnative.core.interfaces.viewmodel_listeners.ILoadingListener; import it.integry.integrywmsnative.core.rest.consumers.SystemRESTConsumer; import it.integry.integrywmsnative.core.settings.SettingsManager; import it.integry.integrywmsnative.core.utility.UtilityServer; import it.integry.integrywmsnative.core.utility.UtilityString; +import it.integry.integrywmsnative.gest.login.dto.AuthTokenClaimsDTO; import it.integry.integrywmsnative.gest.login.exception.InvalidServerCodAziendaException; import it.integry.integrywmsnative.gest.login.exception.InvalidUserDepositException; import it.integry.integrywmsnative.gest.login.rest.LoginRESTConsumer; @@ -35,6 +40,43 @@ public class LoginViewModel { public void login(String codAzienda, String username, String password) { this.sendOnLoadingStarted(); + retrieveServerData(codAzienda, (protocol, host, port) -> { + + UtilityServer.isEmsApiAvailable(protocol, host, port, () -> { + + FirebaseInstallations.getInstance().getId().addOnCompleteListener(fid -> { + + retrieveAvailableProfiles(protocol, host, port, username, selectedProfile -> { + SettingsManager.i().createUserSession(); + + authenticate(protocol, host, port, username, password, selectedProfile, fid.getResult(), fullName -> { + + SettingsManager.i().getUser() + .setFullname(fullName); + + SettingsManager.i().getServer() + .setCodAzienda(codAzienda) + .setProtocol(protocol) + .setHost(host) + .setPort(port); + + loadDepo(() -> { + SettingsManager.update(); + this.sendOnLoginCompleted(fullName); + }); + + }); + + }); + + }); + + }, this::sendError); + }); + } + + + private void retrieveServerData(String codAzienda, RunnableArgsss onComplete) { mLoginRESTConsumer.retrieveServerData(codAzienda, value -> { final String serverEndpoint = value.getEndpointRestApi(); @@ -52,52 +94,66 @@ public class LoginViewModel { final String host = u.getHost(); final int port = u.getPort(); - UtilityServer.isEmsApiAvailable(protocol, host, port, () -> { + onComplete.run(protocol, host, port); - mLoginRESTConsumer.authenticate(protocol, host, port, username, password, loginDTO -> { - - SettingsManager.i().createUserSession(); - SettingsManager.i().getUser().setFullname(!UtilityString.isNullOrEmpty(loginDTO.getFullName()) ? loginDTO.getFullName() : username); - - List availableProfiles = null; - if(loginDTO.getAvailableProfiles() != null && !loginDTO.getAvailableProfiles().isEmpty()) { - availableProfiles = Stream.of(loginDTO.getAvailableProfiles()) - .sorted() - .toList(); - } - - this.sendOnLoginCompleted(protocol, host, port, loginDTO.getFullName(), availableProfiles); - }, this::sendError); - - - }, this::sendError); }, ex -> { this.sendError(new InvalidServerCodAziendaException(codAzienda, ex)); }); } + private void retrieveAvailableProfiles(String protocol, String host, int port, String username, RunnableArgs onComplete) { + mLoginRESTConsumer.retrieveAvailableProfiles(protocol, host, port, username, availableProfiles -> { - public void loadDepo(String codAzienda, String protocol, String host, int port, String username, String password, Runnable onComplete) { + if (availableProfiles == null || availableProfiles.isEmpty()) { + this.sendError(new Exception("Non รจ stato trovato alcun profilo per l'utente: " + username)); + return; + } - SettingsManager.i().getServer().setCodAzienda(codAzienda); - SettingsManager.i().getServer().setProtocol(protocol); - SettingsManager.i().getServer().setHost(host); - SettingsManager.i().getServer().setPort(port); + if (availableProfiles.size() == 1) { + onComplete.run(availableProfiles.get(0)); - SettingsManager.i().getUser().setUsername(username); - SettingsManager.i().getUser().setPassword(password); + } else { + availableProfiles = availableProfiles.stream() + .sorted() + .collect(Collectors.toList()); + + this.sendRequestProfileSelection(availableProfiles, onComplete); + } + }, this::sendError); + } + + private void authenticate(String protocol, String host, int port, String username, String password, String profileDb, String deviceSalt, RunnableArgs onComplete) { + mLoginRESTConsumer.authenticate(protocol, host, port, username, password, profileDb, deviceSalt, sessionData -> { + + JWT jwt = new JWT(sessionData.getAccessToken()); + var claims = jwt.getClaims(); + + AuthTokenClaimsDTO claimsDetails = claims.get("details").asObject(AuthTokenClaimsDTO.class); + + SettingsManager.i().getUserSession() + .setProfileDB(profileDb) + .setDeviceId(deviceSalt) + .setAccessToken(sessionData.getAccessToken()) + .setRefreshToken(sessionData.getRefreshToken()) + .setRefreshTokenExpiryDate(sessionData.getExpiryDate()); + + onComplete.run(UtilityString.isNull(claimsDetails.getUserDTO().getFullname(), claimsDetails.getUserDTO().getUsername())); + + }, this::sendError); + } + + public void loadDepo(Runnable onComplete) { this.mSystemRESTConsumer.getAvailableCodMdeps(availableCodMdeps -> { SettingsManager.iDB().setAvailableCodMdep(availableCodMdeps); - if (availableCodMdeps == null || availableCodMdeps.size() == 0) { + if (availableCodMdeps == null || availableCodMdeps.isEmpty()) { this.sendError(new InvalidUserDepositException()); return; } SettingsManager.i().getUserSession().setDepo(availableCodMdeps.get(0)); - if (onComplete != null) onComplete.run(); }, this::sendError); } @@ -111,9 +167,14 @@ public class LoginViewModel { if (this.mListener != null) mListener.onLoadingEnded(); } - private void sendOnLoginCompleted(String protocol, String host, int port, String fullName, List availableProfiles) { + private void sendOnLoginCompleted(String fullName) { if (this.mListener != null) - mListener.onLoginCompleted(protocol, host, port, fullName, availableProfiles); + mListener.onLoginCompleted(fullName); + } + + private void sendRequestProfileSelection(List availableProfiles, RunnableArgs onComplete) { + if (this.mListener != null) + mListener.requestProfileSelection(availableProfiles, onComplete); } private void sendError(Exception ex) { @@ -128,7 +189,9 @@ public class LoginViewModel { public interface Listener extends ILoadingListener { void onError(Exception ex); - void onLoginCompleted(String protocol, String host, int port, String fullName, List availableProfiles); + void onLoginCompleted(String fullName); + + void requestProfileSelection(List availableProfiles, RunnableArgs onComplete); } }