clndr/api/middleware/jwt.go

59 lines
1.3 KiB
Go

package middleware
import (
"fmt"
"log"
"net/http"
"os"
"strings"
"github.com/golang-jwt/jwt"
)
var secret = []byte(os.Getenv("SECRET"))
func Auth(f http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// get token
authheader, ok := r.Header["Authorization"]
if !ok {
http.Error(w, "Missing token", http.StatusBadRequest)
return
}
tokenString := strings.Split(authheader[0], " ")[1]
//parse token
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return secret, nil
})
if err != nil {
http.Error(w, "Bad token", http.StatusBadRequest)
return
}
// check if path is allowed
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid && r.URL.Path == claims["path"] {
log.Println(r.URL.Path)
f(w, r)
} else {
log.Println(err)
http.Error(w, "Forbidden", http.StatusUnauthorized)
}
// it's all good
}
}
func GenerateToken(path string) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"path": path,
})
tokenString, err := token.SignedString(secret)
if err != nil {
panic(err)
}
fmt.Println(tokenString)
}