-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrefresh_token.go
53 lines (43 loc) · 1.53 KB
/
refresh_token.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
package main
import (
"log"
"net/http"
"example.com/chirpy/internal/auth"
)
func (cfg *apiConfig) handlerRevokeRefreshToken(w http.ResponseWriter, r *http.Request) {
bearer, err := auth.GetBearerToken(r.Header)
if err != nil {
log.Printf("Unable to fetch bearer token: %s", err)
respondWithError(w, http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized))
return
}
if err := cfg.dbQueries.RevokeRefreshToken(r.Context(), bearer); err != nil {
log.Printf("Unable to revoke refresh token: %s", err)
respondWithError(w, http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized))
return
}
w.WriteHeader(http.StatusNoContent)
}
func (cfg *apiConfig) handlerUpdateRefreshToken(w http.ResponseWriter, r *http.Request) {
type response struct {
Token string `json:"token"`
}
bearer, err := auth.GetBearerToken(r.Header)
if err != nil {
log.Printf("Unable to fetch bearer token: %s", err)
respondWithError(w, http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized))
return
}
userId, err := cfg.dbQueries.GetUserFromRefreshToken(r.Context(), bearer)
if err != nil {
respondWithError(w, http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized))
return
}
newAccessToken, err := auth.MakeJWT(userId, cfg.jwtSecret, accessTokenExpiresIn)
if err != nil {
log.Printf("Unable to create new access token: %s", err)
respondWithError(w, http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError))
return
}
respondWithJson(w, http.StatusOK, response{newAccessToken})
}