2022-02-17 12:31:01 +00:00
|
|
|
package web
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
|
2022-02-18 13:35:03 +00:00
|
|
|
"github.com/labstack/echo/v4"
|
2022-02-17 12:31:01 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var sessions map[string]time.Time
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
sessions = make(map[string]time.Time)
|
|
|
|
}
|
|
|
|
|
2022-02-18 13:35:03 +00:00
|
|
|
func checkAuth(token string) error {
|
2022-02-17 12:31:01 +00:00
|
|
|
for sToken, expiree := range sessions {
|
|
|
|
// Expire old sessions
|
|
|
|
if time.Now().After(expiree) {
|
|
|
|
delete(sessions, sToken)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
// Check for valid session of token
|
|
|
|
if token == sToken {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return errors.New("this token is not associated with a valid session")
|
|
|
|
}
|
2022-02-18 13:35:03 +00:00
|
|
|
|
|
|
|
func withAuth(handler echo.HandlerFunc) echo.HandlerFunc {
|
|
|
|
return func(c echo.Context) error {
|
|
|
|
session, err := c.Cookie("session")
|
|
|
|
if err != nil || checkAuth(session.Value) != nil {
|
|
|
|
return c.Redirect(http.StatusSeeOther, "/")
|
|
|
|
}
|
|
|
|
return handler(c)
|
|
|
|
}
|
|
|
|
}
|