A deployable markdown editor that connects with your self hosted files and lets you edit in a beautiful interface
at main 85 lines 1.8 kB view raw
1package auth 2 3import ( 4 "fmt" 5 "net/http" 6 "os" 7 "strconv" 8 9 "github.com/gorilla/sessions" 10) 11 12const ( 13 SessionName = "markedit-session" 14 UserIDKey = "user_id" 15) 16 17var store *sessions.CookieStore 18 19// InitSessions initializes the session store 20func InitSessions() error { 21 sessionSecret := os.Getenv("SESSION_SECRET") 22 if sessionSecret == "" { 23 return fmt.Errorf("SESSION_SECRET not configured") 24 } 25 26 if len(sessionSecret) < 32 { 27 return fmt.Errorf("SESSION_SECRET must be at least 32 characters") 28 } 29 30 store = sessions.NewCookieStore([]byte(sessionSecret)) 31 32 // Configure session options 33 sessionSecure := os.Getenv("SESSION_SECURE") == "true" 34 maxAge := 86400 // 24 hours default 35 36 if maxAgeStr := os.Getenv("SESSION_MAX_AGE"); maxAgeStr != "" { 37 if val, err := strconv.Atoi(maxAgeStr); err == nil { 38 maxAge = val 39 } 40 } 41 42 store.Options = &sessions.Options{ 43 Path: "/", 44 MaxAge: maxAge, 45 HttpOnly: true, 46 Secure: sessionSecure, 47 SameSite: http.SameSiteLaxMode, 48 } 49 50 return nil 51} 52 53// GetSession retrieves the session for a request 54func GetSession(r *http.Request) (*sessions.Session, error) { 55 return store.Get(r, SessionName) 56} 57 58// SaveSession saves the session 59func SaveSession(r *http.Request, w http.ResponseWriter, session *sessions.Session) error { 60 return session.Save(r, w) 61} 62 63// SetUserID sets the user ID in the session 64func SetUserID(session *sessions.Session, userID int) { 65 session.Values[UserIDKey] = userID 66} 67 68// GetUserID gets the user ID from the session 69func GetUserID(session *sessions.Session) (int, bool) { 70 val, ok := session.Values[UserIDKey] 71 if !ok { 72 return 0, false 73 } 74 75 userID, ok := val.(int) 76 return userID, ok 77} 78 79// ClearSession clears the session 80func ClearSession(session *sessions.Session) { 81 session.Options.MaxAge = -1 82 for key := range session.Values { 83 delete(session.Values, key) 84 } 85}