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

feat: Implement JWT refresh token for authorization #2264

Open
wants to merge 1 commit into
base: development
Choose a base branch
from
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
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ import org.fossasia.openevent.general.utils.extensions.withDefaultSchedulers
import retrofit2.HttpException
import timber.log.Timber

const val HEADER_TYPE = "headerType"
const val JWT_ACCESS_TOKEN = "jwtAccessToken"
const val JWT_REFRESH_TOKEN = "jwtRefreshToken"

class StartupViewModel(
private val preference: Preference,
private val resource: Resource,
Expand Down Expand Up @@ -116,4 +120,23 @@ class StartupViewModel(
Timber.e(it, "Error in fetching settings form API")
})
}

fun checkAccessToken() {
if (!authHolder.isLoggedIn() || authHolder.isTokenValid())
return
preference.putString(HEADER_TYPE, JWT_REFRESH_TOKEN)
compositeDisposable += authService.refreshToken()
.withDefaultSchedulers()
.doFinally {
preference.putString(HEADER_TYPE, JWT_ACCESS_TOKEN)
}.subscribe({
authHolder.accessToken = it.accessToken
liveHarshit marked this conversation as resolved.
Show resolved Hide resolved
}, {
if (it is HttpException) {
if (it.code() == HttpErrors.UNAUTHORIZED)
liveHarshit marked this conversation as resolved.
Show resolved Hide resolved
logoutAndRefresh()
}
Timber.e(it, "Error refreshing token, logged out.")
})
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import retrofit2.http.DELETE

interface AuthApi {

@POST("../auth/session")
@POST("auth/login")
fun login(@Body login: Login): Single<LoginResponse>

@GET("users/{id}")
Expand Down Expand Up @@ -51,4 +51,7 @@ interface AuthApi {

@DELETE("users/{id}")
fun deleteAccount(@Path("id") userId: Long): Completable

@POST("/auth/token/refresh")
fun refreshToken(): Single<LoginResponse>
}
42 changes: 32 additions & 10 deletions app/src/main/java/org/fossasia/openevent/general/auth/AuthHolder.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,37 +3,59 @@ package org.fossasia.openevent.general.auth
import org.fossasia.openevent.general.data.Preference
import org.fossasia.openevent.general.utils.JWTUtils

private const val TOKEN_KEY = "TOKEN"
private const val ACCESS_TOKEN = "accessToken"
private const val REFRESH_TOKEN = "refreshToken"

class AuthHolder(private val preference: Preference) {

var token: String? = null
var accessToken: String? = null
get() {
return preference.getString(TOKEN_KEY)
return preference.getString(ACCESS_TOKEN)
}
set(value) {
if (value != null && JWTUtils.isExpired(value))
throw IllegalStateException("Cannot set expired token")
throw IllegalStateException("Cannot set expired accessToken")
field = value
preference.putString(TOKEN_KEY, value)
preference.putString(ACCESS_TOKEN, value)
}

fun getAuthorization(): String? {
var refreshToken: String? = null
get() {
return preference.getString(REFRESH_TOKEN)
}
set(value) {
if (value != null && JWTUtils.isExpired(value))
throw IllegalStateException("Cannot set expired refreshToken")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mean this will crash the app or what? User should be logged out in this case

field = value
preference.putString(REFRESH_TOKEN, value)
}

fun getAccessAuthorization(): String? {
if (!isLoggedIn())
return null
return "JWT $accessToken"
}

fun getRefreshAuthorization(): String? {
if (!isLoggedIn())
return null
return "JWT $token"
return "JWT $refreshToken"
}

fun isTokenValid(): Boolean {
return accessToken != null && !JWTUtils.isExpired(accessToken)
}

fun isLoggedIn(): Boolean {
if (token == null || JWTUtils.isExpired(token)) {
token = null
if (accessToken == null || JWTUtils.isExpired(accessToken)) {
accessToken = null
return false
}

return true
}

fun getId(): Long {
return if (!isLoggedIn()) -1 else JWTUtils.getIdentity(token)
return if (!isLoggedIn()) -1 else JWTUtils.getIdentity(accessToken)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import org.fossasia.openevent.general.auth.change.Password
import org.fossasia.openevent.general.auth.forgot.Email
import org.fossasia.openevent.general.auth.forgot.RequestToken
import org.fossasia.openevent.general.auth.forgot.RequestTokenResponse
import org.fossasia.openevent.general.event.EventApi
import org.fossasia.openevent.general.event.EventDao
import org.fossasia.openevent.general.order.OrderDao
import timber.log.Timber
Expand All @@ -20,16 +19,16 @@ class AuthService(
private val userDao: UserDao,
private val orderDao: OrderDao,
private val attendeeDao: AttendeeDao,
private val eventDao: EventDao,
private val eventApi: EventApi
private val eventDao: EventDao
) {
fun login(username: String, password: String): Single<LoginResponse> {
if (username.isEmpty() || password.isEmpty())
throw IllegalArgumentException("Username or password cannot be empty")

return authApi.login(Login(username, password))
.map {
authHolder.token = it.accessToken
authHolder.accessToken = it.accessToken
authHolder.refreshToken = it.refreshToken
it
}
}
Expand Down Expand Up @@ -66,7 +65,7 @@ class AuthService(

fun logout(): Completable {
return Completable.fromAction {
authHolder.token = null
authHolder.accessToken = null
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove refresh token as well

userDao.deleteUser(authHolder.getId())
orderDao.deleteAllOrders()
attendeeDao.deleteAllAttendees()
Expand Down Expand Up @@ -122,4 +121,8 @@ class AuthService(
fun resetPassword(requestPasswordReset: RequestPasswordReset): Single<ResetPasswordResponse> {
return authApi.resetPassword(requestPasswordReset)
}

fun refreshToken(): Single<LoginResponse> {
return authApi.refreshToken()
}
}
11 changes: 10 additions & 1 deletion app/src/main/java/org/fossasia/openevent/general/auth/Login.kt
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
package org.fossasia.openevent.general.auth

data class Login(val email: String, val password: String)
import com.fasterxml.jackson.databind.PropertyNamingStrategy
import com.fasterxml.jackson.databind.annotation.JsonNaming

@JsonNaming(PropertyNamingStrategy.KebabCaseStrategy::class)
data class Login(
val email: String,
val password: String,
val rememberMe: Boolean = true,
val includeInResponse: Boolean = true
)
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,7 @@ import com.fasterxml.jackson.databind.PropertyNamingStrategy
import com.fasterxml.jackson.databind.annotation.JsonNaming

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy::class)
data class LoginResponse(val accessToken: String)
data class LoginResponse(
val accessToken: String,
val refreshToken: String
)
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,23 @@ package org.fossasia.openevent.general.auth

import okhttp3.Interceptor
import okhttp3.Response
import org.fossasia.openevent.general.HEADER_TYPE
import org.fossasia.openevent.general.JWT_ACCESS_TOKEN
import org.fossasia.openevent.general.JWT_REFRESH_TOKEN
import org.fossasia.openevent.general.data.Preference

class RequestAuthenticator(private val authHolder: AuthHolder) : Interceptor {
class RequestAuthenticator(
private val authHolder: AuthHolder,
private val preference: Preference
) : Interceptor {

override fun intercept(chain: Interceptor.Chain): Response {
val authorization = authHolder.getAuthorization()
val headerType = preference.getString(HEADER_TYPE, JWT_ACCESS_TOKEN)
val authorization =
if (headerType == JWT_REFRESH_TOKEN)
authHolder.getRefreshAuthorization()
else
authHolder.getAccessAuthorization()
Copy link
Member

@iamareebjamal iamareebjamal Aug 19, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, no, no. How does it refresh the token when it is expired?

See the answers here https://stackoverflow.com/questions/22450036/refreshing-oauth-token-using-retrofit-without-modifying-all-calls

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good approach. 👍

val original = chain.request()
return if (authorization != null) {
val request = original.newBuilder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ val apiModule = module {
}

factory { AuthHolder(get()) }
factory { AuthService(get(), get(), get(), get(), get(), get(), get()) }
factory { AuthService(get(), get(), get(), get(), get(), get()) }

factory { EventService(get(), get(), get(), get(), get(), get(), get(), get(), get()) }
factory { SpeakerService(get(), get(), get()) }
Expand Down Expand Up @@ -296,7 +296,7 @@ val networkModule = module {
.connectTimeout(connectTimeout.toLong(), TimeUnit.SECONDS)
.readTimeout(readTimeout.toLong(), TimeUnit.SECONDS)
.addInterceptor(HostSelectionInterceptor(get()))
.addInterceptor(RequestAuthenticator(get()))
.addInterceptor(RequestAuthenticator(get(), get()))
.addNetworkInterceptor(StethoInterceptor())

if (BuildConfig.DEBUG) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ class EventsFragment : Fragment(), BottomIconDoubleClick {
rootView.eventsRecycler.adapter = eventsListAdapter
rootView.eventsRecycler.isNestedScrollingEnabled = false

startupViewModel.checkAccessToken()
startupViewModel.syncNotifications()
startupViewModel.fetchSettings()
handleNotificationDotVisibility(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class OrderDetailsViewModel(
})
}

fun getToken() = authHolder.getAuthorization().nullToEmpty()
fun getToken() = authHolder.getAccessAuthorization().nullToEmpty()

fun loadAttendeeDetails(orderId: Long) {
if (orderId == -1L) return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

public class JWTUtils {

public static SparseArrayCompat<String> decode(String token) {
private static SparseArrayCompat<String> decode(String token) {
SparseArrayCompat<String> decoded = new SparseArrayCompat<>(2);

String[] split = token.split("\\.");
Expand All @@ -17,7 +17,7 @@ public static SparseArrayCompat<String> decode(String token) {
return decoded;
}

public static long getExpiry(String token) throws JSONException {
private static long getExpiry(String token) throws JSONException {
SparseArrayCompat<String> decoded = decode(token);

// We are using JSONObject instead of GSON as it takes about 5 ms instead of 150 ms taken by GSON
Expand Down