Tasks/views/sessionViews.go

45 lines
1.3 KiB
Go
Raw Normal View History

2016-05-09 10:11:05 +08:00
package views
import (
"net/http"
"github.com/thewhitetulip/Tasks/sessions"
)
//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 {
loginTemplate.Execute(w, nil) // in case of error during fetching session info, execute login template
2016-05-09 10:11:05 +08:00
} else {
2016-05-10 00:59:36 +08:00
isLoggedIn := session.Values["loggedin"]
if isLoggedIn != "true" {
if r.Method == "POST" {
if r.FormValue("password") == "secret" && r.FormValue("username") == "user" {
session.Values["loggedin"] = "true"
session.Save(r, w)
http.Redirect(w, r, "/", 302)
return
}
} else if r.Method == "GET" {
loginTemplate.Execute(w, nil)
}
} else {
http.Redirect(w, r, "/", 302)
}
2016-05-09 10:11:05 +08:00
}
}