-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser.go
147 lines (123 loc) · 3.61 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
package main
import (
"encoding/json"
"fmt"
"net/http"
"reflect"
"regexp"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/olivere/elastic"
)
const (
USER_INDEX = "user"
)
type User struct {
Username string `json:"username"`
Password string `json:"password"`
Age int64 `json:"age"`
Gender string `json:"gender"`
}
var mySigningKey = []byte("secret")
func checkUser(username, password string) (bool, error) {
query := elastic.NewTermQuery("username", username)
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
}
func handlerLogin(w http.ResponseWriter, r *http.Request) {
fmt.Println("Received one login request")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
if r.Method == "OPTIONS" {
return
}
// Get User information from client
decoder := json.NewDecoder(r.Body)
var user User
if err := decoder.Decode(&user); err != nil {
http.Error(w, "Cannot decode user data from client", http.StatusBadRequest)
fmt.Printf("Cannot decode user data from client %v\n", err)
return
}
exists, err := checkUser(user.Username, user.Password)
if err != nil {
http.Error(w, "Failed to read user from Elasticsearch", http.StatusInternalServerError)
fmt.Printf("Failed to read user from Elasticsearch %v\n", err)
return
}
if !exists {
http.Error(w, "User doesn't exists or wrong password", http.StatusUnauthorized)
fmt.Printf("User doesn't exists or wrong password\n")
return
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"username": user.Username,
"exp": time.Now().Add(time.Hour * 24).Unix(),
})
tokenString, err := token.SignedString(mySigningKey)
if err != nil {
http.Error(w, "Failed to generate token", http.StatusInternalServerError)
fmt.Printf("Failed to generate token %v\n", err)
return
}
w.Write([]byte(tokenString))
}
func handlerSignup(w http.ResponseWriter, r *http.Request) {
fmt.Println("Received one signup request")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
if r.Method == "OPTIONS" {
return
}
decoder := json.NewDecoder(r.Body)
var user User
if err := decoder.Decode(&user); err != nil {
http.Error(w, "Cannot decode user data from client", http.StatusBadRequest)
fmt.Printf("Cannot decode user data from client %v\n", err)
return
}
if user.Username == "" || user.Password == "" || regexp.MustCompile(`^[a-z0-9]$`).MatchString(user.Username) {
http.Error(w, "Invalid username or password", http.StatusBadRequest)
fmt.Printf("Invalid username or password\n")
return
}
success, err := addUser(&user)
if err != nil {
http.Error(w, "Failed to save user to Elasticsearch", http.StatusInternalServerError)
fmt.Printf("Failed to save user to Elasticsearch %v\n", err)
return
}
if !success {
http.Error(w, "User already exists", http.StatusBadRequest)
fmt.Println("User already exists")
return
}
fmt.Printf("User added successfully: %s.\n", user.Username)
}