-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser.go
152 lines (129 loc) · 3.48 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
148
149
150
151
152
package main
import (
"encoding/json"
"fmt"
"net/http"
"reflect"
"regexp"
"time"
jwt "github.com/dgrijalva/jwt-go"
elastic "gopkg.in/olivere/elastic.v3"
)
const (
TYPE_USER = "user"
)
var (
usernamePattern = regexp.MustCompile(`^[a-z0-9_]+$`).MatchString
)
type User struct {
Username string `json:"username"`
Password string `json:"password"`
Age int `json:"age"`
Gender string `json:"gender"`
}
func checkUser(username, password string) bool {
es_client, err := elastic.NewClient(elastic.SetURL(ES_URL), elastic.SetSniff(false))
if err != nil {
fmt.Printf("ES is not setup %v\n", err)
return false
}
// Search with a term query
termQuery := elastic.NewTermQuery("username", username)
queryResult, err := es_client.Search().
Index(INDEX).
Query(termQuery).
Pretty(true).
Do()
if err != nil {
fmt.Printf("ES query failed %v\n", err)
return false
}
var tyu User
for _, item := range queryResult.Each(reflect.TypeOf(tyu)) {
u := item.(User)
return u.Password == password && u.Username == username
}
// If no user exist, return false.
return false
}
func addUser(user User) bool {
es_client, err := elastic.NewClient(elastic.SetURL(ES_URL), elastic.SetSniff(false))
if err != nil {
fmt.Printf("ES is not setup %v\n", err)
return false
}
termQuery := elastic.NewTermQuery("username", user.Username)
queryResult, err := es_client.Search().
Index(INDEX).
Query(termQuery).
Pretty(true).
Do()
if err != nil {
fmt.Printf("ES query failed %v\n", err)
return false
}
if queryResult.TotalHits() > 0 {
fmt.Printf("User %s already exists, cannot create duplicate user.\n", user.Username)
return false
}
_, err = es_client.Index().
Index(INDEX).
Type(TYPE_USER).
Id(user.Username).
BodyJson(user).
Refresh(true).
Do()
if err != nil {
fmt.Printf("ES save user failed %v\n", err)
return false
}
return true
}
func signupHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("Received one signup request")
decoder := json.NewDecoder(r.Body)
var u User
if err := decoder.Decode(&u); err != nil {
panic(err)
return
}
if u.Username != "" && u.Password != "" && usernamePattern(u.Username) {
if addUser(u) {
fmt.Println("User added successfully.")
w.Write([]byte("User added successfully."))
} else {
fmt.Println("Failed to add a new user.")
http.Error(w, "Failed to add a new user", http.StatusInternalServerError)
}
} else {
fmt.Println("Empty password or username.")
http.Error(w, "Empty password or username", http.StatusInternalServerError)
}
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
}
func loginHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("Received one login request")
decoder := json.NewDecoder(r.Body)
var u User
if err := decoder.Decode(&u); err != nil {
panic(err)
return
}
if checkUser(u.Username, u.Password) {
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
/* Set token claims */
claims["username"] = u.Username
claims["exp"] = time.Now().Add(time.Hour * 24).Unix()
/* Sign the token with our secret */
tokenString, _ := token.SignedString(mySigningKey)
/* Finally, write the token to the browser window */
w.Write([]byte(tokenString))
} else {
fmt.Println("Invalid password or username.")
http.Error(w, "Invalid password or username", http.StatusForbidden)
}
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
}