-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler_refresh_tokens.go
48 lines (41 loc) · 1.19 KB
/
handler_refresh_tokens.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
package main
import (
"net/http"
"time"
"github.com/chichigami/chirpy/internal/auth"
)
func (cfg *apiConfig) handlerRevokeRefreshToken(w http.ResponseWriter, req *http.Request) {
reqToken, err := auth.GetBearerToken(req.Header)
if err != nil {
respondWithError(w, 401, "refresh token expired or does not exist")
return
}
cfg.db.RevokeRefreshToken(req.Context(), reqToken)
w.WriteHeader(http.StatusNoContent)
}
func (cfg *apiConfig) handlerRefreshToken(w http.ResponseWriter, req *http.Request) {
type response struct {
Token string `json:"token"`
}
reqToken, err := auth.GetBearerToken(req.Header)
if err != nil {
respondWithError(w, 401, err.Error())
return
}
dbUser, err := cfg.db.GetUserFromRefreshToken(req.Context(), reqToken)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "refresh token expired or does not exist")
return
}
if dbUser.RevokedAt.Valid {
respondWithError(w, http.StatusUnauthorized, "refresh token revoked")
}
jwtToken, err := auth.MakeJWT(dbUser.UserID, cfg.jwtSecret, time.Hour)
if err != nil {
respondWithError(w, 500, "access token generation failed")
return
}
respondWithJSON(w, http.StatusOK, response{
Token: jwtToken,
})
}