accountSwitch.go 15 KB

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