-
Notifications
You must be signed in to change notification settings - Fork 0
/
revoke.go
54 lines (44 loc) · 1.3 KB
/
revoke.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
package main
import (
"fmt"
"net/http"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/hatrnuhn/chirpy-webserver/internal/auth"
)
func (cfg *apiConfig) handlePostRevoke(w http.ResponseWriter, r *http.Request) {
// reads rToken from Header
rToken, err := auth.ParseReq(r, cfg.jwtSecret, "Bearer")
if err != nil {
respondWithError(w, http.StatusUnauthorized, err.Error())
return
}
if claims, ok := rToken.Claims.(*jwt.RegisteredClaims); ok {
// verifs RJWT
if claims.Issuer != "chirpy-refresh" {
respondWithError(w, http.StatusUnauthorized, "invalid RJWT")
return
}
// verifs RJWT expiration
isNotExp, err := cfg.db.RJWTNotExp(rToken.Raw)
if err != nil {
respondWithError(w, http.StatusInternalServerError, fmt.Sprintf("couldn't verify RJWT expiration status: %s", err.Error()))
return
}
if !isNotExp {
respondWithError(w, http.StatusUnauthorized, "RJWT is expired")
return
}
// updates tokens on db
_, err = cfg.db.WriteRefreshToken(rToken.Raw, time.Now().Unix())
if err != nil {
respondWithError(w, http.StatusInternalServerError, fmt.Sprintf("couldn't write RJWT to db: %s", err.Error()))
return
}
// returns with StatusOK
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
} else {
respondWithError(w, http.StatusBadRequest, "invalid RJWT")
}
}