added csrf token

This commit is contained in:
Suraj Patil 2016-01-18 06:32:15 +05:30
parent f4c07340a2
commit afe0ab81ee
3 changed files with 24 additions and 11 deletions

View File

@ -122,8 +122,8 @@ nav .glyphicon:hover{
NotesFeed NotesFeed
-------------------------------------- */ -------------------------------------- */
.noteHeading { .noteHeading {
font-weight:700; font-weight:900;
font-size:15px; font-size:17px;
color:#666666; color:#666666;
margin-bottom:0px; margin-bottom:0px;
padding-bottom:5px; padding-bottom:5px;

View File

@ -14,4 +14,5 @@ type Context struct {
Navigation string Navigation string
Search string Search string
Message string Message string
CSRFToken string
} }

View File

@ -9,6 +9,7 @@ import (
"os" "os"
"strconv" "strconv"
"strings" "strings"
"time"
"text/template" "text/template"
) )
@ -63,8 +64,12 @@ func ShowAllTasksFunc(w http.ResponseWriter, r *http.Request) {
if message != "" { if message != "" {
context.Message = message context.Message = message
} }
homeTemplate.Execute(w, context) context.CSRFToken = "abcde"
message = "" 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 { } else {
message = "Method not allowed" message = "Method not allowed"
http.Redirect(w, r, "/", http.StatusFound) 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) { func AddTaskFunc(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" { // Will work only for GET requests, will redirect to home if r.Method == "POST" { // Will work only for GET requests, will redirect to home
r.ParseForm() r.ParseForm()
title := r.Form.Get("title") title := template.HTMLEscapeString(r.Form.Get("title"))
content := r.Form.Get("content") content := template.HTMLEscapeString(r.Form.Get("content"))
truth := db.AddTask(title, content) formToken := template.HTMLEscapeString(r.Form.Get("CSRFToken"))
if truth != nil { cookie, _ := r.Cookie("csrftoken")
message = "Error adding task" log.Println(cookie)
} else { log.Println(formToken)
message = "Task added" 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 { } else {
message = "Method not allowed" message = "Method not allowed"
http.Redirect(w, r, "/", http.StatusFound) http.Redirect(w, r, "/", http.StatusFound)