added session handling middleware

This commit is contained in:
Suraj Patil 2016-05-11 22:49:32 +05:30
parent dacbef54e4
commit 9c9c52a025
6 changed files with 351 additions and 419 deletions

42
main.go
View File

@ -15,29 +15,27 @@ import (
func main() { func main() {
values := config.ReadConfig("config.json") values := config.ReadConfig("config.json")
views.PopulateTemplates() views.PopulateTemplates()
http.HandleFunc("/", views.ShowAllTasksFunc) http.HandleFunc("/", views.RequiresLogin(views.ShowAllTasksFunc))
http.HandleFunc("/login/", views.LoginFunc) http.HandleFunc("/login/", views.LoginFunc)
http.HandleFunc("/logout/", views.LogoutFunc) http.HandleFunc("/logout/", views.RequiresLogin(views.LogoutFunc))
http.HandleFunc("/add-category/", views.AddCategoryFunc) http.HandleFunc("/add-category/", views.RequiresLogin(views.AddCategoryFunc))
http.HandleFunc("/add-comment/", views.AddCommentFunc) http.HandleFunc("/add-comment/", views.RequiresLogin(views.AddCommentFunc))
http.HandleFunc("/del-comment/", views.DeleteCommentFunc) http.HandleFunc("/del-comment/", views.RequiresLogin(views.DeleteCommentFunc))
http.HandleFunc("/del-category/", views.DeleteCategoryFunc) http.HandleFunc("/del-category/", views.RequiresLogin(views.DeleteCategoryFunc))
http.HandleFunc("/upd-category/", views.UpdateCategoryFunc) http.HandleFunc("/upd-category/", views.RequiresLogin(views.UpdateCategoryFunc))
http.HandleFunc("/category/", views.ShowCategoryFunc) http.HandleFunc("/category/", views.RequiresLogin(views.ShowCategoryFunc))
http.HandleFunc("/complete/", views.CompleteTaskFunc) http.HandleFunc("/complete/", views.RequiresLogin(views.CompleteTaskFunc))
//delete permanently deletes from db http.HandleFunc("/delete/", views.RequiresLogin(views.DeleteTaskFunc))
http.HandleFunc("/delete/", views.DeleteTaskFunc) http.HandleFunc("/files/", views.RequiresLogin(views.UploadedFileHandler))
http.HandleFunc("/files/", views.UploadedFileHandler) http.HandleFunc("/deleted/", views.RequiresLogin(views.ShowTrashTaskFunc))
http.HandleFunc("/deleted/", views.ShowTrashTaskFunc) http.HandleFunc("/trash/", views.RequiresLogin(views.TrashTaskFunc))
//trash moves to recycle bin http.HandleFunc("/edit/", views.RequiresLogin(views.EditTaskFunc))
http.HandleFunc("/trash/", views.TrashTaskFunc) http.HandleFunc("/completed/", views.RequiresLogin(views.ShowCompleteTasksFunc))
http.HandleFunc("/edit/", views.EditTaskFunc) http.HandleFunc("/restore/", views.RequiresLogin(views.RestoreTaskFunc))
http.HandleFunc("/completed/", views.ShowCompleteTasksFunc) http.HandleFunc("/incomplete/", views.RequiresLogin(views.RestoreFromCompleteFunc))
http.HandleFunc("/restore/", views.RestoreTaskFunc) http.HandleFunc("/add/", views.RequiresLogin(views.AddTaskFunc))
http.HandleFunc("/incomplete/", views.RestoreFromCompleteFunc) http.HandleFunc("/update/", views.RequiresLogin(views.UpdateTaskFunc))
http.HandleFunc("/add/", views.AddTaskFunc) http.HandleFunc("/search/", views.RequiresLogin(views.SearchTaskFunc))
http.HandleFunc("/update/", views.UpdateTaskFunc)
http.HandleFunc("/search/", views.SearchTaskFunc)
//http.HandleFunc("/static/", ServeStaticFunc) //http.HandleFunc("/static/", ServeStaticFunc)
http.Handle("/static/", http.FileServer(http.Dir("public"))) http.Handle("/static/", http.FileServer(http.Dir("public")))
log.Println("running server on ", values.ServerPort) log.Println("running server on ", values.ServerPort)

View File

@ -16,13 +16,11 @@ import (
"time" "time"
"github.com/thewhitetulip/Tasks/db" "github.com/thewhitetulip/Tasks/db"
"github.com/thewhitetulip/Tasks/sessions"
"github.com/thewhitetulip/Tasks/utils" "github.com/thewhitetulip/Tasks/utils"
) )
// 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 sessions.IsLoggedIn(r) {
if r.Method == "GET" { if r.Method == "GET" {
token := r.URL.Path[len("/files/"):] token := r.URL.Path[len("/files/"):]
@ -33,11 +31,9 @@ func UploadedFileHandler(w http.ResponseWriter, r *http.Request) {
//} //}
} }
} }
}
//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 sessions.IsLoggedIn(r) {
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 var filelink string // will store the html when we have files to be uploaded, appened to the note content
r.ParseForm() r.ParseForm()
@ -124,14 +120,11 @@ func AddTaskFunc(w http.ResponseWriter, r *http.Request) {
} }
} }
} else {
http.Redirect(w, r, "/login/", 302)
}
} }
//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 sessions.IsLoggedIn(r) {
r.ParseForm() r.ParseForm()
category := r.Form.Get("category") category := r.Form.Get("category")
if strings.Trim(category, " ") != "" { if strings.Trim(category, " ") != "" {
@ -144,14 +137,10 @@ func AddCategoryFunc(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/", http.StatusFound) http.Redirect(w, r, "/", http.StatusFound)
} }
} }
} else {
http.Redirect(w, r, "/login/", 302)
}
} }
//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 sessions.IsLoggedIn(r) {
if r.Method == "GET" { if r.Method == "GET" {
id, err := strconv.Atoi(r.URL.Path[len("/edit/"):]) id, err := strconv.Atoi(r.URL.Path[len("/edit/"):])
if err != nil { if err != nil {
@ -170,14 +159,10 @@ func EditTaskFunc(w http.ResponseWriter, r *http.Request) {
editTemplate.Execute(w, task) editTemplate.Execute(w, task)
} }
} }
} else {
http.Redirect(w, r, "/login/", 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 sessions.IsLoggedIn(r) {
if r.Method == "POST" { if r.Method == "POST" {
r.ParseForm() r.ParseForm()
text := r.Form.Get("commentText") text := r.Form.Get("commentText")
@ -202,7 +187,4 @@ func AddCommentFunc(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/", http.StatusFound) http.Redirect(w, r, "/", http.StatusFound)
} }
} else {
http.Redirect(w, r, "/login", 302)
}
} }

View File

@ -10,7 +10,6 @@ import (
"strconv" "strconv"
"github.com/thewhitetulip/Tasks/db" "github.com/thewhitetulip/Tasks/db"
"github.com/thewhitetulip/Tasks/sessions"
"github.com/thewhitetulip/Tasks/utils" "github.com/thewhitetulip/Tasks/utils"
) )
@ -19,8 +18,6 @@ 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 sessions.IsLoggedIn(r) {
if r.Method == "GET" { if r.Method == "GET" {
id, err := strconv.Atoi(r.URL.Path[len("/trash/"):]) id, err := strconv.Atoi(r.URL.Path[len("/trash/"):])
if err != nil { if err != nil {
@ -37,14 +34,10 @@ func TrashTaskFunc(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, redirectURL, http.StatusFound) http.Redirect(w, r, redirectURL, http.StatusFound)
} }
} }
} else {
http.Redirect(w, r, "/login/", 302)
}
} }
//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 sessions.IsLoggedIn(r) {
if r.Method == "GET" { if r.Method == "GET" {
id, err := strconv.Atoi(r.URL.Path[len("/restore/"):]) id, err := strconv.Atoi(r.URL.Path[len("/restore/"):])
if err != nil { if err != nil {
@ -60,14 +53,10 @@ func RestoreTaskFunc(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/deleted/", http.StatusFound) http.Redirect(w, r, "/deleted/", http.StatusFound)
} }
} }
} else {
http.Redirect(w, r, "/login/", 302)
}
} }
//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 sessions.IsLoggedIn(r) {
if r.Method == "GET" { if r.Method == "GET" {
id := r.URL.Path[len("/delete/"):] id := r.URL.Path[len("/delete/"):]
if id == "all" { if id == "all" {
@ -93,14 +82,10 @@ func DeleteTaskFunc(w http.ResponseWriter, r *http.Request) {
} }
} }
} }
} else {
http.Redirect(w, r, "/login/", 302)
}
} }
//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 sessions.IsLoggedIn(r) {
if r.Method == "GET" { if r.Method == "GET" {
id, err := strconv.Atoi(r.URL.Path[len("/incomplete/"):]) id, err := strconv.Atoi(r.URL.Path[len("/incomplete/"):])
if err != nil { if err != nil {
@ -116,14 +101,10 @@ func RestoreFromCompleteFunc(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/completed", http.StatusFound) http.Redirect(w, r, "/completed", http.StatusFound)
} }
} }
} else {
http.Redirect(w, r, "/login/", 302)
}
} }
//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 sessions.IsLoggedIn(r) {
if r.Method == "GET" { if r.Method == "GET" {
categoryName := r.URL.Path[len("/del-category/"):] categoryName := r.URL.Path[len("/del-category/"):]
err := db.DeleteCategoryByName(categoryName) err := db.DeleteCategoryByName(categoryName)
@ -135,14 +116,10 @@ func DeleteCategoryFunc(w http.ResponseWriter, r *http.Request) {
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 sessions.IsLoggedIn(r) {
if r.Method == "GET" { if r.Method == "GET" {
id := r.URL.Path[len("/del-comment/"):] id := r.URL.Path[len("/del-comment/"):]
commentID, err := strconv.Atoi(id) commentID, err := strconv.Atoi(id)
@ -161,7 +138,4 @@ func DeleteCommentFunc(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/", http.StatusFound) http.Redirect(w, r, "/", http.StatusFound)
} }
} else {
http.Redirect(w, r, "/login/", 302)
}
} }

View File

@ -14,7 +14,6 @@ import (
"text/template" "text/template"
"github.com/thewhitetulip/Tasks/db" "github.com/thewhitetulip/Tasks/db"
"github.com/thewhitetulip/Tasks/sessions"
"github.com/thewhitetulip/Tasks/utils" "github.com/thewhitetulip/Tasks/utils"
) )
@ -56,7 +55,6 @@ 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 sessions.IsLoggedIn(r) {
if r.Method == "GET" { if r.Method == "GET" {
redirectURL := utils.GetRedirectUrl(r.Referer()) redirectURL := utils.GetRedirectUrl(r.Referer())
id, err := strconv.Atoi(r.URL.Path[len("/complete/"):]) id, err := strconv.Atoi(r.URL.Path[len("/complete/"):])
@ -72,14 +70,10 @@ func CompleteTaskFunc(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, redirectURL, http.StatusFound) http.Redirect(w, r, redirectURL, http.StatusFound)
} }
} }
} else {
http.Redirect(w, r, "/login/", 302)
}
} }
//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 sessions.IsLoggedIn(r) {
if r.Method == "POST" { if r.Method == "POST" {
r.ParseForm() r.ParseForm()
query := r.Form.Get("query") query := r.Form.Get("query")
@ -91,14 +85,10 @@ func SearchTaskFunc(w http.ResponseWriter, r *http.Request) {
searchTemplate.Execute(w, context) searchTemplate.Execute(w, context)
} }
} else {
http.Redirect(w, r, "/login/", 302)
}
} }
//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 sessions.IsLoggedIn(r) {
if r.Method == "POST" { if r.Method == "POST" {
r.ParseForm() r.ParseForm()
id, err := strconv.Atoi(r.Form.Get("id")) id, err := strconv.Atoi(r.Form.Get("id"))
@ -121,14 +111,10 @@ func UpdateTaskFunc(w http.ResponseWriter, r *http.Request) {
} }
http.Redirect(w, r, "/", http.StatusFound) http.Redirect(w, r, "/", http.StatusFound)
} }
} else {
http.Redirect(w, r, "/login/", 302)
}
} }
//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 sessions.IsLoggedIn(r) {
if r.Method == "POST" { if r.Method == "POST" {
var redirectURL string var redirectURL string
r.ParseForm() r.ParseForm()
@ -147,7 +133,4 @@ func UpdateCategoryFunc(w http.ResponseWriter, r *http.Request) {
log.Println("redirecting to " + redirectURL) log.Println("redirecting to " + redirectURL)
http.Redirect(w, r, redirectURL, http.StatusFound) http.Redirect(w, r, redirectURL, http.StatusFound)
} }
} else {
http.Redirect(w, r, "/login/", 302)
}
} }

View File

@ -6,6 +6,17 @@ import (
"github.com/thewhitetulip/Tasks/sessions" "github.com/thewhitetulip/Tasks/sessions"
) )
//RequiresLogin is a middleware which will be used for each httpHandler to check if there is any active session
func RequiresLogin(handler func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if !sessions.IsLoggedIn(r) {
http.Redirect(w, r, "/login/", 302)
return
}
handler(w, r)
}
}
//LogoutFunc Implements the logout functionality. WIll delete the session information from the cookie store //LogoutFunc Implements the logout functionality. WIll delete the session information from the cookie store
func LogoutFunc(w http.ResponseWriter, r *http.Request) { func LogoutFunc(w http.ResponseWriter, r *http.Request) {
session, err := sessions.Store.Get(r, "session") session, err := sessions.Store.Get(r, "session")

View File

@ -25,7 +25,6 @@ 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 sessions.IsLoggedIn(r) == true {
if r.Method == "GET" { if r.Method == "GET" {
context, err := db.GetTasks("pending", "") context, err := db.GetTasks("pending", "")
categories := db.GetCategories() categories := db.GetCategories()
@ -44,14 +43,10 @@ func ShowAllTasksFunc(w http.ResponseWriter, r *http.Request) {
homeTemplate.Execute(w, context) homeTemplate.Execute(w, context)
} }
} }
} else {
http.Redirect(w, r, "/login/", 302)
}
} }
//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 sessions.IsLoggedIn(r) {
if r.Method == "GET" { if r.Method == "GET" {
context, err := db.GetTasks("deleted", "") context, err := db.GetTasks("deleted", "")
categories := db.GetCategories() categories := db.GetCategories()
@ -65,14 +60,10 @@ func ShowTrashTaskFunc(w http.ResponseWriter, r *http.Request) {
} }
deletedTemplate.Execute(w, context) deletedTemplate.Execute(w, context)
} }
} else {
http.Redirect(w, r, "/login/", 302)
}
} }
//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 sessions.IsLoggedIn(r) {
if r.Method == "GET" { if r.Method == "GET" {
context, err := db.GetTasks("completed", "") context, err := db.GetTasks("completed", "")
categories := db.GetCategories() categories := db.GetCategories()
@ -82,15 +73,11 @@ func ShowCompleteTasksFunc(w http.ResponseWriter, r *http.Request) {
} }
completedTemplate.Execute(w, context) completedTemplate.Execute(w, context)
} }
} else {
http.Redirect(w, r, "/login/", 302)
}
} }
//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 sessions.IsLoggedIn(r) {
if r.Method == "GET" && sessions.IsLoggedIn(r) { if r.Method == "GET" && sessions.IsLoggedIn(r) {
category := r.URL.Path[len("/category/"):] category := r.URL.Path[len("/category/"):]
context, err := db.GetTasks("", category) context, err := db.GetTasks("", category)
@ -110,7 +97,4 @@ func ShowCategoryFunc(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, &cookie) http.SetCookie(w, &cookie)
homeTemplate.Execute(w, context) homeTemplate.Execute(w, context)
} }
} else {
http.Redirect(w, r, "/login/", 302)
}
} }