login.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package user
  2. import (
  3. "time"
  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. )
  9. func Login(name string, password string) (user *model.User, err error) {
  10. u := query.User
  11. user, err = u.Where(u.Name.Eq(name)).First()
  12. if err != nil {
  13. return nil, ErrPasswordIncorrect
  14. }
  15. // if the user is not initialized, return error
  16. if user.Password == "" {
  17. return nil, ErrPasswordIncorrect
  18. }
  19. if err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
  20. return nil, ErrPasswordIncorrect
  21. }
  22. if !user.Status {
  23. return nil, ErrUserBanned
  24. }
  25. return
  26. }
  27. func BanIP(ip string) {
  28. b := query.BanIP
  29. banIP, err := b.Where(b.IP.Eq(ip)).First()
  30. if err != nil || banIP.ExpiredAt <= time.Now().Unix() {
  31. _ = b.Create(&model.BanIP{
  32. IP: ip,
  33. Attempts: 1,
  34. ExpiredAt: time.Now().Unix() + int64(settings.AuthSettings.BanThresholdMinutes*60),
  35. })
  36. return
  37. }
  38. _, _ = b.Where(b.IP.Eq(ip)).UpdateSimple(b.Attempts.Add(1))
  39. }