-
Notifications
You must be signed in to change notification settings - Fork 0
/
changePost.go
244 lines (213 loc) · 7.65 KB
/
changePost.go
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
package main
import (
"crypto/md5"
"database/sql"
"encoding/hex"
"encoding/json"
"html/template"
"log"
"math/rand"
"net/http"
"strconv"
"time"
"github.com/jmoiron/sqlx"
sqlite3 "github.com/mattn/go-sqlite3"
)
// Generate a random string of 32 characters
func generateRandomString() string {
randomNum := strconv.Itoa(rand.Int())
hash := md5.Sum([]byte(randomNum))
return hex.EncodeToString(hash[:])
}
func handlerToRetrieveHomePage(w http.ResponseWriter, r *http.Request) {
// Creating HTML template
template, err := template.ParseFiles("dist/templates/index.tmpl", navBarTemplatePath, footerTemplatePath)
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError)+": Error in template parsing", http.StatusInternalServerError)
log.Println("error: could not generate html template", err)
return
}
// Add struct values to the template
template.Execute(w, nil)
}
// Delete the post with the given link if having edit access
func handleDeletePost(w http.ResponseWriter, r *http.Request) {
log.Println(r.URL.RequestURI(), r.Method)
entry, err := getEntryForRequestedLink(w, r)
if err != nil {
return
}
if entry.Access == "View" { // Post removal forbidden
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
log.Println("error: view links cannot delete posts")
} else { // Try post removal
query := `PRAGMA foreign_keys = ON;
DELETE FROM posts where post_id = $1`
_, err := db.Exec(query, entry.PostID)
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
log.Println("unsuccessful database entry removal", err)
} else {
log.Println("Successful data removal")
}
}
}
// Update the post with the given link if having edit access
func handleUpdatePost(w http.ResponseWriter, r *http.Request) {
log.Println(r.URL.RequestURI(), r.Method)
entry, err := getEntryForRequestedLink(w, r)
if err != nil {
return
}
if entry.Access == "View" { // Post removal forbidden
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
log.Println("error: view links cannot update posts")
} else { // Try post editing
// Decode Post Contents
err := json.NewDecoder(r.Body).Decode(&entry)
if err != nil {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
log.Println("error: JSON decoding error occured")
return
}
// Error Check Null Fields
if entry.Title == "" || entry.Body == "" || entry.Scope == "" {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
log.Println("error: all fields are required and should be non-null")
return
}
// Generate the query based on the fields passed
query := `UPDATE Posts
SET title=:title, body=:body, scope=:scope
WHERE post_id=:post_id`
_, err = db.NamedExec(query, entry)
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
log.Println("error: unsuccessful entry update")
} else {
log.Println("Data updated successfully")
}
}
}
// isUniqueViolation returns true if the supplied error resulted from a primary key constraint failure.
func isUniqueViolation(err error) bool {
if err, ok := err.(sqlite3.Error); ok {
return err.Code == 19 && err.ExtendedCode == 1555
}
return false
}
// Add a unique link to the database and return it
func addLinkIDToDatabase(w http.ResponseWriter, tx *sqlx.Tx, linkID string, postID int64, access string) string {
query := `INSERT INTO links (link_id, access, post_id)
VALUES ($1, $2, $3)`
_, err := tx.Exec(query, linkID, access, postID)
if err != nil {
if isUniqueViolation(err) {
linkID = addLinkIDToDatabase(w, tx, generateRandomString(), postID, access)
} else {
tx.Rollback()
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
log.Println("post creation unsuccessful")
}
}
return linkID
}
// Add the post in the entry variable to the database
func addPostToDatabase(w http.ResponseWriter, entry post) (string, string, error) {
// Start Transaction
tx, err := db.Beginx()
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
log.Println("error: failure while beginning transaction", err)
}
// Insert data in posts table
var result sql.Result
query := `INSERT INTO posts (title, body, scope, epoch)
VALUES ($1, $2, $3, $4)`
result, err = tx.Exec(query, entry.Title, entry.Body, entry.Scope, time.Now().Unix())
if err != nil {
tx.Rollback()
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
log.Println("error: post creation unsuccessful", err)
return "", "", err
}
postID, err := result.LastInsertId()
// Insert the Link ID's to the Link table
editID := addLinkIDToDatabase(w, tx, generateRandomString(), postID, "Edit")
viewID := addLinkIDToDatabase(w, tx, generateRandomString(), postID, "View")
// Commit Transaction
err = tx.Commit()
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
log.Println("error: failure while commiting transaction ", err)
}
return editID, viewID, nil
}
// Create a post with the contents given by client and respond back with the access links
func handleCreatePost(w http.ResponseWriter, r *http.Request) {
log.Println(r.URL.RequestURI(), r.Method)
// Decode Post Contents
newPost := post{}
err := json.NewDecoder(r.Body).Decode(&newPost)
if err != nil {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
log.Println("error: decoding error occured", err)
return
}
// Error Check Null Fields
if newPost.Title == "" || newPost.Body == "" || newPost.Scope == "" {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
log.Println("error: all fields are required and should be non-null")
return
}
var editLink string
var viewLink string
editLink, viewLink, err = addPostToDatabase(w, newPost)
if err != nil {
return
}
// Encode and Send Response To Client
response := postLinks{EditLink: editLink, ViewLink: viewLink}
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(response)
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
log.Println("error: encoding unsuccessful")
}
}
// Report the post based on the link
func handlePostReport(w http.ResponseWriter, r *http.Request) {
entry, err := getEntryForRequestedLink(w, r)
if err != nil {
return
}
if entry.Access == "Edit" {
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
log.Println("error: cannot report a post with edit access")
} else {
// Decode Post Contents
updatedPostContents := post{}
err := json.NewDecoder(r.Body).Decode(&updatedPostContents)
if err != nil {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
log.Println("error: JSON decoding error occured")
return
}
updatedPostContents.PostID = entry.PostID
// Error Check Null Field
if updatedPostContents.ReportReason == "" {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
log.Println("error: all fields are required and should be non-null")
return
}
// Report the post
query := `INSERT INTO REPORT (reason, post_id) VALUES (:reason, :post_id)`
_, err = db.NamedExec(query, updatedPostContents)
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
log.Println("error: unsuccessful post reporting ", err)
} else {
log.Println("Post reported successfully!")
}
}
}