Last active
November 14, 2020 06:10
-
-
Save krittawatcode/daafe6121d9bc1bebef4bd11d5eae629 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package service | |
import ( | |
"fmt" | |
"os" | |
"time" | |
"github.com/dgrijalva/jwt-go" | |
) | |
//jwt service | |
type JWTService interface { | |
GenerateToken(email string, isUser bool) string | |
ValidateToken(token string) (*jwt.Token, error) | |
} | |
type authCustomClaims struct { | |
Name string `json:"name"` | |
User bool `json:"user"` | |
jwt.StandardClaims | |
} | |
type jwtServices struct { | |
secretKey string | |
issure string | |
} | |
//auth-jwt | |
func JWTAuthService() JWTService { | |
return &jwtServices{ | |
secretKey: getSecretKey(), | |
issure: "Bikash", | |
} | |
} | |
func getSecretKey() string { | |
secret := os.Getenv("SECRET") | |
if secret == "" { | |
secret = "secret" | |
} | |
return secret | |
} | |
func (service *jwtServices) GenerateToken(email string, isUser bool) string { | |
claims := &authCustomClaims{ | |
email, | |
isUser, | |
jwt.StandardClaims{ | |
ExpiresAt: time.Now().Add(time.Hour * 48).Unix(), | |
Issuer: service.issure, | |
IssuedAt: time.Now().Unix(), | |
}, | |
} | |
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) | |
//encoded string | |
t, err := token.SignedString([]byte(service.secretKey)) | |
if err != nil { | |
panic(err) | |
} | |
return t | |
} | |
func (service *jwtServices) 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"]) | |
} | |
return []byte(service.secretKey), nil | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment