token

package
v0.0.0-...-32bbb43 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 26, 2021 License: Unlicense Imports: 4 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var JwtAuthenithication = func(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		notAuth := []string{"/auth/register", "/auth/login"}
		requestPath := r.URL.Path
		for _, value := range notAuth {
			if value == requestPath {
				next.ServeHTTP(w, r)
				return
			}
		}

		c, err := r.Cookie("token")
		if err != nil {
			if err == http.ErrNoCookie {
				w.WriteHeader(http.StatusUnauthorized)
				return
			}

			w.WriteHeader(http.StatusBadRequest)
			return
		}

		tokenString := c.Value
		claims := &Claims{}

		token, err := jwt.ParseWithClaims(tokenString, claims, func(tk *jwt.Token) (interface{}, error) {
			return []byte(os.Getenv("token_password")), nil
		})
		if err != nil {
			if err == jwt.ErrSignatureInvalid {
				w.WriteHeader(http.StatusUnauthorized)
				return
			}

			w.WriteHeader(http.StatusBadRequest)
			return
		}

		if !token.Valid {
			w.WriteHeader(http.StatusUnauthorized)
			return
		}

		if time.Now().Unix()-claims.ExpiresAt > 30 {
			w.WriteHeader(http.StatusBadRequest)
			return
		}

		claims, expTime := NewClaims(claims.Login)
		tokenStr := claims.String()

		http.SetCookie(w, &http.Cookie{
			Name:    "token",
			Value:   tokenStr,
			Expires: expTime,
			Path:    "/",

			HttpOnly: true,
		})

		next.ServeHTTP(w, r)
	})
}

Functions

This section is empty.

Types

type Claims

type Claims struct {
	Login string `json:"login"`
	jwt.StandardClaims
}

func NewClaims

func NewClaims(login string) (*Claims, time.Time)

func (*Claims) String

func (tk *Claims) String() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL