Skip to content

Commit

Permalink
NOISSUE - Update auth in journal service (#2527)
Browse files Browse the repository at this point in the history
Signed-off-by: Felix Gateru <[email protected]>
  • Loading branch information
felixgateru authored Nov 25, 2024
1 parent f42f45e commit b20b450
Show file tree
Hide file tree
Showing 22 changed files with 593 additions and 270 deletions.
72 changes: 65 additions & 7 deletions api/openapi/journal.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,56 @@ tags:
url: http://docs.mainflux.io/

paths:
/journal/{entity_type}/{id}:
/journal/user/{userID}:
get:
tags:
- journal-log
summary: List journal log
summary: List user journal log
description: |
Retrieves a list of journal. Due to performance concerns, data
is retrieved in subsets. The API must ensure that the entire
dataset is consumed either by making subsequent requests, or by
increasing the subset size of the initial request.
parameters:
- $ref: "#/components/parameters/user_id"
- $ref: "#/components/parameters/offset"
- $ref: "#/components/parameters/limit"
- $ref: "#/components/parameters/operation"
- $ref: "#/components/parameters/with_attributes"
- $ref: "#/components/parameters/with_metadata"
- $ref: "#/components/parameters/from"
- $ref: "#/components/parameters/to"
- $ref: "#/components/parameters/dir"
security:
- bearerAuth: []
responses:
"200":
$ref: "#/components/responses/JournalsPageRes"
"400":
description: Failed due to malformed query parameters.
"401":
description: Missing or invalid access token provided.
"403":
description: Failed to perform authorization over the entity.
"404":
description: A non-existent entity request.
"422":
description: Database can't process request.
"500":
$ref: "#/components/responses/ServiceError"

/{domainID}/journal/{entityType}/{id}:
get:
tags:
- journal-log
summary: List entity journal log
description: |
Retrieves a list of journal. Due to performance concerns, data
is retrieved in subsets. The API must ensure that the entire
dataset is consumed either by making subsequent requests, or by
increasing the subset size of the initial request.
parameters:
- $ref: "#/components/parameters/domain_id"
- $ref: "#/components/parameters/entity_type"
- $ref: "#/components/parameters/id"
- $ref: "#/components/parameters/offset"
Expand Down Expand Up @@ -146,23 +185,42 @@ components:
example: { "error": "malformed entity specification" }

parameters:
domain_id:
name: domainID
description: Unique identifier for a domain.
in: path
schema:
type: string
format: uuid
required: true
example: bb7edb32-2eac-4aad-aebe-ed96fe073879

entity_type:
name: entity_type
description: Type of entity, e.g. user, group, thing, etc.
name: entityType
description: Type of entity, e.g. user, group, thing, etc.entityType
in: path
schema:
type: string
enum:
- user
- group
- thing
- channel
required: true
example: user
example: group

user_id:
name: userID
description: Unique identifier for a user.
in: path
schema:
type: string
format: uuid
required: true
example: bb7edb32-2eac-4aad-aebe-ed96fe073879

id:
name: id
description: Unique identifier for an entity, e.g. user, group, domain, etc. Used together with entity_type.
description: Unique identifier for an entity, e.g. group, channel or thing. Used together with entity_type.
in: path
schema:
type: string
Expand Down
18 changes: 12 additions & 6 deletions cli/journal.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,30 @@ import (
)

var cmdJournal = cobra.Command{
Use: "get <entity_type> <entity_id> <user_auth_token>",
Use: "get <entity_type> <entity_id> <domain_id> <user_auth_token>",
Short: "Get journal",
Long: "Get journal\n" +
"Usage:\n" +
"\tmagistrala-cli journal get <entity_type> <entity_id> <user_auth_token> - lists journal logs\n" +
"\tmagistrala-cli journal get <entity_type> <entity_id> <user_auth_token> --offset <offset> --limit <limit> - lists journal logs with provided offset and limit\n",
"\tmagistrala-cli journal get user <user_id> <user_auth_token> - lists user journal logs\n" +
"\tmagistrala-cli journal get <entity_type> <entity_id> <domain_id> <user_auth_token> - lists entity journal logs\n" +
"\tmagistrala-cli journal get <entity_type> <entity_id> <domain_id> <user_auth_token> --offset <offset> --limit <limit> - lists user journal logs with provided offset and limit\n",
Run: func(cmd *cobra.Command, args []string) {
if len(args) != 3 {
if len(args) < 3 || len(args) > 4 {
logUsageCmd(*cmd, cmd.Use)
return
}

pageMetadata := mgxsdk.PageMetadata{
Offset: Offset,
Limit: Limit,
}

journal, err := sdk.Journal(args[0], args[1], pageMetadata, args[2])
entityType, entityID, token := args[0], args[1], args[2]
domainID := ""
if len(args) == 4 {
entityType, entityID, domainID, token = args[0], args[1], args[2], args[3]
}

journal, err := sdk.Journal(entityType, entityID, domainID, pageMetadata, token)
if err != nil {
logErrorCmd(*cmd, err)
return
Expand Down
31 changes: 26 additions & 5 deletions cli/journal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,9 @@ func TestGetJournalCmd(t *testing.T) {
rootCmd := setFlags(invCmd)

var page mgsdk.JournalsPage
entityType := "entity_type"
entityId := journal.ID
entityType := "group"
entityId := testsutil.GenerateUUID(t)
domainId := testsutil.GenerateUUID(t)

cases := []struct {
desc string
Expand All @@ -43,10 +44,26 @@ func TestGetJournalCmd(t *testing.T) {
errLogMessage string
}{
{
desc: "get journal with journal id",
desc: "get user journal",
args: []string{
"user",
entityId,
token,
},
logType: entityLog,
page: mgsdk.JournalsPage{
Total: 1,
Offset: 0,
Limit: 10,
Journals: []mgsdk.Journal{journal},
},
},
{
desc: "get group journal",
args: []string{
entityType,
entityId,
domainId,
token,
},
logType: entityLog,
Expand All @@ -63,6 +80,7 @@ func TestGetJournalCmd(t *testing.T) {
entityType,
entityId,
token,
domainId,
extraArg,
},
logType: usageLog,
Expand All @@ -72,6 +90,7 @@ func TestGetJournalCmd(t *testing.T) {
args: []string{
entityType,
entityId,
domainId,
invalidToken,
},
logType: errLog,
Expand All @@ -82,8 +101,10 @@ func TestGetJournalCmd(t *testing.T) {

for _, tc := range cases {
t.Run(tc.desc, func(t *testing.T) {
sdkCall := sdkMock.On("Journal", tc.args[0], tc.args[1], mock.Anything, tc.args[2]).Return(tc.page, tc.sdkErr)

sdkCall := sdkMock.On("Journal", tc.args[0], tc.args[1], "", mock.Anything, tc.args[2]).Return(tc.page, tc.sdkErr)
if tc.args[0] != "user" {
sdkCall = sdkMock.On("Journal", tc.args[0], tc.args[1], tc.args[2], mock.Anything, tc.args[3]).Return(tc.page, tc.sdkErr)
}
out := executeCommand(t, rootCmd, append([]string{getCmd}, tc.args...)...)

switch tc.logType {
Expand Down
10 changes: 5 additions & 5 deletions cmd/journal/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import (
"github.com/absmach/magistrala/journal/middleware"
journalpg "github.com/absmach/magistrala/journal/postgres"
mglog "github.com/absmach/magistrala/logger"
mgauthn "github.com/absmach/magistrala/pkg/authn"
authsvcAuthn "github.com/absmach/magistrala/pkg/authn/authsvc"
mgauthz "github.com/absmach/magistrala/pkg/authz"
authsvcAuthz "github.com/absmach/magistrala/pkg/authz/authsvc"
Expand Down Expand Up @@ -134,7 +133,7 @@ func main() {
}()
tracer := tp.Tracer(svcName)

svc := newService(db, dbConfig, authn, authz, logger, tracer)
svc := newService(db, dbConfig, authz, logger, tracer)

subscriber, err := store.NewSubscriber(ctx, cfg.ESURL, logger)
if err != nil {
Expand All @@ -158,7 +157,7 @@ func main() {
return
}

hs := http.NewServer(ctx, cancel, svcName, httpServerConfig, api.MakeHandler(svc, logger, svcName, cfg.InstanceID), logger)
hs := http.NewServer(ctx, cancel, svcName, httpServerConfig, api.MakeHandler(svc, authn, logger, svcName, cfg.InstanceID), logger)

if cfg.SendTelemetry {
chc := chclient.New(svcName, magistrala.Version, logger, cancel)
Expand All @@ -178,12 +177,13 @@ func main() {
}
}

func newService(db *sqlx.DB, dbConfig pgclient.Config, authn mgauthn.Authentication, authz mgauthz.Authorization, logger *slog.Logger, tracer trace.Tracer) journal.Service {
func newService(db *sqlx.DB, dbConfig pgclient.Config, authz mgauthz.Authorization, logger *slog.Logger, tracer trace.Tracer) journal.Service {
database := postgres.NewDatabase(db, dbConfig, tracer)
repo := journalpg.NewRepository(database)
idp := uuid.New()

svc := journal.NewService(authn, authz, idp, repo)
svc := journal.NewService(idp, repo)
svc = middleware.AuthorizationMiddleware(svc, authz)
svc = middleware.LoggingMiddleware(svc, logger)
counter, latency := prometheus.MakeMetrics("journal", "journal_writer")
svc = middleware.MetricsMiddleware(svc, counter, latency)
Expand Down
10 changes: 9 additions & 1 deletion journal/api/endpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,12 @@ package api
import (
"context"

"github.com/absmach/magistrala/internal/api"
"github.com/absmach/magistrala/journal"
"github.com/absmach/magistrala/pkg/apiutil"
"github.com/absmach/magistrala/pkg/authn"
"github.com/absmach/magistrala/pkg/errors"
svcerr "github.com/absmach/magistrala/pkg/errors/service"
"github.com/go-kit/kit/endpoint"
)

Expand All @@ -19,7 +22,12 @@ func retrieveJournalsEndpoint(svc journal.Service) endpoint.Endpoint {
return nil, errors.Wrap(apiutil.ErrValidation, err)
}

page, err := svc.RetrieveAll(ctx, req.token, req.page)
session, ok := ctx.Value(api.SessionKey).(authn.Session)
if !ok {
return nil, svcerr.ErrAuthorization
}

page, err := svc.RetrieveAll(ctx, session, req.page)
if err != nil {
return nil, err
}
Expand Down
Loading

0 comments on commit b20b450

Please sign in to comment.