go-urlsh/internal/misc/cookie.go

69 lines
1.9 KiB
Go

package misc
import (
"context"
"log"
"time"
"code.lila.network/adoralaura/go-urlsh/internal/constants"
"code.lila.network/adoralaura/go-urlsh/models"
"github.com/gofiber/fiber/v2"
)
// SetLoginCookie handles setting the Login Cookie. It
// - generates a new cookie secret
// - sets its expiry
// - adds the necessary DB entry for the session and last login
// - adds the cookie to the fiber context
func SetLoginCookie(c *fiber.Ctx, user models.User, expiryTime time.Duration) error {
expires := time.Now().Add(expiryTime)
key := NewLoginCookie(constants.LoginCookieLength)
var dblogin models.Session
cookie := new(fiber.Cookie)
cookie.Name = constants.LoginCookieName
cookie.Value = key
cookie.Expires = expires
dblogin.Expires = expires
dblogin.Cookie = key
dblogin.UserName = user.UserName
_, err := models.DB.NewInsert().Model(&dblogin).Exec(context.Background())
if err != nil {
log.Printf("DB Error inserting login cookie information for user %v: %v\n", dblogin.UserName, err.Error())
return fiber.NewError(fiber.StatusInternalServerError, "500 Internal Server Error")
}
user.LastLogin = time.Now()
_, err = models.DB.NewUpdate().Model(&user).WherePK().Exec(context.Background())
if err != nil {
log.Printf("DB Error updating last login information for user %v: %v\n", dblogin.UserName, err.Error())
return fiber.NewError(fiber.StatusInternalServerError, "500 Internal Server Error")
}
c.Cookie(cookie)
return nil
}
func SetMFAFlowCookie(c *fiber.Ctx, cookievalue string) {
expires := time.Now().Add(30 * time.Minute)
cookie := new(fiber.Cookie)
cookie.Name = constants.MFAFlowCookieName
cookie.Value = cookievalue
cookie.Expires = expires
c.Cookie(cookie)
}
func SetMFASetupCookie(c *fiber.Ctx, cookievalue string) {
expires := time.Now().Add(30 * time.Minute)
cookie := new(fiber.Cookie)
cookie.Name = constants.MFASetupCookieName
cookie.Value = cookievalue
cookie.Expires = expires
c.Cookie(cookie)
}