/
handler.go
98 lines (90 loc) · 2.38 KB
/
handler.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
package main
import (
"encoding/json"
"net/http"
"github.com/briankliwon/microservices-docker-go/auth/pkg/models"
"golang.org/x/crypto/bcrypt"
)
func (app *application) authorize(w http.ResponseWriter, r *http.Request) {
_, err := app.srv.ValidationBearerToken(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
httpResponse := &models.HttpResponseMessage{
Message: "Authentiicated",
}
b, err := json.Marshal(httpResponse)
if err != nil {
app.serverError(w, err)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(b)
}
func (app *application) token(w http.ResponseWriter, r *http.Request) {
app.srv.HandleTokenRequest(w, r)
}
func (app *application) signup(w http.ResponseWriter, r *http.Request) {
var m models.Auth
err := json.NewDecoder(r.Body).Decode(&m)
if err != nil {
app.serverError(w, err)
}
passwordEncrypted, err := bcrypt.GenerateFromPassword([]byte(m.Password), 14)
if err != nil {
app.serverError(w, err)
}
m.Password = string(passwordEncrypted)
insertResult, err := app.auth.Insert(m)
if err != nil {
app.serverError(w, err)
}
app.infoLog.Printf("New user have been created, id=%s", insertResult.ID)
httpResponse := &models.HttpResponse{
Message: "New user have been created",
OauthData: models.Oauth2Key{
ClientID: app.oauth2.ClientID,
ClientSecret: app.oauth2.ClientSecret,
},
}
b, err := json.Marshal(httpResponse)
if err != nil {
app.serverError(w, err)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(b)
}
func (app *application) login(w http.ResponseWriter, r *http.Request) {
var m models.Auth
err := json.NewDecoder(r.Body).Decode(&m)
if err != nil {
app.responseError(w, "Login Failed")
return
}
userData, err := app.auth.Select(m)
if err != nil {
app.responseError(w, "Login Failed")
return
}
err = bcrypt.CompareHashAndPassword([]byte(userData.Password), []byte(m.Password))
if err != nil {
app.responseError(w, "Login Failed")
return
}
httpResponse := &models.HttpResponse{
Message: "Login success",
OauthData: models.Oauth2Key{
ClientID: app.oauth2.ClientID,
ClientSecret: app.oauth2.ClientSecret,
},
}
b, err := json.Marshal(httpResponse)
if err != nil {
app.serverError(w, err)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(b)
}