Files
magistrala/pkg/authn/authsvc/authn.go
T
Steve Munene ac8dadefc6
Continuous Delivery / lint-and-build (push) Has been cancelled
Continuous Delivery / Build and Push Docker Images (push) Has been cancelled
Deploy GitHub Pages / swagger-ui (push) Has been cancelled
CI Pipeline / Lint Proto (push) Has been cancelled
CI Pipeline / lint-and-build (push) Has been cancelled
CI Pipeline / Detect Changes (push) Has been cancelled
CI Pipeline / Test ${{ matrix.module }} (push) Has been cancelled
CI Pipeline / Upload Coverage (push) Has been cancelled
Property Based Tests / api-test (push) Has been cancelled
NOISSUE - Fix refreshKey method (#3472)
Signed-off-by: nyagamunene <stevenyaga2014@gmail.com>
2026-04-15 13:30:00 +02:00

53 lines
1.8 KiB
Go

// Copyright (c) Abstract Machines
// SPDX-License-Identifier: Apache-2.0
package authsvc
import (
"context"
grpcAuthV1 "github.com/absmach/magistrala/api/grpc/auth/v1"
mgauth "github.com/absmach/magistrala/auth"
"github.com/absmach/magistrala/auth/api/grpc/auth"
"github.com/absmach/magistrala/pkg/authn"
"github.com/absmach/magistrala/pkg/errors"
"github.com/absmach/magistrala/pkg/grpcclient"
grpchealth "google.golang.org/grpc/health/grpc_health_v1"
)
type authentication struct {
authSvcClient grpcAuthV1.AuthServiceClient
}
var _ authn.Authentication = (*authentication)(nil)
func NewAuthentication(ctx context.Context, cfg grpcclient.Config) (authn.Authentication, grpcclient.Handler, error) {
client, err := grpcclient.NewHandler(cfg)
if err != nil {
return nil, nil, err
}
health := grpchealth.NewHealthClient(client.Connection())
resp, err := health.Check(ctx, &grpchealth.HealthCheckRequest{
Service: "auth",
})
if err != nil || resp.GetStatus() != grpchealth.HealthCheckResponse_SERVING {
return nil, nil, grpcclient.ErrSvcNotServing
}
authSvcClient := auth.NewAuthClient(client.Connection(), cfg.Timeout)
return authentication{authSvcClient}, client, nil
}
func (a authentication) Authenticate(ctx context.Context, token string) (authn.Session, error) {
res, err := a.authSvcClient.Authenticate(ctx, &grpcAuthV1.AuthNReq{Token: token})
if err != nil {
return authn.Session{}, errors.Wrap(errors.ErrAuthentication, err)
}
if res.GetTokenType() == uint32(mgauth.PersonalAccessToken) {
return authn.Session{Type: authn.PersonalAccessToken, PatID: res.GetId(), UserID: res.GetUserId(), Role: authn.Role(res.GetUserRole())}, nil
}
return authn.Session{Type: authn.AccessToken, UserID: res.GetUserId(), Role: authn.Role(res.GetUserRole()), Verified: res.GetVerified()}, nil
}