Tasks/views/sessionViews.go

65 lines
1.8 KiB
Go
Raw Normal View History

2016-05-09 10:11:05 +08:00
package views
import (
"log"
2016-05-09 10:11:05 +08:00
"net/http"
"github.com/thewhitetulip/Tasks/db"
2016-05-09 10:11:05 +08:00
"github.com/thewhitetulip/Tasks/sessions"
)
2016-05-12 01:19:32 +08:00
//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)
}
}
2016-05-09 10:11:05 +08:00
//LogoutFunc Implements the logout functionality. WIll delete the session information from the cookie store
func LogoutFunc(w http.ResponseWriter, r *http.Request) {
2016-05-10 00:59:36 +08:00
session, err := sessions.Store.Get(r, "session")
if err == nil { //If there is no error, then remove session
if session.Values["loggedin"] != "false" {
session.Values["loggedin"] = "false"
session.Save(r, w)
}
2016-05-09 10:11:05 +08:00
}
2016-05-10 00:59:36 +08:00
http.Redirect(w, r, "/login", 302) //redirect to login irrespective of error or not
2016-05-09 10:11:05 +08:00
}
//LoginFunc implements the login functionality, will add a cookie to the cookie store for managing authentication
func LoginFunc(w http.ResponseWriter, r *http.Request) {
2016-05-10 00:59:36 +08:00
session, err := sessions.Store.Get(r, "session")
2016-05-09 10:11:05 +08:00
2016-05-10 00:59:36 +08:00
if err != nil {
log.Println("error identifying session")
loginTemplate.Execute(w, nil)
return
}
switch r.Method {
case "GET":
loginTemplate.Execute(w, nil)
case "POST":
log.Print("Inside POST")
r.ParseForm()
username := r.Form.Get("username")
password := r.Form.Get("password")
if (username != "" && password != "") && db.ValidUser(username, password) {
session.Values["loggedin"] = "true"
session.Values["username"] = username
session.Save(r, w)
log.Print("user ", username, " is authenticated")
2016-05-10 00:59:36 +08:00
http.Redirect(w, r, "/", 302)
return
2016-05-10 00:59:36 +08:00
}
log.Print("Invalid user " + username)
loginTemplate.Execute(w, nil)
2016-05-09 10:11:05 +08:00
}
}