-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
57 lines (49 loc) · 1.64 KB
/
jwt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package vcago
import (
"net/http"
"os"
"github.com/Viva-con-Agua/vcago/vmod"
"github.com/dgrijalva/jwt-go"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
//JWTMiddleware handles authentication by jwt
type JWTMiddleware struct {
RequestCount uint64 `json:"request_count"`
Scope string `json:"scope"`
}
//AccessCookieConfig can with echo for middleware.JWTWithConfig(vmod.AccessConfig) to handling access controll
//The token is reachable with c.Get("token")
var AccessCookieConfig = middleware.JWTConfig{
Claims: &vmod.AccessToken{},
ContextKey: "token",
TokenLookup: "cookie:access_token",
SigningKey: []byte(os.Getenv("JWT_SECRET")),
}
//RefreshCookieConfig can with echo for middleware.JWTWithConfig(vmod.AccessConfig) to handling access controll
//The token is reachable with c.Get("token")
var RefreshCookieConfig = middleware.JWTConfig{
Claims: &vmod.RefreshToken{},
ContextKey: "token",
TokenLookup: "cookie:refresh_token",
SigningKey: []byte(os.Getenv("JWT_SECRET")),
}
//JWTNewAccessCookie create a new http.Cookie contains the access_token.
func JWTNewAccessCookie(token *vmod.JWTToken) *http.Cookie {
var cookie = HTTPBaseCookie
cookie.Name = "access_token"
cookie.Value = token.AccessToken
return &cookie
}
//JWTNewRefreshCookie create a new http.Cookie contains the refresh_token.
func JWTNewRefreshCookie(token *vmod.JWTToken) *http.Cookie {
var cookie = HTTPBaseCookie
cookie.Name = "refresh_token"
cookie.Value = token.RefreshToken
return &cookie
}
func JWTUser(c echo.Context) (u *vmod.User) {
token := c.Get("token").(*jwt.Token)
u = &token.Claims.(*vmod.AccessToken).User
return
}