Guest User

Untitled

a guest
Apr 26th, 2018
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.75 KB | None | 0 0
  1. /**
  2. * Part of the AuthenticationHandler interface
  3. *
  4. * Called when the Amazon Cognito service returns a valid set of tokens, when the tokens
  5. * are available (cached) or after successful completion of the authentication process.
  6. *
  7. * @param userSession Contains the valid user tokens
  8. * @param newDevice If this is a new device, then contains the device information
  9. */
  10. override fun onSuccess(userSession: CognitoUserSession?, newDevice: CognitoDevice?) {
  11. Log.i(TAG, "onSuccess()")
  12. val cognitoUser = (identityManager as AWSIdentityManager).userPool.currentUser
  13. val user = User(cognitoUser.userId)
  14.  
  15. // This is the important token storage part
  16. userSession?.let {
  17. user.username = it.username
  18. user.tokens[TokenType.ACCESS_TOKEN] = userSession.accessToken.jwtToken
  19. user.tokens[TokenType.ID_TOKEN] = userSession.idToken.jwtToken
  20. user.tokens[TokenType.REFRESH_TOKEN] = userSession.refreshToken.token
  21. }
  22.  
  23. // Obtain the details about the user from Amazon Cognito
  24. cognitoUser.getDetails(object : GetDetailsHandler {
  25. /**
  26. * This method is called on successfully fetching user attributes.
  27. * `attributesList` contains all attributes set for the user.
  28. *
  29. * @param cognitoUserDetails contains the users' details retrieved from the Cognito Service
  30. */
  31. override fun onSuccess(cognitoUserDetails: CognitoUserDetails?) {
  32. Log.i(TAG, "getDetails::onSuccess()")
  33. cognitoUserDetails?.let {
  34. for ((key, value) in it.attributes.attributes) {
  35. user.userAttributes[key] = value
  36. }
  37. }
  38.  
  39. Log.d(TAG, "getDetails::onSuccess(): Details received")
  40.  
  41. runOnUiThread {
  42. identityManager.signin(user)
  43. this@AuthenticatorActivity.finish()
  44. }
  45. }
  46.  
  47. /**
  48. * This method is called upon encountering errors during this operation.
  49. * Probe `exception` for the cause of this exception.
  50. *
  51. * @param exception REQUIRED: Failure details.
  52. */
  53. override fun onFailure(exception: Exception?) {
  54. // Print out the message - this should technically not happen
  55. val message: String = exception?.localizedMessage ?: "Unknown error"
  56. Log.e(TAG, "getDetails::onFailure $message", exception)
  57.  
  58. runOnUiThread {
  59. identityManager.signin(user)
  60. this@AuthenticatorActivity.finish()
  61. }
  62. }
  63. })
  64. }
  65.  
  66. /**
  67. * This method is called when a fatal exception was encountered during
  68. * authentication. The current authentication process continue because of the error
  69. * , hence a continuation is not available. Probe `exception` for details.
  70. *
  71. * @param exception is this Exception leading to authentication failure.
  72. */
  73. override fun onFailure(exception: Exception?) {
  74. val message: String = exception?.localizedMessage ?: "Error submitting credentials"
  75. Log.e(TAG, "onFailure: $message", exception)
  76. runOnUiThread {
  77. alert("Error submitting credentials") {
  78. title = "Login Denied"
  79. positiveButton("Close") { }
  80. }.show()
  81. }
  82. }
  83.  
  84. /**
  85. * Obtain the credentials for the user.
  86. *
  87. * @param continuation A continuation object for continuing with the task
  88. * @param userId The user-ID (username or alias) used in authentication.
  89. */
  90. override fun getAuthenticationDetails(continuation: AuthenticationContinuation?, userId: String?) {
  91. // This should never occur!!! That's because we use initiateUserAuthentication() which gets
  92. // supplied with the authenticationDetails.
  93. Log.i(TAG, "getAuthenticationDetails()")
  94. val username = loginform_username.getContent()
  95. val password = loginform_password.getContent()
  96. val authDetails = AuthenticationDetails(username, password, HashMap<String, String>())
  97. continuation?.let {
  98. it.setAuthenticationDetails(authDetails)
  99. it.continueTask()
  100. }
  101. }
  102.  
  103. /**
  104. * Call out to the dev to respond to a challenge.
  105. * The authentication process as presented the user with the a challenge, to successfully authenticate.
  106. * This a generic challenge, that is not MFA or user password verification.
  107. *
  108. * @param continuation contains details about the challenge and allows dev to respond to the
  109. * challenge.
  110. */
  111. @SuppressLint("InflateParams")
  112. override fun authenticationChallenge(continuation: ChallengeContinuation?) {
  113. Log.i(TAG, "authenticationChallenge: ${continuation?.challengeName}")
  114.  
  115. when (continuation?.challengeName) {
  116. "NEW_PASSWORD_REQUIRED" -> {
  117. runOnUiThread {
  118. val newPasswordDialog = layoutInflater.inflate(R.layout.dialog_new_password, null)
  119. val passwordInput = newPasswordDialog.find(R.id.newpassworddialog_password) as EditText
  120. alert {
  121. title = "Enter New Password"
  122. customView = newPasswordDialog
  123. positiveButton("OK") {
  124. // Respond to the challenge
  125. Log.i(TAG, "authenticationChallenge: new password = ${passwordInput.getContent()}")
  126. continuation.setChallengeResponse("NEW_PASSWORD", passwordInput.getContent())
  127. continuation.setChallengeResponse("USERNAME", loginform_username.getContent())
  128. thread(start = true) { continuation.continueTask() }
  129. }
  130. }.show()
  131. }
  132. }
  133.  
  134. else -> {
  135. Log.e(TAG, "authenticationChallenge: error - unexpected challenge")
  136. throw NotImplementedError("authenticationChallenge is not implemented")
  137. }
  138. }
  139. }
  140.  
  141. /**
  142. * Call out to the dev to send MFA code.
  143. * MFA code would have been sent via the deliveryMethod before this is invoked.
  144. * This callback can be invoked in two scenarios -
  145. * 1) MFA verification is required and only one possible MFA delivery medium is
  146. * available.
  147. * 2) MFA verification is required and a MFA delivery medium was successfully set.
  148. * 3) An MFA code sent earlier was incorrect and at-least one more attempt to send
  149. * MFA code is available.
  150. *
  151. * @param continuation medium through which the MFA will be delivered
  152. */
  153. @Suppress("InflateParams")
  154. override fun getMFACode(continuation: MultiFactorAuthenticationContinuation?) {
  155. runOnUiThread {
  156. val mfaPromptDialog = layoutInflater.inflate(R.layout.dialog_mfa_prompt, null)
  157. val mfaInput = mfaPromptDialog.find(R.id.mfapromptdialog_code) as MFAEditText
  158. continuation?.let {
  159. val mfaInstructions = mfaPromptDialog.find(R.id.mfapromptdialog_instructions) as TextView
  160. mfaInstructions.text = "Enter the code we just sent to ${it.parameters.deliveryMedium}:${it.parameters.destination}"
  161. }
  162. alert {
  163. title = "Multi-factor Code Required"
  164. customView = mfaPromptDialog
  165. positiveButton("OK") {
  166. continuation?.let {
  167. Log.i(TAG, "getMFACode: new code = ${mfaInput.getContent()}")
  168. it.setMfaCode(mfaInput.getContent())
  169. thread(start = true) { it.continueTask() }
  170. }
  171. }
  172. }.show()
  173. }
  174. }
Add Comment
Please, Sign In to add comment