session.go 1.5 KB

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