-
Notifications
You must be signed in to change notification settings - Fork 3
/
users_handlers.go
executable file
·69 lines (54 loc) · 1.69 KB
/
users_handlers.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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"time"
)
type UsersHandlers struct {
dbConnection *MongoConnection
}
func (uHandlers *UsersHandlers) SignIn(w http.ResponseWriter, r *http.Request) {
name := r.FormValue("name")
email := r.FormValue("email")
ages := r.FormValue("ages")
sex := r.FormValue("sex")
password := r.FormValue("password")
userAges, _ := strconv.Atoi(ages)
user := &User{Name: name, Email: email, Ages: userAges, Sex: sex, Password: password, Date_Created: time.Now()}
result := uHandlers.dbConnection.CreateNewUser(user)
if result {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
return
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusNotFound)
if err := json.NewEncoder(w).Encode(jsonErr{Code: http.StatusNotFound, Text: "Not Found"}); err != nil {
panic(err)
}
}
func (uHandlers *UsersHandlers) Login(w http.ResponseWriter, r *http.Request) {
email := r.FormValue("email")
password := r.FormValue("password")
user := uHandlers.dbConnection.LoginWithCredentials(email, password)
userID := fmt.Sprintf("%x", string(user.Id))
log.Println(userID)
if user != nil {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
userMap := make(map[string]string)
userMap["token"] = userID
if err := json.NewEncoder(w).Encode(userMap); err != nil {
panic(err)
}
return
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusNotFound)
if err := json.NewEncoder(w).Encode(jsonErr{Code: http.StatusNotFound, Text: "Not Found"}); err != nil {
panic(err)
}
}