5551c44a6b93a415e2ea38f071e0ce35545ddb48
[aquarium] / src / main / scala / gr / grnet / aquarium / logic / events / UserEvent.scala
1 package gr.grnet.aquarium.logic.events
2
3 import gr.grnet.aquarium.util.json.JsonHelpers
4 import net.liftweb.json.{Extraction, parse => parseJson}
5 import gr.grnet.aquarium.MasterConf._
6
7 /**
8  * Represents an incoming user event.
9  *
10  * @author Georgios Gousios <gousiosg@gmail.com>
11  */
12 case class UserEvent(
13   override val id: String,
14   override val timestamp: Long,
15   userId: String,
16   eventVersion: Short,
17   eventType: Short, //1: create, 2: modify
18   state: String,    //ACTIVE, SUSPENDED
19   idp: String,
20   tenant: String,
21   roles: Array[String]
22   ) extends AquariumEvent(id, timestamp) {
23
24   assert(eventType == 1 || eventType == 2)
25   assert(state.equalsIgnoreCase("ACTIVE") ||
26     state.equalsIgnoreCase("SUSPENDED"))
27
28   /**
29    * Validate this event according to the following rules:
30    *
31    * Valid event states: `(eventType, state)`:
32    *  - `a := 1, ACTIVE`
33    *  - `b := 2, ACTIVE`
34    *  - `c := 2, SUSPENDED`
35    *
36    * Valid transitions:
37    *  - `(non-existent) -> a`
38    *  - `a -> c`
39    *  - `c -> b`
40    */
41   def validate: Boolean = {
42
43     if (eventType == 1) {
44       if (MasterConf.IMStore.userExists(userId))
45         return false
46
47       if (!state.equalsIgnoreCase("ACTIVE")) return false
48       return true
49     }
50
51     // All user events are of type 2 (modify) from hereon
52     val oldEvent = MasterConf.IMStore.findLastUserEvent(this.userId)
53
54     oldEvent match {
55       case Some(x) =>
56         x.state match {
57           case y if (y.equalsIgnoreCase("SUSPENDED")) => this.state match {
58             case z if (z.equalsIgnoreCase("ACTIVE")) =>  //OK
59             case _ => return false
60           }
61           case y if (y.equalsIgnoreCase("ACTIVE")) =>  this.state match {
62             case z if (z.equalsIgnoreCase("SUSPENDED")) =>
63               if (x.eventType == 2) return false
64             case _ => return false
65           }
66         }
67       case None => return false
68     }
69
70     true
71   }
72 }
73
74 object UserEvent {
75   def fromJson(json: String): ResourceEvent = {
76     implicit val formats = JsonHelpers.DefaultJsonFormats
77     val jsonAST = parseJson(json)
78     Extraction.extract[ResourceEvent](jsonAST)
79   }
80 }