neko/internal/session/auth.go

51 lines
950 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
}
session, ok := manager.GetByToken(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
}
2021-03-15 07:58:15 +13:00
if !session.Profile().CanLogin {
return nil, fmt.Errorf("login disabled")
}
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 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
}
// get from Cookie
cookie, err := r.Cookie("NEKO_SESSION")
if err == nil {
return cookie.Value, true
}
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
}