Skip to content

Instantly share code, notes, and snippets.

@AndSky90
Created November 16, 2019 13:43
Show Gist options
  • Save AndSky90/e284ac43b64ee21943de9330bd8b3c17 to your computer and use it in GitHub Desktop.
Save AndSky90/e284ac43b64ee21943de9330bd8b3c17 to your computer and use it in GitHub Desktop.
AuthProvider
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