SHARE
TWEET

auth.sml

a guest Nov 26th, 2019 141 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. service auth
  2.  
  3. use {
  4.     "std" 1.0
  5.     "std/time" 1.0
  6. }
  7.  
  8. User = entity {
  9.     name     String
  10.     password String
  11. }
  12.  
  13. Session = entity {
  14.     user     User
  15.     creation Time
  16. }
  17.  
  18. RUser = resolver { u User } {
  19.     name     = String => u.name
  20.     sessions = Set<RSession> => entities<Session>(
  21.         predicate: (s) => s.user == u,
  22.         sortBy:    Session.creation,
  23.     )
  24. }
  25.  
  26. RSession = resolver { s Session } {
  27.     user     = RUser => RUser{u: s.user}
  28.     creation = Time => s.creation
  29. }
  30.  
  31. RRoot = root {
  32.     users Set<RUser> = authUser<Set<RUser>>(() => map(
  33.         entities<User>(sortBy: User.name)),
  34.         (u User) -> RUser => RUser{u: u},
  35.     )
  36. }
  37.  
  38. ErrWrongCredentials = Nil
  39.  
  40. TrnLogin = Transaction<RSession>
  41.  
  42. login = transaction(
  43.     name     String,
  44.     password String,
  45. ) -> (
  46.     ErrWrongCredentials or
  47.     TrnLogin
  48. ) => {
  49.     user = std::entity<User>(
  50.         predicate: (u) => u.name == name && u.password == password,
  51.     )
  52.     newSession = Session{
  53.         user:     user as User,
  54.         creation: time::now(),
  55.     }
  56.     & = user as u {
  57.         User then TrnLogin {
  58.             mutations: std::new(newSession),
  59.             data:      RSession{s: newSession},
  60.         }
  61.         else ErrWrongCredentials
  62.     }
  63. }
  64.  
  65. TrnLogout = std::Transaction<std::Nil>
  66. SessionId = std::ID<Session>
  67.  
  68. logout = transaction(sessionId SessionId) -> TrnLogout => TrnLogout{
  69.     mutations: std::delete(sessionId),
  70. }
  71.  
  72. # Is returned when the client is unauthorized
  73. ErrUnauth = Nil
  74.  
  75. # Equals a t:Session if there is one
  76. auth = () -> ?Session => {
  77.     sid = SessionId(std::header("SID") as String or "")
  78.     s = std::entity<Session>(
  79.         predicate: (s Session) -> Bool => id(s) == sid as SessionId,
  80.     )
  81.     & = match {
  82.         sid == SessionId && s == Session then s as Session
  83.     }
  84. }
  85.  
  86. # Equals t:D returned by p:data if the current client is a logged in user
  87. authUser = <D>(data ()->D) -> (D or ErrUnauth) => {
  88.     & = auth() as {
  89.         Session then data()
  90.         else ErrUnauth
  91.     }
  92. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top