Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 6, 2023 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/a15b7c44c5708cc3a5320224d28dec89 to your computer and use it in GitHub Desktop.
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/a4ea37ef6b23729330c878eb806a0a2f00553f1f
// summary : ZIO learning - an authentication service
// keywords : scala, zio, learning, service, authentication, environment, pure-functional, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// 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.2.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