Skip to content

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

Set access_token/refresh_token/user cookie if login successfully.

天舟532a500738f4
diff --git a/backend/api/auth.go b/backend/api/auth.go
index 43fb1ab5fc..cb85f12fae 100644
--- a/backend/api/auth.go
+++ b/backend/api/auth.go
@@ -6,5 +6,5 @@ type Login struct {
}
type AuthService interface {
- FindUserWithEmailAndPassword(email string, password string) (*Principal, error)
+ FindPrincipalByEmail(email string) (*Principal, error)
}
diff --git a/backend/api/principal.go b/backend/api/principal.go
index 7e281c9006..ecf95c13f2 100644
--- a/backend/api/principal.go
+++ b/backend/api/principal.go
@@ -2,5 +2,6 @@ package api
type Principal struct {
ID uint `jsonapi:"primary,principal"`
+ Name string `jsonapi:"attr,name"`
Email string `jsonapi:"attr,email"`
}
diff --git a/backend/go.mod b/backend/go.mod
index 1f1c5c471d..00340f63ec 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -3,6 +3,7 @@ module github.com/bytebase/bytebase
go 1.16
require (
+ github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect
github.com/golang-migrate/migrate/v4 v4.14.1 // indirect
github.com/google/jsonapi v1.0.0 // indirect
github.com/labstack/echo/v4 v4.2.2 // indirect
diff --git a/backend/server/auth.go b/backend/server/auth.go
index 4fcc9e5d94..e7eb28c67c 100644
--- a/backend/server/auth.go
+++ b/backend/server/auth.go
@@ -16,12 +16,23 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted login request")
}
- _, err := s.AuthService.FindUserWithEmailAndPassword(login.Email, login.Password)
+ user, err := s.AuthService.FindPrincipalByEmail(login.Email)
if err != nil {
if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
return echo.NewHTTPError(http.StatusUnauthorized)
}
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to process login request")
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to authenticate user")
+ }
+
+ // // Compare the stored hashed password, with the hashed version of the password that was received.
+ // if err := bcrypt.CompareHashAndPassword([]byte(storedUser.Password), []byte(u.Password)); err != nil {
+ // // If the two passwords don't match, return a 401 status.
+ // return echo.NewHTTPError(http.StatusUnauthorized, "Password is incorrect")
+ // }
+
+ // If password is correct, generate tokens and set cookies.
+ if err := GenerateTokensAndSetCookies(user, c); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate access token")
}
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
diff --git a/backend/server/jwt.go b/backend/server/jwt.go
new file mode 100644
index 0000000000..2223e92670
--- /dev/null
+++ b/backend/server/jwt.go
@@ -0,0 +1,168 @@
+package server
+
+import (
+ "fmt"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/bytebase/bytebase/api"
+ "github.com/dgrijalva/jwt-go"
+ "github.com/labstack/echo/v4"
+)
+
+const (
+ accessTokenCookieName = "access-token"
+ refreshTokenCookieName = "refresh-token"
+ // Just for the demo purpose, I declared a secret here. In the real-world application, you might need to get it from the env variables.
+ jwtSecretKey = "some-secret-key"
+ jwtRefreshSecretKey = "some-refresh-secret-key"
+)
+
+func GetJWTSecret() string {
+ return jwtSecretKey
+}
+
+func GetRefreshJWTSecret() string {
+ return jwtRefreshSecretKey
+}
+
+// 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 {
+ Name string `json:"name"`
+ jwt.StandardClaims
+}
+
+// GenerateTokensAndSetCookies generates jwt token and saves it to the http-only cookie.
+func GenerateTokensAndSetCookies(user *api.Principal, c echo.Context) error {
+ accessToken, exp, err := generateAccessToken(user)
+ if err != nil {
+ return err
+ }
+ setTokenCookie(accessTokenCookieName, accessToken, exp, c)
+ setUserCookie(user, exp, c)
+
+ // We generate here a new refresh token and saving it to the cookie.
+ refreshToken, exp, err := generateRefreshToken(user)
+ if err != nil {
+ return err
+ }
+ setTokenCookie(refreshTokenCookieName, refreshToken, exp, c)
+
+ return nil
+}
+
+func generateAccessToken(user *api.Principal) (string, time.Time, error) {
+ // Declare the expiration time of the token (1h).
+ expirationTime := time.Now().Add(1 * time.Hour)
+
+ return generateToken(user, expirationTime, []byte(GetJWTSecret()))
+}
+
+func generateRefreshToken(user *api.Principal) (string, time.Time, error) {
+ // Declare the expiration time of the token - 24 hours.
+ expirationTime := time.Now().Add(24 * time.Hour)
+
+ return generateToken(user, expirationTime, []byte(GetRefreshJWTSecret()))
+}
+
+// Pay attention to this function. It holds the main JWT token generation logic.
+func generateToken(user *api.Principal, expirationTime time.Time, secret []byte) (string, time.Time, error) {
+ // Create the JWT claims, which includes the username and expiry time.
+ claims := &Claims{
+ Name: user.Name,
+ StandardClaims: jwt.StandardClaims{
+ // In JWT, the expiry time is expressed as unix milliseconds.
+ ExpiresAt: expirationTime.Unix(),
+ },
+ }
+
+ // Declare the token with the HS256 algorithm used for signing, and the claims.
+ token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
+
+ // Create the JWT string.
+ tokenString, err := token.SignedString(secret)
+ if err != nil {
+ return "", time.Now(), err
+ }
+
+ return tokenString, expirationTime, nil
+}
+
+// Here we are creating a new cookie, which will store the valid JWT token.
+func setTokenCookie(name, token string, expiration time.Time, c echo.Context) {
+ cookie := new(http.Cookie)
+ cookie.Name = name
+ cookie.Value = token
+ cookie.Expires = expiration
+ cookie.Path = "/"
+ // Http-only helps mitigate the risk of client side script accessing the protected cookie.
+ cookie.HttpOnly = true
+
+ c.SetCookie(cookie)
+}
+
+// Purpose of this cookie is to store the user's name.
+func setUserCookie(user *api.Principal, expiration time.Time, c echo.Context) {
+ cookie := new(http.Cookie)
+ cookie.Name = "user"
+ cookie.Value = user.Name
+ cookie.Expires = expiration
+ cookie.Path = "/"
+ c.SetCookie(cookie)
+}
+
+func TokenRefresherMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ // Skips auth end point
+ if strings.HasPrefix(c.Path(), "/api/auth") {
+ return next(c)
+ }
+
+ // If the user is not authenticated (no user token data in the context), don't do anything.
+ if c.Get("user") == nil {
+ return next(c)
+ }
+ // Gets user token from the context.
+ u := c.Get("user").(*jwt.Token)
+
+ claims := u.Claims.(*Claims)
+
+ // 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.
+ if time.Until(time.Unix(claims.ExpiresAt, 0)) < 15*time.Minute {
+ // Gets the refresh token from the cookie.
+ fmt.Println("Token about to expire, generate new token...")
+ rc, err := c.Cookie(refreshTokenCookieName)
+ if err == nil && rc != nil {
+ // Parses token and checks if it valid.
+ tkn, err := jwt.ParseWithClaims(rc.Value, claims, func(token *jwt.Token) (interface{}, error) {
+ return []byte(GetRefreshJWTSecret()), nil
+ })
+ if err != nil {
+ if err == jwt.ErrSignatureInvalid {
+ c.Response().Writer.WriteHeader(http.StatusUnauthorized)
+ }
+ }
+
+ if tkn != nil && tkn.Valid {
+ // If everything is good, update tokens.
+ _ = GenerateTokensAndSetCookies(&api.Principal{
+ Name: claims.Name,
+ }, c)
+ }
+ }
+ }
+
+ return next(c)
+ }
+}
+
+// JWTErrorChecker will be executed when user try to access a protected path.
+func JWTErrorChecker(err error, c echo.Context) error {
+ // Redirects to the signIn form.
+ fmt.Printf("Unauthorized to access protected route %s, err: %v\n", c.Path(), err)
+ return err
+}
diff --git a/backend/server/server.go b/backend/server/server.go
index 1d57b8fa6b..45a28b21bb 100644
--- a/backend/server/server.go
+++ b/backend/server/server.go
@@ -63,6 +63,20 @@ func NewServer() *Server {
g := e.Group("/api")
+ g.Use(middleware.JWTWithConfig(middleware.JWTConfig{
+ Skipper: func(c echo.Context) bool {
+ return strings.HasPrefix(c.Path(), "/api/auth")
+ },
+ Claims: &Claims{},
+ SigningMethod: middleware.AlgorithmHS256,
+ SigningKey: []byte(GetJWTSecret()),
+ ContextKey: "user",
+ TokenLookup: "cookie:access-token", // "<source>:<name>"
+ ErrorHandlerWithContext: JWTErrorChecker,
+ }))
+
+ g.Use(TokenRefresherMiddleware)
+
s.registerDebugRoutes(g)
s.registerAuthRoutes(g)
diff --git a/backend/sqlite/auth.go b/backend/sqlite/auth.go
index 6f1694fe32..918ba300d1 100644
--- a/backend/sqlite/auth.go
+++ b/backend/sqlite/auth.go
@@ -16,6 +16,6 @@ func NewAuthService(db *DB) *AuthService {
return &AuthService{db: db}
}
-func (s *AuthService) FindUserWithEmailAndPassword(email string, password string) (*api.Principal, error) {
+func (s *AuthService) FindPrincipalByEmail(email string) (*api.Principal, error) {
return &api.Principal{ID: 1, Email: "[email protected]"}, nil
}