session.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package models
  2. import (
  3. "github.com/beego/beego/v2/client/orm"
  4. "time"
  5. )
  6. type Session struct {
  7. SessionId int `orm:"column(session_id);pk"`
  8. UserId int
  9. OpenId string
  10. AccessToken string
  11. ExpireTime time.Time
  12. CreatedTime time.Time
  13. LastUpdatedTime time.Time
  14. }
  15. func GetSessionByToken(token string) (item *Session, err error) {
  16. sql := `SELECT * FROM session WHERE access_token=? AND expire_time> NOW() ORDER BY session_id DESC LIMIT 1 `
  17. o := orm.NewOrmUsingDB("rddp")
  18. err = o.Raw(sql, token).QueryRow(&item)
  19. return
  20. }
  21. func GetSessionCountByToken(token string) (count int, err error) {
  22. sql := `SELECT COUNT(1) AS count FROM session WHERE access_token=? AND expire_time> NOW() ORDER BY session_id DESC LIMIT 1 `
  23. o := orm.NewOrmUsingDB("rddp")
  24. err = o.Raw(sql, token).QueryRow(&count)
  25. return
  26. }
  27. //添加用户session信息
  28. func AddSession(item *Session) (err error) {
  29. o := orm.NewOrmUsingDB("rddp")
  30. _, err = o.Insert(item)
  31. return
  32. }
  33. func GetTokenByUid(uid int) (item *Session, err error) {
  34. sql := `SELECT * FROM session WHERE user_id=? AND expire_time> NOW() ORDER BY session_id DESC LIMIT 1 `
  35. o := orm.NewOrmUsingDB("rddp")
  36. err = o.Raw(sql, uid).QueryRow(&item)
  37. return
  38. }
  39. //根据用户id获取token
  40. func GetTokenByOpenId(openId string) (item *Session, err error) {
  41. sql := `SELECT * FROM session WHERE open_id=? AND expire_time> NOW() ORDER BY session_id DESC LIMIT 1 `
  42. o := orm.NewOrmUsingDB("rddp")
  43. err = o.Raw(sql, openId).QueryRow(&item)
  44. return
  45. }
  46. //更新session
  47. func UpdateSession(sessionId, userId int, expireTime time.Time) (err error) {
  48. sql := `update session set user_id=?,expire_time=? where session_id = ? `
  49. o := orm.NewOrmUsingDB("rddp")
  50. _, err = o.Raw(sql, userId, expireTime, sessionId).Exec()
  51. return
  52. }