forked from sean-laioffer/2021Spring2AroundBackend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.go
58 lines (49 loc) · 1.28 KB
/
user.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
package main
import (
"fmt"
"reflect"
"github.com/olivere/elastic/v7"
)
const (
USER_INDEX = "user"
)
type User struct {
Username string `json:"username"`
Password string `json:"password"`
Age int64 `json:"age"`
Gender string `json:"gender"`
}
func checkUser(username, password string) (bool, error) {
query := elastic.NewBoolQuery()
query.Must(elastic.NewTermQuery("username", username))
query.Must(elastic.NewTermQuery("password", password))
searchResult, err := readFromES(query, USER_INDEX)
if err != nil {
return false, err
}
var utype User
for _, item := range searchResult.Each(reflect.TypeOf(utype)) {
u := item.(User)
if u.Password == password {
fmt.Printf("Login as %s\n", username)
return true, nil
}
}
return false, nil
}
func addUser(user *User) (bool, error) {
query := elastic.NewTermQuery("username", user.Username)
searchResult, err := readFromES(query, USER_INDEX)
if err != nil {
return false, err
}
if searchResult.TotalHits() > 0 {
return false, nil
}
err = saveToES(user, USER_INDEX, user.Username)
if err != nil {
return false, err
}
fmt.Printf("User is added: %s\n", user.Username)
return true, nil
}