package Auth
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
|
|
"git.tovijaeschke.xyz/tovi/Capsule/Backend/Database"
|
|
"git.tovijaeschke.xyz/tovi/Capsule/Backend/Models"
|
|
)
|
|
|
|
func CheckCookie(r *http.Request) (Models.Session, error) {
|
|
var (
|
|
c *http.Cookie
|
|
sessionToken string
|
|
userSession Models.Session
|
|
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, err = Database.GetSessionByID(sessionToken)
|
|
if err != nil {
|
|
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() {
|
|
Database.DeleteSession(&userSession)
|
|
return userSession, errors.New("Cookie expired")
|
|
}
|
|
|
|
return userSession, nil
|
|
}
|
|
|
|
func CheckCookieCurrentUser(w http.ResponseWriter, r *http.Request) (Models.User, error) {
|
|
var (
|
|
session Models.Session
|
|
userData Models.User
|
|
err error
|
|
)
|
|
|
|
session, err = CheckCookie(r)
|
|
if err != nil {
|
|
return userData, err
|
|
}
|
|
|
|
return session.User, nil
|
|
}
|