MSP-7470 Init user auth

This commit is contained in:
Синельник Тимур Романович committed 2026-04-01 10:05:20 +03:00
1 parent b67eb8137c
commit eb6326c343
35 files changed
+1059 -142

No files matched your search

+7 -2
View File
@@ -4,12 +4,13 @@ import (
"context"
"isp-gate-service/domain"
"isp-gate-service/entity"
"github.com/pkg/errors"
)
type AdminAuth interface {
Authenticate(ctx context.Context, token string) (*domain.AdminAuthenticateResponse, error)
Authenticate(ctx context.Context, token string) (*entity.AdminAuthenticateResponse, error)
Authorize(ctx context.Context, adminId int, permission string) (bool, error)
}
@@ -30,7 +31,11 @@ func (s Admin) AdminAuthenticate(ctx context.Context, token string) (*domain.Adm
if err != nil {
return nil, errors.WithMessage(err, "get admin token data from admin service")
}
return resp, nil
return &domain.AdminAuthenticateResponse{
Authenticated: resp.Authenticated,
ErrorReason: resp.ErrorReason,
AdminId: resp.AdminId,
}, nil
}
func (s Admin) AdminAuthorize(ctx context.Context, adminId int, permission string) (bool, error) {
+45 -18
View File
@@ -2,54 +2,81 @@ package service
import (
"context"
"isp-gate-service/domain"
"isp-gate-service/entity"
"github.com/pkg/errors"
"isp-gate-service/domain"
)
type AuthenticationCache interface {
Get(ctx context.Context, token string) (*domain.AuthData, error)
Set(ctx context.Context, token string, data domain.AuthData) error
Get(ctx context.Context, token string) (*entity.AppAuthData, error)
Set(ctx context.Context, token string, data entity.AppAuthData) error
}
type AuthenticationRepo interface {
Authenticate(ctx context.Context, token string) (*domain.AuthenticateResponse, error)
Authenticate(ctx context.Context, token string) (*entity.AuthenticateResponse, error)
}
type Auth struct {
type Authentication struct {
cache AuthenticationCache
repo AuthenticationRepo
}
func NewAuthentication(cache AuthenticationCache, repo AuthenticationRepo) Auth {
return Auth{
func NewAuthentication(
cache AuthenticationCache,
repo AuthenticationRepo,
) Authentication {
return Authentication{
cache: cache,
repo: repo,
}
}
func (s Auth) Authenticate(ctx context.Context, token string) (*domain.AuthenticateResponse, error) {
func (s Authentication) Authenticate(ctx context.Context, token string) (*domain.AuthenticateAppResponse, error) {
authData, err := s.cache.Get(ctx, token)
if errors.Is(err, domain.ErrAuthenticationCacheMiss) {
switch {
case errors.Is(err, domain.ErrAuthenticationCacheMiss):
resp, err := s.repo.Authenticate(ctx, token)
if err != nil {
return nil, errors.WithMessage(err, "auth repo authenticate")
}
if !resp.Authenticated {
return resp, nil
return s.convertAuthReponse(resp), nil
}
err = s.cache.Set(ctx, token, *resp.AuthData)
if err != nil {
return nil, errors.WithMessage(err, "auth cache set")
}
return resp, nil
}
if err != nil {
return s.convertAuthReponse(resp), nil
case err != nil:
return nil, errors.WithMessage(err, "auth cache get")
default:
return &domain.AuthenticateAppResponse{
Authenticated: true,
ErrorReason: "",
AuthData: s.convertAuthData(authData),
}, nil
}
}
func (s Authentication) convertAuthReponse(resp *entity.AuthenticateResponse) *domain.AuthenticateAppResponse {
return &domain.AuthenticateAppResponse{
Authenticated: resp.Authenticated,
ErrorReason: resp.ErrorReason,
AuthData: s.convertAuthData(resp.AuthData),
}
}
func (Authentication) convertAuthData(authData *entity.AppAuthData) *domain.AppAuthData {
if authData == nil {
return nil
}
return &domain.AppAuthData{
AppName: authData.AppName,
SystemId: authData.SystemId,
DomainId: authData.DomainId,
ServiceId: authData.ServiceId,
ApplicationId: authData.ApplicationId,
}
return &domain.AuthenticateResponse{
Authenticated: true,
ErrorReason: "",
AuthData: authData,
}, nil
}
+3 -3
View File
@@ -3,7 +3,7 @@ package service
import (
"context"
"fmt"
"isp-gate-service/domain"
"isp-gate-service/entity"
"github.com/pkg/errors"
)
@@ -14,7 +14,7 @@ type AuthorizationCache interface {
}
type AuthorizationRepo interface {
Authorize(ctx context.Context, req domain.AuthorizeRequest) (bool, error)
Authorize(ctx context.Context, req entity.AuthorizeRequest) (bool, error)
}
type Authorization struct {
@@ -39,7 +39,7 @@ func (s Authorization) Authorize(ctx context.Context, applicationId int, httpMet
return true, nil
}
ok, err = s.repo.Authorize(ctx, domain.AuthorizeRequest{
ok, err = s.repo.Authorize(ctx, entity.AuthorizeRequest{
ApplicationId: applicationId,
HttpMethod: httpMethod,
Endpoint: endpoint,
+41
View File
@@ -0,0 +1,41 @@
package token_provider
import (
"isp-gate-service/conf"
"isp-gate-service/request"
"net/http"
"strings"
"github.com/pkg/errors"
)
type CookieProvider struct {
cookieName string
validate bool
}
func NewCookieProvider(cfg conf.CookieTokenProvider) CookieProvider {
return CookieProvider{
cookieName: cfg.CookieName,
validate: cfg.Validate,
}
}
func (p CookieProvider) ExtractToken(ctx *request.Context) (string, error) {
cookie, err := ctx.Request().Cookie(p.cookieName)
switch {
case errors.Is(err, http.ErrNoCookie):
return "", nil
case err != nil:
return "", errors.WithMessagef(err, "get cookie with name '%s'", p.cookieName)
}
if !p.validate {
return strings.TrimSpace(cookie.Value), nil
}
err = cookie.Valid()
if err != nil {
return "", errors.WithMessagef(err, "validate cookie with name '%s'", p.cookieName)
}
return strings.TrimSpace(cookie.Value), nil
}
+22
View File
@@ -0,0 +1,22 @@
package token_provider
import (
"isp-gate-service/conf"
"isp-gate-service/request"
"strings"
)
type HeaderProvider struct {
headerName string
}
func NewHeaderProvider(cfg conf.HeaderTokenProvider) HeaderProvider {
return HeaderProvider{
headerName: cfg.HeaderName,
}
}
func (p HeaderProvider) ExtractToken(ctx *request.Context) (string, error) {
value := ctx.Request().Header.Get(p.headerName)
return strings.TrimSpace(value), nil
}
+211
View File
@@ -0,0 +1,211 @@
package service
import (
"context"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/entity"
"isp-gate-service/request"
"isp-gate-service/service/token_provider"
"sort"
"strings"
"github.com/pkg/errors"
)
type UserAuthenticationCache interface {
Get(ctx context.Context, authModuleName string, token string) (*entity.UserAuthData, error)
Set(ctx context.Context, authModuleName string, token string, data entity.UserAuthData) error
}
type UserAuthenticationRepo interface {
Authenticate(ctx context.Context, authModuleName string, token string) (*entity.UserAuthenticateResponse, error)
}
type TokenProvider interface {
ExtractToken(ctx *request.Context) (string, error)
}
type userAuthSetting struct {
tokenProviders []string
endpointPrefix string
authModuleName string
skipAppAuth bool
}
type UserAuthentication struct {
cache UserAuthenticationCache
repo UserAuthenticationRepo
endpointsSettings []userAuthSetting
tokenProviders map[string]TokenProvider
}
func NewUserAuthentication(
cfg conf.UserAuth,
cache UserAuthenticationCache,
repo UserAuthenticationRepo,
) (UserAuthentication, error) {
tokenProviders := make(map[string]TokenProvider, len(cfg.TokenProviders))
for i, provider := range cfg.TokenProviders {
_, ok := tokenProviders[provider.Name]
if ok {
return UserAuthentication{}, errors.Errorf("token provider name must have unique name, found duplicate at [%d] with name '%s'", i, provider.Name)
}
tokenProvider, err := tokenProviderFromConfig(provider)
if err != nil {
return UserAuthentication{}, errors.WithMessagef(err, "init token provider with name '%s'", provider.Name)
}
tokenProviders[provider.Name] = tokenProvider
}
endpointsSettings := make([]userAuthSetting, 0, len(cfg.EndpointSettings))
for _, endpoint := range cfg.EndpointSettings {
prefix := strings.TrimPrefix(endpoint.EndpointPrefix, "/")
for _, providerName := range endpoint.TokenProviders {
_, ok := tokenProviders[providerName]
if !ok {
return UserAuthentication{}, errors.Errorf("endpoint with prefix '%s' has unknown token provider '%s'", prefix, providerName)
}
}
endpointsSettings = append(endpointsSettings, userAuthSetting{
endpointPrefix: prefix,
authModuleName: endpoint.AuthModuleName,
tokenProviders: endpoint.TokenProviders,
skipAppAuth: endpoint.SkipAppAuth,
})
}
sort.Slice(endpointsSettings, func(i, j int) bool {
return len(endpointsSettings[i].endpointPrefix) > len(endpointsSettings[j].endpointPrefix)
})
return UserAuthentication{
cache: cache,
repo: repo,
endpointsSettings: endpointsSettings,
tokenProviders: tokenProviders,
}, nil
}
func (s UserAuthentication) Authenticate(ctx *request.Context) (*domain.AuthenticateUserResponse, error) {
normalizedEndpoint := ctx.EndpointMeta().NormalizedEndpoint
for _, setting := range s.endpointsSettings {
if !strings.HasPrefix(normalizedEndpoint, setting.endpointPrefix) {
continue
}
token, err := s.extractToken(ctx, setting.tokenProviders)
if err != nil {
return nil, errors.WithMessage(err, "extract user token")
}
if token == "" {
return &domain.AuthenticateUserResponse{
Authenticated: false,
ErrorReason: "failed extract user token",
}, nil
}
resp, err := s.authenticate(
ctx.Context(),
setting.authModuleName,
token,
setting.skipAppAuth,
)
if err != nil {
return nil, errors.WithMessage(err, "auth")
}
return resp, nil
}
return &domain.AuthenticateUserResponse{
ShouldSkip: true,
}, nil
}
func (s UserAuthentication) extractToken(ctx *request.Context, providers []string) (string, error) {
for _, providerName := range providers {
provider := s.tokenProviders[providerName]
token, err := provider.ExtractToken(ctx)
if err != nil {
return "", errors.WithMessagef(err, "extract token by '%s'", providerName)
}
if token != "" {
return token, nil
}
}
return "", nil
}
func (s UserAuthentication) authenticate(
ctx context.Context,
authModuleName string,
token string,
skipAppAuth bool,
) (*domain.AuthenticateUserResponse, error) {
authData, err := s.cache.Get(ctx, authModuleName, token)
switch {
case errors.Is(err, domain.ErrAuthenticationCacheMiss):
resp, err := s.repo.Authenticate(ctx, authModuleName, token)
if err != nil {
return nil, errors.WithMessage(err, "auth repo authenticate")
}
if !resp.Authenticated {
return s.convertAuthReponse(resp, skipAppAuth), nil
}
err = s.cache.Set(ctx, authModuleName, token, *resp.AuthData)
if err != nil {
return nil, errors.WithMessage(err, "auth cache set")
}
return s.convertAuthReponse(resp, skipAppAuth), nil
case err != nil:
return nil, errors.WithMessage(err, "auth cache get")
default:
return &domain.AuthenticateUserResponse{
Authenticated: true,
ErrorReason: "",
AuthData: s.convertAuthData(authData, skipAppAuth),
}, nil
}
}
func (s UserAuthentication) convertAuthReponse(resp *entity.UserAuthenticateResponse, skipAppAuth bool) *domain.AuthenticateUserResponse {
return &domain.AuthenticateUserResponse{
Authenticated: resp.Authenticated,
ErrorReason: resp.ErrorReason,
AuthData: s.convertAuthData(resp.AuthData, skipAppAuth),
}
}
func (UserAuthentication) convertAuthData(authData *entity.UserAuthData, skipAppAuth bool) *domain.UserAuthData {
if authData == nil {
return nil
}
return &domain.UserAuthData{
Identity: authData.Identity,
IdentityHeader: authData.IdentityHeader,
ExtraHeaders: authData.ExtraHeaders,
SkipAppAuth: skipAppAuth,
}
}
//nolint:ireturn
func tokenProviderFromConfig(cfg conf.TokenProvider) (TokenProvider, error) {
switch cfg.Type {
case conf.HeaderTokenProviderType:
if cfg.HeaderProvider == nil {
return nil, errors.Errorf("token method '%s' has empty header provider", cfg.Name)
}
return token_provider.NewHeaderProvider(*cfg.HeaderProvider), nil
case conf.CookieTokenProviderType:
if cfg.CookieProvider == nil {
return nil, errors.Errorf("token method '%s' has empty cookie provider", cfg.Name)
}
return token_provider.NewCookieProvider(*cfg.CookieProvider), nil
default:
return nil, errors.Errorf("unknown token provider with type '%s'", cfg.Type)
}
}