-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers_users.go
210 lines (185 loc) · 5.62 KB
/
handlers_users.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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package main
import (
"encoding/json"
"errors"
"fmt"
"github/ntvviktor/GoServer/internal/auth"
"github/ntvviktor/GoServer/internal/database"
"net/http"
"strings"
"time"
)
type User struct {
ID int `json:"id"`
Email string `json:"email"`
Password string `json:"-"`
AccessToken string `json:"token"`
RefreshToken string `json:"refresh_token"`
IsChirpyRed bool `json:"is_chirpy_red"`
}
func (apiConfig *apiConfig) createUser(w http.ResponseWriter, req *http.Request) {
type parameter struct {
Email string `json:"email"`
Password string `json:"password"`
}
type response struct {
ID int `json:"id"`
Email string `json:"email"`
//IsChirpyRed bool `json:"is_chirpy_red"`
}
decoder := json.NewDecoder(req.Body)
param := parameter{}
err := decoder.Decode(¶m)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Malformed JSON Request")
return
}
hashedPassword, _ := auth.HashUserPassword(param.Password)
user, err := apiConfig.DB.CreateUser(param.Email, hashedPassword)
if err != nil {
if errors.Is(err, database.ErrAlreadyExists) {
respondWithError(w, http.StatusConflict, "User already exists")
return
}
respondWithError(w, http.StatusInternalServerError, "Couldn't create user")
return
}
respondWithJSON(w, 201, response{
ID: user.ID,
Email: user.Email,
//IsChirpyRed: user.IsChirpyRed,
})
}
func (apiConfig *apiConfig) authenticateUser(w http.ResponseWriter, req *http.Request) {
type parameter struct {
Email string `json:"email"`
Password string `json:"password"`
ExpiresTime int `json:"expires_in_seconds"`
}
type response struct {
User
}
decoder := json.NewDecoder(req.Body)
param := parameter{}
err := decoder.Decode(¶m)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Malformed JSON Request")
return
}
authUser, err := apiConfig.DB.GetUserByEmail(param.Email)
if err != nil {
if errors.Is(err, database.ErrNotExist) {
respondWithError(w, http.StatusNotFound, "User not found!")
return
}
http.Error(w, "Internal Error", 500)
return
}
err = auth.AuthenticateUser(param.Password, authUser.Password)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Wrong Password")
return
}
accessToken, err := auth.GenerateJWT(authUser.ID, apiConfig.jwtSecret, auth.AccessToken)
refreshToken, err := auth.GenerateJWT(authUser.ID, apiConfig.jwtSecret, auth.RefreshToken)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Error creating JWT token")
return
}
respondWithJSON(w, http.StatusOK, response{
User{
ID: authUser.ID,
Email: authUser.Email,
IsChirpyRed: authUser.IsChirpyRed,
AccessToken: accessToken,
RefreshToken: refreshToken,
},
})
}
func (apiConfig *apiConfig) validateUser(w http.ResponseWriter, req *http.Request) {
tokenString, canCut := getTokenFromHeader(req)
if !canCut {
respondWithError(w, http.StatusUnauthorized, "Malformed request token string")
return
}
type parameter struct {
Email string `json:"email"`
Password string `json:"password"`
}
param := parameter{}
decoder := json.NewDecoder(req.Body)
err := decoder.Decode(¶m)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Malformed request, token is not valid!")
return
}
validID, issuer, err := auth.ValidateJWT(tokenString, apiConfig.jwtSecret)
if err != nil || issuer == "chirpy-refresh" {
respondWithError(w, http.StatusUnauthorized, "Cannot validate token")
return
}
hashedPassword, err := auth.HashUserPassword(param.Password)
user, err := apiConfig.DB.UpdateUser(validID, param.Email, hashedPassword)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Internal Server Error")
}
type response struct {
Email string `json:"email"`
ID int `json:"id"`
}
respondWithJSON(w, 200, response{
Email: user.Email,
ID: user.ID,
})
}
func (apiConfig *apiConfig) postRefreshToken(w http.ResponseWriter, req *http.Request) {
tokenString, canCut := getTokenFromHeader(req)
if !canCut {
respondWithError(w, http.StatusUnauthorized, "Malformed request token string")
return
}
validID, issuer, err := auth.ValidateJWT(tokenString, apiConfig.jwtSecret)
if err != nil || issuer != "chirpy-refresh" {
respondWithError(w, http.StatusUnauthorized, "Unauthorized JSON Token")
return
}
user, err := apiConfig.DB.GetUser(validID)
if err != nil || issuer != "chirpy-refresh" {
respondWithError(w, http.StatusNotFound, "User Not found")
return
}
if user.RevokeToken.ID != "" {
respondWithError(w, http.StatusUnauthorized, "Unauthorized JSON Token")
return
}
type response struct {
Token string `json:"token"`
}
respondWithJSON(w, 200, response{
Token: tokenString,
})
}
func (apiConfig *apiConfig) postRevokeToken(w http.ResponseWriter, req *http.Request) {
tokenString, canCut := getTokenFromHeader(req)
if !canCut {
respondWithError(w, http.StatusUnauthorized, "Malformed request token string")
return
}
validID, issuer, err := auth.ValidateJWT(tokenString, apiConfig.jwtSecret)
if err != nil || issuer != "chirpy-refresh" {
respondWithError(w, http.StatusUnauthorized, "Unauthorized JSON Token")
return
}
user, err := apiConfig.DB.CreateRevokeToken(validID, time.Now(), tokenString)
if err != nil || issuer != "chirpy-refresh" {
respondWithError(w, http.StatusNotFound, "User Not found")
return
}
respondWithJSON(w, 200, user.Email)
}
func getTokenFromHeader(req *http.Request) (string, bool) {
authorizedToken := req.Header.Get("Authorization")
tokenString, canCut := strings.CutPrefix(authorizedToken, "Bearer ")
fmt.Println(tokenString)
return tokenString, canCut
}