|
| 1 | +// a simple middleware for handling JWT Tokens in Pragma Go backends |
| 2 | +package pjwt |
| 3 | + |
| 4 | +import ( |
| 5 | + "context" |
| 6 | + "fmt" |
| 7 | + "net/http" |
| 8 | + "os" |
| 9 | + "strings" |
| 10 | + "time" |
| 11 | + |
| 12 | + "github.com/dgrijalva/jwt-go" |
| 13 | +) |
| 14 | + |
| 15 | +var SECRET_KEY string |
| 16 | + |
| 17 | +func init() { |
| 18 | + SECRET_KEY = os.Getenv("PRAGMA_JWT_SECRET_KEY") |
| 19 | + if SECRET_KEY == "" { |
| 20 | + panic("JWT Secret not found in environment") |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +type Adapter func(http.Handler) http.Handler |
| 25 | + |
| 26 | +func SetAuthContext() Adapter { |
| 27 | + return func(h http.Handler) http.Handler { |
| 28 | + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 29 | + v := r.Header.Get("Authorization") |
| 30 | + if !strings.Contains(v, "bearer") { |
| 31 | + h.ServeHTTP(w, r) |
| 32 | + return |
| 33 | + } |
| 34 | + |
| 35 | + tokenString := strings.SplitAfter(v, " ")[1] |
| 36 | + token, err := jwt.Parse(tokenString, func(t *jwt.Token) (interface{}, error) { |
| 37 | + if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok { |
| 38 | + return nil, fmt.Errorf("Unexpected signing method: %v", t.Header["alg"]) |
| 39 | + } |
| 40 | + |
| 41 | + return []byte(SECRET_KEY), nil |
| 42 | + }) |
| 43 | + if err != nil { |
| 44 | + panic(err) |
| 45 | + } |
| 46 | + |
| 47 | + if !token.Valid { |
| 48 | + panic(err) |
| 49 | + } |
| 50 | + |
| 51 | + claims, ok := token.Claims.(jwt.MapClaims) |
| 52 | + if !ok { |
| 53 | + // TODO |
| 54 | + panic("something not ok") |
| 55 | + } |
| 56 | + |
| 57 | + ctx := context.WithValue(r.Context(), "user_id", claims["user_id"]) |
| 58 | + |
| 59 | + h.ServeHTTP(w, r.WithContext(ctx)) |
| 60 | + }) |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +// create a claims token |
| 65 | +func NewClaims(uid string) *jwt.Token { |
| 66 | + return jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ |
| 67 | + "user_id": uid, |
| 68 | + "exp": time.Now().Add(time.Hour * time.Duration(12)).Unix(), |
| 69 | + "iat": time.Now().Unix(), |
| 70 | + }) |
| 71 | +} |
| 72 | + |
| 73 | +// create a signed claims string |
| 74 | +func NewSignedString(uid string) (string, error) { |
| 75 | + return NewClaims(uid).SignedString(SECRET_KEY) |
| 76 | +} |
| 77 | + |
| 78 | +func UserIDFromContext(ctx context.Context) (string, bool) { |
| 79 | + uid, ok := ctx.Value("user_id").(string) |
| 80 | + if uid == "" { |
| 81 | + ok = false |
| 82 | + } |
| 83 | + return uid, ok |
| 84 | +} |
0 commit comments