Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Auto-Login via Header #253

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions backend/app/api/handlers/v1/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,12 @@ func WithRegistration(allowRegistration bool) func(*V1Controller) {
}
}

func WithHeaderAuthEnabled(headerAuthEnabled bool) func(*V1Controller) {
return func(ctrl *V1Controller) {
ctrl.headerAuthEnabled = headerAuthEnabled
}
}

func WithSecureCookies(secure bool) func(*V1Controller) {
return func(ctrl *V1Controller) {
ctrl.cookieSecure = secure
Expand All @@ -70,6 +76,7 @@ type V1Controller struct {
maxUploadSize int64
isDemo bool
allowRegistration bool
headerAuthEnabled bool
bus *eventbus.EventBus
url string
}
Expand All @@ -91,6 +98,7 @@ type (
Build Build `json:"build"`
Demo bool `json:"demo"`
AllowRegistration bool `json:"allowRegistration"`
HeaderAuthEnabled bool `json:"headerAuthEnabled"`
}
)

Expand Down Expand Up @@ -125,6 +133,7 @@ func (ctrl *V1Controller) HandleBase(ready ReadyFunc, build Build) errchain.Hand
Build: build,
Demo: ctrl.isDemo,
AllowRegistration: ctrl.allowRegistration,
HeaderAuthEnabled: ctrl.headerAuthEnabled,
})
}
}
Expand Down
20 changes: 18 additions & 2 deletions backend/app/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ var (

func build() string {
short := commit
//goland:noinspection GoBoolExpressions
if len(short) > 7 {
short = short[:7]
}
Expand Down Expand Up @@ -72,6 +73,13 @@ func run(cfg *config.Config) error {
app := new(cfg)
app.setupLogger()

if (cfg.Proxy.HeaderExternalUserName != "" || cfg.Proxy.HeaderExternalUserId != "") && len(cfg.Proxy.TrustedHosts) == 0 {
panic("To use External User login, Trusted Hosts must be set")
}
if cfg.Proxy.HeaderExternalUserName != "" && cfg.Proxy.HeaderExternalUserId == "" {
panic("External User Name header is set but External User ID Header is not set")
}

// =========================================================================
// Initialize Database & Repos

Expand Down Expand Up @@ -173,14 +181,22 @@ func run(cfg *config.Config) error {
logger := log.With().Caller().Logger()

router := chi.NewMux()
router.Use(
var middlewares []func(handler http.Handler) http.Handler
if len(app.conf.Proxy.TrustedHosts) > 0 {
middlewares = append(middlewares,
mid.TrustedIps(logger, app.conf.Proxy.TrustedHosts),
middleware.RealIP,
)
}
middlewares = append(middlewares,
middleware.RequestID,
middleware.RealIP,
mid.Logger(logger),
middleware.Recoverer,
middleware.StripSlashes,
)

router.Use(middlewares...)

chain := errchain.New(mid.Errors(logger))

app.mountRoutes(router, chain, app.repos)
Expand Down
20 changes: 19 additions & 1 deletion backend/app/api/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,21 @@ func getQuery(r *http.Request) (string, error) {
return token, nil
}

func getHeader(external_user_id_header string, external_user_name_header string, user_service *services.UserService) func(r *http.Request) (string, error) {
return func(r *http.Request) (string, error) {
externalId := r.Header.Get(external_user_id_header)
if externalId == "" {
return "", errors.New("external user id header is required")
}
userToken, err := user_service.LoginWithExternalIDHeader(r.Context(), externalId)
if err != nil {
//todo create user
return "", errors.New("no user with provided external user id")
}
return userToken.Raw, nil
}
}

// mwAuthToken is a middleware that will check the database for a stateful token
// and attach it's user to the request context, or return an appropriate error.
// Authorization support is by token via Headers or Query Parameter
Expand All @@ -116,10 +131,13 @@ func (a *app) mwAuthToken(next errchain.Handler) errchain.Handler {
}

if requestToken == "" {
keyFuncs := [...]KeyFunc{
keyFuncs := []KeyFunc{
getBearer,
getQuery,
}
if len(a.conf.Proxy.TrustedHosts) > 0 {
keyFuncs = append(keyFuncs, getHeader(a.conf.Proxy.HeaderExternalUserId, a.conf.Proxy.HeaderExternalUserName, a.services.User))
}

for _, keyFunc := range keyFuncs {
token, err := keyFunc(r)
Expand Down
1 change: 1 addition & 0 deletions backend/app/api/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ func (a *app) mountRoutes(r *chi.Mux, chain *errchain.ErrChain, repos *repo.AllR
a.bus,
v1.WithMaxUploadSize(a.conf.Web.MaxUploadSize),
v1.WithRegistration(a.conf.Options.AllowRegistration),
v1.WithHeaderAuthEnabled(a.conf.Proxy.HeaderExternalUserId != ""),
v1.WithDemoStatus(a.conf.Demo), // Disable Password Change in Demo Mode
v1.WithURL(fmt.Sprintf("%s:%s", a.conf.Web.Host, a.conf.Web.Port)),
)
Expand Down
3 changes: 3 additions & 0 deletions backend/app/api/static/docs/docs.go
Original file line number Diff line number Diff line change
Expand Up @@ -2944,6 +2944,9 @@ const docTemplate = `{
"demo": {
"type": "boolean"
},
"headerAuthEnabled": {
"type": "boolean"
},
"health": {
"type": "boolean"
},
Expand Down
3 changes: 3 additions & 0 deletions backend/app/api/static/docs/swagger.json
Original file line number Diff line number Diff line change
Expand Up @@ -2937,6 +2937,9 @@
"demo": {
"type": "boolean"
},
"headerAuthEnabled": {
"type": "boolean"
},
"health": {
"type": "boolean"
},
Expand Down
2 changes: 2 additions & 0 deletions backend/app/api/static/docs/swagger.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -671,6 +671,8 @@ definitions:
$ref: '#/definitions/v1.Build'
demo:
type: boolean
headerAuthEnabled:
type: boolean
health:
type: boolean
message:
Expand Down
9 changes: 9 additions & 0 deletions backend/internal/core/services/service_user.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,15 @@ func (svc *UserService) Login(ctx context.Context, username, password string, ex
return svc.createSessionToken(ctx, usr.ID, extendedSession)
}

// LoginWithExternalIDHeader returns the user matching the external id provided
func (svc *UserService) LoginWithExternalIDHeader(ctx context.Context, id string) (UserAuthTokenDetail, error) {
usr, err := svc.repos.Users.GetOneExternalID(ctx, id)
if err != nil {
return UserAuthTokenDetail{}, ErrorInvalidLogin
}
return svc.createSessionToken(ctx, usr.ID, false)
}

func (svc *UserService) Logout(ctx context.Context, token string) error {
hash := hasher.HashToken(token)
err := svc.repos.AuthTokens.DeleteToken(ctx, hash)
Expand Down
3 changes: 2 additions & 1 deletion backend/internal/data/ent/migrate/schema.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

75 changes: 74 additions & 1 deletion backend/internal/data/ent/mutation.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions backend/internal/data/ent/schema/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ func (User) Fields() []ent.Field {
Values("user", "owner"),
field.Time("activated_on").
Optional(),
field.String("external_user_id").
Optional().
Sensitive(),
}
}

Expand Down
12 changes: 11 additions & 1 deletion backend/internal/data/ent/user.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading