From afe0ab81ee79f39263aee8f9fdb1359a760f528b Mon Sep 17 00:00:00 2001 From: Suraj Patil Date: Mon, 18 Jan 2016 06:32:15 +0530 Subject: [PATCH] added csrf token --- public/static/css/styles.css | 4 ++-- types/types.go | 1 + views/views.go | 30 +++++++++++++++++++++--------- 3 files changed, 24 insertions(+), 11 deletions(-) diff --git a/public/static/css/styles.css b/public/static/css/styles.css index 23f9639..ba3e032 100644 --- a/public/static/css/styles.css +++ b/public/static/css/styles.css @@ -122,8 +122,8 @@ nav .glyphicon:hover{ NotesFeed -------------------------------------- */ .noteHeading { - font-weight:700; - font-size:15px; + font-weight:900; + font-size:17px; color:#666666; margin-bottom:0px; padding-bottom:5px; diff --git a/types/types.go b/types/types.go index 9e06fc3..473717d 100644 --- a/types/types.go +++ b/types/types.go @@ -14,4 +14,5 @@ type Context struct { Navigation string Search string Message string + CSRFToken string } diff --git a/views/views.go b/views/views.go index 7b6189e..9180df1 100644 --- a/views/views.go +++ b/views/views.go @@ -9,6 +9,7 @@ import ( "os" "strconv" "strings" + "time" "text/template" ) @@ -63,8 +64,12 @@ func ShowAllTasksFunc(w http.ResponseWriter, r *http.Request) { if message != "" { context.Message = message } - homeTemplate.Execute(w, context) + context.CSRFToken = "abcde" message = "" + expiration := time.Now().Add(365 * 24 * time.Hour) + cookie := http.Cookie{Name: "csrftoken",Value:"abcd",Expires:expiration} + http.SetCookie(w, &cookie) + homeTemplate.Execute(w, context) } else { message = "Method not allowed" http.Redirect(w, r, "/", http.StatusFound) @@ -104,15 +109,22 @@ func SearchTaskFunc(w http.ResponseWriter, r *http.Request) { func AddTaskFunc(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { // Will work only for GET requests, will redirect to home r.ParseForm() - title := r.Form.Get("title") - content := r.Form.Get("content") - truth := db.AddTask(title, content) - if truth != nil { - message = "Error adding task" - } else { - message = "Task added" + title := template.HTMLEscapeString(r.Form.Get("title")) + content := template.HTMLEscapeString(r.Form.Get("content")) + formToken := template.HTMLEscapeString(r.Form.Get("CSRFToken")) + cookie, _ := r.Cookie("csrftoken") + log.Println(cookie) + log.Println(formToken) + if formToken == cookie.Value and title != nil and content!=nil{ + truth := db.AddTask(title, content) + if truth != nil { + message = "Error adding task" + } else { + message = "Task added" + } + http.Redirect(w, r, "/", http.StatusFound) } - http.Redirect(w, r, "/", http.StatusFound) + } else { message = "Method not allowed" http.Redirect(w, r, "/", http.StatusFound)