Skip to content

Instantly share code, notes, and snippets.

@albertodebortoli
Created December 3, 2019 11:11
Show Gist options
  • Save albertodebortoli/8767530d6cb97352dfcd9ff3679dfe2c to your computer and use it in GitHub Desktop.
Save albertodebortoli/8767530d6cb97352dfcd9ff3679dfe2c to your computer and use it in GitHub Desktop.
used by 'Lessons learned from handling JWT on mobile' article on Medium
private func getValidUserAuthorizationInMutualExclusion(completion: @escaping (Result<AuthorizationValue, Error>) -> Void) {
semaphore.wait()
guard let authenticationInfo = authenticationInfoStore.userAuthenticationInfo else {
semaphore.signal()
let error = // forge an error for 'missing authorization'
completion(.failure(error))
return
}
if authenticationInfo.isValid {
semaphore.signal()
completion(.success(authenticationInfo.bearerToken))
return
}
tokenRefreshAPI.refreshAccessToken(authenticationInfo.refreshToken) { result in
switch result {
case .success(let authenticationInfo):
self.authenticationInfoStore.persistUserAuthenticationInfo(authenticationInfo)
self.semaphore.signal()
completion(.success(authenticationInfo.bearerToken))
case .failure(let error) where error.isClientError:
self.authenticationInfoStore.wipeUserAuthenticationInfo()
self.semaphore.signal()
completion(.failure(error))
case .failure(let error):
self.semaphore.signal()
completion(.failure(error))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment