feat: add ip whitelist

This commit is contained in:
Jacky 2024-07-20 10:37:19 +08:00
parent 7a9aa3a33b
commit 3b937ee0f4
No known key found for this signature in database
GPG key ID: 215C21B10DF38B4D
17 changed files with 1026 additions and 927 deletions

View file

@ -2,12 +2,12 @@ package user
import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/model"
"github.com/0xJacky/Nginx-UI/internal/logger"
"github.com/0xJacky/Nginx-UI/internal/user"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
"net/http"
"time"
"github.com/gin-gonic/gin"
"golang.org/x/crypto/bcrypt"
)
type LoginUser struct {
@ -15,32 +15,51 @@ type LoginUser struct {
Password string `json:"password" binding:"required,max=255"`
}
const (
ErrPasswordIncorrect = 4031
ErrMaxAttempts = 4291
ErrUserBanned = 4033
)
type LoginResponse struct {
Message string `json:"message"`
Token string `json:"token"`
Error string `json:"error,omitempty"`
Code int `json:"code"`
Token string `json:"token,omitempty"`
}
func Login(c *gin.Context) {
var user LoginUser
ok := api.BindAndValid(c, &user)
var json LoginUser
ok := api.BindAndValid(c, &json)
if !ok {
return
}
u, _ := model.GetUser(user.Name)
if err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(user.Password)); err != nil {
u, err := user.Login(json.Name, json.Password)
if err != nil {
time.Sleep(5 * time.Second)
c.JSON(http.StatusForbidden, gin.H{
"message": "The username or password is incorrect",
})
switch {
case errors.Is(err, user.ErrPasswordIncorrect):
c.JSON(http.StatusForbidden, LoginResponse{
Message: "Password incorrect",
Code: ErrPasswordIncorrect,
})
case errors.Is(err, user.ErrUserBanned):
c.JSON(http.StatusForbidden, LoginResponse{
Message: "The user is banned",
Code: ErrUserBanned,
})
default:
api.ErrHandler(c, err)
}
return
}
token, err := model.GenerateJWT(u.Name)
logger.Info("[User Login]", u.Name)
token, err := user.GenerateJWT(u.Name)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
c.JSON(http.StatusInternalServerError, LoginResponse{
Message: err.Error(),
})
return
}
@ -54,7 +73,7 @@ func Login(c *gin.Context) {
func Logout(c *gin.Context) {
token := c.GetHeader("Authorization")
if token != "" {
err := model.DeleteToken(token)
err := user.DeleteToken(token)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),