accountSwitch.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. package auth
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "log"
  7. "net/http"
  8. "time"
  9. "github.com/gorilla/sessions"
  10. uuid "github.com/satori/go.uuid"
  11. "imuslab.com/arozos/mod/database"
  12. "imuslab.com/arozos/mod/utils"
  13. )
  14. /*
  15. Account Switch
  16. This script handle account switching logic
  17. The switchable account pools work like this
  18. Let say user A want to switch to user B account
  19. A will create a pool with user A and B username inside the pool
  20. The pool UUID will be returned to the client, and stored in local storage
  21. The client can always switch between A and B as both are in the pool and the
  22. client is logged in either A or B's account.
  23. */
  24. type SwitchableAccount struct {
  25. Username string //Username of the account
  26. LastSwitch int64 //Last time this account is accessed
  27. }
  28. type SwitchableAccountsPool struct {
  29. UUID string //UUID of this pool, one pool per browser instance
  30. Creator string //The user who created the pool. When logout, the pool is discarded
  31. Accounts []*SwitchableAccount //Accounts that is cross switchable in this pool
  32. parent *SwitchableAccountPoolManager
  33. }
  34. type SwitchableAccountPoolManager struct {
  35. SessionStore *sessions.CookieStore
  36. SessionName string
  37. Database *database.Database
  38. ExpireTime int64 //Expire time of the switchable account
  39. authAgent *AuthAgent
  40. }
  41. // Create a new switchable account pool manager
  42. func NewSwitchableAccountPoolManager(sysdb *database.Database, parent *AuthAgent, key []byte) *SwitchableAccountPoolManager {
  43. //Create new database table
  44. sysdb.NewTable("auth_acswitch")
  45. //Create new session store
  46. thisManager := SwitchableAccountPoolManager{
  47. SessionStore: sessions.NewCookieStore(key),
  48. SessionName: "ao_acc",
  49. Database: sysdb,
  50. ExpireTime: 604800,
  51. authAgent: parent,
  52. }
  53. //Do an initialization cleanup
  54. go func() {
  55. thisManager.RunNightlyCleanup()
  56. }()
  57. //Return the manager
  58. return &thisManager
  59. }
  60. // When called, this will clear the account switching pool in which all users session has expired
  61. func (m *SwitchableAccountPoolManager) RunNightlyCleanup() {
  62. pools, err := m.GetAllPools()
  63. if err != nil {
  64. log.Println("[auth] Unable to load account switching pools. Cleaning skipped: " + err.Error())
  65. return
  66. }
  67. for _, pool := range pools {
  68. pool.DeletePoolIfAllUserSessionExpired()
  69. }
  70. }
  71. // Handle switchable account listing for this browser
  72. func (m *SwitchableAccountPoolManager) HandleSwitchableAccountListing(w http.ResponseWriter, r *http.Request) {
  73. //Get username and pool id
  74. currentUsername, err := m.authAgent.GetUserName(w, r)
  75. if err != nil {
  76. utils.SendErrorResponse(w, err.Error())
  77. return
  78. }
  79. session, _ := m.SessionStore.Get(r, m.SessionName)
  80. poolid, ok := session.Values["poolid"].(string)
  81. if !ok {
  82. utils.SendErrorResponse(w, "invalid pool id given")
  83. return
  84. }
  85. //Check pool exists
  86. targetPool, err := m.GetPoolByID(poolid)
  87. if err != nil {
  88. //Pool expired. Unset the session
  89. unsetPoolidFromSession(session, w, r)
  90. utils.SendErrorResponse(w, err.Error())
  91. return
  92. }
  93. //Check if the user can access this pool
  94. if !targetPool.IsAccessibleBy(currentUsername) {
  95. //Unset the session
  96. unsetPoolidFromSession(session, w, r)
  97. utils.SendErrorResponse(w, "access denied")
  98. return
  99. }
  100. //Update the user Last Switch Time
  101. targetPool.UpdateUserLastSwitchTime(currentUsername)
  102. //OK. List all the information about the pool
  103. type AccountInfo struct {
  104. Username string
  105. IsExpired bool
  106. }
  107. results := []*AccountInfo{}
  108. for _, acc := range targetPool.Accounts {
  109. results = append(results, &AccountInfo{
  110. Username: acc.Username,
  111. IsExpired: (time.Now().Unix() > acc.LastSwitch+m.ExpireTime),
  112. })
  113. }
  114. js, _ := json.Marshal(results)
  115. utils.SendJSONResponse(w, string(js))
  116. }
  117. // Handle unauth account listing by cookie. You can use this without authRouter.
  118. func (m *SwitchableAccountPoolManager) GetUnauthedSwitchableAccountCreatorList(w http.ResponseWriter, r *http.Request) string {
  119. resumeSessionOwnerName := ""
  120. session, _ := m.SessionStore.Get(r, m.SessionName)
  121. poolid, ok := session.Values["poolid"].(string)
  122. if !ok {
  123. //poolid not found. Return empty string
  124. return ""
  125. }
  126. targetPool, err := m.GetPoolByID(poolid)
  127. if err != nil {
  128. //Target pool not found or all user expired
  129. unsetPoolidFromSession(session, w, r)
  130. return ""
  131. }
  132. //Get the creator name of the pool
  133. resumeSessionOwnerName = targetPool.Creator
  134. return resumeSessionOwnerName
  135. }
  136. // Handle logout of the current user, return the fallback user if any
  137. func (m *SwitchableAccountPoolManager) HandleLogoutforUser(w http.ResponseWriter, r *http.Request) (string, error) {
  138. currentUsername, err := m.authAgent.GetUserName(w, r)
  139. if err != nil {
  140. return "", err
  141. }
  142. session, _ := m.SessionStore.Get(r, m.SessionName)
  143. poolid, ok := session.Values["poolid"].(string)
  144. if !ok {
  145. return "", errors.New("user not in a any switchable account pool")
  146. }
  147. //Get the target pool
  148. targetpool, err := m.GetPoolByID(poolid)
  149. if err != nil {
  150. return "", err
  151. }
  152. //Remove the user from the pool
  153. targetpool.RemoveUser(currentUsername)
  154. //Check if the logout user is the creator. If yes, remove the pool
  155. if targetpool.Creator == currentUsername {
  156. targetpool.Delete()
  157. //Unset the session
  158. unsetPoolidFromSession(session, w, r)
  159. return "", nil
  160. }
  161. //return the creator so after logout, the client is switched back to the master account
  162. return targetpool.Creator, nil
  163. }
  164. // Logout all the accounts in the pool
  165. func (m *SwitchableAccountPoolManager) HandleLogoutAllAccounts(w http.ResponseWriter, r *http.Request) {
  166. currentUsername, err := m.authAgent.GetUserName(w, r)
  167. if err != nil {
  168. utils.SendErrorResponse(w, err.Error())
  169. return
  170. }
  171. session, _ := m.SessionStore.Get(r, m.SessionName)
  172. poolid, ok := session.Values["poolid"].(string)
  173. if !ok {
  174. utils.SendErrorResponse(w, "invalid pool id given")
  175. return
  176. }
  177. //Get the target pool
  178. targetpool, err := m.GetPoolByID(poolid)
  179. if err != nil {
  180. utils.SendErrorResponse(w, err.Error())
  181. return
  182. }
  183. if !targetpool.IsAccessibleBy(currentUsername) {
  184. utils.SendErrorResponse(w, "permission denied")
  185. return
  186. }
  187. //Remove the pool
  188. targetpool.Delete()
  189. //Unset the session
  190. unsetPoolidFromSession(session, w, r)
  191. utils.SendOK(w)
  192. }
  193. // Handle account switching
  194. func (m *SwitchableAccountPoolManager) HandleAccountSwitch(w http.ResponseWriter, r *http.Request) {
  195. previousUserName, err := m.authAgent.GetUserName(w, r)
  196. if err != nil {
  197. utils.SendErrorResponse(w, err.Error())
  198. return
  199. }
  200. session, _ := m.SessionStore.Get(r, m.SessionName)
  201. poolid, ok := session.Values["poolid"].(string)
  202. if !ok {
  203. //No pool is given. Generate a pool for this request
  204. poolid = uuid.NewV4().String()
  205. newPool := SwitchableAccountsPool{
  206. UUID: poolid,
  207. Creator: previousUserName,
  208. Accounts: []*SwitchableAccount{
  209. {
  210. Username: previousUserName,
  211. LastSwitch: time.Now().Unix(),
  212. },
  213. },
  214. parent: m,
  215. }
  216. newPool.Save()
  217. session.Values["poolid"] = poolid
  218. session.Options = &sessions.Options{
  219. MaxAge: 3600 * 24 * 30, //One month
  220. Path: "/",
  221. }
  222. session.Save(r, w)
  223. }
  224. //Get switchable pool from manager
  225. targetPool, err := m.GetPoolByID(poolid)
  226. if err != nil {
  227. utils.SendErrorResponse(w, err.Error())
  228. return
  229. }
  230. //Check if this user can access this pool
  231. if !targetPool.IsAccessibleByRequest(w, r) {
  232. utils.SendErrorResponse(w, "access request denied: user not belongs to this account pool")
  233. return
  234. }
  235. //OK! Switch the user to alternative account
  236. username, err := utils.PostPara(r, "username")
  237. if err != nil {
  238. utils.SendErrorResponse(w, "invalid or empty username given")
  239. return
  240. }
  241. password, err := utils.PostPara(r, "password")
  242. if err != nil {
  243. //Password not given. Check for direct switch
  244. switchToTargetAlreadySwitchedBefore := targetPool.UserAlreadyInPool(username)
  245. if !switchToTargetAlreadySwitchedBefore {
  246. utils.SendErrorResponse(w, "account must be added before it can switch without password")
  247. return
  248. }
  249. //Check if the switching is expired
  250. lastSwitchTime := targetPool.GetLastSwitchTimeFromUsername(username)
  251. if time.Now().Unix() > lastSwitchTime+m.ExpireTime {
  252. //Already expired
  253. utils.SendErrorResponse(w, "target account session has expired")
  254. return
  255. }
  256. //Not expired. Switch over directly
  257. m.authAgent.LoginUserByRequest(w, r, username, true)
  258. } else {
  259. //Password given. Use Add User Account routine
  260. ok, reason := m.authAgent.ValidateUsernameAndPasswordWithReason(username, password)
  261. if !ok {
  262. utils.SendErrorResponse(w, reason)
  263. return
  264. }
  265. m.authAgent.LoginUserByRequest(w, r, username, true)
  266. }
  267. //Update the pool account info
  268. targetPool.UpdateUserPoolAccountInfo(username)
  269. targetPool.Save()
  270. js, _ := json.Marshal(poolid)
  271. utils.SendJSONResponse(w, string(js))
  272. //Debug print
  273. //js, _ = json.MarshalIndent(targetPool, "", " ")
  274. //fmt.Println("Switching Pool Updated", string(js))
  275. }
  276. func (m *SwitchableAccountPoolManager) GetAllPools() ([]*SwitchableAccountsPool, error) {
  277. results := []*SwitchableAccountsPool{}
  278. entries, err := m.Database.ListTable("auth_acswitch")
  279. if err != nil {
  280. return results, err
  281. }
  282. for _, keypairs := range entries {
  283. //thisPoolID := string(keypairs[0])
  284. thisPool := SwitchableAccountsPool{}
  285. err = json.Unmarshal(keypairs[1], &thisPool)
  286. if err == nil {
  287. thisPool.parent = m
  288. results = append(results, &thisPool)
  289. }
  290. }
  291. return results, nil
  292. }
  293. // This function shall be called when user logged in after login session expired.
  294. // This will see if the user is logging in as the pool creator.
  295. // If yes, they can continue to access the switchable account pools.
  296. // if the user is logging in as a sub-account (i.e. not the creator of the switchable account pool),
  297. // the account pool id will be reset to prevent hacking from sub-account to master account
  298. func (m *SwitchableAccountPoolManager) MatchPoolCreatorOrResetPoolID(username string, w http.ResponseWriter, r *http.Request) {
  299. session, _ := m.SessionStore.Get(r, m.SessionName)
  300. poolid, ok := session.Values["poolid"].(string)
  301. if !ok {
  302. //No pool. Continue
  303. return
  304. }
  305. //Get switchable pool from manager
  306. targetPool, err := m.GetPoolByID(poolid)
  307. if err != nil {
  308. utils.SendErrorResponse(w, err.Error())
  309. return
  310. }
  311. if targetPool.Creator != username {
  312. //Reset the pool id for this user
  313. unsetPoolidFromSession(session, w, r)
  314. } else {
  315. //User logging in with master account after login session expired.
  316. //Allow user to continue access sub-accounts in the pool
  317. return
  318. }
  319. }
  320. // Get a switchable account pool by its id
  321. func (m *SwitchableAccountPoolManager) GetPoolByID(uuid string) (*SwitchableAccountsPool, error) {
  322. targetPool := SwitchableAccountsPool{}
  323. err := m.authAgent.Database.Read("auth_acswitch", uuid, &targetPool)
  324. if err != nil {
  325. return nil, errors.New("pool with given uuid not found")
  326. }
  327. targetPool.parent = m
  328. return &targetPool, nil
  329. }
  330. // Remove user from all switch pool, which should be called when a user is logged out or removed
  331. func (p *SwitchableAccountPoolManager) RemoveUserFromAllSwitchableAccountPool(username string) error {
  332. allAccountPool, err := p.GetAllPools()
  333. if err != nil {
  334. return err
  335. }
  336. for _, accountPool := range allAccountPool {
  337. if accountPool.IsAccessibleBy(username) {
  338. //aka this user is in the pool
  339. accountPool.RemoveUser(username)
  340. }
  341. }
  342. return nil
  343. }
  344. func (p *SwitchableAccountPoolManager) ExpireUserFromAllSwitchableAccountPool(username string) error {
  345. allAccountPool, err := p.GetAllPools()
  346. if err != nil {
  347. return err
  348. }
  349. for _, accountPool := range allAccountPool {
  350. fmt.Println(allAccountPool)
  351. if accountPool.IsAccessibleBy(username) {
  352. //aka this user is in the pool
  353. accountPool.ExpireUser(username)
  354. }
  355. }
  356. return nil
  357. }
  358. /*
  359. Switachable Account Pool functions
  360. */
  361. // Check if the requester can switch within target pool
  362. func (p *SwitchableAccountsPool) IsAccessibleByRequest(w http.ResponseWriter, r *http.Request) bool {
  363. username, err := p.parent.authAgent.GetUserName(w, r)
  364. if err != nil {
  365. return false
  366. }
  367. return p.IsAccessibleBy(username)
  368. }
  369. // Check if a given username can switch within this pool
  370. func (p *SwitchableAccountsPool) IsAccessibleBy(username string) bool {
  371. for _, account := range p.Accounts {
  372. if account.Username == username {
  373. return true
  374. }
  375. }
  376. return false
  377. }
  378. func (p *SwitchableAccountsPool) UserAlreadyInPool(username string) bool {
  379. for _, acc := range p.Accounts {
  380. if acc.Username == username {
  381. return true
  382. }
  383. }
  384. return false
  385. }
  386. func (p *SwitchableAccountsPool) UpdateUserLastSwitchTime(username string) bool {
  387. for _, acc := range p.Accounts {
  388. if acc.Username == username {
  389. acc.LastSwitch = time.Now().Unix()
  390. }
  391. }
  392. return false
  393. }
  394. func (p *SwitchableAccountsPool) GetLastSwitchTimeFromUsername(username string) int64 {
  395. for _, acc := range p.Accounts {
  396. if acc.Username == username {
  397. return acc.LastSwitch
  398. }
  399. }
  400. return 0
  401. }
  402. // Everytime switching to a given user in a pool, call this update function to
  403. // update contents inside the pool
  404. func (p *SwitchableAccountsPool) UpdateUserPoolAccountInfo(username string) {
  405. if !p.UserAlreadyInPool(username) {
  406. p.Accounts = append(p.Accounts, &SwitchableAccount{
  407. Username: username,
  408. LastSwitch: time.Now().Unix(),
  409. })
  410. } else {
  411. p.UpdateUserLastSwitchTime(username)
  412. }
  413. }
  414. // Expire the session of a user manually
  415. func (p *SwitchableAccountsPool) ExpireUser(username string) {
  416. for _, acc := range p.Accounts {
  417. if acc.Username == username {
  418. acc.LastSwitch = 0
  419. }
  420. }
  421. p.Save()
  422. }
  423. // Remove a user from the pool
  424. func (p *SwitchableAccountsPool) RemoveUser(username string) {
  425. newAccountList := []*SwitchableAccount{}
  426. for _, acc := range p.Accounts {
  427. if acc.Username != username {
  428. newAccountList = append(newAccountList, acc)
  429. }
  430. }
  431. p.Accounts = newAccountList
  432. p.Save()
  433. }
  434. // Save changes of this pool to database
  435. func (p *SwitchableAccountsPool) DeletePoolIfAllUserSessionExpired() {
  436. allExpred := true
  437. for _, acc := range p.Accounts {
  438. if !p.IsAccountExpired(acc) {
  439. allExpred = false
  440. }
  441. }
  442. if allExpred {
  443. //All account expired. Remove this pool
  444. p.Delete()
  445. }
  446. }
  447. // Save changes of this pool to database
  448. func (p *SwitchableAccountsPool) Save() {
  449. p.parent.Database.Write("auth_acswitch", p.UUID, p)
  450. }
  451. // Delete this pool from database
  452. func (p *SwitchableAccountsPool) Delete() error {
  453. return p.parent.Database.Delete("auth_acswitch", p.UUID)
  454. }
  455. // Check if an account is expired
  456. func (p *SwitchableAccountsPool) IsAccountExpired(acc *SwitchableAccount) bool {
  457. return time.Now().Unix() > acc.LastSwitch+p.parent.ExpireTime
  458. }
  459. func unsetPoolidFromSession(session *sessions.Session, w http.ResponseWriter, r *http.Request) {
  460. //Unset the session
  461. session.Values["poolid"] = nil
  462. session.Save(r, w)
  463. }