2020-11-02 06:39:12 +13:00
|
|
|
package session
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
2020-11-02 08:23:09 +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
|
|
|
)
|
|
|
|
|
2020-11-02 08:23:09 +13:00
|
|
|
const (
|
|
|
|
token_name = "password"
|
|
|
|
)
|
|
|
|
|
|
|
|
func (manager *SessionManagerCtx) Authenticate(r *http.Request) (types.Session, error) {
|
|
|
|
token := getToken(r)
|
|
|
|
if token == "" {
|
|
|
|
return nil, fmt.Errorf("no password provided")
|
|
|
|
}
|
2020-11-02 06:39:12 +13:00
|
|
|
|
2020-11-02 08:23:09 +13:00
|
|
|
isAdmin := (token == manager.config.AdminPassword)
|
|
|
|
isUser := (token == manager.config.Password)
|
|
|
|
|
|
|
|
if !isAdmin && !isUser {
|
|
|
|
return nil, fmt.Errorf("invalid password")
|
|
|
|
}
|
2020-11-02 06:39:12 +13:00
|
|
|
|
2020-11-26 10:07:05 +13:00
|
|
|
return manager.Create(types.MemberProfile{
|
|
|
|
IsAdmin: isAdmin,
|
|
|
|
})
|
2020-11-02 08:23:09 +13:00
|
|
|
}
|
|
|
|
|
|
|
|
func getToken(r *http.Request) string {
|
|
|
|
// Get token from query
|
|
|
|
if token := r.URL.Query().Get(token_name); token != "" {
|
|
|
|
return token
|
2020-11-02 06:39:12 +13:00
|
|
|
}
|
|
|
|
|
2020-11-02 08:23:09 +13:00
|
|
|
// Get token from authorization header
|
|
|
|
bearer := r.Header.Get("Authorization")
|
|
|
|
if len(bearer) > 7 && strings.ToUpper(bearer[0:6]) == "BEARER" {
|
|
|
|
return bearer[7:]
|
2020-11-02 06:39:12 +13:00
|
|
|
}
|
|
|
|
|
2020-11-02 08:23:09 +13:00
|
|
|
// Get token from cookie
|
|
|
|
cookie, err := r.Cookie(token_name)
|
|
|
|
if err == nil {
|
|
|
|
return cookie.Value
|
2020-11-02 06:39:12 +13:00
|
|
|
}
|
|
|
|
|
2020-11-02 08:23:09 +13:00
|
|
|
return ""
|
2020-11-02 06:39:12 +13:00
|
|
|
}
|