package com.betaseries.betaseries.authentication; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import com.betaseries.betaseries.authentication.model.Authentication; import com.betaseries.betaseries.authentication.webservice.AuthenticationService; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import rx.Observable; /** * Created by florentchampigny on 11/04/15. */ public class AuthenticationManager { private static final String PREFS_AUTH = "PREFS_AUTH"; private static final String TOKEN = "TOKEN"; private static final String NOM_UTILISATEUR = "NOM_UTILISATEUR"; protected SharedPreferences sharedPreferences; protected AuthenticationService authenticationService; public AuthenticationManager(AuthenticationService authenticationService, Context context) { this.authenticationService = authenticationService; sharedPreferences = context.getSharedPreferences(PREFS_AUTH, Context.MODE_PRIVATE); } public void setToken(String token) { sharedPreferences.edit().putString(TOKEN, token).apply(); } public String getToken() { return sharedPreferences.getString(TOKEN, null); } public String getNomUtilisateur() { return sharedPreferences.getString(NOM_UTILISATEUR, null); } public void setNomUtilisateur(String nomUtilisateur) { sharedPreferences.edit().putString(NOM_UTILISATEUR, nomUtilisateur).apply(); } public boolean isAuthentified() { return getToken() != null; } public Observable<Authentication> authentifier(String login, String password) { return Observable.create(subscriber -> authenticationService.authentifier(login, toMd5(password)) .doOnError(subscriber::onError) .onErrorReturn(null) .subscribe(authentification -> { setToken(authentification.getToken()); setNomUtilisateur(login); subscriber.onNext(authentification); // after sending all values we complete the sequence subscriber.onCompleted(); }) ); } private String toMd5(String string) { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] messageDigest = md.digest(string.getBytes()); BigInteger number = new BigInteger(1, messageDigest); String md5 = number.toString(16); while (md5.length() < 32) md5 = "0" + md5; return md5; } catch (NoSuchAlgorithmException e) { Log.e("MD5", e.getLocalizedMessage()); return null; } } }