session.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. package back
  2. import (
  3. "errors"
  4. "sync"
  5. "github.com/gin-gonic/contrib/sessions"
  6. "github.com/gin-gonic/gin"
  7. )
  8. var sessionKey = string("MySecretKey")
  9. type session struct {
  10. Hash string
  11. Manager int32
  12. Rows []session
  13. }
  14. var managerSession map[string]manager
  15. var managerSessionMutex = sync.RWMutex{}
  16. func prepareQueriesSession() []string {
  17. var e error
  18. ebox := make([]string, 0)
  19. queries["Select#Session#All"], e = db.Prepare(`SELECT "Hash", "Manager" FROM "Session"`)
  20. if e != nil {
  21. ebox = append(ebox, "Select#Session#All - "+e.Error())
  22. }
  23. queries["Insert#Session#"], e = db.Prepare(`INSERT INTO "Session"("Hash", "Manager") VALUES($1, $2)`)
  24. if e != nil {
  25. ebox = append(ebox, "Insert#Session# - "+e.Error())
  26. }
  27. queries["Delete#Session#"], e = db.Prepare(`DELETE FROM "Session" WHERE "Hash"=$1`)
  28. if e != nil {
  29. ebox = append(ebox, "Delete#Session# - "+e.Error())
  30. }
  31. return ebox
  32. }
  33. func (s *session) Insert() error {
  34. stmt, ok := queries["Insert#Session#"]
  35. if !ok {
  36. return errors.New("Запрос Insert#Session# не найден")
  37. }
  38. _, e := stmt.Exec(s.Hash, s.Manager)
  39. if e != nil {
  40. return errors.New("Не удалось создать сессию")
  41. }
  42. m := manager{}
  43. m.ID = s.Manager
  44. e = m.SelectByID()
  45. if e != nil {
  46. return loadSession()
  47. }
  48. managerSessionMutex.Lock()
  49. managerSession[s.Hash] = manager{
  50. ID: m.ID,
  51. Login: m.Login,
  52. Password: m.Password,
  53. FirstName: m.FirstName,
  54. LastName: m.LastName,
  55. Patronymic: m.Patronymic,
  56. Role: m.Role,
  57. }
  58. managerSessionMutex.Unlock()
  59. return nil
  60. }
  61. func (s *session) Delete() error {
  62. stmt, ok := queries["Delete#Session#"]
  63. if !ok {
  64. logger.Println("Запрос Delete#Session# не найден")
  65. return errors.New("Запрос Delete#Session# не найден")
  66. }
  67. _, e := stmt.Exec(s.Hash)
  68. if e != nil {
  69. logger.Println("Не удалось удалить сессию из базы данных")
  70. return errors.New("Не удалось удалить сессию из базы данных")
  71. }
  72. managerSessionMutex.Lock()
  73. delete(managerSession, s.Hash)
  74. managerSessionMutex.Unlock()
  75. return nil
  76. }
  77. func loadSession() error {
  78. stmt, ok := queries["Select#Session#All"]
  79. if !ok {
  80. return errors.New("Запрос Select#Session#All не найден")
  81. }
  82. rows, e := stmt.Query()
  83. if e != nil {
  84. return e
  85. }
  86. defer rows.Close()
  87. s := session{}
  88. m := manager{}
  89. managerSessionMutex.Lock()
  90. managerSession = make(map[string]manager)
  91. defer managerSessionMutex.Unlock()
  92. for rows.Next() {
  93. e = rows.Scan(&s.Hash, &m.ID)
  94. if e != nil {
  95. return e
  96. }
  97. e = m.SelectByID()
  98. if e != nil {
  99. logger.Println("Ошибка получения данных о менеджере с ID", m.ID, e)
  100. continue
  101. }
  102. managerSession[s.Hash] = manager{
  103. ID: m.ID,
  104. Login: m.Login,
  105. Password: m.Password,
  106. FirstName: m.FirstName,
  107. LastName: m.LastName,
  108. Patronymic: m.Patronymic,
  109. Role: m.Role,
  110. }
  111. }
  112. return nil
  113. }
  114. func getRoleFromContext(c *gin.Context) string {
  115. defer catch()
  116. cookieSession := sessions.Default(c)
  117. sessionHash, ok := cookieSession.Get(sessionKey).(string)
  118. if ok {
  119. managerSessionMutex.Lock()
  120. sessionManager, ok := managerSession[sessionHash]
  121. managerSessionMutex.Unlock()
  122. if ok {
  123. return sessionManager.Role
  124. }
  125. }
  126. return ""
  127. }
  128. func getManagerFromContext(c *gin.Context) *manager {
  129. defer catch()
  130. cookieSession := sessions.Default(c)
  131. sessionHash, ok := cookieSession.Get(sessionKey).(string)
  132. if ok {
  133. managerSessionMutex.Lock()
  134. sessionManager, ok := managerSession[sessionHash]
  135. managerSessionMutex.Unlock()
  136. if ok {
  137. return &sessionManager
  138. }
  139. }
  140. return nil
  141. }
  142. func clearSessionFromContext(c *gin.Context) {
  143. defer catch()
  144. cookieSession := sessions.Default(c)
  145. sessionHash, ok := cookieSession.Get(sessionKey).(string)
  146. if ok {
  147. s := session{}
  148. s.Hash = sessionHash
  149. s.Delete()
  150. cookieSession.Clear()
  151. cookieSession.Save()
  152. c.SetCookie("session", "", -1, "/", Setting.ServerDomain, false, true)
  153. }
  154. }
  155. func catch() {
  156. exception := recover()
  157. if exception != nil {
  158. logger.Println(exception)
  159. }
  160. }