Configuration and Authentication

Network SDK

  1. Prerequisites
  2. Authentication & Configuration
  3. Plan a Trip
  4. Get Quotes
  5. Book a Trip
  6. Track a Trip
  7. Testing

Network SDK Configuration

In order to initialise the Network SDK on either iOS or Android, a working environment must be provided. The available environments are Sandbox and Production. The Sandbox is used for development and testing purposes. Bookings in the sandbox are not paid for and trip progress is simulated using Karhoo Bot fleets. A custom environment can also be provided.

// set up KarhooSDKConfiguration 
struct KarhooSDKConfig: KarhooSDKConfigurationProvider {
	static var onUpdateAuthentication: (@escaping () -> Void) -> Void = { $0() }
  func environment() -> KarhooSDKConfiguration {
       return .sandbox
   }
 
  func authenticationMethod() -> AuthenticationMethod {
    	return .karhooUser
   }
  
  func requireSDKAuthentication(callback: @escaping () -> Void) {
        KarhooConfig.onUpdateAuthentication {
            callback()
        }
    }
}

//App Delegate
Karhoo.set(configuration: KarhooSDKConfig())

//Where you are setting up the KarhooConfig
KarhooConfig.onUpdateAuthentication = { callback in
//Refresh your own access token in order to ensure a proper validity period for the Karhoo token
//Then use that token to refresh the credentials inside the SDK
	let authService = Karhoo.getAuthService()
   authService.login(token: yourTtoken).execute { result in
		if result.isSuccess() {
			callback()
		} else {
			// Show error
		}
	}
}
// set up KarhooSDKConfiguration
import com.karhoo.sdk.api.KarhooEnvironment
import com.karhoo.sdk.api.KarhooSDKConfiguration

class SDKConfig : KarhooSDKConfiguration {
		var sdkAuthenticationRequired: ((callback: () -> Unit) -> Unit)? = null
      
    override fun environment(): KarhooEnvironment {
        return KarhooEnvironment.Sandbox()
    }

    override fun context(): Context {
        return context
    }
  
    override fun authenticationMethod(): AuthenticationMethod {
    	return AuthenticationMethod.KarhooUser()
    }
  
  	override suspend fun requireSDKAuthentication(callback: () -> Unit) {
        sdkAuthenticationRequired?.invoke(callback)
    }
}

//Application file
val config = SDKConfig(context = this.applicationContext)
config.sdkAuthenticationRequired = {
	loginInBackground(it, yourToken)
}
KarhooApi.setConfiguration(configuration = config)

private var deferredRequests: MutableList<(()-> Unit)> = arrayListOf()
private fun loginInBackground(callback: () -> Unit, token: String) {
	if (!requestedAuthentication) {
		Log.e(TAG, "Need an external authentication")
		requestedAuthentication = true
		deferredRequests.add(callback)

		GlobalScope.launch {
//Refresh your own access token in order to ensure a proper validity period for the Karhoo token
//Then use that token to refresh the credentials inside the SDK 
      KarhooApi.authService.login(token).execute { result ->
        when (result) {
        	is Resource.Success -> {
						Log.e(TAG, "We got a new token from the back-end")
						deferredRequests.map {
							it.invoke()
						}
						deferredRequests.clear()
						requestedAuthentication = false
					}
					is Resource.Failure -> toastErrorMessage(result.error)
 				}
			}
		}
  } else {
    deferredRequests.add(callback)
  }
}

📘

Important changes since SDK Android v1.5.1 / iOS v1.7.0

The KarhooSDKConfiguration provided to the KarhooSDKConfig during the initialization process of the SDK, will also contain a new method called requireSDKAuthentication.
This method is called whenever an external authentication is required. This happens only when all attempts to refresh the access token needed for authenticating requests have failed.
This method receives a callback parameter which should be invoked when the external authentication has finalized.

🚧

iOS

Inside KarhooSDKConfiguration.requireSDKAuthentication closure, you should not log out the user. You need to provide new authentication credentials to Karhoo SDK without deleting the old one.

Authentication

The network SDK currently supports 3 different types of authentication methods, each can be used for different use cases depending on the integration model:

  • Username/password: The users created and managed in the Karhoo platform
  • Token Exchange or Third-party authentication: The users are created and managed in your own identity system
  • Guest authentication: No sign-in required

The AuthenticationMethod is set as part of the SDK configuration, therefore it is important to configure the SDK for the right configuration mechanism first

Username/password

SDK Configuration

struct SDKConfig: KarhooSDKConfigurationProvider {
 
  func authenticationMethod() -> AuthenticationMethod {
    	return .karhooUser
   }
}
class SDKConfig : KarhooSDKConfiguration {

    override fun authenticationMethod(): AuthenticationMethod {
    	return AuthenticationMethod.KarhooUser()
    }
}

User Authentication

The KarhooApi.userService provides all the required functionality for common user management tasks such as registering a new user, logging in an existing user, updating the user details and resetting their password.

Since we have specified AuthenticationMethod.KarhooUser as the authentication method, you need to use the KarhooApi.userService.loginUser API to authenticate the user:

val userService = KarhooApi.userService
val userLogin = UserLogin(email = "[email protected]", password = "password")

userService.loginUser(userLogin: userLogin).execute { result in
     switch result {
        case .success(let user):
            print("User: \(user)")
        case .failure(let error):
            print("error: \(error.code) \(error.message)")
    }
}
val loginRequest = UserLogin(email = "[email protected]", password = "password"
KarhooApi.userService.loginUser(loginRequest).execute { result ->
   when (result) {
      is Resource.Success -> {
         val userInfo: UserInfo = result.data
         Log.d("Welcome ${userInfo?.firstName}")
         // Proceed to next step
      }
      is Resource.Failure -> {
         if (result.error == KarhooError.UserAlreadyLoggedIn) {
            Log.d("Welcome back")
            // Proceed to next step
         } else {
            Log.d((result.error)
         }
      }
   }
}

Token Exchange

You will first need to integrate your external authentication system with the Karhoo platform before initialising the SDK with your client id. When using this authentication method, the authentication service must be used to login and revoke access before interacting with other Karhoo services.

SDK Configuration

struct SDKConfig: KarhooSDKConfigurationProvider {
 
	func authenticationMethod() -> AuthenticationMethod {
  	let settings = TokenExchangeSettings(clientId: "", scope: "")
    	return .tokenExchange(settings: settings)
   }
}
class SDKConfig : KarhooSDKConfiguration {
  
    override fun authenticationMethod(): AuthenticationMethod {
    		return AuthenticationMethod.TokenExhange(clientId = "",
        			                                   scope = "") 
		}
}

User Authentication

The KarhooApi.authService provides all the required functionality for common user management tasks such as registering a new user, logging in an existing user, updating the user details and resetting their password.

Since we have specified AuthenticationMethod.TokenExhange as the authentication method, the KarhooApi.authService.login API needs to be used to authenticate the user:

let authService = Karhoo.getAuthService()

authService.login(token: String).execute(callback: { result in
     switch result {
        case .success(let user):
            print("User: \(user)")
        case .failure(let error):
            print("error: \(error.code) \(error.message)")
    	}
   })
}
val authService = KarhooApi.authService

authService.login(token = "123csXXs").execute { result ->
    when (result) {
        is Resource.Success -> Log.d(result.data) // Handle data
        is Resource.Failure -> Log.d(result.error.internalMessage) //Handle errors
    }
}

Guest authentication

The user does not require any credentials in order to access the Karhoo platform in the guest authentication method. You need to configure the SDK with valid parameters.

struct SDKConfig: KarhooSDKConfigurationProvider {
  func authenticationMethod() -> AuthenticationMethod {
  	let guestSettings = GuestSettings(identifier: "",
                                    referer: "",
                                    organisationId: "")
    	return .guest(settings: guestSettings)
   }
}
class SDKConfig : KarhooSDKConfiguration {

	override fun authenticationMethod(): AuthenticationMethod {
    	return AuthenticationMethod.Guest(identifier = "client_identifier", referer = "referer", organisationId = "organisation_id")
  }
}

What’s Next