codes.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package notifications
  2. import (
  3. "crypto/sha1"
  4. "encoding/hex"
  5. "fmt"
  6. "time"
  7. "github.com/Unknwon/com"
  8. "github.com/grafana/grafana/pkg/setting"
  9. )
  10. // create a time limit code
  11. // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
  12. func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string {
  13. format := "200601021504"
  14. var start, end time.Time
  15. var startStr, endStr string
  16. if startInf == nil {
  17. // Use now time create code
  18. start = time.Now()
  19. startStr = start.Format(format)
  20. } else {
  21. // use start string create code
  22. startStr = startInf.(string)
  23. start, _ = time.ParseInLocation(format, startStr, time.Local)
  24. startStr = start.Format(format)
  25. }
  26. end = start.Add(time.Minute * time.Duration(minutes))
  27. endStr = end.Format(format)
  28. // create sha1 encode string
  29. sh := sha1.New()
  30. sh.Write([]byte(data + setting.SecretKey + startStr + endStr + com.ToStr(minutes)))
  31. encoded := hex.EncodeToString(sh.Sum(nil))
  32. code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
  33. return code
  34. }
  35. // verify time limit code
  36. func VerifyTimeLimitCode(data string, minutes int, code string) bool {
  37. if len(code) <= 18 {
  38. return false
  39. }
  40. // split code
  41. start := code[:12]
  42. lives := code[12:18]
  43. if d, err := com.StrTo(lives).Int(); err == nil {
  44. minutes = d
  45. }
  46. // right active code
  47. retCode := CreateTimeLimitCode(data, minutes, start)
  48. if retCode == code && minutes > 0 {
  49. // check time is expired or not
  50. before, _ := time.ParseInLocation("200601021504", start, time.Local)
  51. now := time.Now()
  52. if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() {
  53. return true
  54. }
  55. }
  56. return false
  57. }