@@ -14,6 +14,7 @@ import (
1414 "github.com/bstaijen/mariadb-for-microservices/comment-service/database"
1515 "github.com/bstaijen/mariadb-for-microservices/shared/util"
1616 jwt "github.com/dgrijalva/jwt-go"
17+ "github.com/gorilla/mux"
1718 "github.com/urfave/negroni"
1819
1920 "strconv"
@@ -270,6 +271,69 @@ func GetLastTenHandler(connection *sql.DB, cnf config.Config) negroni.HandlerFun
270271 })
271272}
272273
274+ // DeleteCommentHandler : is the handler to remove a comment in the database
275+ func DeleteCommentHandler (connection * sql.DB , cnf config.Config ) negroni.HandlerFunc {
276+ return negroni .HandlerFunc (func (w http.ResponseWriter , r * http.Request , next http.HandlerFunc ) {
277+
278+ var queryToken = r .URL .Query ().Get ("token" )
279+
280+ if len (queryToken ) < 1 {
281+ queryToken = r .Header .Get ("token" )
282+ }
283+
284+ if len (queryToken ) < 1 {
285+ w .WriteHeader (http .StatusBadRequest )
286+ w .Write ([]byte (string ("token is mandatory" )))
287+ return
288+ }
289+
290+ tok , err := jwt .Parse (queryToken , func (t * jwt.Token ) (interface {}, error ) {
291+ return []byte (cnf .SecretKey ), nil
292+ })
293+
294+ if err != nil {
295+ util .SendErrorMessage (w , "You are not authorized" )
296+ return
297+ }
298+
299+ claims := tok .Claims .(jwt.MapClaims )
300+ var userID = claims ["sub" ].(float64 ) // gets the ID
301+
302+ // Get commentID
303+ vars := mux .Vars (r )
304+ strID := vars ["id" ]
305+ commentID , err := strconv .Atoi (strID )
306+
307+ if err != nil {
308+ util .SendErrorMessage (w , "id needs to be numeric" )
309+ return
310+ }
311+
312+ if commentID < 1 {
313+ util .SendErrorMessage (w , "id needs to be greater than 0" )
314+ return
315+ }
316+
317+ comment , err := db .GetCommentByID (connection , commentID )
318+ if err != nil {
319+ util .SendError (w , err )
320+ return
321+ }
322+
323+ if comment .UserID != int (userID ) {
324+ util .SendErrorMessage (w , "you can only remove your own comment" )
325+ return
326+ }
327+
328+ _ , err = db .DeleteCommentByID (connection , commentID )
329+ if err != nil {
330+ util .SendError (w , err )
331+ return
332+ }
333+ util .SendOKMessage (w , "Comment removed" )
334+ })
335+ }
336+
273337func getUsernames (cnf config.Config , input []* sharedModels.GetUsernamesRequest ) []* sharedModels.GetUsernamesResponse {
274338 type Req struct {
275339 Requests []* sharedModels.GetUsernamesRequest `json:"requests"`
0 commit comments