-
Notifications
You must be signed in to change notification settings - Fork 148
/
helpers.go
80 lines (74 loc) · 2.25 KB
/
helpers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package users
import (
"errors"
"net/http"
"strconv"
"github.com/NyaaPantsu/nyaa/models"
"github.com/NyaaPantsu/nyaa/utils/log"
"github.com/NyaaPantsu/nyaa/utils/validator/user"
"golang.org/x/crypto/bcrypt"
)
// CheckEmail : check if email is in database
func CheckEmail(email string) bool {
if len(email) == 0 {
return false
}
var count int
models.ORM.Model(models.User{}).Where("email = ?", email).Count(&count)
return count != 0
}
// Exists : check if the users credentials match to a user in db
func Exists(email string, pass string) (user *models.User, status int, err error) {
if email == "" || pass == "" {
return user, http.StatusNotFound, errors.New("no_username_password")
}
var userExist = &models.User{}
// search by email or username
if userValidator.EmailValidation(email) {
if models.ORM.Where("email = ?", email).First(userExist).RecordNotFound() {
status, err = http.StatusNotFound, errors.New("user_not_found")
return
}
} else if models.ORM.Where("username = ?", email).First(userExist).RecordNotFound() {
status, err = http.StatusNotFound, errors.New("user_not_found")
return
}
user = userExist
err = bcrypt.CompareHashAndPassword([]byte(userExist.Password), []byte(pass))
if err != nil {
status, err = http.StatusUnauthorized, errors.New("incorrect_password")
return
}
if userExist.IsBanned() {
status, err = http.StatusUnauthorized, errors.New("account_banned")
return
}
if userExist.IsScraped() {
status, err = http.StatusUnauthorized, errors.New("account_need_activation")
return
}
status, err = http.StatusOK, nil
return
}
// SuggestUsername suggest user's name if user's name already occupied.
func SuggestUsername(username string) string {
var count int
var usernameCandidate string
models.ORM.Model(models.User{}).Where(&models.User{Username: username}).Count(&count)
log.Debugf("count Before : %d", count)
if count == 0 {
return username
}
var postfix int
for {
usernameCandidate = username + strconv.Itoa(postfix)
log.Debugf("usernameCandidate: %s\n", usernameCandidate)
models.ORM.Model(models.User{}).Where(&models.User{Username: usernameCandidate}).Count(&count)
log.Debugf("count after : %d\n", count)
postfix = postfix + 1
if count == 0 {
break
}
}
return usernameCandidate
}