1 object Dependencies { 2 trait PasswordControl { 3 val mapPasswords: Map[String,String] 4 def matchUserPassword(uid: String, pwd: String): Boolean 5 } 6 }
1 object catsComposeFree extends App { 2 import Dependencies._ 3 import FreeModules._ 4 import DSLs._ 5 import IMPLs._ 6 object UserPasswords extends PasswordControl { 7 override val mapPasswords: Map[String, String] = Map( 8 "Tiger" -> "123", 9 "John" -> "456"
10 ) 11 override def matchUserPassword(uid: String, pwd: String): Boolean =
12 mapPasswords.getOrElse(uid,pwd+"!") == pwd 13 } 14
15 val r = interactLoginDSL.foldMap(userLogin).run(UserPasswords) 16 println(r) 17
18 }
1 Enter your User ID: 2 Tiger 3 Enter your Password: 4 123
5 true
6 ... 7 Enter your User ID: 8 Chan 9 Enter your Password: 10 123
11 false
1 val userLoginDSL: Free[InteractLogin,Unit] = for { 2 uid <- ask[InteractLogin]("Enter your User ID:") 3 pwd <- ask[InteractLogin]("Enter your Password:") 4 aut <- authenticate[InteractLogin](uid,pwd) 5 _ <- if (aut) tell[InteractLogin](s"Hello $uid") 6 else tell[InteractLogin]("Sorry, who are you?") 7 } yield()
1 //val r = interactLoginDSL.foldMap(userLogin).run(UserPasswords) 2 //println(r)
3 userLoginDSL.foldMap(userLogin).run(UserPasswords)
1 Enter your User ID: 2 Tiger 3 Enter your Password: 4 123
5 Hello Tiger 6 ... 7 Enter your User ID: 8 CHAN 9 Enter your Password: 10 123
11 Sorry, who are you?
1 sealed trait Auth[+A] 2 object Auth { 3 case class Authorize(uid: String) extends Auth[Boolean] 4 def authorize[G[_]](uid:String)(implicit I: Inject[Auth,G]): Free[G,Boolean] =
5 Free.liftF(I.inj(Authorize(uid))) 6 }
1 object Dependencies { 2 trait PasswordControl { 3 val mapPasswords: Map[String,String] 4 def matchUserPassword(uid: String, pwd: String): Boolean 5 } 6 trait PermControl { 7 val mapAuthorized: Map[String,Boolean] 8 def authorized(uid: String): Boolean 9 } 10 }
1 import Auth._ 2 type Permit[A] = Coproduct[Auth,InteractLogin,A] 3 val userPermitDSL: Free[Permit,Unit] = for { 4 uid <- ask[Permit]("Enter your User ID:") 5 pwd <- ask[Permit]("Enter your Password:") 6 auth <- authenticate[Permit](uid,pwd) 7 perm <- if(auth) authorize[Permit](uid) 8 else Free.pure[Permit,Boolean](false) 9 _ <- if (perm) tell[Permit](s"Hell