diff --git a/.gitignore b/.gitignore
index c4b45f3c..1b777d2f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -36,4 +36,5 @@ app/google-services.json
secrets.properties
# Mac
-.DS_store
\ No newline at end of file
+.DS_store
+.kotlin/
diff --git a/README.md b/README.md
index aecc01f1..44bb004f 100644
--- a/README.md
+++ b/README.md
@@ -11,3 +11,17 @@ Score is Cornell’s all-in-one sports discovery hub that makes Cornell sports e
- `secrets.properties`
4. Add `secrets.properties` to the project root and `google-services.json` to the app level in Android Studio
5. Build and run!
+
+## Authentication
+
+Google sign-in uses Credential Manager and Firebase Authentication, then exchanges the Firebase ID token for Score backend tokens. Enable Google as a sign-in provider in Firebase, register the Android signing SHA-1 and SHA-256 fingerprints, and install the updated `app/google-services.json`. The file must include the web OAuth client so the Google Services plugin generates `default_web_client_id`. The backend Firebase Admin configuration must use the same Firebase project.
+
+The backend must support `loginUser(idToken:)`, `signupUser(idToken:)`, `refreshAccessToken`, and `logoutUser`. Android requests the access and refresh tokens from login and signup. Cornell email filtering is also required on the backend to enforce the restriction outside this client.
+
+The welcome screen's Sign Up and Log In buttons both start Google sign-in. The app first calls `loginUser`; only a missing-user response triggers `signupUser`. Successful authentication enters the existing app, and Sign Up Later keeps guest browsing available.
+
+`AuthRepository.state` records the backend session. A Firebase session alone does not sign the user into Score. Backend sessions are encrypted using Android Keystore and stored outside backups. Session restoration refreshes expired access tokens; network failures preserve the saved session, while rejected refresh tokens clear it.
+
+Auth is currently limited to the welcome flow. Profile screens, profile and sports onboarding, and authorization headers on the app's existing API client are not connected to it.
+
+Run `./gradlew :app:testDebugUnitTest :app:lintDebug :app:assembleDebug` with Java 17 to verify the app. End-to-end Google sign-in needs a device or emulator with Google Play services and a backend configured for the updated Firebase project.
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 5a35daca..4b5fb85a 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -19,7 +19,6 @@ plugins {
id("com.google.gms.google-services")
}
-
android {
namespace = "com.cornellappdev.score"
compileSdk = 37
@@ -38,23 +37,15 @@ android {
}
buildTypes {
debug {
- buildConfigField(
- "String",
- "BASE_URL",
- "\"${secrets.getProperty("API_URL_DEV")}\""
- )
+ buildConfigField("String", "BASE_URL", "\"${secrets.getProperty("API_URL_DEV")}\"")
buildConfigField(
"String",
"SOCKET_URL",
- "\"${secrets.getProperty("SOCKET_URL_DEV")}\""
+ "\"${secrets.getProperty("SOCKET_URL_DEV")}\"",
)
}
release {
- buildConfigField(
- "String",
- "BASE_URL",
- "\"${secrets.getProperty("API_URL_PROD")}\""
- )
+ buildConfigField("String", "BASE_URL", "\"${secrets.getProperty("API_URL_PROD")}\"")
buildConfigField(
"String",
"SOCKET_URL",
@@ -63,7 +54,7 @@ android {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
- "proguard-rules.pro"
+ "proguard-rules.pro",
)
}
}
@@ -117,16 +108,25 @@ dependencies {
lintChecks(libs.compose.lint.checks)
implementation(platform("com.google.firebase:firebase-bom:35.2.0"))
implementation("com.google.firebase:firebase-analytics")
+ implementation("com.google.firebase:firebase-auth")
+ implementation("androidx.credentials:credentials:1.5.0")
+ implementation("androidx.credentials:credentials-play-services-auth:1.5.0")
+ implementation("com.google.android.libraries.identity.googleid:googleid:1.1.1")
+ implementation("org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.10.1")
+ implementation("androidx.lifecycle:lifecycle-runtime-compose:2.8.7")
}
apollo {
service("service") {
packageName.set("com.example.score")
- secrets.getProperty("API_URL_DEV")?.takeIf { it.isNotBlank() }?.let { apiUrl ->
- introspection {
- endpointUrl.set(apiUrl)
- schemaFile.set(file("src/main/graphql/schema.graphqls"))
+ secrets
+ .getProperty("API_URL_PROD")
+ ?.takeIf { it.isNotBlank() }
+ ?.let { apiUrl ->
+ introspection {
+ endpointUrl.set(apiUrl)
+ schemaFile.set(file("src/main/graphql/schema.graphqls"))
+ }
}
- }
}
}
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 730c7730..29f5b7d9 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -3,6 +3,7 @@
xmlns:tools="http://schemas.android.com/tools">
+
+ Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
+ CircularProgressIndicator(color = CrimsonPrimary)
+ }
+ showMainApp -> RootNavigation()
+ else ->
+ OnboardingSequence(
+ signedIn = signedIn,
+ onSignIn = { authViewModel.signIn(activity) },
+ onSkipSignIn = authViewModel::skipSignIn,
+ onOnboardingComplete = authViewModel::completeOnboarding,
+ )
+ }
+ AuthStatusOverlay(signInState, authViewModel::dismissError)
+ }
+}
diff --git a/app/src/main/java/com/cornellappdev/score/auth/AuthApi.kt b/app/src/main/java/com/cornellappdev/score/auth/AuthApi.kt
new file mode 100644
index 00000000..1eccd05a
--- /dev/null
+++ b/app/src/main/java/com/cornellappdev/score/auth/AuthApi.kt
@@ -0,0 +1,90 @@
+package com.cornellappdev.score.auth
+
+import com.apollographql.apollo.ApolloClient
+import com.apollographql.apollo.api.ApolloResponse
+import com.apollographql.apollo.api.http.HttpHeader
+import com.apollographql.apollo.exception.ApolloHttpException
+import com.example.score.LoginUserMutation
+import com.example.score.LogoutUserMutation
+import com.example.score.RefreshAccessTokenMutation
+import com.example.score.SignupUserMutation
+import javax.inject.Inject
+import javax.inject.Named
+
+interface AuthApi {
+ suspend fun login(idToken: String): AuthTokens
+
+ suspend fun signup(idToken: String): AuthTokens
+
+ suspend fun refresh(refreshToken: String): String
+
+ suspend fun revoke(token: String)
+}
+
+class UserNotFoundException : Exception()
+
+class InvalidSessionException : Exception()
+
+class ApolloAuthApi @Inject constructor(@Named("auth") private val client: ApolloClient) : AuthApi {
+ override suspend fun login(idToken: String): AuthTokens {
+ val response = client.mutation(LoginUserMutation(idToken)).execute()
+ if (response.errors?.any { it.message.removeSuffix(".") == "User not found" } == true) {
+ throw UserNotFoundException()
+ }
+ response.checkErrors()
+ val result = response.data?.loginUser ?: error("Missing login response")
+ return tokens(result.accessToken, result.refreshToken)
+ }
+
+ override suspend fun signup(idToken: String): AuthTokens {
+ val response = client.mutation(SignupUserMutation(idToken)).execute()
+ response.checkErrors()
+ val result = response.data?.signupUser ?: error("Missing signup response")
+ return tokens(result.accessToken, result.refreshToken)
+ }
+
+ override suspend fun refresh(refreshToken: String): String {
+ val response =
+ client
+ .mutation(RefreshAccessTokenMutation())
+ .httpHeaders(listOf(HttpHeader("Authorization", "Bearer $refreshToken")))
+ .execute()
+ val status = (response.exception as? ApolloHttpException)?.statusCode
+ if (status == 422 || response.isSessionRejected()) throw InvalidSessionException()
+ response.checkErrors()
+ return response.data?.refreshAccessToken?.newAccessToken?.takeIf { it.isNotBlank() }
+ ?: error("Missing refresh response")
+ }
+
+ override suspend fun revoke(token: String) {
+ client
+ .mutation(LogoutUserMutation())
+ .httpHeaders(listOf(HttpHeader("Authorization", "Bearer $token")))
+ .execute()
+ .checkErrors()
+ }
+
+ private fun tokens(access: String?, refresh: String?): AuthTokens {
+ require(!access.isNullOrBlank() && !refresh.isNullOrBlank()) { "Missing session tokens" }
+ return AuthTokens(access, refresh)
+ }
+
+ private fun ApolloResponse<*>.isSessionRejected(): Boolean {
+ if ((exception as? ApolloHttpException)?.statusCode == 401) return true
+ return errors.orEmpty().any {
+ it.extensions?.get("code") == "UNAUTHENTICATED" ||
+ it.message in
+ setOf(
+ "Token has expired",
+ "Token has been revoked",
+ "Signature verification failed",
+ "Not enough segments",
+ )
+ }
+ }
+
+ private fun ApolloResponse<*>.checkErrors() {
+ exception?.let { throw it }
+ check(errors.isNullOrEmpty()) { "Authentication request failed" }
+ }
+}
diff --git a/app/src/main/java/com/cornellappdev/score/auth/AuthModule.kt b/app/src/main/java/com/cornellappdev/score/auth/AuthModule.kt
new file mode 100644
index 00000000..791edb74
--- /dev/null
+++ b/app/src/main/java/com/cornellappdev/score/auth/AuthModule.kt
@@ -0,0 +1,27 @@
+package com.cornellappdev.score.auth
+
+import com.apollographql.apollo.ApolloClient
+import com.cornellappdev.score.BuildConfig
+import dagger.Binds
+import dagger.Module
+import dagger.Provides
+import dagger.hilt.InstallIn
+import dagger.hilt.components.SingletonComponent
+import javax.inject.Named
+import javax.inject.Singleton
+
+@Module
+@InstallIn(SingletonComponent::class)
+abstract class AuthModule {
+ @Binds @Singleton abstract fun bindStorage(storage: EncryptedSessionStorage): SessionStorage
+
+ @Binds @Singleton abstract fun bindApi(api: ApolloAuthApi): AuthApi
+
+ companion object {
+ @Provides
+ @Singleton
+ @Named("auth")
+ fun provideAuthClient(): ApolloClient =
+ ApolloClient.Builder().serverUrl(BuildConfig.BASE_URL).build()
+ }
+}
diff --git a/app/src/main/java/com/cornellappdev/score/auth/AuthRepository.kt b/app/src/main/java/com/cornellappdev/score/auth/AuthRepository.kt
new file mode 100644
index 00000000..349f8093
--- /dev/null
+++ b/app/src/main/java/com/cornellappdev/score/auth/AuthRepository.kt
@@ -0,0 +1,129 @@
+package com.cornellappdev.score.auth
+
+import javax.inject.Inject
+import javax.inject.Singleton
+import kotlin.time.Duration.Companion.milliseconds
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+
+@Singleton
+class AuthRepository
+@Inject
+constructor(private val authApi: AuthApi, private val sessionStorage: SessionStorage) {
+ private val mutex = Mutex()
+ private val _authState = MutableStateFlow(AuthState.Loading)
+ val authState = _authState.asStateFlow()
+ private var session: AuthSession? = null
+ private var hasRestoredSession = false
+
+ suspend fun restoreSession() {
+ var restoredFromStorage = false
+ for (attempt in 0 until RESTORE_ATTEMPTS) {
+ try {
+ mutex.withLock { restoreStoredSession() }
+ restoredFromStorage = true
+ break
+ } catch (error: CancellationException) {
+ throw error
+ } catch (_: Exception) {
+ if (attempt < RESTORE_ATTEMPTS - 1) {
+ delay((RESTORE_RETRY_DELAY_MILLIS * (attempt + 1)).milliseconds)
+ }
+ }
+ }
+
+ if (!restoredFromStorage) {
+ mutex.withLock { if (!hasRestoredSession) _authState.value = AuthState.SignedOut }
+ return
+ }
+
+ try {
+ getValidAccessToken()
+ } catch (error: CancellationException) {
+ throw error
+ } catch (_: Exception) {
+ // Network or refresh failures should not prevent a later token request from retrying.
+ }
+ }
+
+ suspend fun signIn(identity: GoogleIdentity) =
+ mutex.withLock {
+ require(identity.user.email.endsWith("@cornell.edu", ignoreCase = true))
+ val tokens =
+ try {
+ authApi.login(identity.firebaseIdToken)
+ } catch (_: UserNotFoundException) {
+ authApi.signup(identity.firebaseIdToken)
+ }
+ saveSession(AuthSession(identity.user, tokens.accessToken, tokens.refreshToken))
+ hasRestoredSession = true
+ }
+
+ suspend fun getValidAccessToken(): String? =
+ mutex.withLock {
+ restoreStoredSession()
+ val current = session ?: return@withLock null
+ if (!isTokenExpired(current.accessToken)) return@withLock current.accessToken
+ if (isTokenExpired(current.refreshToken)) {
+ clearSession()
+ return@withLock null
+ }
+ try {
+ val token = authApi.refresh(current.refreshToken)
+ saveSession(current.copy(accessToken = token))
+ token
+ } catch (_: InvalidSessionException) {
+ clearSession()
+ null
+ }
+ }
+
+ suspend fun signOut() {
+ val previous =
+ mutex.withLock {
+ val current = session
+ clearSession()
+ current
+ } ?: return
+ for (token in listOf(previous.refreshToken, previous.accessToken)) {
+ try {
+ authApi.revoke(token)
+ } catch (error: CancellationException) {
+ throw error
+ } catch (_: Exception) {}
+ }
+ }
+
+ private suspend fun restoreStoredSession() {
+ if (hasRestoredSession) return
+ session = sessionStorage.read()
+ hasRestoredSession = true
+ publishState()
+ }
+
+ private suspend fun saveSession(value: AuthSession) {
+ sessionStorage.save(value)
+ session = value
+ publishState()
+ }
+
+ private suspend fun clearSession() {
+ sessionStorage.clear()
+ session = null
+ hasRestoredSession = true
+ publishState()
+ }
+
+ private fun publishState() {
+ _authState.value = session?.let { AuthState.SignedIn(it.user) } ?: AuthState.SignedOut
+ }
+
+ private companion object {
+ const val RESTORE_ATTEMPTS = 3
+ const val RESTORE_RETRY_DELAY_MILLIS = 100L
+ }
+}
diff --git a/app/src/main/java/com/cornellappdev/score/auth/AuthState.kt b/app/src/main/java/com/cornellappdev/score/auth/AuthState.kt
new file mode 100644
index 00000000..f8b0eb6c
--- /dev/null
+++ b/app/src/main/java/com/cornellappdev/score/auth/AuthState.kt
@@ -0,0 +1,39 @@
+package com.cornellappdev.score.auth
+
+import java.util.Base64
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import kotlinx.serialization.json.longOrNull
+
+sealed interface AuthState {
+ data object Loading : AuthState
+
+ data object SignedOut : AuthState
+
+ data class SignedIn(val user: AuthUser) : AuthState
+}
+
+@Serializable data class AuthUser(val id: String, val name: String, val email: String)
+
+@Serializable
+data class AuthSession(val user: AuthUser, val accessToken: String, val refreshToken: String)
+
+data class AuthTokens(val accessToken: String, val refreshToken: String)
+
+data class GoogleIdentity(val user: AuthUser, val firebaseIdToken: String)
+
+fun isTokenExpired(token: String, nowMillis: Long = System.currentTimeMillis()): Boolean {
+ return try {
+ val payload = String(Base64.getUrlDecoder().decode(token.split('.')[1]), Charsets.UTF_8)
+ val expiresAt =
+ Json.parseToJsonElement(payload).jsonObject["exp"]?.jsonPrimitive?.longOrNull
+ ?: return true
+ expiresAt <= nowMillis / 1000 + 60
+ } catch (_: IllegalArgumentException) {
+ true
+ } catch (_: IndexOutOfBoundsException) {
+ true
+ }
+}
diff --git a/app/src/main/java/com/cornellappdev/score/auth/AuthStatusOverlay.kt b/app/src/main/java/com/cornellappdev/score/auth/AuthStatusOverlay.kt
new file mode 100644
index 00000000..63c53184
--- /dev/null
+++ b/app/src/main/java/com/cornellappdev/score/auth/AuthStatusOverlay.kt
@@ -0,0 +1,54 @@
+package com.cornellappdev.score.auth
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.window.Dialog
+import androidx.compose.ui.window.DialogProperties
+import com.cornellappdev.score.R
+import com.cornellappdev.score.theme.CrimsonPrimary
+
+@Composable
+fun AuthStatusOverlay(
+ state: SignInState,
+ onDismissError: () -> Unit,
+ modifier: Modifier = Modifier,
+) {
+ if (state.busy) {
+ Dialog(
+ onDismissRequest = {},
+ properties =
+ DialogProperties(
+ dismissOnBackPress = false,
+ dismissOnClickOutside = false,
+ usePlatformDefaultWidth = false,
+ ),
+ ) {
+ Box(
+ modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.2f)),
+ contentAlignment = Alignment.Center,
+ ) {
+ CircularProgressIndicator(color = CrimsonPrimary)
+ }
+ }
+ }
+ state.error?.let { message ->
+ AlertDialog(
+ onDismissRequest = onDismissError,
+ title = { Text(stringResource(R.string.auth_error_title)) },
+ text = { Text(stringResource(message)) },
+ confirmButton = {
+ TextButton(onClick = onDismissError) { Text(stringResource(android.R.string.ok)) }
+ },
+ )
+ }
+}
diff --git a/app/src/main/java/com/cornellappdev/score/auth/AuthViewModel.kt b/app/src/main/java/com/cornellappdev/score/auth/AuthViewModel.kt
new file mode 100644
index 00000000..8817753e
--- /dev/null
+++ b/app/src/main/java/com/cornellappdev/score/auth/AuthViewModel.kt
@@ -0,0 +1,152 @@
+package com.cornellappdev.score.auth
+
+import android.app.Activity
+import android.net.ConnectivityManager
+import android.net.NetworkCapabilities
+import android.util.Log
+import androidx.credentials.exceptions.GetCredentialCancellationException
+import androidx.credentials.exceptions.NoCredentialException
+import androidx.lifecycle.ViewModel
+import androidx.lifecycle.viewModelScope
+import com.cornellappdev.score.R
+import com.cornellappdev.score.model.OnboardingPreferencesRepository
+import dagger.hilt.android.lifecycle.HiltViewModel
+import javax.inject.Inject
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.launch
+
+data class SignInState(val busy: Boolean = false, val error: Int? = null)
+
+data class OnboardingState(val welcomeCompleted: Boolean, val profileSetupCompleted: Boolean)
+
+@HiltViewModel
+class AuthViewModel
+@Inject
+constructor(
+ private val authRepository: AuthRepository,
+ private val googleSignInClient: GoogleSignInClient,
+ private val onboardingPreferences: OnboardingPreferencesRepository,
+) : ViewModel() {
+ private companion object {
+ const val TAG = "AuthViewModel"
+ }
+
+ val authState = authRepository.authState
+ private val _signInState = MutableStateFlow(SignInState(busy = true))
+ val signInState = _signInState.asStateFlow()
+
+ private val _onboardingState =
+ MutableStateFlow(
+ OnboardingState(
+ welcomeCompleted = onboardingPreferences.isOnboardingCompleted(),
+ profileSetupCompleted = onboardingPreferences.isProfileSetupCompleted(),
+ )
+ )
+ val onboardingState = _onboardingState.asStateFlow()
+
+ fun skipSignIn() {
+ onboardingPreferences.markOnboardingCompleted()
+ _onboardingState.value = _onboardingState.value.copy(welcomeCompleted = true)
+ }
+
+ fun completeOnboarding() {
+ onboardingPreferences.markProfileSetupCompleted()
+ _onboardingState.value =
+ OnboardingState(welcomeCompleted = true, profileSetupCompleted = true)
+ }
+
+ init {
+ viewModelScope.launch {
+ Log.d(TAG, "Restoring saved Score session")
+ authRepository.restoreSession()
+ Log.d(
+ TAG,
+ "Session restoration complete; signedIn=${authRepository.authState.value is AuthState.SignedIn}",
+ )
+ _signInState.value = SignInState()
+ }
+ }
+
+ fun signIn(activity: Activity) {
+ if (_signInState.value.busy) return
+ if (!activity.hasInternetConnection()) {
+ _signInState.value = SignInState(error = R.string.auth_no_internet)
+ return
+ }
+ viewModelScope.launch {
+ _signInState.value = SignInState(busy = true)
+ try {
+ Log.i(TAG, "Google sign-in started")
+ val identity = googleSignInClient.signIn(activity)
+ Log.i(TAG, "Google/Firebase sign-in completed; starting backend authentication")
+ authRepository.signIn(identity)
+ Log.i(TAG, "Backend authentication completed; Score session saved")
+ _signInState.value = SignInState()
+ } catch (error: GetCredentialCancellationException) {
+ Log.w(TAG, "Google credential flow was cancelled: ${error.message}", error)
+ _signInState.value =
+ SignInState(
+ error =
+ if (activity.hasInternetConnection()) {
+ R.string.auth_sign_in_incomplete
+ } else {
+ R.string.auth_no_internet
+ }
+ )
+ } catch (_: NoCredentialException) {
+ Log.w(TAG, "No Google account is available for sign-in")
+ _signInState.value =
+ SignInState(
+ error =
+ if (activity.hasInternetConnection()) {
+ R.string.auth_no_google_account
+ } else {
+ R.string.auth_no_internet
+ }
+ )
+ } catch (_: CornellAccountRequiredException) {
+ Log.w(TAG, "Google sign-in rejected: account is not a Cornell account")
+ _signInState.value = SignInState(error = R.string.auth_cornell_required)
+ } catch (error: CancellationException) {
+ Log.i(TAG, "Sign-in coroutine was cancelled")
+ _signInState.value = SignInState()
+ throw error
+ } catch (error: Exception) {
+ Log.e(
+ TAG,
+ "Sign-in failed (${error.javaClass.simpleName}): ${error.message}",
+ error,
+ )
+ _signInState.value =
+ SignInState(
+ error =
+ if (activity.hasInternetConnection()) {
+ R.string.auth_sign_in_failed
+ } else {
+ R.string.auth_no_internet
+ }
+ )
+ try {
+ googleSignInClient.signOut()
+ } catch (cleanupError: CancellationException) {
+ throw cleanupError
+ } catch (cleanupError: Exception) {
+ Log.w(TAG, "Could not clear Google credential state", cleanupError)
+ }
+ }
+ }
+ }
+
+ private fun Activity.hasInternetConnection(): Boolean {
+ val connectivity = getSystemService(ConnectivityManager::class.java)
+ return connectivity
+ ?.getNetworkCapabilities(connectivity.activeNetwork)
+ ?.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) == true
+ }
+
+ fun dismissError() {
+ _signInState.value = _signInState.value.copy(error = null)
+ }
+}
diff --git a/app/src/main/java/com/cornellappdev/score/auth/GoogleSignInClient.kt b/app/src/main/java/com/cornellappdev/score/auth/GoogleSignInClient.kt
new file mode 100644
index 00000000..0932eea2
--- /dev/null
+++ b/app/src/main/java/com/cornellappdev/score/auth/GoogleSignInClient.kt
@@ -0,0 +1,61 @@
+package com.cornellappdev.score.auth
+
+import android.app.Activity
+import android.content.Context
+import androidx.credentials.ClearCredentialStateRequest
+import androidx.credentials.CredentialManager
+import androidx.credentials.CustomCredential
+import androidx.credentials.GetCredentialRequest
+import androidx.credentials.exceptions.ClearCredentialException
+import com.cornellappdev.score.R
+import com.google.android.libraries.identity.googleid.GetSignInWithGoogleOption
+import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential
+import com.google.firebase.auth.FirebaseAuth
+import com.google.firebase.auth.GoogleAuthProvider
+import dagger.hilt.android.qualifiers.ApplicationContext
+import javax.inject.Inject
+import kotlinx.coroutines.tasks.await
+
+class GoogleSignInClient @Inject constructor(@ApplicationContext private val context: Context) {
+ suspend fun signIn(activity: Activity): GoogleIdentity {
+ val option =
+ GetSignInWithGoogleOption.Builder(activity.getString(R.string.default_web_client_id))
+ .build()
+ val request = GetCredentialRequest.Builder().addCredentialOption(option).build()
+ val credential =
+ CredentialManager.create(activity).getCredential(activity, request).credential
+ require(
+ credential is CustomCredential &&
+ credential.type == GoogleIdTokenCredential.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL
+ )
+ val googleToken: GoogleIdTokenCredential =
+ GoogleIdTokenCredential.createFrom(credential.data)
+ val firebase = FirebaseAuth.getInstance()
+ val result =
+ firebase
+ .signInWithCredential(GoogleAuthProvider.getCredential(googleToken.idToken, null))
+ .await()
+ val user = requireNotNull(result.user)
+ val email = user.email.orEmpty()
+ if (!email.endsWith("@cornell.edu", ignoreCase = true)) {
+ firebase.signOut()
+ throw CornellAccountRequiredException()
+ }
+ val idToken = requireNotNull(user.getIdToken(false).await().token)
+ return GoogleIdentity(
+ AuthUser(user.uid, user.displayName ?: email.substringBefore('@'), email),
+ idToken,
+ )
+ }
+
+ suspend fun signOut() {
+ FirebaseAuth.getInstance().signOut()
+ try {
+ CredentialManager.create(context).clearCredentialState(ClearCredentialStateRequest())
+ } catch (_: ClearCredentialException) {
+ return
+ }
+ }
+}
+
+class CornellAccountRequiredException : Exception()
diff --git a/app/src/main/java/com/cornellappdev/score/auth/SessionStorage.kt b/app/src/main/java/com/cornellappdev/score/auth/SessionStorage.kt
new file mode 100644
index 00000000..63620403
--- /dev/null
+++ b/app/src/main/java/com/cornellappdev/score/auth/SessionStorage.kt
@@ -0,0 +1,124 @@
+package com.cornellappdev.score.auth
+
+import android.content.Context
+import android.security.keystore.KeyGenParameterSpec
+import android.security.keystore.KeyProperties
+import android.util.AtomicFile
+import dagger.hilt.android.qualifiers.ApplicationContext
+import java.io.File
+import java.io.FileNotFoundException
+import java.security.KeyStore
+import javax.crypto.AEADBadTagException
+import javax.crypto.Cipher
+import javax.crypto.KeyGenerator
+import javax.crypto.SecretKey
+import javax.crypto.spec.GCMParameterSpec
+import javax.inject.Inject
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.SerializationException
+import kotlinx.serialization.encodeToString
+import kotlinx.serialization.json.Json
+
+interface SessionStorage {
+ suspend fun read(): AuthSession?
+
+ suspend fun save(session: AuthSession)
+
+ suspend fun clear()
+}
+
+class EncryptedSessionStorage @Inject constructor(@ApplicationContext context: Context) :
+ SessionStorage {
+ private val file = AtomicFile(File(context.noBackupFilesDir, "auth_session"))
+
+ override suspend fun read(): AuthSession? =
+ withContext(Dispatchers.IO) {
+ val bytes =
+ try {
+ file.readFully()
+ } catch (_: FileNotFoundException) {
+ return@withContext null
+ }
+
+ if (bytes.size < IV_SIZE + GCM_TAG_SIZE) {
+ file.delete()
+ return@withContext null
+ }
+
+ // Reading must not create a replacement key: it could never decrypt this saved session.
+ val key = existingEncryptionKey()
+ if (key == null) {
+ file.delete()
+ return@withContext null
+ }
+
+ val data =
+ try {
+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")
+ cipher.init(
+ Cipher.DECRYPT_MODE,
+ key,
+ GCMParameterSpec(GCM_TAG_SIZE * 8, bytes.copyOfRange(0, IV_SIZE)),
+ )
+ cipher.doFinal(bytes.copyOfRange(IV_SIZE, bytes.size))
+ } catch (_: AEADBadTagException) {
+ // The current key failed AES-GCM authentication for these saved bytes.
+ file.delete()
+ return@withContext null
+ }
+
+ try {
+ Json.decodeFromString(String(data, Charsets.UTF_8))
+ } catch (_: SerializationException) {
+ file.delete()
+ null
+ }
+ }
+
+ override suspend fun save(session: AuthSession) =
+ withContext(Dispatchers.IO) {
+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")
+ cipher.init(Cipher.ENCRYPT_MODE, encryptionKey())
+ val encrypted =
+ cipher.iv + cipher.doFinal(Json.encodeToString(session).toByteArray(Charsets.UTF_8))
+ val output = file.startWrite()
+ try {
+ output.write(encrypted)
+ file.finishWrite(output)
+ } catch (error: Exception) {
+ file.failWrite(output)
+ throw error
+ }
+ }
+
+ override suspend fun clear() = withContext(Dispatchers.IO) { file.delete() }
+
+ private fun existingEncryptionKey(): SecretKey? {
+ val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
+ return keyStore.getKey(KEY_ALIAS, null) as? SecretKey
+ }
+
+ private fun encryptionKey(): SecretKey {
+ existingEncryptionKey()?.let { return it }
+ return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
+ .apply {
+ init(
+ KeyGenParameterSpec.Builder(
+ KEY_ALIAS,
+ KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
+ )
+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
+ .build()
+ )
+ }
+ .generateKey()
+ }
+
+ private companion object {
+ const val IV_SIZE = 12
+ const val GCM_TAG_SIZE = 16
+ const val KEY_ALIAS = "score_auth_session"
+ }
+}
diff --git a/app/src/main/java/com/cornellappdev/score/model/OnboardingPreferencesRepository.kt b/app/src/main/java/com/cornellappdev/score/model/OnboardingPreferencesRepository.kt
index cc3b1b59..48a6ce69 100644
--- a/app/src/main/java/com/cornellappdev/score/model/OnboardingPreferencesRepository.kt
+++ b/app/src/main/java/com/cornellappdev/score/model/OnboardingPreferencesRepository.kt
@@ -25,6 +25,21 @@ class OnboardingPreferencesRepository @Inject constructor(
}
}
+ fun isProfileSetupCompleted(): Boolean =
+ preferences.getBoolean(
+ KEY_PROFILE_SETUP_COMPLETED,
+ isOnboardingCompleted() &&
+ preferences.contains(KEY_ONBOARDING_PROFILE_PICTURE) &&
+ preferences.contains(KEY_ONBOARDING_FAVORITE_SPORTS)
+ )
+
+ fun markProfileSetupCompleted() {
+ preferences.edit {
+ putBoolean(KEY_PROFILE_SETUP_COMPLETED, true)
+ putBoolean(KEY_ONBOARDING_COMPLETED, true)
+ }
+ }
+
fun getFavoriteSports(): Set =
preferences.getStringSet(KEY_ONBOARDING_FAVORITE_SPORTS, emptySet())
.orEmpty()
@@ -49,6 +64,7 @@ class OnboardingPreferencesRepository @Inject constructor(
private companion object {
const val PREFERENCES_NAME = "score_app_preferences"
const val KEY_ONBOARDING_COMPLETED = "onboarding_completed"
+ const val KEY_PROFILE_SETUP_COMPLETED = "profile_setup_completed"
const val KEY_ONBOARDING_PROFILE_PICTURE = "onboarding_profile_picture"
const val KEY_ONBOARDING_FAVORITE_SPORTS = "onboarding_favorite_sports"
}
diff --git a/app/src/main/java/com/cornellappdev/score/screen/OnboardingSequence.kt b/app/src/main/java/com/cornellappdev/score/screen/OnboardingSequence.kt
index 0daf53ec..1114e99c 100644
--- a/app/src/main/java/com/cornellappdev/score/screen/OnboardingSequence.kt
+++ b/app/src/main/java/com/cornellappdev/score/screen/OnboardingSequence.kt
@@ -10,31 +10,39 @@ import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import com.cornellappdev.score.viewmodel.OnboardingSequenceViewModel
private enum class OnboardingStep {
- WELCOME,
PROFILE_SELECT,
SPORT_SELECT
}
@Composable
fun OnboardingSequence(
+ signedIn: Boolean,
+ onSignIn: () -> Unit,
+ onSkipSignIn: () -> Unit,
onOnboardingComplete: () -> Unit,
- viewModel: OnboardingSequenceViewModel = hiltViewModel()
) {
- var onboardingStep by rememberSaveable {
- mutableStateOf(OnboardingStep.WELCOME)
+ if (!signedIn) {
+ OnboardingScreen(
+ onSignUp = onSignIn,
+ onLogIn = onSignIn,
+ onLater = onSkipSignIn,
+ )
+ return
}
- val completeOnboarding = remember {
- onOnboardingComplete
+ ProfileSetupSequence(onOnboardingComplete = onOnboardingComplete)
+}
+
+@Composable
+private fun ProfileSetupSequence(
+ onOnboardingComplete: () -> Unit,
+ viewModel: OnboardingSequenceViewModel = hiltViewModel(),
+) {
+ var onboardingStep by rememberSaveable {
+ mutableStateOf(OnboardingStep.PROFILE_SELECT)
}
when (onboardingStep) {
- OnboardingStep.WELCOME -> OnboardingScreen(
- onSignUp = { onboardingStep = OnboardingStep.PROFILE_SELECT },
- onLogIn = completeOnboarding,
- onLater = completeOnboarding
- )
-
OnboardingStep.PROFILE_SELECT -> OnboardingProfileSelectScreen(
onNext = { selectedPicture ->
viewModel.saveProfilePicture(selectedPicture.name)
@@ -57,7 +65,7 @@ fun OnboardingSequence(
},
onFinish = {
viewModel.saveFavoriteSports(selectedFavorites.toSet())
- completeOnboarding()
+ onOnboardingComplete()
}
)
}
diff --git a/app/src/main/java/com/cornellappdev/score/util/GameDataUtil.kt b/app/src/main/java/com/cornellappdev/score/util/GameDataUtil.kt
index 2da4dbb8..f67f232b 100644
--- a/app/src/main/java/com/cornellappdev/score/util/GameDataUtil.kt
+++ b/app/src/main/java/com/cornellappdev/score/util/GameDataUtil.kt
@@ -102,7 +102,6 @@ fun parseResultScore(result: String?): Pair? {
val homeScore = scorePart[0].toIntOrNull()
val oppScore = secondScorePartEdge[0].toIntOrNull()
- Log.d("HIHI", oppScore.toString())
if (homeScore != null && oppScore != null) {
return Pair(homeScore, oppScore)
} else {
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 0a64d4f6..196950be 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -52,4 +52,10 @@
Finish with %1$d sports
Finish with 1 sport
Remove favorite sport
+ Please use your Cornell Google account (@cornell.edu).
+ Couldn’t sign in. Please try again.
+ Sign-in didn’t finish. Please try again.
+ Connect to the internet and try signing in again.
+ Account
+ No Google account is available for sign-in. Add your Cornell Google account to this device and try again.