Skip to content

Commit ebb6620

Browse files
committed
initial commit
0 parents  commit ebb6620

File tree

3 files changed

+92
-0
lines changed

3 files changed

+92
-0
lines changed

go.mod

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
module github.com/PragmaEngineering/pjwt
2+
3+
go 1.14
4+
5+
require github.com/dgrijalva/jwt-go v3.2.0+incompatible

go.sum

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
github.com/dgrijalva/jwt-go v1.0.2 h1:KPldsxuKGsS2FPWsNeg9ZO18aCrGKujPoWXn2yo+KQM=
2+
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
3+
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=

middleware.go

+84
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
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

Comments
 (0)