added error handling in session view

This commit is contained in:
Suraj Patil 2016-05-09 22:29:36 +05:30
parent 45000d7a8e
commit eb1bf99924
1 changed files with 25 additions and 19 deletions

View File

@ -8,31 +8,37 @@ import (
//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, _ := sessions.Store.Get(r, "session") session, err := sessions.Store.Get(r, "session")
if session.Values["loggedin"] != "false" { if err == nil { //If there is no error, then remove session
session.Values["loggedin"] = "false" if session.Values["loggedin"] != "false" {
session.Save(r, w) session.Values["loggedin"] = "false"
http.Redirect(w, r, "/login", 302) session.Save(r, w)
return }
} }
http.Redirect(w, r, "/login", 302) http.Redirect(w, r, "/login", 302) //redirect to login irrespective of error or not
} }
//LoginFunc implements the login functionality, will add a cookie to the cookie store for managing authentication //LoginFunc implements the login functionality, will add a cookie to the cookie store for managing authentication
func LoginFunc(w http.ResponseWriter, r *http.Request) { func LoginFunc(w http.ResponseWriter, r *http.Request) {
session, _ := sessions.Store.Get(r, "session") session, err := sessions.Store.Get(r, "session")
if r.Method == "POST" && r.FormValue("password") == "secret" && r.FormValue("username") == "user" { if err != nil {
session.Values["loggedin"] = "true" loginTemplate.Execute(w, nil) // in case of error during fetching session info, execute login template
session.Save(r, w)
http.Redirect(w, r, "/", 302)
return
}
if session.Values["loggedin"] == "true" {
http.Redirect(w, r, "/", 302)
} else { } else {
loginTemplate.Execute(w, nil) 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)
}
} }
} }