Authentication
Authenticate the patient with the Nabla SDK
Once a Patient is authenticated in your app, you need to authenticate them on Nabla SDK so that they can securely access their conversations.
This is done by calling setCurrentUser(userId:)
on the NablaClient
. This method does not require any credential or secret, but uses the SessionTokenProvider
provided when you initialized the NablaClient
.
You can later use NablaClient.clearCurrentUser()
to remove any data associated to the current user from our SDK. You would usually call this when the user logs out from your app.
This SessionTokenProvider
will be also called every time the Nabla SDK needs to authenticate the user, and you are responsible for providing an accessToken
and a refreshToken
from your backend. See server side documentation for more details.
The userId
is unique String
used to identify the user and will be passed to your SessionTokenProvider
when provideTokens(userId:completion:)
is called. You must call clearCurrentUser()
before setCurrentUser(userId:)
with a different userId
. Otherwise, an error will be thrown.
Note that the
SessionTokenProvider
will be called only when the SDK needs to identify the user, it might not be instantaneously called after callingsetCurrentUSer(userId:)
.
import NablaCore
import NablaMessagingCore
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
NablaClient.initialize(
configuration: .init(
apiKey: "YOUR_API_KEY",
),
modules: [
NablaMessagingModule()
],
sessionTokenProvider: self
)
do {
try NablaClient.shared.setCurrentUser(userId: myUserId)
} catch {
print("Unable to set the current user: \(error)")
}
// ...
return true
}
}
extension AppDelegate: SessionTokenProvider {
func provideTokens(forUserId userId: String, completion: (AuthTokens?) -> Void) {
// Use your own backend to get the tokens for your user
myService.getAuthTokens() { tokens in
completion(tokens)
}
}
}
It is NOT recommended to call clearCurrentUser()
before each call to setCurrentUser(userId:)
, as this would always remove the persisted data and impact the experience of users with bad network conditions. Call clearCurrentUser()
when users log out of your app instead.
Make sure you call
setCurrentUser(userId:)
before calling any other method of the SDK, otherwise aNablaError.authenticationError
will be returned or thrown.
The example above makes AppDelegate
implement SessionTokenProvider
. For production application, we recommend that SessionTokenProvider
is implemented by another class, usually responsible for the authentication in the other parts of your app.
Updated 6 months ago