1package handler
2
3import (
4 "fmt"
5 "time"
6
7 "github.com/bnema/gordon/internal/db/queries"
8 "github.com/bnema/gordon/internal/server"
9 "github.com/labstack/echo-contrib/session"
10 "github.com/labstack/echo/v4"
11)
12
13func ValidateSessionAndUser(c echo.Context, a *server.App) error {
14 sessionExpiryTime := 30 * time.Minute
15
16 sess, err := session.Get("session", c)
17 if err != nil {
18 return err
19 }
20
21 accountID, ok := sess.Values["accountID"].(string)
22 if !ok {
23 return fmt.Errorf("accountID not found or invalid type")
24 }
25
26 sessionID, ok := sess.Values["sessionID"].(string)
27 if !ok {
28 return fmt.Errorf("sessionID not found or invalid type")
29 }
30
31 accountExists, err := IsAccountIDInDB(a, accountID)
32 if err != nil || !accountExists {
33 return fmt.Errorf("account does not exist")
34 }
35
36 sessionExpired, err := IsSessionExpiredInDB(a, accountID, sessionID)
37 if err != nil || sessionExpired {
38 return fmt.Errorf("session is expired")
39 }
40
41 // Extend session expiration conditionally, e.g., if it's close to expiring
42 err = queries.ExtendSessionExpiration(a, accountID, sessionID, time.Now().Add(sessionExpiryTime))
43 if err != nil {
44 return fmt.Errorf("failed to extend session: %v", err)
45 }
46
47 return nil
48}
49
50func IsSessionExpiredInDB(a *server.App, accountID string, sessionID string) (bool, error) {
51 currentTime := time.Now()
52 expirationTime, err := queries.GetSessionExpiration(a, accountID, sessionID, currentTime)
53 if err != nil {
54 return false, err
55 }
56
57 return currentTime.After(expirationTime), nil
58}
59
60func IsAccountIDInDB(a *server.App, accountID string) (bool, error) {
61 accountExists, err := queries.CheckDBAccountExists(a, accountID)
62 if err != nil {
63 return false, err
64 }
65
66 return accountExists, nil
67}
68
69// ResetSession resets the session cookie and session data
70// func ResetSession(c echo.Context) error {
71// // Manually expire the cookie
72// cookie := new(http.Cookie)
73// cookie.Name = "session"
74// cookie.Value = ""
75// cookie.Path = "/"
76// cookie.Expires = time.Unix(0, 0)
77// cookie.MaxAge = -1 // Clear immediately
78// c.SetCookie(cookie)
79// // Invalidate the existing session
80// sess, err := session.Get("session", c)
81// if err != nil {
82// log.Println(err)
83// return echo.NewHTTPError(http.StatusInternalServerError, "Could not get session")
84// }
85// sess.Options.MaxAge = -1
86// if err := sess.Save(c.Request(), c.Response()); err != nil {
87// log.Println("Could not delete session:", err)
88// return echo.NewHTTPError(http.StatusInternalServerError, "Could not delete session")
89// }
90
91// return nil
92// }