2022-03-28 13:00:26 +02:00
|
|
|
//go:build go1.18
|
2022-05-24 00:44:36 +02:00
|
|
|
// +build go1.18
|
2022-03-28 13:00:26 +02:00
|
|
|
|
2022-04-02 16:30:55 +02:00
|
|
|
package auth
|
2022-03-28 13:00:26 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/kataras/iris/v12/context"
|
|
|
|
|
|
|
|
"github.com/kataras/jwt"
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
2022-04-02 20:14:46 +02:00
|
|
|
// StandardClaims is an alias of jwt.Claims, it holds the standard JWT claims.
|
2022-03-28 13:00:26 +02:00
|
|
|
StandardClaims = jwt.Claims
|
2022-04-02 20:14:46 +02:00
|
|
|
// User is an alias of an empty interface, it's here to declare the typeof T,
|
|
|
|
// which can be any custom struct type.
|
2022-04-07 00:56:42 +02:00
|
|
|
//
|
|
|
|
// Example can be found at: https://github.com/kataras/iris/tree/master/_examples/auth/auth/user.go.
|
|
|
|
User = any
|
2022-03-28 13:00:26 +02:00
|
|
|
)
|
|
|
|
|
2022-04-02 16:30:55 +02:00
|
|
|
const accessTokenContextKey = "iris.auth.context.access_token"
|
2022-03-28 13:00:26 +02:00
|
|
|
|
2022-04-02 20:14:46 +02:00
|
|
|
// GetAccessToken accepts the iris Context and returns the raw access token value.
|
|
|
|
// It's only available after Auth.VerifyHandler is executed.
|
2022-03-28 13:00:26 +02:00
|
|
|
func GetAccessToken(ctx *context.Context) string {
|
|
|
|
return ctx.Values().GetString(accessTokenContextKey)
|
|
|
|
}
|
|
|
|
|
2022-04-02 16:30:55 +02:00
|
|
|
const standardClaimsContextKey = "iris.auth.context.standard_claims"
|
2022-03-28 13:00:26 +02:00
|
|
|
|
2022-04-02 20:14:46 +02:00
|
|
|
// GetStandardClaims accepts the iris Context and returns the standard token's claims.
|
|
|
|
// It's only available after Auth.VerifyHandler is executed.
|
2022-03-28 13:00:26 +02:00
|
|
|
func GetStandardClaims(ctx *context.Context) StandardClaims {
|
|
|
|
if v := ctx.Values().Get(standardClaimsContextKey); v != nil {
|
|
|
|
if c, ok := v.(StandardClaims); ok {
|
|
|
|
return c
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return StandardClaims{}
|
|
|
|
}
|
|
|
|
|
2022-04-02 16:30:55 +02:00
|
|
|
const userContextKey = "iris.auth.context.user"
|
2022-03-28 13:00:26 +02:00
|
|
|
|
2022-04-02 20:14:46 +02:00
|
|
|
// GetUser is the package-level function of the Auth.GetUser method.
|
|
|
|
// It returns the T user value after Auth.VerifyHandler is executed.
|
2022-03-28 13:00:26 +02:00
|
|
|
func GetUser[T User](ctx *context.Context) T {
|
|
|
|
if v := ctx.Values().Get(userContextKey); v != nil {
|
|
|
|
if t, ok := v.(T); ok {
|
|
|
|
return t
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var empty T
|
|
|
|
return empty
|
|
|
|
}
|
|
|
|
|
2022-04-02 20:14:46 +02:00
|
|
|
// GetUser accepts the iris Context and returns the T custom user/claims struct value.
|
|
|
|
// It's only available after Auth.VerifyHandler is executed.
|
2022-04-02 16:30:55 +02:00
|
|
|
func (s *Auth[T]) GetUser(ctx *context.Context) T {
|
2022-03-28 13:00:26 +02:00
|
|
|
return GetUser[T](ctx)
|
|
|
|
}
|