2022-09-05 14:17:07 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2022-09-06 11:22:28 +02:00
|
|
|
crand "crypto/rand"
|
|
|
|
"encoding/hex"
|
|
|
|
"net/http"
|
|
|
|
"time"
|
2022-09-05 14:17:07 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
func Must[T any](value T, err error) T {
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return value
|
|
|
|
}
|
|
|
|
|
2022-09-06 11:22:28 +02:00
|
|
|
func generateRandomID(length int) (string, error) {
|
|
|
|
data := make([]byte, 32)
|
|
|
|
if _, err := crand.Read(data); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return hex.EncodeToString(data), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func GetSession(w http.ResponseWriter, r *http.Request) (*Session, error) {
|
|
|
|
cookie, err := r.Cookie("session")
|
|
|
|
if err != nil {
|
|
|
|
return makeNewSession(w)
|
2022-09-05 14:17:07 +02:00
|
|
|
}
|
|
|
|
|
2022-09-06 11:22:28 +02:00
|
|
|
session := GetSessionByID(cookie.Value)
|
|
|
|
if session == nil {
|
|
|
|
return makeNewSession(w)
|
2022-09-05 14:17:07 +02:00
|
|
|
}
|
|
|
|
|
2022-09-06 11:22:28 +02:00
|
|
|
// update cookie expiration date
|
|
|
|
session.ExpirationDate = time.Now().AddDate(1, 0, 0)
|
|
|
|
if err := UpdateSession(session); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
http.SetCookie(w, &http.Cookie{
|
|
|
|
Name: "session",
|
|
|
|
Value: session.ID,
|
|
|
|
Expires: session.ExpirationDate,
|
|
|
|
Secure: true,
|
|
|
|
HttpOnly: true,
|
|
|
|
})
|
|
|
|
|
|
|
|
return session, nil
|
2022-09-05 14:17:07 +02:00
|
|
|
}
|
|
|
|
|
2022-09-06 11:22:28 +02:00
|
|
|
func makeNewSession(w http.ResponseWriter) (*Session, error) {
|
|
|
|
session, err := NewSession()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := InsertSession(session); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// insert default bookmarks
|
|
|
|
for _, bookmark := range DefaultBookmarks() {
|
|
|
|
bookmark.SessionID = session.ID
|
|
|
|
if err := InsertBookmark(&bookmark); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2022-09-05 14:17:07 +02:00
|
|
|
}
|
|
|
|
|
2022-09-06 11:22:28 +02:00
|
|
|
// insert default settings
|
|
|
|
settings := DefaultSettings()
|
|
|
|
settings.SessionID = session.ID
|
|
|
|
if err := InsertSettings(settings); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
http.SetCookie(w, &http.Cookie{
|
|
|
|
Name: "session",
|
|
|
|
Value: session.ID,
|
|
|
|
Expires: session.ExpirationDate,
|
|
|
|
Secure: true,
|
|
|
|
HttpOnly: true,
|
|
|
|
})
|
|
|
|
|
|
|
|
return session, nil
|
2022-09-05 14:17:07 +02:00
|
|
|
}
|