Skip to content

Instantly share code, notes, and snippets.

@alorma
Created June 7, 2014 18:08
Show Gist options
  • Save alorma/494a4513210c357ab773 to your computer and use it in GitHub Desktop.
Save alorma/494a4513210c357ab773 to your computer and use it in GitHub Desktop.
package app.picaboo.android.security;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import java.util.UUID;
/**
* Created by Bernat on 07/06/2014.
*/
public class CredentialsHelper {
private static final String KEY_USER = "KEY_USER";
private static final String KEY_PASS = "KEY_PASS";
private final SharedPreferences preferences;
public CredentialsHelper(Context context) {
preferences = PreferenceManager.getDefaultSharedPreferences(context);
}
public void saveUser(String user, String password) {
SharedPreferences.Editor editor = preferences.edit();
editor.putString(KEY_USER, user);
editor.putString(KEY_PASS, password);
editor.commit();
}
private void savePass(String password) {
SharedPreferences.Editor editor = preferences.edit();
editor.putString(KEY_PASS, password);
editor.commit();
}
public String getUser() {
return preferences.getString(KEY_USER, "");
}
public String getPassword() {
String pass = preferences.getString(KEY_PASS, null);
if (pass == null) {
pass = getRandomPassword();
savePass(pass);
}
return pass;
}
private String getRandomPassword() {
return UUID.randomUUID().toString();
}
public void clear() {
SharedPreferences.Editor editor = preferences.edit();
editor.remove(KEY_USER);
editor.remove(KEY_PASS);
editor.commit();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment