mirror of
https://github.com/kataras/iris.git
synced 2025-12-18 02:17:05 +00:00
add context partial user helper and accept a generic interface on SetUser - the same method now returns an error if the given value does not complete at least one method of the User interface
This commit is contained in:
@@ -28,6 +28,21 @@ type UserClaims struct {
|
||||
Username string `json:"username"`
|
||||
}
|
||||
|
||||
// GetID implements the partial context user's ID interface.
|
||||
// Note that if claims were a map then the claims value converted to UserClaims
|
||||
// and no need to implement any method.
|
||||
//
|
||||
// This is useful when multiple auth methods are used (e.g. basic auth, jwt)
|
||||
// but they all share a couple of methods.
|
||||
func (u *UserClaims) GetID() string {
|
||||
return u.ID
|
||||
}
|
||||
|
||||
// GetUsername implements the partial context user's Username interface.
|
||||
func (u *UserClaims) GetUsername() string {
|
||||
return u.Username
|
||||
}
|
||||
|
||||
// Validate completes the middleware's custom ClaimsValidator.
|
||||
// It will not accept a token which its claims missing the username field
|
||||
// (useful to not accept refresh tokens generated by the same algorithm).
|
||||
@@ -58,8 +73,15 @@ func main() {
|
||||
protectedAPI.Use(verifyMiddleware)
|
||||
|
||||
protectedAPI.Get("/", func(ctx iris.Context) {
|
||||
claims := jwt.Get(ctx).(*UserClaims)
|
||||
ctx.Writef("Username: %s\n", claims.Username)
|
||||
// Access the claims through: jwt.Get:
|
||||
// claims := jwt.Get(ctx).(*UserClaims)
|
||||
// ctx.Writef("Username: %s\n", claims.Username)
|
||||
//
|
||||
// OR through context's user (if at least one method was implement by our UserClaims):
|
||||
user := ctx.User()
|
||||
id, _ := user.GetID()
|
||||
username, _ := user.GetUsername()
|
||||
ctx.Writef("ID: %s\nUsername: %s\n", id, username)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user