init
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// Auth user auth.
|
||||
type Auth struct {
|
||||
UserID int64 `json:"id"`
|
||||
Access string `json:"access"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
// HasAdminAccess checks if the user has admin access.
|
||||
func (a *Auth) HasAdminAccess() bool {
|
||||
return a.Access == "admin"
|
||||
}
|
||||
|
||||
type authKey struct{}
|
||||
|
||||
// NewContext returns a new Context that carries value.
|
||||
func NewContext(ctx context.Context, auth *Auth) context.Context {
|
||||
return context.WithValue(ctx, authKey{}, auth)
|
||||
}
|
||||
|
||||
// FromContext returns the Auth value stored in ctx, if any.
|
||||
func FromContext(ctx context.Context) (auth *Auth, ok bool) {
|
||||
auth, ok = ctx.Value(authKey{}).(*Auth)
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
// authSecretFromEnv retrieves the authentication secret from the environment variable.
|
||||
func authSecretFromEnv(key string) string {
|
||||
if secret := os.Getenv(key); secret != "" {
|
||||
return secret
|
||||
}
|
||||
return time.Now().Format("20060102150405")
|
||||
}
|
||||
|
||||
// cookieNameFromEnv retrieves the cookie name from the environment variable.
|
||||
func cookieNameFromEnv(key string) string {
|
||||
if name := os.Getenv(key); name != "" {
|
||||
return name
|
||||
}
|
||||
return "access_token"
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-kratos/kratos/v2/errors"
|
||||
"github.com/go-kratos/kratos/v2/transport"
|
||||
httpm "github.com/go-kratos/kratos/v2/transport/http"
|
||||
)
|
||||
|
||||
var (
|
||||
// noAuthPaths defines the paths that do not require authentication.
|
||||
noAuthPaths = map[string]struct{}{
|
||||
"/v1/admins/login": {},
|
||||
}
|
||||
// authSecretKey is the secret key used for signing JWT tokens.
|
||||
authSecretKey = authSecretFromEnv("KRATOS_AUTH_SECRET")
|
||||
// cookieName is the name of the cookie that stores the authorization token.
|
||||
cookieName = cookieNameFromEnv("KRATOS_AUTH_COOKIE")
|
||||
// ErrUnauthorized indicates that the token is invalid.
|
||||
ErrUnauthorized = errors.Unauthorized("UNAUTHORIZED", "Token is invalid")
|
||||
// ErrForbidden indicates that access is denied.
|
||||
ErrForbidden = errors.Forbidden("FORBIDDEN", "Access denied")
|
||||
)
|
||||
|
||||
// Middleware is an authentication middleware for HTTP servers.
|
||||
func Middleware() httpm.FilterFunc {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := noAuthPaths[r.URL.Path]; ok {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
cookie, err := r.Cookie(cookieName)
|
||||
if err != nil {
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
auth, err := ParseToken(cookie.Value, authSecretKey)
|
||||
if err != nil {
|
||||
ec := errors.FromError(err)
|
||||
http.Error(w, ec.Message, int(ec.Code))
|
||||
return
|
||||
}
|
||||
ctx := NewContext(r.Context(), auth)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// SetCookie sets the login cookie in the HTTP response.
|
||||
func SetCookie(ctx context.Context, userID int64, access string, expiresAt time.Time) error {
|
||||
tr, ok := transport.FromServerContext(ctx)
|
||||
if !ok {
|
||||
return fmt.Errorf("failed to get transport from context")
|
||||
}
|
||||
token, err := GenerateToken(userID, access, authSecretKey, expiresAt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cookie := &http.Cookie{
|
||||
Name: cookieName,
|
||||
Value: token,
|
||||
Path: "/",
|
||||
Expires: expiresAt,
|
||||
}
|
||||
tr.ReplyHeader().Add("Set-Cookie", cookie.String())
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteCookie clears the login cookie in the HTTP response.
|
||||
func DeleteCookie(ctx context.Context) error {
|
||||
tr, ok := transport.FromServerContext(ctx)
|
||||
if !ok {
|
||||
return fmt.Errorf("failed to get transport from context")
|
||||
}
|
||||
expires := time.Now().AddDate(0, 0, -1)
|
||||
cookie := &http.Cookie{
|
||||
Name: cookieName,
|
||||
Value: "",
|
||||
Path: "/",
|
||||
Expires: expires,
|
||||
}
|
||||
tr.ReplyHeader().Add("Set-Cookie", cookie.String())
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// GenerateToken generates a JWT token for the given username.
|
||||
func GenerateToken(userID int64, access, secret string, expiresAt time.Time) (string, error) {
|
||||
now := time.Now()
|
||||
claims := Auth{
|
||||
UserID: userID,
|
||||
Access: access,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ID: uuid.NewString(),
|
||||
Issuer: "kratos",
|
||||
Subject: "user",
|
||||
Audience: []string{"admin"},
|
||||
IssuedAt: jwt.NewNumericDate(now),
|
||||
NotBefore: jwt.NewNumericDate(now),
|
||||
ExpiresAt: jwt.NewNumericDate(expiresAt),
|
||||
},
|
||||
}
|
||||
return jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(secret))
|
||||
}
|
||||
|
||||
// ParseToken parses the JWT token string and returns the Auth claims.
|
||||
func ParseToken(tokenStr, secret string) (*Auth, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenStr, &Auth{}, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(secret), nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !token.Valid {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
auth, ok := token.Claims.(*Auth)
|
||||
if !ok {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
return auth, nil
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package validate
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/go-kratos/kratos/v2/errors"
|
||||
"github.com/go-kratos/kratos/v2/middleware"
|
||||
"go.einride.tech/aip/fieldbehavior"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// Middleware is a middleware that validates the request message with [FieldBehavior](https://google.aip.dev/203)
|
||||
func Middleware() middleware.Middleware {
|
||||
return func(handler middleware.Handler) middleware.Handler {
|
||||
return func(ctx context.Context, req any) (reply any, err error) {
|
||||
if msg, ok := req.(proto.Message); ok {
|
||||
if err := fieldbehavior.ValidateRequiredFields(msg); err != nil {
|
||||
return nil, errors.BadRequest("VALIDATOR", err.Error()).WithCause(err)
|
||||
}
|
||||
}
|
||||
return handler(ctx, req)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user