accountSwitch.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. package auth
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "time"
  8. uuid "github.com/satori/go.uuid"
  9. "imuslab.com/arozos/mod/database"
  10. "imuslab.com/arozos/mod/utils"
  11. )
  12. /*
  13. Account Switch
  14. This script handle account switching logic
  15. The switchable account pools work like this
  16. Let say user A want to switch to user B account
  17. A will create a pool with user A and B username inside the pool
  18. The pool UUID will be returned to the client, and stored in local storage
  19. The client can always switch between A and B as both are in the pool and the
  20. client is logged in either A or B's account.
  21. */
  22. type SwitchableAccount struct {
  23. Username string //Username of the account
  24. LastSwitch int64 //Last time this account is accessed
  25. }
  26. type SwitchableAccountsPool struct {
  27. UUID string //UUID of this pool, one pool per browser instance
  28. Accounts []*SwitchableAccount //Accounts that is cross switchable in this pool
  29. parent *SwitchableAccountPoolManager
  30. }
  31. type SwitchableAccountPoolManager struct {
  32. Database *database.Database
  33. ExpireTime int64 //Expire time of the switchable account
  34. authAgent *AuthAgent
  35. }
  36. // Create a new switchable account pool manager
  37. func NewSwitchableAccountPoolManager(sysdb *database.Database, parent *AuthAgent) *SwitchableAccountPoolManager {
  38. sysdb.NewTable("auth_acswitch")
  39. thisManager := SwitchableAccountPoolManager{
  40. Database: sysdb,
  41. ExpireTime: 604800,
  42. authAgent: parent,
  43. }
  44. return &thisManager
  45. }
  46. // Handle switchable account listing for this browser
  47. func (m *SwitchableAccountPoolManager) HandleSwitchableAccountListing(w http.ResponseWriter, r *http.Request) {
  48. //Get username and pool id
  49. currentUsername, err := m.authAgent.GetUserName(w, r)
  50. if err != nil {
  51. utils.SendErrorResponse(w, err.Error())
  52. return
  53. }
  54. poolid, err := utils.GetPara(r, "pid")
  55. if err != nil {
  56. utils.SendErrorResponse(w, "invalid pool id given")
  57. return
  58. }
  59. //Check pool exists
  60. targetPool, err := m.GetPoolByID(poolid)
  61. if err != nil {
  62. utils.SendErrorResponse(w, err.Error())
  63. return
  64. }
  65. //Check if the user can access this pool
  66. if !targetPool.IsAccessibleBy(currentUsername) {
  67. utils.SendErrorResponse(w, "permission denied")
  68. return
  69. }
  70. //OK. List all the information about the pool
  71. type AccountInfo struct {
  72. Username string
  73. IsExpired bool
  74. }
  75. results := []*AccountInfo{}
  76. for _, acc := range targetPool.Accounts {
  77. results = append(results, &AccountInfo{
  78. Username: acc.Username,
  79. IsExpired: (time.Now().Unix() > acc.LastSwitch+m.ExpireTime),
  80. })
  81. }
  82. js, _ := json.Marshal(results)
  83. utils.SendJSONResponse(w, string(js))
  84. }
  85. // Logout all the accounts in the pool
  86. func (m *SwitchableAccountPoolManager) HandleLogoutAllAccounts(w http.ResponseWriter, r *http.Request) {
  87. currentUsername, err := m.authAgent.GetUserName(w, r)
  88. if err != nil {
  89. utils.SendErrorResponse(w, err.Error())
  90. return
  91. }
  92. poolid, err := utils.PostPara(r, "pid")
  93. if err != nil {
  94. utils.SendErrorResponse(w, "invalid pool id given")
  95. }
  96. //Get the target pool
  97. targetpool, err := m.GetPoolByID(poolid)
  98. if err != nil {
  99. utils.SendErrorResponse(w, err.Error())
  100. return
  101. }
  102. if !targetpool.IsAccessibleBy(currentUsername) {
  103. utils.SendErrorResponse(w, "permission denied")
  104. return
  105. }
  106. //Remove the pool
  107. targetpool.Delete()
  108. utils.SendOK(w)
  109. }
  110. // Handle account switching
  111. func (m *SwitchableAccountPoolManager) HandleAccountSwitch(w http.ResponseWriter, r *http.Request) {
  112. previousUserName, err := m.authAgent.GetUserName(w, r)
  113. if err != nil {
  114. utils.SendErrorResponse(w, err.Error())
  115. return
  116. }
  117. poolid, err := utils.PostPara(r, "pid")
  118. if err != nil {
  119. //No pool is given. Generate a pool for this request
  120. poolid = uuid.NewV4().String()
  121. newPool := SwitchableAccountsPool{
  122. UUID: poolid,
  123. Accounts: []*SwitchableAccount{
  124. {
  125. Username: previousUserName,
  126. LastSwitch: time.Now().Unix(),
  127. },
  128. },
  129. parent: m,
  130. }
  131. newPool.Save()
  132. }
  133. //Get switchable pool from manager
  134. targetPool, err := m.GetPoolByID(poolid)
  135. if err != nil {
  136. utils.SendErrorResponse(w, err.Error())
  137. return
  138. }
  139. //Check if this user can access this pool
  140. if !targetPool.IsAccessibleByRequest(w, r) {
  141. utils.SendErrorResponse(w, "access request denied: user not belongs to this account pool")
  142. return
  143. }
  144. //OK! Switch the user to alternative account
  145. username, err := utils.PostPara(r, "username")
  146. if err != nil {
  147. utils.SendErrorResponse(w, "invalid or empty username given")
  148. return
  149. }
  150. password, err := utils.PostPara(r, "password")
  151. if err != nil {
  152. //Password not given. Check for direct switch
  153. switchToTargetAlreadySwitchedBefore := targetPool.UserAlreadyInPool(username)
  154. if !switchToTargetAlreadySwitchedBefore {
  155. utils.SendErrorResponse(w, "account must be added before it can switch without password")
  156. return
  157. }
  158. //Check if the switching is expired
  159. lastSwitchTime := targetPool.GetLastSwitchTimeFromUsername(username)
  160. if time.Now().Unix() > lastSwitchTime+m.ExpireTime {
  161. //Already expired
  162. utils.SendErrorResponse(w, "target account session has expired")
  163. return
  164. }
  165. //Not expired. Switch over directly
  166. m.authAgent.LoginUserByRequest(w, r, username, true)
  167. } else {
  168. //Password given. Use Add User Account routine
  169. ok, reason := m.authAgent.ValidateUsernameAndPasswordWithReason(username, password)
  170. if !ok {
  171. utils.SendErrorResponse(w, reason)
  172. return
  173. }
  174. m.authAgent.LoginUserByRequest(w, r, username, true)
  175. }
  176. //Update the pool account info
  177. targetPool.UpdateUserPoolAccountInfo(username)
  178. targetPool.Save()
  179. js, _ := json.Marshal(poolid)
  180. utils.SendJSONResponse(w, string(js))
  181. //Debug print
  182. //js, _ = json.MarshalIndent(targetPool, "", " ")
  183. //fmt.Println("Switching Pool Updated", string(js))
  184. }
  185. func (m *SwitchableAccountPoolManager) GetAllPools() ([]*SwitchableAccountsPool, error) {
  186. results := []*SwitchableAccountsPool{}
  187. entries, err := m.Database.ListTable("auth_acswitch")
  188. if err != nil {
  189. return results, err
  190. }
  191. for _, keypairs := range entries {
  192. //thisPoolID := string(keypairs[0])
  193. thisPool := SwitchableAccountsPool{}
  194. err = json.Unmarshal(keypairs[1], &thisPool)
  195. if err == nil {
  196. thisPool.parent = m
  197. results = append(results, &thisPool)
  198. }
  199. }
  200. return results, nil
  201. }
  202. // Get a switchable account pool by its id
  203. func (m *SwitchableAccountPoolManager) GetPoolByID(uuid string) (*SwitchableAccountsPool, error) {
  204. targetPool := SwitchableAccountsPool{}
  205. err := m.authAgent.Database.Read("auth_acswitch", uuid, &targetPool)
  206. if err != nil {
  207. return nil, errors.New("pool with given uuid not found")
  208. }
  209. targetPool.parent = m
  210. return &targetPool, nil
  211. }
  212. // Remove user from all switch pool, which should be called when a user is logged out or removed
  213. func (p *SwitchableAccountPoolManager) RemoveUserFromAllSwitchableAccountPool(username string) error {
  214. allAccountPool, err := p.GetAllPools()
  215. if err != nil {
  216. return err
  217. }
  218. for _, accountPool := range allAccountPool {
  219. if accountPool.IsAccessibleBy(username) {
  220. //aka this user is in the pool
  221. accountPool.RemoveUser(username)
  222. }
  223. }
  224. return nil
  225. }
  226. func (p *SwitchableAccountPoolManager) ExpireUserFromAllSwitchableAccountPool(username string) error {
  227. allAccountPool, err := p.GetAllPools()
  228. if err != nil {
  229. return err
  230. }
  231. for _, accountPool := range allAccountPool {
  232. fmt.Println(allAccountPool)
  233. if accountPool.IsAccessibleBy(username) {
  234. //aka this user is in the pool
  235. accountPool.ExpireUser(username)
  236. }
  237. }
  238. return nil
  239. }
  240. /*
  241. Switachable Account Pool functions
  242. */
  243. // Check if the requester can switch within target pool
  244. func (p *SwitchableAccountsPool) IsAccessibleByRequest(w http.ResponseWriter, r *http.Request) bool {
  245. username, err := p.parent.authAgent.GetUserName(w, r)
  246. if err != nil {
  247. return false
  248. }
  249. return p.IsAccessibleBy(username)
  250. }
  251. // Check if a given username can switch within this pool
  252. func (p *SwitchableAccountsPool) IsAccessibleBy(username string) bool {
  253. for _, account := range p.Accounts {
  254. if account.Username == username {
  255. return true
  256. }
  257. }
  258. return false
  259. }
  260. func (p *SwitchableAccountsPool) UserAlreadyInPool(username string) bool {
  261. for _, acc := range p.Accounts {
  262. if acc.Username == username {
  263. return true
  264. }
  265. }
  266. return false
  267. }
  268. func (p *SwitchableAccountsPool) UpdateUserLastSwitchTime(username string) bool {
  269. for _, acc := range p.Accounts {
  270. if acc.Username == username {
  271. acc.LastSwitch = time.Now().Unix()
  272. }
  273. }
  274. return false
  275. }
  276. func (p *SwitchableAccountsPool) GetLastSwitchTimeFromUsername(username string) int64 {
  277. for _, acc := range p.Accounts {
  278. if acc.Username == username {
  279. return acc.LastSwitch
  280. }
  281. }
  282. return 0
  283. }
  284. // Everytime switching to a given user in a pool, call this update function to
  285. // update contents inside the pool
  286. func (p *SwitchableAccountsPool) UpdateUserPoolAccountInfo(username string) {
  287. if !p.UserAlreadyInPool(username) {
  288. p.Accounts = append(p.Accounts, &SwitchableAccount{
  289. Username: username,
  290. LastSwitch: time.Now().Unix(),
  291. })
  292. } else {
  293. p.UpdateUserLastSwitchTime(username)
  294. }
  295. }
  296. // Expire the session of a user manually
  297. func (p *SwitchableAccountsPool) ExpireUser(username string) {
  298. for _, acc := range p.Accounts {
  299. if acc.Username == username {
  300. acc.LastSwitch = 0
  301. }
  302. }
  303. p.Save()
  304. }
  305. // Remove a user from the pool
  306. func (p *SwitchableAccountsPool) RemoveUser(username string) {
  307. newAccountList := []*SwitchableAccount{}
  308. for _, acc := range p.Accounts {
  309. if acc.Username != username {
  310. newAccountList = append(newAccountList, acc)
  311. }
  312. }
  313. p.Accounts = newAccountList
  314. p.Save()
  315. }
  316. // Save changes of this pool to database
  317. func (p *SwitchableAccountsPool) Save() {
  318. p.parent.Database.Write("auth_acswitch", p.UUID, p)
  319. }
  320. // Delete this pool from database
  321. func (p *SwitchableAccountsPool) Delete() error {
  322. return p.parent.Database.Delete("auth_acswitch", p.UUID)
  323. }