-
Notifications
You must be signed in to change notification settings - Fork 0
/
authn.go
33 lines (27 loc) · 985 Bytes
/
authn.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
// Copyright 2023 daz-3ux(杨鹏达) <[email protected]>. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file. The original repo for
// this file is https://github.com/Daz-3ux/dBlog.
package middleware
import (
"github.com/gin-gonic/gin"
"github.com/Daz-3ux/dBlog/internal/pkg/core"
"github.com/Daz-3ux/dBlog/internal/pkg/errno"
"github.com/Daz-3ux/dBlog/internal/pkg/known"
"github.com/Daz-3ux/dBlog/pkg/token"
)
// Authn is an authentication Gin middleware used to extract and validate a token from gin.Context
// If the token is valid, it sets the `sub` from the token as the <username> in gin.Context's XUsernameKey key
func Authn() gin.HandlerFunc {
return func(c *gin.Context) {
// extract JWT token
username, err := token.ParseRequest(c)
if err != nil {
core.WriteResponse(c, errno.ErrTokenInvalid, nil)
c.Abort()
return
}
c.Set(known.XUsernameKey, username)
c.Next()
}
}