udemy-go-web-2/internal/urlsigner/signer.go

46 lines
950 B
Go
Raw Normal View History

package urlsigner
import (
"fmt"
"strings"
"time"
goalone "github.com/bwmarrin/go-alone"
)
type Signer struct {
Secret []byte
}
func (s *Signer) GenerateTokenFromString(data string) string {
var urlToSign string
crypt := goalone.New(s.Secret, goalone.Timestamp)
if strings.Contains(data, "?") {
urlToSign = fmt.Sprintf("%s&hash=", data)
} else {
urlToSign = fmt.Sprintf("%s?hash=", data)
}
tokenBytes := crypt.Sign([]byte(urlToSign))
token := string(tokenBytes)
return token
}
func (s *Signer) VerifyToken(token string) bool {
crypt := goalone.New(s.Secret, goalone.Timestamp)
_, err := crypt.Unsign([]byte(token))
if err != nil {
fmt.Println(err)
2024-08-21 09:44:38 +00:00
return false
}
return true
}
func (s *Signer) Expired(token string, minutesUntilExpire int) bool {
crypt := goalone.New(s.Secret, goalone.Timestamp)
ts := crypt.Parse([]byte(token))
return time.Since(ts.Timestamp) > time.Duration(minutesUntilExpire)*time.Minute
}