| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- package notifications
- import (
- "crypto/sha1"
- "encoding/hex"
- "fmt"
- "time"
- "github.com/Unknwon/com"
- "github.com/grafana/grafana/pkg/setting"
- )
- // create a time limit code
- // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
- func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string {
- format := "200601021504"
- var start, end time.Time
- var startStr, endStr string
- if startInf == nil {
- // Use now time create code
- start = time.Now()
- startStr = start.Format(format)
- } else {
- // use start string create code
- startStr = startInf.(string)
- start, _ = time.ParseInLocation(format, startStr, time.Local)
- startStr = start.Format(format)
- }
- end = start.Add(time.Minute * time.Duration(minutes))
- endStr = end.Format(format)
- // create sha1 encode string
- sh := sha1.New()
- sh.Write([]byte(data + setting.SecretKey + startStr + endStr + com.ToStr(minutes)))
- encoded := hex.EncodeToString(sh.Sum(nil))
- code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
- return code
- }
- // verify time limit code
- func VerifyTimeLimitCode(data string, minutes int, code string) bool {
- if len(code) <= 18 {
- return false
- }
- // split code
- start := code[:12]
- lives := code[12:18]
- if d, err := com.StrTo(lives).Int(); err == nil {
- minutes = d
- }
- // right active code
- retCode := CreateTimeLimitCode(data, minutes, start)
- if retCode == code && minutes > 0 {
- // check time is expired or not
- before, _ := time.ParseInLocation("200601021504", start, time.Local)
- now := time.Now()
- if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() {
- return true
- }
- }
- return false
- }
|