2023-07-01 00:03:28 +08:00
|
|
|
package v1
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/golang-jwt/jwt/v4"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
|
|
"github.com/pkg/errors"
|
2023-09-17 22:55:13 +08:00
|
|
|
|
2023-07-31 20:55:40 +08:00
|
|
|
"github.com/usememos/memos/api/auth"
|
2023-07-06 22:53:38 +08:00
|
|
|
"github.com/usememos/memos/common/util"
|
2023-09-15 08:18:30 +08:00
|
|
|
storepb "github.com/usememos/memos/proto/gen/store"
|
2023-07-01 00:03:28 +08:00
|
|
|
"github.com/usememos/memos/store"
|
|
|
|
)
|
|
|
|
|
2023-09-14 20:16:17 +08:00
|
|
|
const (
|
|
|
|
// The key name used to store user id in the context
|
|
|
|
// user id is extracted from the jwt token subject field.
|
|
|
|
userIDContextKey = "user-id"
|
|
|
|
)
|
2023-07-31 20:55:40 +08:00
|
|
|
|
2023-07-01 00:03:28 +08:00
|
|
|
func extractTokenFromHeader(c echo.Context) (string, error) {
|
|
|
|
authHeader := c.Request().Header.Get("Authorization")
|
|
|
|
if authHeader == "" {
|
|
|
|
return "", nil
|
|
|
|
}
|
|
|
|
|
|
|
|
authHeaderParts := strings.Fields(authHeader)
|
|
|
|
if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != "bearer" {
|
|
|
|
return "", errors.New("Authorization header format must be Bearer {token}")
|
|
|
|
}
|
|
|
|
|
|
|
|
return authHeaderParts[1], nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func findAccessToken(c echo.Context) string {
|
2023-09-25 20:14:01 +08:00
|
|
|
// Check the HTTP request header first.
|
|
|
|
accessToken, _ := extractTokenFromHeader(c)
|
2023-07-01 00:03:28 +08:00
|
|
|
if accessToken == "" {
|
2023-09-25 20:14:01 +08:00
|
|
|
// Check the cookie.
|
|
|
|
cookie, _ := c.Cookie(auth.AccessTokenCookieName)
|
|
|
|
if cookie != nil {
|
|
|
|
accessToken = cookie.Value
|
|
|
|
}
|
2023-07-01 00:03:28 +08:00
|
|
|
}
|
|
|
|
return accessToken
|
|
|
|
}
|
|
|
|
|
|
|
|
// JWTMiddleware validates the access token.
|
|
|
|
func JWTMiddleware(server *APIV1Service, next echo.HandlerFunc, secret string) echo.HandlerFunc {
|
|
|
|
return func(c echo.Context) error {
|
2023-07-31 20:55:40 +08:00
|
|
|
ctx := c.Request().Context()
|
|
|
|
path := c.Request().URL.Path
|
2023-07-01 00:03:28 +08:00
|
|
|
method := c.Request().Method
|
|
|
|
|
|
|
|
if server.defaultAuthSkipper(c) {
|
|
|
|
return next(c)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Skip validation for server status endpoints.
|
2023-07-22 12:58:17 +08:00
|
|
|
if util.HasPrefixes(path, "/api/v1/ping", "/api/v1/idp", "/api/v1/status", "/api/v1/user") && path != "/api/v1/user/me" && method == http.MethodGet {
|
2023-07-01 00:03:28 +08:00
|
|
|
return next(c)
|
|
|
|
}
|
|
|
|
|
2023-09-15 08:18:30 +08:00
|
|
|
accessToken := findAccessToken(c)
|
|
|
|
if accessToken == "" {
|
2023-07-01 00:03:28 +08:00
|
|
|
// Allow the user to access the public endpoints.
|
2023-07-06 22:53:38 +08:00
|
|
|
if util.HasPrefixes(path, "/o") {
|
2023-07-01 00:03:28 +08:00
|
|
|
return next(c)
|
|
|
|
}
|
|
|
|
// When the request is not authenticated, we allow the user to access the memo endpoints for those public memos.
|
2023-07-06 22:53:38 +08:00
|
|
|
if util.HasPrefixes(path, "/api/v1/memo") && method == http.MethodGet {
|
2023-07-01 00:03:28 +08:00
|
|
|
return next(c)
|
|
|
|
}
|
|
|
|
return echo.NewHTTPError(http.StatusUnauthorized, "Missing access token")
|
|
|
|
}
|
|
|
|
|
2023-09-20 19:24:26 +08:00
|
|
|
userID, err := getUserIDFromAccessToken(accessToken, secret)
|
2023-07-01 00:03:28 +08:00
|
|
|
if err != nil {
|
2023-09-20 19:24:26 +08:00
|
|
|
removeAccessTokenAndCookies(c)
|
|
|
|
return echo.NewHTTPError(http.StatusUnauthorized, "Invalid or expired access token")
|
2023-07-01 00:03:28 +08:00
|
|
|
}
|
|
|
|
|
2023-09-15 08:18:30 +08:00
|
|
|
accessTokens, err := server.Store.GetUserAccessTokens(ctx, userID)
|
|
|
|
if err != nil {
|
|
|
|
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to get user access tokens.").WithInternal(err)
|
|
|
|
}
|
|
|
|
if !validateAccessToken(accessToken, accessTokens) {
|
2023-09-20 19:24:26 +08:00
|
|
|
removeAccessTokenAndCookies(c)
|
2023-09-15 08:18:30 +08:00
|
|
|
return echo.NewHTTPError(http.StatusUnauthorized, "Invalid access token.")
|
|
|
|
}
|
|
|
|
|
2023-07-01 00:03:28 +08:00
|
|
|
// Even if there is no error, we still need to make sure the user still exists.
|
2023-07-02 14:27:23 +08:00
|
|
|
user, err := server.Store.GetUser(ctx, &store.FindUser{
|
2023-07-01 00:03:28 +08:00
|
|
|
ID: &userID,
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Server error to find user ID: %d", userID)).SetInternal(err)
|
|
|
|
}
|
|
|
|
if user == nil {
|
|
|
|
return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("Failed to find user ID: %d", userID))
|
|
|
|
}
|
|
|
|
|
|
|
|
// Stores userID into context.
|
2023-09-14 20:16:17 +08:00
|
|
|
c.Set(userIDContextKey, userID)
|
2023-07-01 00:03:28 +08:00
|
|
|
return next(c)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-20 19:24:26 +08:00
|
|
|
func getUserIDFromAccessToken(accessToken, secret string) (int32, error) {
|
|
|
|
claims := &auth.ClaimsMessage{}
|
|
|
|
_, err := jwt.ParseWithClaims(accessToken, claims, func(t *jwt.Token) (any, error) {
|
|
|
|
if t.Method.Alg() != jwt.SigningMethodHS256.Name {
|
|
|
|
return nil, errors.Errorf("unexpected access token signing method=%v, expect %v", t.Header["alg"], jwt.SigningMethodHS256)
|
|
|
|
}
|
|
|
|
if kid, ok := t.Header["kid"].(string); ok {
|
|
|
|
if kid == "v1" {
|
|
|
|
return []byte(secret), nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil, errors.Errorf("unexpected access token kid=%v", t.Header["kid"])
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return 0, errors.Wrap(err, "Invalid or expired access token")
|
|
|
|
}
|
|
|
|
// We either have a valid access token or we will attempt to generate new access token.
|
|
|
|
userID, err := util.ConvertStringToInt32(claims.Subject)
|
|
|
|
if err != nil {
|
|
|
|
return 0, errors.Wrap(err, "Malformed ID in the token")
|
|
|
|
}
|
|
|
|
return userID, nil
|
|
|
|
}
|
|
|
|
|
2023-09-15 08:18:30 +08:00
|
|
|
func (*APIV1Service) defaultAuthSkipper(c echo.Context) bool {
|
2023-07-01 00:03:28 +08:00
|
|
|
path := c.Path()
|
2023-09-15 08:18:30 +08:00
|
|
|
return util.HasPrefixes(path, "/api/v1/auth")
|
|
|
|
}
|
2023-07-01 00:03:28 +08:00
|
|
|
|
2023-09-15 08:18:30 +08:00
|
|
|
func validateAccessToken(accessTokenString string, userAccessTokens []*storepb.AccessTokensUserSetting_AccessToken) bool {
|
|
|
|
for _, userAccessToken := range userAccessTokens {
|
|
|
|
if accessTokenString == userAccessToken.AccessToken {
|
|
|
|
return true
|
|
|
|
}
|
2023-07-01 00:03:28 +08:00
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|