mirror of
https://github.com/0xJacky/nginx-ui.git
synced 2025-05-11 18:35:51 +02:00
feat: add login failed ban ip list
This commit is contained in:
parent
ccb04c07d8
commit
cff843b82b
43 changed files with 2264 additions and 959 deletions
|
@ -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 {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue