Back to project page Joetz-Android-V2.
The source code is released under:
GNU General Public License
If you think the Android project Joetz-Android-V2 listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
package com.example.jens.myapplication.apimanager.manager; /*from w ww. j av a 2s.co m*/ import android.content.Context; import android.util.Base64; import com.example.jens.myapplication.apimanager.ApiConnection; import com.example.jens.myapplication.apimanager.CancellableTask; import com.example.jens.myapplication.apimanager.PostRequestTask; import com.example.jens.myapplication.apimanager.RequestParams; import com.example.jens.myapplication.apimanager.SimpleRequestTask; import com.example.jens.myapplication.domain.User; import com.example.jens.myapplication.domain.UserRole; import com.example.jens.myapplication.sam.JoetzApplication; import com.example.jens.myapplication.util.JsonUtils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; //import org.codehaus.jackson.map.ObjectMapper; /** * This class retrieves and holds user information for authentication throughout the application. */ public class LoginManager { private static final String URL_LOGIN = "api/users/login"; private static final String AUTH_FILE = "authFile"; // private static final int CRYPT_FLAG_NONE = 0; // private static final int CRYPT_FLAG_PASS = 1<<0; private final Context context; private String authKey = null; private User user; public LoginManager(Context context){ this.context = context; } /** * Checks if there is currently an authentication key stored in the cache * @return true if there is a key stored in the cache<br/> * false if there is no key in the cache */ public boolean existsCachedKey(){ File cacheDir = context.getCacheDir(); File authFile = new File(cacheDir.getPath() + "/" + AUTH_FILE); return authFile.exists(); } /** * Attempt to login with the cached key * @param afterTask Task to be executed when the request is finished * @return the task */ public CancellableTask tryLoginWithCachedKey(SimpleRequestTask afterTask){ String key = retrieveAuthToken(); if(key == null){ throw new IllegalStateException("No cached key was found"); } return login(key, afterTask, false); } /** * Perform a login request * @param email Email to try to login with * @param password Password to try to login with * @param postTask Task to be executed when the request is finished * @param stayLoggedIn Whether or not the key will be stored in the cache * to keep being logged in * @return the task */ public CancellableTask login(String email, String password, SimpleRequestTask postTask, boolean stayLoggedIn){ if(email == null || password == null){ throw new IllegalArgumentException("Email and password cannot be null"); } return login(createAuthKey(email, password), postTask, stayLoggedIn); } /** * Login procedure (creating authentication key) * @param tryAuthKey Authorization key * @param postTask SimpleTask instance with code that should be executed when response from * server is received. * @param stayLoggedIn Whether or not the key will be stored in the cache * to keep being logged in */ private CancellableTask login(final String tryAuthKey, final SimpleRequestTask postTask, final boolean stayLoggedIn){ if(authKey != null || user != null){ throw new IllegalStateException("Cannot attempt login while logged in"); } PostRequestTask<User> userTask = new PostRequestTask<User>() { @Override public void doTask(User obj, int statusCode) { if (statusCode == ApiConnection.STATUS_OK && obj != null) { user = obj; authKey = tryAuthKey; if(obj.getUserRole().value() >= UserRole.MONITOR.value()){ ActivityManager am = JoetzApplication.getContext().getActivityManager(); if(!am.isActivitiesLoaded()){ am.retrieveActivities(null); } } if(stayLoggedIn){ saveAuthKey(); } } postTask.doTask(statusCode); } }; RequestParams requestParams = new RequestParams() .setAuthKey(tryAuthKey); return ApiConnection.post(URL_LOGIN, JsonUtils.createSimpleUserTask(), userTask, requestParams); } public boolean isLoggedIn(){ return authKey != null; } public String getAuthKey(){ return authKey; } private void setAuthKey(String authKey){ this.authKey = authKey; } /** * Creates an authorization key (encoded base64) * @param email * @param password * @return The base64 encoded authorization key */ /*private String createAuthKey(String email, String password){ return createAuthKey(email, password, CRYPT_FLAG_NONE); }*/ /** * Creates an authorization key (encoded base64) * @param email * @param password * @return The base64 encoded authorization key */ private String createAuthKey(String email, String password){ String toEncode = email + ":" + password; String stringEncoded = ""; try { stringEncoded = "Basic " + Base64.encodeToString(toEncode.getBytes("UTF-8"), Base64.NO_WRAP); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return stringEncoded; } /* private String createAuthKey(String email, String password, int flagsEncodedPart){ String encPassword = (flagsEncodedPart&CRYPT_FLAG_PASS) > 0 ? password : AESEncryption.encrypt(password); String toEncode = email + ":" + encPassword; String stringEncoded = ""; try { stringEncoded = "Basic " + Base64.encodeToString(toEncode.getBytes("UTF-8"), Base64.NO_WRAP); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return stringEncoded; }*/ /** * Logout and clear cache */ public void logout(){ authKey = null; user = null; deleteSavedAuthToken(); } /** * Let the manager know the email has changed, to change the authorization key * @param email the new email */ public void emailChanged(String email){ String decoded = new String(Base64.decode(authKey.substring(6).getBytes(), Base64.NO_WRAP)); String pass = decoded.split(":")[1]; // String newKey = createAuthKey(email, pass, CRYPT_FLAG_PASS); String newKey = createAuthKey(email, pass); this.authKey = newKey; if(existsCachedKey()){ saveAuthKey(); } } /** * Let the manager know the password has changed, to change the authorization key * @param password the new password */ public void passwordChanged(String password){ String decoded = new String(Base64.decode(authKey.substring(6).getBytes(), Base64.NO_WRAP)); //String newKey = "Basic " + decoded.split(":")[0] + ":" + password; String email = decoded.split(":")[0]; String newKey = createAuthKey(email, password); this.authKey = newKey; if(existsCachedKey()){ saveAuthKey(); } } /** * Save the authorization key to the cache */ private void saveAuthKey(){ if(authKey == null){ return; } FileOutputStream fos = null; try{ //Use cache files to save token File cacheDir = context.getCacheDir(); File authFile = new File(cacheDir.getPath() + "/" + AUTH_FILE); if(!authFile.exists()){ authFile.createNewFile(); } fos = new FileOutputStream(authFile); fos.write(authKey.getBytes()); fos.close(); } catch (IOException e) { e.printStackTrace(); }finally{ if(fos != null){ try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * * @return AuthToken if it exists, null if it does not */ private String retrieveAuthToken(){ FileInputStream fis = null; try{ File cacheDir = context.getCacheDir(); File authFile = new File(cacheDir.getPath() + "/" + AUTH_FILE); if(!authFile.exists()){ return null; } fis = new FileInputStream(authFile); int amt = fis.available(); char[] chars = new char[amt]; for(int i=0; i<amt; i++){ chars[i] = (char) fis.read(); } return new String(chars); }catch(IOException e){ e.printStackTrace(); }finally{ if(fis != null){ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } /** * Delete auth token from the cache */ private void deleteSavedAuthToken(){ File cacheDir = context.getCacheDir(); File authTokenFile = new File(cacheDir.getPath() + "/" + AUTH_FILE); if(authTokenFile.exists()){ authTokenFile.delete(); } } public User getUser(){ return user; } /** * Set the current user, used to reflect the newly returned user object after a request * that modifies the current user. * @param user */ public void setUser(User user){ if(!isLoggedIn()){ throw new IllegalStateException("Trying to set user without being logged in"); } this.user = user; } public void setLoggedInUser(User user, String password){ String email = user.getPerson().getEmail(); if(email == null || password == null || email.isEmpty() || password.isEmpty()){ throw new IllegalArgumentException("Password and email are required"); } String authKey = createAuthKey(email, password); setAuthKey(authKey); setUser(user); } }