Skip to content
Open
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
59 changes: 59 additions & 0 deletions app/src/main/java/com/example/roomie/data/AuthRepository.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package com.example.roomie.data

import com.example.roomie.data.api.DevTokenProvider
import com.example.roomie.data.api.LoginResponse
import com.example.roomie.data.api.MeResponse
import com.example.roomie.data.api.Presence
import com.example.roomie.data.api.RetrofitInstance
import com.example.roomie.data.api.RoomieApiResponse
import com.example.roomie.data.api.UpdateMeBody
import com.example.roomie.data.api.apiCall
import com.example.roomie.data.api.ResponseFlow
import com.example.roomie.data.api.repositoryScope
import kotlinx.coroutines.flow.StateFlow
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class AuthRepository @Inject constructor(
private val retrofitInstance: RetrofitInstance,
private val devTokenProvider: DevTokenProvider,
) {
private val scope = repositoryScope()

private val _me = ResponseFlow<MeResponse>(scope)

/** You, your house, and invites you've received. */
val me: StateFlow<RoomieApiResponse<MeResponse>> = _me.state

/** Signs in to the local backend or mock server as [netId], with no Firebase involved. */
suspend fun devLogin(netId: String): RoomieApiResponse<LoginResponse> {
devTokenProvider.netId = netId.trim().lowercase()
return login()
}

/** Call right after sign-in, once the [com.example.roomie.data.api.TokenProvider] has a token. */
suspend fun login(): RoomieApiResponse<LoginResponse> = apiCall { retrofitInstance.userApi.login() }

/** Pipelines the response into [me]. */
fun fetchMe(refresh: Boolean = false) {
_me.fetch(refresh) { retrofitInstance.userApi.getMe() }
}

/** Updates [me] too, unless you signed in as someone else while the request was out. */
suspend fun updateMe(
name: String? = null,
major: String? = null,
presence: Presence? = null,
): RoomieApiResponse<MeResponse> {
val session = devTokenProvider.session
return apiCall { retrofitInstance.userApi.updateMe(UpdateMeBody(name, major, presence)) }.also { result ->
result.ifSuccess { if (devTokenProvider.session == session) _me.set(RoomieApiResponse.Success(it)) }
}
}

fun signOut() {
devTokenProvider.netId = null
_me.set(RoomieApiResponse.Pending)
}
}
66 changes: 66 additions & 0 deletions app/src/main/java/com/example/roomie/data/HouseRepository.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package com.example.roomie.data

import com.example.roomie.data.api.CreateHouseBody
import com.example.roomie.data.api.HouseDto
import com.example.roomie.data.api.InviteBody
import com.example.roomie.data.api.JoinHouseBody
import com.example.roomie.data.api.RetrofitInstance
import com.example.roomie.data.api.RoomieApiResponse
import com.example.roomie.data.api.UpdateHouseBody
import com.example.roomie.data.api.apiCall
import com.example.roomie.data.api.ResponseFlow
import com.example.roomie.data.api.repositoryScope
import kotlinx.coroutines.flow.StateFlow
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class HouseRepository @Inject constructor(private val retrofitInstance: RetrofitInstance) {

private val scope = repositoryScope()
private val api get() = retrofitInstance.houseApi

private val _house = ResponseFlow<HouseDto>(scope)

/** Your house. Every call below that returns the house updates this too. */
val house: StateFlow<RoomieApiResponse<HouseDto>> = _house.state

/** Pipelines the response into [house]. */
fun fetchHouse(houseId: Int, refresh: Boolean = false) {
_house.fetch(refresh) { api.getHouse(houseId).house }
}

suspend fun createHouse(body: CreateHouseBody): RoomieApiResponse<HouseDto> =
updatingHouse { api.createHouse(body).house }

suspend fun updateHouse(houseId: Int, body: UpdateHouseBody): RoomieApiResponse<HouseDto> =
updatingHouse { api.updateHouse(houseId, body).house }

suspend fun invite(houseId: Int, netIds: List<String>): RoomieApiResponse<HouseDto> =
updatingHouse { api.invite(houseId, InviteBody(netIds)).house }

suspend fun cancelInvite(houseId: Int, inviteId: Int): RoomieApiResponse<Unit> =
apiCall { api.cancelInvite(houseId, inviteId) }.also { it.ifSuccess { fetchHouse(houseId, refresh = true) } }

suspend fun regenerateInviteCode(houseId: Int): RoomieApiResponse<HouseDto> =
updatingHouse { api.regenerateInviteCode(houseId).house }

suspend fun joinHouse(inviteCode: String): RoomieApiResponse<HouseDto> =
updatingHouse { api.joinHouse(JoinHouseBody(inviteCode.trim())).house }

suspend fun acceptInvite(inviteId: Int): RoomieApiResponse<HouseDto> =
updatingHouse { api.acceptInvite(inviteId).house }

suspend fun declineInvite(inviteId: Int): RoomieApiResponse<Unit> =
apiCall { api.declineInvite(inviteId) }

/** Clears [house]. Any [fetchHouse] still in flight is cancelled so it can't bring the house back. */
suspend fun leaveHouse(houseId: Int): RoomieApiResponse<Unit> =
apiCall { api.leaveHouse(houseId) }.also { it.ifSuccess { _house.set(RoomieApiResponse.Pending) } }

suspend fun removeMember(houseId: Int, userId: Int): RoomieApiResponse<Unit> =
apiCall { api.removeMember(houseId, userId) }.also { it.ifSuccess { fetchHouse(houseId, refresh = true) } }

private suspend fun updatingHouse(call: suspend () -> HouseDto): RoomieApiResponse<HouseDto> =
apiCall(call).also { result -> result.ifSuccess { _house.set(RoomieApiResponse.Success(it)) } }
}
76 changes: 76 additions & 0 deletions app/src/main/java/com/example/roomie/data/api/ApiModels.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package com.example.roomie.data.api

import java.time.Instant
import java.time.LocalDate

// Objects the backend returns, shared across services. Money is whole cents and IDs are ints.
// These mirror the API exactly; map them to the app's models in data/Models.kt at the repository
// or ViewModel layer.

enum class MemberRole { OWNER, MEMBER }

/** The "I'm home / away" toggle. */
enum class Presence { HOME, AWAY }

/** The public view of a person: members, rotation, assignee, claimedBy, … */
data class UserDto(
val id: Int,
/** Lowercase, e.g. `mnh49`. */
val netid: String,
val name: String,
val avatarUrl: String?,
val presence: Presence,
)

/** Your own user, from `/auth/login` and `/users/me`. */
data class SelfDto(
val id: Int,
val netid: String,
val name: String,
val avatarUrl: String?,
val presence: Presence,
val email: String,
val major: String?,
val createdAt: Instant,
)

/** A [UserDto] plus what only makes sense inside a house. */
data class MemberDto(
val id: Int,
val netid: String,
val name: String,
val avatarUrl: String?,
val presence: Presence,
val role: MemberRole,
/** If the owner leaves, the member who joined earliest becomes owner. */
val joinedAt: Instant,
)

data class HouseDto(
val id: Int,
val name: String,
/** e.g. `LOFT-4827`. Not case-sensitive. */
val inviteCode: String,
val unit: String?,
val leaseEndsOn: LocalDate?,
/** IANA name. Decides what "today" means for chores. */
val timezone: String,
val members: List<MemberDto>,
val pendingInvites: List<PendingInviteDto>,
)

/** An invite the house sent that hasn't been answered. */
data class PendingInviteDto(val id: Int, val netid: String, val createdAt: Instant)

/** The short house in `GET /users/me`. [role] is yours. */
data class HouseSummaryDto(val id: Int, val name: String, val role: MemberRole)

/** An invite you received. Has enough for the "Join this house?" prompt. */
data class InviteDto(
val id: Int,
val createdAt: Instant,
val house: InviteHouseDto,
val invitedBy: UserDto,
)

data class InviteHouseDto(val id: Int, val name: String, val members: List<UserDto>)
74 changes: 74 additions & 0 deletions app/src/main/java/com/example/roomie/data/api/HouseApiService.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package com.example.roomie.data.api

import retrofit2.http.Body
import retrofit2.http.DELETE
import retrofit2.http.GET
import retrofit2.http.PATCH
import retrofit2.http.POST
import retrofit2.http.Path
import java.time.LocalDate

interface HouseApiService {

/** Creates a house with you as owner and invites [CreateHouseBody.inviteNetids]. */
@POST("houses")
suspend fun createHouse(@Body body: CreateHouseBody): HouseResponse

@GET("houses/{houseId}")
suspend fun getHouse(@Path("houseId") houseId: Int): HouseResponse

/** Any member can edit house settings. */
@PATCH("houses/{houseId}")
suspend fun updateHouse(@Path("houseId") houseId: Int, @Body body: UpdateHouseBody): HouseResponse

/** Skips people already in the house. */
@POST("houses/{houseId}/invites")
suspend fun invite(@Path("houseId") houseId: Int, @Body body: InviteBody): HouseResponse

@DELETE("houses/{houseId}/invites/{inviteId}")
suspend fun cancelInvite(@Path("houseId") houseId: Int, @Path("inviteId") inviteId: Int)

/** Owner only. The old code stops working. */
@POST("houses/{houseId}/invite-code")
suspend fun regenerateInviteCode(@Path("houseId") houseId: Int): HouseResponse

@POST("houses/join")
suspend fun joinHouse(@Body body: JoinHouseBody): HouseResponse

@POST("invites/{inviteId}/accept")
suspend fun acceptInvite(@Path("inviteId") inviteId: Int): HouseResponse

@POST("invites/{inviteId}/decline")
suspend fun declineInvite(@Path("inviteId") inviteId: Int)

/** Also removes you from rotations, releases your shopping claims and passes on ownership. */
@DELETE("houses/{houseId}/members/me")
suspend fun leaveHouse(@Path("houseId") houseId: Int)

/** Owner only, with the same cleanup as leaving. */
@DELETE("houses/{houseId}/members/{userId}")
suspend fun removeMember(@Path("houseId") houseId: Int, @Path("userId") userId: Int)
}

data class HouseResponse(val house: HouseDto)

data class CreateHouseBody(
val name: String,
val unit: String? = null,
val leaseEndsOn: LocalDate? = null,
/** IANA name. The server defaults to America/New_York. */
val timezone: String? = null,
val inviteNetids: List<String>? = null,
)

data class UpdateHouseBody(
val name: String? = null,
val unit: String? = null,
val leaseEndsOn: LocalDate? = null,
val timezone: String? = null,
)

data class InviteBody(val netids: List<String>)

/** Not case-sensitive. */
data class JoinHouseBody(val inviteCode: String)
14 changes: 14 additions & 0 deletions app/src/main/java/com/example/roomie/data/api/NetworkModule.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.example.roomie.data.api

import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent

@Module
@InstallIn(SingletonComponent::class)
abstract class NetworkModule {

@Binds
abstract fun bindTokenProvider(provider: DevTokenProvider): TokenProvider
}
97 changes: 97 additions & 0 deletions app/src/main/java/com/example/roomie/data/api/RetrofitInstance.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
package com.example.roomie.data.api

import com.example.roomie.BuildConfig
import kotlinx.coroutines.runBlocking
import okhttp3.Authenticator
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Inject
import javax.inject.Singleton

/**
* The Retrofit client every Roomie API service shares. It adds `Authorization: Bearer <token>`
* to each request and, on a 401, asks [TokenProvider] for a fresh token and retries once, as long as
* the request went to the API's own origin and the user hasn't switched accounts in the meantime.
*/
@Singleton
class RetrofitInstance internal constructor(retrofit: Retrofit) {

@Inject
constructor(tokenProvider: TokenProvider) :
this(roomieRetrofit(BuildConfig.API_URL, tokenProvider, logBodies = BuildConfig.DEBUG))

val userApi: UserApiService by lazy { retrofit.create(UserApiService::class.java) }
val houseApi: HouseApiService by lazy { retrofit.create(HouseApiService::class.java) }
}

/** Builds the client. Separate from [RetrofitInstance] so tests can point it at a fake server. */
internal fun roomieRetrofit(
baseUrl: String,
tokenProvider: TokenProvider,
logBodies: Boolean,
): Retrofit {
val apiOrigin = baseUrl.toHttpUrl()

val authInterceptor = Interceptor { chain ->
val request = chain.request()
// Read the session before the token: if they disagree, the retry is refused (the safe side).
val session = AuthSession(tokenProvider.session)
val token = runBlocking { tokenProvider.token(forceRefresh = false) }
val tagged = request.newBuilder().tag(AuthSession::class.java, session)
if (token != null && request.header("Authorization") == null) {
tagged.header("Authorization", "Bearer $token")
}
chain.proceed(tagged.build())
}

val authenticator = Authenticator { _, response ->
val request = response.request
// Never send the token anywhere but the API itself, e.g. after a cross-origin redirect.
if (!request.url.hasSameOrigin(apiOrigin)) return@Authenticator null
// Retry once. Count only earlier 401s: redirects and retries also show up in priorResponse.
if (response.prior401Count() > 0) return@Authenticator null
// The request belongs to the session it started in. If the user switched accounts since,
// replaying it with the new account's token would act as the wrong user.
val startedIn = request.tag(AuthSession::class.java) ?: return@Authenticator null
if (startedIn.id != tokenProvider.session) return@Authenticator null
val token = runBlocking { tokenProvider.token(forceRefresh = true) }
?: return@Authenticator null
if (startedIn.id != tokenProvider.session) return@Authenticator null
request.newBuilder().header("Authorization", "Bearer $token").build()
}

val client = OkHttpClient.Builder()
.addInterceptor(authInterceptor)
.apply {
if (logBodies) {
addInterceptor(HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
redactHeader("Authorization")
})
}
}
.authenticator(authenticator)
.build()

return Retrofit.Builder()
.baseUrl(baseUrl)
.client(client)
.addConverterFactory(GsonConverterFactory.create(RoomieGson.gson))
.build()
}

/** Which [TokenProvider.session] a request was started in. Attached as an OkHttp request tag. */
private class AuthSession(val id: Long)

private fun HttpUrl.hasSameOrigin(other: HttpUrl) =
scheme == other.scheme && host == other.host && port == other.port

/** How many 401s came before this response in the same call (not counting this one). */
private fun Response.prior401Count(): Int =
generateSequence(priorResponse) { it.priorResponse }.count { it.code == 401 }
Loading