-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdelete_chirp.go
More file actions
54 lines (45 loc) · 1.24 KB
/
Copy pathdelete_chirp.go
File metadata and controls
54 lines (45 loc) · 1.24 KB
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 (
"database/sql"
"errors"
"net/http"
"github.com/google/uuid"
"github.com/nk-reddy/chirpy/internal/auth"
)
func (cfg *apiConfig) handlerDeleteChirp(w http.ResponseWriter, r *http.Request) {
// get the user from JWT
clientToken, err := auth.GetBearerToken(r.Header)
if err != nil {
respondWithError(w, http.StatusUnauthorized, err.Error())
return
}
userID, err := auth.ValidateJWT(clientToken, cfg.jwtSK)
if err != nil {
respondWithError(w, http.StatusUnauthorized, err.Error())
return
}
chirpID, err := uuid.Parse(r.PathValue("chirpID"))
if err != nil {
respondWithError(w, http.StatusBadRequest, "invalid chirp ID")
return
}
chirp, err := cfg.db.GetChirp(r.Context(), chirpID)
if errors.Is(err, sql.ErrNoRows) {
respondWithError(w, http.StatusNotFound, "chirp not found")
return
}
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
if chirp.UserID != userID {
respondWithError(w, http.StatusForbidden, "not allowed to delete another user's chirp")
return
}
err = cfg.db.DeleteChirp(r.Context(), chirp.ID)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "could not delete chirp")
return
}
w.WriteHeader(http.StatusNoContent)
}