Skip to content

Commit 0fb2c85

Browse files
committed
finished rate limiting for prem
1 parent 50978be commit 0fb2c85

File tree

4 files changed

+35
-7
lines changed

4 files changed

+35
-7
lines changed

leetstudy_backend/cmd/cache/rate_limiter.go

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"net/http"
66
"time"
77

8+
"leetstudy_backend/cmd/database"
89
"github.com/labstack/echo/v4"
910

1011
)
@@ -40,12 +41,26 @@ func RateLimitByIP(limit int, window time.Duration) echo.MiddlewareFunc {
4041
func RateLimitByUser(limit int, window time.Duration) echo.MiddlewareFunc {
4142
return func(next echo.HandlerFunc) echo.HandlerFunc {
4243
return func(c echo.Context) error {
43-
userID := c.Request().Header.Get("X-User-ID") // Or use your JWT logic
44+
userID := c.Request().Header.Get("X-User-ID") // Or get from JWT context
4445

4546
if userID == "" {
4647
return c.String(http.StatusUnauthorized, "Missing user ID")
4748
}
4849

50+
db := database.GetDB()
51+
var isPremium bool
52+
err := db.QueryRow("SELECT is_premium FROM users WHERE id = $1", userID).Scan(&isPremium)
53+
if err != nil {
54+
fmt.Println("[ERROR] Failed to fetch user:", err)
55+
return c.String(http.StatusInternalServerError, "Failed to validate user status")
56+
}
57+
58+
// Adjust rate limit if premium
59+
userLimit := float64(limit)
60+
if isPremium {
61+
userLimit = float64(limit) * 1.5
62+
}
63+
4964
key := fmt.Sprintf("rate_limit:user:%s", userID)
5065
count, err := RDB.Incr(Ctx, key).Result()
5166
if err != nil {
@@ -56,11 +71,13 @@ func RateLimitByUser(limit int, window time.Duration) echo.MiddlewareFunc {
5671
RDB.Expire(Ctx, key, window)
5772
}
5873

59-
if count > int64(limit) {
74+
if float64(count) > userLimit {
6075
ttl, _ := RDB.TTL(Ctx, key).Result()
6176
return c.JSON(http.StatusTooManyRequests, map[string]interface{}{
6277
"error": "Rate limit exceeded.",
6378
"retry_after": ttl.Seconds(),
79+
"premium": isPremium,
80+
"limit": int(userLimit),
6481
})
6582
}
6683

leetstudy_backend/main.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ func main() {
164164
e.GET("/sessions/:sessionId/messages", handlers.GetChatMessagesHandler)
165165
e.DELETE("/sessions/:sessionId", handlers.DeleteChatSessionHandler)
166166
// Feedback
167-
e.POST("/feedback", handlers.HandleFeedback)
167+
e.POST("/feedback", handlers.HandleFeedback, cache.RateLimitByIP(2, time.Hour));
168168

169169
//Section for ai hints //TODO
170170
// add rate limiting here

leetstudy_backend/readme.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,3 +79,6 @@ redis-cli ping
7979
brew services stop redis
8080
```
8181
82+
```
83+
stripe listen --forward-to http://localhost:8080/stripe-webhook
84+
```

website/src/components/feedbackButton.tsx

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ export function FeedbackButton() {
1717
toast.error("Please enter some feedback");
1818
return;
1919
}
20-
20+
2121
setLoading(true);
2222
try {
2323
const response = await fetch("http://localhost:8080/feedback", {
@@ -32,16 +32,24 @@ export function FeedbackButton() {
3232
email: user?.email || "",
3333
}),
3434
});
35-
35+
3636
if (!response.ok) {
37+
if (response.status === 429) {
38+
const { retry_after } = await response.json();
39+
toast.error(
40+
`Too many requests. Please wait ${Math.ceil(retry_after)} seconds before trying again.`
41+
);
42+
return;
43+
}
44+
3745
const error = await response.json();
3846
throw new Error(error.error || "Failed to submit feedback");
3947
}
40-
48+
4149
toast.success("Thank you for your feedback!");
4250
setFeedback("");
4351
setOpen(false);
44-
} catch (error: unknown) { // Using unknown instead of any for better type safety
52+
} catch (error: unknown) {
4553
console.error("Error submitting feedback:", error);
4654
toast.error(
4755
error instanceof Error ? error.message : "Failed to submit feedback"

0 commit comments

Comments
 (0)