-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchirp-delete.go
More file actions
60 lines (48 loc) · 1.59 KB
/
chirp-delete.go
File metadata and controls
60 lines (48 loc) · 1.59 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
55
56
57
58
59
60
package main
import (
"log"
"net/http"
"github.com/google/uuid"
"github.com/mdmdj/bootdev-chirpy/internal/auth"
"github.com/mdmdj/bootdev-chirpy/internal/database"
)
func chirpDeleteOneRoute(w http.ResponseWriter, r *http.Request) {
chirpID := r.PathValue("chirpID")
chirpUUID, err := uuid.Parse(chirpID)
if chirpID == "" || err != nil {
log.Printf("Error deleting chirp, bad ID: %s", chirpID)
respondWithError(w, http.StatusNotFound, "404 Chirp Not Found")
return
}
token, err := auth.GetBearerToken(r.Header)
if err != nil {
log.Printf("Error in GetBearerToken: %s", err)
respondWithError(w, http.StatusUnauthorized, "Something went wrong")
return
}
userID, err := auth.ValidateJWT(token, cfg.secret)
if err != nil {
log.Printf("Error in ValidateJWT: %s", err)
respondWithError(w, http.StatusUnauthorized, "Something went wrong")
return
}
dbChirp, err := cfg.db.GetOneChirp(r.Context(), chirpUUID)
if err != nil {
log.Printf("Error deleting chirp, bad ID: %s", chirpID)
respondWithError(w, http.StatusNotFound, "404 Chirp Not Found")
return
}
if dbChirp.UserID != userID {
log.Printf("Error deleting chirp, user is not the author: %s %s %s", dbChirp.ID, dbChirp.UserID, userID)
respondWithError(w, http.StatusForbidden, "403 Not allowed to delete this chirp")
}
err = cfg.db.DeleteOneChirp(r.Context(), database.DeleteOneChirpParams{
ID: chirpUUID,
UserID: userID})
if err != nil {
log.Printf("Error in DeleteOneChirp: %s", err)
respondWithError(w, http.StatusInternalServerError, "Something went wrong")
return
}
w.WriteHeader(http.StatusNoContent)
}