-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler_chirp_delete.go
56 lines (41 loc) · 1.34 KB
/
handler_chirp_delete.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"
"strconv"
"github.com/go-chi/chi/v5"
"github.com/jcsmurph/chirpy/internal/auth"
)
func (cfg *apiConfig) handlerChirpDelete(w http.ResponseWriter, r *http.Request) {
token, err := auth.GetBearerToken(r.Header)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Couldn't find JWT")
return
}
validAccessToken := auth.ValidateAccessToken(token, cfg.jwtSecret)
if validAccessToken != nil {
respondWithError(w, http.StatusUnauthorized, "Token is not an access token")
return
}
subject, ValidateJWTerr := auth.ValidateJWT(token, cfg.jwtSecret)
if ValidateJWTerr != nil {
respondWithError(w, http.StatusUnauthorized, "Couldn't validate JWT")
return
}
chirpIDString := chi.URLParam(r, "chirpID")
chirpID, err := strconv.Atoi(chirpIDString)
userID, err := strconv.Atoi(subject)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid Chirp ID")
return
}
dbChirp, err := cfg.DB.GetChirpID(chirpID)
if err != nil {
respondWithError(w, http.StatusNotFound, "Couldn't get chirp")
return
}
deleteChirpErr := cfg.DB.DeleteChirp(dbChirp.ID, userID)
if deleteChirpErr != nil {
respondWithError(w, http.StatusForbidden, "The user is not authorized to delete the chirp")
}
respondWithStatus(w, http.StatusOK)
}