code refactoring

This commit is contained in:
Suraj Patil 2016-09-21 22:10:46 +05:30
parent b1c88a5bc6
commit f34db50464
4 changed files with 333 additions and 283 deletions

View File

@ -22,116 +22,125 @@ 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" { if r.Method != "GET" {
token := r.URL.Path[len("/files/"):] http.Redirect(w, r, "/", http.StatusBadRequest)
return
//file, err := db.GetFileName(token)
//if err != nil {
log.Println("serving file ./files/" + token)
http.ServeFile(w, r, "./files/"+token)
//}
} }
token := r.URL.Path[len("/files/"):]
//file, err := db.GetFileName(token)
//if err != nil {
log.Println("serving file ./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" { // Will work only for POST requests, will redirect to home if r.Method != "POST" { // Will work only for POST requests, will redirect to home
var filelink string // will store the html when we have files to be uploaded, appened to the note content http.Redirect(w, r, "/", http.StatusBadRequest)
r.ParseForm() return
file, handler, err := r.FormFile("uploadfile") }
if err != nil && handler != nil {
//Case executed when file is uploaded and yet an error occurs
log.Println(err)
message = "Error uploading file"
http.Redirect(w, r, "/", http.StatusInternalServerError)
}
taskPriority, priorityErr := strconv.Atoi(r.FormValue("priority")) var filelink string // will store the html when we have files to be uploaded, appened to the note content
r.ParseForm()
file, handler, err := r.FormFile("uploadfile")
if err != nil && handler != nil {
//Case executed when file is uploaded and yet an error occurs
log.Println(err)
message = "Error uploading file"
http.Redirect(w, r, "/", http.StatusInternalServerError)
}
if priorityErr != nil { taskPriority, priorityErr := strconv.Atoi(r.FormValue("priority"))
log.Print(priorityErr)
message = "Bad task priority" if priorityErr != nil {
log.Print(priorityErr)
message = "Bad task priority"
}
priorityList := []int{1, 2, 3}
found := false
for _, priority := range priorityList {
if taskPriority == priority {
found = true
} }
priorityList := []int{1, 2, 3} }
found := false //If someone gives us incorrect priority number, we give the priority
for _, priority := range priorityList { //to that task as 1 i.e. Low
if taskPriority == priority { if !found {
found = true taskPriority = 1
}
var hidden int
hideTimeline := r.FormValue("hide")
if hideTimeline != "" {
hidden = 1
} else {
hidden = 0
}
// dueDate := r.FormValue("dueDate")
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 {
username := sessions.GetCurrentUserName(r)
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()
//If someone gives us incorrect priority number, we give the priority io.Copy(f, file)
//to that task as 1 i.e. Low
if !found {
taskPriority = 1
}
var hidden int
hideTimeline := r.FormValue("hide")
if hideTimeline != "" {
hidden = 1
} else {
hidden = 0
}
// dueDate := r.FormValue("dueDate")
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 strings.HasSuffix(handler.Filename, ".png") || strings.HasSuffix(handler.Filename, ".jpg") {
if formToken == cookie.Value { filelink = "<br> <img src='/files/" + token + "'/>"
username := sessions.GetCurrentUserName(r)
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, username)
if fileTruth != nil {
message = "Error adding filename in db"
log.Println("error adding task to db")
}
}
//taskTruth := db.AddTask(title, content, category, taskPriority, username, dueDate)
taskTruth := db.AddTask(title, content, category, taskPriority, username, hidden)
if taskTruth != nil {
message = "Error adding task"
log.Println("error adding task to db")
http.Redirect(w, r, "/", http.StatusInternalServerError)
} else { } else {
message = "Task added" filelink = "<br> <a href=/files/" + token + ">" + handler.Filename + "</a>"
log.Println("added task to db")
http.Redirect(w, r, "/", http.StatusFound)
} }
} else { content = content + filelink
log.Println("CSRF mismatch")
message = "Server Error"
http.Redirect(w, r, "/", http.StatusInternalServerError)
}
fileTruth := db.AddFile(handler.Filename, token, username)
if fileTruth != nil {
message = "Error adding filename in db"
log.Println("error adding task to db")
}
}
//taskTruth := db.AddTask(title, content, category, taskPriority, username, dueDate)
taskTruth := db.AddTask(title, content, category, taskPriority, username, hidden)
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)
} }
} }
//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) {
if r.Method != "POST" { // We respond only to POST requests, redirect to home for others
http.Redirect(w, r, "/", http.StatusBadRequest)
return
}
r.ParseForm() r.ParseForm()
category := r.Form.Get("category") category := r.Form.Get("category")
if strings.Trim(category, " ") != "" { if strings.Trim(category, " ") != "" {
@ -160,19 +169,19 @@ func EditTaskFunc(w http.ResponseWriter, r *http.Request) {
log.Println(err) log.Println(err)
http.Redirect(w, r, "/", http.StatusBadRequest) http.Redirect(w, r, "/", http.StatusBadRequest)
return return
} else {
redirectURL := utils.GetRedirectUrl(r.Referer())
username := sessions.GetCurrentUserName(r)
task, err := db.GetTaskByID(username, id)
categories := db.GetCategories(username)
task.Categories = categories
task.Referer = redirectURL
if err != nil {
task.Message = "Error fetching Tasks"
}
editTemplate.Execute(w, task)
} }
redirectURL := utils.GetRedirectUrl(r.Referer())
username := sessions.GetCurrentUserName(r)
task, err := db.GetTaskByID(username, id)
categories := db.GetCategories(username)
task.Categories = categories
task.Referer = redirectURL
if err != nil {
task.Message = "Error fetching Tasks"
}
editTemplate.Execute(w, task)
} }
//AddCommentFunc will be used //AddCommentFunc will be used

View File

@ -19,130 +19,154 @@ 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" {
id, err := strconv.Atoi(r.URL.Path[len("/trash/"):]) if r.Method != "GET" {
http.Redirect(w, r, "/", http.StatusBadRequest)
return
}
id, err := strconv.Atoi(r.URL.Path[len("/trash/"):])
if err != nil {
log.Println("TrashTaskFunc", err)
message = "Incorrect command"
http.Redirect(w, r, redirectURL, http.StatusFound)
} else {
username := sessions.GetCurrentUserName(r)
err = db.TrashTask(username, id)
if err != nil { if err != nil {
log.Println("TrashTaskFunc", err) message = "Error trashing task"
message = "Incorrect command"
http.Redirect(w, r, redirectURL, http.StatusFound)
} else { } else {
username := sessions.GetCurrentUserName(r) message = "Task trashed"
err = db.TrashTask(username, 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)
} }
} }
//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" { if r.Method != "GET" {
id, err := strconv.Atoi(r.URL.Path[len("/restore/"):]) http.Redirect(w, r, "/", http.StatusBadRequest)
if err != nil { return
log.Println(err)
http.Redirect(w, r, "/deleted", http.StatusBadRequest)
} else {
username := sessions.GetCurrentUserName(r)
err = db.RestoreTask(username, id)
if err != nil {
message = "Restore failed"
} else {
message = "Task restored"
}
http.Redirect(w, r, "/deleted/", http.StatusFound)
}
} }
id, err := strconv.Atoi(r.URL.Path[len("/restore/"):])
if err != nil {
log.Println(err)
http.Redirect(w, r, "/deleted", http.StatusBadRequest)
} else {
username := sessions.GetCurrentUserName(r)
err = db.RestoreTask(username, id)
if err != nil {
message = "Restore failed"
} else {
message = "Task restored"
}
http.Redirect(w, r, "/deleted/", 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) {
username := sessions.GetCurrentUserName(r) username := sessions.GetCurrentUserName(r)
if r.Method == "GET" { if r.Method != "GET" {
id := r.URL.Path[len("/delete/"):] http.Redirect(w, r, "/", http.StatusBadRequest)
if id == "all" { return
err := db.DeleteAll(username) }
if err != nil {
message = "Error deleting tasks" id := r.URL.Path[len("/delete/"):]
http.Redirect(w, r, "/", http.StatusInternalServerError) if id == "all" {
} err := db.DeleteAll(username)
http.Redirect(w, r, "/", http.StatusFound) if err != nil {
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 { } else {
id, err := strconv.Atoi(id) err = db.DeleteTask(username, id)
if err != nil { if err != nil {
log.Println(err) message = "Error deleting task"
http.Redirect(w, r, "/", http.StatusBadRequest)
} else { } else {
err = db.DeleteTask(username, id) message = "Task deleted"
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)
} }
} }
} }
//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" { if r.Method != "GET" {
id, err := strconv.Atoi(r.URL.Path[len("/incomplete/"):]) http.Redirect(w, r, "/", http.StatusBadRequest)
if err != nil { return
log.Println(err)
http.Redirect(w, r, "/completed", http.StatusBadRequest)
} else {
username := sessions.GetCurrentUserName(r)
err = db.RestoreTaskFromComplete(username, id)
if err != nil {
message = "Restore failed"
} else {
message = "Task restored"
}
http.Redirect(w, r, "/completed", http.StatusFound)
}
} }
id, err := strconv.Atoi(r.URL.Path[len("/incomplete/"):])
if err != nil {
log.Println(err)
http.Redirect(w, r, "/completed", http.StatusBadRequest)
} else {
username := sessions.GetCurrentUserName(r)
err = db.RestoreTaskFromComplete(username, id)
if err != nil {
message = "Restore failed"
} else {
message = "Task restored"
}
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" { if r.Method != "GET" {
categoryName := r.URL.Path[len("/del-category/"):] http.Redirect(w, r, "/", http.StatusBadRequest)
username := sessions.GetCurrentUserName(r) return
err := db.DeleteCategoryByName(username, categoryName)
if err != nil {
message = "error deleting category"
} else {
message = "Category " + categoryName + " deleted"
}
http.Redirect(w, r, "/", http.StatusFound)
} }
categoryName := r.URL.Path[len("/del-category/"):]
username := sessions.GetCurrentUserName(r)
err := db.DeleteCategoryByName(username, categoryName)
if err != nil {
message = "error deleting category"
} else {
message = "Category " + categoryName + " deleted"
}
http.Redirect(w, r, "/", http.StatusFound)
} }
//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" { if r.Method != "GET" {
id := r.URL.Path[len("/del-comment/"):] http.Redirect(w, r, "/", http.StatusBadRequest)
commentID, err := strconv.Atoi(id) return
if err != nil {
http.Redirect(w, r, "/", http.StatusBadRequest)
return
}
username := sessions.GetCurrentUserName(r)
err = db.DeleteCommentByID(username, commentID)
if err != nil {
message = "comment not deleted"
} else {
message = "comment deleted"
}
http.Redirect(w, r, "/", http.StatusFound)
} }
id := r.URL.Path[len("/del-comment/"):]
commentID, err := strconv.Atoi(id)
if err != nil {
http.Redirect(w, r, "/", http.StatusBadRequest)
return
}
username := sessions.GetCurrentUserName(r)
err = db.DeleteCommentByID(username, commentID)
if err != nil {
message = "comment not deleted"
} else {
message = "comment deleted"
}
http.Redirect(w, r, "/", http.StatusFound)
} }

View File

@ -56,117 +56,132 @@ 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" { if r.Method != "GET" {
redirectURL := utils.GetRedirectUrl(r.Referer()) http.Redirect(w, r, "/", http.StatusBadRequest)
id, err := strconv.Atoi(r.URL.Path[len("/complete/"):]) return
if err != nil {
log.Println(err)
} else {
username := sessions.GetCurrentUserName(r)
err = db.CompleteTask(username, id)
if err != nil {
message = "Complete task failed"
} else {
message = "Task marked complete"
}
http.Redirect(w, r, redirectURL, http.StatusFound)
}
} }
redirectURL := utils.GetRedirectUrl(r.Referer())
id, err := strconv.Atoi(r.URL.Path[len("/complete/"):])
if err != nil {
log.Println(err)
} else {
username := sessions.GetCurrentUserName(r)
err = db.CompleteTask(username, id)
if err != nil {
message = "Complete task failed"
} else {
message = "Task marked complete"
}
http.Redirect(w, r, redirectURL, 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" { if r.Method != "POST" {
r.ParseForm() http.Redirect(w, r, "/", http.StatusBadRequest)
query := r.Form.Get("query") return
username := sessions.GetCurrentUserName(r)
context, err := db.SearchTask(username, query)
if err != nil {
log.Println("error fetching search results")
}
categories := db.GetCategories(username)
context.Categories = categories
searchTemplate.Execute(w, context)
} }
r.ParseForm()
query := r.Form.Get("query")
username := sessions.GetCurrentUserName(r)
context, err := db.SearchTask(username, query)
if err != nil {
log.Println("error fetching search results")
}
categories := db.GetCategories(username)
context.Categories = categories
searchTemplate.Execute(w, context)
} }
//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" { if r.Method != "POST" {
r.ParseForm() http.Redirect(w, r, "/", http.StatusBadRequest)
id, err := strconv.Atoi(r.Form.Get("id")) return
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)
}
username := sessions.GetCurrentUserName(r)
var hidden int
hideTimeline := r.FormValue("hide")
if hideTimeline != "" {
hidden = 1
} else {
hidden = 0
}
err = db.UpdateTask(id, title, content, category, priority, username, hidden)
if err != nil {
message = "Error updating task"
} else {
message = "Task updated"
log.Println(message)
}
http.Redirect(w, r, "/", http.StatusFound)
} }
r.ParseForm()
id, err := strconv.Atoi(r.Form.Get("id"))
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)
}
username := sessions.GetCurrentUserName(r)
var hidden int
hideTimeline := r.FormValue("hide")
if hideTimeline != "" {
hidden = 1
} else {
hidden = 0
}
err = db.UpdateTask(id, title, content, category, priority, username, hidden)
if err != nil {
message = "Error updating task"
} else {
message = "Task updated"
log.Println(message)
}
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" { if r.Method != "POST" {
var redirectURL string http.Redirect(w, r, "/", http.StatusBadRequest)
r.ParseForm() return
oldName := r.URL.Path[len("/upd-category/"):]
newName := r.Form.Get("catname")
username := sessions.GetCurrentUserName(r)
err := db.UpdateCategoryByName(username, oldName, newName)
if err != nil {
message = "error updating category"
log.Println("not updated category " + oldName)
redirectURL = "/category/" + oldName
} else {
message = "cat " + oldName + " -> " + newName
redirectURL = "/category/" + newName
}
log.Println("redirecting to " + redirectURL)
http.Redirect(w, r, redirectURL, http.StatusFound)
} }
var redirectURL string
r.ParseForm()
oldName := r.URL.Path[len("/upd-category/"):]
newName := r.Form.Get("catname")
username := sessions.GetCurrentUserName(r)
err := db.UpdateCategoryByName(username, oldName, newName)
if err != nil {
message = "error updating category"
log.Println("not updated category " + oldName)
redirectURL = "/category/" + oldName
} else {
message = "cat " + oldName + " -> " + newName
redirectURL = "/category/" + newName
}
log.Println("redirecting to " + redirectURL)
http.Redirect(w, r, redirectURL, http.StatusFound)
} }
//SignUpFunc will enable new users to sign up to our service //SignUpFunc will enable new users to sign up to our service
func SignUpFunc(w http.ResponseWriter, r *http.Request) { func SignUpFunc(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" { if r.Method != "POST" {
r.ParseForm() http.Redirect(w, r, "/", http.StatusBadRequest)
return
}
r.ParseForm()
username := r.Form.Get("username") username := r.Form.Get("username")
password := r.Form.Get("password") password := r.Form.Get("password")
email := r.Form.Get("email") email := r.Form.Get("email")
log.Println(username, password, email) log.Println(username, password, email)
err := db.CreateUser(username, password, email) err := db.CreateUser(username, password, email)
if err != nil { if err != nil {
http.Error(w, "Unable to sign user up", http.StatusInternalServerError) http.Error(w, "Unable to sign user up", http.StatusInternalServerError)
} else { } else {
http.Redirect(w, r, "/login/", 302) http.Redirect(w, r, "/login/", 302)
}
} }
} }

View File

@ -60,5 +60,7 @@ func LoginFunc(w http.ResponseWriter, r *http.Request) {
} }
log.Print("Invalid user " + username) log.Print("Invalid user " + username)
loginTemplate.Execute(w, nil) loginTemplate.Execute(w, nil)
default:
http.Redirect(w, r, "/login/", http.StatusUnauthorized)
} }
} }