Skip to content

Instantly share code, notes, and snippets.

@johnnylambada
Created January 14, 2022 01:21
Show Gist options
  • Save johnnylambada/39f2c0d857cc00bc972ff292c6d71d71 to your computer and use it in GitHub Desktop.
Save johnnylambada/39f2c0d857cc00bc972ff292c6d71d71 to your computer and use it in GitHub Desktop.
class LoginActivity : AppCompatActivity() {
private val vm: LoginViewModel by viewModels()
private lateinit var binding: ActivityLoginBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityLoginBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.loginWithGoogleButton.setOnClickListener {
lifecycleScope.launchWhenCreated {
suspend fun tryLogin(onfail: ()->Unit ) {
val myUser = vm.loginAndReturnMyUser() // Call backend with google creds
if (myUser!=null) {
startMainActivity()
} else {
onfail()
}
}
try {
val result = Amplify.Auth.signInWithSocialWebUI(
AuthProvider.google(),
this@LoginActivity
)
if (result.isSignInComplete) {
Timber.i("LoginActivity: signed in: $result")
tryLogin {
Timber.e("getMe failed")
}
} else {
Timber.e("LoginActivity: sign in failed")
}
} catch (ex: AuthException) {
tryLogin {
Timber.e("LoginActivity: exception", ex)
}
}
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
Timber.d("requestCode=${requestCode} resultCode=${resultCode} data=$data")
if (requestCode == AWSCognitoAuthPlugin.WEB_UI_SIGN_IN_ACTIVITY_CODE) {
if (data != null) {
if (resultCode == Activity.RESULT_CANCELED) {
Amplify.Auth.handleWebUISignInResponse(data)
}
} else {
hideProgress()
}
}
}
private fun startMainActivity() {
startActivity(MainActivity.getStartingIntent(this))
}
companion object {
fun getStartingIntent(context: Context) = Intent(context, LoginActivity::class.java)
.apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment