-
Notifications
You must be signed in to change notification settings - Fork 3
/
twitter.go
377 lines (348 loc) · 8.29 KB
/
twitter.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
package main
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
"github.com/gorilla/mux"
"github.com/gorilla/securecookie"
"html/template"
"fmt"
"log"
"net/http"
"os"
)
//Users table
type User struct {
Userid int64
Username string
Password string
Posts []*Post
}
//Posts table
type Post struct {
Tweetid string
Username string
Status string
}
//global variables
var AddUser User = User{}
var AddTweet string
var logname string
var logpass string
var currentuser string
var postvalue string
var statusid string
var settweet string
var db *sql.DB
var err error
//db
func ReadStatus() (res [][]string) {
err := db.Ping()
if err != nil {
log.Fatal(err)
}
rows, err := db.Query("SELECT id, tweet, username FROM posts WHERE username = ? ORDER BY id DESC", currentuser)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var tweet, id, username string
for rows.Next() {
err := rows.Scan(&id, &tweet, &username)
if err != nil {
return res
}
var a []string
a = append(a, id, tweet, username)
res = append(res, a)
}
return
}
func ReadSingleStatus() (res string) {
err := db.Ping()
if err != nil {
log.Fatal(err)
}
rows, err := db.Query("SELECT tweet FROM posts WHERE id = ?", statusid)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var status string
for rows.Next() {
err := rows.Scan(&status)
if err != nil {
log.Fatal(err)
}
res = status
}
return
}
func ReadStatusId() (res int) {
err := db.Ping()
if err != nil {
log.Fatal(err)
}
rows, err := db.Query("SELECT id FROM posts WHERE tweet = ?", AddTweet)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var status string
for rows.Next() {
err := rows.Scan(&status)
if err != nil {
log.Fatal(err)
}
}
return
}
func InsertData() {
stmt, err := db.Prepare("INSERT INTO users(id, username, password) VALUES(?, ?, ?)")
if err != nil {
log.Fatal(err)
}
res, err := stmt.Exec(AddUser.Userid, AddUser.Username, AddUser.Password)
if err != nil {
log.Fatal(err)
}
lastId, err := res.LastInsertId()
if err != nil {
log.Fatal(err)
}
rowCnt, err := res.RowsAffected()
if err != nil {
log.Fatal(err)
}
fmt.Printf("ID = %d, affected = %d\n", lastId, rowCnt)
}
func InsertTweetData() {
stmt, err := db.Prepare("INSERT INTO posts(tweet, username) VALUES(?, ?)")
if err != nil {
log.Fatal(err)
}
res, err := stmt.Exec(AddTweet, AddUser.Username)
if err != nil {
log.Fatal(err)
}
lastId, err := res.LastInsertId()
if err != nil {
log.Fatal(err)
}
rowCnt, err := res.RowsAffected()
if err != nil {
log.Fatal(err)
}
fmt.Printf("ID = %d, affected = %d\n", lastId, rowCnt)
}
func DeleteTweet() {
stmt, err := db.Prepare("DELETE FROM posts where id = ?")
if err != nil {
log.Fatal(err)
}
res, err := stmt.Exec(postvalue)
if err != nil {
log.Fatal(err)
}
lastId, err := res.LastInsertId()
if err != nil {
log.Fatal(err)
}
rowCnt, err := res.RowsAffected()
if err != nil {
log.Fatal(err)
}
fmt.Printf("ID = %d, affected = %d\n", lastId, rowCnt)
}
func EditTweet() {
stmt, err := db.Prepare("UPDATE posts SET tweet = ? where id = ?")
a, err := stmt.Exec(settweet, statusid)
if err != nil {
log.Fatal(err)
}
lastId, err := a.LastInsertId()
if err != nil {
log.Fatal(err)
}
rowCnt, err := a.RowsAffected()
if err != nil {
log.Fatal(err)
}
fmt.Printf("ID = %d, affected = %d\n", lastId, rowCnt)
}
func AuthUser() (res string) {
err := db.Ping()
if err != nil {
log.Fatal(err)
}
rows, err := db.Query("SELECT username FROM users WHERE username = ?", logname)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var logusername string
for rows.Next() {
err := rows.Scan(&logusername)
if err != nil {
return ""
}
res = logusername
}
return
}
func AuthPw() (res string) {
err := db.Ping()
if err != nil {
log.Fatal(err)
}
rows, err := db.Query("SELECT password FROM users WHERE username = ?", logname)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var logpw string
for rows.Next() {
err := rows.Scan(&logpw)
if err != nil {
return ""
}
res = logpw
}
return
}
//handlers
func logHandler(w http.ResponseWriter, r *http.Request) {
renderTemplate(w, "log", "log", User{})
}
func loginHandler(w http.ResponseWriter, r *http.Request) {
logname = r.FormValue("name")
logpass = r.FormValue("password")
AddUser.Password = logpass
fmt.Println(AuthPw(), logpass)
redirectTarget := "/"
switch {
//existing user correct pw
case logname != "" && logpass != "" && logname == AuthUser() && logpass == AuthPw():
setSession(logname, w)
redirectTarget = "/home"
//existing user wrong pw
case logname != "" && logpass != "" && logname == AuthUser() && logpass != AuthPw():
fmt.Fprintf(w, "<html>wrong password</html>")
//new user
case logname != "" && logpass != "" && logname != AuthUser():
AddUser.Username = logname
AddUser.Password = logpass
InsertData()
setSession(logname, w)
redirectTarget = "/home"
}
http.Redirect(w, r, redirectTarget, 302)
}
func logoutHandler(w http.ResponseWriter, r *http.Request) {
clearSession(w)
http.Redirect(w, r, "/", 302)
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
currentuser = getUserName(r)
if currentuser != "" {
var as []Post
a := User{}
m := ReadStatus()
for i := 0; i < len(m); i++ {
as = append(as, Post{Tweetid: m[i][0], Username: currentuser, Status: m[i][1]})
}
a = User{Username: currentuser}
for i := 0; i < len(m); i++ {
a.Posts = append(a.Posts, &as[i])
}
renderTemplate(w, "home", "homepage", a)
} else {
http.Redirect(w, r, "/", 302)
}
}
func usertweetHandler(w http.ResponseWriter, r *http.Request) {
AddUser.Username = getUserName(r)
AddTweet = r.FormValue("twt")
InsertTweetData()
http.Redirect(w, r, "/home", 302)
}
func deleteHandler(w http.ResponseWriter, r *http.Request) {
currentuser = getUserName(r)
postvalue = r.PostFormValue("xdel")
DeleteTweet()
http.Redirect(w, r, "/home", 302)
}
func editHandler(w http.ResponseWriter, r *http.Request) {
statusid = r.PostFormValue("xedit")
as := Post{Tweetid: statusid, Status: ReadSingleStatus()}
a := User{Posts: []*Post{&as}}
renderTemplate(w, "edit", "editpage", a)
}
func saveHandler(w http.ResponseWriter, r *http.Request) {
statusid = r.PostFormValue("xsave")
settweet = r.PostFormValue("textedit")
EditTweet()
http.Redirect(w, r, "/home", 302)
}
var cookieHandler = securecookie.New(
securecookie.GenerateRandomKey(64),
securecookie.GenerateRandomKey(32))
func getUserName(r *http.Request) (currentuser string) {
if cookie, err := r.Cookie("session"); err == nil {
cookieValue := make(map[string]string)
if err = cookieHandler.Decode("session", cookie.Value, &cookieValue); err == nil {
currentuser = cookieValue["name"]
}
}
return
}
func setSession(userName string, w http.ResponseWriter) {
value := map[string]string{
"name": userName,
}
if encoded, err := cookieHandler.Encode("session", value); err == nil {
cookie := &http.Cookie{
Name: "session",
Value: encoded,
Path: "/",
}
http.SetCookie(w, cookie)
}
}
func clearSession(r http.ResponseWriter) {
cookie := &http.Cookie{
Name: "session",
Value: "",
Path: "/",
MaxAge: -1,
}
http.SetCookie(r, cookie)
}
func renderTemplate(w http.ResponseWriter, tmpl string, def string, x User) {
t := template.Must(template.New("tele").ParseFiles("layout/" + tmpl + ".html"))
if err := t.ExecuteTemplate(w, def, x); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
var router = mux.NewRouter()
func main() {
db, err = sql.Open("mysql", os.Getenv("DB_USERNAME")+":"+os.Getenv("DB_PASSWORD")+"@tcp("+os.Getenv("DB_CLEARDB")+":3306)/"+os.Getenv("DB_NAME"))
if err != nil {
log.Fatal(err)
}
defer db.Close()
router.HandleFunc("/", logHandler)
router.HandleFunc("/login", loginHandler)
router.HandleFunc("/home", homeHandler)
router.HandleFunc("/home/tweets", usertweetHandler).Methods("POST")
router.HandleFunc("/logout", logoutHandler).Methods("POST")
router.HandleFunc("/home/delete", deleteHandler).Methods("POST")
router.HandleFunc("/home/edit", editHandler).Methods("POST")
router.HandleFunc("/home/save", saveHandler).Methods("POST")
router.PathPrefix("/").Handler(http.FileServer(http.Dir("./layout/")))
http.Handle("/", router)
err := http.ListenAndServe(":"+os.Getenv("PORT"), nil)
if err != nil {
panic(err)
}
}
//to revisit lousy error handling again