Fix /bookshelf route - add direct route with JWT authentication
- Added direct /bookshelf route that works with both Authorization header and cookie token - Imported missing strings package - Users can now access /bookshelf directly instead of /api/bookshelf
This commit is contained in:
@@ -10,6 +10,7 @@ import (
|
||||
"context"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
@@ -190,6 +191,44 @@ func main() {
|
||||
return c.HTML(http.StatusOK, buf.String())
|
||||
})
|
||||
|
||||
// Direct /bookshelf route (protected)
|
||||
e.GET("/bookshelf", func(c echo.Context) error {
|
||||
tokenString := c.Request().Header.Get("Authorization")
|
||||
if tokenString != "" && strings.HasPrefix(tokenString, "Bearer ") {
|
||||
tokenString = tokenString[7:]
|
||||
} else {
|
||||
// Check for token in cookie
|
||||
cookie, err := c.Cookie("token")
|
||||
if err != nil {
|
||||
return c.Redirect(http.StatusFound, "/login")
|
||||
}
|
||||
tokenString = cookie.Value
|
||||
}
|
||||
|
||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(cfg.JWTSecret), nil
|
||||
})
|
||||
|
||||
if err != nil || !token.Valid {
|
||||
return c.Redirect(http.StatusFound, "/login")
|
||||
}
|
||||
|
||||
claims := token.Claims.(jwt.MapClaims)
|
||||
user := templates.User{
|
||||
ID: claims["user_id"].(string),
|
||||
Email: claims["user_email"].(string),
|
||||
Username: claims["user_username"].(string),
|
||||
Role: claims["user_role"].(string),
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
err = templates.BookShelf(user).Render(c.Request().Context(), &buf)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.HTML(http.StatusOK, buf.String())
|
||||
})
|
||||
|
||||
// Dashboard route (protected) - keep for backward compatibility
|
||||
protected.GET("/dashboard", func(c echo.Context) error {
|
||||
userID := c.Get("user_id").(string)
|
||||
|
||||
Reference in New Issue
Block a user