2020-11-02 06:39:12 +13:00
|
|
|
package session
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
|
2020-11-02 08:23:09 +13:00
|
|
|
"demodesk/neko/internal/types"
|
2020-11-02 06:39:12 +13:00
|
|
|
)
|
|
|
|
|
2021-01-30 10:22:14 +13:00
|
|
|
func (manager *SessionManagerCtx) AuthenticateRequest(r *http.Request) (types.Session, error) {
|
2020-11-29 03:22:04 +13:00
|
|
|
id, secret, ok := getAuthData(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-01-30 10:22:14 +13:00
|
|
|
return manager.Authenticate(id, secret)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (manager *SessionManagerCtx) Authenticate(id string, secret string) (types.Session, error) {
|
2020-11-28 07:59:54 +13:00
|
|
|
session, ok := manager.Get(id)
|
|
|
|
if !ok {
|
|
|
|
return nil, fmt.Errorf("member not found")
|
2020-11-02 06:39:12 +13:00
|
|
|
}
|
|
|
|
|
2020-11-28 07:59:54 +13:00
|
|
|
if !session.VerifySecret(secret) {
|
|
|
|
return nil, fmt.Errorf("invalid password provided")
|
2020-11-02 06:39:12 +13:00
|
|
|
}
|
|
|
|
|
2020-12-07 06:48:50 +13:00
|
|
|
if !session.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
|
|
|
|
|
|
|
func getAuthData(r *http.Request) (string, string, bool) {
|
2021-01-30 10:22:14 +13:00
|
|
|
// get from Cookies
|
|
|
|
cid, err1 := r.Cookie("neko-id")
|
|
|
|
csecret, err2 := r.Cookie("neko-secret")
|
|
|
|
if err1 == nil && err2 == nil {
|
|
|
|
return cid.Value, csecret.Value, true
|
|
|
|
}
|
|
|
|
|
|
|
|
// get from BasicAuth
|
2020-11-29 03:22:04 +13:00
|
|
|
id, secret, ok := r.BasicAuth()
|
|
|
|
if ok {
|
|
|
|
return id, secret, true
|
|
|
|
}
|
|
|
|
|
2021-01-30 10:22:14 +13:00
|
|
|
// get from QueryParams
|
2020-11-29 03:22:04 +13:00
|
|
|
id = r.URL.Query().Get("id")
|
|
|
|
secret = r.URL.Query().Get("secret")
|
|
|
|
if id != "" && secret != "" {
|
|
|
|
return id, secret, true
|
|
|
|
}
|
|
|
|
|
|
|
|
return "", "", false
|
2021-02-15 02:40:17 +13:00
|
|
|
}
|