neko/internal/session/auth.go

47 lines
862 B
Go
Raw Normal View History

2020-11-02 06:39:12 +13:00
package session
import (
"fmt"
"net/http"
2021-03-14 09:44:38 +13:00
"strings"
2020-11-02 06:39:12 +13:00
2020-11-02 08:23:09 +13:00
"demodesk/neko/internal/types"
2020-11-02 06:39:12 +13:00
)
2021-03-14 08:42:56 +13:00
func (manager *SessionManagerCtx) Authenticate(r *http.Request) (types.Session, error) {
token, ok := getToken(r)
2020-11-28 07:59:54 +13:00
if !ok {
return nil, fmt.Errorf("no authentication provided")
2020-11-02 06:39:12 +13:00
}
2021-03-14 08:42:56 +13:00
session, ok := manager.Get(token)
2020-11-28 07:59:54 +13:00
if !ok {
2021-03-14 08:42:56 +13:00
return nil, fmt.Errorf("session not found")
2020-12-07 06:48:50 +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-14 08:42:56 +13:00
func getToken(r *http.Request) (string, bool) {
// get from Cookie
2021-03-14 09:11:48 +13:00
cookie, err := r.Cookie("NEKO_SESSION")
2021-03-14 08:42:56 +13:00
if err == nil {
return cookie.Value, true
2021-01-30 10:22:14 +13:00
}
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
}