login.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package user
  2. import (
  3. "errors"
  4. "github.com/0xJacky/Nginx-UI/model"
  5. "github.com/0xJacky/Nginx-UI/query"
  6. "github.com/0xJacky/Nginx-UI/settings"
  7. "golang.org/x/crypto/bcrypt"
  8. "time"
  9. )
  10. var (
  11. ErrPasswordIncorrect = errors.New("password incorrect")
  12. ErrUserBanned = errors.New("user banned")
  13. )
  14. func Login(name string, password string) (user *model.Auth, err error) {
  15. u := query.Auth
  16. user, err = u.Where(u.Name.Eq(name)).First()
  17. if err != nil {
  18. return nil, ErrPasswordIncorrect
  19. }
  20. if err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
  21. return nil, ErrPasswordIncorrect
  22. }
  23. if !user.Status {
  24. return nil, ErrUserBanned
  25. }
  26. return
  27. }
  28. func BanIP(ip string) {
  29. b := query.BanIP
  30. banIP, err := b.Where(b.IP.Eq(ip)).First()
  31. if err != nil || banIP.ExpiredAt <= time.Now().Unix() {
  32. _ = b.Create(&model.BanIP{
  33. IP: ip,
  34. Attempts: 1,
  35. ExpiredAt: time.Now().Unix() + int64(settings.AuthSettings.BanThresholdMinutes*60),
  36. })
  37. }
  38. _, _ = b.Where(b.IP.Eq(ip)).UpdateSimple(b.Attempts.Add(1))
  39. }