app redirects to login page is user isn't authenticated

This commit is contained in:
Suraj Patil 2016-05-09 23:06:35 +05:30
parent eb1bf99924
commit dacbef54e4
4 changed files with 370 additions and 338 deletions

View File

@ -22,178 +22,187 @@ import (
// UploadedFileHandler is used to handle the uploaded file related requests // UploadedFileHandler is used to handle the uploaded file related requests
func UploadedFileHandler(w http.ResponseWriter, r *http.Request) { func UploadedFileHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" && sessions.IsLoggedIn(r) { if sessions.IsLoggedIn(r) {
token := r.URL.Path[len("/files/"):] if r.Method == "GET" {
token := r.URL.Path[len("/files/"):]
//file, err := db.GetFileName(token) //file, err := db.GetFileName(token)
//if err != nil { //if err != nil {
log.Println("serving file ./files/" + token) log.Println("serving file ./files/" + token)
http.ServeFile(w, r, "./files/"+token) http.ServeFile(w, r, "./files/"+token)
//} //}
}
} }
} }
//AddTaskFunc is used to handle the addition of new task, "/add" URL //AddTaskFunc is used to handle the addition of new task, "/add" URL
func AddTaskFunc(w http.ResponseWriter, r *http.Request) { func AddTaskFunc(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" && sessions.IsLoggedIn(r) { // Will work only for POST requests, will redirect to home if sessions.IsLoggedIn(r) {
var filelink string // will store the html when we have files to be uploaded, appened to the note content if r.Method == "POST" { // Will work only for POST requests, will redirect to home
r.ParseForm() var filelink string // will store the html when we have files to be uploaded, appened to the note content
file, handler, err := r.FormFile("uploadfile") r.ParseForm()
if err != nil && handler != nil { file, handler, err := r.FormFile("uploadfile")
//Case executed when file is uploaded and yet an error occurs if err != nil && handler != nil {
log.Println(err) //Case executed when file is uploaded and yet an error occurs
message = "Error uploading file" log.Println(err)
http.Redirect(w, r, "/", http.StatusInternalServerError) message = "Error uploading file"
}
taskPriority, priorityErr := strconv.Atoi(r.FormValue("priority"))
if priorityErr != nil {
log.Print(priorityErr)
message = "Bad task priority"
http.Redirect(w, r, "/", http.StatusInternalServerError)
}
priorityList := []int{1, 2, 3}
found := false
for _, priority := range priorityList {
if taskPriority == priority {
found = true
}
}
//If someone gives us incorrect priority number, we give the priority
//to that task as 1 i.e. Low
if !found {
taskPriority = 1
}
category := r.FormValue("category")
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")
if formToken == cookie.Value {
if handler != nil {
// this will be executed whenever a file is uploaded
r.ParseMultipartForm(32 << 20) //defined maximum size of file
defer file.Close()
randomFileName := md5.New()
io.WriteString(randomFileName, strconv.FormatInt(time.Now().Unix(), 10))
io.WriteString(randomFileName, handler.Filename)
token := fmt.Sprintf("%x", randomFileName.Sum(nil))
f, err := os.OpenFile("./files/"+token, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
log.Println(err)
return
}
defer f.Close()
io.Copy(f, file)
if strings.HasSuffix(handler.Filename, ".png") || strings.HasSuffix(handler.Filename, ".jpg") {
filelink = "<br> <img src='/files/" + token + "'/>"
} else {
filelink = "<br> <a href=/files/" + token + ">" + handler.Filename + "</a>"
}
content = content + filelink
fileTruth := db.AddFile(handler.Filename, token)
if fileTruth != nil {
message = "Error adding filename in db"
log.Println("error adding task to db")
}
}
taskTruth := db.AddTask(title, content, category, taskPriority)
if taskTruth != nil {
message = "Error adding task"
log.Println("error adding task to db")
http.Redirect(w, r, "/", http.StatusInternalServerError) http.Redirect(w, r, "/", http.StatusInternalServerError)
} else {
message = "Task added"
log.Println("added task to db")
http.Redirect(w, r, "/", http.StatusFound)
} }
} else {
log.Println("CSRF mismatch")
message = "Server Error"
http.Redirect(w, r, "/", http.StatusInternalServerError)
}
taskPriority, priorityErr := strconv.Atoi(r.FormValue("priority"))
if priorityErr != nil {
log.Print(priorityErr)
message = "Bad task priority"
http.Redirect(w, r, "/", http.StatusInternalServerError)
}
priorityList := []int{1, 2, 3}
found := false
for _, priority := range priorityList {
if taskPriority == priority {
found = true
}
}
//If someone gives us incorrect priority number, we give the priority
//to that task as 1 i.e. Low
if !found {
taskPriority = 1
}
category := r.FormValue("category")
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")
if formToken == cookie.Value {
if handler != nil {
// this will be executed whenever a file is uploaded
r.ParseMultipartForm(32 << 20) //defined maximum size of file
defer file.Close()
randomFileName := md5.New()
io.WriteString(randomFileName, strconv.FormatInt(time.Now().Unix(), 10))
io.WriteString(randomFileName, handler.Filename)
token := fmt.Sprintf("%x", randomFileName.Sum(nil))
f, err := os.OpenFile("./files/"+token, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
log.Println(err)
return
}
defer f.Close()
io.Copy(f, file)
if strings.HasSuffix(handler.Filename, ".png") || strings.HasSuffix(handler.Filename, ".jpg") {
filelink = "<br> <img src='/files/" + token + "'/>"
} else {
filelink = "<br> <a href=/files/" + token + ">" + handler.Filename + "</a>"
}
content = content + filelink
fileTruth := db.AddFile(handler.Filename, token)
if fileTruth != nil {
message = "Error adding filename in db"
log.Println("error adding task to db")
}
}
taskTruth := db.AddTask(title, content, category, taskPriority)
if taskTruth != nil {
message = "Error adding task"
log.Println("error adding task to db")
http.Redirect(w, r, "/", http.StatusInternalServerError)
} else {
message = "Task added"
log.Println("added task to db")
http.Redirect(w, r, "/", http.StatusFound)
}
} else {
log.Println("CSRF mismatch")
message = "Server Error"
http.Redirect(w, r, "/", http.StatusInternalServerError)
}
}
} else { } else {
message = "Method not allowed" http.Redirect(w, r, "/login/", 302)
http.Redirect(w, r, "/", http.StatusFound)
} }
} }
//AddCategoryFunc used to add new categories to the database //AddCategoryFunc used to add new categories to the database
func AddCategoryFunc(w http.ResponseWriter, r *http.Request) { func AddCategoryFunc(w http.ResponseWriter, r *http.Request) {
r.ParseForm() if sessions.IsLoggedIn(r) {
category := r.Form.Get("category") r.ParseForm()
if strings.Trim(category, " ") != "" { category := r.Form.Get("category")
err := db.AddCategory(category) if strings.Trim(category, " ") != "" {
if err != nil { err := db.AddCategory(category)
message = "Error adding category" if err != nil {
http.Redirect(w, r, "/", http.StatusBadRequest) message = "Error adding category"
} else { http.Redirect(w, r, "/", http.StatusBadRequest)
message = "Added category" } else {
http.Redirect(w, r, "/", http.StatusFound) message = "Added category"
http.Redirect(w, r, "/", http.StatusFound)
}
} }
} else { } else {
message = "Invalid Category Name" http.Redirect(w, r, "/login/", 302)
http.Redirect(w, r, "/", http.StatusBadRequest)
} }
} }
//EditTaskFunc is used to edit tasks, handles "/edit/" URL //EditTaskFunc is used to edit tasks, handles "/edit/" URL
func EditTaskFunc(w http.ResponseWriter, r *http.Request) { func EditTaskFunc(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" && sessions.IsLoggedIn(r) { if sessions.IsLoggedIn(r) {
id, err := strconv.Atoi(r.URL.Path[len("/edit/"):]) if r.Method == "GET" {
if err != nil { id, err := strconv.Atoi(r.URL.Path[len("/edit/"):])
log.Println(err)
http.Redirect(w, r, "/", http.StatusBadRequest)
} else {
redirectUrl := utils.GetRedirectUrl(r.Referer())
task, err := db.GetTaskByID(id)
categories := db.GetCategories()
task.Categories = categories
task.Referer = redirectUrl
if err != nil { if err != nil {
task.Message = "Error fetching Tasks" log.Println(err)
http.Redirect(w, r, "/", http.StatusBadRequest)
} else {
redirectURL := utils.GetRedirectUrl(r.Referer())
task, err := db.GetTaskByID(id)
categories := db.GetCategories()
task.Categories = categories
task.Referer = redirectURL
if err != nil {
task.Message = "Error fetching Tasks"
}
editTemplate.Execute(w, task)
} }
editTemplate.Execute(w, task)
} }
} else { } else {
message = "Method not allowed" http.Redirect(w, r, "/login/", http.StatusFound)
http.Redirect(w, r, "/", http.StatusFound)
} }
} }
//AddCommentFunc will be used //AddCommentFunc will be used
func AddCommentFunc(w http.ResponseWriter, r *http.Request) { func AddCommentFunc(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" && sessions.IsLoggedIn(r) { if sessions.IsLoggedIn(r) {
r.ParseForm() if r.Method == "POST" {
text := r.Form.Get("commentText") r.ParseForm()
id := r.Form.Get("taskID") text := r.Form.Get("commentText")
id := r.Form.Get("taskID")
idInt, err := strconv.Atoi(id) idInt, err := strconv.Atoi(id)
if (err != nil) || (text == "") { if (err != nil) || (text == "") {
log.Println("unable to convert into integer") log.Println("unable to convert into integer")
message = "Error adding comment" message = "Error adding comment"
} else {
err = db.AddComments(idInt, text)
if err != nil {
log.Println("unable to insert into db")
message = "Comment not added"
} else { } else {
message = "Comment added" err = db.AddComments(idInt, text)
if err != nil {
log.Println("unable to insert into db")
message = "Comment not added"
} else {
message = "Comment added"
}
} }
http.Redirect(w, r, "/", http.StatusFound)
} }
} else {
http.Redirect(w, r, "/", http.StatusFound) http.Redirect(w, r, "/login", 302)
} }
} }

View File

@ -18,138 +18,150 @@ import (
func TrashTaskFunc(w http.ResponseWriter, r *http.Request) { func TrashTaskFunc(w http.ResponseWriter, r *http.Request) {
//for best UX we want the user to be returned to the page making //for best UX we want the user to be returned to the page making
//the delete transaction, we use the r.Referer() function to get the link //the delete transaction, we use the r.Referer() function to get the link
redirectUrl := utils.GetRedirectUrl(r.Referer()) redirectURL := utils.GetRedirectUrl(r.Referer())
if r.Method == "GET" && sessions.IsLoggedIn(r) { if sessions.IsLoggedIn(r) {
id, err := strconv.Atoi(r.URL.Path[len("/trash/"):]) if r.Method == "GET" {
if err != nil { id, err := strconv.Atoi(r.URL.Path[len("/trash/"):])
log.Println("TrashTaskFunc", err)
message = "Incorrect command"
http.Redirect(w, r, redirectUrl, http.StatusFound)
} else {
err = db.TrashTask(id)
if err != nil { if err != nil {
message = "Error trashing task" log.Println("TrashTaskFunc", err)
message = "Incorrect command"
http.Redirect(w, r, redirectURL, http.StatusFound)
} else { } else {
message = "Task trashed" err = db.TrashTask(id)
if err != nil {
message = "Error trashing task"
} else {
message = "Task trashed"
}
http.Redirect(w, r, redirectURL, http.StatusFound)
} }
http.Redirect(w, r, redirectUrl, http.StatusFound)
} }
} else { } else {
message = "Method not allowed" http.Redirect(w, r, "/login/", 302)
http.Redirect(w, r, redirectUrl, http.StatusFound)
} }
} }
//RestoreTaskFunc is used to restore task from trash, handles "/restore/" URL //RestoreTaskFunc is used to restore task from trash, handles "/restore/" URL
func RestoreTaskFunc(w http.ResponseWriter, r *http.Request) { func RestoreTaskFunc(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" && sessions.IsLoggedIn(r) { if sessions.IsLoggedIn(r) {
id, err := strconv.Atoi(r.URL.Path[len("/restore/"):]) if r.Method == "GET" {
if err != nil { id, err := strconv.Atoi(r.URL.Path[len("/restore/"):])
log.Println(err)
http.Redirect(w, r, "/deleted", http.StatusBadRequest)
} else {
err = db.RestoreTask(id)
if err != nil { if err != nil {
message = "Restore failed" log.Println(err)
http.Redirect(w, r, "/deleted", http.StatusBadRequest)
} else { } else {
message = "Task restored" err = db.RestoreTask(id)
if err != nil {
message = "Restore failed"
} else {
message = "Task restored"
}
http.Redirect(w, r, "/deleted/", http.StatusFound)
} }
http.Redirect(w, r, "/deleted/", http.StatusFound)
} }
} else { } else {
message = "Method not allowed" http.Redirect(w, r, "/login/", 302)
http.Redirect(w, r, "/", http.StatusFound)
} }
} }
//DeleteTaskFunc is used to delete a task, trash = move to recycle bin, delete = permanent delete //DeleteTaskFunc is used to delete a task, trash = move to recycle bin, delete = permanent delete
func DeleteTaskFunc(w http.ResponseWriter, r *http.Request) { func DeleteTaskFunc(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" && sessions.IsLoggedIn(r) { if sessions.IsLoggedIn(r) {
id := r.URL.Path[len("/delete/"):] if r.Method == "GET" {
if id == "all" { id := r.URL.Path[len("/delete/"):]
err := db.DeleteAll() if id == "all" {
if err != nil { err := db.DeleteAll()
message = "Error deleting tasks"
http.Redirect(w, r, "/", http.StatusInternalServerError)
}
http.Redirect(w, r, "/", http.StatusFound)
} else {
id, err := strconv.Atoi(id)
if err != nil {
log.Println(err)
http.Redirect(w, r, "/", http.StatusBadRequest)
} else {
err = db.DeleteTask(id)
if err != nil { if err != nil {
message = "Error deleting task" message = "Error deleting tasks"
} else { http.Redirect(w, r, "/", http.StatusInternalServerError)
message = "Task deleted" }
http.Redirect(w, r, "/", http.StatusFound)
} else {
id, err := strconv.Atoi(id)
if err != nil {
log.Println(err)
http.Redirect(w, r, "/", http.StatusBadRequest)
} else {
err = db.DeleteTask(id)
if err != nil {
message = "Error deleting task"
} else {
message = "Task deleted"
}
http.Redirect(w, r, "/deleted", http.StatusFound)
} }
http.Redirect(w, r, "/deleted", http.StatusFound)
} }
} }
} else { } else {
message = "Method not allowed" http.Redirect(w, r, "/login/", 302)
http.Redirect(w, r, "/", http.StatusFound)
} }
} }
//RestoreFromCompleteFunc restores the task from complete to pending //RestoreFromCompleteFunc restores the task from complete to pending
func RestoreFromCompleteFunc(w http.ResponseWriter, r *http.Request) { func RestoreFromCompleteFunc(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" && sessions.IsLoggedIn(r) { if sessions.IsLoggedIn(r) {
id, err := strconv.Atoi(r.URL.Path[len("/incomplete/"):]) if r.Method == "GET" {
if err != nil { id, err := strconv.Atoi(r.URL.Path[len("/incomplete/"):])
log.Println(err)
http.Redirect(w, r, "/completed", http.StatusBadRequest)
} else {
err = db.RestoreTaskFromComplete(id)
if err != nil { if err != nil {
message = "Restore failed" log.Println(err)
http.Redirect(w, r, "/completed", http.StatusBadRequest)
} else { } else {
message = "Task restored" err = db.RestoreTaskFromComplete(id)
if err != nil {
message = "Restore failed"
} else {
message = "Task restored"
}
http.Redirect(w, r, "/completed", http.StatusFound)
} }
http.Redirect(w, r, "/completed", http.StatusFound)
} }
} else { } else {
message = "Method not allowed" http.Redirect(w, r, "/login/", 302)
http.Redirect(w, r, "/completed", http.StatusFound)
} }
} }
//DeleteCategoryFunc will delete any category //DeleteCategoryFunc will delete any category
func DeleteCategoryFunc(w http.ResponseWriter, r *http.Request) { func DeleteCategoryFunc(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" && sessions.IsLoggedIn(r) { if sessions.IsLoggedIn(r) {
categoryName := r.URL.Path[len("/del-category/"):] if r.Method == "GET" {
err := db.DeleteCategoryByName(categoryName) categoryName := r.URL.Path[len("/del-category/"):]
if err != nil { err := db.DeleteCategoryByName(categoryName)
message = "error deleting category" if err != nil {
} else { message = "error deleting category"
message = "Category " + categoryName + " deleted" } else {
} message = "Category " + categoryName + " deleted"
}
http.Redirect(w, r, "/", http.StatusFound) http.Redirect(w, r, "/", http.StatusFound)
}
} else {
http.Redirect(w, r, "/login/", 302)
} }
} }
//DeleteCommentFunc will delete any category //DeleteCommentFunc will delete any category
func DeleteCommentFunc(w http.ResponseWriter, r *http.Request) { func DeleteCommentFunc(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" && sessions.IsLoggedIn(r) { if sessions.IsLoggedIn(r) {
id := r.URL.Path[len("/del-comment/"):] if r.Method == "GET" {
commentID, err := strconv.Atoi(id) id := r.URL.Path[len("/del-comment/"):]
if err != nil { commentID, err := strconv.Atoi(id)
http.Redirect(w, r, "/", http.StatusBadRequest) if err != nil {
return http.Redirect(w, r, "/", http.StatusBadRequest)
return
}
err = db.DeleteCommentByID(commentID)
if err != nil {
message = "comment not deleted"
} else {
message = "comment deleted"
}
http.Redirect(w, r, "/", http.StatusFound)
} }
} else {
err = db.DeleteCommentByID(commentID) http.Redirect(w, r, "/login/", 302)
if err != nil {
message = "comment not deleted"
} else {
message = "comment deleted"
}
http.Redirect(w, r, "/", http.StatusFound)
} }
} }

View File

@ -56,92 +56,98 @@ func PopulateTemplates() {
//CompleteTaskFunc is used to show the complete tasks, handles "/completed/" url //CompleteTaskFunc is used to show the complete tasks, handles "/completed/" url
func CompleteTaskFunc(w http.ResponseWriter, r *http.Request) { func CompleteTaskFunc(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" && sessions.IsLoggedIn(r) { if sessions.IsLoggedIn(r) {
redirectURL := utils.GetRedirectUrl(r.Referer()) if r.Method == "GET" {
id, err := strconv.Atoi(r.URL.Path[len("/complete/"):]) redirectURL := utils.GetRedirectUrl(r.Referer())
if err != nil { id, err := strconv.Atoi(r.URL.Path[len("/complete/"):])
log.Println(err)
} else {
err = db.CompleteTask(id)
if err != nil { if err != nil {
message = "Complete task failed" log.Println(err)
} else { } else {
message = "Task marked complete" err = db.CompleteTask(id)
if err != nil {
message = "Complete task failed"
} else {
message = "Task marked complete"
}
http.Redirect(w, r, redirectURL, http.StatusFound)
} }
http.Redirect(w, r, redirectURL, http.StatusFound)
} }
} else { } else {
message = "Method not allowed" http.Redirect(w, r, "/login/", 302)
http.Redirect(w, r, "/", http.StatusFound)
} }
} }
//SearchTaskFunc is used to handle the /search/ url, handles the search function //SearchTaskFunc is used to handle the /search/ url, handles the search function
func SearchTaskFunc(w http.ResponseWriter, r *http.Request) { func SearchTaskFunc(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" && sessions.IsLoggedIn(r) { if sessions.IsLoggedIn(r) {
r.ParseForm() if r.Method == "POST" {
query := r.Form.Get("query") r.ParseForm()
query := r.Form.Get("query")
context := db.SearchTask(query) context := db.SearchTask(query)
categories := db.GetCategories() categories := db.GetCategories()
context.Categories = categories context.Categories = categories
searchTemplate.Execute(w, context) searchTemplate.Execute(w, context)
}
} else { } else {
message = "Method not allowed" http.Redirect(w, r, "/login/", 302)
http.Redirect(w, r, "/", http.StatusFound)
} }
} }
//UpdateTaskFunc is used to update a task, handes "/update/" URL //UpdateTaskFunc is used to update a task, handes "/update/" URL
func UpdateTaskFunc(w http.ResponseWriter, r *http.Request) { func UpdateTaskFunc(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" && sessions.IsLoggedIn(r) { if sessions.IsLoggedIn(r) {
r.ParseForm() if r.Method == "POST" {
id, err := strconv.Atoi(r.Form.Get("id")) r.ParseForm()
if err != nil { id, err := strconv.Atoi(r.Form.Get("id"))
log.Println(err) if err != nil {
log.Println(err)
}
category := r.Form.Get("category")
title := r.Form.Get("title")
content := r.Form.Get("content")
priority, err := strconv.Atoi(r.Form.Get("priority"))
if err != nil {
log.Println(err)
}
err = db.UpdateTask(id, title, content, category, priority)
if err != nil {
message = "Error updating task"
} else {
message = "Task updated"
log.Println(message)
}
http.Redirect(w, r, "/", http.StatusFound)
} }
category := r.Form.Get("category")
title := r.Form.Get("title")
content := r.Form.Get("content")
priority, err := strconv.Atoi(r.Form.Get("priority"))
if err != nil {
log.Println(err)
}
err = db.UpdateTask(id, title, content, category, priority)
if err != nil {
message = "Error updating task"
} else {
message = "Task updated"
log.Println(message)
}
http.Redirect(w, r, "/", http.StatusFound)
} else { } else {
message = "Method not allowed" http.Redirect(w, r, "/login/", 302)
http.Redirect(w, r, "/", http.StatusFound)
} }
} }
//UpdateCategoryFunc is used to update a task, handes "/upd-category/" URL //UpdateCategoryFunc is used to update a task, handes "/upd-category/" URL
func UpdateCategoryFunc(w http.ResponseWriter, r *http.Request) { func UpdateCategoryFunc(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" && sessions.IsLoggedIn(r) { if sessions.IsLoggedIn(r) {
var redirectURL string if r.Method == "POST" {
r.ParseForm() var redirectURL string
oldName := r.URL.Path[len("/upd-category/"):] r.ParseForm()
newName := r.Form.Get("catname") oldName := r.URL.Path[len("/upd-category/"):]
newName := r.Form.Get("catname")
err := db.UpdateCategoryByName(oldName, newName) err := db.UpdateCategoryByName(oldName, newName)
if err != nil { if err != nil {
message = "error updating category" message = "error updating category"
log.Println("not updated category " + oldName) log.Println("not updated category " + oldName)
redirectURL = "/category/" + oldName redirectURL = "/category/" + oldName
} else { } else {
message = "cat " + oldName + " -> " + newName message = "cat " + oldName + " -> " + newName
redirectURL = "/category/" + newName redirectURL = "/category/" + newName
}
log.Println("redirecting to " + redirectURL)
http.Redirect(w, r, redirectURL, http.StatusFound)
} }
log.Println("redirecting to " + redirectURL) } else {
http.Redirect(w, r, redirectURL, http.StatusFound) http.Redirect(w, r, "/login/", 302)
} }
} }

View File

@ -25,87 +25,92 @@ var err error
//ShowAllTasksFunc is used to handle the "/" URL which is the default ons //ShowAllTasksFunc is used to handle the "/" URL which is the default ons
//TODO add http404 error //TODO add http404 error
func ShowAllTasksFunc(w http.ResponseWriter, r *http.Request) { func ShowAllTasksFunc(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" && sessions.IsLoggedIn(r) { if sessions.IsLoggedIn(r) == true {
context, err := db.GetTasks("pending", "") if r.Method == "GET" {
categories := db.GetCategories() context, err := db.GetTasks("pending", "")
if err != nil { categories := db.GetCategories()
http.Redirect(w, r, "/", http.StatusInternalServerError) if err != nil {
http.Redirect(w, r, "/", http.StatusInternalServerError)
} else {
if message != "" {
context.Message = message
}
context.CSRFToken = "abcd"
context.Categories = categories
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)
}
} }
if message != "" {
context.Message = message
}
context.CSRFToken = "abcd"
context.Categories = categories
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" http.Redirect(w, r, "/login/", 302)
http.Redirect(w, r, "/", http.StatusFound)
} }
} }
//ShowTrashTaskFunc is used to handle the "/trash" URL which is used to show the deleted tasks //ShowTrashTaskFunc is used to handle the "/trash" URL which is used to show the deleted tasks
func ShowTrashTaskFunc(w http.ResponseWriter, r *http.Request) { func ShowTrashTaskFunc(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" && sessions.IsLoggedIn(r) { if sessions.IsLoggedIn(r) {
context, err := db.GetTasks("deleted", "") if r.Method == "GET" {
categories := db.GetCategories() context, err := db.GetTasks("deleted", "")
context.Categories = categories categories := db.GetCategories()
if err != nil { context.Categories = categories
http.Redirect(w, r, "/trash", http.StatusInternalServerError) if err != nil {
http.Redirect(w, r, "/trash", http.StatusInternalServerError)
}
if message != "" {
context.Message = message
message = ""
}
deletedTemplate.Execute(w, context)
} }
if message != "" {
context.Message = message
message = ""
}
deletedTemplate.Execute(w, context)
} else { } else {
message = "Method not allowed" http.Redirect(w, r, "/login/", 302)
http.Redirect(w, r, "/", http.StatusFound)
} }
} }
//ShowCompleteTasksFunc is used to populate the "/completed/" URL //ShowCompleteTasksFunc is used to populate the "/completed/" URL
func ShowCompleteTasksFunc(w http.ResponseWriter, r *http.Request) { func ShowCompleteTasksFunc(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" && sessions.IsLoggedIn(r) { if sessions.IsLoggedIn(r) {
context, err := db.GetTasks("completed", "") if r.Method == "GET" {
categories := db.GetCategories() context, err := db.GetTasks("completed", "")
context.Categories = categories categories := db.GetCategories()
if err != nil { context.Categories = categories
http.Redirect(w, r, "/completed", http.StatusInternalServerError) if err != nil {
http.Redirect(w, r, "/completed", http.StatusInternalServerError)
}
completedTemplate.Execute(w, context)
} }
completedTemplate.Execute(w, context)
} else { } else {
message = "Method not allowed" http.Redirect(w, r, "/login/", 302)
http.Redirect(w, r, "/", http.StatusFound)
} }
} }
//ShowCategoryFunc will populate the /category/<id> URL which shows all the tasks related //ShowCategoryFunc will populate the /category/<id> URL which shows all the tasks related
// to that particular category // to that particular category
func ShowCategoryFunc(w http.ResponseWriter, r *http.Request) { func ShowCategoryFunc(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" && sessions.IsLoggedIn(r) { if sessions.IsLoggedIn(r) {
category := r.URL.Path[len("/category/"):] if r.Method == "GET" && sessions.IsLoggedIn(r) {
context, err := db.GetTasks("", category) category := r.URL.Path[len("/category/"):]
categories := db.GetCategories() context, err := db.GetTasks("", category)
categories := db.GetCategories()
if err != nil { if err != nil {
http.Redirect(w, r, "/", http.StatusInternalServerError) http.Redirect(w, r, "/", http.StatusInternalServerError)
}
if message != "" {
context.Message = message
}
context.CSRFToken = "abcd"
context.Categories = categories
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)
} }
if message != "" {
context.Message = message
}
context.CSRFToken = "abcd"
context.Categories = categories
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" http.Redirect(w, r, "/login/", 302)
http.Redirect(w, r, "/", http.StatusFound)
} }
} }