Last active
February 3, 2026 20:27
-
-
Save dacr/a15b7c44c5708cc3a5320224d28dec89 to your computer and use it in GitHub Desktop.
ZIO learning - an authentication service / published by https://github.com/dacr/code-examples-manager #b7a7176e-6d20-4035-8c1d-08c9be42083f/d5049b42fb2560777b0b4b7647bb3c6684a56da3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // summary : ZIO learning - an authentication service | |
| // keywords : scala, zio, learning, service, authentication, environment, pure-functional, @testable | |
| // publish : gist | |
| // authors : David Crosson | |
| // license : Apache License Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) | |
| // id : b7a7176e-6d20-4035-8c1d-08c9be42083f | |
| // created-on : 2021-05-01T21:42:05+02:00 | |
| // managed-by : https://github.com/dacr/code-examples-manager | |
| // run-with : scala-cli $file | |
| // --------------------- | |
| //> using scala "3.4.2" | |
| //> using dep "dev.zio::zio:2.0.13" | |
| //> using dep "fr.janalyse::zio-worksheet:2.0.13.0" | |
| // --------------------- | |
| import zio.*, zio.worksheet.* | |
| case class AuthToken(token: String) | |
| trait Authenticator: | |
| def authenticate: Task[AuthToken] | |
| case class AuthenticatorLive() extends Authenticator: | |
| override def authenticate: Task[AuthToken] = | |
| for | |
| username <- System.env("APP_USERNAME") | |
| password <- System.env("APP_PASSWORD") | |
| token = s"secured-auth-token-for-$username" | |
| yield AuthToken(token) | |
| object Authenticator: | |
| val live = ZLayer.succeed(AuthenticatorLive()) | |
| def authenticate: RIO[Authenticator, AuthToken] = ZIO.serviceWithZIO(_.authenticate) | |
| // ------------------------------------------------------------- | |
| val app: ZIO[Authenticator, Throwable, Unit] = | |
| for | |
| _ <- Console.printLine("started") | |
| token <- Authenticator.authenticate | |
| _ <- Console.printLine(s"got token $token") | |
| yield () | |
| // ------------------------------------------------------------- | |
| app.provideLayer(Authenticator.live).unsafeRun |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment