Documentation
¶
Index ¶
- func Authenticate() gin.HandlerFunc
- func CreateRefreshToken(userId int64, username string, orgId int64, productId int64, ...) (string, error)
- func CreateToken(userId int64, username string, orgId int64, productId int64, roles []string, ...) (string, error)
- func InitToken(iss, access, refresh string)
- func ParseRefreshToken(tokenString string) (dto.LoginUser, error)
- func ParseToken(tokenString string) (userInfo dto.LoginUser, err error)
- type UserClaims
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Authenticate ¶
func Authenticate() gin.HandlerFunc
Authenticate returns a Gin middleware that validates the Bearer JWT token in the Authorization header. On success it stores the parsed LoginUser in the request context under the key "userInfo"; on failure it aborts with HTTP 401 Unauthorized.
Example ¶
ExampleAuthenticate shows the Gin middleware in action. A valid Bearer token returns 200; a missing header returns 401.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"time"
"github.com/gin-gonic/gin"
"github.com/phcp-tech/common-library-golang/token"
)
func main() {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(token.Authenticate())
r.GET("/protected", func(c *gin.Context) { c.Status(http.StatusOK) })
// Valid token — 200 OK.
tok, _ := token.CreateToken(1, "alice", 5, 10, []string{"admin"}, time.Hour)
w := httptest.NewRecorder()
req, _ := http.NewRequest(http.MethodGet, "/protected", nil)
req.Header.Set("Authorization", "Bearer "+tok)
r.ServeHTTP(w, req)
fmt.Println(w.Code)
// Missing Authorization header — 401 Unauthorized.
w2 := httptest.NewRecorder()
req2, _ := http.NewRequest(http.MethodGet, "/protected", nil)
r.ServeHTTP(w2, req2)
fmt.Println(w2.Code)
}
Output: 200 401
func CreateRefreshToken ¶
func CreateRefreshToken(userId int64, username string, orgId int64, productId int64, expires time.Duration) (string, error)
CreateRefreshToken creates a long-lived refresh token signed with a different secret (jwt.refresh.secretcode). The expires parameter controls the token lifetime in minutes.
Example ¶
ExampleCreateRefreshToken shows how to generate a long-lived refresh token. Refresh tokens are signed with a separate secret (jwt.refresh.secretcode) and do not carry role information.
package main
import (
"fmt"
"time"
"github.com/phcp-tech/common-library-golang/token"
)
func main() {
tok, err := token.CreateRefreshToken(42, "alice", 7, 100, 24*time.Hour)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(tok != "")
}
Output: true
func CreateToken ¶
func CreateToken(userId int64, username string, orgId int64, productId int64, roles []string, expires time.Duration) (string, error)
CreateToken generates a signed HS256 JWT access token for the given user, valid for the specified duration.
Example ¶
ExampleCreateToken shows how to generate a signed HS256 access token for a user. The returned string is a standard Bearer token for use in the Authorization header.
package main
import (
"fmt"
"time"
"github.com/phcp-tech/common-library-golang/token"
)
func main() {
tok, err := token.CreateToken(42, "alice", 7, 100, []string{"admin", "editor"}, time.Hour)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(tok != "")
}
Output: true
func InitToken ¶
func InitToken(iss, access, refresh string)
InitToken stores the JWT signing secrets and issuer. It must be called once at application startup before any token function. The secrets and issuer are typically read from env.Env() after env.InitEnv().
Example ¶
ExampleInitToken shows how to initialise the token package once at application startup. The secrets and issuer are typically read from env.Env() after env.InitEnv() has been called.
package main
import (
"github.com/phcp-tech/common-library-golang/token"
)
func main() {
token.InitToken(
"myapp", // jwt issuer identifier
"my-access-secret", // jwt.access.secretcode from config
"my-refresh-secret", // jwt.refresh.secretcode from config
)
}
Output:
func ParseRefreshToken ¶
ParseRefreshToken parses and validates a refresh token using the refresh secret code. Returns the embedded user info on success, or an error if the token is invalid or expired.
Example ¶
ExampleParseRefreshToken shows the refresh-token round-trip. Note that Roles is always empty in a refresh token.
package main
import (
"fmt"
"time"
"github.com/phcp-tech/common-library-golang/token"
)
func main() {
tok, err := token.CreateRefreshToken(42, "alice", 7, 100, 24*time.Hour)
if err != nil {
fmt.Println("error:", err)
return
}
user, err := token.ParseRefreshToken(tok)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(user.Username)
fmt.Println(user.OrgId)
fmt.Println(len(user.Roles) == 0) // refresh tokens carry no roles
}
Output: alice 7 true
func ParseToken ¶
ParseToken parses and validates a JWT access token string, returning the embedded LoginUser information on success or an error if the token is invalid or expired.
Example ¶
ExampleParseToken shows the create-and-parse round-trip. ParseToken validates the signature, issuer, and token type, then returns the embedded LoginUser.
package main
import (
"fmt"
"time"
"github.com/phcp-tech/common-library-golang/token"
)
func main() {
tok, err := token.CreateToken(42, "alice", 7, 100, []string{"admin", "editor"}, time.Hour)
if err != nil {
fmt.Println("error:", err)
return
}
user, err := token.ParseToken(tok)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(user.Username)
fmt.Println(user.UserId)
fmt.Println(user.OrgId)
}
Output: alice 42 7
Types ¶
type UserClaims ¶
type UserClaims struct {
dto.LoginUser
jwt.RegisteredClaims
}
UserClaims holds the JWT claims for an authenticated user, including UserId, ProductId, and Roles embedded from LoginUser, along with standard registered JWT claims. Note: the secret key is assumed trustworthy; field-level encryption may be added in the future.