Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

Add principal id to the jwt token and use this info as the updater_id when updating the principal.

天舟c6a4e8e932dd
diff --git a/backend/api/auth.go b/backend/api/auth.go
index 70198a527c..227858a458 100644
--- a/backend/api/auth.go
+++ b/backend/api/auth.go
@@ -1,6 +1,7 @@
package api
type Login struct {
+ // Domain specific fields
Email string `jsonapi:"attr,email"`
Password string `jsonapi:"attr,password"`
}
diff --git a/backend/api/principal.go b/backend/api/principal.go
index 4a3aed75d6..4e1d4438c7 100644
--- a/backend/api/principal.go
+++ b/backend/api/principal.go
@@ -18,20 +18,29 @@ const (
)
type Principal struct {
- ID int `jsonapi:"primary,principal"`
- CreatorId int `jsonapi:"attr,creatorId"`
- CreatorTs int64 `jsonapi:"attr,creatorTs"`
- UpdaterId int `jsonapi:"attr,updaterId"`
- UpdatedTs int64 `jsonapi:"attr,updatedTs"`
- Status PrincipalStatus `jsonapi:"attr,status"`
- Type PrincipalType `jsonapi:"attr,type"`
- Name string `jsonapi:"attr,name"`
- Email string `jsonapi:"attr,email"`
+ ID int `jsonapi:"primary,principal"`
+
+ // Standard fields
+ CreatorId int `jsonapi:"attr,creatorId"`
+ CreatorTs int64 `jsonapi:"attr,creatorTs"`
+ UpdaterId int `jsonapi:"attr,updaterId"`
+ UpdatedTs int64 `jsonapi:"attr,updatedTs"`
+
+ // Domain specific fields
+ Status PrincipalStatus `jsonapi:"attr,status"`
+ Type PrincipalType `jsonapi:"attr,type"`
+ Name string `jsonapi:"attr,name"`
+ Email string `jsonapi:"attr,email"`
// Not needed to return to the client
PasswordHash string
}
type PrincipalPatch struct {
+ // Standard fields
+ // Value is assigned from the jwt subject field passed by the client.
+ UpdaterId int
+
+ // Domain specific fields
Name *string `jsonapi:"attr,name"`
}
diff --git a/backend/server/jwt.go b/backend/server/jwt.go
index a17067fad3..c9ed957890 100644
--- a/backend/server/jwt.go
+++ b/backend/server/jwt.go
@@ -3,6 +3,7 @@ package server
import (
"fmt"
"net/http"
+ "strconv"
"strings"
"time"
@@ -25,6 +26,12 @@ const (
// 1. The access token is about to expire in <<refreshThresholdDuration>>
// 2. The access token has already expired, we refresh the token so that the ongoing request can pass through
cookieExpDuration = refreshTokenDuration
+
+ // The key name used to store jwt token in the context
+ tokenContextKey = "token"
+ // The key name used to store principal id in the context
+ // principal id is extracted from the jwt token subject field.
+ principalIdContextKey = "principal-id"
)
func GetJWTSecret() string {
@@ -35,6 +42,14 @@ func GetRefreshJWTSecret() string {
return jwtRefreshSecretKey
}
+func GetTokenContextKey() string {
+ return tokenContextKey
+}
+
+func GetPrincipalIdContextKey() string {
+ return principalIdContextKey
+}
+
// Create a struct that will be encoded to a JWT.
// We add jwt.StandardClaims as an embedded type, to provide fields like expiry time.
type Claims struct {
@@ -81,6 +96,7 @@ func generateToken(user *api.Principal, expirationTime time.Time, secret []byte)
StandardClaims: jwt.StandardClaims{
// In JWT, the expiry time is expressed as unix milliseconds.
ExpiresAt: expirationTime.Unix(),
+ Subject: strconv.Itoa(user.ID),
},
}
@@ -119,7 +135,10 @@ func setUserCookie(user *api.Principal, expiration time.Time, c echo.Context) {
c.SetCookie(cookie)
}
-func TokenRefresherMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
+// TokenMiddleware does following things
+// 1. Extract principal id from the token and set it in the context to be used by the handler.
+// 2. Refresh the access_token and refresh_token if access_token is about to expire.
+func TokenMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
// Skips auth end point
if strings.HasPrefix(c.Path(), "/api/auth") {
@@ -127,14 +146,20 @@ func TokenRefresherMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
}
// If the user is not authenticated (no user token data in the context), don't do anything.
- if c.Get("user") == nil {
+ if c.Get(GetTokenContextKey()) == nil {
return next(c)
}
// Gets user token from the context.
- u := c.Get("user").(*jwt.Token)
+ u := c.Get(GetTokenContextKey()).(*jwt.Token)
claims := u.Claims.(*Claims)
+ principalId, err := strconv.Atoi(claims.Subject)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusUnauthorized, "Malformatted ID in the token.")
+ }
+ c.Set(GetPrincipalIdContextKey(), principalId)
+
// We ensure that a new token is not issued until enough time has elapsed.
// In this case, a new token will only be issued if the old token is within
// 15 mins of expiry.
diff --git a/backend/server/principal.go b/backend/server/principal.go
index 31b47f1786..c3e4310296 100644
--- a/backend/server/principal.go
+++ b/backend/server/principal.go
@@ -58,7 +58,7 @@ func (s *Server) registerPrincipalRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s.", c.Param("id")))
}
- principalPatch := &api.PrincipalPatch{}
+ principalPatch := &api.PrincipalPatch{UpdaterId: c.Get(GetPrincipalIdContextKey()).(int)}
if err := jsonapi.UnmarshalPayload(c.Request().Body, principalPatch); err != nil {
log.Println(err)
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted patch principal request.")
diff --git a/backend/server/server.go b/backend/server/server.go
index 340693da7a..676a2b1e9e 100644
--- a/backend/server/server.go
+++ b/backend/server/server.go
@@ -65,17 +65,17 @@ func NewServer() *Server {
g.Use(middleware.JWTWithConfig(middleware.JWTConfig{
Skipper: func(c echo.Context) bool {
- return strings.HasPrefix(c.Path(), "/api/auth") || strings.HasPrefix(c.Path(), "/api/principal")
+ return strings.HasPrefix(c.Path(), "/api/auth") || c.Path() == "/api/principal"
},
Claims: &Claims{},
SigningMethod: middleware.AlgorithmHS256,
SigningKey: []byte(GetJWTSecret()),
- ContextKey: "user",
+ ContextKey: GetTokenContextKey(),
TokenLookup: "cookie:access-token", // "<source>:<name>"
ErrorHandlerWithContext: JWTErrorChecker,
}))
- g.Use(TokenRefresherMiddleware)
+ g.Use(TokenMiddleware)
s.registerDebugRoutes(g)
diff --git a/backend/sqlite/principal.go b/backend/sqlite/principal.go
index 3851091401..e0de64b34a 100644
--- a/backend/sqlite/principal.go
+++ b/backend/sqlite/principal.go
@@ -178,11 +178,12 @@ func patchPrincipal(ctx context.Context, tx *Tx, id int, patch *api.PrincipalPat
// Execute update query with RETURNING.
rows, err := tx.QueryContext(ctx, `
UPDATE principal
- SET name = ?
+ SET name = ?, updater_id = ?
WHERE id = ?
RETURNING *
`,
principal.Name,
+ principal.UpdaterId,
id,
)
if err != nil {