|
|
- package Auth
-
- import (
- "errors"
- "net/http"
- "time"
- )
-
- var (
- Sessions = map[string]Session{}
- )
-
- type Session struct {
- Username string
- Expiry time.Time
- }
-
- func (s Session) IsExpired() bool {
- return s.Expiry.Before(time.Now())
- }
-
- func CheckCookie(r *http.Request) (Session, error) {
- var (
- c *http.Cookie
- sessionToken string
- userSession Session
- exists bool
- err error
- )
-
- c, err = r.Cookie("session_token")
- if err != nil {
- return userSession, err
- }
- sessionToken = c.Value
-
- // We then get the session from our session map
- userSession, exists = Sessions[sessionToken]
- if !exists {
- return userSession, errors.New("Cookie not found")
- }
-
- // If the session is present, but has expired, we can delete the session, and return
- // an unauthorized status
- if userSession.IsExpired() {
- delete(Sessions, sessionToken)
- return userSession, errors.New("Cookie expired")
- }
-
- return userSession, nil
- }
|