2017-11-07 17:53:02 +00:00
|
|
|
package core
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/kirsle/blog/core/forms"
|
|
|
|
"github.com/kirsle/blog/core/models/users"
|
|
|
|
)
|
|
|
|
|
2017-11-08 03:48:22 +00:00
|
|
|
// Login logs the browser in as the given user.
|
|
|
|
func (b *Blog) Login(w http.ResponseWriter, r *http.Request, u *users.User) error {
|
|
|
|
session, err := b.store.Get(r, "session") // TODO session name
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2017-11-07 17:53:02 +00:00
|
|
|
}
|
2017-11-08 03:48:22 +00:00
|
|
|
session.Values["logged-in"] = true
|
|
|
|
session.Values["user-id"] = u.ID
|
|
|
|
session.Save(r, w)
|
|
|
|
return nil
|
2017-11-07 17:53:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// LoginHandler shows and handles the login page.
|
|
|
|
func (b *Blog) LoginHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
|
vars := &Vars{
|
|
|
|
Form: forms.Setup{},
|
|
|
|
}
|
|
|
|
|
2017-11-20 05:49:19 +00:00
|
|
|
if r.Method == http.MethodPost {
|
2017-11-07 17:53:02 +00:00
|
|
|
form := &forms.Login{
|
|
|
|
Username: r.FormValue("username"),
|
|
|
|
Password: r.FormValue("password"),
|
|
|
|
}
|
|
|
|
vars.Form = form
|
|
|
|
err := form.Validate()
|
|
|
|
if err != nil {
|
|
|
|
vars.Error = err
|
|
|
|
} else {
|
|
|
|
// Test the login.
|
|
|
|
user, err := users.CheckAuth(form.Username, form.Password)
|
|
|
|
if err != nil {
|
|
|
|
vars.Error = errors.New("bad username or password")
|
|
|
|
} else {
|
|
|
|
// Login OK!
|
2017-11-20 05:49:19 +00:00
|
|
|
b.Flash(w, r, "Login OK!")
|
2017-11-08 03:48:22 +00:00
|
|
|
b.Login(w, r, user)
|
2017-11-07 17:53:02 +00:00
|
|
|
|
2017-11-08 03:48:22 +00:00
|
|
|
// A next URL given? TODO: actually get to work
|
|
|
|
next := r.FormValue("next")
|
|
|
|
log.Info("Redirect after login to: %s", next)
|
|
|
|
if len(next) > 0 && next[0] == '/' {
|
|
|
|
b.Redirect(w, next)
|
2017-11-07 17:53:02 +00:00
|
|
|
} else {
|
2017-11-08 03:48:22 +00:00
|
|
|
b.Redirect(w, "/")
|
2017-11-07 17:53:02 +00:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
b.RenderTemplate(w, r, "login", vars)
|
|
|
|
}
|
|
|
|
|
|
|
|
// LogoutHandler logs the user out and redirects to the home page.
|
|
|
|
func (b *Blog) LogoutHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
|
session, _ := b.store.Get(r, "session")
|
|
|
|
delete(session.Values, "logged-in")
|
|
|
|
delete(session.Values, "user-id")
|
|
|
|
session.Save(r, w)
|
|
|
|
b.Redirect(w, "/")
|
|
|
|
}
|