mirror of https://gitlab.com/ngerakines/tavern.git
92 lines
1.8 KiB
Go
92 lines
1.8 KiB
Go
package web
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-contrib/sessions"
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"github.com/ngerakines/tavern/errors"
|
|
)
|
|
|
|
func (h handler) home(c *gin.Context) {
|
|
session := sessions.Default(c)
|
|
ctx := c.Request.Context()
|
|
trans, transOK := c.Get("trans")
|
|
if !transOK {
|
|
panic("trans not found in context")
|
|
}
|
|
data := gin.H{
|
|
"flashes": getFlashes(session),
|
|
"authenticated": false,
|
|
"Trans": trans,
|
|
}
|
|
|
|
if c.Query("landing") == "true" {
|
|
c.HTML(http.StatusOK, "index", data)
|
|
return
|
|
}
|
|
|
|
_, err := h.storage.GetUserBySession(ctx, session)
|
|
if err == nil {
|
|
c.Redirect(http.StatusFound, h.url("feed"))
|
|
return
|
|
}
|
|
if errors.Is(err, errors.UserSessionNotFoundError{}) {
|
|
|
|
if err := session.Save(); err != nil {
|
|
h.hardFail(c, errors.NewCannotSaveSessionError(err))
|
|
return
|
|
}
|
|
|
|
c.HTML(http.StatusOK, "index", data)
|
|
return
|
|
}
|
|
h.hardFail(c, err)
|
|
}
|
|
|
|
func (h handler) signin(c *gin.Context) {
|
|
session := sessions.Default(c)
|
|
ctx := c.Request.Context()
|
|
|
|
email := c.PostForm("email")
|
|
password := c.PostForm("password")
|
|
userID, err := h.storage.AuthenticateUser(ctx, email, []byte(password))
|
|
if err != nil {
|
|
h.hardFail(c, err)
|
|
return
|
|
}
|
|
|
|
user, err := h.storage.GetUser(ctx, userID)
|
|
if err != nil {
|
|
h.hardFail(c, err)
|
|
return
|
|
}
|
|
err = h.storage.UpdateUserLastAuth(ctx, userID)
|
|
if err != nil {
|
|
h.hardFail(c, err)
|
|
return
|
|
}
|
|
c.SetCookie("lang", user.Locale, 0, "/", h.domain, true, true)
|
|
session.Set(gin.AuthUserKey, userID.String())
|
|
if err = session.Save(); err != nil {
|
|
h.hardFail(c, errors.NewCannotSaveSessionError(err))
|
|
return
|
|
}
|
|
|
|
c.Redirect(http.StatusFound, h.url())
|
|
}
|
|
|
|
func (h handler) signout(c *gin.Context) {
|
|
session := sessions.Default(c)
|
|
|
|
session.Clear()
|
|
|
|
if err := session.Save(); err != nil {
|
|
h.hardFail(c, errors.NewCannotSaveSessionError(err))
|
|
return
|
|
}
|
|
|
|
c.Redirect(http.StatusFound, h.url())
|
|
}
|