socialpredict icon indicating copy to clipboard operation
socialpredict copied to clipboard

Add query limiting to MiddleWare

Open avalonprod opened this issue 1 year ago • 5 comments

This code will allow you to block users who are attempting a DDoS attack. You can specify the maximum number of requests and blocking time.

import (
	"sync"
	"time"

	"golang.org/x/time/rate"
)

type visitor struct {
	limiter  *rate.Limiter
	lastSeen time.Time
}

type rateLimiter struct {
	sync.RWMutex

	visitors map[string]*visitor
	limit    rate.Limit
	burst    int
	ttl      time.Duration
}

func NewRateLimiter(rps int, burst int, ttl time.Duration) *rateLimiter {
	return &rateLimiter{
		visitors: make(map[string]*visitor),
		limit:    rate.Limit(rps),
		burst:    burst,
		ttl:      ttl,
	}
}

func (l *rateLimiter) GetVisitor(ip string) *rate.Limiter {
	l.RLock()
	v, exists := l.visitors[ip]
	l.RUnlock()

	if !exists {
		limiter := rate.NewLimiter(l.limit, l.burst)
		l.Lock()
		l.visitors[ip] = &visitor{limiter, time.Now()}
		l.Unlock()

		return limiter
	}

	v.lastSeen = time.Now()

	return v.limiter
}

func (l *rateLimiter) CleanupVisitors() {
	for {
		time.Sleep(time.Minute)

		l.Lock()

		for ip, v := range l.visitors {
			if time.Since(v.lastSeen) > l.ttl {
				delete(l.visitors, ip)
			}
		}
		l.Unlock()
	}
}

avalonprod avatar Feb 05 '24 20:02 avalonprod

That is so awesome, thank you!!! I did not think of this yet...everything has been in development mode. That being said, it is definitely on the docket now, thank you, I will implement it within the next couple of sprints.

pwdel avatar Feb 05 '24 21:02 pwdel

By the way, how did you find this repo?

pwdel avatar Feb 05 '24 21:02 pwdel

By the way, how did you find this repo?

I found a job posted on Upwork and there was a link to this repository.

avalonprod avatar Feb 05 '24 21:02 avalonprod

Ah, OK, thank you so much. Are you applying for the job or just helping? I want to make it very clear that there is no guarantee to get the job by working on the software for free. I want to discourage you from working on this unless you happen to really be interested in it, to be respectful of your time. On the other hand of course the contribution you already made is very helpful and I would encourage you to include that as a part of your open source contribution portfolio.

pwdel avatar Feb 06 '24 12:02 pwdel

I just had a little look at your code and decided to contribute. Yes it would be nice if I could add to my portfolio. Don't worry about.

avalonprod avatar Feb 06 '24 19:02 avalonprod