Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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