feat: add login failed ban ip list

This commit is contained in:
Jacky 2024-07-21 15:24:58 +08:00
parent ccb04c07d8
commit cff843b82b
No known key found for this signature in database
GPG key ID: 215C21B10DF38B4D
43 changed files with 2264 additions and 959 deletions

View file

@ -4,12 +4,17 @@ import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/logger"
"github.com/0xJacky/Nginx-UI/internal/user"
"github.com/0xJacky/Nginx-UI/query"
"github.com/0xJacky/Nginx-UI/settings"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
"net/http"
"sync"
"time"
)
var mutex = &sync.Mutex{}
type LoginUser struct {
Name string `json:"name" binding:"required,max=255"`
Password string `json:"password" binding:"required,max=255"`
@ -29,6 +34,25 @@ type LoginResponse struct {
}
func Login(c *gin.Context) {
// make sure that only one request is processed at a time
mutex.Lock()
defer mutex.Unlock()
// check if the ip is banned
clientIP := c.ClientIP()
b := query.BanIP
banIP, _ := b.Where(b.IP.Eq(clientIP),
b.ExpiredAt.Gte(time.Now().Unix()),
b.Attempts.Gte(settings.AuthSettings.MaxAttempts),
).Count()
if banIP > 0 {
c.JSON(http.StatusTooManyRequests, LoginResponse{
Message: "Max attempts",
Code: ErrMaxAttempts,
})
return
}
var json LoginUser
ok := api.BindAndValid(c, &json)
if !ok {
@ -37,7 +61,7 @@ func Login(c *gin.Context) {
u, err := user.Login(json.Name, json.Password)
if err != nil {
time.Sleep(5 * time.Second)
// time.Sleep(5 * time.Second)
switch {
case errors.Is(err, user.ErrPasswordIncorrect):
c.JSON(http.StatusForbidden, LoginResponse{
@ -52,9 +76,13 @@ func Login(c *gin.Context) {
default:
api.ErrHandler(c, err)
}
user.BanIP(clientIP)
return
}
// login success, clear banned record
_, _ = b.Where(b.IP.Eq(clientIP)).Delete()
logger.Info("[User Login]", u.Name)
token, err := user.GenerateJWT(u.Name)
if err != nil {