81 lines
1.7 KiB
Go
Raw Normal View History

2020-11-01 18:39:12 +01:00
package session
import (
2021-08-29 17:09:13 +02:00
"errors"
2020-11-01 18:39:12 +01:00
"net/http"
2021-03-13 21:44:38 +01:00
"strings"
2021-03-17 14:09:10 +01:00
"time"
2020-11-01 18:39:12 +01:00
"github.com/demodesk/neko/pkg/types"
2020-11-01 18:39:12 +01:00
)
2021-03-17 14:09:10 +01:00
func (manager *SessionManagerCtx) CookieSetToken(w http.ResponseWriter, token string) {
sameSite := http.SameSiteDefaultMode
if manager.config.CookieSecure {
sameSite = http.SameSiteNoneMode
}
http.SetCookie(w, &http.Cookie{
Name: manager.config.CookieName,
Value: token,
2022-01-16 21:03:25 +01:00
Expires: time.Now().Add(manager.config.CookieExpiration),
2021-03-17 14:09:10 +01:00
Secure: manager.config.CookieSecure,
SameSite: sameSite,
HttpOnly: true,
})
}
2021-03-25 10:29:28 +01:00
func (manager *SessionManagerCtx) CookieClearToken(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie(manager.config.CookieName)
if err != nil {
return
2021-03-17 14:09:10 +01:00
}
2021-03-25 10:29:28 +01:00
cookie.Value = ""
cookie.Expires = time.Unix(0, 0)
http.SetCookie(w, cookie)
2021-03-17 14:09:10 +01:00
}
2021-03-13 20:42:56 +01:00
func (manager *SessionManagerCtx) Authenticate(r *http.Request) (types.Session, error) {
2021-03-17 14:09:10 +01:00
token, ok := manager.getToken(r)
2020-11-27 19:59:54 +01:00
if !ok {
2021-08-29 17:09:13 +02:00
return nil, errors.New("no authentication provided")
2020-11-01 18:39:12 +01:00
}
session, ok := manager.GetByToken(token)
2020-11-27 19:59:54 +01:00
if !ok {
2021-08-29 17:09:13 +02:00
return nil, types.ErrSessionNotFound
2020-12-06 18:48:50 +01:00
}
2021-03-14 19:58:15 +01:00
if !session.Profile().CanLogin {
2021-08-29 17:09:13 +02:00
return nil, types.ErrSessionLoginDisabled
2021-03-14 19:58:15 +01:00
}
2020-11-27 19:59:54 +01:00
return session, nil
2020-11-01 18:39:12 +01:00
}
2020-11-28 15:22:04 +01:00
2021-03-17 14:09:10 +01:00
func (manager *SessionManagerCtx) getToken(r *http.Request) (string, bool) {
2021-04-24 21:11:07 +02:00
if manager.CookieEnabled() {
// get from Cookie
cookie, err := r.Cookie(manager.config.CookieName)
if err == nil {
return cookie.Value, true
}
}
2021-03-13 20:42:56 +01:00
// get from Header
reqToken := r.Header.Get("Authorization")
splitToken := strings.Split(reqToken, "Bearer ")
if len(splitToken) == 2 {
return strings.TrimSpace(splitToken[1]), true
2020-11-28 15:22:04 +01:00
}
2021-03-13 20:42:56 +01:00
// get from URL
token := r.URL.Query().Get("token")
if token != "" {
return token, true
2020-11-28 15:22:04 +01:00
}
2021-03-13 20:42:56 +01:00
return "", false
2021-02-14 14:40:17 +01:00
}