-
Notifications
You must be signed in to change notification settings - Fork 0
/
homePostBoard.go
233 lines (214 loc) · 5.44 KB
/
homePostBoard.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
package homepostboard
import (
"crypto/md5"
"database/sql"
"fmt"
"html/template"
"io"
"log"
"net/http"
"strconv"
"strings"
"time"
"github.com/gorilla/sessions"
_ "github.com/mattn/go-sqlite3"
)
//TODO:UID is for IP and Name is for requestBody
type PostData struct {
UId int
UserName string
Content string
Created string
}
type PostContext struct {
Context []PostData
}
var database *sql.DB
var err error
var Store = sessions.NewCookieStore([]byte("hpb"))
func (p *PostData) WriteDb() {
stmt, err := database.Prepare("INSERT INTO postdata(username, content, created) VALUES(?,?,?)")
if err != nil {
log.Fatal(err)
}
res, err := stmt.Exec(p.UserName, p.Content, p.Created)
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)
}
log.Printf("ID = %d, affected = %d\n", lastId, rowCnt)
}
func init() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
database, err =
sql.Open("sqlite3", "./postData.db")
if err != nil {
log.Fatal(err)
}
sql_table := `
CREATE TABLE IF NOT EXISTS postdata(
uid INTEGER PRIMARY KEY AUTOINCREMENT,
username VARCHAR(64) NULL,
content VARCHAR(3000) NULL,
created DATE NULL
);
`
_, err := database.Exec(sql_table)
if err != nil {
log.Fatal(err)
}
}
func showPostBoard(pattern string, w http.ResponseWriter) (err error) {
sqlStr := "SELECT " + pattern + " FROM postdata"
rows, err := database.Query(sqlStr)
if err != nil {
log.Fatal(err)
}
var c PostContext
var uid int
var username string
var content string
var created string
for rows.Next() {
err = rows.Scan(&uid, &username, &content, &created)
if err != nil {
log.Fatal(err)
}
p := PostData{UId: uid, UserName: username, Content: content, Created: created}
c.Context = append(c.Context, p)
}
rows.Close()
t, err := template.ParseFiles("./templates/board.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = t.Execute(w, c)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
return
}
//IsAct will check if the user has an active session and return True
func IsAct(r *http.Request) bool {
session, _ := Store.Get(r, "session")
if session.Values["act"] == "true" {
return true
}
return false
}
func tokenCreate() string {
ct := time.Now().Unix()
h := md5.New()
io.WriteString(h, strconv.FormatInt(ct, 10))
token := fmt.Sprintf("%x", h.Sum(nil))
// fmt.Println("token created :", token)
return token
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
session, _ := Store.Get(r, "session")
if session.Values["act"] != "true" {
session.Values["act"] = "true"
err = session.Save(r, w)
if err != nil {
log.Fatal(err)
}
fmt.Println("write the session data")
}
err = showPostBoard("*", w)
if err != nil {
log.Fatal(err)
}
} else if r.Method == "POST" {
session, err := Store.Get(r, "session")
if err != nil {
log.Fatal(err)
}
if session.Values["act"] == "true" {
err = r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
t := time.Now().Format("2006-01-02 15:04:05")
n := strings.Split(r.RemoteAddr, ":")[0] + "-" + strings.TrimLeft(strings.Fields(r.UserAgent())[1], "(")
uname := strings.TrimRight(n, ";")
// fmt.Println("uanme =", uname)
p := PostData{UserName: uname, Content: r.Form["body"][0], Created: t}
p.WriteDb()
err = showPostBoard("*", w)
if err != nil {
log.Fatal(err)
}
// session.Values["username"] = username
} else {
fmt.Println("the session is not active go to root")
http.Redirect(w, r, "/", 302)
}
} else {
http.Error(w, "Unknown HTTP Action", http.StatusInternalServerError)
return
}
}
func AddPostHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
t, err := template.ParseFiles("./templates/addpost.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
token := tokenCreate()
expiration := time.Now().Add(365 * 24 * time.Hour)
cookie := http.Cookie{Name: "csrftoken", Value: token, Expires: expiration}
http.SetCookie(w, &cookie)
err = t.Execute(w, token)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
} else if r.Method == "POST" {
err = r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//
formToken := template.HTMLEscapeString(r.Form.Get("CSRFToken"))
cookie, err := r.Cookie("csrftoken")
if err != nil {
log.Print(err)
return
}
if formToken == cookie.Value {
t := time.Now().Format("2006-01-02 15:04:05")
n := strings.Split(r.RemoteAddr, ":")[0] + "-" + strings.TrimLeft(strings.Fields(r.UserAgent())[1], "(")
uname := strings.TrimRight(n, ";")
// fmt.Println("uanme =", uname)
p := PostData{UserName: uname, Content: r.Form["body"][0], Created: t}
p.WriteDb()
} else {
log.Print("form token mismatch")
}
http.Redirect(w, r, "/", 302)
} else {
log.Print("Unknown request")
http.Redirect(w, r, "/", 302)
}
}
func main() {
defer database.Close()
http.HandleFunc("/addpost/", AddPostHandler)
http.HandleFunc("/", rootHandler)
http.Handle("/static/", http.FileServer(http.Dir("public")))
log.Print("Running the server on port 8091.")
log.Fatal(http.ListenAndServe(":8091", nil))
}