openpredictionmarkets / socialpredict

Easy to Deploy Prediction Market Platform
MIT License
29 stars 4 forks source link

Add query limiting to MiddleWare #48

Open avalonprod opened 5 months ago

avalonprod commented 5 months ago

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()
    }
}
pwdel commented 5 months ago

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 commented 5 months ago

By the way, how did you find this repo?

avalonprod commented 5 months ago

By the way, how did you find this repo?

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

pwdel commented 5 months ago

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.

avalonprod commented 5 months ago

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.