neko/internal/session/auth.go

57 lines
1.0 KiB
Go
Raw Normal View History

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
"demodesk/neko/internal/utils"
)
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
id, err := utils.NewUID(32)
if err != nil {
2020-11-02 08:23:09 +13:00
return nil, err
2020-11-02 06:39:12 +13:00
}
2020-11-02 08:23:09 +13:00
return manager.New(id, isAdmin), nil
}
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
}