63 lines
1.4 KiB
Go
63 lines
1.4 KiB
Go
package auth
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gorilla/sessions"
|
|
"github.com/labstack/echo-contrib/session"
|
|
"github.com/labstack/echo/v4"
|
|
"gitnet.fr/deblan/budget/database/manager"
|
|
"gitnet.fr/deblan/budget/database/model"
|
|
"gitnet.fr/deblan/budget/view"
|
|
"gitnet.fr/deblan/budget/view/template/auth"
|
|
)
|
|
|
|
type Controller struct {
|
|
}
|
|
|
|
func New(e *echo.Echo) *Controller {
|
|
c := Controller{}
|
|
|
|
e.GET("/login", c.LoginGet)
|
|
e.POST("/login", c.LoginPost)
|
|
e.GET("/logout", c.LogoutGet)
|
|
|
|
return &c
|
|
}
|
|
|
|
func (ctrl *Controller) LoginGet(c echo.Context) error {
|
|
return view.Render(c, 200, auth.Page(false))
|
|
}
|
|
|
|
func (ctrl *Controller) LoginPost(c echo.Context) error {
|
|
username := c.FormValue("username")
|
|
password := c.FormValue("password")
|
|
|
|
var count int64
|
|
db := manager.Get()
|
|
db.Db.Model(model.User{}).Where("username = ?", username).Count(&count)
|
|
|
|
if count > 0 {
|
|
var user model.User
|
|
db.Db.Model(model.User{}).Where("username = ?", username).Find(&user)
|
|
|
|
if user.HasPassword(password) {
|
|
sess, _ := session.Get("session", c)
|
|
sess.Options = &sessions.Options{
|
|
Path: "/",
|
|
MaxAge: 86400 * 7,
|
|
HttpOnly: true,
|
|
}
|
|
sess.Values["user"] = user.ID
|
|
sess.Save(c.Request(), c.Response())
|
|
|
|
return c.Redirect(302, "/")
|
|
}
|
|
}
|
|
|
|
return view.Render(c, 200, auth.Page(true))
|
|
}
|
|
|
|
func (ctrl *Controller) LogoutGet(c echo.Context) error {
|
|
return c.String(http.StatusOK, "Hello, World!")
|
|
}
|