-
Notifications
You must be signed in to change notification settings - Fork 160
/
handler_refresh.go
56 lines (46 loc) · 1.26 KB
/
handler_refresh.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
package main
import (
"net/http"
"time"
"github.com/bootdotdev/learn-file-storage-s3-golang-starter/internal/auth"
)
func (cfg *apiConfig) handlerRefresh(w http.ResponseWriter, r *http.Request) {
type response struct {
Token string `json:"token"`
}
refreshToken, err := auth.GetBearerToken(r.Header)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Couldn't find token", err)
return
}
user, err := cfg.db.GetUserByRefreshToken(refreshToken)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Couldn't get user for refresh token", err)
return
}
accessToken, err := auth.MakeJWT(
user.ID,
cfg.jwtSecret,
time.Hour,
)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Couldn't validate token", err)
return
}
respondWithJSON(w, http.StatusOK, response{
Token: accessToken,
})
}
func (cfg *apiConfig) handlerRevoke(w http.ResponseWriter, r *http.Request) {
refreshToken, err := auth.GetBearerToken(r.Header)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Couldn't find token", err)
return
}
err = cfg.db.RevokeRefreshToken(refreshToken)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't revoke session", err)
return
}
w.WriteHeader(http.StatusNoContent)
}