camper/pkg/auth/session.go

51 lines
961 B
Go

/*
* SPDX-FileCopyrightText: 2023 jordi fita mas <jfita@peritasoft.com>
* SPDX-License-Identifier: AGPL-3.0-only
*/
package auth
import (
"net/http"
"time"
"golang.org/x/text/language"
"dev.tandem.ws/tandem/camper/pkg/locale"
)
const (
sessionCookie = "camper-session"
)
type User struct {
Email string
LoggedIn bool
Role string
Language language.Tag
CsrfToken string
Locale *locale.Locale
}
func SetSessionCookie(w http.ResponseWriter, cookie string) {
http.SetCookie(w, createSessionCookie(cookie, 8766*24*time.Hour))
}
func GetSessionCookie(r *http.Request) string {
if cookie, err := r.Cookie(sessionCookie); err == nil {
return cookie.Value
}
return ""
}
func createSessionCookie(value string, duration time.Duration) *http.Cookie {
return &http.Cookie{
Name: sessionCookie,
Value: value,
Path: "/",
Expires: time.Now().Add(duration),
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
}
}