74 lines
1.5 KiB
Go
74 lines
1.5 KiB
Go
package users
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"github.com/gorilla/Schema"
|
|
|
|
"gitlab.quimbo.fr/odwrtw/canape-sql/auth"
|
|
"gitlab.quimbo.fr/odwrtw/canape-sql/web"
|
|
)
|
|
|
|
func LoginHandler(e *web.Env, w http.ResponseWriter, r *http.Request) error {
|
|
if r.Method == "GET" {
|
|
return e.Rends(w, r, "users/login")
|
|
}
|
|
|
|
type loginForm struct {
|
|
Username string
|
|
Password string
|
|
}
|
|
|
|
err := r.ParseForm()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
form := new(loginForm)
|
|
decoder := schema.NewDecoder()
|
|
err = decoder.Decode(form, r.PostForm)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
err = e.Auth.Login(w, r, form.Username, form.Password)
|
|
if err != nil {
|
|
if err == auth.ErrInvalidPassword || err == ErrUnknownUser {
|
|
web.SetData(r, "FormErrors", "Error invalid user or password")
|
|
return e.Rends(w, r, "users/login")
|
|
}
|
|
return err
|
|
}
|
|
|
|
path, err := auth.GetPostLoginRedirect(e.Auth, w, r)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if path != "" {
|
|
http.Redirect(w, r, path, http.StatusTemporaryRedirect)
|
|
return nil
|
|
}
|
|
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
|
return nil
|
|
}
|
|
|
|
func LogoutHandler(e *web.Env, w http.ResponseWriter, r *http.Request) error {
|
|
e.Auth.Logout(w, r)
|
|
route := e.GetLoginRouteGetter()()
|
|
http.Redirect(w, r, route, http.StatusTemporaryRedirect)
|
|
return nil
|
|
}
|
|
|
|
func DetailsHandler(e *web.Env, w http.ResponseWriter, r *http.Request) error {
|
|
u := auth.GetCurrentUser(r)
|
|
if u == nil {
|
|
return nil
|
|
}
|
|
_, ok := u.(*User)
|
|
if !ok {
|
|
return fmt.Errorf("Invalid user type")
|
|
}
|
|
return nil
|
|
}
|