Compare commits

...

3 commits

Author SHA1 Message Date
17149f2c58 Add file store 2022-10-02 14:39:55 -04:00
f3fd61643d WIP 2022-10-02 08:52:48 -04:00
8cb09bb609 WIP auth flow 2022-09-30 23:54:21 -04:00
5 changed files with 311 additions and 36 deletions

73
pkg/auth/authenticator.go Normal file
View file

@ -0,0 +1,73 @@
package auth
import (
"io"
"net/http"
"github.com/labstack/echo/v4"
"dynatron.me/x/blasphem/pkg/frontend"
)
type Authenticator struct {
Flows FlowStore
}
func (a *Authenticator) InitAuth() {
a.Flows = make(FlowStore)
}
type AuthProvider interface {
ProviderName() string
ProviderID() *string
ProviderType() string
}
type AuthProviderBase struct {
Name string `json:"name"`
ID *string `json:"id"`
Type string `json:"type"`
}
func (bp *AuthProviderBase) ProviderName() string { return bp.Name }
func (bp *AuthProviderBase) ProviderID() *string { return bp.ID }
func (bp *AuthProviderBase) ProviderType() string { return bp.Type }
type LocalProvider struct {
AuthProviderBase
}
var HomeAssistant = "homeassistant"
func hassProvider() *LocalProvider {
return &LocalProvider{
AuthProviderBase: AuthProviderBase{
Name: "Home Assistant Local",
Type: HomeAssistant,
},
}
}
// TODO: make this configurable
func (s *Authenticator) ProvidersHandler(c echo.Context) error {
providers := []AuthProvider{
hassProvider(),
}
return c.JSON(http.StatusOK, providers)
}
func (s *Authenticator) AuthorizeHandler(c echo.Context) error {
authContents, err := frontend.RootFS.Open("authorize.html")
if err != nil {
return err
}
defer authContents.Close()
b, err := io.ReadAll(authContents)
if err != nil {
return err
}
return c.HTML(http.StatusOK, string(b))
}

183
pkg/auth/flow.go Normal file
View file

@ -0,0 +1,183 @@
package auth
import (
"crypto/rand"
"encoding/hex"
"net/http"
"strings"
"time"
"github.com/labstack/echo/v4"
)
type FlowStore map[FlowID]*Flow
type FlowRequest struct {
ClientID string `json:"client_id"`
Handler []*string `json:"handler"`
RedirectURI string `json:"redirect_uri"`
}
type FlowSchemaItem struct {
Type string `json:"type"`
Name string `json:"name"`
Required bool `json:"required"`
}
type FlowType string
const (
TypeForm FlowType = "form"
)
type FlowID string
type Step string
const (
StepInit Step = "init"
)
type Flow struct {
Type FlowType `json:"type"`
ID FlowID `json:"flow_id"`
Handler []*string `json:"handler"`
StepID Step `json:"step_id"`
Schema []FlowSchemaItem `json:"data_schema"`
Errors []string `json:"errors"`
DescPlace *string `json:"description_placeholders"`
LastStep *string `json:"last_step"`
request *FlowRequest
age time.Time
}
func (f *Flow) touch() {
f.age = time.Now()
}
func genFlowID() FlowID {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
panic(err)
}
return FlowID(hex.EncodeToString(b))
}
func (fs FlowStore) register(f *Flow) {
fs.cull()
fs[f.ID] = f
}
const cullAge = time.Minute * 30
func (fs FlowStore) cull() {
for k, v := range fs {
if time.Now().Sub(v.age) > cullAge {
delete(fs, k)
}
}
}
func (fs FlowStore) Get(id FlowID) *Flow {
f, ok := fs[id]
if ok {
return f
}
return nil
}
func (a *Authenticator) NewFlow(r *FlowRequest) *Flow {
flow := &Flow{
Type: TypeForm,
ID: genFlowID(),
StepID: StepInit,
Schema: []FlowSchemaItem{
{
Type: "string",
Name: "username",
Required: true,
},
{
Type: "string",
Name: "password",
Required: true,
},
},
Handler: r.Handler,
Errors: []string{},
request: r,
}
flow.touch()
a.Flows.register(flow)
return flow
}
func (f *Flow) progress(c echo.Context) error {
switch f.StepID {
case StepInit:
var rm map[string]interface{}
err := c.Bind(&rm)
if err != nil {
return c.String(http.StatusBadRequest, err.Error())
}
for _, si := range f.Schema {
if si.Required {
if _, ok := rm[si.Name]; !ok {
return c.String(http.StatusBadRequest, "missing required param "+si.Name)
}
}
}
// TODO: lookup creds, pass, redirect to url
default:
return c.String(http.StatusBadRequest, "unknown flow step")
}
return nil
}
func (a *Authenticator) LoginFlowDeleteHandler(c echo.Context) error {
flowID := c.Param("flow_id")
if flowID == "" {
return c.String(http.StatusBadRequest, "empty flow ID")
}
delete(a.Flows, FlowID(flowID))
return c.String(http.StatusOK, "deleted")
}
func (a *Authenticator) LoginFlowHandler(c echo.Context) error {
if c.Request().Method == http.MethodPost && strings.HasPrefix(c.Request().Header.Get(echo.HeaderContentType), "text/plain") {
// hack around the content-type, Context.JSON refuses to work otherwise
c.Request().Header.Set(echo.HeaderContentType, "application/json")
}
flowID := c.Param("flow_id")
switch flowID {
case "": // new
var flowReq FlowRequest
err := c.Bind(&flowReq)
if err != nil {
return c.String(http.StatusBadRequest, err.Error())
}
resp := a.NewFlow(&flowReq)
return c.JSON(http.StatusOK, resp)
default:
flow := a.Flows.Get(FlowID(flowID))
if flow == nil {
return c.String(http.StatusNotFound, "no such flow")
}
return flow.progress(c)
}
}

View file

@ -12,7 +12,8 @@ import (
) )
type Config struct { type Config struct {
Server *server.Config `yaml:"server"` DataDir *string `yaml:"data_dir,omitempty"`
Server *server.Config `yaml:"server"`
} }
const ( const (

View file

@ -3,61 +3,51 @@ package server
import ( import (
"io/fs" "io/fs"
"log" "log"
"net/http"
"sync" "sync"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"dynatron.me/x/blasphem/pkg/auth" "dynatron.me/x/blasphem/pkg/auth"
"dynatron.me/x/blasphem/pkg/bus" "dynatron.me/x/blasphem/pkg/blas"
"dynatron.me/x/blasphem/pkg/config" "dynatron.me/x/blasphem/pkg/config"
"dynatron.me/x/blasphem/pkg/frontend" "dynatron.me/x/blasphem/pkg/frontend"
) )
type Server struct { type Server struct {
*blas.Blas
*echo.Echo *echo.Echo
*bus.Bus
auth.Authenticator auth.Authenticator
rootFS fs.FS rootFS fs.FS
wg sync.WaitGroup wg sync.WaitGroup
cfg *config.Config
} }
type StatusWriter struct { func (s *Server) installRoutes() {
http.ResponseWriter
status int
}
func (w *StatusWriter) WriteHeader(status int) {
w.status = status
w.ResponseWriter.WriteHeader(status)
}
func logHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rw := &StatusWriter{ResponseWriter: w}
h.ServeHTTP(rw, r)
logRequest(rw.status, r)
})
}
func logRequest(status int, r *http.Request) {
log.Println(r.Method, status, r.URL.Path)
}
func New(cfg *config.Config) (s *Server, err error) {
s = &Server{
Echo: echo.New(),
cfg: cfg,
}
s.Echo.Debug = true
s.Echo.HideBanner = true
s.GET("/", echo.WrapHandler(frontend.FSHandler)) s.GET("/", echo.WrapHandler(frontend.FSHandler))
s.GET("/api/websocket", s.wsHandler) s.GET("/api/websocket", s.wsHandler)
s.GET("/auth/authorize", s.AuthorizeHandler) s.GET("/auth/authorize", s.AuthorizeHandler)
s.GET("/auth/providers", s.ProvidersHandler) s.GET("/auth/providers", s.ProvidersHandler)
s.POST("/auth/login_flow", s.LoginFlowHandler) s.POST("/auth/login_flow", s.LoginFlowHandler)
s.POST("/auth/login_flow/:flow_id", s.LoginFlowHandler)
s.DELETE("/auth/login_flow/:flow_id", s.LoginFlowDeleteHandler)
}
func New(cfg *config.Config) (s *Server, err error) {
b, err := blas.New(cfg)
if err != nil {
return nil, err
}
s = &Server{
Blas: b,
Echo: echo.New(),
}
s.InitAuth()
s.Echo.Debug = true
s.Echo.HideBanner = true
s.installRoutes()
return s, nil return s, nil
} }
@ -65,7 +55,7 @@ func New(cfg *config.Config) (s *Server, err error) {
func (s *Server) Go() error { func (s *Server) Go() error {
s.wg.Add(1) s.wg.Add(1)
go func() { go func() {
err := s.Start(s.cfg.Server.Bind) err := s.Start(s.Config.Server.Bind)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }

28
pkg/storage/storage.go Normal file
View file

@ -0,0 +1,28 @@
package storage
import (
"io/fs"
)
type Data interface {
}
type Item struct {
Version int `json:"version"`
MinorVersion *int `json:"minor_version,omitempty"`
Key string `json:"key"`
Data Data `json:"data"`
}
type Store struct {
fs.FS
}
func Open(dir fs.FS) (*Store, error) {
stor, err := fs.Sub(dir, ".storage")
if err != nil {
return nil, err
}
return &Store{stor}, nil
}