Change Authentification
Signed-off-by: Sacha Al Himdani <sacha@getprobo.com>
This commit is contained in:
@@ -1,5 +1,9 @@
|
|||||||
import { graphql } from 'react-relay';
|
import { graphql } from 'react-relay';
|
||||||
import { useLazyLoadQuery } from 'react-relay';
|
import { useLazyLoadQuery } from 'react-relay';
|
||||||
|
import type {
|
||||||
|
TrustCenterAccessGraphQuery,
|
||||||
|
TrustCenterAccessGraphQuery$data
|
||||||
|
} from "./__generated__/TrustCenterAccessGraphQuery.graphql";
|
||||||
|
|
||||||
export const trustCenterAccessesQuery = graphql`
|
export const trustCenterAccessesQuery = graphql`
|
||||||
query TrustCenterAccessGraphQuery($trustCenterId: ID!) {
|
query TrustCenterAccessGraphQuery($trustCenterId: ID!) {
|
||||||
@@ -90,6 +94,6 @@ export const deleteTrustCenterAccessMutation = graphql`
|
|||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
export function useTrustCenterAccesses(trustCenterId: string) {
|
export function useTrustCenterAccesses(trustCenterId: string): TrustCenterAccessGraphQuery$data {
|
||||||
return useLazyLoadQuery(trustCenterAccessesQuery, { trustCenterId });
|
return useLazyLoadQuery<TrustCenterAccessGraphQuery>(trustCenterAccessesQuery, { trustCenterId });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import {
|
|||||||
deleteTrustCenterAccessMutation
|
deleteTrustCenterAccessMutation
|
||||||
} from "/hooks/graph/TrustCenterAccessGraph";
|
} from "/hooks/graph/TrustCenterAccessGraph";
|
||||||
import { useMutation } from "react-relay";
|
import { useMutation } from "react-relay";
|
||||||
import type { TrustCenterAccessGraphQuery$data } from "/hooks/graph/__generated__/TrustCenterAccessGraphQuery.graphql";
|
|
||||||
|
|
||||||
type ContextType = {
|
type ContextType = {
|
||||||
organization: {
|
organization: {
|
||||||
@@ -41,7 +40,7 @@ export default function TrustCenterAccessTab() {
|
|||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
};
|
};
|
||||||
|
|
||||||
const data = useTrustCenterAccesses(organization.trustCenter?.id || "");
|
const trustCenterData = useTrustCenterAccesses(organization.trustCenter?.id || "");
|
||||||
|
|
||||||
if (!organization.trustCenter?.id) {
|
if (!organization.trustCenter?.id) {
|
||||||
return (
|
return (
|
||||||
@@ -63,7 +62,6 @@ export default function TrustCenterAccessTab() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const trustCenterData = data as TrustCenterAccessGraphQuery$data | null;
|
|
||||||
const accesses: AccessType[] = trustCenterData?.node?.accesses?.edges ?
|
const accesses: AccessType[] = trustCenterData?.node?.accesses?.edges ?
|
||||||
trustCenterData.node.accesses.edges.map(edge => ({
|
trustCenterData.node.accesses.edges.map(edge => ({
|
||||||
id: edge.node.id,
|
id: edge.node.id,
|
||||||
@@ -343,13 +341,6 @@ export default function TrustCenterAccessTab() {
|
|||||||
</DialogContent>
|
</DialogContent>
|
||||||
|
|
||||||
<DialogFooter>
|
<DialogFooter>
|
||||||
<Button
|
|
||||||
variant="secondary"
|
|
||||||
onClick={() => dialogRef.current?.close()}
|
|
||||||
disabled={isCreating}
|
|
||||||
>
|
|
||||||
{__("Cancel")}
|
|
||||||
</Button>
|
|
||||||
<Button onClick={handleInvite} disabled={isCreating}>
|
<Button onClick={handleInvite} disabled={isCreating}>
|
||||||
{isCreating && <Spinner />}
|
{isCreating && <Spinner />}
|
||||||
{__("Send Invitation")}
|
{__("Send Invitation")}
|
||||||
|
|||||||
@@ -103,10 +103,6 @@ func NewService(
|
|||||||
return svc, nil
|
return svc, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) GetEncryptionKey() cipher.EncryptionKey {
|
|
||||||
return s.encryptionKey
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Service) WithTenant(tenantID gid.TenantID) *TenantService {
|
func (s *Service) WithTenant(tenantID gid.TenantID) *TenantService {
|
||||||
tenantService := &TenantService{
|
tenantService := &TenantService{
|
||||||
pg: s.pg,
|
pg: s.pg,
|
||||||
|
|||||||
@@ -334,7 +334,9 @@ func (s TrustCenterAccessService) sendAccessEmail(ctx context.Context, access *c
|
|||||||
Scheme: "https",
|
Scheme: "https",
|
||||||
Host: s.svc.hostname,
|
Host: s.svc.hostname,
|
||||||
Path: "/trust/" + trustCenter.Slug + "/access",
|
Path: "/trust/" + trustCenter.Slug + "/access",
|
||||||
RawQuery: "token=" + url.QueryEscape(accessToken),
|
RawQuery: url.Values{
|
||||||
|
"token": []string{accessToken},
|
||||||
|
}.Encode(),
|
||||||
}
|
}
|
||||||
|
|
||||||
return s.usrmgr.SendTrustCenterAccessEmail(ctx, access.Name, access.Email, organization.Name, accessURL.String())
|
return s.usrmgr.SendTrustCenterAccessEmail(ctx, access.Name, access.Email, organization.Name, accessURL.String())
|
||||||
|
|||||||
@@ -7174,7 +7174,6 @@ type Mutation {
|
|||||||
input: UpdateTrustCenterInput!
|
input: UpdateTrustCenterInput!
|
||||||
): UpdateTrustCenterPayload!
|
): UpdateTrustCenterPayload!
|
||||||
|
|
||||||
|
|
||||||
revokeTrustCenterAccess(
|
revokeTrustCenterAccess(
|
||||||
input: RevokeTrustCenterAccessInput!
|
input: RevokeTrustCenterAccessInput!
|
||||||
): RevokeTrustCenterAccessPayload!
|
): RevokeTrustCenterAccessPayload!
|
||||||
@@ -7364,8 +7363,6 @@ input UpdateTrustCenterInput {
|
|||||||
slug: String
|
slug: String
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
input RevokeTrustCenterAccessInput {
|
input RevokeTrustCenterAccessInput {
|
||||||
accessId: ID!
|
accessId: ID!
|
||||||
}
|
}
|
||||||
|
|||||||
59
pkg/server/api/trust/v1/auth/auth.go
Normal file
59
pkg/server/api/trust/v1/auth/auth.go
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
|
||||||
|
//
|
||||||
|
// Permission to use, copy, modify, and/or distribute this software for any
|
||||||
|
// purpose with or without fee is hereby granted, provided that the above
|
||||||
|
// copyright notice and this permission notice appear in all copies.
|
||||||
|
//
|
||||||
|
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||||
|
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||||
|
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||||
|
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||||
|
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||||
|
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||||
|
// PERFORMANCE OF THIS SOFTWARE.
|
||||||
|
|
||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/99designs/gqlgen/graphql"
|
||||||
|
"github.com/getprobo/probo/pkg/coredata"
|
||||||
|
"github.com/getprobo/probo/pkg/gid"
|
||||||
|
"github.com/getprobo/probo/pkg/server/api/trust/v1/types"
|
||||||
|
)
|
||||||
|
|
||||||
|
type TokenAccessData struct {
|
||||||
|
TrustCenterID gid.GID
|
||||||
|
Email string
|
||||||
|
TenantID gid.TenantID
|
||||||
|
Scope string
|
||||||
|
}
|
||||||
|
|
||||||
|
type ContextAccessor interface {
|
||||||
|
UserFromContext(ctx context.Context) *coredata.User
|
||||||
|
TokenAccessFromContext(ctx context.Context) *TokenAccessData
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetCurrentUserRole(ctx context.Context, accessor ContextAccessor) types.Role {
|
||||||
|
user := accessor.UserFromContext(ctx)
|
||||||
|
tokenAccess := accessor.TokenAccessFromContext(ctx)
|
||||||
|
|
||||||
|
if user != nil || tokenAccess != nil {
|
||||||
|
return types.RoleUser
|
||||||
|
}
|
||||||
|
return types.RoleNone
|
||||||
|
}
|
||||||
|
|
||||||
|
func MustBeAuthenticatedDirective(accessor ContextAccessor) func(ctx context.Context, obj interface{}, next graphql.Resolver, role *types.Role) (interface{}, error) {
|
||||||
|
return func(ctx context.Context, obj interface{}, next graphql.Resolver, role *types.Role) (interface{}, error) {
|
||||||
|
currentRole := GetCurrentUserRole(ctx, accessor)
|
||||||
|
|
||||||
|
if role != nil && *role == types.RoleUser && currentRole == types.RoleNone {
|
||||||
|
return nil, fmt.Errorf("access denied: authentication required")
|
||||||
|
}
|
||||||
|
|
||||||
|
return next(ctx)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,25 +18,23 @@ package trust_v1
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/base64"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"runtime/debug"
|
"runtime/debug"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/99designs/gqlgen/graphql"
|
|
||||||
"github.com/99designs/gqlgen/graphql/handler"
|
"github.com/99designs/gqlgen/graphql/handler"
|
||||||
"github.com/99designs/gqlgen/graphql/handler/extension"
|
"github.com/99designs/gqlgen/graphql/handler/extension"
|
||||||
"github.com/99designs/gqlgen/graphql/handler/transport"
|
"github.com/99designs/gqlgen/graphql/handler/transport"
|
||||||
"github.com/99designs/gqlgen/graphql/playground"
|
"github.com/99designs/gqlgen/graphql/playground"
|
||||||
"github.com/getprobo/probo/pkg/coredata"
|
"github.com/getprobo/probo/pkg/coredata"
|
||||||
"github.com/getprobo/probo/pkg/crypto/cipher"
|
|
||||||
"github.com/getprobo/probo/pkg/gid"
|
"github.com/getprobo/probo/pkg/gid"
|
||||||
|
"github.com/getprobo/probo/pkg/probo"
|
||||||
"github.com/getprobo/probo/pkg/securecookie"
|
"github.com/getprobo/probo/pkg/securecookie"
|
||||||
|
"github.com/getprobo/probo/pkg/server/api/trust/v1/auth"
|
||||||
"github.com/getprobo/probo/pkg/server/api/trust/v1/schema"
|
"github.com/getprobo/probo/pkg/server/api/trust/v1/schema"
|
||||||
"github.com/getprobo/probo/pkg/server/api/trust/v1/types"
|
"github.com/getprobo/probo/pkg/statelesstoken"
|
||||||
"github.com/getprobo/probo/pkg/trust"
|
"github.com/getprobo/probo/pkg/trust"
|
||||||
"github.com/getprobo/probo/pkg/usrmgr"
|
"github.com/getprobo/probo/pkg/usrmgr"
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
@@ -58,21 +56,6 @@ type (
|
|||||||
}
|
}
|
||||||
|
|
||||||
ctxKey struct{ name string }
|
ctxKey struct{ name string }
|
||||||
|
|
||||||
TokenAccessData struct {
|
|
||||||
TrustCenterID gid.GID
|
|
||||||
Email string
|
|
||||||
TenantID gid.TenantID
|
|
||||||
Scope string
|
|
||||||
}
|
|
||||||
|
|
||||||
TrustCenterTokenData struct {
|
|
||||||
TrustCenterID gid.GID `json:"trust_center_id"`
|
|
||||||
Email string `json:"email"`
|
|
||||||
TenantID gid.TenantID `json:"tenant_id"`
|
|
||||||
Scope string `json:"scope"`
|
|
||||||
ExpiresAt time.Time `json:"expires_at"`
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -97,19 +80,19 @@ func UserFromContext(ctx context.Context) *coredata.User {
|
|||||||
return user
|
return user
|
||||||
}
|
}
|
||||||
|
|
||||||
func TokenAccessFromContext(ctx context.Context) *TokenAccessData {
|
func TokenAccessFromContext(ctx context.Context) *auth.TokenAccessData {
|
||||||
tokenAccess, _ := ctx.Value(tokenAccessContextKey).(*TokenAccessData)
|
tokenAccess, _ := ctx.Value(tokenAccessContextKey).(*auth.TokenAccessData)
|
||||||
return tokenAccess
|
return tokenAccess
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetCurrentUserRole(ctx context.Context) types.Role {
|
// UserFromContext implements auth.ContextAccessor interface
|
||||||
user := UserFromContext(ctx)
|
func (r *Resolver) UserFromContext(ctx context.Context) *coredata.User {
|
||||||
tokenAccess := TokenAccessFromContext(ctx)
|
return UserFromContext(ctx)
|
||||||
|
|
||||||
if user != nil || tokenAccess != nil {
|
|
||||||
return types.RoleUser
|
|
||||||
}
|
}
|
||||||
return types.RoleNone
|
|
||||||
|
// TokenAccessFromContext implements auth.ContextAccessor interface
|
||||||
|
func (r *Resolver) TokenAccessFromContext(ctx context.Context) *auth.TokenAccessData {
|
||||||
|
return TokenAccessFromContext(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewMux(
|
func NewMux(
|
||||||
@@ -120,37 +103,29 @@ func NewMux(
|
|||||||
) *chi.Mux {
|
) *chi.Mux {
|
||||||
r := chi.NewMux()
|
r := chi.NewMux()
|
||||||
|
|
||||||
encryptionKey := trustSvc.GetEncryptionKey()
|
r.Handle("/graphql", graphqlHandler(logger, usrmgrSvc, trustSvc, authCfg))
|
||||||
|
|
||||||
r.Handle("/graphql", graphqlHandler(logger, usrmgrSvc, trustSvc, authCfg, encryptionKey))
|
|
||||||
|
|
||||||
r.Handle("/playground", playground.Handler("GraphQL Playground", "/api/trust/v1/graphql"))
|
r.Handle("/playground", playground.Handler("GraphQL Playground", "/api/trust/v1/graphql"))
|
||||||
|
|
||||||
r.Post("/trust-center-access/authenticate", authTokenHandler(trustSvc, authCfg, encryptionKey))
|
r.Post("/trust-center-access/authenticate", authTokenHandler(trustSvc, authCfg))
|
||||||
r.Delete("/trust-center-access/logout", trustCenterLogoutHandler(authCfg))
|
r.Delete("/trust-center-access/logout", trustCenterLogoutHandler(authCfg))
|
||||||
|
|
||||||
return r
|
return r
|
||||||
}
|
}
|
||||||
|
|
||||||
func graphqlHandler(logger *log.Logger, usrmgrSvc *usrmgr.Service, trustSvc *trust.Service, authCfg AuthConfig, encryptionKey cipher.EncryptionKey) http.HandlerFunc {
|
func graphqlHandler(logger *log.Logger, usrmgrSvc *usrmgr.Service, trustSvc *trust.Service, authCfg AuthConfig) http.HandlerFunc {
|
||||||
var mb int64 = 1 << 20
|
var mb int64 = 1 << 20
|
||||||
|
|
||||||
c := schema.Config{
|
resolver := &Resolver{
|
||||||
Resolvers: &Resolver{
|
|
||||||
trustCenterSvc: trustSvc,
|
trustCenterSvc: trustSvc,
|
||||||
authCfg: authCfg,
|
authCfg: authCfg,
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
c.Directives.MustBeAuthenticated = func(ctx context.Context, obj interface{}, next graphql.Resolver, role *types.Role) (interface{}, error) {
|
c := schema.Config{
|
||||||
currentRole := GetCurrentUserRole(ctx)
|
Resolvers: resolver,
|
||||||
|
|
||||||
if role != nil && *role == types.RoleUser && currentRole == types.RoleNone {
|
|
||||||
return nil, fmt.Errorf("access denied: authentication required")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return next(ctx)
|
c.Directives.MustBeAuthenticated = auth.MustBeAuthenticatedDirective(resolver)
|
||||||
}
|
|
||||||
|
|
||||||
es := schema.NewExecutableSchema(c)
|
es := schema.NewExecutableSchema(c)
|
||||||
|
|
||||||
@@ -175,7 +150,7 @@ func graphqlHandler(logger *log.Logger, usrmgrSvc *usrmgr.Service, trustSvc *tru
|
|||||||
return errors.New("internal server error")
|
return errors.New("internal server error")
|
||||||
})
|
})
|
||||||
|
|
||||||
return WithSession(usrmgrSvc, trustSvc, authCfg, encryptionKey, srv.ServeHTTP)
|
return WithSession(usrmgrSvc, trustSvc, authCfg, srv.ServeHTTP)
|
||||||
}
|
}
|
||||||
|
|
||||||
// TrustService returns a trust service scoped to the given tenant
|
// TrustService returns a trust service scoped to the given tenant
|
||||||
@@ -188,90 +163,125 @@ func (r *Resolver) GetTenantService(ctx context.Context, tenantID gid.TenantID)
|
|||||||
return r.trustCenterSvc.WithTenant(tenantID)
|
return r.trustCenterSvc.WithTenant(tenantID)
|
||||||
}
|
}
|
||||||
|
|
||||||
func WithSession(usrmgrSvc *usrmgr.Service, trustSvc *trust.Service, authCfg AuthConfig, encryptionKey cipher.EncryptionKey, next http.HandlerFunc) http.HandlerFunc {
|
func WithSession(usrmgrSvc *usrmgr.Service, trustSvc *trust.Service, authCfg AuthConfig, next http.HandlerFunc) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
ctx := r.Context()
|
ctx := r.Context()
|
||||||
|
|
||||||
|
if authCtx := trySessionAuth(ctx, w, r, usrmgrSvc, authCfg); authCtx != nil {
|
||||||
|
next(w, r.WithContext(authCtx))
|
||||||
|
updateSessionIfNeeded(authCtx, usrmgrSvc)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if authCtx := tryTokenAuth(ctx, w, r, trustSvc, authCfg); authCtx != nil {
|
||||||
|
next(w, r.WithContext(authCtx))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
next(w, r.WithContext(ctx))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func trySessionAuth(ctx context.Context, w http.ResponseWriter, r *http.Request, usrmgrSvc *usrmgr.Service, authCfg AuthConfig) context.Context {
|
||||||
cookieValue, err := securecookie.Get(r, securecookie.DefaultConfig(
|
cookieValue, err := securecookie.Get(r, securecookie.DefaultConfig(
|
||||||
authCfg.CookieName,
|
authCfg.CookieName,
|
||||||
authCfg.CookieSecret,
|
authCfg.CookieSecret,
|
||||||
))
|
))
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
if err == nil {
|
|
||||||
sessionID, err := gid.ParseGID(cookieValue)
|
sessionID, err := gid.ParseGID(cookieValue)
|
||||||
if err == nil {
|
if err != nil {
|
||||||
|
clearSessionCookie(w, authCfg)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
session, err := usrmgrSvc.GetSession(ctx, sessionID)
|
session, err := usrmgrSvc.GetSession(ctx, sessionID)
|
||||||
if err == nil {
|
if err != nil {
|
||||||
|
clearSessionCookie(w, authCfg)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
user, err := usrmgrSvc.GetUserBySession(ctx, sessionID)
|
user, err := usrmgrSvc.GetUserBySession(ctx, sessionID)
|
||||||
if err == nil {
|
if err != nil {
|
||||||
|
clearSessionCookie(w, authCfg)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
tenantIDs, err := usrmgrSvc.ListTenantsForUserID(ctx, user.ID)
|
tenantIDs, err := usrmgrSvc.ListTenantsForUserID(ctx, user.ID)
|
||||||
if err == nil {
|
if err != nil {
|
||||||
|
clearSessionCookie(w, authCfg)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
ctx = context.WithValue(ctx, sessionContextKey, session)
|
ctx = context.WithValue(ctx, sessionContextKey, session)
|
||||||
ctx = context.WithValue(ctx, userContextKey, user)
|
ctx = context.WithValue(ctx, userContextKey, user)
|
||||||
ctx = context.WithValue(ctx, userTenantContextKey, &tenantIDs)
|
ctx = context.WithValue(ctx, userTenantContextKey, &tenantIDs)
|
||||||
|
|
||||||
next(w, r.WithContext(ctx))
|
return ctx
|
||||||
|
|
||||||
if err := usrmgrSvc.UpdateSession(ctx, session); err != nil {
|
|
||||||
panic(fmt.Errorf("failed to update session: %w", err))
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func tryTokenAuth(ctx context.Context, w http.ResponseWriter, r *http.Request, trustSvc *trust.Service, authCfg AuthConfig) context.Context {
|
||||||
|
cookie, err := r.Cookie(TokenCookieName)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
payload, err := statelesstoken.ValidateToken[probo.TrustCenterAccessData](
|
||||||
|
authCfg.CookieSecret,
|
||||||
|
probo.TokenTypeTrustCenterAccess,
|
||||||
|
cookie.Value,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
clearTokenCookie(w, authCfg)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
tenantID := payload.Data.TrustCenterID.TenantID()
|
||||||
|
tenantSvc := trustSvc.WithTenant(tenantID)
|
||||||
|
isActive, err := tenantSvc.TrustCenterAccesses.IsAccessActive(ctx, payload.Data.TrustCenterID, payload.Data.Email)
|
||||||
|
|
||||||
|
if err != nil || !isActive {
|
||||||
|
clearTokenCookie(w, authCfg)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
tokenAccess := &auth.TokenAccessData{
|
||||||
|
TrustCenterID: payload.Data.TrustCenterID,
|
||||||
|
Email: payload.Data.Email,
|
||||||
|
TenantID: tenantID,
|
||||||
|
Scope: TokenScopeTrustCenterReadOnly,
|
||||||
|
}
|
||||||
|
|
||||||
|
return context.WithValue(ctx, tokenAccessContextKey, tokenAccess)
|
||||||
|
}
|
||||||
|
|
||||||
|
func clearSessionCookie(w http.ResponseWriter, authCfg AuthConfig) {
|
||||||
securecookie.Clear(w, securecookie.DefaultConfig(
|
securecookie.Clear(w, securecookie.DefaultConfig(
|
||||||
authCfg.CookieName,
|
authCfg.CookieName,
|
||||||
authCfg.CookieSecret,
|
authCfg.CookieSecret,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
tokenCookieValue, err := securecookie.Get(r, securecookie.Config{
|
func clearTokenCookie(w http.ResponseWriter, authCfg AuthConfig) {
|
||||||
|
http.SetCookie(w, &http.Cookie{
|
||||||
Name: TokenCookieName,
|
Name: TokenCookieName,
|
||||||
Secret: authCfg.CookieSecret,
|
Value: "",
|
||||||
})
|
Domain: authCfg.CookieDomain,
|
||||||
|
Path: "/",
|
||||||
if err == nil {
|
MaxAge: -1,
|
||||||
encryptedData, err := base64.StdEncoding.DecodeString(tokenCookieValue)
|
Secure: true,
|
||||||
if err == nil {
|
HttpOnly: true,
|
||||||
decryptedData, err := cipher.Decrypt(encryptedData, encryptionKey)
|
SameSite: http.SameSiteStrictMode,
|
||||||
if err == nil {
|
|
||||||
var tokenData TrustCenterTokenData
|
|
||||||
if err := json.Unmarshal(decryptedData, &tokenData); err == nil {
|
|
||||||
if time.Now().Before(tokenData.ExpiresAt) {
|
|
||||||
tenantSvc := trustSvc.WithTenant(tokenData.TenantID)
|
|
||||||
isActive, err := tenantSvc.TrustCenterAccesses.IsAccessActive(ctx, tokenData.TrustCenterID, tokenData.Email)
|
|
||||||
|
|
||||||
if err == nil && isActive {
|
|
||||||
tokenAccess := &TokenAccessData{
|
|
||||||
TrustCenterID: tokenData.TrustCenterID,
|
|
||||||
Email: tokenData.Email,
|
|
||||||
TenantID: tokenData.TenantID,
|
|
||||||
Scope: tokenData.Scope,
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx = context.WithValue(ctx, tokenAccessContextKey, tokenAccess)
|
|
||||||
next(w, r.WithContext(ctx))
|
|
||||||
return
|
|
||||||
} else {
|
|
||||||
securecookie.Clear(w, securecookie.Config{
|
|
||||||
Name: TokenCookieName,
|
|
||||||
Secret: authCfg.CookieSecret,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
securecookie.Clear(w, securecookie.Config{
|
|
||||||
Name: TokenCookieName,
|
|
||||||
Secret: authCfg.CookieSecret,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Continue without authentication for public access
|
func updateSessionIfNeeded(ctx context.Context, usrmgrSvc *usrmgr.Service) {
|
||||||
next(w, r.WithContext(ctx))
|
session := SessionFromContext(ctx)
|
||||||
|
if session != nil {
|
||||||
|
if err := usrmgrSvc.UpdateSession(ctx, session); err != nil {
|
||||||
|
panic(fmt.Errorf("failed to update session: %w", err))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,15 +16,12 @@ package trust_v1
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/base64"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/getprobo/probo/pkg/crypto/cipher"
|
|
||||||
"github.com/getprobo/probo/pkg/probo"
|
"github.com/getprobo/probo/pkg/probo"
|
||||||
"github.com/getprobo/probo/pkg/securecookie"
|
|
||||||
"github.com/getprobo/probo/pkg/statelesstoken"
|
"github.com/getprobo/probo/pkg/statelesstoken"
|
||||||
"github.com/getprobo/probo/pkg/trust"
|
"github.com/getprobo/probo/pkg/trust"
|
||||||
"go.gearno.de/kit/httpserver"
|
"go.gearno.de/kit/httpserver"
|
||||||
@@ -42,7 +39,7 @@ type (
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
func authTokenHandler(trustSvc *trust.Service, authCfg AuthConfig, encryptionKey cipher.EncryptionKey) http.HandlerFunc {
|
func authTokenHandler(trustSvc *trust.Service, authCfg AuthConfig) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
var req AuthTokenRequest
|
var req AuthTokenRequest
|
||||||
// Limit request body size to 1KB to prevent DoS attacks
|
// Limit request body size to 1KB to prevent DoS attacks
|
||||||
@@ -69,43 +66,28 @@ func authTokenHandler(trustSvc *trust.Service, authCfg AuthConfig, encryptionKey
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
tokenData := TrustCenterTokenData{
|
tokenString, err := statelesstoken.NewToken(
|
||||||
TrustCenterID: accessData.TrustCenterID,
|
authCfg.CookieSecret,
|
||||||
Email: accessData.Email,
|
probo.TokenTypeTrustCenterAccess,
|
||||||
TenantID: accessData.TrustCenterID.TenantID(),
|
24*time.Hour,
|
||||||
Scope: TokenScopeTrustCenterReadOnly,
|
*accessData,
|
||||||
ExpiresAt: time.Now().Add(24 * time.Hour),
|
)
|
||||||
}
|
|
||||||
|
|
||||||
tokenBytes, err := json.Marshal(tokenData)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
httpserver.RenderError(w, http.StatusInternalServerError, fmt.Errorf("failed to serialize token data: %w", err))
|
httpserver.RenderError(w, http.StatusInternalServerError, fmt.Errorf("failed to create token: %w", err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
encryptedTokenData, err := cipher.Encrypt(tokenBytes, encryptionKey)
|
cookie := &http.Cookie{
|
||||||
if err != nil {
|
|
||||||
httpserver.RenderError(w, http.StatusInternalServerError, fmt.Errorf("failed to encrypt token data: %w", err))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
encryptedTokenString := base64.StdEncoding.EncodeToString(encryptedTokenData)
|
|
||||||
|
|
||||||
cookieConfig := securecookie.Config{
|
|
||||||
Name: TokenCookieName,
|
Name: TokenCookieName,
|
||||||
Secret: authCfg.CookieSecret,
|
Value: tokenString,
|
||||||
Domain: authCfg.CookieDomain,
|
Domain: authCfg.CookieDomain,
|
||||||
Path: "/",
|
Path: "/",
|
||||||
MaxAge: int(24 * time.Hour / time.Second), // 24 hours
|
MaxAge: int(24 * time.Hour / time.Second), // 24 hours
|
||||||
Secure: true,
|
Secure: true,
|
||||||
HTTPOnly: true,
|
HttpOnly: true,
|
||||||
SameSite: http.SameSiteStrictMode,
|
SameSite: http.SameSiteStrictMode,
|
||||||
}
|
}
|
||||||
|
http.SetCookie(w, cookie)
|
||||||
if err := securecookie.Set(w, cookieConfig, encryptedTokenString); err != nil {
|
|
||||||
httpserver.RenderError(w, http.StatusInternalServerError, fmt.Errorf("failed to set cookie: %w", err))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
httpserver.RenderJSON(w, http.StatusOK, AuthTokenResponse{
|
httpserver.RenderJSON(w, http.StatusOK, AuthTokenResponse{
|
||||||
Success: true,
|
Success: true,
|
||||||
@@ -117,7 +99,7 @@ func authTokenHandler(trustSvc *trust.Service, authCfg AuthConfig, encryptionKey
|
|||||||
|
|
||||||
func validateTrustCenterAccessToken(ctx context.Context, trustSvc *trust.Service, authCfg AuthConfig, tokenString string) (*probo.TrustCenterAccessData, error) {
|
func validateTrustCenterAccessToken(ctx context.Context, trustSvc *trust.Service, authCfg AuthConfig, tokenString string) (*probo.TrustCenterAccessData, error) {
|
||||||
token, err := statelesstoken.ValidateToken[probo.TrustCenterAccessData](
|
token, err := statelesstoken.ValidateToken[probo.TrustCenterAccessData](
|
||||||
authCfg.CookieSecret,
|
trustSvc.GetTokenSecret(),
|
||||||
probo.TokenTypeTrustCenterAccess,
|
probo.TokenTypeTrustCenterAccess,
|
||||||
tokenString,
|
tokenString,
|
||||||
)
|
)
|
||||||
@@ -133,18 +115,17 @@ func validateTrustCenterAccessToken(ctx context.Context, trustSvc *trust.Service
|
|||||||
|
|
||||||
func trustCenterLogoutHandler(authCfg AuthConfig) http.HandlerFunc {
|
func trustCenterLogoutHandler(authCfg AuthConfig) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
cookieConfig := securecookie.Config{
|
// Clear cookie directly
|
||||||
|
http.SetCookie(w, &http.Cookie{
|
||||||
Name: TokenCookieName,
|
Name: TokenCookieName,
|
||||||
Secret: authCfg.CookieSecret,
|
Value: "",
|
||||||
Domain: authCfg.CookieDomain,
|
Domain: authCfg.CookieDomain,
|
||||||
Path: "/",
|
Path: "/",
|
||||||
MaxAge: -1,
|
MaxAge: -1,
|
||||||
Secure: true,
|
Secure: true,
|
||||||
HTTPOnly: true,
|
HttpOnly: true,
|
||||||
SameSite: http.SameSiteStrictMode,
|
SameSite: http.SameSiteStrictMode,
|
||||||
}
|
})
|
||||||
|
|
||||||
securecookie.Clear(w, cookieConfig)
|
|
||||||
|
|
||||||
w.Header().Set("Clear-Site-Data", "*")
|
w.Header().Set("Clear-Site-Data", "*")
|
||||||
|
|
||||||
|
|||||||
@@ -78,10 +78,6 @@ func NewService(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) GetEncryptionKey() cipher.EncryptionKey {
|
|
||||||
return s.encryptionKey
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Service) WithTenant(tenantID gid.TenantID) *TenantService {
|
func (s *Service) WithTenant(tenantID gid.TenantID) *TenantService {
|
||||||
tenantService := &TenantService{
|
tenantService := &TenantService{
|
||||||
pg: s.pg,
|
pg: s.pg,
|
||||||
@@ -106,3 +102,7 @@ func (s *Service) WithTenant(tenantID gid.TenantID) *TenantService {
|
|||||||
|
|
||||||
return tenantService
|
return tenantService
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetTokenSecret() string {
|
||||||
|
return s.tokenSecret
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user