-
Notifications
You must be signed in to change notification settings - Fork 0
/
AuthController.go
executable file
·103 lines (89 loc) · 2.55 KB
/
AuthController.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
package web
import (
"encoding/json"
"github.com/Advanced-Go/Day-6/5-Authentication/easy-issues"
"github.com/Advanced-Go/Day-7/4-Message-Queues/easy-issues/application"
"github.com/Advanced-Go/Day-7/4-Message-Queues/easy-issues/domain"
"github.com/Shopify/sarama"
"github.com/dgrijalva/jwt-go"
"github.com/google/uuid"
"log"
"net/http"
"time"
)
// Controller for Auth model
type AuthController struct {
AuthService domain.AuthService
EventsProducer sarama.SyncProducer
Secret string
}
type LoginResponse struct {
Token string `json:"token"`
}
type JWTData struct {
jwt.StandardClaims
CustomClaims map[string]string `json:"custom,omitempty"`
}
func (c AuthController) Verify(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
func (c AuthController) Login(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "invalid method", http.StatusBadRequest)
return
}
email, _, ok := r.BasicAuth()
if !ok {
http.Error(w, "authorization failed", http.StatusUnauthorized)
return
}
userRegistration, err := c.AuthService.GetRegistrationByEmail(email)
if err != nil {
http.Error(w, err.Error(), http.StatusUnauthorized)
return
}
if userRegistration.Status == domain.RegistrationStatusDeleted {
if err != nil {
http.Error(w, "authorization failed", http.StatusUnauthorized)
return
}
}
ok = easy_issues.CheckPasswordHash("secret", userRegistration.PasswordHash)
if !ok {
http.Error(w, err.Error(), http.StatusUnauthorized)
return
}
claims := JWTData{
StandardClaims: jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Hour).Unix(),
Issuer: "auth.service",
},
CustomClaims: map[string]string{
"userId": userRegistration.Uuid,
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString([]byte(c.Secret))
if err != nil {
http.Error(w, err.Error(), http.StatusUnauthorized)
return
}
response := LoginResponse{
Token: tokenString,
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(response)
}
func (c AuthController) Register(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "invalid method", http.StatusBadRequest)
return
}
// Code to Register new User account -> TODO
event := domain.NewCreateUserRegistrationEvent(uuid.New().String(), "alex.tomas@live.com")
err := application.SubmitEvent(c.EventsProducer, event)
if err != nil {
log.Fatalf("%v.SubmitEvent(_) = _, %v: ", c.EventsProducer, err)
}
}