From 4d930c0c8cb585979798fac2bb254f991faa62fb Mon Sep 17 00:00:00 2001 From: Gabriel Arakaki Giovanini Date: Mon, 26 Jun 2023 22:26:10 +0200 Subject: feat: Add initial user setup --- pkg/ext/middleware.go | 42 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) (limited to 'pkg/ext') diff --git a/pkg/ext/middleware.go b/pkg/ext/middleware.go index 771c0ac..649272e 100644 --- a/pkg/ext/middleware.go +++ b/pkg/ext/middleware.go @@ -4,6 +4,7 @@ import ( "encoding/base64" "time" + "git.sr.ht/~gabrielgio/img/pkg/components/user" "github.com/sirupsen/logrus" "github.com/valyala/fasthttp" ) @@ -54,7 +55,7 @@ func NewAuthMiddleware(key []byte, log *logrus.Entry) *AuthMiddleware { func (a *AuthMiddleware) LoggedIn(next fasthttp.RequestHandler) fasthttp.RequestHandler { return func(ctx *fasthttp.RequestCtx) { path := string(ctx.Path()) - if path == "/login" { + if path == "/login" || path == "/initial" { next(ctx) return } @@ -87,3 +88,42 @@ func (a *AuthMiddleware) LoggedIn(next fasthttp.RequestHandler) fasthttp.Request next(ctx) } } + +type InitialSetupMiddleware struct { + userRepository user.Repository +} + +func NewInitialSetupMiddleware(userRepository user.Repository) *InitialSetupMiddleware { + return &InitialSetupMiddleware{ + userRepository: userRepository, + } +} + +func (i *InitialSetupMiddleware) Check(next fasthttp.RequestHandler) fasthttp.RequestHandler { + return func(ctx *fasthttp.RequestCtx) { + // if user has been set to context it is logged in already + _, ok := ctx.UserValue("token").(*Token) + if ok { + next(ctx) + return + } + + path := string(ctx.Path()) + if path == "/initial" { + next(ctx) + return + } + + exists, err := i.userRepository.Any(ctx) + if err != nil { + InternalServerError(ctx, err) + return + } + + if exists { + next(ctx) + return + } + ctx.Redirect("/initial", 307) + } +} -- cgit v1.2.3