neko/server/internal/session/auth.go

81 lines
1.7 KiB
Go
Raw Normal View History

2020-11-02 06:39:12 +13:00
package session
import (
2021-08-30 03:09:13 +12:00
"errors"
2020-11-02 06:39:12 +13:00
"net/http"
2021-03-14 09:44:38 +13:00
"strings"
2021-03-18 02:09:10 +13:00
"time"
2020-11-02 06:39:12 +13:00
"github.com/demodesk/neko/pkg/types"
2020-11-02 06:39:12 +13:00
)
2021-03-18 02:09:10 +13: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-17 09:03:25 +13:00
Expires: time.Now().Add(manager.config.CookieExpiration),
2021-03-18 02:09:10 +13:00
Secure: manager.config.CookieSecure,
SameSite: sameSite,
HttpOnly: true,
})
}
2021-03-25 22:29:28 +13:00
func (manager *SessionManagerCtx) CookieClearToken(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie(manager.config.CookieName)
if err != nil {
return
2021-03-18 02:09:10 +13:00
}
2021-03-25 22:29:28 +13:00
cookie.Value = ""
cookie.Expires = time.Unix(0, 0)
http.SetCookie(w, cookie)
2021-03-18 02:09:10 +13:00
}
2021-03-14 08:42:56 +13:00
func (manager *SessionManagerCtx) Authenticate(r *http.Request) (types.Session, error) {
2021-03-18 02:09:10 +13:00
token, ok := manager.getToken(r)
2020-11-28 07:59:54 +13:00
if !ok {
2021-08-30 03:09:13 +12:00
return nil, errors.New("no authentication provided")
2020-11-02 06:39:12 +13:00
}
session, ok := manager.GetByToken(token)
2020-11-28 07:59:54 +13:00
if !ok {
2021-08-30 03:09:13 +12:00
return nil, types.ErrSessionNotFound
2020-12-07 06:48:50 +13:00
}
2021-03-15 07:58:15 +13:00
if !session.Profile().CanLogin {
2021-08-30 03:09:13 +12:00
return nil, types.ErrSessionLoginDisabled
2021-03-15 07:58:15 +13:00
}
2020-11-28 07:59:54 +13:00
return session, nil
2020-11-02 06:39:12 +13:00
}
2020-11-29 03:22:04 +13:00
2021-03-18 02:09:10 +13:00
func (manager *SessionManagerCtx) getToken(r *http.Request) (string, bool) {
2021-04-25 07:11:07 +12:00
if manager.CookieEnabled() {
// get from Cookie
cookie, err := r.Cookie(manager.config.CookieName)
if err == nil {
return cookie.Value, true
}
}
2021-03-14 08:42:56 +13: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-29 03:22:04 +13:00
}
2021-03-14 08:42:56 +13:00
// get from URL
token := r.URL.Query().Get("token")
if token != "" {
return token, true
2020-11-29 03:22:04 +13:00
}
2021-03-14 08:42:56 +13:00
return "", false
2021-02-15 02:40:17 +13:00
}