guildgate/token.go

83 lines
1.8 KiB
Go
Raw Permalink Normal View History

2020-09-17 17:36:39 -04:00
package main
import (
"errors"
"log"
2021-02-21 19:39:47 -05:00
"strings"
2020-09-17 17:36:39 -04:00
"time"
"github.com/dgrijalva/jwt-go"
)
type tokenClaim struct {
Sponsor string `json:"sponsor_username"`
jwt.StandardClaims
}
func generateToken(sponsor string) (string, error) {
claim := tokenClaim{
Sponsor: sponsor,
StandardClaims: jwt.StandardClaims{
ExpiresAt: time.Now().UTC().Unix() + 86400,
Issuer: "GuildGate",
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
signedToken, err := token.SignedString([]byte(Conf.Secret))
if err != nil {
return "", err
} else {
return signedToken, nil
}
}
func generatePasswordToken(sponsor string) (string, error) {
claim := tokenClaim{
Sponsor: sponsor,
StandardClaims: jwt.StandardClaims{
ExpiresAt: time.Now().UTC().Unix() + 3600,
Issuer: "GuildGate",
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
signedToken, err := token.SignedString([]byte(Conf.Secret))
if err != nil {
return "", err
} else {
passwordTokenSet[signedToken] = true
return signedToken, nil
}
}
func validateToken(tok string, pass bool) (string, error) {
2020-09-17 17:36:39 -04:00
token, err := jwt.ParseWithClaims(
2021-02-21 19:39:47 -05:00
strings.TrimSpace(tok),
2020-09-17 17:36:39 -04:00
&tokenClaim{},
func(token *jwt.Token) (interface{}, error) {
return []byte(Conf.Secret), nil
},
)
if err != nil {
2020-09-22 18:21:01 -04:00
return "", err
2020-09-17 17:36:39 -04:00
}
claims, ok := token.Claims.(*tokenClaim)
if !ok {
2020-09-22 18:21:01 -04:00
return "", errors.New("Invalid token sponsor passed")
2020-09-17 17:36:39 -04:00
}
if claims.ExpiresAt < time.Now().UTC().Unix() {
2020-09-22 18:21:01 -04:00
return "", errors.New("Token has expired")
2020-09-17 17:36:39 -04:00
}
if pass {
if !passwordTokenSet[tok] {
return "", errors.New("Password token already used")
} else {
log.Printf("Valid Password token received; sponsored by %v\n", claims.Sponsor)
delete(passwordTokenSet, tok)
return claims.Sponsor, nil
}
}
2020-09-17 17:36:39 -04:00
log.Printf("Valid token received; sponsored by %v\n", claims.Sponsor)
2020-09-22 18:21:01 -04:00
return claims.Sponsor, nil
2020-09-17 17:36:39 -04:00
}