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

[FIX] 로그아웃 오류 해결 #110

Merged
merged 9 commits into from
Feb 10, 2024
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,25 @@ class AuthTokenInterceptor @Inject constructor(
authDataStore.authToken.first()
} ?: ""

val refresh: String? = runBlocking {
authDataStore.refreshToken.first()
}?: ""

// "auth/logout" 엔드포인트 확인
if (originalRequest.url.encodedPath.endsWith("auth/logout")) {
// logout 엔드포인트의 경우 refreshToken 사용
requestBuilder.addHeader("Authorization", "${authDataStore.refreshToken}")
} else if(originalRequest.url.encodedPath.endsWith("auth/logout"))
else {
// 다른 엔드포인트의 경우 authToken 사용
if (!token.isNullOrEmpty()) {
requestBuilder.addHeader("Authorization", "$token")
}

Log.d("Token is","${authDataStore.authToken}")
Log.d("Token is","${authDataStore.refreshToken}")
// 로그아웃 요청에는 리프레시 토큰도 추가
if (originalRequest.url.encodedPath.endsWith("v1/auth/logout")) {
val refreshToken: String? = runBlocking {
authDataStore.refreshToken.first()
}
if (!refreshToken.isNullOrEmpty()) {
requestBuilder.addHeader("RefreshToken", "$refresh")
}
}

var request = requestBuilder.build()
var response = chain.proceed(request)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,13 @@ data class AttendInfoPayload(
val curriculumId: Int,
val curriculumName: String,
val isAttended: Boolean,
val date: String,
val time: String
val date: String
)

fun AttendInfoPayload.toModel() =
AttendInfoModel(
curriculumId = curriculumId ?: 0,
curriculumName = curriculumName ?: "",
isAttended = isAttended ?: false,
date = date ?: "2월 17일",
time = time ?: "오후 02:00"
date = date ?: "2월 17일"
)
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.kusitms.data.repository

import android.content.Context
import android.net.ConnectivityManager
import android.util.Log
import com.kusitms.data.local.AuthDataStore
import com.kusitms.data.local.DataStoreUtils
import com.kusitms.data.remote.api.KusitmsApi
Expand Down Expand Up @@ -43,7 +44,9 @@ class AuthRepositoryImpl @Inject constructor(
override suspend fun logOutMember(): Result<Unit> {
return try {
val response = kusitmsApi.logOutMember()
Log.d("response", response.toString())
if (response.result.code == 200) {
Log.d("로그아웃", "성공")
authDataStore.clearAllData()
Result.success(Unit)
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,4 @@ data class AttendInfoModel(
val curriculumName: String,
val isAttended: Boolean,
val date: String,
val time:String
)
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,10 @@ import javax.inject.Inject
class PostAttendCheckUseCase @Inject constructor(
private val homeRepository: HomeRepository
) {
operator fun invoke(
suspend operator fun invoke(
curriculumId: Int,
qrText: String
): Flow<Unit> = flow {
homeRepository.postAttendCheck(
curriculumId, qrText
).onSuccess {
emit(Unit)
}.onFailure {
throw it
): Result<Unit> {
return homeRepository.postAttendCheck(curriculumId, qrText)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ import com.kusitms.presentation.R
import com.kusitms.presentation.common.ui.theme.KusitmsColorPalette
import com.kusitms.presentation.ui.notice.detail.NoticeDetailViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import timber.log.Timber
import java.text.SimpleDateFormat
Expand All @@ -27,6 +29,7 @@ import java.time.LocalDateTime
import java.time.Year
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeParseException
import java.time.temporal.ChronoUnit
import java.util.*
import javax.inject.Inject

Expand All @@ -37,19 +40,21 @@ class AttendViewModel @Inject constructor(
private val getAttendInfoUseCase: GetAttendInfoUseCase,
private val getAttendScoreUseCase: GetAttendScoreUseCase,
getAttendQrUseCase: GetAttendQrUseCase,
private val getIsLoginUseCase: GetIsLoginUseCase,
private val PostAttendCheckUseCase: PostAttendCheckUseCase
):ViewModel() {

private val _attendListInit = MutableStateFlow<List<AttendCurrentModel>>(emptyList())
val attendListInit : StateFlow<List<AttendCurrentModel>> = _attendListInit.asStateFlow()

private val _upcomingAttend = MutableStateFlow(AttendInfoModel(0, "", false, "", ""))
private val _upcomingAttend = MutableStateFlow(AttendInfoModel(0, "커리큘럼이 없습니다", false, ""))
val upcomingAttend : StateFlow<AttendInfoModel> = _upcomingAttend.asStateFlow()

private val _attendScore = MutableStateFlow(AttendModel(0, 0, 0, 0, "수료 가능한 점수에요"))
val attendScore : StateFlow<AttendModel> = _attendScore.asStateFlow()

private val _qrEnabled = MutableStateFlow(true)
val qrEnabled: StateFlow<Boolean> = _qrEnabled.asStateFlow()

private val _attendCheckModel = MutableStateFlow(
AttendCheckModel(curriculumId = upcomingAttend.value.curriculumId, text = "")
)
Expand All @@ -71,7 +76,7 @@ class AttendViewModel @Inject constructor(
)
}
}.collect {
_attendListInit
_attendListInit.value = it
}
}
}
Expand All @@ -84,7 +89,7 @@ class AttendViewModel @Inject constructor(
}.collect {
_upcomingAttend.emit(it)
_attendCheckModel.emit(
AttendCheckModel(curriculumId = it.curriculumId, text = "")
AttendCheckModel(curriculumId = it.curriculumId, text = it.curriculumName)
)
}
}
Expand Down Expand Up @@ -119,16 +124,21 @@ class AttendViewModel @Inject constructor(

fun postAttendCheck() {
viewModelScope.launch {
val model = attendCheckModel
PostAttendCheckUseCase(curriculumId = model.value.curriculumId, qrText = model.value.text).
catch {
Log.d("출석 확인", "출석 실패")
_snackbarEvent.emit(AttendSnackBarEvent.Attend_fail)
}
.collectLatest {
Log.d("출석 확인", "출석 성공")
_snackbarEvent.emit(AttendSnackBarEvent.Attend_success)
while (isActive) {
val model = attendCheckModel.value
if(model.curriculumId != 0) {
PostAttendCheckUseCase(curriculumId = model.curriculumId, qrText = model.text)
.onFailure{
_snackbarEvent.emit(AttendSnackBarEvent.Attend_fail)
}
.onSuccess {
Log.d("출석 확인", "출석 성공")
_snackbarEvent.emit(AttendSnackBarEvent.Attend_success)
_qrEnabled.value = false
}
}
delay(10000L) // 다음 반복까지 10초 대기
}
}
}

Expand All @@ -145,24 +155,44 @@ class AttendViewModel @Inject constructor(
}
}


@RequiresApi(Build.VERSION_CODES.O)
fun combineDateAndTime(date: String, time: String): LocalDateTime? {
val currentYear = LocalDate.now().year
// 날짜 형식에 연도 추가
val dateFormatter = DateTimeFormatter.ofPattern("MM월 dd일", Locale.KOREAN)
val dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy년 MM월 dd일 a hh:mm", Locale.KOREAN)
val timeUntilEvent = flow {
while (true) {
emit(LocalDateTime.now())
delay(60000)
}
}.flatMapLatest { currentTime ->
upcomingAttend.map { attend ->
calculateTimeTerm(attend.date, currentTime)
}
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000L),
initialValue = ""
)

return try {
// 날짜와 시간 문자열을 현재 연도와 결합
val dateTimeStr = "${currentYear}년 $date $time"
LocalDateTime.parse(dateTimeStr, dateTimeFormatter)
} catch (e: Exception) {
null // 파싱 실패 시 null 반환
@RequiresApi(Build.VERSION_CODES.O)
fun calculateTimeTerm(date: String, currentTime: LocalDateTime): String {
if (date.isEmpty()) return ""

val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss")
val eventDate = LocalDateTime.parse(date, formatter)
val minutesDiff = ChronoUnit.MINUTES.between(currentTime, eventDate)

return when {
minutesDiff > 1440 -> "D-${minutesDiff / 1440}" // 하루 이상
minutesDiff in 1..1439 -> {
val hours = minutesDiff / 60
val minutes = minutesDiff % 60
String.format("%02d:%02d", hours, minutes)
} // 하루 이하
minutesDiff in -30..120 -> "Soon" // 이벤트 시작 2시간 이내
minutesDiff <= -30 -> "Ended" // 이벤트 시작 후 30분 지남
else -> "No Event"
}
}

enum class Status(val displayName: String) {
enum class Status(val displayName: String) {
PRESENT("출석"),
ABSENT("결석"),
LATE("지각");
Expand All @@ -183,6 +213,6 @@ class AttendViewModel @Inject constructor(
}

enum class AttendSnackBarEvent {
Attend_success, Attend_fail
Attend_success, Attend_fail, None
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
package com.kusitms.presentation.model.setting

import android.util.Log
import androidx.annotation.StringRes
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.UriHandler
import androidx.compose.ui.text.font.FontVariation
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.navigation.NavHostController
import com.kusitms.domain.usecase.signin.MemberLogOutUseCase
import com.kusitms.domain.usecase.signin.MemberSignOutUseCase
import com.kusitms.presentation.R
import com.kusitms.presentation.model.login.LoginStatus
import com.kusitms.presentation.model.signIn.SignInViewModel
import com.kusitms.presentation.navigation.NavRoutes
Expand Down Expand Up @@ -38,30 +42,60 @@ class SettingViewModel @Inject constructor(

fun logOut() {
viewModelScope.launch {
memberLogOutUseCase()
.onSuccess {
updateSettingStatus(SettingStatus.LOGOUT)
}
.onFailure {
try {
val result = memberLogOutUseCase()
if (result.isSuccess) {
Log.d("로그아웃", "성공")
updateSettingStatus(SettingStatus.LOGOUT_SUCCESS)
} else {
updateSettingStatus(SettingStatus.ERROR)
}
} catch (e: Exception) {
updateSettingStatus(SettingStatus.ERROR)
}
}
}

fun signOut() {
viewModelScope.launch {
memberSignOutUseCase()
.onSuccess {
updateSettingStatus(SettingStatus.SIGNOUT)
updateSettingStatus(SettingStatus.SIGNOUT_SUCCESS)
}
.onFailure {
updateSettingStatus(SettingStatus.ERROR)
}
}
}

companion object {
enum class SettingStatus { LOGOUT, SIGNOUT, DEFAULT, ERROR}

enum class SettingStatus {
LOGOUT, LOGOUT_SUCCESS, SIGNOUT_INIT,SIGNOUT, SIGNOUT_SUCCESS, DEFAULT, ERROR;

@StringRes
fun getTitleResId(): Int {
return when (this) {
LOGOUT -> R.string.logout_dialog_title
SIGNOUT -> R.string.signout_dialog_title
else -> R.string.signout_blank_title
}
}
@StringRes
fun getContentResId(): Int {
return when (this) {
LOGOUT -> R.string.logout_dialog_content
SIGNOUT -> R.string.signout_dialog_content
else -> R.string.signout_blank_title
}
}
@StringRes
fun getOkTextResId(): Int {
return when (this) {
LOGOUT -> R.string.logout_dialog_ok
SIGNOUT -> R.string.signout_dialog_ok
else -> R.string.signout_blank_title
}
}
}

}
Expand All @@ -84,8 +118,8 @@ fun getMemberSetting(viewModel: SettingViewModel, navController: NavHostControll
SettingUiModel(title = "개인정보 처리 방침", url = "https://sheer-billboard-d63.notion.site/KUSITMS-9e6619383bcd4ce68b6ba4b2b6ef0d40?pvs=4"),
SettingUiModel(title = "서비스 이용약관", url = "https://sheer-billboard-d63.notion.site/24a4639559d4433cb89c8f1abb889726?pvs=4"),
SettingUiModel(title = "비밀번호 변경", onClick = { goToSetPw(navController) }),
SettingUiModel(title = "로그아웃", onClick = { viewModel.logOut() }),
SettingUiModel(title = "회원탈퇴", onClick = { viewModel.signOut() })
SettingUiModel(title = "로그아웃", onClick = { viewModel.updateSettingStatus(SettingViewModel.SettingStatus.LOGOUT) }),
SettingUiModel(title = "회원탈퇴", onClick = { viewModel.updateSettingStatus(SettingViewModel.SettingStatus.SIGNOUT_INIT) })
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -171,8 +171,7 @@ fun MainNavigation() {

kusitmsComposableWithAnimation(NavRoutes.CameraPreview.route) {
CameraScreen(
attendViewModel,
navController
attendViewModel
)
}

Expand Down
Loading