refresh.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package dao
  2. import (
  3. "context"
  4. "database/sql"
  5. "encoding/hex"
  6. "fmt"
  7. "time"
  8. "go-common/app/job/main/passport-auth/model"
  9. "go-common/library/log"
  10. )
  11. const (
  12. _addRefreshSQL = "INSERT IGNORE INTO user_refresh_%s (mid,appid,refresh,token,expires) VALUES (?,?,?,?,?)"
  13. _delRefreshSQL = "DELETE FROM user_refresh_%s WHERE refresh = ?"
  14. )
  15. // AddRefresh save token
  16. func (d *Dao) AddRefresh(c context.Context, t *model.Refresh, refresh, token []byte, ct time.Time) (affected int64, err error) {
  17. var row sql.Result
  18. if row, err = d.db.Exec(c, fmt.Sprintf(_addRefreshSQL, formatRefreshSuffix(ct)), t.Mid, t.AppID, refresh, token, t.Expires); err != nil {
  19. log.Error("d.AddToken(%v) err(%v)", t, err)
  20. return
  21. }
  22. return row.RowsAffected()
  23. }
  24. // DelRefresh del token
  25. func (d *Dao) DelRefresh(c context.Context, refresh []byte, ct time.Time) (affected int64, err error) {
  26. var res sql.Result
  27. if res, err = d.db.Exec(c, fmt.Sprintf(_delRefreshSQL, formatRefreshSuffix(ct)), refresh); err != nil {
  28. log.Error("del token failed, dao.db.Exec(%s) error(%v)", hex.EncodeToString(refresh), err)
  29. return
  30. }
  31. return res.RowsAffected()
  32. }
  33. func formatRefreshSuffix(t time.Time) string {
  34. return formatByDate(t.Year(), int(t.Month()))
  35. }
  36. func formatByDate(year, month int) string {
  37. if month%2 == 1 {
  38. return fmt.Sprintf("%4d%02d", year, month)
  39. }
  40. return fmt.Sprintf("%4d%02d", year, month-1)
  41. }