Skip to content

Commit b00ab28

Browse files
AdwindOneviaappleboy
authored
docs(example): update code format (#322)
* update code format * chore: refactor project configuration and tests - Delete the `.idea/workspace.xml` configuration file from the project. Signed-off-by: Bo-Yi Wu <[email protected]> --------- Signed-off-by: Bo-Yi Wu <[email protected]> Co-authored-by: via <[email protected]> Co-authored-by: Bo-Yi Wu <[email protected]>
1 parent 76f00ea commit b00ab28

File tree

3 files changed

+240
-191
lines changed

3 files changed

+240
-191
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,4 @@ _testmain.go
2525
.DS_Store
2626
.vscode
2727
coverage.out
28+
.idea

README.md

+119-94
Original file line numberDiff line numberDiff line change
@@ -65,17 +65,10 @@ type login struct {
6565
Password string `form:"password" json:"password" binding:"required"`
6666
}
6767

68-
var identityKey = "id"
69-
70-
func helloHandler(c *gin.Context) {
71-
claims := jwt.ExtractClaims(c)
72-
user, _ := c.Get(identityKey)
73-
c.JSON(200, gin.H{
74-
"userID": claims[identityKey],
75-
"userName": user.(*User).UserName,
76-
"text": "Hello World.",
77-
})
78-
}
68+
var (
69+
identityKey = "id"
70+
port string
71+
)
7972

8073
// User demo
8174
type User struct {
@@ -84,117 +77,149 @@ type User struct {
8477
LastName string
8578
}
8679

87-
func main() {
88-
port := os.Getenv("PORT")
89-
r := gin.Default()
90-
80+
func init() {
81+
port = os.Getenv("PORT")
9182
if port == "" {
9283
port = "8000"
9384
}
85+
}
9486

87+
func main() {
88+
engine := gin.Default()
9589
// the jwt middleware
96-
authMiddleware, err := jwt.New(&jwt.GinJWTMiddleware{
90+
authMiddleware, err := jwt.New(initParams())
91+
if err != nil {
92+
log.Fatal("JWT Error:" + err.Error())
93+
}
94+
95+
// register middleware
96+
engine.Use(handlerMiddleWare(authMiddleware))
97+
98+
// register route
99+
registerRoute(engine, authMiddleware)
100+
101+
// start http server
102+
if err = http.ListenAndServe(":"+port, engine); err != nil {
103+
log.Fatal(err)
104+
}
105+
}
106+
107+
func registerRoute(r *gin.Engine, handle *jwt.GinJWTMiddleware) {
108+
r.POST("/login", handle.LoginHandler)
109+
r.NoRoute(handle.MiddlewareFunc(), handleNoRoute())
110+
111+
auth := r.Group("/auth", handle.MiddlewareFunc())
112+
auth.GET("/refresh_token", handle.RefreshHandler)
113+
auth.GET("/hello", helloHandler)
114+
}
115+
116+
func handlerMiddleWare(authMiddleware *jwt.GinJWTMiddleware) gin.HandlerFunc {
117+
return func(context *gin.Context) {
118+
errInit := authMiddleware.MiddlewareInit()
119+
if errInit != nil {
120+
log.Fatal("authMiddleware.MiddlewareInit() Error:" + errInit.Error())
121+
}
122+
}
123+
}
124+
125+
func initParams() *jwt.GinJWTMiddleware {
126+
127+
return &jwt.GinJWTMiddleware{
97128
Realm: "test zone",
98129
Key: []byte("secret key"),
99130
Timeout: time.Hour,
100131
MaxRefresh: time.Hour,
101132
IdentityKey: identityKey,
102-
PayloadFunc: func(data interface{}) jwt.MapClaims {
103-
if v, ok := data.(*User); ok {
104-
return jwt.MapClaims{
105-
identityKey: v.UserName,
106-
}
107-
}
108-
return jwt.MapClaims{}
109-
},
110-
IdentityHandler: func(c *gin.Context) interface{} {
111-
claims := jwt.ExtractClaims(c)
112-
return &User{
113-
UserName: claims[identityKey].(string),
114-
}
115-
},
116-
Authenticator: func(c *gin.Context) (interface{}, error) {
117-
var loginVals login
118-
if err := c.ShouldBind(&loginVals); err != nil {
119-
return "", jwt.ErrMissingLoginValues
120-
}
121-
userID := loginVals.Username
122-
password := loginVals.Password
123-
124-
if (userID == "admin" && password == "admin") || (userID == "test" && password == "test") {
125-
return &User{
126-
UserName: userID,
127-
LastName: "Bo-Yi",
128-
FirstName: "Wu",
129-
}, nil
130-
}
131-
132-
return nil, jwt.ErrFailedAuthentication
133-
},
134-
Authorizator: func(data interface{}, c *gin.Context) bool {
135-
if v, ok := data.(*User); ok && v.UserName == "admin" {
136-
return true
137-
}
133+
PayloadFunc: payloadFunc(),
138134

139-
return false
140-
},
141-
Unauthorized: func(c *gin.Context, code int, message string) {
142-
c.JSON(code, gin.H{
143-
"code": code,
144-
"message": message,
145-
})
146-
},
147-
// TokenLookup is a string in the form of "<source>:<name>" that is used
148-
// to extract token from the request.
149-
// Optional. Default value "header:Authorization".
150-
// Possible values:
151-
// - "header:<name>"
152-
// - "query:<name>"
153-
// - "cookie:<name>"
154-
// - "param:<name>"
155-
TokenLookup: "header: Authorization, query: token, cookie: jwt",
135+
IdentityHandler: identityHandler(),
136+
Authenticator: authenticator(),
137+
Authorizator: authorizator(),
138+
Unauthorized: unauthorized(),
139+
TokenLookup: "header: Authorization, query: token, cookie: jwt",
156140
// TokenLookup: "query:token",
157141
// TokenLookup: "cookie:token",
158-
159-
// TokenHeadName is a string in the header. Default value is "Bearer"
160142
TokenHeadName: "Bearer",
143+
TimeFunc: time.Now,
144+
}
145+
}
161146

162-
// TimeFunc provides the current time. You can override it to use another time value. This is useful for testing or if your server uses a different time zone than your tokens.
163-
TimeFunc: time.Now,
164-
})
147+
func payloadFunc() func(data interface{}) jwt.MapClaims {
148+
return func(data interface{}) jwt.MapClaims {
149+
if v, ok := data.(*User); ok {
150+
return jwt.MapClaims{
151+
identityKey: v.UserName,
152+
}
153+
}
154+
return jwt.MapClaims{}
155+
}
156+
}
165157

166-
if err != nil {
167-
log.Fatal("JWT Error:" + err.Error())
158+
func identityHandler() func(c *gin.Context) interface{} {
159+
return func(c *gin.Context) interface{} {
160+
claims := jwt.ExtractClaims(c)
161+
return &User{
162+
UserName: claims[identityKey].(string),
163+
}
168164
}
165+
}
169166

170-
// When you use jwt.New(), the function is already automatically called for checking,
171-
// which means you don't need to call it again.
172-
errInit := authMiddleware.MiddlewareInit()
167+
func authenticator() func(c *gin.Context) (interface{}, error) {
168+
return func(c *gin.Context) (interface{}, error) {
169+
var loginVals login
170+
if err := c.ShouldBind(&loginVals); err != nil {
171+
return "", jwt.ErrMissingLoginValues
172+
}
173+
userID := loginVals.Username
174+
password := loginVals.Password
173175

174-
if errInit != nil {
175-
log.Fatal("authMiddleware.MiddlewareInit() Error:" + errInit.Error())
176+
if (userID == "admin" && password == "admin") || (userID == "test" && password == "test") {
177+
return &User{
178+
UserName: userID,
179+
LastName: "Bo-Yi",
180+
FirstName: "Wu",
181+
}, nil
182+
}
183+
return nil, jwt.ErrFailedAuthentication
176184
}
185+
}
177186

178-
r.POST("/login", authMiddleware.LoginHandler)
187+
func authorizator() func(data interface{}, c *gin.Context) bool {
188+
return func(data interface{}, c *gin.Context) bool {
189+
if v, ok := data.(*User); ok && v.UserName == "admin" {
190+
return true
191+
}
192+
return false
193+
}
194+
}
179195

180-
r.NoRoute(authMiddleware.MiddlewareFunc(), func(c *gin.Context) {
196+
func unauthorized() func(c *gin.Context, code int, message string) {
197+
return func(c *gin.Context, code int, message string) {
198+
c.JSON(code, gin.H{
199+
"code": code,
200+
"message": message,
201+
})
202+
}
203+
}
204+
205+
func handleNoRoute() func(c *gin.Context) {
206+
return func(c *gin.Context) {
181207
claims := jwt.ExtractClaims(c)
182208
log.Printf("NoRoute claims: %#v\n", claims)
183209
c.JSON(404, gin.H{"code": "PAGE_NOT_FOUND", "message": "Page not found"})
184-
})
185-
186-
auth := r.Group("/auth")
187-
// Refresh time can be longer than token timeout
188-
auth.GET("/refresh_token", authMiddleware.RefreshHandler)
189-
auth.Use(authMiddleware.MiddlewareFunc())
190-
{
191-
auth.GET("/hello", helloHandler)
192210
}
211+
}
193212

194-
if err := http.ListenAndServe(":"+port, r); err != nil {
195-
log.Fatal(err)
196-
}
213+
func helloHandler(c *gin.Context) {
214+
claims := jwt.ExtractClaims(c)
215+
user, _ := c.Get(identityKey)
216+
c.JSON(200, gin.H{
217+
"userID": claims[identityKey],
218+
"userName": user.(*User).UserName,
219+
"text": "Hello World.",
220+
})
197221
}
222+
198223
```
199224

200225
## Demo

0 commit comments

Comments
 (0)