Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HeartBeat Baseline for Questionnaire Implementation #181

Merged
merged 8 commits into from
Feb 15, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/google-services.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:123456789012:ios:1234567890123456789012",
"mobilesdk_app_id": "1:123456789012:android:1234567890123456789012",
"android_client_info": {
"package_name": "edu.stanford.bdh.engagehf"
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,3 @@ enum class MeasurementLocations(val value: Int) {
MEASUREMENT_LOCATION_LEFT_UPPER_ARM(BloodPressureRecord.MEASUREMENT_LOCATION_LEFT_UPPER_ARM),
MEASUREMENT_LOCATION_RIGHT_UPPER_ARM(BloodPressureRecord.MEASUREMENT_LOCATION_RIGHT_UPPER_ARM),
}

3 changes: 3 additions & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ lifecycleRuntimeKtx = "2.7.0"
minSdk = "31"
mockKVersion = "1.13.10"
playServicesAuth = "21.2.0"
retrofit = "2.11.0"
rulesVersion = "1.5.0"
runnerVersion = "1.5.2"
securityCryptoKtx = "1.1.0-alpha06"
Expand Down Expand Up @@ -120,6 +121,8 @@ mockk-android = { group = "io.mockk", name = "mockk-android", version.ref = "moc
mockk-core = { group = "io.mockk", name = "mockk", version.ref = "mockKVersion" }
navigation-compose = { module = "androidx.navigation:navigation-compose", version.ref = "composeNavigation" }
play-services-auth = { group = "com.google.android.gms", name = "play-services-auth", version.ref = "playServicesAuth" }
retrofit = { group = "com.squareup.retrofit2", name = "retrofit", version.ref = "retrofit"}
retrofit-converter-kotlinx-serialization = { group = "com.squareup.retrofit2", name = "converter-kotlinx-serialization", version.ref = "retrofit"}
timber = { group = "com.jakewharton.timber", name = "timber", version.ref = "timberVersion" }
vico-compose-m3 = { group = "com.patrykandpatrick.vico", name = "compose-m3", version.ref = "vico" }

Expand Down
14 changes: 13 additions & 1 deletion heartbeat-app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@ plugins {
alias(libs.plugins.spezi.application)
alias(libs.plugins.spezi.compose)
alias(libs.plugins.spezi.hilt)
alias(libs.plugins.spezi.serialization)
alias(libs.plugins.kotlin.parcelize)
alias(libs.plugins.google.gms.google.services)
}

android {
namespace = "edu.stanford.bdh.heartbeat.app"

defaultConfig {
applicationId = "edu.stanford.bdh.heartbeat.app"
applicationId = "edu.stanford.heartbeatstudy"
versionCode = 1
versionName = "1.0.0"
targetSdk = libs.versions.targetSdk.get().toInt()
Expand All @@ -31,3 +34,12 @@ android {
}
}
}

dependencies {
implementation(project(":core:coroutines"))

implementation(libs.firebase.auth.ktx)
implementation(libs.hilt.navigation.compose)
implementation(libs.retrofit)
implementation(libs.retrofit.converter.kotlinx.serialization)
}
29 changes: 29 additions & 0 deletions heartbeat-app/google-services.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"project_info": {
"project_number": "PROJECT_NUMBER",
"project_id": "stanfordbdhgheartbeat",
"storage_bucket": "STORAGE_BUCKET"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:123456789012:android:1234567890123456789012",
"android_client_info": {
"package_name": "edu.stanford.heartbeatstudy"
}
},
"oauth_client": [],
"api_key": [
{
"current_key": "API_KEY"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": []
}
}
}
],
"configuration_version": "1"
}
4 changes: 3 additions & 1 deletion heartbeat-app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

<uses-permission android:name="android.permission.INTERNET" />

<application
android:name=".MainApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:usesCleartextTraffic="true"
android:networkSecurityConfig="@xml/network_security_config"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,12 @@ import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Text
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.fragment.app.FragmentActivity
import dagger.hilt.android.AndroidEntryPoint
import edu.stanford.spezi.core.design.theme.Colors
import edu.stanford.bdh.heartbeat.app.main.MainPage
import edu.stanford.spezi.core.design.theme.SpeziTheme
import edu.stanford.spezi.core.design.theme.TextStyles
import edu.stanford.spezi.core.utils.extensions.testIdentifier

@AndroidEntryPoint
Expand All @@ -27,12 +25,7 @@ class MainActivity : FragmentActivity() {
.testIdentifier(TestIdentifier.ROOT),
contentAlignment = Alignment.Center
) {
Text(
modifier = Modifier.testIdentifier(TestIdentifier.TEXT),
text = "Hello HeartBeat App",
style = TextStyles.headlineLarge,
color = Colors.primary
)
MainPage()
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
package edu.stanford.bdh.heartbeat.app.account

import com.google.firebase.auth.FirebaseAuth
import edu.stanford.spezi.core.coroutines.di.Dispatching
import edu.stanford.spezi.core.logging.speziLogger
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.tasks.await
import javax.inject.Inject

data class AccountInfo(
val email: String,
val name: String?,
val isEmailVerified: Boolean,
)

class AccountManager @Inject internal constructor(
private val firebaseAuth: FirebaseAuth,
@Dispatching.IO private val coroutineScope: CoroutineScope,
) {
private val logger by speziLogger()

fun observeAccountInfo(): Flow<AccountInfo?> = callbackFlow {
val authStateListener = FirebaseAuth.AuthStateListener { _ ->
coroutineScope.launch { send(getAccountInfo()) }
}

firebaseAuth.addAuthStateListener(authStateListener)
awaitClose {
firebaseAuth.removeAuthStateListener(authStateListener)
channel.close()
}
}

fun getAccountInfo(): AccountInfo? {
return firebaseAuth.currentUser?.let { user ->
AccountInfo(
email = user.email ?: "",
name = user.displayName?.takeIf { it.isNotBlank() },
isEmailVerified = user.isEmailVerified
)
}
}

suspend fun getToken(forceRefresh: Boolean = false): Result<String> {
return runCatching {
val user = firebaseAuth.currentUser ?: error("Does not have a current user to get a token for")
val idToken = user.getIdToken(forceRefresh).await()
return@runCatching idToken.token ?: error("Id token refresh didn't include a token")
}.onFailure {
logger.e { "Failed to force refresh token" }
}
}

suspend fun deleteCurrentUser(): Result<Unit> {
return runCatching {
firebaseAuth.currentUser?.delete()?.await()
return@runCatching
}.onFailure {
logger.e { "Failed to delete user." }
}
}

fun signOut() {
runCatching {
firebaseAuth.signOut()
}.onFailure {
logger.e { "Failed to sign out" }
}
}

suspend fun signUpWithEmailAndPassword(
email: String,
password: String,
): Result<Unit> {
return runCatching {
val result = firebaseAuth.createUserWithEmailAndPassword(email, password).await()
if (result?.user == null) error("Failed sign up with email and password")
}.onFailure {
logger.e(it) { "Error signing up with email and password" }
}
}

suspend fun sendForgotPasswordEmail(email: String): Result<Unit> {
return runCatching {
firebaseAuth.sendPasswordResetEmail(email).await().let { }
}.onFailure { e ->
logger.e { "Error sending forgot password email: ${e.message}" }
}
}

suspend fun sendVerificationEmail(): Result<Unit> {
return runCatching {
firebaseAuth.currentUser?.sendEmailVerification()?.await()
return@runCatching
}.onFailure {
logger.e { "Error sending verification email." }
}
}

suspend fun signIn(email: String, password: String): Result<Unit> {
return runCatching {
val result = firebaseAuth.signInWithEmailAndPassword(email, password).await()
if (result.user == null) error("Failed to sign in, returned null user")
}.onFailure { e ->
logger.e { "Error signing in with email and password: ${e.message}" }
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package edu.stanford.bdh.heartbeat.app.account

import androidx.compose.foundation.layout.Column
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.hilt.navigation.compose.hiltViewModel
import edu.stanford.spezi.core.design.theme.Colors

@Composable
fun ForgotPasswordPage(onDismissRequest: () -> Unit) {
val viewModel = hiltViewModel<ForgotPasswordViewModel>()
val uiState by viewModel.uiState.collectAsState()
ForgotPasswordPage(uiState, viewModel::onAction, onDismissRequest)
}

@Composable
private fun ForgotPasswordPage(
uiState: ForgotPasswordUiState,
onAction: (ForgotPasswordAction) -> Unit,
onDismissRequest: () -> Unit,
) {
AlertDialog(
onDismissRequest = onDismissRequest,
title = {
Text("Forgot Password")
},
text = {
if (uiState.isSuccess) {
Text("Sent out a link to reset the password.")
} else {
Column {
Text(
"Please enter your email address of your account. " +
"A password reset email will be sent to the linked email address."
)
OutlinedTextField(
label = {
Text("E-Mail Address")
},
value = uiState.username,
onValueChange = {
onAction(ForgotPasswordAction.UsernameChanged(it))
},
)
uiState.errorMessage?.let {
Text(it, color = Colors.error)
}
}
}
},
confirmButton = {
if (!uiState.isSuccess) {
TextButton(
onClick = {
onAction(ForgotPasswordAction.Submit)
}
) {
Text("Reset Password")
}
}
},
dismissButton = {
TextButton(
onClick = {
onDismissRequest()
}
) {
Text(if (uiState.isSuccess) "Done" else "Close")
}
}
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package edu.stanford.bdh.heartbeat.app.account

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

data class ForgotPasswordUiState(
val username: String = "",
val isLoading: Boolean = false,
val isSuccess: Boolean = false,
val errorMessage: String? = null,
)

sealed interface ForgotPasswordAction {
data class UsernameChanged(val value: String) : ForgotPasswordAction
data object Submit : ForgotPasswordAction
}

@HiltViewModel
class ForgotPasswordViewModel @Inject constructor(
private val accountManager: AccountManager,
) : ViewModel() {

private val _uiState = MutableStateFlow(ForgotPasswordUiState())
val uiState = _uiState.asStateFlow()

fun onAction(action: ForgotPasswordAction) {
when (action) {
is ForgotPasswordAction.UsernameChanged ->
_uiState.update { it.copy(username = action.value) }
is ForgotPasswordAction.Submit -> {
_uiState.update { it.copy(isLoading = true) }
val state = _uiState.value
viewModelScope.launch {
accountManager.sendForgotPasswordEmail(state.username)
.onSuccess {
_uiState.update {
it.copy(
username = "",
isLoading = false,
isSuccess = true,
)
}
}
.onFailure { error ->
_uiState.update {
it.copy(
isLoading = false,
errorMessage = error.message ?: "An unknown error occurred."
)
}
}
}
}
}
}
}
Loading
Loading