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/8ac1b2e664479bde63088731065f661d to your computer and use it in GitHub Desktop.
Save dacr/8ac1b2e664479bde63088731065f661d to your computer and use it in GitHub Desktop.
ZIO learning - an enhanced authentication service using a http service / published by https://github.com/dacr/code-examples-manager #597f2fb2-15e1-4d28-aefd-37dc463ed4f7/da2712a2ed96fb6bb6f7d4c8bd506b5ea21813ae
// summary : ZIO learning - an enhanced authentication service using a http service
// keywords : scala, zio, learning, authentication, 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 : 597f2fb2-15e1-4d28-aefd-37dc463ed4f7
// 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.*
// -------------------------------------------------------------
trait HttpService:
def httpGet(query: String): Task[String]
case class HttpServiceLive() extends HttpService:
override def httpGet(query: String): Task[String] =
for
httpProxy <- System.env("http_proxy")
body <- ZIO.succeed("secured-auth-token")
yield body
object HttpService:
val live = ZLayer.succeed(HttpServiceLive())
def httpGet(query: String): RIO[HttpService, String] = ZIO.serviceWithZIO(_.httpGet(query))
// -------------------------------------------------------------
case class AuthToken(token: String)
trait Authenticator:
def authenticate: Task[AuthToken]
case class AuthenticatorLive(httpService: HttpService) extends Authenticator:
override def authenticate: Task[AuthToken] =
for
username <- System.env("APP_USERNAME")
password <- System.env("APP_PASSWORD")
body <- httpService.httpGet("http://127.0.0.1/auth")
token = "secured-auth-token"
yield AuthToken(token)
object Authenticator:
val live = ZLayer(
for httpService <- ZIO.service[HttpService]
yield AuthenticatorLive(httpService)
)
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(HttpService.live >>> Authenticator.live).unsafeRun
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment