Created
November 16, 2019 13:43
-
-
Save AndSky90/e284ac43b64ee21943de9330bd8b3c17 to your computer and use it in GitHub Desktop.
AuthProvider
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object AuthProvider { | |
var token: Token? = null | |
var isAuthorized: Boolean = false | |
set(value) { | |
field = value | |
SharedPreferencesProvider.setIsAuthorized(value) | |
} | |
fun getAuthHeaderValue(): String { | |
val header = "Bearer ${token?.token}" | |
log(header) | |
return header | |
} | |
fun logout() = deleteToken() | |
fun logoutAndNavigateToSplash(){ | |
logout() | |
NavigationProvider.navigator.openSplash() | |
} | |
fun storeTokenInfoToCache(tokenInfo: TokenInfo) { | |
if (tokenInfo.accessToken != null && tokenInfo.accessToken!!.token != null) { | |
this.token = Token(tokenInfo.accessToken!!.token!!) | |
tokenInfo.accessToken?.refreshedTimestamp = System.currentTimeMillis() | |
Realm.getDefaultInstance().use { | |
it.executeTransaction { t -> | |
t.delete(TokenInfo::class.java) | |
t.insertOrUpdate(tokenInfo) | |
} | |
} | |
isAuthorized = true | |
} | |
} | |
fun getTokenInfoFromCache(): TokenInfo? { | |
Realm.getDefaultInstance().use { | |
val tokenInfoQuery = it.where(TokenInfo::class.java) | |
return if (tokenInfoQuery.findFirst() != null) | |
it.copyFromRealm(tokenInfoQuery.findFirst()!!) | |
else null | |
} | |
} | |
private fun deleteToken(){ | |
Realm.getDefaultInstance().use { | |
it.executeTransaction { t -> | |
t.delete(TokenInfo::class.java) | |
} | |
} | |
isAuthorized = false | |
token = null | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment