mirror of
https://github.com/opencloud-eu/opencloud.git
synced 2026-04-16 13:27:37 -04:00
@@ -68,6 +68,7 @@ config = {
|
||||
"services/groups",
|
||||
"services/idm",
|
||||
"services/idp",
|
||||
"services/invitations",
|
||||
"services/nats",
|
||||
"services/notifications",
|
||||
"services/ocdav",
|
||||
|
||||
1
Makefile
1
Makefile
@@ -32,6 +32,7 @@ OCIS_MODULES = \
|
||||
services/groups \
|
||||
services/idm \
|
||||
services/idp \
|
||||
services/invitations \
|
||||
services/nats \
|
||||
services/notifications \
|
||||
services/ocdav \
|
||||
|
||||
16
docs/services/invitations/_index.md
Normal file
16
docs/services/invitations/_index.md
Normal file
@@ -0,0 +1,16 @@
|
||||
---
|
||||
title: IDP
|
||||
weight: 20
|
||||
geekdocRepo: https://github.com/owncloud/ocis
|
||||
geekdocEditPath: edit/master/docs/services/invitations
|
||||
geekdocFilePath: _index.md
|
||||
geekdocCollapseSection: true
|
||||
---
|
||||
|
||||
## Abstract
|
||||
|
||||
This service provides an invitations service to invite guests into the organization.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
{{< toc-tree >}}
|
||||
15
docs/services/invitations/configuration.md
Normal file
15
docs/services/invitations/configuration.md
Normal file
@@ -0,0 +1,15 @@
|
||||
---
|
||||
title: Service Configuration
|
||||
date: 2023-03-02T15:27:00+01:00
|
||||
weight: 20
|
||||
geekdocRepo: https://github.com/owncloud/ocis
|
||||
geekdocEditPath: edit/master/docs/services/invitations
|
||||
geekdocFilePath: configuration.md
|
||||
geekdocCollapseSection: true
|
||||
---
|
||||
|
||||
## Example YAML Config
|
||||
|
||||
{{< include file="services/_includes/invitations-config-example.yaml" language="yaml" >}}
|
||||
|
||||
{{< include file="services/_includes/invitations_configvars.md" >}}
|
||||
6
go.mod
6
go.mod
@@ -7,6 +7,7 @@ require (
|
||||
github.com/KimMachineGun/automemlimit v0.2.4
|
||||
github.com/Masterminds/semver v1.5.0
|
||||
github.com/MicahParks/keyfunc v1.5.1
|
||||
github.com/Nerzal/gocloak/v13 v13.1.0
|
||||
github.com/armon/go-radix v1.0.0
|
||||
github.com/bbalet/stopwords v1.0.0
|
||||
github.com/blevesearch/bleve/v2 v2.3.6
|
||||
@@ -113,6 +114,7 @@ require (
|
||||
github.com/Masterminds/sprig v2.22.0+incompatible // indirect
|
||||
github.com/Microsoft/go-winio v0.6.0 // indirect
|
||||
github.com/OneOfOne/xxhash v1.2.8 // indirect
|
||||
github.com/Nerzal/gocloak/v13 v13.1.0 // indirect
|
||||
github.com/ProtonMail/go-crypto v0.0.0-20220930113650-c6815a8c17ad // indirect
|
||||
github.com/RoaringBitmap/roaring v0.9.4 // indirect
|
||||
github.com/acomagu/bufpipe v1.0.3 // indirect
|
||||
@@ -185,6 +187,8 @@ require (
|
||||
github.com/go-logfmt/logfmt v0.5.1 // indirect
|
||||
github.com/go-logr/logr v1.2.3 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/go-redis/redis/v8 v8.11.5 // indirect
|
||||
github.com/go-resty/resty/v2 v2.7.0 // indirect
|
||||
github.com/go-sql-driver/mysql v1.6.0 // indirect
|
||||
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0 // indirect
|
||||
github.com/gobwas/glob v0.2.3 // indirect
|
||||
@@ -260,6 +264,7 @@ require (
|
||||
github.com/nats-io/nuid v1.0.1 // indirect
|
||||
github.com/nxadm/tail v1.4.8 // indirect
|
||||
github.com/opencontainers/runtime-spec v1.0.2 // indirect
|
||||
github.com/opentracing/opentracing-go v1.2.0 // indirect
|
||||
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c // indirect
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
@@ -276,6 +281,7 @@ require (
|
||||
github.com/russellhaering/goxmldsig v1.2.0 // indirect
|
||||
github.com/russross/blackfriday/v2 v2.1.0 // indirect
|
||||
github.com/sciencemesh/meshdirectory-web v1.0.4 // indirect
|
||||
github.com/segmentio/ksuid v1.0.4 // indirect
|
||||
github.com/sergi/go-diff v1.2.0 // indirect
|
||||
github.com/sethvargo/go-password v0.2.0 // indirect
|
||||
github.com/shurcooL/httpfs v0.0.0-20190707220628-8d4bc4ba7749 // indirect
|
||||
|
||||
8
go.sum
8
go.sum
@@ -435,6 +435,8 @@ github.com/Microsoft/go-winio v0.4.16/go.mod h1:XB6nPKklQyQ7GC9LdcBEcBl8PF76WugX
|
||||
github.com/Microsoft/go-winio v0.5.2/go.mod h1:WpS1mjBmmwHBEWmogvA2mj8546UReBk4v8QkMxJ6pZY=
|
||||
github.com/Microsoft/go-winio v0.6.0 h1:slsWYD/zyx7lCXoZVlvQrj0hPTM1HI4+v1sIda2yDvg=
|
||||
github.com/Microsoft/go-winio v0.6.0/go.mod h1:cTAf44im0RAYeL23bpB+fzCyDH2MJiz2BO69KH/soAE=
|
||||
github.com/Nerzal/gocloak/v13 v13.1.0 h1:ret4pZTIsSQGZHURDMJ4jXnUmHyEoRykBqDTsAKoj8c=
|
||||
github.com/Nerzal/gocloak/v13 v13.1.0/go.mod h1:rRBtEdh5N0+JlZZEsrfZcB2sRMZWbgSxI2EIv9jpJp4=
|
||||
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
|
||||
github.com/OneOfOne/xxhash v1.2.8 h1:31czK/TI9sNkxIKfaUfGlU47BAxQ0ztGgd9vPyqimf8=
|
||||
github.com/OneOfOne/xxhash v1.2.8/go.mod h1:eZbhyaAYD41SGSSsnmcpxVoRiQ/MPUTjUdIIOT9Um7Q=
|
||||
@@ -827,6 +829,8 @@ github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn
|
||||
github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI=
|
||||
github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo=
|
||||
github.com/go-resty/resty/v2 v2.1.1-0.20191201195748-d7b97669fe48/go.mod h1:dZGr0i9PLlaaTD4H/hoZIDjQ+r6xq8mgbRzHZf7f2J8=
|
||||
github.com/go-resty/resty/v2 v2.7.0 h1:me+K9p3uhSmXtrBZ4k9jcEAfJmuC8IivWHwaLZwPrFY=
|
||||
github.com/go-resty/resty/v2 v2.7.0/go.mod h1:9PWDzw47qPphMRFfhsyk0NnSgvluHcljSMVIq3w7q0I=
|
||||
github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE=
|
||||
github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
|
||||
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
|
||||
@@ -1366,6 +1370,7 @@ github.com/open-policy-agent/opa v0.50.0/go.mod h1:9jKfDk0L5b9rnhH4M0nq10cGHbYOx
|
||||
github.com/opencontainers/runtime-spec v1.0.2 h1:UfAcuLBJB9Coz72x1hgl8O5RVzTdNiaglX6v2DM6FI0=
|
||||
github.com/opencontainers/runtime-spec v1.0.2/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0=
|
||||
github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=
|
||||
github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs=
|
||||
github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc=
|
||||
github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw=
|
||||
github.com/oracle/oci-go-sdk v24.3.0+incompatible/go.mod h1:VQb79nF8Z2cwLkLS35ukwStZIg5F66tcBccjip/j888=
|
||||
@@ -1493,6 +1498,8 @@ github.com/sciencemesh/meshdirectory-web v1.0.4 h1:1YSctF6PAXhoHUYCaeRTj7rHaF7b3
|
||||
github.com/sciencemesh/meshdirectory-web v1.0.4/go.mod h1:fJSThTS3xf+sTdL0iXQoaQJssLI7tn7DetHMHUl4SRk=
|
||||
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529 h1:nn5Wsu0esKSJiIVhscUtVbo7ada43DJhG55ua/hjS5I=
|
||||
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
|
||||
github.com/segmentio/ksuid v1.0.4 h1:sBo2BdShXjmcugAMwjugoGUdUV0pcxY5mW4xKRn3v4c=
|
||||
github.com/segmentio/ksuid v1.0.4/go.mod h1:/XUiZBD3kVx5SmUOl55voK5yeAbBNNIed+2O73XgrPE=
|
||||
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
|
||||
github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=
|
||||
github.com/sergi/go-diff v1.2.0 h1:XU+rvMAioB0UC3q1MFrIQy4Vo5/4VsRDQQXHsEya6xQ=
|
||||
@@ -1816,6 +1823,7 @@ golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qx
|
||||
golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.0.0-20210726213435-c6fcb2dbf985/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.0.0-20211029224645-99673261e6eb/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.0.0-20211216030914-fe4d6282115f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
groups "github.com/owncloud/ocis/v2/services/groups/pkg/config"
|
||||
idm "github.com/owncloud/ocis/v2/services/idm/pkg/config"
|
||||
idp "github.com/owncloud/ocis/v2/services/idp/pkg/config"
|
||||
invitations "github.com/owncloud/ocis/v2/services/invitations/pkg/config"
|
||||
nats "github.com/owncloud/ocis/v2/services/nats/pkg/config"
|
||||
notifications "github.com/owncloud/ocis/v2/services/notifications/pkg/config"
|
||||
ocdav "github.com/owncloud/ocis/v2/services/ocdav/pkg/config"
|
||||
@@ -87,6 +88,7 @@ type Config struct {
|
||||
Groups *groups.Config `yaml:"groups"`
|
||||
IDM *idm.Config `yaml:"idm"`
|
||||
IDP *idp.Config `yaml:"idp"`
|
||||
Invitations *invitations.Config `yaml:"invitations"`
|
||||
Nats *nats.Config `yaml:"nats"`
|
||||
Notifications *notifications.Config `yaml:"notifications"`
|
||||
OCDav *ocdav.Config `yaml:"ocdav"`
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
groups "github.com/owncloud/ocis/v2/services/groups/pkg/config/defaults"
|
||||
idm "github.com/owncloud/ocis/v2/services/idm/pkg/config/defaults"
|
||||
idp "github.com/owncloud/ocis/v2/services/idp/pkg/config/defaults"
|
||||
invitations "github.com/owncloud/ocis/v2/services/invitations/pkg/config/defaults"
|
||||
nats "github.com/owncloud/ocis/v2/services/nats/pkg/config/defaults"
|
||||
notifications "github.com/owncloud/ocis/v2/services/notifications/pkg/config/defaults"
|
||||
ocdav "github.com/owncloud/ocis/v2/services/ocdav/pkg/config/defaults"
|
||||
@@ -60,6 +61,7 @@ func DefaultConfig() *Config {
|
||||
Groups: groups.DefaultConfig(),
|
||||
IDM: idm.DefaultConfig(),
|
||||
IDP: idp.DefaultConfig(),
|
||||
Invitations: invitations.DefaultConfig(),
|
||||
Nats: nats.DefaultConfig(),
|
||||
Notifications: notifications.DefaultConfig(),
|
||||
OCDav: ocdav.DefaultConfig(),
|
||||
|
||||
30
ocis/pkg/command/invitations.go
Normal file
30
ocis/pkg/command/invitations.go
Normal file
@@ -0,0 +1,30 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/config"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/config/configlog"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/config/parser"
|
||||
"github.com/owncloud/ocis/v2/ocis/pkg/command/helper"
|
||||
"github.com/owncloud/ocis/v2/ocis/pkg/register"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/command"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
// InvitationsCommand is the entrypoint for the invitations command.
|
||||
func InvitationsCommand(cfg *config.Config) *cli.Command {
|
||||
return &cli.Command{
|
||||
Name: cfg.Invitations.Service.Name,
|
||||
Usage: helper.SubcommandDescription(cfg.Invitations.Service.Name),
|
||||
Category: "services",
|
||||
Before: func(c *cli.Context) error {
|
||||
configlog.Error(parser.ParseConfig(cfg, true))
|
||||
cfg.Invitations.Commons = cfg.Commons
|
||||
return nil
|
||||
},
|
||||
Subcommands: command.GetCommands(cfg.Invitations),
|
||||
}
|
||||
}
|
||||
|
||||
func init() {
|
||||
register.AddCommand(InvitationsCommand)
|
||||
}
|
||||
@@ -29,6 +29,7 @@ import (
|
||||
groups "github.com/owncloud/ocis/v2/services/groups/pkg/command"
|
||||
idm "github.com/owncloud/ocis/v2/services/idm/pkg/command"
|
||||
idp "github.com/owncloud/ocis/v2/services/idp/pkg/command"
|
||||
invitations "github.com/owncloud/ocis/v2/services/invitations/pkg/command"
|
||||
nats "github.com/owncloud/ocis/v2/services/nats/pkg/command"
|
||||
notifications "github.com/owncloud/ocis/v2/services/notifications/pkg/command"
|
||||
ocdav "github.com/owncloud/ocis/v2/services/ocdav/pkg/command"
|
||||
@@ -108,6 +109,7 @@ func NewService(options ...Option) (*Service, error) {
|
||||
s.ServicesRegistry[opts.Config.StorageSystem.Service.Name] = storageSystem.NewSutureService
|
||||
s.ServicesRegistry[opts.Config.Graph.Service.Name] = graph.NewSutureService
|
||||
s.ServicesRegistry[opts.Config.IDM.Service.Name] = idm.NewSutureService
|
||||
s.ServicesRegistry[opts.Config.Invitations.Service.Name] = invitations.NewSutureService
|
||||
s.ServicesRegistry[opts.Config.OCS.Service.Name] = ocs.NewSutureService
|
||||
s.ServicesRegistry[opts.Config.Store.Service.Name] = store.NewSutureService
|
||||
s.ServicesRegistry[opts.Config.Thumbnails.Service.Name] = thumbnails.NewSutureService
|
||||
|
||||
39
services/invitations/Makefile
Normal file
39
services/invitations/Makefile
Normal file
@@ -0,0 +1,39 @@
|
||||
SHELL := bash
|
||||
NAME := invitations
|
||||
|
||||
include ../../.make/recursion.mk
|
||||
|
||||
############ tooling ############
|
||||
ifneq (, $(shell command -v go 2> /dev/null)) # suppress `command not found warnings` for non go targets in CI
|
||||
include ../../.bingo/Variables.mk
|
||||
endif
|
||||
|
||||
############ go tooling ############
|
||||
include ../../.make/go.mk
|
||||
|
||||
############ release ############
|
||||
include ../../.make/release.mk
|
||||
|
||||
############ docs generate ############
|
||||
include ../../.make/docs.mk
|
||||
|
||||
.PHONY: docs-generate
|
||||
docs-generate: config-docs-generate
|
||||
|
||||
############ generate ############
|
||||
include ../../.make/generate.mk
|
||||
|
||||
.PHONY: ci-go-generate
|
||||
ci-go-generate: $(MOCKERY) # CI runs ci-node-generate automatically before this target
|
||||
$(MOCKERY) --dir pkg/backends/keycloak --output pkg/mocks --case underscore --name GoCloak
|
||||
|
||||
|
||||
.PHONY: ci-node-generate
|
||||
ci-node-generate:
|
||||
|
||||
############ licenses ############
|
||||
.PHONY: ci-node-check-licenses
|
||||
ci-node-check-licenses:
|
||||
|
||||
.PHONY: ci-node-save-licenses
|
||||
ci-node-save-licenses:
|
||||
15
services/invitations/README.md
Normal file
15
services/invitations/README.md
Normal file
@@ -0,0 +1,15 @@
|
||||
# Invitations Service
|
||||
|
||||
The invitations service provides an [Invitation Manager](https://learn.microsoft.com/en-us/graph/api/invitation-post?view=graph-rest-1.0&tabs=http) that can be used to invite external users aka Guests to an organization.
|
||||
|
||||
Users invited via this Invitation Manager (libre graph API) will have `userType="Guest"`, whereas users belonging to the organization have `userType="Member"`.
|
||||
|
||||
The corresponding CS3 API [user types](https://cs3org.github.io/cs3apis/#cs3.identity.user.v1beta1.UserType) used to reperesent this are: `USER_TYPE_GUEST` and `USER_TYPE_PRIMARY`.
|
||||
|
||||
## Provisioning backends
|
||||
|
||||
When oCIS is used for user management the users are created using the `/graph/v1.0/users` endpoint. For larger deployments the keycloak admin API can be used to provision users. We might even make the endpoint, credentials and body configurable using templates.
|
||||
|
||||
## Bridging provisioning delay
|
||||
|
||||
When a guest account has to be provisioned in an external user management there might be a delay between creating the user and it being available in the local ocis system. In the first iteration the invitations service will only keep track of invites in memory. This list could be persisted in future iterations.
|
||||
14
services/invitations/cmd/invitations/main.go
Normal file
14
services/invitations/cmd/invitations/main.go
Normal file
@@ -0,0 +1,14 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/command"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/config/defaults"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := command.Execute(defaults.DefaultConfig()); err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
140
services/invitations/pkg/backends/keycloak/backend.go
Normal file
140
services/invitations/pkg/backends/keycloak/backend.go
Normal file
@@ -0,0 +1,140 @@
|
||||
// Package keycloak offers an invitation backend for the invitation service.
|
||||
package keycloak
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
|
||||
"github.com/Nerzal/gocloak/v13"
|
||||
"github.com/google/uuid"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/invitations"
|
||||
)
|
||||
|
||||
const (
|
||||
idAttr = "OWNCLOUD_ID"
|
||||
userTypeAttr = "OWNCLOUD_USER_TYPE"
|
||||
userTypeVal = "Guest"
|
||||
)
|
||||
|
||||
var userRequiredActions = []string{"UPDATE_PASSWORD", "VERIFY_EMAIL"}
|
||||
|
||||
// Backend represents the keycloak backend.
|
||||
type Backend struct {
|
||||
logger log.Logger
|
||||
client GoCloak
|
||||
clientID string
|
||||
clientSecret string
|
||||
clientRealm string
|
||||
userRealm string
|
||||
}
|
||||
|
||||
// New instantiates a new keycloak.Backend with a default gocloak client.
|
||||
func New(
|
||||
logger log.Logger,
|
||||
baseURL, clientID, clientSecret, clientRealm, userRealm string,
|
||||
insecureSkipVerify bool,
|
||||
) *Backend {
|
||||
client := gocloak.NewClient(baseURL)
|
||||
restyClient := client.RestyClient()
|
||||
restyClient.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: insecureSkipVerify}) //nolint:gosec
|
||||
return NewWithClient(logger, client, clientID, clientSecret, clientRealm, userRealm)
|
||||
}
|
||||
|
||||
// NewWithClient creates a new backend with the supplied GoCloak client.
|
||||
func NewWithClient(
|
||||
logger log.Logger,
|
||||
client GoCloak,
|
||||
clientID, clientSecret, clientRealm, userRealm string,
|
||||
) *Backend {
|
||||
return &Backend{
|
||||
logger: log.Logger{
|
||||
Logger: logger.With().
|
||||
Str("invitationBackend", "keycloak").
|
||||
Str("clientID", clientID).
|
||||
Str("clientRealm", clientRealm).
|
||||
Str("userRealm", userRealm).
|
||||
Logger(),
|
||||
},
|
||||
client: client,
|
||||
clientID: clientID,
|
||||
clientSecret: clientSecret,
|
||||
clientRealm: clientRealm,
|
||||
userRealm: userRealm,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateUser creates a user in the keycloak backend.
|
||||
func (b Backend) CreateUser(ctx context.Context, invitation *invitations.Invitation) (string, error) {
|
||||
token, err := b.getToken(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
u := uuid.New()
|
||||
|
||||
b.logger.Info().
|
||||
Str(idAttr, u.String()).
|
||||
Str("email", invitation.InvitedUserEmailAddress).
|
||||
Msg("Creating new user")
|
||||
user := gocloak.User{
|
||||
Email: &invitation.InvitedUserEmailAddress,
|
||||
Enabled: gocloak.BoolP(true),
|
||||
Username: &invitation.InvitedUserEmailAddress,
|
||||
Attributes: &map[string][]string{
|
||||
idAttr: {u.String()},
|
||||
userTypeAttr: {userTypeVal},
|
||||
},
|
||||
RequiredActions: &userRequiredActions,
|
||||
}
|
||||
|
||||
id, err := b.client.CreateUser(ctx, token.AccessToken, b.userRealm, user)
|
||||
if err != nil {
|
||||
b.logger.Error().
|
||||
Str(idAttr, u.String()).
|
||||
Str("email", invitation.InvitedUserEmailAddress).
|
||||
Err(err).
|
||||
Msg("Failed to create user")
|
||||
return "", err
|
||||
}
|
||||
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// CanSendMail returns true because keycloak does allow to send mail.
|
||||
func (b Backend) CanSendMail() bool { return true }
|
||||
|
||||
// SendMail sends a mail to the user with details on how to reedeem the invitation.
|
||||
func (b Backend) SendMail(ctx context.Context, id string) error {
|
||||
token, err := b.getToken(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
params := gocloak.ExecuteActionsEmail{
|
||||
UserID: &id,
|
||||
Actions: &userRequiredActions,
|
||||
}
|
||||
return b.client.ExecuteActionsEmail(ctx, token.AccessToken, b.userRealm, params)
|
||||
}
|
||||
|
||||
func (b Backend) getToken(ctx context.Context) (*gocloak.JWT, error) {
|
||||
b.logger.Debug().Msg("Logging into keycloak")
|
||||
token, err := b.client.LoginClient(ctx, b.clientID, b.clientSecret, b.clientRealm)
|
||||
if err != nil {
|
||||
b.logger.Error().Err(err).Msg("failed to get token")
|
||||
return nil, fmt.Errorf("failed to get token: %w", err)
|
||||
}
|
||||
|
||||
rRes, err := b.client.RetrospectToken(ctx, token.AccessToken, b.clientID, b.clientSecret, b.clientRealm)
|
||||
if err != nil {
|
||||
b.logger.Error().Err(err).Msg("failed to introspect token")
|
||||
return nil, fmt.Errorf("failed to retrospect token: %w", err)
|
||||
}
|
||||
|
||||
if !*rRes.Active {
|
||||
b.logger.Error().Msg("token not active")
|
||||
return nil, fmt.Errorf("token is not active")
|
||||
}
|
||||
|
||||
return token, nil
|
||||
}
|
||||
202
services/invitations/pkg/backends/keycloak/backend_test.go
Normal file
202
services/invitations/pkg/backends/keycloak/backend_test.go
Normal file
@@ -0,0 +1,202 @@
|
||||
// Package keycloak offers an invitation backend for the invitation service.
|
||||
// TODO: Maybe move this outside of the invitation service and make it more generic?
|
||||
|
||||
package keycloak_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/Nerzal/gocloak/v13"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/backends/keycloak"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/invitations"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/mocks"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/test-go/testify/mock"
|
||||
)
|
||||
|
||||
const (
|
||||
clientID = "test-id"
|
||||
clientSecret = "test-secret"
|
||||
clientRealm = "client-realm"
|
||||
userRealm = "user-realm"
|
||||
jwtToken = "test-token"
|
||||
)
|
||||
|
||||
func TestBackend_CreateUser(t *testing.T) {
|
||||
type args struct {
|
||||
invitation *invitations.Invitation
|
||||
}
|
||||
type mockInputs struct {
|
||||
funcName string
|
||||
args []interface{}
|
||||
returns []interface{}
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want string
|
||||
keycloakMocks []mockInputs
|
||||
assertion assert.ErrorAssertionFunc
|
||||
}{
|
||||
{
|
||||
name: "Test without diplay name",
|
||||
args: args{
|
||||
invitation: &invitations.Invitation{
|
||||
InvitedUserEmailAddress: "test@example.org",
|
||||
},
|
||||
},
|
||||
want: "test-id",
|
||||
keycloakMocks: []mockInputs{
|
||||
{
|
||||
funcName: "LoginClient",
|
||||
args: []interface{}{
|
||||
mock.Anything,
|
||||
clientID,
|
||||
clientSecret,
|
||||
clientRealm,
|
||||
},
|
||||
returns: []interface{}{
|
||||
&gocloak.JWT{
|
||||
AccessToken: jwtToken,
|
||||
},
|
||||
nil,
|
||||
},
|
||||
},
|
||||
{
|
||||
funcName: "RetrospectToken",
|
||||
args: []interface{}{
|
||||
mock.Anything,
|
||||
jwtToken,
|
||||
clientID,
|
||||
clientSecret,
|
||||
clientRealm,
|
||||
},
|
||||
returns: []interface{}{
|
||||
&gocloak.IntroSpectTokenResult{
|
||||
Active: gocloak.BoolP(true),
|
||||
},
|
||||
nil,
|
||||
},
|
||||
},
|
||||
{
|
||||
funcName: "CreateUser",
|
||||
args: []interface{}{
|
||||
mock.Anything,
|
||||
jwtToken,
|
||||
userRealm,
|
||||
mock.Anything, // can't match on the user because it generates a UUID internally.
|
||||
// might be worth refactoring the UUID generation to outside of the func
|
||||
},
|
||||
returns: []interface{}{
|
||||
"test-id",
|
||||
nil,
|
||||
},
|
||||
},
|
||||
},
|
||||
assertion: func(t assert.TestingT, err error, args ...interface{}) bool {
|
||||
return assert.Nil(t, err, args...)
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
c := &mocks.GoCloak{}
|
||||
for _, m := range tt.keycloakMocks {
|
||||
c.On(m.funcName, m.args...).Return(m.returns...)
|
||||
}
|
||||
b := keycloak.NewWithClient(log.NopLogger(), c, clientID, clientSecret, clientRealm, userRealm)
|
||||
got, err := b.CreateUser(ctx, tt.args.invitation)
|
||||
tt.assertion(t, err)
|
||||
assert.Equal(t, tt.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBackend_SendMail(t *testing.T) {
|
||||
type args struct {
|
||||
id string
|
||||
}
|
||||
type mockInputs struct {
|
||||
funcName string
|
||||
args []interface{}
|
||||
returns []interface{}
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
keycloakMocks []mockInputs
|
||||
assertion assert.ErrorAssertionFunc
|
||||
}{
|
||||
{
|
||||
name: "Mail successfully sent",
|
||||
args: args{
|
||||
id: "test-id",
|
||||
},
|
||||
keycloakMocks: []mockInputs{
|
||||
{
|
||||
funcName: "LoginClient",
|
||||
args: []interface{}{
|
||||
mock.Anything,
|
||||
clientID,
|
||||
clientSecret,
|
||||
clientRealm,
|
||||
},
|
||||
returns: []interface{}{
|
||||
&gocloak.JWT{
|
||||
AccessToken: jwtToken,
|
||||
},
|
||||
nil,
|
||||
},
|
||||
},
|
||||
{
|
||||
funcName: "RetrospectToken",
|
||||
args: []interface{}{
|
||||
mock.Anything,
|
||||
jwtToken,
|
||||
clientID,
|
||||
clientSecret,
|
||||
clientRealm,
|
||||
},
|
||||
returns: []interface{}{
|
||||
&gocloak.IntroSpectTokenResult{
|
||||
Active: gocloak.BoolP(true),
|
||||
},
|
||||
nil,
|
||||
},
|
||||
},
|
||||
{
|
||||
funcName: "ExecuteActionsEmail",
|
||||
args: []interface{}{
|
||||
mock.Anything,
|
||||
jwtToken,
|
||||
userRealm,
|
||||
gocloak.ExecuteActionsEmail{
|
||||
UserID: gocloak.StringP("test-id"),
|
||||
Actions: &[]string{"UPDATE_PASSWORD", "VERIFY_EMAIL"},
|
||||
},
|
||||
},
|
||||
returns: []interface{}{
|
||||
nil,
|
||||
},
|
||||
},
|
||||
},
|
||||
assertion: func(t assert.TestingT, err error, args ...interface{}) bool {
|
||||
return assert.Nil(t, err, args...)
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
c := &mocks.GoCloak{}
|
||||
for _, m := range tt.keycloakMocks {
|
||||
c.On(m.funcName, m.args...).Return(m.returns...)
|
||||
}
|
||||
b := keycloak.NewWithClient(log.NopLogger(), c, clientID, clientSecret, clientRealm, userRealm)
|
||||
tt.assertion(t, b.SendMail(ctx, tt.args.id))
|
||||
})
|
||||
}
|
||||
}
|
||||
17
services/invitations/pkg/backends/keycloak/gocloak.go
Normal file
17
services/invitations/pkg/backends/keycloak/gocloak.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package keycloak
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Nerzal/gocloak/v13"
|
||||
)
|
||||
|
||||
// GoCloak represents the parts of gocloak.GoCloak that we use, mainly here for mockery.
|
||||
//
|
||||
//go:generate mockery --name=GoCloak
|
||||
type GoCloak interface {
|
||||
CreateUser(ctx context.Context, token, realm string, user gocloak.User) (string, error)
|
||||
ExecuteActionsEmail(ctx context.Context, token, realm string, params gocloak.ExecuteActionsEmail) error
|
||||
LoginClient(ctx context.Context, clientID, clientSecret, realm string) (*gocloak.JWT, error)
|
||||
RetrospectToken(ctx context.Context, accessToken, clientID, clientSecret, realm string) (*gocloak.IntroSpectTokenResult, error)
|
||||
}
|
||||
54
services/invitations/pkg/command/health.go
Normal file
54
services/invitations/pkg/command/health.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/config/configlog"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/config"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/config/parser"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/logging"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
// Health is the entrypoint for the health command.
|
||||
func Health(cfg *config.Config) *cli.Command {
|
||||
return &cli.Command{
|
||||
Name: "health",
|
||||
Usage: "check health status",
|
||||
Category: "info",
|
||||
Before: func(c *cli.Context) error {
|
||||
return configlog.ReturnError(parser.ParseConfig(cfg))
|
||||
},
|
||||
Action: func(c *cli.Context) error {
|
||||
logger := logging.Configure(cfg.Service.Name, cfg.Log)
|
||||
|
||||
resp, err := http.Get(
|
||||
fmt.Sprintf(
|
||||
"http://%s/healthz",
|
||||
cfg.Debug.Addr,
|
||||
),
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
logger.Fatal().
|
||||
Err(err).
|
||||
Msg("Failed to request health check")
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
logger.Fatal().
|
||||
Int("code", resp.StatusCode).
|
||||
Msg("Health seems to be in bad state")
|
||||
}
|
||||
|
||||
logger.Debug().
|
||||
Int("code", resp.StatusCode).
|
||||
Msg("Health got a good state")
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
59
services/invitations/pkg/command/root.go
Normal file
59
services/invitations/pkg/command/root.go
Normal file
@@ -0,0 +1,59 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/clihelper"
|
||||
ociscfg "github.com/owncloud/ocis/v2/ocis-pkg/config"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/config"
|
||||
"github.com/thejerf/suture/v4"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
// GetCommands provides all commands for this service
|
||||
func GetCommands(cfg *config.Config) cli.Commands {
|
||||
return []*cli.Command{
|
||||
// start this service
|
||||
Server(cfg),
|
||||
|
||||
// interaction with this service
|
||||
|
||||
// infos about this service
|
||||
Health(cfg),
|
||||
Version(cfg),
|
||||
}
|
||||
}
|
||||
|
||||
// Execute is the entry point for the ocis invitations command.
|
||||
func Execute(cfg *config.Config) error {
|
||||
app := clihelper.DefaultApp(&cli.App{
|
||||
Name: "invitations",
|
||||
Usage: "Serve invitations API for oCIS",
|
||||
Commands: GetCommands(cfg),
|
||||
})
|
||||
|
||||
return app.Run(os.Args)
|
||||
}
|
||||
|
||||
// SutureService allows for the webdav command to be embedded and supervised by a suture supervisor tree.
|
||||
type SutureService struct {
|
||||
cfg *config.Config
|
||||
}
|
||||
|
||||
// NewSutureService creates a new webdav.SutureService
|
||||
func NewSutureService(cfg *ociscfg.Config) suture.Service {
|
||||
cfg.Invitations.Commons = cfg.Commons
|
||||
return SutureService{
|
||||
cfg: cfg.Invitations,
|
||||
}
|
||||
}
|
||||
|
||||
func (s SutureService) Serve(ctx context.Context) error {
|
||||
s.cfg.Context = ctx
|
||||
if err := Execute(s.cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
117
services/invitations/pkg/command/server.go
Normal file
117
services/invitations/pkg/command/server.go
Normal file
@@ -0,0 +1,117 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/oklog/run"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/config/configlog"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/version"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/config"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/config/parser"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/logging"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/metrics"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/server/debug"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/server/http"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/service/v0"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/tracing"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
// Server is the entrypoint for the server command.
|
||||
func Server(cfg *config.Config) *cli.Command {
|
||||
return &cli.Command{
|
||||
Name: "server",
|
||||
Usage: fmt.Sprintf("start the %s service without runtime (unsupervised mode)", cfg.Service.Name),
|
||||
Category: "server",
|
||||
Before: func(c *cli.Context) error {
|
||||
return configlog.ReturnFatal(parser.ParseConfig(cfg))
|
||||
},
|
||||
Action: func(c *cli.Context) error {
|
||||
logger := logging.Configure(cfg.Service.Name, cfg.Log)
|
||||
err := tracing.Configure(cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var (
|
||||
gr = run.Group{}
|
||||
ctx, cancel = func() (context.Context, context.CancelFunc) {
|
||||
if cfg.Context == nil {
|
||||
return context.WithCancel(context.Background())
|
||||
}
|
||||
return context.WithCancel(cfg.Context)
|
||||
}()
|
||||
metrics = metrics.New(metrics.Logger(logger))
|
||||
)
|
||||
|
||||
defer cancel()
|
||||
|
||||
metrics.BuildInfo.WithLabelValues(version.GetString()).Set(1)
|
||||
|
||||
{
|
||||
|
||||
svc, err := service.New(
|
||||
service.Logger(logger),
|
||||
service.Config(cfg),
|
||||
//service.WithRelationProviders(relationProviders),
|
||||
)
|
||||
if err != nil {
|
||||
logger.Error().Err(err).Msg("handler init")
|
||||
return err
|
||||
}
|
||||
svc = service.NewInstrument(svc, metrics)
|
||||
svc = service.NewLogging(svc, logger) // this logs service specific data
|
||||
svc = service.NewTracing(svc)
|
||||
|
||||
server, err := http.Server(
|
||||
http.Logger(logger),
|
||||
http.Context(ctx),
|
||||
http.Config(cfg),
|
||||
http.Service(svc),
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
logger.Info().
|
||||
Err(err).
|
||||
Str("transport", "http").
|
||||
Msg("Failed to initialize server")
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
gr.Add(func() error {
|
||||
return server.Run()
|
||||
}, func(err error) {
|
||||
logger.Error().
|
||||
Err(err).
|
||||
Str("transport", "http").
|
||||
Msg("Shutting down server")
|
||||
|
||||
cancel()
|
||||
})
|
||||
}
|
||||
|
||||
{
|
||||
server, err := debug.Server(
|
||||
debug.Logger(logger),
|
||||
debug.Context(ctx),
|
||||
debug.Config(cfg),
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
logger.Info().Err(err).Str("transport", "debug").Msg("Failed to initialize server")
|
||||
return err
|
||||
}
|
||||
|
||||
gr.Add(server.ListenAndServe, func(err error) {
|
||||
logger.Error().Err(err)
|
||||
_ = server.Shutdown(ctx)
|
||||
cancel()
|
||||
})
|
||||
}
|
||||
|
||||
return gr.Run()
|
||||
},
|
||||
}
|
||||
}
|
||||
50
services/invitations/pkg/command/version.go
Normal file
50
services/invitations/pkg/command/version.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/registry"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/version"
|
||||
|
||||
tw "github.com/olekukonko/tablewriter"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/config"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
// Version prints the service versions of all running instances.
|
||||
func Version(cfg *config.Config) *cli.Command {
|
||||
return &cli.Command{
|
||||
Name: "version",
|
||||
Usage: "print the version of this binary and the running service instances",
|
||||
Category: "info",
|
||||
Action: func(c *cli.Context) error {
|
||||
fmt.Println("Version: " + version.GetString())
|
||||
fmt.Printf("Compiled: %s\n", version.Compiled())
|
||||
fmt.Println("")
|
||||
|
||||
reg := registry.GetRegistry()
|
||||
services, err := reg.GetService(cfg.HTTP.Namespace + "." + cfg.Service.Name)
|
||||
if err != nil {
|
||||
fmt.Println(fmt.Errorf("could not get %s services from the registry: %v", cfg.Service.Name, err))
|
||||
return err
|
||||
}
|
||||
|
||||
if len(services) == 0 {
|
||||
fmt.Println("No running " + cfg.Service.Name + " service found.")
|
||||
return nil
|
||||
}
|
||||
|
||||
table := tw.NewWriter(os.Stdout)
|
||||
table.SetHeader([]string{"Version", "Address", "Id"})
|
||||
table.SetAutoFormatHeaders(false)
|
||||
for _, s := range services {
|
||||
for _, n := range s.Nodes {
|
||||
table.Append([]string{s.Version, n.Address, n.Id})
|
||||
}
|
||||
}
|
||||
table.Render()
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
35
services/invitations/pkg/config/config.go
Normal file
35
services/invitations/pkg/config/config.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/shared"
|
||||
)
|
||||
|
||||
// Config combines all available configuration parts.
|
||||
type Config struct {
|
||||
Commons *shared.Commons `yaml:"-"` // don't use this directly as configuration for a service
|
||||
|
||||
Service Service `yaml:"-"`
|
||||
|
||||
Tracing *Tracing `yaml:"tracing"`
|
||||
Log *Log `yaml:"log"`
|
||||
Debug Debug `yaml:"debug"`
|
||||
|
||||
HTTP HTTP `yaml:"http"`
|
||||
|
||||
Keycloak Keycloak `yaml:"keycloak"`
|
||||
TokenManager *TokenManager `yaml:"token_manager"`
|
||||
|
||||
Context context.Context `yaml:"-"`
|
||||
}
|
||||
|
||||
// Keycloak configuration
|
||||
type Keycloak struct {
|
||||
BasePath string `yaml:"base_path" env:"INVITATIONS_KEYCLOAK_BASE_PATH" desc:"The URL to access keycloak."`
|
||||
ClientID string `yaml:"client_id" env:"INVITATIONS_KEYCLOAK_CLIENT_ID" desc:"The client id to authenticate with keycloak."`
|
||||
ClientSecret string `yaml:"client_secret" env:"INVITATIONS_KEYCLOAK_CLIENT_SECRET" desc:"The client secret to use in authentication."`
|
||||
ClientRealm string `yaml:"client_realm" env:"INVITATIONS_KEYCLOAK_CLIENT_REALM" desc:"The realm the client is defined in."`
|
||||
UserRealm string `yaml:"user_realm" env:"INVITATIONS_KEYCLOAK_USER_REALM" desc:"The realm users are defined."`
|
||||
InsecureSkipVerify bool `yaml:"insecure_skip_verify" env:"INVITATIONS_KEYCLOAK_INSECURE_SKIP_VERIFY" desc:"Disable TLS certificate validation for Keycloak connections. Do not set this in production environments."`
|
||||
}
|
||||
9
services/invitations/pkg/config/debug.go
Normal file
9
services/invitations/pkg/config/debug.go
Normal file
@@ -0,0 +1,9 @@
|
||||
package config
|
||||
|
||||
// Debug defines the available debug configuration.
|
||||
type Debug struct {
|
||||
Addr string `yaml:"addr" env:"INVITATIONS_DEBUG_ADDR" desc:"Bind address of the debug server, where metrics, health, config and debug endpoints will be exposed."`
|
||||
Token string `yaml:"token" env:"INVITATIONS_DEBUG_TOKEN" desc:"Token to secure the metrics endpoint."`
|
||||
Pprof bool `yaml:"pprof" env:"INVITATIONS_DEBUG_PPROF" desc:"Enables pprof, which can be used for profiling."`
|
||||
Zpages bool `yaml:"zpages" env:"INVITATIONS_DEBUG_ZPAGES" desc:"Enables zpages, which can be used for collecting and viewing in-memory traces."`
|
||||
}
|
||||
87
services/invitations/pkg/config/defaults/defaultconfig.go
Normal file
87
services/invitations/pkg/config/defaults/defaultconfig.go
Normal file
@@ -0,0 +1,87 @@
|
||||
package defaults
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/config"
|
||||
)
|
||||
|
||||
func FullDefaultConfig() *config.Config {
|
||||
cfg := DefaultConfig()
|
||||
EnsureDefaults(cfg)
|
||||
Sanitize(cfg)
|
||||
return cfg
|
||||
}
|
||||
|
||||
func DefaultConfig() *config.Config {
|
||||
return &config.Config{
|
||||
Debug: config.Debug{
|
||||
Addr: "127.0.0.1:0", // :0 to pick any free local port
|
||||
Token: "",
|
||||
Pprof: false,
|
||||
Zpages: false,
|
||||
},
|
||||
HTTP: config.HTTP{
|
||||
Addr: "127.0.0.1:0", // :0 to pick any free local port
|
||||
Root: "/graph/v1.0",
|
||||
Namespace: "com.owncloud.graph",
|
||||
CORS: config.CORS{
|
||||
AllowedOrigins: []string{"*"},
|
||||
},
|
||||
},
|
||||
Service: config.Service{
|
||||
Name: "invitations",
|
||||
},
|
||||
Keycloak: config.Keycloak{
|
||||
BasePath: "https://keycloak.example.org/",
|
||||
ClientID: "invitations-service",
|
||||
ClientSecret: "fake-secret",
|
||||
ClientRealm: "someRealm",
|
||||
UserRealm: "someRealm",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func EnsureDefaults(cfg *config.Config) {
|
||||
// provide with defaults for shared logging, since we need a valid destination address for "envdecode".
|
||||
if cfg.Log == nil && cfg.Commons != nil && cfg.Commons.Log != nil {
|
||||
cfg.Log = &config.Log{
|
||||
Level: cfg.Commons.Log.Level,
|
||||
Pretty: cfg.Commons.Log.Pretty,
|
||||
Color: cfg.Commons.Log.Color,
|
||||
File: cfg.Commons.Log.File,
|
||||
}
|
||||
} else if cfg.Log == nil {
|
||||
cfg.Log = &config.Log{}
|
||||
}
|
||||
// provide with defaults for shared tracing, since we need a valid destination address for "envdecode".
|
||||
if cfg.Tracing == nil && cfg.Commons != nil && cfg.Commons.Tracing != nil {
|
||||
cfg.Tracing = &config.Tracing{
|
||||
Enabled: cfg.Commons.Tracing.Enabled,
|
||||
Type: cfg.Commons.Tracing.Type,
|
||||
Endpoint: cfg.Commons.Tracing.Endpoint,
|
||||
Collector: cfg.Commons.Tracing.Collector,
|
||||
}
|
||||
} else if cfg.Tracing == nil {
|
||||
cfg.Tracing = &config.Tracing{}
|
||||
}
|
||||
|
||||
if cfg.Commons != nil {
|
||||
cfg.HTTP.TLS = cfg.Commons.HTTPServiceTLS
|
||||
}
|
||||
|
||||
if cfg.TokenManager == nil && cfg.Commons != nil && cfg.Commons.TokenManager != nil {
|
||||
cfg.TokenManager = &config.TokenManager{
|
||||
JWTSecret: cfg.Commons.TokenManager.JWTSecret,
|
||||
}
|
||||
} else if cfg.TokenManager == nil {
|
||||
cfg.TokenManager = &config.TokenManager{}
|
||||
}
|
||||
}
|
||||
|
||||
func Sanitize(cfg *config.Config) {
|
||||
// sanitize config
|
||||
if cfg.HTTP.Root != "/" {
|
||||
cfg.HTTP.Root = strings.TrimSuffix(cfg.HTTP.Root, "/")
|
||||
}
|
||||
}
|
||||
20
services/invitations/pkg/config/http.go
Normal file
20
services/invitations/pkg/config/http.go
Normal file
@@ -0,0 +1,20 @@
|
||||
package config
|
||||
|
||||
import "github.com/owncloud/ocis/v2/ocis-pkg/shared"
|
||||
|
||||
// CORS defines the available cors configuration.
|
||||
type CORS struct {
|
||||
AllowedOrigins []string `yaml:"allow_origins" env:"OCIS_CORS_ALLOW_ORIGINS;INVITATIONS_CORS_ALLOW_ORIGINS" desc:"A comma-separated list of allowed CORS origins. See following chapter for more details: *Access-Control-Allow-Origin* at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin"`
|
||||
AllowedMethods []string `yaml:"allow_methods" env:"OCIS_CORS_ALLOW_METHODS;INVITATIONS_CORS_ALLOW_METHODS" desc:"A comma-separated list of allowed CORS methods. See following chapter for more details: *Access-Control-Request-Method* at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Request-Method"`
|
||||
AllowedHeaders []string `yaml:"allow_headers" env:"OCIS_CORS_ALLOW_HEADERS;INVITATIONS_CORS_ALLOW_HEADERS" desc:"A comma-separated list of allowed CORS headers. See following chapter for more details: *Access-Control-Request-Headers* at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Request-Headers."`
|
||||
AllowCredentials bool `yaml:"allow_credentials" env:"OCIS_CORS_ALLOW_CREDENTIALS;INVITATIONS_CORS_ALLOW_CREDENTIALS" desc:"Allow credentials for CORS.See following chapter for more details: *Access-Control-Allow-Credentials* at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials."`
|
||||
}
|
||||
|
||||
// HTTP defines the available http configuration.
|
||||
type HTTP struct {
|
||||
Addr string `yaml:"addr" env:"INVITATIONS_HTTP_ADDR" desc:"The bind address of the HTTP service."`
|
||||
Namespace string `yaml:"-"`
|
||||
Root string `yaml:"root" env:"INVITATIONS_HTTP_ROOT" desc:"Subdirectory that serves as the root for this HTTP service."`
|
||||
CORS CORS `yaml:"cors"`
|
||||
TLS shared.HTTPServiceTLS `yaml:"tls"`
|
||||
}
|
||||
9
services/invitations/pkg/config/log.go
Normal file
9
services/invitations/pkg/config/log.go
Normal file
@@ -0,0 +1,9 @@
|
||||
package config
|
||||
|
||||
// Log defines the available log configuration.
|
||||
type Log struct {
|
||||
Level string `mapstructure:"level" env:"OCIS_LOG_LEVEL;INVITATIONS_LOG_LEVEL" desc:"The log level. Valid values are: \"panic\", \"fatal\", \"error\", \"warn\", \"info\", \"debug\", \"trace\"."`
|
||||
Pretty bool `mapstructure:"pretty" env:"OCIS_LOG_PRETTY;INVITATIONS_LOG_PRETTY" desc:"Activates pretty log output."`
|
||||
Color bool `mapstructure:"color" env:"OCIS_LOG_COLOR;INVITATIONS_LOG_COLOR" desc:"Activates colorized log output."`
|
||||
File string `mapstructure:"file" env:"OCIS_LOG_FILE;INVITATIONS_LOG_FILE" desc:"The path to the log file. Activates logging to this file if set."`
|
||||
}
|
||||
37
services/invitations/pkg/config/parser/parse.go
Normal file
37
services/invitations/pkg/config/parser/parse.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package parser
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
ociscfg "github.com/owncloud/ocis/v2/ocis-pkg/config"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/config"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/config/defaults"
|
||||
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/config/envdecode"
|
||||
)
|
||||
|
||||
// ParseConfig loads configuration from known paths.
|
||||
func ParseConfig(cfg *config.Config) error {
|
||||
_, err := ociscfg.BindSourcesToStructs(cfg.Service.Name, cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defaults.EnsureDefaults(cfg)
|
||||
|
||||
// load all env variables relevant to the config in the current context.
|
||||
if err := envdecode.Decode(cfg); err != nil {
|
||||
// no environment variable set for this config is an expected "error"
|
||||
if !errors.Is(err, envdecode.ErrNoTargetFieldsAreSet) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
defaults.Sanitize(cfg)
|
||||
|
||||
return Validate(cfg)
|
||||
}
|
||||
|
||||
func Validate(cfg *config.Config) error {
|
||||
return nil
|
||||
}
|
||||
6
services/invitations/pkg/config/reva.go
Normal file
6
services/invitations/pkg/config/reva.go
Normal file
@@ -0,0 +1,6 @@
|
||||
package config
|
||||
|
||||
// TokenManager is the config for using the reva token manager
|
||||
type TokenManager struct {
|
||||
JWTSecret string `yaml:"jwt_secret" env:"OCIS_JWT_SECRET;INVITATIONS_JWT_SECRET" desc:"The secret to mint and validate jwt tokens."`
|
||||
}
|
||||
6
services/invitations/pkg/config/service.go
Normal file
6
services/invitations/pkg/config/service.go
Normal file
@@ -0,0 +1,6 @@
|
||||
package config
|
||||
|
||||
// Service defines the available service configuration.
|
||||
type Service struct {
|
||||
Name string `yaml:"-"`
|
||||
}
|
||||
9
services/invitations/pkg/config/tracing.go
Normal file
9
services/invitations/pkg/config/tracing.go
Normal file
@@ -0,0 +1,9 @@
|
||||
package config
|
||||
|
||||
// Tracing defines the available tracing configuration.
|
||||
type Tracing struct {
|
||||
Enabled bool `yaml:"enabled" env:"OCIS_TRACING_ENABLED;INVITATIONS_TRACING_ENABLED" desc:"Activates tracing."`
|
||||
Type string `yaml:"type" env:"OCIS_TRACING_TYPE;INVITATIONS_TRACING_TYPE" desc:"The type of tracing. Defaults to \"\", which is the same as \"jaeger\". Allowed tracing types are \"jaeger\" and \"\" as of now."`
|
||||
Endpoint string `yaml:"endpoint" env:"OCIS_TRACING_ENDPOINT;INVITATIONS_TRACING_ENDPOINT" desc:"The endpoint of the tracing agent."`
|
||||
Collector string `yaml:"collector" env:"OCIS_TRACING_COLLECTOR;INVITATIONS_TRACING_COLLECTOR" desc:"The HTTP endpoint for sending spans directly to a collector, i.e. http://jaeger-collector:14268/api/traces. Only used if the tracing endpoint is unset."`
|
||||
}
|
||||
70
services/invitations/pkg/invitations/invitations.go
Normal file
70
services/invitations/pkg/invitations/invitations.go
Normal file
@@ -0,0 +1,70 @@
|
||||
package invitations
|
||||
|
||||
import libregraph "github.com/owncloud/libre-graph-api-go"
|
||||
|
||||
// Invitation represents an invitation as per https://learn.microsoft.com/en-us/graph/api/resources/invitation?view=graph-rest-1.0
|
||||
type Invitation struct {
|
||||
// The display name of the user being invited.
|
||||
InvitedUserDisplayName string `json:"invitedUserDisplayName,omitempty"`
|
||||
|
||||
// The email address of the user being invited. Required.
|
||||
InvitedUserEmailAddress string `json:"invitedUserEmailAddress"`
|
||||
|
||||
// Additional configuration for the message being sent to the
|
||||
// invited user, including customizing message text, language
|
||||
// and cc recipient list.
|
||||
InvitedUserMessageInfo *InvitedUserMessageInfo `json:"invitedUserMessageInfo,omitempty"`
|
||||
// The userType of the user being invited. By default, this is
|
||||
// `Guest``. You can invite as `Member`` if you are a company
|
||||
// administrator.
|
||||
InvitedUserType string `json:"invitedUserType,omitempty"`
|
||||
// The URL the user should be redirected to once the invitation
|
||||
// is redeemed. Required.
|
||||
InviteRedirectUrl string `json:"inviteRedirectUrl"`
|
||||
// The URL the user can use to redeem their invitation. Read-only.
|
||||
InviteRedeemUrl string `json:"inviteRedeemUrl,omitempty"`
|
||||
// Reset the user's redemption status and reinvite a user while
|
||||
// retaining their user identifier, group memberships, and app
|
||||
// assignments. This property allows you to enable a user to
|
||||
// sign-in using a different email address from the one in the
|
||||
// previous invitation.
|
||||
ResetRedemption string `json:"resetRedemption,omitempty"`
|
||||
// Indicates whether an email should be sent to the user being
|
||||
// invited. The default is false.
|
||||
SendInvitationMessage bool `json:"sendInvitationMessage,omitempty"`
|
||||
// The status of the invitation. Possible values are:
|
||||
// `PendingAcceptance`, `Completed`, `InProgress`, and `Error`.
|
||||
Status string `json:"status,omitempty"`
|
||||
|
||||
// Relations
|
||||
|
||||
// The user created as part of the invitation creation. Read-Only
|
||||
InvitedUser *libregraph.User `json:"invitedUser,omitempty"`
|
||||
}
|
||||
|
||||
type InvitedUserMessageInfo struct {
|
||||
// Additional recipients the invitation message should be sent
|
||||
// to. Currently only 1 additional recipient is supported.
|
||||
CcRecipients []Recipient `json:"ccRecipients"`
|
||||
|
||||
// Customized message body you want to send if you don't want
|
||||
// the default message.
|
||||
CustomizedMessageBody string `json:"customizedMessageBody"`
|
||||
|
||||
// The language you want to send the default message in. If the
|
||||
// customizedMessageBody is specified, this property is ignored,
|
||||
// and the message is sent using the customizedMessageBody. The
|
||||
// language format should be in ISO 639. The default is en-US.
|
||||
MessageLanguage string `json:"messageLanguage"`
|
||||
}
|
||||
type Recipient struct {
|
||||
// The recipient's email address.
|
||||
EmailAddress EmailAddress `json:"emailAddress"`
|
||||
}
|
||||
type EmailAddress struct {
|
||||
// The email address of the person or entity.
|
||||
Aaddress string `json:"address"`
|
||||
|
||||
// The display name of the person or entity.
|
||||
Name string `json:"name"`
|
||||
}
|
||||
17
services/invitations/pkg/logging/logging.go
Normal file
17
services/invitations/pkg/logging/logging.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package logging
|
||||
|
||||
import (
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/config"
|
||||
)
|
||||
|
||||
// LoggerFromConfig initializes a service-specific logger instance.
|
||||
func Configure(name string, cfg *config.Log) log.Logger {
|
||||
return log.NewLogger(
|
||||
log.Name(name),
|
||||
log.Level(cfg.Level),
|
||||
log.Pretty(cfg.Pretty),
|
||||
log.Color(cfg.Color),
|
||||
log.File(cfg.File),
|
||||
)
|
||||
}
|
||||
81
services/invitations/pkg/metrics/metrics.go
Normal file
81
services/invitations/pkg/metrics/metrics.go
Normal file
@@ -0,0 +1,81 @@
|
||||
package metrics
|
||||
|
||||
import "github.com/prometheus/client_golang/prometheus"
|
||||
|
||||
var (
|
||||
// Namespace defines the namespace for the defines metrics.
|
||||
Namespace = "ocis"
|
||||
|
||||
// Subsystem defines the subsystem for the defines metrics.
|
||||
Subsystem = "invitations"
|
||||
)
|
||||
|
||||
// Metrics defines the available metrics of this service.
|
||||
type Metrics struct {
|
||||
BuildInfo *prometheus.GaugeVec
|
||||
Counter *prometheus.CounterVec
|
||||
Latency *prometheus.SummaryVec
|
||||
Duration *prometheus.HistogramVec
|
||||
}
|
||||
|
||||
// New initializes the available metrics.
|
||||
func New(opts ...Option) *Metrics {
|
||||
options := newOptions(opts...)
|
||||
|
||||
m := &Metrics{
|
||||
BuildInfo: prometheus.NewGaugeVec(prometheus.GaugeOpts{
|
||||
Namespace: Namespace,
|
||||
Subsystem: Subsystem,
|
||||
Name: "build_info",
|
||||
Help: "Build information",
|
||||
}, []string{"version"}),
|
||||
Counter: prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: Namespace,
|
||||
Subsystem: Subsystem,
|
||||
Name: "invitation_total",
|
||||
Help: "How many invitation requests processed",
|
||||
}, []string{}),
|
||||
Latency: prometheus.NewSummaryVec(prometheus.SummaryOpts{
|
||||
Namespace: Namespace,
|
||||
Subsystem: Subsystem,
|
||||
Name: "invitation_latency_microseconds",
|
||||
Help: "Invitation request latencies in microseconds",
|
||||
}, []string{}),
|
||||
Duration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
|
||||
Namespace: Namespace,
|
||||
Subsystem: Subsystem,
|
||||
Name: "invitation_duration_seconds",
|
||||
Help: "Invitation request time in seconds",
|
||||
}, []string{}),
|
||||
}
|
||||
|
||||
if err := prometheus.Register(m.BuildInfo); err != nil {
|
||||
options.Logger.Error().
|
||||
Err(err).
|
||||
Str("metric", "BuildInfo").
|
||||
Msg("Failed to register prometheus metric")
|
||||
}
|
||||
|
||||
if err := prometheus.Register(m.Counter); err != nil {
|
||||
options.Logger.Error().
|
||||
Err(err).
|
||||
Str("metric", "counter").
|
||||
Msg("Failed to register prometheus metric")
|
||||
}
|
||||
|
||||
if err := prometheus.Register(m.Latency); err != nil {
|
||||
options.Logger.Error().
|
||||
Err(err).
|
||||
Str("metric", "latency").
|
||||
Msg("Failed to register prometheus metric")
|
||||
}
|
||||
|
||||
if err := prometheus.Register(m.Duration); err != nil {
|
||||
options.Logger.Error().
|
||||
Err(err).
|
||||
Str("metric", "duration").
|
||||
Msg("Failed to register prometheus metric")
|
||||
}
|
||||
|
||||
return m
|
||||
}
|
||||
31
services/invitations/pkg/metrics/options.go
Normal file
31
services/invitations/pkg/metrics/options.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
||||
)
|
||||
|
||||
// Option defines a single option function.
|
||||
type Option func(o *Options)
|
||||
|
||||
// Options defines the available options for this package.
|
||||
type Options struct {
|
||||
Logger log.Logger
|
||||
}
|
||||
|
||||
// newOptions initializes the available default options.
|
||||
func newOptions(opts ...Option) Options {
|
||||
opt := Options{}
|
||||
|
||||
for _, o := range opts {
|
||||
o(&opt)
|
||||
}
|
||||
|
||||
return opt
|
||||
}
|
||||
|
||||
// Logger provides a function to set the logger option.
|
||||
func Logger(val log.Logger) Option {
|
||||
return func(o *Options) {
|
||||
o.Logger = val
|
||||
}
|
||||
}
|
||||
112
services/invitations/pkg/mocks/go_cloak.go
Normal file
112
services/invitations/pkg/mocks/go_cloak.go
Normal file
@@ -0,0 +1,112 @@
|
||||
// Code generated by mockery v2.14.1. DO NOT EDIT.
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
context "context"
|
||||
|
||||
gocloak "github.com/Nerzal/gocloak/v13"
|
||||
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// GoCloak is an autogenerated mock type for the GoCloak type
|
||||
type GoCloak struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
// CreateUser provides a mock function with given fields: ctx, token, realm, user
|
||||
func (_m *GoCloak) CreateUser(ctx context.Context, token string, realm string, user gocloak.User) (string, error) {
|
||||
ret := _m.Called(ctx, token, realm, user)
|
||||
|
||||
var r0 string
|
||||
if rf, ok := ret.Get(0).(func(context.Context, string, string, gocloak.User) string); ok {
|
||||
r0 = rf(ctx, token, realm, user)
|
||||
} else {
|
||||
r0 = ret.Get(0).(string)
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func(context.Context, string, string, gocloak.User) error); ok {
|
||||
r1 = rf(ctx, token, realm, user)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// ExecuteActionsEmail provides a mock function with given fields: ctx, token, realm, params
|
||||
func (_m *GoCloak) ExecuteActionsEmail(ctx context.Context, token string, realm string, params gocloak.ExecuteActionsEmail) error {
|
||||
ret := _m.Called(ctx, token, realm, params)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(context.Context, string, string, gocloak.ExecuteActionsEmail) error); ok {
|
||||
r0 = rf(ctx, token, realm, params)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// LoginClient provides a mock function with given fields: ctx, clientID, clientSecret, realm
|
||||
func (_m *GoCloak) LoginClient(ctx context.Context, clientID string, clientSecret string, realm string) (*gocloak.JWT, error) {
|
||||
ret := _m.Called(ctx, clientID, clientSecret, realm)
|
||||
|
||||
var r0 *gocloak.JWT
|
||||
if rf, ok := ret.Get(0).(func(context.Context, string, string, string) *gocloak.JWT); ok {
|
||||
r0 = rf(ctx, clientID, clientSecret, realm)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).(*gocloak.JWT)
|
||||
}
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func(context.Context, string, string, string) error); ok {
|
||||
r1 = rf(ctx, clientID, clientSecret, realm)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// RetrospectToken provides a mock function with given fields: ctx, accessToken, clientID, clientSecret, realm
|
||||
func (_m *GoCloak) RetrospectToken(ctx context.Context, accessToken string, clientID string, clientSecret string, realm string) (*gocloak.IntroSpectTokenResult, error) {
|
||||
ret := _m.Called(ctx, accessToken, clientID, clientSecret, realm)
|
||||
|
||||
var r0 *gocloak.IntroSpectTokenResult
|
||||
if rf, ok := ret.Get(0).(func(context.Context, string, string, string, string) *gocloak.IntroSpectTokenResult); ok {
|
||||
r0 = rf(ctx, accessToken, clientID, clientSecret, realm)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).(*gocloak.IntroSpectTokenResult)
|
||||
}
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func(context.Context, string, string, string, string) error); ok {
|
||||
r1 = rf(ctx, accessToken, clientID, clientSecret, realm)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
type mockConstructorTestingTNewGoCloak interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}
|
||||
|
||||
// NewGoCloak creates a new instance of GoCloak. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
func NewGoCloak(t mockConstructorTestingTNewGoCloak) *GoCloak {
|
||||
mock := &GoCloak{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() { mock.AssertExpectations(t) })
|
||||
|
||||
return mock
|
||||
}
|
||||
50
services/invitations/pkg/server/debug/option.go
Normal file
50
services/invitations/pkg/server/debug/option.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package debug
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/config"
|
||||
)
|
||||
|
||||
// Option defines a single option function.
|
||||
type Option func(o *Options)
|
||||
|
||||
// Options defines the available options for this package.
|
||||
type Options struct {
|
||||
Logger log.Logger
|
||||
Context context.Context
|
||||
Config *config.Config
|
||||
}
|
||||
|
||||
// newOptions initializes the available default options.
|
||||
func newOptions(opts ...Option) Options {
|
||||
opt := Options{}
|
||||
|
||||
for _, o := range opts {
|
||||
o(&opt)
|
||||
}
|
||||
|
||||
return opt
|
||||
}
|
||||
|
||||
// Logger provides a function to set the logger option.
|
||||
func Logger(val log.Logger) Option {
|
||||
return func(o *Options) {
|
||||
o.Logger = val
|
||||
}
|
||||
}
|
||||
|
||||
// Context provides a function to set the context option.
|
||||
func Context(val context.Context) Option {
|
||||
return func(o *Options) {
|
||||
o.Context = val
|
||||
}
|
||||
}
|
||||
|
||||
// Config provides a function to set the config option.
|
||||
func Config(val *config.Config) Option {
|
||||
return func(o *Options) {
|
||||
o.Config = val
|
||||
}
|
||||
}
|
||||
63
services/invitations/pkg/server/debug/server.go
Normal file
63
services/invitations/pkg/server/debug/server.go
Normal file
@@ -0,0 +1,63 @@
|
||||
package debug
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/service/debug"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/version"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/config"
|
||||
)
|
||||
|
||||
// Server initializes the debug service and server.
|
||||
func Server(opts ...Option) (*http.Server, error) {
|
||||
options := newOptions(opts...)
|
||||
|
||||
return debug.NewService(
|
||||
debug.Logger(options.Logger),
|
||||
debug.Name(options.Config.Service.Name),
|
||||
debug.Version(version.GetString()),
|
||||
debug.Address(options.Config.Debug.Addr),
|
||||
debug.Token(options.Config.Debug.Token),
|
||||
debug.Pprof(options.Config.Debug.Pprof),
|
||||
debug.Zpages(options.Config.Debug.Zpages),
|
||||
debug.Health(health(options.Config)),
|
||||
debug.Ready(ready(options.Config)),
|
||||
debug.CorsAllowedOrigins(options.Config.HTTP.CORS.AllowedOrigins),
|
||||
debug.CorsAllowedMethods(options.Config.HTTP.CORS.AllowedMethods),
|
||||
debug.CorsAllowedHeaders(options.Config.HTTP.CORS.AllowedHeaders),
|
||||
debug.CorsAllowCredentials(options.Config.HTTP.CORS.AllowCredentials),
|
||||
), nil
|
||||
}
|
||||
|
||||
// health implements the health check.
|
||||
func health(cfg *config.Config) func(http.ResponseWriter, *http.Request) {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
// TODO: check if services are up and running
|
||||
|
||||
_, err := io.WriteString(w, http.StatusText(http.StatusOK))
|
||||
// io.WriteString should not fail but if it does we want to know.
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ready implements the ready check.
|
||||
func ready(cfg *config.Config) func(http.ResponseWriter, *http.Request) {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
// TODO: check if services are up and running
|
||||
|
||||
_, err := io.WriteString(w, http.StatusText(http.StatusOK))
|
||||
// io.WriteString should not fail but if it does we want to know.
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
84
services/invitations/pkg/server/http/option.go
Normal file
84
services/invitations/pkg/server/http/option.go
Normal file
@@ -0,0 +1,84 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/config"
|
||||
svc "github.com/owncloud/ocis/v2/services/invitations/pkg/service/v0"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
// Option defines a single option function.
|
||||
type Option func(o *Options)
|
||||
|
||||
// Options defines the available options for this package.
|
||||
type Options struct {
|
||||
Name string
|
||||
Namespace string
|
||||
Logger log.Logger
|
||||
Context context.Context
|
||||
Config *config.Config
|
||||
Flags []cli.Flag
|
||||
Service svc.Service
|
||||
}
|
||||
|
||||
// newOptions initializes the available default options.
|
||||
func newOptions(opts ...Option) Options {
|
||||
opt := Options{}
|
||||
|
||||
for _, o := range opts {
|
||||
o(&opt)
|
||||
}
|
||||
|
||||
return opt
|
||||
}
|
||||
|
||||
// Name provides a name for the service.
|
||||
func Name(val string) Option {
|
||||
return func(o *Options) {
|
||||
o.Name = val
|
||||
}
|
||||
}
|
||||
|
||||
// Logger provides a function to set the logger option.
|
||||
func Logger(val log.Logger) Option {
|
||||
return func(o *Options) {
|
||||
o.Logger = val
|
||||
}
|
||||
}
|
||||
|
||||
// Context provides a function to set the context option.
|
||||
func Context(val context.Context) Option {
|
||||
return func(o *Options) {
|
||||
o.Context = val
|
||||
}
|
||||
}
|
||||
|
||||
// Config provides a function to set the config option.
|
||||
func Config(val *config.Config) Option {
|
||||
return func(o *Options) {
|
||||
o.Config = val
|
||||
}
|
||||
}
|
||||
|
||||
// Flags provides a function to set the flags option.
|
||||
func Flags(val []cli.Flag) Option {
|
||||
return func(o *Options) {
|
||||
o.Flags = append(o.Flags, val...)
|
||||
}
|
||||
}
|
||||
|
||||
// Namespace provides a function to set the namespace option.
|
||||
func Namespace(val string) Option {
|
||||
return func(o *Options) {
|
||||
o.Namespace = val
|
||||
}
|
||||
}
|
||||
|
||||
// Service provides a function to set the service option.
|
||||
func Service(val svc.Service) Option {
|
||||
return func(o *Options) {
|
||||
o.Service = val
|
||||
}
|
||||
}
|
||||
108
services/invitations/pkg/server/http/server.go
Normal file
108
services/invitations/pkg/server/http/server.go
Normal file
@@ -0,0 +1,108 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
chimiddleware "github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/go-chi/render"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/account"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/cors"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/middleware"
|
||||
ohttp "github.com/owncloud/ocis/v2/ocis-pkg/service/http"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/version"
|
||||
"github.com/owncloud/ocis/v2/services/graph/pkg/service/v0/errorcode"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/invitations"
|
||||
svc "github.com/owncloud/ocis/v2/services/invitations/pkg/service/v0"
|
||||
"go-micro.dev/v4"
|
||||
)
|
||||
|
||||
// Server initializes the http service and server.
|
||||
func Server(opts ...Option) (ohttp.Service, error) {
|
||||
options := newOptions(opts...)
|
||||
service := options.Service
|
||||
|
||||
svc, err := ohttp.NewService(
|
||||
ohttp.TLSConfig(options.Config.HTTP.TLS),
|
||||
ohttp.Logger(options.Logger),
|
||||
ohttp.Namespace(options.Config.HTTP.Namespace),
|
||||
ohttp.Name(options.Config.Service.Name),
|
||||
ohttp.Version(version.GetString()),
|
||||
ohttp.Address(options.Config.HTTP.Addr),
|
||||
ohttp.Context(options.Context),
|
||||
ohttp.Flags(options.Flags...),
|
||||
)
|
||||
if err != nil {
|
||||
options.Logger.Error().
|
||||
Err(err).
|
||||
Msg("Error initializing http service")
|
||||
return ohttp.Service{}, err
|
||||
}
|
||||
|
||||
mux := chi.NewMux()
|
||||
|
||||
mux.Use(chimiddleware.RealIP)
|
||||
mux.Use(chimiddleware.RequestID)
|
||||
mux.Use(middleware.TraceContext)
|
||||
mux.Use(middleware.NoCache)
|
||||
mux.Use(
|
||||
middleware.Cors(
|
||||
cors.Logger(options.Logger),
|
||||
cors.AllowedOrigins(options.Config.HTTP.CORS.AllowedOrigins),
|
||||
cors.AllowedMethods(options.Config.HTTP.CORS.AllowedMethods),
|
||||
cors.AllowedHeaders(options.Config.HTTP.CORS.AllowedHeaders),
|
||||
cors.AllowCredentials(options.Config.HTTP.CORS.AllowCredentials),
|
||||
))
|
||||
mux.Use(middleware.Secure)
|
||||
|
||||
mux.Use(middleware.Version(
|
||||
options.Name,
|
||||
version.String,
|
||||
))
|
||||
mux.Use(middleware.ExtractAccountUUID(
|
||||
account.Logger(options.Logger),
|
||||
account.JWTSecret(options.Config.TokenManager.JWTSecret),
|
||||
))
|
||||
|
||||
// this logs http request related data
|
||||
mux.Use(middleware.Logger(
|
||||
options.Logger,
|
||||
))
|
||||
|
||||
mux.Route(options.Config.HTTP.Root, func(r chi.Router) {
|
||||
r.Post("/invitations", InvitationHandler(service))
|
||||
})
|
||||
|
||||
err = micro.RegisterHandler(svc.Server(), mux)
|
||||
if err != nil {
|
||||
options.Logger.Fatal().Err(err).Msg("failed to register the handler")
|
||||
}
|
||||
|
||||
svc.Init()
|
||||
return svc, nil
|
||||
}
|
||||
|
||||
func InvitationHandler(service svc.Service) func(w http.ResponseWriter, r *http.Request) {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
i := &invitations.Invitation{}
|
||||
err := json.NewDecoder(r.Body).Decode(i)
|
||||
if err != nil {
|
||||
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, fmt.Sprintf("invalid request body: %v", err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
res, err := service.Invite(ctx, i)
|
||||
if err != nil {
|
||||
render.Status(r, http.StatusInternalServerError)
|
||||
render.PlainText(w, r, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
render.Status(r, http.StatusCreated)
|
||||
render.JSON(w, r, res)
|
||||
}
|
||||
}
|
||||
10
services/invitations/pkg/service/v0/errors.go
Normal file
10
services/invitations/pkg/service/v0/errors.go
Normal file
@@ -0,0 +1,10 @@
|
||||
package service
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("query target not found")
|
||||
ErrBadRequest = errors.New("bad request")
|
||||
ErrMissingEmail = errors.New("missing email address")
|
||||
ErrBackend = errors.New("backend error")
|
||||
)
|
||||
38
services/invitations/pkg/service/v0/instrument.go
Normal file
38
services/invitations/pkg/service/v0/instrument.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/invitations"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/metrics"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
)
|
||||
|
||||
// NewInstrument returns a service that instruments metrics.
|
||||
func NewInstrument(next Service, metrics *metrics.Metrics) Service {
|
||||
return instrument{
|
||||
next: next,
|
||||
metrics: metrics,
|
||||
}
|
||||
}
|
||||
|
||||
type instrument struct {
|
||||
next Service
|
||||
metrics *metrics.Metrics
|
||||
}
|
||||
|
||||
// Invite implements the Service interface.
|
||||
func (i instrument) Invite(ctx context.Context, invitation *invitations.Invitation) (*invitations.Invitation, error) {
|
||||
timer := prometheus.NewTimer(prometheus.ObserverFunc(func(v float64) {
|
||||
us := v * 1000000
|
||||
|
||||
i.metrics.Latency.WithLabelValues().Observe(us)
|
||||
i.metrics.Duration.WithLabelValues().Observe(v)
|
||||
}))
|
||||
|
||||
defer timer.ObserveDuration()
|
||||
|
||||
i.metrics.Counter.WithLabelValues().Inc()
|
||||
|
||||
return i.next.Invite(ctx, invitation)
|
||||
}
|
||||
30
services/invitations/pkg/service/v0/logging.go
Normal file
30
services/invitations/pkg/service/v0/logging.go
Normal file
@@ -0,0 +1,30 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/invitations"
|
||||
)
|
||||
|
||||
// NewLogging returns a service that logs messages.
|
||||
func NewLogging(next Service, logger log.Logger) Service {
|
||||
return logging{
|
||||
next: next,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
type logging struct {
|
||||
next Service
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
// Invite implements the Service interface.
|
||||
func (l logging) Invite(ctx context.Context, invitation *invitations.Invitation) (*invitations.Invitation, error) {
|
||||
l.logger.Debug().
|
||||
Interface("invitation", invitation).
|
||||
Msg("Invite")
|
||||
|
||||
return l.next.Invite(ctx, invitation)
|
||||
}
|
||||
40
services/invitations/pkg/service/v0/option.go
Normal file
40
services/invitations/pkg/service/v0/option.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/config"
|
||||
)
|
||||
|
||||
// Option defines a single option function.
|
||||
type Option func(o *Options)
|
||||
|
||||
// Options defines the available options for this package.
|
||||
type Options struct {
|
||||
Logger log.Logger
|
||||
Config *config.Config
|
||||
}
|
||||
|
||||
// newOptions initializes the available default options.
|
||||
func newOptions(opts ...Option) Options {
|
||||
opt := Options{}
|
||||
|
||||
for _, o := range opts {
|
||||
o(&opt)
|
||||
}
|
||||
|
||||
return opt
|
||||
}
|
||||
|
||||
// Logger provides a function to set the logger option.
|
||||
func Logger(val log.Logger) Option {
|
||||
return func(o *Options) {
|
||||
o.Logger = val
|
||||
}
|
||||
}
|
||||
|
||||
// Config provides a function to set the config option.
|
||||
func Config(val *config.Config) Option {
|
||||
return func(o *Options) {
|
||||
o.Config = val
|
||||
}
|
||||
}
|
||||
100
services/invitations/pkg/service/v0/service.go
Normal file
100
services/invitations/pkg/service/v0/service.go
Normal file
@@ -0,0 +1,100 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/backends/keycloak"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/config"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/invitations"
|
||||
)
|
||||
|
||||
const (
|
||||
OwnCloudInstanceRel = "http://invitations.owncloud/rel/server-instance"
|
||||
OpenIDConnectRel = "http://openid.net/specs/connect/1.0/issuer"
|
||||
)
|
||||
|
||||
// Service defines the extension handlers.
|
||||
type Service interface {
|
||||
// Invite creates a new invitation. Invitation adds an external user to the organization.
|
||||
//
|
||||
// When creating a new invitation you have several options available:
|
||||
// 1. On invitation creation, Microsoft Graph can automatically send an
|
||||
// invitation email directly to the invited user, or your app can use
|
||||
// the inviteRedeemUrl returned in the creation response to craft your
|
||||
// own invitation (through your communication mechanism of choice) to
|
||||
// the invited user. If you decide to have Microsoft Graph send an
|
||||
// invitation email automatically, you can control the content and
|
||||
// language of the email using invitedUserMessageInfo.
|
||||
// 2. When the user is invited, a user entity (of userType Guest) is
|
||||
// created and can now be used to control access to resources. The
|
||||
// invited user has to go through the redemption process to access any
|
||||
// resources they have been invited to.
|
||||
Invite(ctx context.Context, invitation *invitations.Invitation) (*invitations.Invitation, error)
|
||||
}
|
||||
|
||||
// Backend defines the behaviour of a user backend.
|
||||
type Backend interface {
|
||||
// CreateUser creates a user in the backend and returns an identifier string.
|
||||
CreateUser(ctx context.Context, invitation *invitations.Invitation) (string, error)
|
||||
// CanSendMail should return true if the backend can send mail
|
||||
CanSendMail() bool
|
||||
// SendMail sends a mail to the user with details on how to reedeem the invitation.
|
||||
SendMail(ctx context.Context, identifier string) error
|
||||
}
|
||||
|
||||
// New returns a new instance of Service
|
||||
func New(opts ...Option) (Service, error) {
|
||||
options := newOptions(opts...)
|
||||
|
||||
// Harcode keycloak backend for now, but this should be configurable in the future.
|
||||
backend := keycloak.New(
|
||||
options.Logger,
|
||||
options.Config.Keycloak.BasePath,
|
||||
options.Config.Keycloak.ClientID,
|
||||
options.Config.Keycloak.ClientSecret,
|
||||
options.Config.Keycloak.ClientRealm,
|
||||
options.Config.Keycloak.UserRealm,
|
||||
options.Config.Keycloak.InsecureSkipVerify,
|
||||
)
|
||||
|
||||
return svc{
|
||||
log: options.Logger,
|
||||
config: options.Config,
|
||||
backend: backend,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type svc struct {
|
||||
config *config.Config
|
||||
log log.Logger
|
||||
backend Backend
|
||||
}
|
||||
|
||||
// Invite implements the service interface
|
||||
func (s svc) Invite(ctx context.Context, invitation *invitations.Invitation) (*invitations.Invitation, error) {
|
||||
if invitation == nil {
|
||||
return nil, ErrBadRequest
|
||||
}
|
||||
|
||||
if invitation.InvitedUserEmailAddress == "" {
|
||||
return nil, ErrMissingEmail
|
||||
}
|
||||
|
||||
id, err := s.backend.CreateUser(ctx, invitation)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %s", ErrBackend, err)
|
||||
}
|
||||
|
||||
// As we only have a single backend, and that backend supports email, we don't have
|
||||
// any code to handle mailing ourself yet.
|
||||
if s.backend.CanSendMail() {
|
||||
err := s.backend.SendMail(ctx, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %s", ErrBackend, err)
|
||||
}
|
||||
}
|
||||
|
||||
return invitation, nil
|
||||
}
|
||||
31
services/invitations/pkg/service/v0/tracing.go
Normal file
31
services/invitations/pkg/service/v0/tracing.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/invitations"
|
||||
invitationstracing "github.com/owncloud/ocis/v2/services/invitations/pkg/tracing"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// NewTracing returns a service that instruments traces.
|
||||
func NewTracing(next Service) Service {
|
||||
return tracing{
|
||||
next: next,
|
||||
}
|
||||
}
|
||||
|
||||
type tracing struct {
|
||||
next Service
|
||||
}
|
||||
|
||||
// Invite implements the Service interface.
|
||||
func (t tracing) Invite(ctx context.Context, invitation *invitations.Invitation) (*invitations.Invitation, error) {
|
||||
ctx, span := invitationstracing.TraceProvider.Tracer("invitations").Start(ctx, "Invite", trace.WithAttributes(
|
||||
attribute.KeyValue{Key: "invitation", Value: attribute.StringValue(invitation.InvitedUserEmailAddress)},
|
||||
))
|
||||
defer span.End()
|
||||
|
||||
return t.next.Invite(ctx, invitation)
|
||||
}
|
||||
23
services/invitations/pkg/tracing/tracing.go
Normal file
23
services/invitations/pkg/tracing/tracing.go
Normal file
@@ -0,0 +1,23 @@
|
||||
package tracing
|
||||
|
||||
import (
|
||||
pkgtrace "github.com/owncloud/ocis/v2/ocis-pkg/tracing"
|
||||
"github.com/owncloud/ocis/v2/services/invitations/pkg/config"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
var (
|
||||
// TraceProvider is the global trace provider for the proxy service.
|
||||
TraceProvider = trace.NewNoopTracerProvider()
|
||||
)
|
||||
|
||||
func Configure(cfg *config.Config) error {
|
||||
var err error
|
||||
if cfg.Tracing.Enabled {
|
||||
if TraceProvider, err = pkgtrace.GetTraceProvider(cfg.Tracing.Endpoint, cfg.Tracing.Collector, cfg.Service.Name, cfg.Tracing.Type); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -219,6 +219,10 @@ func DefaultPolicies() []config.Policy {
|
||||
Endpoint: "/app/", // /app or /apps? ocdav only handles /apps
|
||||
Service: "com.owncloud.web.frontend",
|
||||
},
|
||||
{
|
||||
Endpoint: "/graph/v1.0/invitations",
|
||||
Service: "com.owncloud.graph.invitations",
|
||||
},
|
||||
{
|
||||
Endpoint: "/graph/",
|
||||
Service: "com.owncloud.graph.graph",
|
||||
|
||||
Reference in New Issue
Block a user