diff options
| author | Melonai <einebeere@gmail.com> | 2021-07-26 23:50:43 +0200 |
|---|---|---|
| committer | Melonai <einebeere@gmail.com> | 2021-07-26 23:50:43 +0200 |
| commit | 175da8f22cd791e81338fe61e6099125868cf5a0 (patch) | |
| tree | 91a234d8aafd54be34aae5ff5b948b34e52fb020 /token.go | |
| parent | 83a8214119eccb39f4c38e7b1ae54daebdeb0184 (diff) | |
| download | portgate-175da8f22cd791e81338fe61e6099125868cf5a0.tar.zst portgate-175da8f22cd791e81338fe61e6099125868cf5a0.zip | |
Basic Authentication and Authorization
Diffstat (limited to 'token.go')
| -rw-r--r-- | token.go | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/token.go b/token.go new file mode 100644 index 0000000..1031e7c --- /dev/null +++ b/token.go @@ -0,0 +1,42 @@ +package portgate + +import ( + "github.com/golang-jwt/jwt" + "github.com/valyala/fasthttp" + "time" +) + +func CreateToken(config *Config, givenKey string) (string, error) { + // Our token will last 7 days + token := jwt.NewWithClaims(jwt.SigningMethodHS512, jwt.StandardClaims{ + ExpiresAt: GetExpirationDateFrom(time.Now()).Unix(), + IssuedAt: time.Now().Unix(), + }) + + return token.SignedString([]byte(config.jwtSecret)) +} + +func VerifyToken(config *Config, tokenString string) (bool, error) { + token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { + return []byte(config.jwtSecret), nil + }) + + if err == nil && token.Valid { + return true, nil + } else { + return false, err + } +} + +func VerifyTokenFromCookie(config *Config, ctx *fasthttp.RequestCtx) bool { + cookie := ctx.Request.Header.Cookie("_portgate_token") + if cookie != nil { + ok, _ := VerifyToken(config, string(cookie)) + return ok + } + return false +} + +func GetExpirationDateFrom(date time.Time) time.Time { + return date.AddDate(0, 0, 7) +} |
