Testing from the Client¶
Let’s test it from a client.
Open chatclient/src/main/scala/chatroom/ChannelManager.scala
Implement the Init Auth Service¶
- First, implement ChannelManager apply method in its companion object:
Use a ManagedChannelBuilder to create a new ManagedChannel and assign it to authChannel:
// TODO Build a new ManagedChannel
val authChannel: ManagedChannel = ManagedChannelBuilder.forTarget("localhost:9091").usePlaintext(true).build
- Instantiate a new blocking stub and assign it to authService:
// TODO Get a new Blocking Stub
val authService: AuthenticationServiceBlockingStub = AuthenticationServiceGrpc.blockingStub(authChannel)
Implement authenticate(…)¶
This method will be called when you start the client and initiate the login process:
- Call authService.authenticate(…) to retrieve the token
// TODO Call authService.authenticate(...) and retreive the token
val authenticationReponse = authService.authenticate(new AuthenticationRequest(username, password))
val token = authenticationReponse.token
- Once retrieved the token, call authService.authorization(…) to retrieve all roles, and print them out
// TODO Retrieve all the roles with authService.authorization(...) and print out all the roles
val authorizationResponse = authService.authorization(new AuthorizationRequest(token))
logger.info("user has these roles: " + authorizationResponse.roles)
- Finally, return the token
// TODO Return the token
token
- If any StatusRuntimeException is caught, handle it, print the error, and then return None
try {
...
}
catch {
case e: StatusRuntimeException =>
if (e.getStatus.getCode == Status.Code.UNAUTHENTICATED) {
logger.error("user not authenticated: " + username, e)
} else {
logger.error("caught a gRPC exception", e)
}
// TODO If there are errors, return None
None
}
You can use scala Try monad to compose all operations and handle if any exception occurs
(for {
authenticationResponse <- Try(...)
token = authenticationResponse.token
authorizationResponse <- Try(...)
} yield {
logger.info("user has these roles: " + authorizationResponse.roles)
token
}).fold({
case e: StatusRuntimeException =>
if (e.getStatus.getCode == Status.Code.UNAUTHENTICATED) {
logger.error("user not authenticated: " + username, e)
} else {
logger.error("caught a gRPC exception", e)
}
None
}, Some(_))