go-pingbot/website/routes/api/auth/token.go

47 lines
994 B
Go
Raw Normal View History

2021-08-02 19:32:36 +00:00
package auth
import (
2021-08-02 20:34:06 +00:00
"fmt"
"time"
2021-08-02 19:32:36 +00:00
"github.com/golang-jwt/jwt"
"gitlab.com/gaming0skar123/go/pingbot/config"
)
2021-08-02 20:34:06 +00:00
type authCustomClaims struct {
Name string `json:"name"`
Password string `json:"password"`
jwt.StandardClaims
}
func GenerateToken(username, password string) string {
claims := &authCustomClaims{
username,
password,
jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Hour * 48).Unix(),
Issuer: username,
IssuedAt: time.Now().Unix(),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
//encoded string
t, err := token.SignedString([]byte(config.JWT_Secret))
if err != nil {
panic(err)
}
return t
}
func ValidateToken(encodedToken string) (*jwt.Token, error) {
return jwt.Parse(encodedToken, func(token *jwt.Token) (interface{}, error) {
if _, isvalid := token.Method.(*jwt.SigningMethodHMAC); !isvalid {
return nil, fmt.Errorf("Invalid token", token.Header["alg"])
}
2021-08-02 19:32:36 +00:00
return []byte(config.JWT_Secret), nil
})
}