Skip to content

Commit

Permalink
Try new IP checker
Browse files Browse the repository at this point in the history
  • Loading branch information
kenellorando committed Feb 24, 2023
1 parent 3d81edd commit 9e4c653
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions cadence/server/db_redis.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package main

import (
"context"
"net"
"net/http"
"time"

Expand All @@ -28,8 +29,12 @@ func redisInit() {

func rateLimit(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip := r.RemoteAddr
_, err := dbr.RateLimit.Get(ctx, ip).Result()
ip, err := checkIP(r)
if err != nil {
w.WriteHeader(http.StatusInternalServerError) // 500 Internal Server Error
return
}
_, err = dbr.RateLimit.Get(ctx, ip).Result()
if err != nil {
if err == redis.Nil {
// redis.Nil means the IP is not in the database.
Expand All @@ -47,3 +52,16 @@ func rateLimit(next http.Handler) http.Handler {
}
})
}

func checkIP(r *http.Request) (ip string, err error) {
// We look at the remote address and check the IP.
// If for some reason no remote IP is there, we error to reject.
if r.RemoteAddr != "" {
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil || ip == "" {
return "", err
}
return ip, nil
}
return "", err
}

0 comments on commit 9e4c653

Please sign in to comment.