com.vodafone360.people.engine.login
Class LoginEngine

java.lang.Object
  extended by com.vodafone360.people.engine.BaseEngine
      extended by com.vodafone360.people.engine.login.LoginEngine

public class LoginEngine
extends BaseEngine

Engine handling sign in to existing accounts and sign up to new accounts.


Nested Class Summary
static interface LoginEngine.ILoginEventsListener
          Listener interface that can be used by clients to receive login state events from the engine.
private static class LoginEngine.State
          List of states for LoginEngine.
 
Nested classes/interfaces inherited from class com.vodafone360.people.engine.BaseEngine
BaseEngine.IEngineEventCallback
 
Field Summary
private static long ACTIVATE_LOGIN_TIMEOUT
          Timeout used when waiting for the server to sent an activation SMS.
private static java.lang.String AUTH_SESSION_HOLDER
          Used to verify datatype of server response for Auth.getSessionByCredentials(com.vodafone360.people.engine.BaseEngine, java.lang.String, java.lang.String, java.util.Map>) request.
private  java.lang.String mActivationCode
          Holds the activation code once an activation SMS has been received.
private  boolean mAreLoginDetailsValid
          Determines if current login information from database can be used to establish a session.
private  Context mContext
          Context used for listening to SMS events
private  boolean mCurrentLoginState
          Determines if the user is currently logged in with a valid session
private  java.lang.String mCurrentSubscriberId
          Subscriber ID fetched from SIM card
private  DatabaseHelper mDb
          Database used for fetching/storing state information
private  BroadcastReceiver mEventReceiver
          A broadcast receiver which is used to receive notifications when a data SMS arrives.
private  java.util.ArrayList<LoginEngine.ILoginEventsListener> mEventsListener
          Contains a list of login engine observers which will be notified when the login engine changes state.
private  boolean mIsRegistrationComplete
          Set to true when sign in or sign up has been completed by the user.
private  LoginDetails mLoginDetails
          Contains user login details such as user name and password
private  java.lang.Object mMutex
          mutex for thread synchronization
private  PublicKeyDetails mPublicKey
          Contains a public key for encrypting login details to be sent to the server
private  RegistrationDetails mRegistrationDetails
          Contains user registration details such as name, username, password, etc.
private static int MS_IN_SECONDS
          To convert between seconds and milliseconds
private  LoginEngine.State mState
          Current state of the engine
private  TelephonyManager mTelephonyManager
          Android telephony manager used for fetching subscriber ID
private static AuthSessionHolder sActivatedSession
          Contains the authenticated session information while the user is logged in
private static java.lang.String STATUS_MSG
          Used to verify datatype of server response to request activation code and activation account.
 
Fields inherited from class com.vodafone360.people.engine.BaseEngine
mActiveUiRequest, mCurrentTimeout, mEngineId, mEventCallback
 
Constructor Summary
LoginEngine(Context context, BaseEngine.IEngineEventCallback eventCallback, DatabaseHelper db)
          Public constructor.
 
Method Summary
 void addListener(LoginEngine.ILoginEventsListener listener)
          Add a listener which will receive events whenever the login state changes.
 void addUiFetchPrivacyStatementRequest()
          Called by the INowPlusService implementation to privacy statement for the UI.
 void addUiFetchTermsOfServiceRequest()
          Called by the INowPlusService implementation to fetch terms of service text for the UI.
 void addUiGetUsernameStateRequest(java.lang.String username)
          Called by the INowPlusService implementation to check if a username is available for registration.
 void addUiLoginRequest(LoginDetails loginDetails)
          Called by the INowPlusService implementation to start a manual login.
 void addUiRegistrationRequest(RegistrationDetails details)
          Called by the INowPlusService implementation to start the sign-up process.
 void addUiRemoveUserDataRequest()
          Called by the INowPlusService implementation to remove user data Issues a UI request to effectively log out.
 boolean getLoginRequired()
          A helper function which determines which activity should be displayed when the UI is loaded.
 void getNewPublicKey()
          Requests a new Public Key from the server.
 long getNextRunTime()
          Return the absolute time in milliseconds when the engine needs to run (based on System.currentTimeMillis).
static AuthSessionHolder getSession()
          Retrieves the active comms session.
private  void handleActivateAccountResponse(java.util.List<BaseDataType> data)
          Called when a response to the Activate API is received (manual login or sign-up).
private  void handleCreateSessionAutoResponse(java.util.List<BaseDataType> data)
          Called when a response to the GetSessionByCredentials API is received (auto login).
private  void handleCreateSessionManualResponse(java.util.List<BaseDataType> data)
          Called when a response to the GetSessionByCredentials API is received (manual login).
private  void handleNewPublicKeyResponse(java.util.List<BaseDataType> mDataTypes)
          Called when a response to the server fetch public key request is received.
private  void handleRequestingActivationResponse(java.util.List<BaseDataType> data)
          Called when a response to the RequestActivationCode API is received (manual login).
private  void handleServerSimpleTextResponse(java.util.List<BaseDataType> data)
          Called when a response to the GetTermsAndConditions, GetPrivacyStatement and GetUsernameState APIs are received.
private  void handleSignUpResponse(java.util.List<BaseDataType> data)
          Called when a response to the sign-up API is received.
private  void handleSmsResponse()
          Called when an SMS is received during sign-up or manual login.
private  void initialiseEngine()
          Called by the run() function the first time it is executed to perform non-trivial initialisation such as auto login.
 boolean isLoggedIn()
          Determines if the user is currently logged in with a valid session.
private static java.lang.String makeSecurePassword(java.lang.String userName, java.lang.String password, long ts)
          Concatenates the username, password, current time and some other data into a string which can be encrypted and sent to the server.
private  void newState(LoginEngine.State newState)
          Changes the state of the engine.
 void onCreate()
          This will be called immediately after creation to perform extra initialisation.
 void onDestroy()
          This will be called just before the engine is shutdown.
private  void onLoginStateChanged(boolean loggedIn)
          Called when the engine transitions between the logged in and logged out states.
protected  void onRequestComplete()
          Called by the base engine implementation whenever a UI request is completed to do any necessary cleanup.
 void onReset()
          Called by the framework before a remove user data operation takes place.
protected  void onTimeoutEvent()
          Handles timeouts for SMS activation and auto login retries.
private  byte[] prepareBytesForSignup(long timeStampInSeconds)
          Encrypts the sign-up data ready for sending to the server
protected  void processCommsResponse(ResponseQueue.Response resp)
          Called when a server response is received, processes the response based on the engine state.
protected  void processUiRequest(ServiceUiRequest requestId, java.lang.Object data)
          Called when a UI request is ready to be processed.
private  void removeAllListeners()
          Remove all ILoginStateChangeListener (done as part of cleanup).
 void removeListener(LoginEngine.ILoginEventsListener listener)
          Remove a listener added by the addListener function.
private  void restoreLoginState()
          Once the engine has finished processing a user request, this function is called to restore the state back to an appropriate value (based on the user login state).
 boolean retryAutoLogin()
          Retries to log the user in based on credential information stored in the database.
 void run()
          Do some work but anything that takes longer than 1 second must be broken up.
 void setActivatedSession(AuthSessionHolder session)
          Helper function to store the new session in the database and inform clients that the session has changed.
private  void setRegistrationComplete(boolean value)
          Helper function to set the registration complete flag and update the database with the new state.
static void setTestSession(AuthSessionHolder session)
          Set 'dummy' auth session for test purposes only.
private  void startActivateAccount()
          Sends a activate account request to the server.
private  void startFetchPrivacyStatement()
          Sends a fetch privacy statement request to the server.
private  void startFetchTermsOfService()
          Sends a fetch terms of service request to the server.
private  void startFetchUsernameState(java.lang.String username)
          Sends a fetch user-name state request to the server.
private  void startGetSessionManual()
          Sends a get session by credentials request to the server.
private  void startLogout()
          Clears the session and registration complete information so that the user will need to manually login again to use the now+ services.
private  void startManualLoginProcess(LoginDetails details)
          Sets registration complete flag to false then starts a new sign-in request.
private  void startRegistrationProcessCrypted(RegistrationDetails details)
          Starts the sign-up process where the password is RSA encrypted.
private  void startRequestActivationCode()
          Sends a request activation code request to the server.
private  void startSignUpCrypted(byte[] theBytes, long timestamp)
          Puts the engine into the signing up state and sends an encrypted sign-up request to the server.
private  boolean uiRequestReady()
          Helper function which returns true if a UI request is waiting on the queue and we are ready to process it.
private  boolean validateRegistrationDetails()
          Basic check to determine if the registration details given by the user are valid
 
Methods inherited from class com.vodafone360.people.engine.BaseEngine
addUiRequestToQueue, clearTimeout, completeUiRequest, completeUiRequest, deactivateEngine, emptyUiRequestQueue, engineId, genericHandleResponseType, getCurrentTimeout, isCommsResponseOutstanding, isDeactivated, isUiRequestOutstanding, onCommsInMessage, processCommsInQueue, processTimeout, processUiQueue, setReqId, setTimeout
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

mMutex

private final java.lang.Object mMutex
mutex for thread synchronization


STATUS_MSG

private static final java.lang.String STATUS_MSG
Used to verify datatype of server response to request activation code and activation account.

See Also:
Constant Field Values

AUTH_SESSION_HOLDER

private static final java.lang.String AUTH_SESSION_HOLDER
Used to verify datatype of server response for Auth.getSessionByCredentials(com.vodafone360.people.engine.BaseEngine, java.lang.String, java.lang.String, java.util.Map>) request.

See Also:
Constant Field Values

MS_IN_SECONDS

private static final int MS_IN_SECONDS
To convert between seconds and milliseconds

See Also:
Constant Field Values

mState

private LoginEngine.State mState
Current state of the engine


mContext

private Context mContext
Context used for listening to SMS events


mDb

private DatabaseHelper mDb
Database used for fetching/storing state information


mCurrentSubscriberId

private java.lang.String mCurrentSubscriberId
Subscriber ID fetched from SIM card


mTelephonyManager

private TelephonyManager mTelephonyManager
Android telephony manager used for fetching subscriber ID


sActivatedSession

private static AuthSessionHolder sActivatedSession
Contains the authenticated session information while the user is logged in


mLoginDetails

private final LoginDetails mLoginDetails
Contains user login details such as user name and password


mPublicKey

private PublicKeyDetails mPublicKey
Contains a public key for encrypting login details to be sent to the server


mRegistrationDetails

private final RegistrationDetails mRegistrationDetails
Contains user registration details such as name, username, password, etc.


mAreLoginDetailsValid

private boolean mAreLoginDetailsValid
Determines if current login information from database can be used to establish a session. Set to false if login fails repeatedly.


ACTIVATE_LOGIN_TIMEOUT

private static final long ACTIVATE_LOGIN_TIMEOUT
Timeout used when waiting for the server to sent an activation SMS. If this time in milliseconds is exceeded, the login will fail with SMS not received error.

See Also:
Constant Field Values

mActivationCode

private java.lang.String mActivationCode
Holds the activation code once an activation SMS has been received.


mIsRegistrationComplete

private boolean mIsRegistrationComplete
Set to true when sign in or sign up has been completed by the user. When this is false the landing page will be displayed when the application is launched.


mEventsListener

private final java.util.ArrayList<LoginEngine.ILoginEventsListener> mEventsListener
Contains a list of login engine observers which will be notified when the login engine changes state.


mCurrentLoginState

private boolean mCurrentLoginState
Determines if the user is currently logged in with a valid session


mEventReceiver

private final BroadcastReceiver mEventReceiver
A broadcast receiver which is used to receive notifications when a data SMS arrives.

Constructor Detail

LoginEngine

public LoginEngine(Context context,
                   BaseEngine.IEngineEventCallback eventCallback,
                   DatabaseHelper db)
Public constructor.

Parameters:
context - The service Context
eventCallback - Provides access to useful engine manager functionality
db - The Now+ database used for fetching/storing login state information
Method Detail

onCreate

public void onCreate()
This will be called immediately after creation to perform extra initialisation.

Specified by:
onCreate in class BaseEngine

onDestroy

public void onDestroy()
This will be called just before the engine is shutdown. Cleans up any resources used.

Specified by:
onDestroy in class BaseEngine

addUiLoginRequest

public void addUiLoginRequest(LoginDetails loginDetails)
Called by the INowPlusService implementation to start a manual login. Adds a manual login UI request to the queue and kicks the worker thread.

Parameters:
loginDetails - The login information entered by the user

addUiRemoveUserDataRequest

public void addUiRemoveUserDataRequest()
Called by the INowPlusService implementation to remove user data Issues a UI request to effectively log out.


addUiRegistrationRequest

public void addUiRegistrationRequest(RegistrationDetails details)
Called by the INowPlusService implementation to start the sign-up process. Adds a registration UI request to the queue and kicks the worker thread.

Parameters:
details - The registration details entered by the user

addUiFetchTermsOfServiceRequest

public void addUiFetchTermsOfServiceRequest()
Called by the INowPlusService implementation to fetch terms of service text for the UI. Adds a fetch terms of service UI request to the queue and kicks the worker thread.


addUiFetchPrivacyStatementRequest

public void addUiFetchPrivacyStatementRequest()
Called by the INowPlusService implementation to privacy statement for the UI. Adds a fetch privacy statement UI request to the queue and kicks the worker thread.


addUiGetUsernameStateRequest

public void addUiGetUsernameStateRequest(java.lang.String username)
Called by the INowPlusService implementation to check if a username is available for registration. Adds a get username state UI request to the queue and kicks the worker thread.

Parameters:
username - Username to fetch the state of

getNextRunTime

public long getNextRunTime()
Return the absolute time in milliseconds when the engine needs to run (based on System.currentTimeMillis).

Specified by:
getNextRunTime in class BaseEngine
Returns:
-1 never needs to run, 0 needs to run as soon as possible, CurrentTime + 60000 to run in 1 minute, etc.

run

public void run()
Do some work but anything that takes longer than 1 second must be broken up. The type of work done includes:

Specified by:
run in class BaseEngine

uiRequestReady

private boolean uiRequestReady()
Helper function which returns true if a UI request is waiting on the queue and we are ready to process it.

Returns:
true if the request can be processed now.

isLoggedIn

public boolean isLoggedIn()
Determines if the user is currently logged in with a valid session.

Returns:
true if logged in, false otherwise

addListener

public void addListener(LoginEngine.ILoginEventsListener listener)
Add a listener which will receive events whenever the login state changes.

Parameters:
listener - The callback interface

removeListener

public void removeListener(LoginEngine.ILoginEventsListener listener)
Remove a listener added by the addListener function.

Parameters:
listener - The same callback interface passed in to the add function

removeAllListeners

private void removeAllListeners()
Remove all ILoginStateChangeListener (done as part of cleanup).


restoreLoginState

private void restoreLoginState()
Once the engine has finished processing a user request, this function is called to restore the state back to an appropriate value (based on the user login state).


processCommsResponse

protected void processCommsResponse(ResponseQueue.Response resp)
Called when a server response is received, processes the response based on the engine state.

Specified by:
processCommsResponse in class BaseEngine
Parameters:
resp - Response data from server

processUiRequest

protected void processUiRequest(ServiceUiRequest requestId,
                                java.lang.Object data)
Called when a UI request is ready to be processed. Handlers the UI request based on the type.

Specified by:
processUiRequest in class BaseEngine
Parameters:
requestId - UI request type
data - Interpretation of this data depends on the request type

initialiseEngine

private void initialiseEngine()
Called by the run() function the first time it is executed to perform non-trivial initialisation such as auto login.


startRegistrationProcessCrypted

private void startRegistrationProcessCrypted(RegistrationDetails details)
Starts the sign-up process where the password is RSA encrypted. A setting determines if this function is used in preference to #startRegistrationProcess(RegistrationDetails) function.

Parameters:
details - Registration details received from the UI request

prepareBytesForSignup

private byte[] prepareBytesForSignup(long timeStampInSeconds)
                              throws InvalidCipherTextException
Encrypts the sign-up data ready for sending to the server

Parameters:
timeStampInSeconds - Current time in milliseconds
Returns:
Raw data that can be sent to the server
Throws:
InvalidCipherTextException

makeSecurePassword

private static java.lang.String makeSecurePassword(java.lang.String userName,
                                                   java.lang.String password,
                                                   long ts)
Concatenates the username, password, current time and some other data into a string which can be encrypted and sent to the server.

Parameters:
userName - User name for sign-in or sign-up
password - Password as entered by user
ts - Current time in milliseconds
Returns:
Concatenated data

startSignUpCrypted

private void startSignUpCrypted(byte[] theBytes,
                                long timestamp)
Puts the engine into the signing up state and sends an encrypted sign-up request to the server.

Parameters:
theBytes - byte-array containing encrypted password data.
timestamp - Current timestamp.

validateRegistrationDetails

private boolean validateRegistrationDetails()
Basic check to determine if the registration details given by the user are valid

Returns:
true if the details are valid, false otherwise.

getNewPublicKey

public void getNewPublicKey()
Requests a new Public Key from the server.


startFetchTermsOfService

private void startFetchTermsOfService()
Sends a fetch terms of service request to the server.


startFetchPrivacyStatement

private void startFetchPrivacyStatement()
Sends a fetch privacy statement request to the server.


startFetchUsernameState

private void startFetchUsernameState(java.lang.String username)
Sends a fetch user-name state request to the server.

Parameters:
username, - the user-name to retrieve information for.

startManualLoginProcess

private void startManualLoginProcess(LoginDetails details)
Sets registration complete flag to false then starts a new sign-in request.

Parameters:
details - Login details received from the UI request

startRequestActivationCode

private void startRequestActivationCode()
Sends a request activation code request to the server.


startGetSessionManual

private void startGetSessionManual()
Sends a get session by credentials request to the server.


startActivateAccount

private void startActivateAccount()
Sends a activate account request to the server.


startLogout

private void startLogout()
Clears the session and registration complete information so that the user will need to manually login again to use the now+ services. Does not currently send a request to the server to log out.


retryAutoLogin

public boolean retryAutoLogin()
Retries to log the user in based on credential information stored in the database.

Returns:
true if the login process was able to start

setRegistrationComplete

private void setRegistrationComplete(boolean value)
Helper function to set the registration complete flag and update the database with the new state.

Parameters:
value - true if registration is completed

newState

private void newState(LoginEngine.State newState)
Changes the state of the engine. Also displays the login notification if necessary.

Parameters:
newState - The new state

onLoginStateChanged

private void onLoginStateChanged(boolean loggedIn)
Called when the engine transitions between the logged in and logged out states. Notifies listeners.

Parameters:
loggedIn - true if the user is now logged in, false otherwise.

getLoginRequired

public boolean getLoginRequired()
A helper function which determines which activity should be displayed when the UI is loaded.

Returns:
true if landing page should be displayed, false otherwise

getSession

public static AuthSessionHolder getSession()
Retrieves the active comms session.

Returns:
The session or NULL if the user is logged out.

setActivatedSession

public void setActivatedSession(AuthSessionHolder session)
Helper function to store the new session in the database and inform clients that the session has changed.

Parameters:
session - The new session or NULL if the user has logged off.

handleSignUpResponse

private void handleSignUpResponse(java.util.List<BaseDataType> data)
Called when a response to the sign-up API is received. In case of success sets a timeout value waiting for the activation SMS to arrive.

Parameters:
data - The received data

handleNewPublicKeyResponse

private void handleNewPublicKeyResponse(java.util.List<BaseDataType> mDataTypes)
Called when a response to the server fetch public key request is received. Validates the response and stores the new public key details.

Parameters:
mDataTypes - Response data from server.

handleCreateSessionManualResponse

private void handleCreateSessionManualResponse(java.util.List<BaseDataType> data)
Called when a response to the GetSessionByCredentials API is received (manual login). In case of success, tries to activate the account using the activation code received by SMS.

Parameters:
data - The received data

handleCreateSessionAutoResponse

private void handleCreateSessionAutoResponse(java.util.List<BaseDataType> data)
Called when a response to the GetSessionByCredentials API is received (auto login). In case of success, moves to the logged in state

Parameters:
data - The received data

handleRequestingActivationResponse

private void handleRequestingActivationResponse(java.util.List<BaseDataType> data)
Called when a response to the RequestActivationCode API is received (manual login). In case of success, tries to fetch a login session from the server.

Parameters:
data - The received data

handleActivateAccountResponse

private void handleActivateAccountResponse(java.util.List<BaseDataType> data)
Called when a response to the Activate API is received (manual login or sign-up). In case of success, moves to the logged in state and completes the manual login or sign-up request.

Parameters:
data - The received data

handleServerSimpleTextResponse

private void handleServerSimpleTextResponse(java.util.List<BaseDataType> data)
Called when a response to the GetTermsAndConditions, GetPrivacyStatement and GetUsernameState APIs are received. In case of success, completes the request and passes the response data to the UI.

Parameters:
data - The received data

handleSmsResponse

private void handleSmsResponse()
Called when an SMS is received during sign-up or manual login. Starts requesting a session from the server.


onRequestComplete

protected void onRequestComplete()
Called by the base engine implementation whenever a UI request is completed to do any necessary cleanup. We use it to restore our state to a suitable value.

Specified by:
onRequestComplete in class BaseEngine

onTimeoutEvent

protected void onTimeoutEvent()
Handles timeouts for SMS activation and auto login retries.

Specified by:
onTimeoutEvent in class BaseEngine

onReset

public void onReset()
Called by the framework before a remove user data operation takes place. Initiates a suitable UI request which will kick the worker thread.

Overrides:
onReset in class BaseEngine

setTestSession

public static void setTestSession(AuthSessionHolder session)
Set 'dummy' auth session for test purposes only.

Parameters:
session - 'dummy' session supplied to LoginEngine


JavaDoc