Implement paste deletion endpoint

This commit is contained in:
Lukas SP 2020-08-23 00:45:30 +02:00
parent 3aba9adb32
commit e297a5c2b4
1 changed files with 68 additions and 0 deletions

View File

@ -12,6 +12,8 @@ import (
// InitializePastesController initializes the '/v1/pastes/*' controller
func InitializePastesController(group *router.Group) {
group.GET("/{id}", v1GetPaste)
group.POST("/", v1PostPaste)
group.DELETE("/{id}", v1DeletePaste)
}
// v1GetPaste handles the 'GET /v1/pastes/{id}' endpoint
@ -73,6 +75,14 @@ func v1PostPaste(ctx *fasthttp.RequestCtx) {
return
}
// Save the paste
err = storage.Current.Save(paste)
if err != nil {
ctx.SetStatusCode(fasthttp.StatusInternalServerError)
ctx.SetBodyString(err.Error())
return
}
// Respond with the paste
jsonData, err := json.Marshal(paste)
if err != nil {
@ -82,3 +92,61 @@ func v1PostPaste(ctx *fasthttp.RequestCtx) {
}
ctx.SetBody(jsonData)
}
// v1DeletePaste handles the 'DELETE /v1/pastes/{id}'
func v1DeletePaste(ctx *fasthttp.RequestCtx) {
// Parse the ID
id, err := snowflake.ParseString(ctx.UserValue("id").(string))
if err != nil {
ctx.SetStatusCode(fasthttp.StatusBadRequest)
ctx.SetBodyString("invalid ID format")
return
}
// Unmarshal the body
values := make(map[string]string)
err := json.Unmarshal(ctx.PostBody(), &values)
if err != nil {
ctx.SetStatusCode(fasthttp.StatusBadRequest)
ctx.SetBodyString("invalid request body")
return
}
// Validate the deletion token of the paste
if values["deletionToken"] == "" {
ctx.SetStatusCode(fasthttp.StatusBadRequest)
ctx.SetBodyString("missing 'deletionToken' field")
return
}
// Retrieve the paste
paste, err := storage.Current.Get(id)
if err != nil {
ctx.SetStatusCode(fasthttp.StatusInternalServerError)
ctx.SetBodyString(err.Error())
return
}
if paste == nil {
ctx.SetStatusCode(fasthttp.StatusNotFound)
ctx.SetBodyString("paste not found")
return
}
// Check if the deletion token is correct
if !paste.CheckDeletionToken(values["deletionToken"]) {
ctx.SetStatusCode(fasthttp.StatusForbidden)
ctx.SetBodyString("invalid deletion token")
return
}
// Delete the paste
err = storage.Current.Delete(paste.ID)
if err != nil {
ctx.SetStatusCode(fasthttp.StatusInternalServerError)
ctx.SetBodyString(err.Error())
return
}
// Respond with 'ok'
ctx.SetBodyString("ok")
}