func getApiPostAuthorsHandler(w http.ResponseWriter, r *http.Request, params map[string]string) { userName := authentication.GetUserName(r) if userName != "" { post_id := params["id"] postId, err := strconv.ParseInt(post_id, 10, 64) if err != nil || postId < 1 { http.Error(w, err.Error(), http.StatusInternalServerError) return } var authors []structure.User authors, err = database.RetrieveAuthors(postId) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } json, err := json.Marshal(usersToJson(authors)) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.Write(json) return } else { http.Error(w, "Not logged in!", http.StatusInternalServerError) return } }
// API function to add and remove post authors func putApiPostAuthorsHandler(w http.ResponseWriter, r *http.Request, params map[string]string) { userName := authentication.GetUserName(r) if userName != "" { userId, err := getUserId(userName) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } userRole, err := getUserRole(userName) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } post_id := params["id"] postId, err := strconv.ParseInt(post_id, 10, 64) if err != nil || postId < 1 { http.Error(w, err.Error(), http.StatusInternalServerError) return } // Check the post for existence (there's no foreign key constraint) post, err := database.RetrievePostById(postId) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // Allow this action only to the main author if post.Author.Id != userId && userRole != 4 { http.Error(w, "Not your post", http.StatusInternalServerError) return } decoder := json.NewDecoder(r.Body) var json JsonChangePostAuthors err = decoder.Decode(&json) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } delete_author_ids := json.Delete add_author_ids := json.Add var existing_authors []structure.User existing_authors, err = database.RetrieveAuthors(postId) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // Delete users for _, author_id := range delete_author_ids { err = database.DeletePostAuthor(postId, author_id) // Don't even check for errors } // Filter out ones who is already listed as author for _, author_id := range add_author_ids { author_exists := false for _, author := range existing_authors { if author.Id == author_id { author_exists = true break } } if !author_exists { _, err = database.RetrieveUser(author_id) if err == nil { // Verify that this user exists in DB // and save him _ = database.InsertPostAuthor(int(postId), author_id) } } } w.WriteHeader(http.StatusOK) w.Write([]byte("Authors added!")) return } else { http.Error(w, "Not logged in!", http.StatusInternalServerError) return } }