feat: implement user access control system with remote synchronization and database enforcement
This commit is contained in:
@@ -7,10 +7,11 @@ import androidx.room.RoomDatabase
|
||||
import com.example.data.model.MaintenanceActivity
|
||||
import com.example.data.model.OSUpdateHistory
|
||||
import com.example.data.model.SyncConflictLog
|
||||
import com.example.data.model.UserAccess
|
||||
|
||||
@Database(
|
||||
entities = [MaintenanceActivity::class, OSUpdateHistory::class, SyncConflictLog::class],
|
||||
version = 4,
|
||||
entities = [MaintenanceActivity::class, OSUpdateHistory::class, SyncConflictLog::class, UserAccess::class],
|
||||
version = 5,
|
||||
exportSchema = false
|
||||
)
|
||||
abstract class AppDatabase : RoomDatabase() {
|
||||
|
||||
@@ -8,6 +8,7 @@ import androidx.room.Update
|
||||
import com.example.data.model.MaintenanceActivity
|
||||
import com.example.data.model.OSUpdateHistory
|
||||
import com.example.data.model.SyncConflictLog
|
||||
import com.example.data.model.UserAccess
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
@Dao
|
||||
@@ -62,4 +63,13 @@ interface MaintenanceDao {
|
||||
|
||||
@Query("DELETE FROM sync_conflict_logs")
|
||||
suspend fun clearAllConflictLogs()
|
||||
|
||||
@Query("SELECT * FROM user_access WHERE email = :email LIMIT 1")
|
||||
suspend fun getUserAccess(email: String): UserAccess?
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertUserAccessList(accessList: List<UserAccess>)
|
||||
|
||||
@Query("DELETE FROM user_access")
|
||||
suspend fun clearUserAccess()
|
||||
}
|
||||
|
||||
10
app/src/main/java/com/example/data/model/UserAccess.kt
Normal file
10
app/src/main/java/com/example/data/model/UserAccess.kt
Normal file
@@ -0,0 +1,10 @@
|
||||
package com.example.data.model
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.PrimaryKey
|
||||
|
||||
@Entity(tableName = "user_access")
|
||||
data class UserAccess(
|
||||
@PrimaryKey val email: String,
|
||||
val nivelAcesso: String
|
||||
)
|
||||
@@ -4,6 +4,7 @@ import android.content.Context
|
||||
import android.util.Log
|
||||
import com.example.data.model.MaintenanceActivity
|
||||
import com.example.data.model.OSUpdateHistory
|
||||
import com.example.data.model.UserAccess
|
||||
import com.squareup.moshi.JsonClass
|
||||
import com.squareup.moshi.Moshi
|
||||
import com.google.auth.oauth2.GoogleCredentials
|
||||
@@ -807,4 +808,33 @@ class GoogleSheetsSyncService(private val context: Context) {
|
||||
appendValues("history!A:I", appendRows)
|
||||
Log.d(tag, "Successfully appended ${historyToAppend.size} logs to 'history' sheet.")
|
||||
}
|
||||
|
||||
fun fetchUserAccessList(): List<UserAccess> {
|
||||
val rows = fetchValues("acesso!A:Z")
|
||||
val accessList = mutableListOf<UserAccess>()
|
||||
if (rows.size <= 1) return accessList
|
||||
|
||||
val headers = rows[0].map { it.trim().lowercase() }
|
||||
val emailIdx = headers.indexOfFirst { it == "email" || it == "e-mail" || it.contains("email") }
|
||||
val nivelIdx = headers.indexOfFirst { it == "nivel_acesso" || it == "nivel" || it.contains("nivel") || it.contains("nível") }
|
||||
|
||||
if (emailIdx == -1 || nivelIdx == -1) {
|
||||
Log.e(tag, "Colunas de email ou nivel_acesso não encontradas na aba acesso. Headers: $headers")
|
||||
return accessList
|
||||
}
|
||||
|
||||
val getCell = { row: List<String>, idx: Int ->
|
||||
if (idx >= 0 && idx < row.size) row[idx].trim() else ""
|
||||
}
|
||||
|
||||
for (i in 1 until rows.size) {
|
||||
val row = rows[i]
|
||||
val email = getCell(row, emailIdx)
|
||||
val nivel = getCell(row, nivelIdx)
|
||||
if (email.isNotBlank()) {
|
||||
accessList.add(UserAccess(email = email, nivelAcesso = nivel))
|
||||
}
|
||||
}
|
||||
return accessList
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import com.example.data.model.MaintenanceActivity
|
||||
import com.example.data.model.OSUpdateHistory
|
||||
import com.example.data.model.GoogleUser
|
||||
import com.example.data.model.SyncConflictLog
|
||||
import com.example.data.model.UserAccess
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
@@ -29,6 +30,10 @@ class MaintenanceRepository(
|
||||
|
||||
fun getHistoryForOs(numeroOs: String): Flow<List<OSUpdateHistory>> = dao.getHistoryForOs(numeroOs)
|
||||
|
||||
suspend fun getUserAccess(email: String): UserAccess? = withContext(Dispatchers.IO) {
|
||||
dao.getUserAccess(email)
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates progress of an OS, auto-generates a history record, and marks as unsynced (offline-first).
|
||||
*/
|
||||
@@ -191,6 +196,18 @@ class MaintenanceRepository(
|
||||
try {
|
||||
android.util.Log.d("MaintenanceRepository", "Starting Google Sheets synchronization...")
|
||||
|
||||
// 0. Fetch user access list and store locally
|
||||
try {
|
||||
val remoteAccessList = sheetsSyncService.fetchUserAccessList()
|
||||
dao.clearUserAccess()
|
||||
if (remoteAccessList.isNotEmpty()) {
|
||||
dao.insertUserAccessList(remoteAccessList)
|
||||
android.util.Log.d("MaintenanceRepository", "Sincronizadas ${remoteAccessList.size} permissões de acesso.")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.e("MaintenanceRepository", "Falha ao carregar lista de acessos da planilha", e)
|
||||
}
|
||||
|
||||
// 1. Fetch remote OS definitions from the "project" sheet
|
||||
val (remoteActivities, _) = sheetsSyncService.fetchRemoteActivities()
|
||||
|
||||
|
||||
@@ -87,6 +87,7 @@ fun MaintenanceDashboardScreen(
|
||||
val selectedActivity by viewModel.selectedActivity.collectAsStateWithLifecycle()
|
||||
val selectedActivityHistory by viewModel.selectedActivityHistory.collectAsStateWithLifecycle()
|
||||
val currentUser by viewModel.currentUser.collectAsStateWithLifecycle()
|
||||
val userAccessLevel by viewModel.userAccessLevel.collectAsStateWithLifecycle()
|
||||
|
||||
var showEditSheet by remember { mutableStateOf(false) }
|
||||
var showImporterSheet by remember { mutableStateOf(false) }
|
||||
@@ -574,6 +575,7 @@ fun MaintenanceDashboardScreen(
|
||||
activity = selectedActivity!!,
|
||||
history = selectedActivityHistory,
|
||||
currentUser = currentUser,
|
||||
userAccessLevel = userAccessLevel,
|
||||
onDismiss = {
|
||||
showEditSheet = false
|
||||
viewModel.selectActivity(null)
|
||||
@@ -1063,6 +1065,7 @@ fun EditActivityBottomSheet(
|
||||
activity: MaintenanceActivity,
|
||||
history: List<OSUpdateHistory>,
|
||||
currentUser: com.example.data.model.GoogleUser?,
|
||||
userAccessLevel: String?,
|
||||
onDismiss: () -> Unit,
|
||||
onUpdateProgress: (Int, String, String?) -> Unit,
|
||||
onGoogleLoginClick: () -> Unit
|
||||
@@ -1363,22 +1366,76 @@ fun EditActivityBottomSheet(
|
||||
Text("Conectar com o Google", fontWeight = FontWeight.Bold, color = Color.White)
|
||||
}
|
||||
} else {
|
||||
Button(
|
||||
onClick = {
|
||||
isSubmitting = true
|
||||
onUpdateProgress(progressValue.toInt(), observationText, selectedMockPhotoPath)
|
||||
onDismiss()
|
||||
},
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(48.dp)
|
||||
.testTag("save_progress_button"),
|
||||
colors = ButtonDefaults.buttonColors(containerColor = CargillGreen),
|
||||
shape = RoundedCornerShape(10.dp)
|
||||
) {
|
||||
Icon(Icons.Default.Save, contentDescription = "Salvar")
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
Text("Salvar Atualizações (Salva Local Offline)", fontWeight = FontWeight.Black)
|
||||
val hasEditAccess = userAccessLevel?.trim()?.lowercase().let { it == "total" || it == "editor" }
|
||||
if (!hasEditAccess) {
|
||||
Card(
|
||||
colors = CardDefaults.cardColors(containerColor = Color(0xFFFCE8E6)),
|
||||
border = BorderStroke(1.dp, Color(0xFFFAD2CF)),
|
||||
shape = RoundedCornerShape(8.dp),
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Lock,
|
||||
contentDescription = "Acesso Restrito",
|
||||
tint = Color(0xFFC5221F),
|
||||
modifier = Modifier.size(24.dp)
|
||||
)
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = "Acesso Restrito",
|
||||
fontWeight = FontWeight.Bold,
|
||||
fontSize = 13.sp,
|
||||
color = Color(0xFFC5221F)
|
||||
)
|
||||
Text(
|
||||
text = "Seu nível de acesso (${userAccessLevel ?: "nenhum"}) não possui permissão para editar OS.",
|
||||
fontSize = 11.sp,
|
||||
color = Color(0xFFC5221F)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Button(
|
||||
onClick = {},
|
||||
enabled = false,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(48.dp)
|
||||
.testTag("save_progress_button_disabled"),
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = Color.Gray,
|
||||
disabledContainerColor = Color.LightGray
|
||||
),
|
||||
shape = RoundedCornerShape(10.dp)
|
||||
) {
|
||||
Icon(Icons.Default.Save, contentDescription = "Salvar", tint = Color.DarkGray)
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
Text("Salvar Atualizações (Acesso Negado)", fontWeight = FontWeight.Black, color = Color.DarkGray)
|
||||
}
|
||||
} else {
|
||||
Button(
|
||||
onClick = {
|
||||
isSubmitting = true
|
||||
onUpdateProgress(progressValue.toInt(), observationText, selectedMockPhotoPath)
|
||||
onDismiss()
|
||||
},
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(48.dp)
|
||||
.testTag("save_progress_button"),
|
||||
colors = ButtonDefaults.buttonColors(containerColor = CargillGreen),
|
||||
shape = RoundedCornerShape(10.dp)
|
||||
) {
|
||||
Icon(Icons.Default.Save, contentDescription = "Salvar")
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
Text("Salvar Atualizações (Salva Local Offline)", fontWeight = FontWeight.Black)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -59,6 +59,9 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
||||
private val _currentUser = MutableStateFlow<com.example.data.model.GoogleUser?>(null)
|
||||
val currentUser = _currentUser.asStateFlow()
|
||||
|
||||
private val _userAccessLevel = MutableStateFlow<String?>(null)
|
||||
val userAccessLevel = _userAccessLevel.asStateFlow()
|
||||
|
||||
// UI Operation States
|
||||
private val _isSyncing = MutableStateFlow(false)
|
||||
val isSyncing = _isSyncing.asStateFlow()
|
||||
@@ -204,7 +207,11 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
||||
)
|
||||
|
||||
init {
|
||||
_currentUser.value = repository.getSavedUser()
|
||||
val savedUser = repository.getSavedUser()
|
||||
_currentUser.value = savedUser
|
||||
savedUser?.let {
|
||||
checkUserAccessLevel(it.email)
|
||||
}
|
||||
// Automatically check and pull service orders from Sheets on first launch.
|
||||
viewModelScope.launch {
|
||||
val currentList = repository.allActivities.first()
|
||||
@@ -216,6 +223,9 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
||||
when (val result = repository.synchronizeWithBackend()) {
|
||||
is SyncResult.Success -> {
|
||||
_syncStatusMessage.value = "Sincronização inicial concluída! ${result.syncedItems} OSs sincronizadas."
|
||||
_currentUser.value?.let { user ->
|
||||
checkUserAccessLevel(user.email)
|
||||
}
|
||||
}
|
||||
is SyncResult.Error -> {
|
||||
_syncStatusMessage.value = "Falha na sincronização inicial: ${result.message}"
|
||||
@@ -305,6 +315,9 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
||||
_selectedActivity.value?.let { active ->
|
||||
_selectedActivity.value = allActivitiesState.value.find { it.numeroOs == active.numeroOs }
|
||||
}
|
||||
_currentUser.value?.let { user ->
|
||||
checkUserAccessLevel(user.email)
|
||||
}
|
||||
}
|
||||
is SyncResult.Error -> {
|
||||
_syncStatusMessage.value = "Falha na sincronização: ${result.message}"
|
||||
@@ -318,11 +331,20 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
||||
val user = com.example.data.model.GoogleUser(email, displayName)
|
||||
repository.saveUser(user)
|
||||
_currentUser.value = user
|
||||
checkUserAccessLevel(email)
|
||||
}
|
||||
|
||||
fun logoutUser() {
|
||||
repository.clearSavedUser()
|
||||
_currentUser.value = null
|
||||
_userAccessLevel.value = null
|
||||
}
|
||||
|
||||
fun checkUserAccessLevel(email: String) {
|
||||
viewModelScope.launch {
|
||||
val access = repository.getUserAccess(email)
|
||||
_userAccessLevel.value = access?.nivelAcesso
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -337,6 +359,13 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
||||
emailEditor: String?
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
val email = emailEditor ?: ""
|
||||
val access = repository.getUserAccess(email)
|
||||
val level = access?.nivelAcesso?.trim()?.lowercase()
|
||||
if (level != "total" && level != "editor") {
|
||||
_syncStatusMessage.value = "Erro: Nível de acesso '$level' não possui permissão para editar."
|
||||
return@launch
|
||||
}
|
||||
repository.updateProgress(numeroOs, novoPercentual, observacao, fotoPath, recurso, emailEditor)
|
||||
// Update selected activity model in state to refresh UI
|
||||
_selectedActivity.value?.let { active ->
|
||||
|
||||
@@ -259,4 +259,91 @@ class ExampleRobolectricTest {
|
||||
kotlinx.coroutines.Dispatchers.resetMain()
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||
@Test
|
||||
fun `test user access control check in ViewModel`() {
|
||||
val testDispatcher = kotlinx.coroutines.test.UnconfinedTestDispatcher()
|
||||
kotlinx.coroutines.Dispatchers.setMain(testDispatcher)
|
||||
try {
|
||||
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||
val db = androidx.room.Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
|
||||
.allowMainThreadQueries()
|
||||
.setQueryExecutor { it.run() }
|
||||
.setTransactionExecutor { it.run() }
|
||||
.build()
|
||||
val repository = com.example.data.repository.MaintenanceRepository(db.maintenanceDao(), context)
|
||||
|
||||
val userAdmin = com.example.data.model.UserAccess("admin@cargill.com", "total")
|
||||
val userEditor = com.example.data.model.UserAccess("editor@cargill.com", "editor")
|
||||
val userViewer = com.example.data.model.UserAccess("viewer@cargill.com", "leitor")
|
||||
|
||||
kotlinx.coroutines.runBlocking {
|
||||
db.maintenanceDao().insertUserAccessList(listOf(userAdmin, userEditor, userViewer))
|
||||
|
||||
val viewModel = com.example.ui.viewmodel.MaintenanceViewModel(repository)
|
||||
|
||||
// Setup a dummy activity in database
|
||||
val act = com.example.data.model.MaintenanceActivity(
|
||||
numeroOs = "OS-ACCESS",
|
||||
descricao = "Access Test",
|
||||
setor = "Geral",
|
||||
equipe = "Mecânica",
|
||||
recurso = "Sem Recurso",
|
||||
dataInicio = "27/08/2026 10:00",
|
||||
dataFim = "27/08/2026 17:00",
|
||||
percentualExecucao = 0,
|
||||
synced = true
|
||||
)
|
||||
db.maintenanceDao().insertActivity(act)
|
||||
|
||||
// Start collection to activate stateIn subscription
|
||||
val collectionJob = viewModel.viewModelScope.launch {
|
||||
viewModel.filteredActivities.collect {}
|
||||
}
|
||||
val collectionJob2 = viewModel.viewModelScope.launch {
|
||||
viewModel.userAccessLevel.collect {}
|
||||
}
|
||||
|
||||
// Test 1: User not logged in
|
||||
viewModel.selectActivity(act)
|
||||
// Access level should be null
|
||||
assertEquals(null, viewModel.userAccessLevel.value)
|
||||
|
||||
// Test 2: Log in as viewer (viewer@cargill.com)
|
||||
viewModel.loginUser("viewer@cargill.com", "Viewer User")
|
||||
Thread.sleep(100)
|
||||
org.robolectric.shadows.ShadowLooper.idleMainLooper()
|
||||
assertEquals("leitor", viewModel.userAccessLevel.value)
|
||||
|
||||
// Attempt to edit progress (should fail because access level is leitor, which is not total or editor)
|
||||
viewModel.updateProgress("OS-ACCESS", 50, "Tentando editar", null, "Viewer User", "viewer@cargill.com")
|
||||
Thread.sleep(100)
|
||||
org.robolectric.shadows.ShadowLooper.idleMainLooper()
|
||||
// OS percentualExecucao should remain 0
|
||||
val actAfterViewer = db.maintenanceDao().getActivityByOsOneShot("OS-ACCESS")
|
||||
assertEquals(0, actAfterViewer?.percentualExecucao)
|
||||
|
||||
// Test 3: Log in as editor (editor@cargill.com)
|
||||
viewModel.loginUser("editor@cargill.com", "Editor User")
|
||||
Thread.sleep(100)
|
||||
org.robolectric.shadows.ShadowLooper.idleMainLooper()
|
||||
assertEquals("editor", viewModel.userAccessLevel.value)
|
||||
|
||||
// Attempt to edit progress (should succeed because access level is editor)
|
||||
viewModel.updateProgress("OS-ACCESS", 80, "Editando com editor", null, "Editor User", "editor@cargill.com")
|
||||
Thread.sleep(100)
|
||||
org.robolectric.shadows.ShadowLooper.idleMainLooper()
|
||||
// OS percentualExecucao should now be 80
|
||||
val actAfterEditor = db.maintenanceDao().getActivityByOsOneShot("OS-ACCESS")
|
||||
assertEquals(80, actAfterEditor?.percentualExecucao)
|
||||
|
||||
collectionJob.cancel()
|
||||
collectionJob2.cancel()
|
||||
}
|
||||
db.close()
|
||||
} finally {
|
||||
kotlinx.coroutines.Dispatchers.resetMain()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -189,4 +189,47 @@ class ExampleUnitTest {
|
||||
assertEquals("OS2", overdueActivities.first().numeroOs)
|
||||
assertEquals("TAG1", overdueActivities.first().tag)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUserAccessParsingAndValidation() {
|
||||
// Simulate user access lists matching dynamic headers
|
||||
val rows = listOf(
|
||||
listOf("E-mail", "Nível de Acesso"),
|
||||
listOf("admin@cargill.com", "total"),
|
||||
listOf("editor@cargill.com", "editor"),
|
||||
listOf("viewer@cargill.com", "leitor"),
|
||||
listOf("random@cargill.com", "outro")
|
||||
)
|
||||
|
||||
val headers = rows[0].map { it.trim().lowercase() }
|
||||
val emailIdx = headers.indexOfFirst { it == "email" || it == "e-mail" || it.contains("email") }
|
||||
val nivelIdx = headers.indexOfFirst { it == "nivel_acesso" || it == "nivel" || it.contains("nivel") || it.contains("nível") }
|
||||
|
||||
assertEquals(0, emailIdx)
|
||||
assertEquals(1, nivelIdx)
|
||||
|
||||
val accessMap = mutableMapOf<String, String>()
|
||||
for (i in 1 until rows.size) {
|
||||
val row = rows[i]
|
||||
val email = row[emailIdx].trim()
|
||||
val nivel = row[nivelIdx].trim()
|
||||
accessMap[email] = nivel
|
||||
}
|
||||
|
||||
assertEquals("total", accessMap["admin@cargill.com"])
|
||||
assertEquals("editor", accessMap["editor@cargill.com"])
|
||||
assertEquals("leitor", accessMap["viewer@cargill.com"])
|
||||
|
||||
// Function to check write permission
|
||||
val hasWriteAccess = { email: String ->
|
||||
val level = accessMap[email]?.trim()?.lowercase()
|
||||
level == "total" || level == "editor"
|
||||
}
|
||||
|
||||
assertTrue(hasWriteAccess("admin@cargill.com"))
|
||||
assertTrue(hasWriteAccess("editor@cargill.com"))
|
||||
assertFalse(hasWriteAccess("viewer@cargill.com"))
|
||||
assertFalse(hasWriteAccess("random@cargill.com"))
|
||||
assertFalse(hasWriteAccess("nonexistent@cargill.com"))
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user