Compare commits

..
Author SHA1 Message Date
kobergj d9ec62e133 Merge pull request #12091 from kobergj/FixCI
Backport CI fix
2026-03-23 00:11:49 +00:00
kobergj 31b719d308 Merge pull request #12091 from kobergj/FixCI
Backport CI fix
2026-03-22 00:09:29 +00:00
kobergj aaafc41a4b Merge pull request #12091 from kobergj/FixCI
Backport CI fix
2026-03-21 00:09:04 +00:00
kobergj 20d2fd277a Merge pull request #12091 from kobergj/FixCI
Backport CI fix
2026-03-20 00:08:42 +00:00
kobergj 4d78fdafde Merge pull request #12091 from kobergj/FixCI
Backport CI fix
2026-03-19 00:09:34 +00:00
kobergj e05ca4d9f5 Merge pull request #12091 from kobergj/FixCI
Backport CI fix
2026-03-18 03:08:52 +00:00
kobergj bed1000fe0 Merge pull request #12091 from kobergj/FixCI
Backport CI fix
2026-03-18 00:10:01 +00:00
kobergj f4299090ed Merge pull request #12091 from kobergj/FixCI
Backport CI fix
2026-03-17 03:35:17 +00:00
kobergj 5cd12c3aeb Merge pull request #12091 from kobergj/FixCI
Backport CI fix
2026-03-17 00:08:01 +00:00
kobergj 645fb4e5bd Merge pull request #12091 from kobergj/FixCI
Backport CI fix
2026-03-16 03:42:40 +00:00
kobergj 82e568d37d Merge pull request #12091 from kobergj/FixCI
Backport CI fix
2026-03-16 00:10:36 +00:00
kobergj 4e700f0740 Merge pull request #12091 from kobergj/FixCI
Backport CI fix
2026-03-15 00:08:40 +00:00
kobergj a0b0d20bd9 Merge pull request #12091 from kobergj/FixCI
Backport CI fix
2026-03-14 00:08:32 +00:00
kobergj bff040a6c0 Merge pull request #12091 from kobergj/FixCI
Backport CI fix
2026-03-13 00:09:35 +00:00
kobergj 1c2f071b33 Merge pull request #12091 from kobergj/FixCI
Backport CI fix
2026-03-12 00:07:56 +00:00
kobergj 48b5a93560 Merge pull request #12091 from kobergj/FixCI
Backport CI fix
2026-03-11 10:24:39 +00:00
kobergj 782af50f04 Merge pull request #12098 from owncloud/Release-8.0.1
[full-ci][k6-test] Release 8.0.1
2026-03-11 08:10:40 +00:00
kobergj 6542518682 Merge pull request #12096 from owncloud/backport/ocisdev-670
[backport] feat: add globalID for EK users
2026-03-11 00:08:11 +00:00
kobergj f398c32630 Merge pull request #12096 from owncloud/backport/ocisdev-670
[backport] feat: add globalID for EK users
2026-03-10 00:04:22 +00:00
kobergj df2fad3837 Merge pull request #12096 from owncloud/backport/ocisdev-670
[backport] feat: add globalID for EK users
2026-03-09 14:52:09 +00:00
kobergj 8f9e07a984 Merge pull request #12097 from kobergj/BumpReva
[full-ci] Bump Reva
2026-03-09 13:55:57 +00:00
kobergj f77e64cdf5 Merge pull request #12085 from owncloud/OmitExternalIDWhenEmpty
[OCISDEV-704] Dont write ExternalID when empty
2026-03-09 09:58:23 +00:00
Roman Perekhod 8cce4abe4b Merge pull request #12052 from owncloud/backport/8.0/OCISDEV-617
fix:[OCISDEV-617] Expose the signature-auth attribute
2026-03-09 00:08:09 +00:00
Roman Perekhod 33390e9256 Merge pull request #12052 from owncloud/backport/8.0/OCISDEV-617
fix:[OCISDEV-617] Expose the signature-auth attribute
2026-03-08 00:36:37 +00:00
Roman Perekhod f8ee51d7f2 Merge pull request #12052 from owncloud/backport/8.0/OCISDEV-617
fix:[OCISDEV-617] Expose the signature-auth attribute
2026-03-07 00:35:38 +00:00
Roman Perekhod ae1bf0b6ed Merge pull request #12052 from owncloud/backport/8.0/OCISDEV-617
fix:[OCISDEV-617] Expose the signature-auth attribute
2026-03-06 15:34:29 +00:00
kobergj b56532aa15 Merge pull request #12077 from kobergj/BackportGroupFix
[OCISDEV-672][Backport 8.0] Dont use hardcoded groupOfNames
2026-03-06 00:36:15 +00:00
kobergj d07fa88107 Merge pull request #12077 from kobergj/BackportGroupFix
[OCISDEV-672][Backport 8.0] Dont use hardcoded groupOfNames
2026-03-05 00:08:57 +00:00
kobergj a545914163 Merge pull request #12077 from kobergj/BackportGroupFix
[OCISDEV-672][Backport 8.0] Dont use hardcoded groupOfNames
2026-03-04 09:27:05 +00:00
Lukas Hirt 7e640b4f73 Merge pull request #12074 from owncloud/chore/bump-web
[full-ci] chore(web): bump ownCloud Web to v12.3.2
2026-03-04 00:09:09 +00:00
Lukas Hirt adea638bdf Merge pull request #12074 from owncloud/chore/bump-web
[full-ci] chore(web): bump ownCloud Web to v12.3.2
2026-03-03 03:34:59 +00:00
Lukas Hirt 2324800182 Merge pull request #12074 from owncloud/chore/bump-web
[full-ci] chore(web): bump ownCloud Web to v12.3.2
2026-03-03 00:07:42 +00:00
Lukas Hirt 3f54d016ae Merge pull request #12074 from owncloud/chore/bump-web
[full-ci] chore(web): bump ownCloud Web to v12.3.2
2026-03-02 10:32:08 +00:00
Roman Perekhod 3faba4b4c5 Merge pull request #12058 from owncloud/backport/use-kpop-without-dependency
[backport] chore(idp): use kpop without dependency
2026-03-02 00:08:12 +00:00
Roman Perekhod 445c4941a5 Merge pull request #12058 from owncloud/backport/use-kpop-without-dependency
[backport] chore(idp): use kpop without dependency
2026-03-01 00:07:48 +00:00
Roman Perekhod 005f8fbe47 Merge pull request #12058 from owncloud/backport/use-kpop-without-dependency
[backport] chore(idp): use kpop without dependency
2026-02-28 00:07:29 +00:00
Roman Perekhod b520e09564 Merge pull request #12058 from owncloud/backport/use-kpop-without-dependency
[backport] chore(idp): use kpop without dependency
2026-02-27 00:20:27 +00:00
Roman Perekhod f6d540b791 Merge pull request #12058 from owncloud/backport/use-kpop-without-dependency
[backport] chore(idp): use kpop without dependency
2026-02-26 00:19:15 +00:00
Roman Perekhod 44ae095b6f Merge pull request #12058 from owncloud/backport/use-kpop-without-dependency
[backport] chore(idp): use kpop without dependency
2026-02-25 00:17:17 +00:00
Roman Perekhod 8949852719 Merge pull request #12058 from owncloud/backport/use-kpop-without-dependency
[backport] chore(idp): use kpop without dependency
2026-02-24 15:41:24 +00:00
kobergj 375d5e22d9 Merge pull request #12031 from owncloud/bp-11986
[tests-only][full-ci] test:  fix public link related test for k8s deployment
2026-02-24 00:21:31 +00:00
kobergj d5b6596b7d Merge pull request #12031 from owncloud/bp-11986
[tests-only][full-ci] test:  fix public link related test for k8s deployment
2026-02-23 03:42:18 +00:00
kobergj 2d04904c94 Merge pull request #12031 from owncloud/bp-11986
[tests-only][full-ci] test:  fix public link related test for k8s deployment
2026-02-23 00:20:50 +00:00
kobergj 1da5a3f435 Merge pull request #12031 from owncloud/bp-11986
[tests-only][full-ci] test:  fix public link related test for k8s deployment
2026-02-22 00:20:33 +00:00
kobergj 49938864be Merge pull request #12031 from owncloud/bp-11986
[tests-only][full-ci] test:  fix public link related test for k8s deployment
2026-02-21 00:21:19 +00:00
kobergj 1f028f48f8 Merge pull request #12031 from owncloud/bp-11986
[tests-only][full-ci] test:  fix public link related test for k8s deployment
2026-02-20 03:31:56 +00:00
kobergj 1168ba48ab Merge pull request #12031 from owncloud/bp-11986
[tests-only][full-ci] test:  fix public link related test for k8s deployment
2026-02-20 00:20:57 +00:00
kobergj 77998a3d6e Merge pull request #12031 from owncloud/bp-11986
[tests-only][full-ci] test:  fix public link related test for k8s deployment
2026-02-19 03:32:58 +00:00
kobergj f35b602ad4 Merge pull request #12031 from owncloud/bp-11986
[tests-only][full-ci] test:  fix public link related test for k8s deployment
2026-02-19 00:20:12 +00:00
kobergj ea5fbe9f2d Merge pull request #12031 from owncloud/bp-11986
[tests-only][full-ci] test:  fix public link related test for k8s deployment
2026-02-18 09:32:47 +00:00
Martin 1602985c6d Merge pull request #12023 from kobergj/AutomationChanges
[docs-only] Write to docs-stable-8.0
2026-02-18 03:29:46 +00:00
Martin 6ca3153ebb Merge pull request #12023 from kobergj/AutomationChanges
[docs-only] Write to docs-stable-8.0
2026-02-18 00:20:04 +00:00
Martin 0621eb75cc Merge pull request #12023 from kobergj/AutomationChanges
[docs-only] Write to docs-stable-8.0
2026-02-17 03:30:40 +00:00
Martin 863b171ae3 Merge pull request #12023 from kobergj/AutomationChanges
[docs-only] Write to docs-stable-8.0
2026-02-17 00:29:30 +00:00
Martin 337be23110 Merge pull request #12023 from kobergj/AutomationChanges
[docs-only] Write to docs-stable-8.0
2026-02-16 13:23:36 +00:00
Julian Koberg a908c6cb6f initial commit 2026-02-16 11:29:45 +01:00
1593 changed files with 78053 additions and 170395 deletions

No files matched your search

-19
View File
@@ -1,19 +0,0 @@
---
exclude_paths:
- '.github/**'
- 'CHANGELOG.md'
- '**/CHANGELOG.md'
- 'changelog/**'
- '**/changelog/**'
- 'docs/**'
- '**/docs/**'
- '**/pkg/proto/**'
- 'konnectd/ui_config/**'
- 'konnectd/scripts/**'
- 'settings/rollup.config.js'
- 'accounts/rollup.config.js'
- 'ocis/docker/eos-ocis/Dockerfile'
- 'ocis/docker/eos-ocis-dev/Dockerfile'
- 'deployments/**'
...
-7
View File
@@ -1,7 +0,0 @@
# The test runner source for API tests
CORE_COMMITID=ec99c594e90b83c8a3778834e31a5714df630ffc
CORE_BRANCH=master
# The test runner source for UI tests
WEB_COMMITID=5945833ca594c16d33514da74b3d2eb64d3560fd
WEB_BRANCH=master
-1620
View File
File diff suppressed because it is too large. Load diff
-27
View File
@@ -1,27 +0,0 @@
# http://editorconfig.org
root = true
[*]
charset = utf-8
insert_final_newline = true
trim_trailing_whitespace = true
[Makefile]
indent_style = tab
indent_size = 4
[*.go]
indent_style = tab
indent_size = 4
[*.starlark]
indent_style = space
indent_size = 2
[*.yml]
indent_style = space
indent_size = 2
[*.md]
trim_trailing_whitespace = true
-2
View File
@@ -1,2 +0,0 @@
/onlyoffice/ @LukasHirt
.drone.star @wkloucek @micbar @phil-davis @individual-it
-45
View File
@@ -1,45 +0,0 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: Type:Bug
assignees: ''
---
## Describe the bug
A clear and concise description of what the bug is.
## Steps to reproduce
Steps to reproduce the behavior:
1.
2.
3.
## Expected behavior
A clear and concise description of what you expected to happen.
## Actual behavior
A clear and concise description of what happened.
## Setup
Please describe how you started the server and provide a list of relevant environment variables.
<details>
<p>
```console
OCIS_VERSION=vX.X.X
BRANCH=vX.X.X
STORAGE_FRONTEND_UPLOAD_DISABLE_TUS=false
```
</p>
</details>
## Additional context
Add any other context about the problem here.
-20
View File
@@ -1,20 +0,0 @@
---
name: Feature request
about: Suggest an idea for improving oCIS
title: ''
labels: Category:Feature, Topic:needs-triage
assignees: ''
---
## Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
## Describe the solution you'd like
A clear and concise description of what you want to happen.
## Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.
## Additional context
Add any other context or screenshots about the feature request here.
-12
View File
@@ -1,12 +0,0 @@
# Configuration for update-docs - https://github.com/behaviorbot/update-docs
# Comment to be posted to on PRs that don't update documentation
updateDocsComment: >
Thanks for opening this pull request! The maintainers of this repository would appreciate it if you would create a [changelog](https://github.com/owncloud/ocis/blob/master/changelog/README.md) item based on your changes.
updateDocsWhiteList:
- Tests-only
- tests-only
- Tests-Only
updateDocsTargetFiles:
- changelog/unreleased/
-57
View File
@@ -1,57 +0,0 @@
<!--
Thanks for submitting a change to ownCloud!
This is the bug tracker for the oCIS component. Find other components at https://github.com/owncloud/core/blob/master/.github/CONTRIBUTING.md#guidelines
For fixing potential security issues please see https://owncloud.org/security/
To make it possible for us to get your change reviewed and merged please carefully fill out the requested information below.
Please note that any kind of change needs first be submitted to the master branch which holds the next version of OCIS.
Please set the following labels:
- Set label "Status:Needs-Review" for review or "Status:In-Progress" if the PR still has open tasks.
- Assignment: assign to self
- Reviewers: pick at least one
-->
## Description
<!--- Describe your changes in detail -->
## Related Issue
<!--- This project only accepts pull requests related to open issues -->
<!--- If suggesting a new feature or change, please discuss it in an issue first -->
<!--- If fixing a bug, there should be an issue describing it with steps to reproduce -->
<!--- Please link to the issue here: -->
- Fixes <issue_link>
## Motivation and Context
<!--- Why is this change required? What problem does it solve? -->
## How Has This Been Tested?
<!--- Please describe in detail how you tested your changes. -->
<!--- Include details of your testing environment, and the tests you ran to -->
<!--- see how your change affects other areas of the code, etc. -->
- test environment:
- test case 1:
- test case 2:
- ...
## Screenshots (if appropriate):
## Types of changes
<!--- What types of changes does your code introduce? Put an `x` in all the boxes that apply: -->
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to change)
- [ ] Technical debt
- [ ] Tests only (no source changes)
## Checklist:
<!-- Tick the checkboxes when done. -->
<!-- Raise documentation ticket in owncloud.github.io/ -->
- [ ] Code changes
- [ ] Unit tests added
- [ ] Acceptance tests added
- [ ] Documentation ticket raised: <link>
-52
View File
@@ -1,52 +0,0 @@
---
_extends: gh-labels
repository:
name: ocis
description: ':atom_symbol: ownCloud Infinite Scale Stack'
homepage: https://owncloud.github.io/ocis/
topics: reva, ocis
private: false
has_issues: true
has_projects: false
has_wiki: true
has_downloads: false
default_branch: master
allow_squash_merge: true
allow_merge_commit: true
allow_rebase_merge: true
labels:
- name: OCIS-Fastlane
color: "#deadbf"
description: Something isn't working
teams:
- name: ci
permission: admin
- name: employees
permission: push
branches:
- name: master
protection:
required_pull_request_reviews:
required_approving_review_count: 1
dismiss_stale_reviews: false
require_code_owner_reviews: false
dismissal_restrictions: {}
required_status_checks:
strict: true
contexts:
- continuous-integration/drone/pr
enforce_admins: false
restrictions:
users: []
teams:
- ci
- employees
...
-18
View File
@@ -1,18 +0,0 @@
only: issues
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 60
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 10
# Issues with these labels will never be considered stale
exemptLabels:
- "Type:Bug"
- "Type:Technical-Debt"
# Label to use when marking an issue as stale
staleLabel: "Status:Stale"
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
This issue has been automatically marked as stale because it has not had
recent activity. It will be closed in 10 days if no further activity occurs. Thank you
for your contributions.
# Comment to post when closing a stale issue. Set to `false` to disable
closeComment: false
-26
View File
@@ -1,26 +0,0 @@
*/coverage.out
ocis/config/identifier-registration.yaml
*/bin
dist/
/hugo
*.key
*crt
node_modules/
*/assets
.idea
yarn-error.log
# Konnectd
konnectd/assets/identifier
# Composer - used for API acceptance tests
composer.lock
vendor
vendor-bin/**/vendor
vendor-bin/**/composer.lock
# drone CI is in .drone.star, do not let someone accidentally commit a local .drone.yml
.drone.yml
-2225
View File
File diff suppressed because it is too large. Load diff
-32
View File
@@ -1,32 +0,0 @@
FROM webhippie/golang:1.15 as build
COPY ./ /ocis/
ENV CGO_ENABLED=0
ENV GOOS=linux
RUN apk update && \
apk upgrade --ignore musl-dev && \
apk add make gcc bash && \
rm -rf /var/cache/apk/*
WORKDIR /ocis/ocis
RUN make clean generate build
FROM alpine:3
RUN apk update && \
apk upgrade && \
apk add ca-certificates mailcap && \
rm -rf /var/cache/apk/* && \
echo 'hosts: files dns' >| /etc/nsswitch.conf
LABEL maintainer="ownCloud GmbH <devops@owncloud.com>" \
org.label-schema.name="ownCloud Infinite Scale" \
org.label-schema.vendor="ownCloud GmbH" \
org.label-schema.schema-version="1.0"
ENTRYPOINT ["/usr/bin/ocis"]
CMD ["server"]
COPY --from=build /ocis/ocis/bin/ocis /usr/bin/ocis
-202
View File
@@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2020 ownCloud GmbH
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-99
View File
@@ -1,99 +0,0 @@
SHELL := bash
# define standard colors
BLACK := $(shell tput -Txterm setaf 0)
RED := $(shell tput -Txterm setaf 1)
GREEN := $(shell tput -Txterm setaf 2)
YELLOW := $(shell tput -Txterm setaf 3)
LIGHTPURPLE := $(shell tput -Txterm setaf 4)
PURPLE := $(shell tput -Txterm setaf 5)
BLUE := $(shell tput -Txterm setaf 6)
WHITE := $(shell tput -Txterm setaf 7)
RESET := $(shell tput -Txterm sgr0)
OCIS_MODULES = \
accounts \
glauth \
konnectd \
ocis \
ocis-pkg \
ocs \
onlyoffice \
proxy \
settings \
storage \
store \
thumbnails \
web \
webdav
.PHONY: help
help:
@echo "Please use 'make <target>' where <target> is one of the following:"
@echo
@echo -e "${GREEN}Testing with test suite natively installed:${RESET}\n"
@echo -e "${PURPLE}\tdocs: https://owncloud.github.io/ocis/development/testing/#testing-with-test-suite-natively-installed${RESET}\n"
@echo -e "\tmake test-acceptance-api\t${BLUE}run API acceptance tests${RESET}"
@echo -e "\tmake clean-tests\t\t${BLUE}delete API tests framework dependencies${RESET}"
@echo
@echo -e "${BLACK}---------------------------------------------------------${RESET}"
@echo
@echo -e "${RED}You also should have a look at other available Makefiles:${RESET}"
@echo
@echo -e "${GREEN}oCIS:${RESET}\n"
@echo -e "${PURPLE}\tdocs: https://owncloud.github.io/ocis/development/building/${RESET}\n"
@echo -e "\tsee ./ocis/Makefile"
@echo -e "\tor run ${YELLOW}make -C ocis help${RESET}"
@echo
@echo -e "${GREEN}Documentation:${RESET}\n"
@echo -e "${PURPLE}\tdocs: https://owncloud.github.io/ocis/development/building-docs/${RESET}\n"
@echo -e "\tsee ./docs/Makefile"
@echo -e "\tor run ${YELLOW}make -C docs help${RESET}"
@echo
@echo -e "${GREEN}Testing with test suite in docker:${RESET}\n"
@echo -e "${PURPLE}\tdocs: https://owncloud.github.io/ocis/development/testing/#testing-with-test-suite-in-docker${RESET}\n"
@echo -e "\tsee ./tests/acceptance/docker/Makefile"
@echo -e "\tor run ${YELLOW}make -C tests/acceptance/docker help${RESET}"
@echo
.PHONY: clean-tests
clean-tests:
@rm -Rf vendor-bin/**/vendor vendor-bin/**/composer.lock tests/acceptance/output
BEHAT_BIN=vendor-bin/behat/vendor/bin/behat
.PHONY: test-acceptance-api
test-acceptance-api: vendor-bin/behat/vendor
BEHAT_BIN=$(BEHAT_BIN) $(PATH_TO_CORE)/tests/acceptance/run.sh --remote --type api
vendor/bamarni/composer-bin-plugin: composer.lock
composer install
vendor-bin/behat/vendor: vendor/bamarni/composer-bin-plugin vendor-bin/behat/composer.lock
composer bin behat install --no-progress
vendor-bin/behat/composer.lock: vendor-bin/behat/composer.json
@echo behat composer.lock is not up to date.
composer.lock: composer.json
@echo composer.lock is not up to date.
.PHONY: go-mod-tidy
go-mod-tidy:
@for mod in $(OCIS_MODULES); do \
$(MAKE) --no-print-directory -C $$mod go-mod-tidy; \
done
.PHONY: test
test:
@for mod in $(OCIS_MODULES); do \
$(MAKE) --no-print-directory -C $$mod test; \
done
.PHONY: go-coverage
go-coverage:
@if [ ! -f coverage.out ]; then $(MAKE) test &>/dev/null; fi;
@for mod in $(OCIS_MODULES); do \
echo -n "% coverage $$mod: "; $(MAKE) --no-print-directory -C $$mod go-coverage; \
done
-37
View File
@@ -1,37 +0,0 @@
# ownCloud Infinite Scale
[![Rocket chat](https://img.shields.io/badge/Chat%20on%20Rocket.Chat-blue?logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAABhGlDQ1BJQ0MgcHJvZmlsZQAAKJF9kT1Iw0AcxV9TpSItDnaQIpKhOlkQFemoVShChVArtOpgcv2EJg1Jiouj4Fpw8GOx6uDirKuDqyAIfoA4OTopukiJ/0sKLWI8OO7Hu3uPu3eA0Kwy1eyZAFTNMtLJhJjNrYqBVwQxghDiiMjM1OckKQXP8XUPH1/vYjzL+9yfI5QvmAzwicSzTDcs4g3imU1L57xPHGZlOU98Tjxu0AWJH7muuPzGueSwwDPDRiY9TxwmFktdrHQxKxsq8TRxNK9qlC9kXc5z3uKsVuusfU/+wmBBW1nmOs1hJLGIJUgQoaCOCqqwEKNVI8VEmvYTHv6I45fIpZCrAkaOBdSgQnb84H/wu1uzODXpJgUTQO+LbX+MAoFdoNWw7e9j226dAP5n4Err+GtNIP5JeqOjRY+AgW3g4rqjKXvA5Q4w9KTLhuxIfppCsQi8n9E35YDBW6B/ze2tvY/TByBDXaVugINDYKxE2ese7+7r7u3fM+3+fgDAvHLGj7r9AwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB+QMHg05Mvq8cfAAAAAGYktHRAD/AP8A/6C9p5MAAAcbSURBVGje7VlpTFRXGLU0NmmNpuma9IciCCKCQDTuxqQWkrrTNJAal6Y2ECyoURONRBPXuBujVpsYiys1qUH7w8QVjQnVP9Zqq3Y2FgcQmIEBBpgZmPl6vvveLG94D2ZAFhNvcsIwb5nv3G87994hQ970oY+OjgaygR3AWmAyMPRNIjAV+A8gGQ3AKX1U1Nf60aNTgVn4nIDvPgLeGYwE3gd+ATwBJBhuQ2xshyEuzmWIiWnQRUY+0o0adRBkUvQxMRGDicAHwLkg4xUwTJtG5RkZVDZnDunHjKmCV3JB4r3BQyIq6jgM83RFQhCZNIlMqamkj41txzO/47tcYBWwApgHJAGfABH96YGxMMbMxnVHoAsweRdgBf4GfgW+A77AxPRt3ugjIzONycmO+qIiMqal9YxAVBThPYQcIYSX9H90dDvwFNjIRPqWQFKSo+3RI7Jev84xHjaBMuRHdX4+mVesoNJZs0gfFyeRkIiwd2qAQmA1sBhIAT4F3n0dIRSLH9LVbd9OzpqaHnvBMGMG6ZOSQrmXPVMve+cikANwme55UYDb1xri413VO3aQITm5N7nQ0/x5BXBR+Bb4sEdeQJ2vN0ycKNxuGDeuV3kggM96GbqA78V3UmipwQHcAzK4vIdTRvNQ16UyGhtLtbt2hRZKsnGGsWOpFL3iZXo6Va9aRbVbt5LlwAGyHj0qwJ9rt2yhqpwcqli8mExTp4pnfCQ7v7tVzpmEUGZ/GmD2GmReupScZjOV4ce0ZloYDS9VLFpEdbt3k/3GDXKZTORuaiLq6CCt4cE1vsdpNJIdBaNu506qWLBAvEun7hmWON902VdwMQoo8j5ku3CB2hsbqSw7W3XGjRMmUHVuLtlv3aKOhgbq1fB4qKO+XpBh7xgTE9U8wr0lq8uKhYs/i9hPSKCWBw+kchpYUXhmUF7Ny5ZRy7175HE66XUPj8NB9uJiMi9Z4v9NPwkb8H1IBCznz5ORNY/3YTQmnhnr4cO9n/EQBnvEsn+/sCWIRCUwW4vAJu+NprlzFTNvTEmhxkuXRPz21/C0t4tQNnIUKEkUs9ZSI/AlYFfczB6JjyfbuXMiVvt9uN3UcPo0GbxdXbKrA/hJjcAIoESRPAidmk2b+iTeQ/ZEWxu9Wr9e0ld+2x7w4kqNxInA2S+dPp0cz5/TQA/H06dkmjIl0AstQGqw8RFy4xA3cU1+tWGDcKNWorF7azZuJFtBQefkxnMt9++LhlaHpuh48qTTO9orK8l67JjwctPly+RubdXMh+o1a6Q+4fdCfjCB4bJrfDc1FhaqvxAhVbN5s9TQWBrgLxvqcbl897TcvUsmrC+88oFXcs4XL/z8bDaqWrnSJzGwdKX6Eyc0vWA7cyY4mQuMgesMfPEZ8MynLJE4bITacBoMZJo82R+X+MsywlVW5ruHPaMbOZICPVp/8qTvemtJiSgQXqP4esX8+Zpl2n7zpiAZQOAPxc6JrM3/DYUASwY2WEFg5kxyVVT4CcBDgQS4uzacOuUn8PAhGcaPVxKALHFDAagSgFTpjgCH0F+KELp4UTMmWf9A/EkhhBdb9u1TaCA2kEl5VSnrHSbuCyG7XcS1NwyZjO3s2V6FEC/EyxVJjPKlJczczc3UdOWKMLzp6lVhULDGaXv8mKxHjojQYfHWqRBYLGTDJHHXtd++rVmuRRKvXh2cxJsDjR8GHFfsC3EZRZg4nj0b+DKKCiZyTllGvwre2MqQ48qlaGRIRhZZA9rI1q0LbmQlWo1sKHBSISWg0zn+tPpBn0sJJL6KlMjpSpXGKfZJWcxhjcw9gWOx32YePYWTWkXM3QI+7m6FthxoVshpLGLsd+70i/Gc3JY9exRlVsZLYGYoS0wOpW3y9odUlVDqeD3Q1/HOqzxzZqbagoa3YZaGs0sxCigNJMD7Rq/fao+Y8eZr16gqK0taxHReUtYBP2BFGBEOgZEKAnip5dAhTZdz13bq9aKTdpUrfI11EN/LRtdu20bl8+aJRNVY1LO8WRiW8TKB2Yo8wHq4qaios/G1tVSdlycMYMnLcqAqO5tq8vPJsnevCDsGxzTLC57lioULJXmMDi6MVpbIwFrPW/7jerrduDewEvE+jlOnU2qi8nJhkG8PVGVjS4HQNrbagNtAOvennho/Pjh8uJV75TKHAYcMz7bG7IULt7xgL5Q3fkf09ripQNEHEhOlPSCrlVqKi8VCh3uDivFtgZWrC7jkxGTxeAb4Ue4/vTtYNEDdydvfjuBGVrl8OZWnpUkaXj0E/gQWyDOYB2wHDssa6xhwENgqn4bOBxLFoWG4ydnN7LMesmhtJWqEC8/mb3xUO9AHfXy+VR1m3D6X9/aHD4aTSj4xOQr8I/aHOh+5eoVUrVwl1nCzG2znxbwz8bncA7JkOcGxu0/eucuUY3fYkLfj7Xg7Bs34HwoINZEQp4aVAAAAAElFTkSuQmCC)](https://talk.owncloud.com/channel/infinitescale)
[![Build Status](https://drone.owncloud.com/api/badges/owncloud/ocis/status.svg)](https://drone.owncloud.com/owncloud/ocis)
[![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=owncloud_ocis&metric=security_rating)](https://sonarcloud.io/dashboard?id=owncloud_ocis)
[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=owncloud_ocis&metric=coverage)](https://sonarcloud.io/dashboard?id=owncloud_ocis)
[![Go Report](https://goreportcard.com/badge/github.com/owncloud/ocis)](https://goreportcard.com/report/github.com/owncloud/ocis)
[![Go Doc](https://godoc.org/github.com/owncloud/ocis?status.svg)](http://godoc.org/github.com/owncloud/ocis)
[![oCIS docker image](https://img.shields.io/docker/v/owncloud/ocis?label=oCIS%20docker%20image&logo=docker&sort=semver)](https://hub.docker.com/r/owncloud/ocis)
**ownCloud Infinite Scale is currently in a technical preview state. It will be subject to a lot of changes and is not yet ready for general production deployments.**
## Run ownCloud Infinite Scale
Please see [Getting Started](https://owncloud.github.io/ocis/getting-started/)
## Development
Please see [Development - Getting Started](https://owncloud.github.io/ocis/development/getting-started/)
## Security
If you find a security issue please contact [security@owncloud.com](mailto:security@owncloud.com) first
## Contributing
Fork -> Patch -> Push -> Pull Request
## License
Apache-2.0
## Copyright
```console
Copyright (c) 2020 ownCloud GmbH <https://owncloud.com>
```
+46
View File
@@ -0,0 +1,46 @@
---
title: ownCloud
---
{{< toc >}}
## Admin Documentation
Before you start reading, if you are interested in:
- learning ocis from an admin perspective,
- different deployment scenarios,
- deployment examples,
- detailed settings and more
we would recommend to continue with the [ownCloud Admin Documentation for Infinite Scale](https://doc.owncloud.com/ocis/latest/).
## Developer Documentation
Welcome to our developer documentation. Here you find documentation with focus for *developers*:
- [oCIS]({{< ref "./ocis" >}}) server
- oCIS Services
- Clients like:
- [ownCloud Web](https://github.com/owncloud/web) - the new web frontend for oCIS and ownCloud
- [ownCloud Android app](https://github.com/owncloud/android)
- [ownCloud iOS app](https://github.com/owncloud/ios-app)
- [ownCloud Desktop Syncing Client](https://github.com/owncloud/client)
- Integrations
## We love open source
The oCIS server is Apache v2 licensed.
The lower storage layer of oCIS is defined by the CS3 APIs and implemented in the REVA project. Our goal is to develop the CS3 APIs to an open standard and collaborate on the open source REVA reference implementation for CS3 APIs.
You can also find all client sources on [GitHub](https://github.com/owncloud/).
## Join the oCIS Community
The [server repository](https://github.com/owncloud/ocis) on [GitHub](https://www.github.com) is a good entry point to the oCIS project. In addition to that there are also ownCloud projects for clients for [iOS](https://github.com/owncloud/ios-app), [Android](https://github.com/owncloud/android), the major [Desktop](https://github.com/owncloud/desktop) platforms and [ownCloud Web](https://github.com/owncloud/web).
To chat about development, join our public chat on [matrix: ownCloud Infinite Scale](https://matrix.to/#/#ocis:matrix.org).
If you want to help and improve ownCloud or oCIS, start coding or open issues on GitHub in the related repository.
We are very happy to hear your feedback and ideas!
-2
View File
@@ -1,2 +0,0 @@
*
!bin/
-17
View File
@@ -1,17 +0,0 @@
{
"env": {
"browser": true,
"es6": true,
"amd": true
},
"extends": [
"standard",
"plugin:vue/essential"
],
"parserOptions": {
"sourceType": "module"
},
"rules": {
}
}
-202
View File
@@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-199
View File
@@ -1,199 +0,0 @@
SHELL := bash
NAME := accounts
IMPORT := github.com/owncloud/ocis/$(NAME)
BIN := bin
DIST := dist
HUGO := hugo
PROTO_VERSION := v0
PROTO_SRC := pkg/proto/$(PROTO_VERSION)
ifeq ($(OS), Windows_NT)
EXECUTABLE := $(NAME).exe
UNAME := Windows
else
EXECUTABLE := $(NAME)
UNAME := $(shell uname -s)
endif
ifeq ($(UNAME), Darwin)
GOBUILD ?= go build -i
else
GOBUILD ?= go build
endif
PACKAGES ?= $(shell go list ./...)
SOURCES ?= $(shell find . -name "*.go" -type f -not -path "./node_modules/*")
GENERATE ?= $(IMPORT)/pkg/assets
FEATURE_PATH ?= "ui/tests/acceptance/features"
TAGS ?=
ifndef OUTPUT
ifneq ($(DRONE_TAG),)
OUTPUT ?= $(subst v,,$(DRONE_TAG))
else
OUTPUT ?= testing
endif
endif
ifndef VERSION
ifneq ($(DRONE_TAG),)
VERSION ?= $(subst v,,$(DRONE_TAG))
else
VERSION ?= $(shell git rev-parse --short HEAD)
endif
endif
ifndef DATE
DATE := $(shell date -u '+%Y%m%d')
endif
LDFLAGS += -s -w -X "$(IMPORT)/pkg/version.String=$(VERSION)" -X "$(IMPORT)/pkg/version.Date=$(DATE)"
GCFLAGS += all=-N -l
.PHONY: all
all: build
.PHONY: sync
sync:
go mod download
.PHONY: clean
clean:
go clean -i ./...
rm -rf $(BIN) $(DIST) $(HUGO)
.PHONY: go-mod-tidy
go-mod-tidy:
@go mod tidy
.PHONY: fmt
fmt:
gofmt -s -w $(SOURCES)
.PHONY: vet
vet:
go vet $(PACKAGES)
.PHONY: staticcheck
staticcheck:
go run honnef.co/go/tools/cmd/staticcheck -tags '$(TAGS)' $(PACKAGES)
.PHONY: lint
lint:
for PKG in $(PACKAGES); do go run golang.org/x/lint/golint -set_exit_status $$PKG || exit 1; done;
.PHONY: generate
generate: protobuf
go generate $(GENERATE)
.PHONY: changelog
changelog:
go run github.com/restic/calens >| CHANGELOG.md
.PHONY: test
test:
go run github.com/haya14busa/goverage -v -coverprofile coverage.out $(PACKAGES)
.PHONY: go-coverage
go-coverage:
@if [ ! -f coverage.out ]; then $(MAKE) test &>/dev/null; fi;
@go tool cover -func coverage.out | tail -1 | grep -Eo "[0-9]+\.[0-9]+"
.PHONY: install
install: $(SOURCES)
go install -v -tags '$(TAGS)' -ldflags '$(LDFLAGS)' ./cmd/$(NAME)
.PHONY: build
build: $(BIN)/$(EXECUTABLE) $(BIN)/$(EXECUTABLE)-debug
$(BIN)/$(EXECUTABLE): $(SOURCES)
$(GOBUILD) -v -tags '$(TAGS)' -ldflags '$(LDFLAGS)' -o $@ ./cmd/$(NAME)
$(BIN)/$(EXECUTABLE)-debug: $(SOURCES)
$(GOBUILD) -v -tags '$(TAGS)' -ldflags '$(LDFLAGS)' -gcflags '$(GCFLAGS)' -o $@ ./cmd/$(NAME)
.PHONY: release
release: release-dirs release-linux release-windows release-darwin release-copy release-check
.PHONY: release-dirs
release-dirs:
mkdir -p $(DIST)/binaries $(DIST)/release
.PHONY: release-linux
release-linux: release-dirs
go run github.com/mitchellh/gox -tags 'netgo $(TAGS)' -ldflags '-extldflags "-static" $(LDFLAGS)' -os 'linux' -arch 'amd64 386 arm64 arm' -output '$(DIST)/binaries/$(EXECUTABLE)-$(OUTPUT)-{{.OS}}-{{.Arch}}' ./cmd/$(NAME)
.PHONY: release-windows
release-windows: release-dirs
go run github.com/mitchellh/gox -tags 'netgo $(TAGS)' -ldflags '-extldflags "-static" $(LDFLAGS)' -os 'windows' -arch 'amd64' -output '$(DIST)/binaries/$(EXECUTABLE)-$(OUTPUT)-{{.OS}}-{{.Arch}}' ./cmd/$(NAME)
.PHONY: release-darwin
release-darwin: release-dirs
go run github.com/mitchellh/gox -tags 'netgo $(TAGS)' -ldflags '$(LDFLAGS)' -os 'darwin' -arch 'amd64' -output '$(DIST)/binaries/$(EXECUTABLE)-$(OUTPUT)-{{.OS}}-{{.Arch}}' ./cmd/$(NAME)
.PHONY: release-copy
release-copy:
$(foreach file,$(wildcard $(DIST)/binaries/$(EXECUTABLE)-*),cp $(file) $(DIST)/release/$(notdir $(file));)
.PHONY: release-check
release-check:
cd $(DIST)/release; $(foreach file,$(wildcard $(DIST)/release/$(EXECUTABLE)-*),sha256sum $(notdir $(file)) > $(notdir $(file)).sha256;)
.PHONY: release-finish
release-finish: release-copy release-check
.PHONY: config-docs-generate
config-docs-generate:
go run github.com/owncloud/flaex >| ../docs/extensions/$(NAME)/configuration.md
.PHONY: test-acceptance-webui
test-acceptance-webui:
./ui/tests/run-acceptance-test.sh $(FEATURE_PATH)
.PHONY: watch
watch:
go run github.com/cespare/reflex -c reflex.conf
$(GOPATH)/bin/protoc-gen-go:
GO111MODULE=off go get -v google.golang.org/protobuf/cmd/protoc-gen-go
$(GOPATH)/bin/protoc-gen-micro:
GO111MODULE=on go get -v github.com/micro/protoc-gen-micro/v2
$(GOPATH)/bin/protoc-gen-microweb:
GO111MODULE=off go get -v github.com/owncloud/protoc-gen-microweb
$(GOPATH)/bin/protoc-gen-openapiv2:
GO111MODULE=off go get -v github.com/grpc-ecosystem/grpc-gateway/protoc-gen-openapiv2
$(PROTO_SRC)/accounts.pb.go: $(PROTO_SRC)/accounts.proto
protoc \
-I=third_party/ \
-I=$(PROTO_SRC)/ \
--go_out=. accounts.proto
$(PROTO_SRC)/accounts.pb.micro.go: $(PROTO_SRC)/accounts.proto
protoc \
-I=third_party/ \
-I=$(PROTO_SRC)/ \
--micro_out=. accounts.proto
$(PROTO_SRC)/accounts.pb.web.go: $(PROTO_SRC)/accounts.proto
protoc \
-I=third_party/ \
-I=$(PROTO_SRC)/ \
--microweb_out=. accounts.proto
$(PROTO_SRC)/accounts.swagger.json: $(PROTO_SRC)/accounts.proto
# the other commands above respect the declared package in the .proto file for placement of the resulting file.
# `swagger_out` doesn't, so we have to specify the output path as `$(PROTO_SRC)` instead of `.`
protoc \
-I=third_party/ \
-I=$(PROTO_SRC)/ \
--swagger_out=$(PROTO_SRC) accounts.proto
.PHONY: protobuf
protobuf: $(GOPATH)/bin/protoc-gen-go $(GOPATH)/bin/protoc-gen-micro $(GOPATH)/bin/protoc-gen-microweb $(GOPATH)/bin/protoc-gen-openapiv2 \
$(PROTO_SRC)/accounts.pb.go $(PROTO_SRC)/accounts.pb.micro.go $(PROTO_SRC)/accounts.pb.web.go $(PROTO_SRC)/accounts.swagger.json
-25
View File
@@ -1,25 +0,0 @@
module.exports = function (api) {
api.cache(true)
const presets = [
[
'@babel/preset-env',
{
useBuiltIns: 'usage',
corejs: '3'
}
]
]
const plugins = [
'@babel/plugin-syntax-dynamic-import',
'@babel/plugin-proposal-class-properties',
'@babel/plugin-proposal-object-rest-spread',
'@babel/plugin-transform-runtime',
'@babel/plugin-proposal-export-default-from'
]
return {
presets,
plugins
}
}
-13
View File
@@ -1,13 +0,0 @@
package main
import (
"os"
"github.com/owncloud/ocis/accounts/pkg/command"
)
func main() {
if err := command.Execute(); err != nil {
os.Exit(1)
}
}
-19
View File
@@ -1,19 +0,0 @@
FROM amd64/alpine:latest
RUN apk update && \
apk upgrade && \
apk add ca-certificates mailcap && \
rm -rf /var/cache/apk/* && \
echo 'hosts: files dns' >| /etc/nsswitch.conf
LABEL maintainer="ownCloud GmbH <devops@owncloud.com>" \
org.label-schema.name="oCIS Accounts" \
org.label-schema.vendor="ownCloud GmbH" \
org.label-schema.schema-version="1.0"
EXPOSE 9180
ENTRYPOINT ["/usr/bin/ocis-accounts"]
CMD ["server"]
COPY bin/ocis-accounts /usr/bin/ocis-accounts
-19
View File
@@ -1,19 +0,0 @@
FROM arm32v6/alpine:latest
RUN apk update && \
apk upgrade && \
apk add ca-certificates mailcap && \
rm -rf /var/cache/apk/* && \
echo 'hosts: files dns' >| /etc/nsswitch.conf
LABEL maintainer="ownCloud GmbH <devops@owncloud.com>" \
org.label-schema.name="oCIS Accounts" \
org.label-schema.vendor="ownCloud GmbH" \
org.label-schema.schema-version="1.0"
EXPOSE 9180
ENTRYPOINT ["/usr/bin/ocis-accounts"]
CMD ["server"]
COPY bin/ocis-accounts /usr/bin/ocis-accounts
-19
View File
@@ -1,19 +0,0 @@
FROM arm64v8/alpine:latest
RUN apk update && \
apk upgrade && \
apk add ca-certificates mailcap && \
rm -rf /var/cache/apk/* && \
echo 'hosts: files dns' >| /etc/nsswitch.conf
LABEL maintainer="ownCloud GmbH <devops@owncloud.com>" \
org.label-schema.name="oCIS Accounts" \
org.label-schema.vendor="ownCloud GmbH" \
org.label-schema.schema-version="1.0"
EXPOSE 9180
ENTRYPOINT ["/usr/bin/ocis-accounts"]
CMD ["server"]
COPY bin/ocis-accounts /usr/bin/ocis-accounts
-22
View File
@@ -1,22 +0,0 @@
image: owncloud/ocis-accounts:{{#if build.tag}}{{trimPrefix "v" build.tag}}{{else}}latest{{/if}}
{{#if build.tags}}
tags:
{{#each build.tags}}
- {{this}}
{{/each}}
{{/if}}
manifests:
- image: owncloud/ocis-accounts:{{#if build.tag}}{{trimPrefix "v" build.tag}}-{{/if}}linux-amd64
platform:
architecture: amd64
os: linux
- image: owncloud/ocis-accounts:{{#if build.tag}}{{trimPrefix "v" build.tag}}-{{/if}}linux-arm64
platform:
architecture: arm64
variant: v8
os: linux
- image: owncloud/ocis-accounts:{{#if build.tag}}{{trimPrefix "v" build.tag}}-{{/if}}linux-arm
platform:
architecture: arm
variant: v6
os: linux
-40
View File
@@ -1,40 +0,0 @@
module github.com/owncloud/ocis/accounts
go 1.15
require (
contrib.go.opencensus.io/exporter/jaeger v0.2.1
contrib.go.opencensus.io/exporter/ocagent v0.6.0
contrib.go.opencensus.io/exporter/zipkin v0.1.1
github.com/cs3org/go-cs3apis v0.0.0-20201118090759-87929f5bae21
github.com/cs3org/reva v1.5.1
github.com/go-chi/chi v4.1.2+incompatible
github.com/go-chi/render v1.0.1
github.com/gofrs/uuid v3.3.0+incompatible
github.com/golang/protobuf v1.4.3
github.com/mennanov/fieldmask-utils v0.3.3
github.com/micro/cli/v2 v2.1.2
github.com/micro/go-micro/v2 v2.9.1
github.com/oklog/run v1.1.0
github.com/olekukonko/tablewriter v0.0.4
github.com/openzipkin/zipkin-go v0.2.2
github.com/owncloud/ocis/ocis-pkg v0.0.0-20201103111659-46bf133a3c63
github.com/owncloud/ocis/settings v0.0.0-20200918114005-1a0ddd2190ee
github.com/prometheus/client_golang v1.7.1
github.com/restic/calens v0.2.0
github.com/rs/zerolog v1.20.0
github.com/spf13/viper v1.7.0
github.com/stretchr/testify v1.6.1
go.opencensus.io v0.22.5
golang.org/x/crypto v0.0.0-20200709230013-948cd5f35899
golang.org/x/net v0.0.0-20200822124328-c89045814202
google.golang.org/genproto v0.0.0-20200624020401-64a14ca9d1ad
google.golang.org/grpc v1.33.2
google.golang.org/protobuf v1.25.0
)
replace (
github.com/owncloud/ocis/ocis-pkg => ../ocis-pkg
github.com/owncloud/ocis/settings => ../settings
google.golang.org/grpc => google.golang.org/grpc v1.26.0
)
-1209
View File
File diff suppressed because it is too large. Load diff
-11
View File
@@ -1,11 +0,0 @@
const path = require('path')
const WEB_PATH = process.env.WEB_PATH
const config = require(path.join(WEB_PATH, 'nightwatch.conf.js'))
config.page_objects_path = [WEB_PATH + '/tests/acceptance/pageObjects', 'ui/tests/acceptance/pageobjects']
config.custom_commands_path = WEB_PATH + '/tests/acceptance/customCommands'
module.exports = {
...config
}
-84
View File
@@ -1,84 +0,0 @@
{
"private": true,
"name": "ocis-accounts",
"version": "0.0.0",
"description": "",
"homepage": "https://github.com/owncloud/ocis-accounts#readme",
"license": "Apache-2.0",
"author": "ownCloud GmbH <devops@owncloud.com>",
"repository": "https://github.com/owncloud/ocis-accounts.git",
"bugs": {
"url": "https://github.com/owncloud/ocis/accounts/issues",
"email": "support@owncloud.com"
},
"scripts": {
"lint": "eslint ui/**/*.vue ui/**/*.js --color --global requirejs --global require",
"build": "rollup -c",
"watch": "rollup -c -w",
"test": "echo 'Not implemented'",
"generate-api": "node node_modules/swagger-vue-generator/bin/generate-api.js --package-version v0 --source pkg/proto/v0/accounts.swagger.json --moduleName accounts --destination ui/client/accounts/index.js",
"acceptance-tests": "cucumber-js --retry 1 --require-module @babel/register --require-module @babel/polyfill --require ${TEST_INFRA_DIRECTORY}/acceptance/setup.js --require ui/tests/acceptance/stepDefinitions --require ${TEST_INFRA_DIRECTORY}/acceptance/stepDefinitions --format node_modules/cucumber-pretty -t \"${TEST_TAGS:-not @skip and not @skipOnOC10}\""
},
"devDependencies": {
"@babel/core": "^7.7.7",
"@babel/plugin-proposal-class-properties": "^7.7.4",
"@babel/plugin-proposal-export-default-from": "^7.7.4",
"@babel/plugin-proposal-object-rest-spread": "^7.7.7",
"@babel/plugin-syntax-dynamic-import": "^7.7.4",
"@babel/plugin-transform-runtime": "^7.8.0",
"@babel/polyfill": "^7.10.1",
"@babel/preset-env": "^7.7.7",
"@babel/register": "7.10.1",
"@erquhart/rollup-plugin-node-builtins": "^2.1.5",
"@rollup/plugin-commonjs": "^11.0.1",
"@rollup/plugin-json": "^4.0.1",
"@rollup/plugin-replace": "^2.3.0",
"archiver": "^4.0.1",
"axios": "^0.21.1",
"core-js": "3",
"cross-env": "^6.0.3",
"cucumber": "^6.0.5",
"cucumber-pretty": ">=6.0.0",
"debounce": "^1.2.0",
"easygettext": "^2.7.0",
"eslint": "6.8.0",
"eslint-config-standard": "^14.1.0",
"eslint-plugin-import": "^2.17.3",
"eslint-plugin-node": "11.0.0",
"eslint-plugin-promise": "^4.1.1",
"eslint-plugin-standard": "^4.0.0",
"eslint-plugin-vue": "^6.1.2",
"fs-extra": "^9.0.1",
"join-path": "^1.1.1",
"ldap": "^0.7.1",
"nightwatch": "^1.3.6",
"nightwatch-api": "^3.0.1",
"node-fetch": "^2.6.1",
"nightwatch-vrt": "^0.2.10",
"qs": "^6.9.1",
"rimraf": "^3.0.0",
"rollup": "^1.28.0",
"rollup-plugin-babel": "^4.3.3",
"rollup-plugin-eslint": "^7.0.0",
"rollup-plugin-filesize": "^6.2.1",
"rollup-plugin-node-globals": "^1.4.0",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-terser": "^5.1.3",
"rollup-plugin-vue": "^5.1.4",
"swagger-vue-generator": "^1.0.6",
"url-search-params-polyfill": "^8.1.0",
"vue-template-compiler": "^2.6.11",
"vuex": "^3.5.1",
"xml-js": "^1.6.11"
},
"browserslist": [
"> 1%",
"not dead"
],
"peerDependencies": {
"owncloud-design-system": "^1.7.0"
},
"dependencies": {
"validator": "^13.1.1"
}
}
-66
View File
@@ -1,66 +0,0 @@
package assets
import (
"net/http"
"os"
"path"
"github.com/owncloud/ocis/accounts/pkg/config"
"github.com/owncloud/ocis/ocis-pkg/log"
// Fake the import to make the dep tree happy.
_ "golang.org/x/net/context"
// Fake the import to make the dep tree happy.
_ "golang.org/x/net/webdav"
)
//go:generate go run github.com/UnnoTed/fileb0x embed.yml
// assets gets initialized by New and provides the handler.
type assets struct {
logger log.Logger
config *config.Config
}
// Open just implements the HTTP filesystem interface.
func (a assets) Open(original string) (http.File, error) {
if a.config.Asset.Path != "" {
if stat, err := os.Stat(a.config.Asset.Path); err == nil && stat.IsDir() {
custom := path.Join(
a.config.Asset.Path,
original,
)
if _, err := os.Stat(custom); !os.IsNotExist(err) {
f, err := os.Open(custom)
if err != nil {
return nil, err
}
return f, nil
}
} else {
a.logger.Warn().
Str("path", a.config.Asset.Path).
Msg("Assets directory doesn't exist")
}
}
return FS.OpenFile(
CTX,
original,
os.O_RDONLY,
0644,
)
}
// New returns a new http filesystem to serve assets.
func New(opts ...Option) http.FileSystem {
options := newOptions(opts...)
return assets{
config: options.Config,
}
}
-173
View File
@@ -1,173 +0,0 @@
// Code generated by fileb0x at "2021-01-13 08:23:16.044077 +0100 CET m=+0.009014926" from config file "embed.yml" DO NOT EDIT.
// modification hash(c8fdaaee3828640ec93899c4406b029b.8058aec596c5fb73022d09bb97af796e)
package assets
import (
"bytes"
"compress/gzip"
"context"
"io"
"net/http"
"os"
"path"
"golang.org/x/net/webdav"
)
var (
// CTX is a context for webdav vfs
CTX = context.Background()
// FS is a virtual memory file system
FS = webdav.NewMemFS()
// Handler is used to server files through a http handler
Handler *webdav.Handler
// HTTP is the http file system
HTTP http.FileSystem = new(HTTPFS)
)
// HTTPFS implements http.FileSystem
type HTTPFS struct {
// Prefix allows to limit the path of all requests. F.e. a prefix "css" would allow only calls to /css/*
Prefix string
}
// FileAccountsJs is "accounts.js"
var FileAccountsJs = []byte("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\xec\xbd\xeb\x72\xdb\x38\xb7\x28\xf8\x7b\xf6\x53\x48\xdc\xfd\x71\x03\xad\x65\x45\x4a\xfa\x4a\x05\xad\xcf\x49\x9c\x74\xba\x93\x38\x6d\x3b\xe9\x8b\x5a\xdb\x45\x53\x90\x8d\x58\x02\x14\x10\xf2\x25\x12\xe7\x7d\xe6\x35\xe6\xc9\xa6\x70\x23\x41\x8a\x4a\xf7\xb7\xcf\x3e\xa7\xce\xd4\x4c\x95\xcb\x22\x41\x5c\x17\x80\x75\xc3\x5a\x0b\x33\x3a\x67\x9c\x22\x34\x5f\xf3\x4c\x31\xc1\x11\xde\x44\xeb\x9c\x76\x72\x25\x59\xa6\xa2\xd1\x4d\x2a\x3b\x8a\x44\x6b\x6e\x33\xce\xa2\x2e\x51\xf7\x2b\x2a\xe6\x9d\xcb\x85\xb8\x48\x17\x67\x57\x2c\x1f\x57\x8f\x49\x5b\xce\x5b\xc6\x67\xe2\x76\x6c\x7f\x5a\x73\xd8\x0a\x5c\x3d\xad\x39\x72\xba\x98\x8f\xf5\xbf\x64\x53\x8c\x7c\x67\x3b\x14\x29\xa0\x78\x23\xa9\x5a\x4b\xde\x51\x88\x92\x0d\xbd\x5b\x09\xa9\xf2\x64\x53\x14\x40\xfb\xee\x0d\x57\x8f\x85\x1e\x11\x27\xe1\x90\x15\xde\xe8\x44\x4a\x76\x53\x8e\x2f\x3e\xd0\x4c\xf5\x57\x52\x28\xa1\x7b\x02\x9c\xd0\xfe\x55\x9a\x1f\xdf\xf2\xb7\x52\xac\xa8\x54\xf7\x20\x49\xe4\x0b\x46\xc4\xf7\xf7\xf4\x7e\x79\x21\x16\x63\xfb\x93\x6c\x0a\x10\x44\xf6\x99\xa2\x32\x55\x42\x6e\xb7\xd1\x3f\xff\xe9\x5f\x22\x60\x44\xf6\xd3\xfc\x9e\x67\x2f\xc3\xef\xb5\x94\x08\x52\x22\xfb\x4a\x9c\x2a\xc9\xf8\xe5\x59\x7a\x69\xb2\x04\xef\x51\x05\x94\x4c\x03\x05\x78\x09\x16\x37\x06\x0b\x52\xdf\x6b\x93\x67\x73\x93\x2e\xd6\x34\xe1\x40\xf9\x7a\x49\x65\x7a\xb1\xa0\x49\x77\x00\x99\xe0\x73\x76\xb9\x2e\xdf\x6f\x25\x53\xee\xb9\xc0\xa0\x26\x74\x5a\x28\x79\xbf\xc9\xd0\xa6\x80\x28\xc2\x45\x96\xaa\xec\x4a\xc3\x2c\x0b\x20\x58\xeb\x82\x2e\x43\x78\x51\x94\x7d\xcc\x6d\x06\x90\x16\xd0\x82\xd0\x38\xa6\x15\x98\x3b\x8c\xe7\x2a\xe5\x99\x86\xe4\x7c\x4c\x93\x39\x30\x3f\x15\x99\xa4\xa9\xa2\x48\x54\x99\x31\xa4\x84\xd3\xdb\xce\x11\x92\xdb\xed\x64\x8a\x47\xae\x51\xd6\x3f\x67\xfc\x46\x5c\xd3\x9d\x5e\xe9\x26\x25\x89\xf2\x75\xbe\xa2\x7c\x46\x67\xa7\x2a\x95\x2a\xf2\xe5\xca\xdc\x02\x18\xde\xb0\x39\x8a\xe8\x1d\xcd\xd6\x8a\xf1\xcb\x88\x10\x22\xb1\xba\x92\xe2\xb6\x63\x9a\x94\x52\x48\x14\xbd\xa0\xdc\x4e\x53\x87\xe5\x9d\x74\x21\x69\x3a\xbb\xef\xc8\x35\xe7\xba\x08\x1e\xe9\x2a\x32\xb1\x5c\x2d\xa8\xa2\x33\x5b\x85\xa9\xd6\xd4\xa3\xdf\x85\xab\x92\xf9\x2e\x9c\x22\x5c\xcc\x85\x44\xbc\xbf\xa4\xea\x4a\xcc\x88\x00\xde\x4f\xe5\x25\x61\xa3\x91\xed\x7e\x4a\x78\x7f\x46\x17\xf4\x32\x55\x54\x37\x90\xda\xe4\x8c\xdc\xa2\x14\xb8\x69\x33\x33\xad\x64\x84\x90\x05\xce\x04\x57\x8c\xaf\xa9\x6f\x20\x2b\x0a\xdd\x03\x4e\xef\x94\xee\x80\x6f\x07\xf3\x7e\x4e\xb9\x22\xbc\x7f\xee\x7e\x53\x79\x39\xa2\x8b\x9c\x76\x6a\x1d\x2e\xf3\x9b\x71\x34\xe0\x18\xc0\x48\x92\x60\xe0\x76\x08\x23\xde\x9f\xb1\x7c\xa5\x97\xcc\xd1\x5d\x46\x57\x06\xd2\xe6\x0b\x2e\x74\x43\x91\xed\x61\xd8\x4a\x1c\xf3\x7e\x7a\x21\xd7\x2b\x85\xfc\x57\x5b\x17\x1e\x49\x12\x4c\x8e\x41\x56\x39\x59\xbb\x69\x36\x70\xe7\x42\x2e\xd3\x85\xae\x2d\xef\x9b\xc5\xa2\x7b\x2c\x35\xf0\x04\xa7\xe3\xa0\x77\x49\x35\x8c\xdf\x19\x5d\xcc\x22\xc8\x0d\xc4\x5b\xa0\xe7\xb6\x8d\xf9\x0e\xba\x9e\xc4\x56\x57\x14\x15\x84\x6c\x6b\x71\x8c\x9a\x20\x70\x13\xea\x72\xba\x69\xcd\xed\xf8\x8b\x02\x29\xe0\x90\x62\x60\xd5\x56\xf1\xc3\xd9\xe8\x3d\xe7\x3a\xa0\xeb\x4e\xfc\xd8\x20\x95\x97\x89\xea\x67\xe9\x62\x81\x74\xc6\xa2\xda\x90\xb5\xec\xae\x45\x93\xbb\x28\x0a\xd5\xbf\x95\xe9\x8a\xe4\x06\x6a\x0b\x12\xa2\xd5\x39\xc2\x9b\xaa\x03\xb3\xda\xdb\x4a\xbf\xe9\x22\x57\xba\xc8\xd5\x44\x4c\x49\x40\x3b\xfc\x7e\xbf\x62\x79\x61\x2a\x5e\xfa\x7d\x7b\x49\xd5\x5b\xbf\x63\x8f\xe7\x70\x43\x96\x71\xbc\x44\x4b\x74\x8c\x26\x53\x8c\xf1\xe8\x26\x8e\x6f\xba\x44\xe3\x01\x6e\x87\x72\x03\x02\xc7\x31\xba\x22\x37\xd8\xd4\x74\x49\x56\xd5\x9e\x27\xf3\xe0\xb9\x8e\x19\xae\x70\x35\x90\x7b\x0d\x84\x89\x5d\xe6\xe0\x01\xe0\xd7\xd0\xb4\x3f\x17\xf2\x28\xcd\xae\x02\x52\x40\xf1\xc6\xa2\xcf\x1a\x75\x08\x46\xe5\x71\x0a\xa2\xa0\x70\x81\xcd\x5f\xd9\xdc\x85\x25\x47\x06\xbd\x8c\xc2\xdc\xa4\x8e\x53\xca\x02\x69\x05\x32\x8d\x4e\x42\xa2\x24\x21\xc5\x9b\x6e\x99\x53\xea\x92\x90\x42\x66\xab\x37\xab\x7c\x22\xa6\xa0\x80\xd9\x85\x6e\x07\xd7\xad\xd6\xb9\x9d\x56\xbb\x48\xe7\x64\xd1\x37\x8b\xb6\xc4\x71\x71\x1c\x09\x03\xb6\x8a\x64\xcd\x4b\xd0\xcf\x21\x3a\x3f\x4f\x6f\x53\xa6\x22\x3c\xa6\x7d\x49\x73\xb1\xb8\xa1\x68\xde\x77\xa9\xb8\xaf\xae\x28\xaf\x53\x50\xe9\xb0\x09\x28\xd3\xcb\x02\x43\xf3\xb3\x03\xbf\xff\x8e\x93\xa0\xe6\xb6\x1a\x5d\x97\x89\x82\x14\x2d\x76\x2b\xb4\x03\x69\xa9\xb7\xc8\x90\xdb\x4f\x06\x66\x1a\x90\x3a\xd5\x17\x20\x72\x2c\x6d\x6b\x29\xa4\x38\x49\x11\x0e\xe8\xd2\x6d\x35\x83\x9c\xa8\x92\x60\x4f\xa8\xdb\xb7\x53\x0d\xeb\x1b\xc1\x66\x9d\x81\x46\x50\x06\x9b\xd0\x12\x11\x13\xbe\x5e\x2c\xa0\x42\x02\x34\x44\x93\x55\x6d\x7d\xdb\x95\x38\x46\xb4\x44\x07\x1e\xaf\x51\x83\x0f\x6c\x0b\x60\x7b\xd3\x56\x21\x76\xa3\x59\x8c\x68\x13\xa3\xd8\x1a\xf4\x72\x3a\xbb\x5f\x51\x47\xa1\xce\xae\x68\xc7\x37\xdf\x99\x09\x9a\x77\xb8\x50\x9d\x95\x14\x37\x6c\x46\x3b\x69\xe7\x3f\x4c\xe1\xff\xe8\xd8\xba\xa2\x12\x5a\x8b\xc2\xd2\xca\x35\xe2\x50\x0d\xc0\xb6\x11\xae\x3b\x8d\xf3\xed\xba\x73\x05\xf7\x74\x4b\x9a\xe5\xd8\x84\xd8\x62\x64\x99\x00\xf3\xd5\x2f\x51\x31\x16\x16\x49\x23\x3a\x51\x7a\xa5\xac\x17\xea\x4d\xba\xa4\x53\x22\xec\xc2\x00\xda\xd7\x2b\x8e\x28\xf3\xf3\x4a\x64\xe5\xce\xee\x56\xLine truncated
func init() {
err := CTX.Err()
if err != nil {
panic(err)
}
var f webdav.File
var rb *bytes.Reader
var r *gzip.Reader
rb = bytes.NewReader(FileAccountsJs)
r, err = gzip.NewReader(rb)
if err != nil {
panic(err)
}
err = r.Close()
if err != nil {
panic(err)
}
f, err = FS.OpenFile(CTX, "accounts.js", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)
if err != nil {
panic(err)
}
_, err = io.Copy(f, r)
if err != nil {
panic(err)
}
err = f.Close()
if err != nil {
panic(err)
}
Handler = &webdav.Handler{
FileSystem: FS,
LockSystem: webdav.NewMemLS(),
}
}
// Open a file
func (hfs *HTTPFS) Open(path string) (http.File, error) {
path = hfs.Prefix + path
f, err := FS.OpenFile(CTX, path, os.O_RDONLY, 0644)
if err != nil {
return nil, err
}
return f, nil
}
// ReadFile is adapTed from ioutil
func ReadFile(path string) ([]byte, error) {
f, err := FS.OpenFile(CTX, path, os.O_RDONLY, 0644)
if err != nil {
return nil, err
}
buf := bytes.NewBuffer(make([]byte, 0, bytes.MinRead))
// If the buffer overflows, we will get bytes.ErrTooLarge.
// Return that as an error. Any other panic remains.
defer func() {
e := recover()
if e == nil {
return
}
if panicErr, ok := e.(error); ok && panicErr == bytes.ErrTooLarge {
err = panicErr
} else {
panic(e)
}
}()
_, err = buf.ReadFrom(f)
return buf.Bytes(), err
}
// WriteFile is adapTed from ioutil
func WriteFile(filename string, data []byte, perm os.FileMode) error {
f, err := FS.OpenFile(CTX, filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
if err != nil {
return err
}
n, err := f.Write(data)
if err == nil && n < len(data) {
err = io.ErrShortWrite
}
if err1 := f.Close(); err == nil {
err = err1
}
return err
}
// WalkDirs looks for files in the given dir and returns a list of files in it
// usage for all files in the b0x: WalkDirs("", false)
func WalkDirs(name string, includeDirsInList bool, files ...string) ([]string, error) {
f, err := FS.OpenFile(CTX, name, os.O_RDONLY, 0)
if err != nil {
return nil, err
}
fileInfos, err := f.Readdir(0)
if err != nil {
return nil, err
}
err = f.Close()
if err != nil {
return nil, err
}
for _, info := range fileInfos {
filename := path.Join(name, info.Name())
if includeDirsInList || !info.IsDir() {
files = append(files, filename)
}
if info.IsDir() {
files, err = WalkDirs(filename, includeDirsInList, files...)
if err != nil {
return nil, err
}
}
}
return files, nil
}
-17
View File
@@ -1,17 +0,0 @@
---
pkg: "assets"
dest: "."
output: "embed.go"
fmt: true
noprefix: true
compression:
compress: true
custom:
- files:
- "../../assets/"
base: "../../assets/"
prefix: ""
...
-40
View File
@@ -1,40 +0,0 @@
package assets
import (
"github.com/owncloud/ocis/accounts/pkg/config"
"github.com/owncloud/ocis/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
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
}
}
-57
View File
@@ -1,57 +0,0 @@
package command
import (
"fmt"
"github.com/micro/cli/v2"
"github.com/micro/go-micro/v2/client/grpc"
"github.com/owncloud/ocis/accounts/pkg/config"
"github.com/owncloud/ocis/accounts/pkg/flagset"
accounts "github.com/owncloud/ocis/accounts/pkg/proto/v0"
)
// AddAccount command creates a new account
func AddAccount(cfg *config.Config) *cli.Command {
a := &accounts.Account{
PasswordProfile: &accounts.PasswordProfile{},
}
return &cli.Command{
Name: "add",
Usage: "Create a new account",
Aliases: []string{"create", "a"},
Flags: flagset.AddAccountWithConfig(cfg, a),
Before: func(c *cli.Context) error {
// Write value of username to the flags beneath, as preferred name
// and on-premises-sam-account-name is probably confusing for users.
if username := c.String("username"); username != "" {
if !c.IsSet("on-premises-sam-account-name") {
if err := c.Set("on-premises-sam-account-name", username); err != nil {
return err
}
}
if !c.IsSet("preferred-name") {
if err := c.Set("preferred-name", username); err != nil {
return err
}
}
}
return nil
},
Action: func(c *cli.Context) error {
accSvcID := cfg.GRPC.Namespace + "." + cfg.Server.Name
accSvc := accounts.NewAccountsService(accSvcID, grpc.NewClient())
_, err := accSvc.CreateAccount(c.Context, &accounts.CreateAccountRequest{
Account: a,
})
if err != nil {
fmt.Println(fmt.Errorf("could not create account %w", err))
return err
}
return nil
}}
}
-76
View File
@@ -1,76 +0,0 @@
package command
import (
"fmt"
"github.com/micro/cli/v2"
"github.com/micro/go-micro/v2/client/grpc"
tw "github.com/olekukonko/tablewriter"
"github.com/owncloud/ocis/accounts/pkg/config"
"github.com/owncloud/ocis/accounts/pkg/flagset"
accounts "github.com/owncloud/ocis/accounts/pkg/proto/v0"
"os"
"strconv"
)
// InspectAccount command shows detailed information about a specific account.
func InspectAccount(cfg *config.Config) *cli.Command {
return &cli.Command{
Name: "inspect",
Usage: "Show detailed data on an existing account",
ArgsUsage: "id",
Flags: flagset.InspectAccountWithConfig(cfg),
Action: func(c *cli.Context) error {
accServiceID := cfg.GRPC.Namespace + "." + cfg.Server.Name
if c.NArg() != 1 {
fmt.Println("Please provide a user-id")
os.Exit(1)
}
uid := c.Args().First()
accSvc := accounts.NewAccountsService(accServiceID, grpc.NewClient())
acc, err := accSvc.GetAccount(c.Context, &accounts.GetAccountRequest{
Id: uid,
})
if err != nil {
fmt.Println(fmt.Errorf("could not view account %w", err))
return err
}
buildAccountInspectTable(acc).Render()
return nil
}}
}
func buildAccountInspectTable(acc *accounts.Account) *tw.Table {
table := tw.NewWriter(os.Stdout)
table.SetAutoMergeCells(true)
table.AppendBulk([][]string{
{"ID", acc.Id},
{"Mail", acc.Mail},
{"DisplayName", acc.DisplayName},
{"PreferredName", acc.PreferredName},
{"AccountEnabled", strconv.FormatBool(acc.AccountEnabled)},
{"CreationType", acc.CreationType},
{"CreatedDateTime", acc.CreatedDateTime.String()},
{"Description", acc.Description},
{"ExternalUserState", acc.ExternalUserState},
{"UidNumber", fmt.Sprintf("%+d", acc.UidNumber)},
{"GidNumber", fmt.Sprintf("%+d", acc.GidNumber)},
{"IsResourceAccount", strconv.FormatBool(acc.IsResourceAccount)},
{"OnPremisesDistinguishedName", acc.OnPremisesDistinguishedName},
{"OnPremisesDomainName", acc.OnPremisesDomainName},
{"OnPremisesImmutableId", acc.OnPremisesImmutableId},
{"OnPremisesSamAccountName", acc.OnPremisesSamAccountName},
{"OnPremisesSecurityIdentifier", acc.OnPremisesSecurityIdentifier},
{"OnPremisesUserPrincipalName", acc.OnPremisesUserPrincipalName},
{"RefreshTokenValidFromDateTime", acc.RefreshTokensValidFromDateTime.String()},
})
// Merged cell with group memberships
for k := range acc.MemberOf {
table.Append([]string{"MemberOf", acc.MemberOf[k].DisplayName})
}
return table
}
-50
View File
@@ -1,50 +0,0 @@
package command
import (
"fmt"
"github.com/micro/cli/v2"
"github.com/micro/go-micro/v2/client/grpc"
tw "github.com/olekukonko/tablewriter"
"github.com/owncloud/ocis/accounts/pkg/config"
"github.com/owncloud/ocis/accounts/pkg/flagset"
accounts "github.com/owncloud/ocis/accounts/pkg/proto/v0"
"os"
"strconv"
)
// ListAccounts command lists all accounts
func ListAccounts(cfg *config.Config) *cli.Command {
return &cli.Command{
Name: "list",
Usage: "List existing accounts",
Aliases: []string{"ls"},
Flags: flagset.ListAccountsWithConfig(cfg),
Action: func(c *cli.Context) error {
accSvcID := cfg.GRPC.Namespace + "." + cfg.Server.Name
accSvc := accounts.NewAccountsService(accSvcID, grpc.NewClient())
resp, err := accSvc.ListAccounts(c.Context, &accounts.ListAccountsRequest{})
if err != nil {
fmt.Println(fmt.Errorf("could not list accounts %w", err))
return err
}
buildAccountsListTable(resp.Accounts).Render()
return nil
}}
}
// buildAccountsListTable creates an ascii table for printing on the cli
func buildAccountsListTable(accs []*accounts.Account) *tw.Table {
table := tw.NewWriter(os.Stdout)
table.SetHeader([]string{"Id", "DisplayName", "Mail", "AccountEnabled"})
table.SetAutoFormatHeaders(false)
for _, acc := range accs {
table.Append([]string{
acc.Id,
acc.DisplayName,
acc.Mail,
strconv.FormatBool(acc.AccountEnabled)})
}
return table
}
-34
View File
@@ -1,34 +0,0 @@
package command
import (
"context"
"fmt"
"github.com/micro/cli/v2"
"github.com/micro/go-micro/v2/client/grpc"
merrors "github.com/micro/go-micro/v2/errors"
"github.com/owncloud/ocis/accounts/pkg/config"
index "github.com/owncloud/ocis/accounts/pkg/proto/v0"
)
// RebuildIndex rebuilds the entire configured index.
func RebuildIndex(cdf *config.Config) *cli.Command {
return &cli.Command{
Name: "rebuildIndex",
Usage: "Rebuilds the service's index, i.e. deleting and then re-adding all existing documents",
Aliases: []string{"rebuild", "ri"},
Action: func(ctx *cli.Context) error {
idxSvcID := "com.owncloud.api.accounts"
idxSvc := index.NewIndexService(idxSvcID, grpc.NewClient())
_, err := idxSvc.RebuildIndex(context.Background(), &index.RebuildIndexRequest{})
if err != nil {
fmt.Println(merrors.FromError(err).Detail)
return err
}
fmt.Println("index rebuilt successfully")
return nil
},
}
}
-39
View File
@@ -1,39 +0,0 @@
package command
import (
"fmt"
"github.com/micro/cli/v2"
"github.com/micro/go-micro/v2/client/grpc"
"github.com/owncloud/ocis/accounts/pkg/config"
"github.com/owncloud/ocis/accounts/pkg/flagset"
accounts "github.com/owncloud/ocis/accounts/pkg/proto/v0"
"os"
)
// RemoveAccount command deletes an existing account.
func RemoveAccount(cfg *config.Config) *cli.Command {
return &cli.Command{
Name: "remove",
Usage: "Removes an existing account",
ArgsUsage: "id",
Aliases: []string{"rm"},
Flags: flagset.RemoveAccountWithConfig(cfg),
Action: func(c *cli.Context) error {
accServiceID := cfg.GRPC.Namespace + "." + cfg.Server.Name
if c.NArg() != 1 {
fmt.Println("Please provide a user-id")
os.Exit(1)
}
uid := c.Args().First()
accSvc := accounts.NewAccountsService(accServiceID, grpc.NewClient())
_, err := accSvc.DeleteAccount(c.Context, &accounts.DeleteAccountRequest{Id: uid})
if err != nil {
fmt.Println(fmt.Errorf("could not delete account %w", err))
return err
}
return nil
}}
}
-120
View File
@@ -1,120 +0,0 @@
package command
import (
"os"
"strings"
"github.com/owncloud/ocis/accounts/pkg/flagset"
"github.com/micro/cli/v2"
"github.com/owncloud/ocis/accounts/pkg/config"
"github.com/owncloud/ocis/accounts/pkg/version"
"github.com/owncloud/ocis/ocis-pkg/log"
"github.com/spf13/viper"
)
var (
defaultConfigPaths = []string{"/etc/ocis", "$HOME/.ocis", "./config"}
defaultFilename = "accounts"
)
// Execute is the entry point for the ocis-accounts command.
func Execute() error {
cfg := config.New()
app := &cli.App{
Name: "ocis-accounts",
Version: version.String,
Usage: "Provide accounts and groups for oCIS",
Compiled: version.Compiled(),
Authors: []*cli.Author{
{
Name: "ownCloud GmbH",
Email: "support@owncloud.com",
},
},
Flags: flagset.RootWithConfig(cfg),
Before: func(c *cli.Context) error {
cfg.Server.Version = version.String
return ParseConfig(c, cfg)
},
Commands: []*cli.Command{
Server(cfg),
AddAccount(cfg),
UpdateAccount(cfg),
ListAccounts(cfg),
InspectAccount(cfg),
RemoveAccount(cfg),
PrintVersion(cfg),
RebuildIndex(cfg),
},
}
cli.HelpFlag = &cli.BoolFlag{
Name: "help,h",
Usage: "Show the help",
}
cli.VersionFlag = &cli.BoolFlag{
Name: "version,v",
Usage: "Print the version",
}
return app.Run(os.Args)
}
// NewLogger initializes a service-specific logger instance.
func NewLogger(cfg *config.Config) log.Logger {
return log.NewLogger(
log.Name("accounts"),
log.Level(cfg.Log.Level),
log.Pretty(cfg.Log.Pretty),
log.Color(cfg.Log.Color),
)
}
// ParseConfig loads accounts configuration from Viper known paths.
func ParseConfig(c *cli.Context, cfg *config.Config) error {
logger := NewLogger(cfg)
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.SetEnvPrefix("ACCOUNTS")
viper.AutomaticEnv()
if c.IsSet("config-file") {
viper.SetConfigFile(c.String("config-file"))
} else {
viper.SetConfigName(defaultFilename)
for _, v := range defaultConfigPaths {
viper.AddConfigPath(v)
}
}
if err := viper.ReadInConfig(); err != nil {
switch err.(type) {
case viper.ConfigFileNotFoundError:
logger.Debug().
Msg("no config found on preconfigured location")
case viper.UnsupportedConfigError:
logger.Fatal().
Err(err).
Msg("Unsupported config type")
default:
logger.Fatal().
Err(err).
Msg("Failed to read config")
}
}
if err := viper.Unmarshal(&cfg); err != nil {
logger.Fatal().
Err(err).
Msg("Failed to parse config")
}
return nil
}
-194
View File
@@ -1,194 +0,0 @@
package command
import (
"context"
"os"
"os/signal"
"strings"
"time"
"contrib.go.opencensus.io/exporter/jaeger"
"contrib.go.opencensus.io/exporter/ocagent"
"contrib.go.opencensus.io/exporter/zipkin"
"github.com/micro/cli/v2"
"github.com/oklog/run"
openzipkin "github.com/openzipkin/zipkin-go"
zipkinhttp "github.com/openzipkin/zipkin-go/reporter/http"
"github.com/owncloud/ocis/accounts/pkg/config"
"github.com/owncloud/ocis/accounts/pkg/flagset"
"github.com/owncloud/ocis/accounts/pkg/metrics"
"github.com/owncloud/ocis/accounts/pkg/server/grpc"
"github.com/owncloud/ocis/accounts/pkg/server/http"
svc "github.com/owncloud/ocis/accounts/pkg/service/v0"
"go.opencensus.io/stats/view"
"go.opencensus.io/trace"
)
// Server is the entry point for the server command.
func Server(cfg *config.Config) *cli.Command {
return &cli.Command{
Name: "server",
Usage: "Start ocis accounts service",
Description: "uses an LDAP server as the storage backend",
Flags: flagset.ServerWithConfig(cfg),
Before: func(ctx *cli.Context) error {
if cfg.HTTP.Root != "/" {
cfg.HTTP.Root = strings.TrimSuffix(cfg.HTTP.Root, "/")
}
// When running on single binary mode the before hook from the root command won't get called. We manually
// call this before hook from ocis command, so the configuration can be loaded.
return ParseConfig(ctx, cfg)
},
Action: func(c *cli.Context) error {
logger := NewLogger(cfg)
if cfg.Tracing.Enabled {
switch t := cfg.Tracing.Type; t {
case "agent":
exporter, err := ocagent.NewExporter(
ocagent.WithReconnectionPeriod(5*time.Second),
ocagent.WithAddress(cfg.Tracing.Endpoint),
ocagent.WithServiceName(cfg.Tracing.Service),
)
if err != nil {
logger.Error().
Err(err).
Str("endpoint", cfg.Tracing.Endpoint).
Str("collector", cfg.Tracing.Collector).
Msg("Failed to create agent tracing")
return err
}
trace.RegisterExporter(exporter)
view.RegisterExporter(exporter)
case "jaeger":
exporter, err := jaeger.NewExporter(
jaeger.Options{
AgentEndpoint: cfg.Tracing.Endpoint,
CollectorEndpoint: cfg.Tracing.Collector,
Process: jaeger.Process{
ServiceName: cfg.Tracing.Service,
},
},
)
if err != nil {
logger.Error().
Err(err).
Str("endpoint", cfg.Tracing.Endpoint).
Str("collector", cfg.Tracing.Collector).
Msg("Failed to create jaeger tracing")
return err
}
trace.RegisterExporter(exporter)
case "zipkin":
endpoint, err := openzipkin.NewEndpoint(
cfg.Tracing.Service,
cfg.Tracing.Endpoint,
)
if err != nil {
logger.Error().
Err(err).
Str("endpoint", cfg.Tracing.Endpoint).
Str("collector", cfg.Tracing.Collector).
Msg("Failed to create zipkin tracing")
return err
}
exporter := zipkin.NewExporter(
zipkinhttp.NewReporter(
cfg.Tracing.Collector,
),
endpoint,
)
trace.RegisterExporter(exporter)
default:
logger.Warn().
Str("type", t).
Msg("Unknown tracing backend")
}
trace.ApplyConfig(
trace.Config{
DefaultSampler: trace.AlwaysSample(),
},
)
} else {
logger.Debug().
Msg("Tracing is not enabled")
}
var (
gr = run.Group{}
ctx, cancel = context.WithCancel(context.Background())
mtrcs = metrics.New()
)
defer cancel()
mtrcs.BuildInfo.WithLabelValues(cfg.Server.Version).Set(1)
handler, err := svc.New(svc.Logger(logger), svc.Config(cfg))
if err != nil {
logger.Fatal().Err(err).Msg("could not initialize service handler")
}
{
server := http.Server(
http.Logger(logger),
http.Name(cfg.Server.Name),
http.Context(ctx),
http.Config(cfg),
http.Metrics(mtrcs),
http.Flags(flagset.RootWithConfig(config.New())),
http.Flags(flagset.ServerWithConfig(config.New())),
http.Handler(handler),
)
gr.Add(server.Run, func(_ error) {
logger.Info().
Str("server", "http").
Msg("Shutting down server")
cancel()
})
}
{
server := grpc.Server(
grpc.Logger(logger),
grpc.Name(cfg.Server.Name),
grpc.Context(ctx),
grpc.Config(cfg),
grpc.Metrics(mtrcs),
grpc.Handler(handler),
)
gr.Add(func() error {
logger.Info().Str("service", server.Name()).Msg("Reporting settings bundles to settings service")
svc.RegisterSettingsBundles(&logger)
svc.RegisterPermissions(&logger)
return server.Run()
}, func(_ error) {
logger.Info().
Str("server", "grpc").
Msg("Shutting down server")
cancel()
})
}
{
stop := make(chan os.Signal, 1)
gr.Add(func() error {
signal.Notify(stop, os.Interrupt)
<-stop
return nil
}, func(err error) {
close(stop)
cancel()
})
}
return gr.Run()
},
}
}
-87
View File
@@ -1,87 +0,0 @@
package command
import (
"errors"
"fmt"
"github.com/micro/cli/v2"
"github.com/micro/go-micro/v2/client/grpc"
"github.com/owncloud/ocis/accounts/pkg/config"
"github.com/owncloud/ocis/accounts/pkg/flagset"
accounts "github.com/owncloud/ocis/accounts/pkg/proto/v0"
"google.golang.org/genproto/protobuf/field_mask"
)
// UpdateAccount command for modifying accounts including password policies
func UpdateAccount(cfg *config.Config) *cli.Command {
a := &accounts.Account{
PasswordProfile: &accounts.PasswordProfile{},
}
return &cli.Command{
Name: "update",
Usage: "Make changes to an existing account",
ArgsUsage: "id",
Flags: flagset.UpdateAccountWithConfig(cfg, a),
Before: func(c *cli.Context) error {
if len(c.StringSlice("password_policies")) > 0 {
// StringSliceFlag doesn't support Destination
a.PasswordProfile.PasswordPolicies = c.StringSlice("password_policies")
}
if c.NArg() != 1 {
return errors.New("missing account-id")
}
if c.NumFlags() == 0 {
return errors.New("missing attribute-flags for update")
}
return nil
},
Action: func(c *cli.Context) error {
a.Id = c.Args().First()
accSvcID := cfg.GRPC.Namespace + "." + cfg.Server.Name
accSvc := accounts.NewAccountsService(accSvcID, grpc.NewClient())
_, err := accSvc.UpdateAccount(c.Context, &accounts.UpdateAccountRequest{
Account: a,
UpdateMask: buildAccUpdateMask(c.FlagNames()),
})
if err != nil {
fmt.Println(fmt.Errorf("could not update account %w", err))
return err
}
return nil
}}
}
// buildAccUpdateMask by mapping passed update flags to account fieldNames.
//
// The UpdateMask is passed with the update-request to the server so that
// only the modified values are transferred.
func buildAccUpdateMask(setFlags []string) *field_mask.FieldMask {
var flagToPath = map[string]string{
"enabled": "AccountEnabled",
"displayname": "DisplayName",
"preferred-name": "PreferredName",
"uidnumber": "UidNumber",
"gidnumber": "GidNumber",
"mail": "Mail",
"description": "Description",
"password": "PasswordProfile.Password",
"password-policies": "PasswordProfile.PasswordPolicies",
"force-password-change": "PasswordProfile.ForceChangePasswordNextSignIn",
"force-password-change-mfa": "PasswordProfile.ForceChangePasswordNextSignInWithMfa",
"on-premises-sam-account-name": "OnPremisesSamAccountName",
}
updatedPaths := make([]string, 0)
for _, v := range setFlags {
if _, ok := flagToPath[v]; ok {
updatedPaths = append(updatedPaths, flagToPath[v])
}
}
return &field_mask.FieldMask{Paths: updatedPaths}
}
-46
View File
@@ -1,46 +0,0 @@
package command
import (
"fmt"
"os"
"github.com/owncloud/ocis/ocis-pkg/registry"
"github.com/micro/cli/v2"
tw "github.com/olekukonko/tablewriter"
"github.com/owncloud/ocis/accounts/pkg/config"
"github.com/owncloud/ocis/accounts/pkg/flagset"
)
// PrintVersion prints the service versions of all running instances.
func PrintVersion(cfg *config.Config) *cli.Command {
return &cli.Command{
Name: "version",
Usage: "Print the versions of the running instances",
Flags: flagset.ListAccountsWithConfig(cfg),
Action: func(c *cli.Context) error {
reg := *registry.GetRegistry()
services, err := reg.GetService(cfg.GRPC.Namespace + "." + cfg.Server.Name)
if err != nil {
fmt.Println(fmt.Errorf("could not get accounts services from the registry: %v", err))
return err
}
if len(services) == 0 {
fmt.Println("No running accounts 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
},
}
}
-129
View File
@@ -1,129 +0,0 @@
// Package config should be moved to internal
package config
// LDAP defines the available ldap configuration.
type LDAP struct {
Hostname string
Port int
BaseDN string
UserFilter string
GroupFilter string
BindDN string
BindPassword string
IDP string
Schema LDAPSchema
}
// LDAPSchema defines the available ldap schema configuration.
type LDAPSchema struct {
AccountID string
Identities string
Username string
DisplayName string
Mail string
Groups string
}
// HTTP defines the available http configuration.
type HTTP struct {
Addr string
Namespace string
Root string
CacheTTL int
}
// GRPC defines the available grpc configuration.
type GRPC struct {
Addr string
Namespace string
}
// Server configures a server.
type Server struct {
Version string
Name string
HashDifficulty int
}
// Asset defines the available asset configuration.
type Asset struct {
Path string
}
// TokenManager is the config for using the reva token manager
type TokenManager struct {
JWTSecret string
}
// Log defines the available logging configuration.
type Log struct {
Level string
Pretty bool
Color bool
}
// Repo defines which storage implementation is to be used.
type Repo struct {
Disk Disk
CS3 CS3
}
// Disk is the local disk implementation of the storage.
type Disk struct {
Path string
}
// CS3 is the cs3 implementation of the storage.
type CS3 struct {
ProviderAddr string
DataURL string
DataPrefix string
JWTSecret string
}
// ServiceUser defines the user required for EOS.
type ServiceUser struct {
UUID string
Username string
UID int64
GID int64
}
// Index defines config for indexes.
type Index struct {
UID, GID Bound
}
// Bound defines a lower and upper bound.
type Bound struct {
Lower, Upper int64
}
// Tracing defines the available tracing configuration.
type Tracing struct {
Enabled bool
Type string
Endpoint string
Collector string
Service string
}
// Config merges all Account config parameters.
type Config struct {
LDAP LDAP
HTTP HTTP
GRPC GRPC
Server Server
Asset Asset
Log Log
TokenManager TokenManager
Repo Repo
Index Index
ServiceUser ServiceUser
Tracing Tracing
}
// New returns a new config.
func New() *Config {
return &Config{}
}
-467
View File
@@ -1,467 +0,0 @@
package flagset
import (
"github.com/micro/cli/v2"
"github.com/owncloud/ocis/accounts/pkg/config"
accounts "github.com/owncloud/ocis/accounts/pkg/proto/v0"
)
// RootWithConfig applies cfg to the root flagset
func RootWithConfig(cfg *config.Config) []cli.Flag {
return []cli.Flag{
&cli.StringFlag{
Name: "log-level",
Value: "info",
Usage: "Set logging level",
EnvVars: []string{"ACCOUNTS_LOG_LEVEL"},
Destination: &cfg.Log.Level,
},
&cli.BoolFlag{
Value: true,
Name: "log-pretty",
Usage: "Enable pretty logging",
EnvVars: []string{"ACCOUNTS_LOG_PRETTY"},
Destination: &cfg.Log.Pretty,
},
&cli.BoolFlag{
Value: true,
Name: "log-color",
Usage: "Enable colored logging",
EnvVars: []string{"ACCOUNTS_LOG_COLOR"},
Destination: &cfg.Log.Color,
},
}
}
// ServerWithConfig applies cfg to the root flagset
func ServerWithConfig(cfg *config.Config) []cli.Flag {
return []cli.Flag{
&cli.BoolFlag{
Name: "tracing-enabled",
Usage: "Enable sending traces",
EnvVars: []string{"ACCOUNTS_TRACING_ENABLED"},
Destination: &cfg.Tracing.Enabled,
},
&cli.StringFlag{
Name: "tracing-type",
Value: "jaeger",
Usage: "Tracing backend type",
EnvVars: []string{"ACCOUNTS_TRACING_TYPE"},
Destination: &cfg.Tracing.Type,
},
&cli.StringFlag{
Name: "tracing-endpoint",
Value: "",
Usage: "Endpoint for the agent",
EnvVars: []string{"ACCOUNTS_TRACING_ENDPOINT"},
Destination: &cfg.Tracing.Endpoint,
},
&cli.StringFlag{
Name: "tracing-collector",
Value: "",
Usage: "Endpoint for the collector",
EnvVars: []string{"ACCOUNTS_TRACING_COLLECTOR"},
Destination: &cfg.Tracing.Collector,
},
&cli.StringFlag{
Name: "tracing-service",
Value: "accounts",
Usage: "Service name for tracing",
EnvVars: []string{"ACCOUNTS_TRACING_SERVICE"},
Destination: &cfg.Tracing.Service,
},
&cli.StringFlag{
Name: "http-namespace",
Value: "com.owncloud.web",
Usage: "Set the base namespace for the http namespace",
EnvVars: []string{"ACCOUNTS_HTTP_NAMESPACE"},
Destination: &cfg.HTTP.Namespace,
},
&cli.StringFlag{
Name: "http-addr",
Value: "0.0.0.0:9181",
Usage: "Address to bind http server",
EnvVars: []string{"ACCOUNTS_HTTP_ADDR"},
Destination: &cfg.HTTP.Addr,
},
&cli.StringFlag{
Name: "http-root",
Value: "/",
Usage: "Root path of http server",
EnvVars: []string{"ACCOUNTS_HTTP_ROOT"},
Destination: &cfg.HTTP.Root,
},
&cli.IntFlag{
Name: "http-cache-ttl",
Value: 604800, // 7 days
Usage: "Set the static assets caching duration in seconds",
EnvVars: []string{"ACCOUNTS_CACHE_TTL"},
Destination: &cfg.HTTP.CacheTTL,
},
&cli.StringFlag{
Name: "grpc-namespace",
Value: "com.owncloud.api",
Usage: "Set the base namespace for the grpc namespace",
EnvVars: []string{"ACCOUNTS_GRPC_NAMESPACE"},
Destination: &cfg.GRPC.Namespace,
},
&cli.StringFlag{
Name: "grpc-addr",
Value: "0.0.0.0:9180",
Usage: "Address to bind grpc server",
EnvVars: []string{"ACCOUNTS_GRPC_ADDR"},
Destination: &cfg.GRPC.Addr,
},
&cli.StringFlag{
Name: "name",
Value: "accounts",
Usage: "service name",
EnvVars: []string{"ACCOUNTS_NAME"},
Destination: &cfg.Server.Name,
},
&cli.IntFlag{
Name: "accounts-hash-difficulty",
Value: 11,
Usage: "accounts password hash difficulty",
EnvVars: []string{"ACCOUNTS_HASH_DIFFICULTY"},
Destination: &cfg.Server.HashDifficulty,
},
&cli.StringFlag{
Name: "asset-path",
Value: "",
Usage: "Path to custom assets",
EnvVars: []string{"ACCOUNTS_ASSET_PATH"},
Destination: &cfg.Asset.Path,
},
&cli.StringFlag{
Name: "jwt-secret",
Value: "Pive-Fumkiu4",
Usage: "Used to create JWT to talk to reva, should equal reva's jwt-secret",
EnvVars: []string{"ACCOUNTS_JWT_SECRET"},
Destination: &cfg.TokenManager.JWTSecret,
},
&cli.StringFlag{
Name: "storage-disk-path",
Value: "",
Usage: "Path on the local disk, e.g. /var/tmp/ocis/accounts",
EnvVars: []string{"ACCOUNTS_STORAGE_DISK_PATH"},
Destination: &cfg.Repo.Disk.Path,
},
&cli.StringFlag{
Name: "storage-cs3-provider-addr",
Value: "localhost:9215",
Usage: "bind address for the metadata storage provider",
EnvVars: []string{"ACCOUNTS_STORAGE_CS3_PROVIDER_ADDR"},
Destination: &cfg.Repo.CS3.ProviderAddr,
},
&cli.StringFlag{
Name: "storage-cs3-data-url",
Value: "http://localhost:9216",
Usage: "http endpoint of the metadata storage",
EnvVars: []string{"ACCOUNTS_STORAGE_CS3_DATA_URL"},
Destination: &cfg.Repo.CS3.DataURL,
},
&cli.StringFlag{
Name: "storage-cs3-data-prefix",
Value: "data",
Usage: "path prefix for the http endpoint of the metadata storage, without leading slash",
EnvVars: []string{"ACCOUNTS_STORAGE_CS3_DATA_PREFIX"},
Destination: &cfg.Repo.CS3.DataPrefix,
},
&cli.StringFlag{
Name: "storage-cs3-jwt-secret",
Value: "Pive-Fumkiu4",
Usage: "Used to create JWT to talk to reva, should equal reva's jwt-secret",
EnvVars: []string{"ACCOUNTS_STORAGE_CS3_JWT_SECRET"},
Destination: &cfg.Repo.CS3.JWTSecret,
},
&cli.StringFlag{
Name: "service-user-uuid",
Value: "95cb8724-03b2-11eb-a0a6-c33ef8ef53ad",
Usage: "uuid of the internal service user (required on EOS)",
EnvVars: []string{"ACCOUNTS_SERVICE_USER_UUID"},
Destination: &cfg.ServiceUser.UUID,
},
&cli.StringFlag{
Name: "service-user-username",
Value: "",
Usage: "username of the internal service user (required on EOS)",
EnvVars: []string{"ACCOUNTS_SERVICE_USER_USERNAME"},
Destination: &cfg.ServiceUser.Username,
},
&cli.Int64Flag{
Name: "service-user-uid",
Value: 0,
Usage: "uid of the internal service user (required on EOS)",
EnvVars: []string{"ACCOUNTS_SERVICE_USER_UID"},
Destination: &cfg.ServiceUser.UID,
},
&cli.Int64Flag{
Name: "service-user-gid",
Value: 0,
Usage: "gid of the internal service user (required on EOS)",
EnvVars: []string{"ACCOUNTS_SERVICE_USER_GID"},
Destination: &cfg.ServiceUser.GID,
},
&cli.Int64Flag{
Name: "uid-index-lower-bound",
Value: 0,
Usage: "define a starting point for the account UID",
EnvVars: []string{"ACCOUNTS_UID_INDEX_LOWER_BOUND"},
Destination: &cfg.Index.UID.Lower,
},
&cli.Int64Flag{
Name: "gid-index-lower-bound",
Value: 1000,
Usage: "define a starting point for the account GID",
EnvVars: []string{"ACCOUNTS_GID_INDEX_LOWER_BOUND"},
Destination: &cfg.Index.GID.Lower,
},
&cli.Int64Flag{
Name: "uid-index-upper-bound",
Value: 0,
Usage: "define an ending point for the account UID",
EnvVars: []string{"ACCOUNTS_UID_INDEX_UPPER_BOUND"},
Destination: &cfg.Index.UID.Upper,
},
&cli.Int64Flag{
Name: "gid-index-upper-bound",
Value: 1000,
Usage: "define an ending point for the account GID",
EnvVars: []string{"ACCOUNTS_GID_INDEX_UPPER_BOUND"},
Destination: &cfg.Index.GID.Upper,
},
}
}
// UpdateAccountWithConfig applies update command flags to cfg
func UpdateAccountWithConfig(cfg *config.Config, a *accounts.Account) []cli.Flag {
if a.PasswordProfile == nil {
a.PasswordProfile = &accounts.PasswordProfile{}
}
return []cli.Flag{
&cli.StringFlag{
Name: "grpc-namespace",
Value: "com.owncloud.api",
Usage: "Set the base namespace for the grpc namespace",
EnvVars: []string{"ACCOUNTS_GRPC_NAMESPACE"},
Destination: &cfg.GRPC.Namespace,
},
&cli.StringFlag{
Name: "name",
Value: "accounts",
Usage: "service name",
EnvVars: []string{"ACCOUNTS_NAME"},
Destination: &cfg.Server.Name,
},
&cli.BoolFlag{
Name: "enabled",
Usage: "Enable the account",
Destination: &a.AccountEnabled,
},
&cli.StringFlag{
Name: "displayname",
Usage: "Set the displayname for the account",
Destination: &a.DisplayName,
},
&cli.StringFlag{
Name: "preferred-name",
Usage: "Set the preferred-name for the account",
Destination: &a.PreferredName,
},
&cli.StringFlag{
Name: "on-premises-sam-account-name",
Usage: "Set the on-premises-sam-account-name",
Destination: &a.OnPremisesSamAccountName,
},
&cli.Int64Flag{
Name: "uidnumber",
Usage: "Set the uidnumber for the account",
Destination: &a.UidNumber,
},
&cli.Int64Flag{
Name: "gidnumber",
Usage: "Set the gidnumber for the account",
Destination: &a.GidNumber,
},
&cli.StringFlag{
Name: "mail",
Usage: "Set the mail for the account",
Destination: &a.Mail,
},
&cli.StringFlag{
Name: "description",
Usage: "Set the description for the account",
Destination: &a.Description,
},
&cli.StringFlag{
Name: "password",
Usage: "Set the password for the account",
Destination: &a.PasswordProfile.Password,
// TODO read password from ENV?
},
&cli.StringSliceFlag{
Name: "password-policies",
Usage: "Possible policies: DisableStrongPassword, DisablePasswordExpiration",
},
&cli.BoolFlag{
Name: "force-password-change",
Usage: "Force password change on next sign-in",
Destination: &a.PasswordProfile.ForceChangePasswordNextSignIn,
},
&cli.BoolFlag{
Name: "force-password-change-mfa",
Usage: "Force password change on next sign-in with mfa",
Destination: &a.PasswordProfile.ForceChangePasswordNextSignInWithMfa,
},
}
}
// AddAccountWithConfig applies create command flags to cfg
func AddAccountWithConfig(cfg *config.Config, a *accounts.Account) []cli.Flag {
if a.PasswordProfile == nil {
a.PasswordProfile = &accounts.PasswordProfile{}
}
return []cli.Flag{
&cli.StringFlag{
Name: "grpc-namespace",
Value: "com.owncloud.api",
Usage: "Set the base namespace for the grpc namespace",
EnvVars: []string{"ACCOUNTS_GRPC_NAMESPACE"},
Destination: &cfg.GRPC.Namespace,
},
&cli.StringFlag{
Name: "name",
Value: "accounts",
Usage: "service name",
EnvVars: []string{"ACCOUNTS_NAME"},
Destination: &cfg.Server.Name,
},
&cli.BoolFlag{
Name: "enabled",
Usage: "Enable the account",
Destination: &a.AccountEnabled,
},
&cli.StringFlag{
Name: "displayname",
Usage: "Set the displayname for the account",
Destination: &a.DisplayName,
},
&cli.StringFlag{
Name: "username",
Usage: "Username will be written to preferred-name and on_premises_sam_account_name",
},
&cli.StringFlag{
Name: "preferred-name",
Usage: "Set the preferred-name for the account",
Destination: &a.PreferredName,
},
&cli.StringFlag{
Name: "on-premises-sam-account-name",
Usage: "Set the on-premises-sam-account-name",
Destination: &a.OnPremisesSamAccountName,
},
&cli.Int64Flag{
Name: "uidnumber",
Usage: "Set the uidnumber for the account",
Destination: &a.UidNumber,
},
&cli.Int64Flag{
Name: "gidnumber",
Usage: "Set the gidnumber for the account",
Destination: &a.GidNumber,
},
&cli.StringFlag{
Name: "mail",
Usage: "Set the mail for the account",
Destination: &a.Mail,
},
&cli.StringFlag{
Name: "description",
Usage: "Set the description for the account",
Destination: &a.Description,
},
&cli.StringFlag{
Name: "password",
Usage: "Set the password for the account",
Destination: &a.PasswordProfile.Password,
// TODO read password from ENV?
},
&cli.StringSliceFlag{
Name: "password-policies",
Usage: "Possible policies: DisableStrongPassword, DisablePasswordExpiration",
},
&cli.BoolFlag{
Name: "force-password-change",
Usage: "Force password change on next sign-in",
Destination: &a.PasswordProfile.ForceChangePasswordNextSignIn,
},
&cli.BoolFlag{
Name: "force-password-change-mfa",
Usage: "Force password change on next sign-in with mfa",
Destination: &a.PasswordProfile.ForceChangePasswordNextSignInWithMfa,
},
}
}
// ListAccountsWithConfig applies list command flags to cfg
func ListAccountsWithConfig(cfg *config.Config) []cli.Flag {
return []cli.Flag{
&cli.StringFlag{
Name: "grpc-namespace",
Value: "com.owncloud.api",
Usage: "Set the base namespace for the grpc namespace",
EnvVars: []string{"ACCOUNTS_GRPC_NAMESPACE"},
Destination: &cfg.GRPC.Namespace,
},
&cli.StringFlag{
Name: "name",
Value: "accounts",
Usage: "service name",
EnvVars: []string{"ACCOUNTS_NAME"},
Destination: &cfg.Server.Name,
},
}
}
// RemoveAccountWithConfig applies remove command flags to cfg
func RemoveAccountWithConfig(cfg *config.Config) []cli.Flag {
return []cli.Flag{
&cli.StringFlag{
Name: "grpc-namespace",
Value: "com.owncloud.api",
Usage: "Set the base namespace for the grpc namespace",
EnvVars: []string{"ACCOUNTS_GRPC_NAMESPACE"},
Destination: &cfg.GRPC.Namespace,
},
&cli.StringFlag{
Name: "name",
Value: "accounts",
Usage: "service name",
EnvVars: []string{"ACCOUNTS_NAME"},
Destination: &cfg.Server.Name,
},
}
}
// InspectAccountWithConfig applies inspect command flags to cfg
func InspectAccountWithConfig(cfg *config.Config) []cli.Flag {
return []cli.Flag{
&cli.StringFlag{
Name: "grpc-namespace",
Value: "com.owncloud.api",
Usage: "Set the base namespace for the grpc namespace",
EnvVars: []string{"ACCOUNTS_GRPC_NAMESPACE"},
Destination: &cfg.GRPC.Namespace,
},
&cli.StringFlag{
Name: "name",
Value: "accounts",
Usage: "service name",
EnvVars: []string{"ACCOUNTS_NAME"},
Destination: &cfg.Server.Name,
},
}
}
-33
View File
@@ -1,33 +0,0 @@
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 = "accounts"
)
// Metrics defines the available metrics of this service.
type Metrics struct {
// Counter *prometheus.CounterVec
BuildInfo *prometheus.GaugeVec
}
// New initializes the available metrics.
func New() *Metrics {
m := &Metrics{
BuildInfo: prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: Namespace,
Subsystem: Subsystem,
Name: "build_info",
Help: "Build information",
}, []string{"version"}),
}
_ = prometheus.Register(m.BuildInfo)
// TODO: implement metrics
return m
}
-89
View File
@@ -1,89 +0,0 @@
package proto
import (
context "context"
empty "github.com/golang/protobuf/ptypes/empty"
client "github.com/micro/go-micro/v2/client"
)
// MockAccountsService can be used to write tests
/*
To creata a mock overwrite the functions of an instance like this:
```go
func mockAccSvc(retErr bool) proto.AccountsService {
if retErr {
return &proto.MockAccountsService{
ListFunc: func(ctx context.Context, in *proto.ListAccountsRequest, opts ...client.CallOption) (out *proto.ListAccountsResponse, err error) {
return nil, fmt.Errorf("error returned by mockAccountsService LIST")
},
}
}
return &proto.MockAccountsService{
ListFunc: func(ctx context.Context, in *proto.ListAccountsRequest, opts ...client.CallOption) (out *proto.ListAccountsResponse, err error) {
return &proto.ListAccountsResponse{
Accounts: []*proto.Account{
{
Id: "yay",
},
},
}, nil
},
}
}
```
*/
type MockAccountsService struct {
ListFunc func(ctx context.Context, in *ListAccountsRequest, opts ...client.CallOption) (*ListAccountsResponse, error)
GetFunc func(ctx context.Context, in *GetAccountRequest, opts ...client.CallOption) (*Account, error)
CreateFunc func(ctx context.Context, in *CreateAccountRequest, opts ...client.CallOption) (*Account, error)
UpdateFunc func(ctx context.Context, in *UpdateAccountRequest, opts ...client.CallOption) (*Account, error)
DeleteFunc func(ctx context.Context, in *DeleteAccountRequest, opts ...client.CallOption) (*empty.Empty, error)
}
// ListAccounts will panic if the function has been called, but not mocked
func (m MockAccountsService) ListAccounts(ctx context.Context, in *ListAccountsRequest, opts ...client.CallOption) (*ListAccountsResponse, error) {
if m.ListFunc != nil {
return m.ListFunc(ctx, in, opts...)
}
panic("ListFunc was called in test but not mocked")
}
// GetAccount will panic if the function has been called, but not mocked
func (m MockAccountsService) GetAccount(ctx context.Context, in *GetAccountRequest, opts ...client.CallOption) (*Account, error) {
if m.GetFunc != nil {
return m.GetFunc(ctx, in, opts...)
}
panic("GetFunc was called in test but not mocked")
}
// CreateAccount will panic if the function has been called, but not mocked
func (m MockAccountsService) CreateAccount(ctx context.Context, in *CreateAccountRequest, opts ...client.CallOption) (*Account, error) {
if m.CreateFunc != nil {
return m.CreateFunc(ctx, in, opts...)
}
panic("CreateFunc was called in test but not mocked")
}
// UpdateAccount will panic if the function has been called, but not mocked
func (m MockAccountsService) UpdateAccount(ctx context.Context, in *UpdateAccountRequest, opts ...client.CallOption) (*Account, error) {
if m.UpdateFunc != nil {
return m.UpdateFunc(ctx, in, opts...)
}
panic("UpdateFunc was called in test but not mocked")
}
// DeleteAccount will panic if the function has been called, but not mocked
func (m MockAccountsService) DeleteAccount(ctx context.Context, in *DeleteAccountRequest, opts ...client.CallOption) (*empty.Empty, error) {
if m.DeleteFunc != nil {
return m.DeleteFunc(ctx, in, opts...)
}
panic("DeleteFunc was called in test but not mocked")
}
File diff suppressed because it is too large. Load diff
-627
View File
@@ -1,627 +0,0 @@
// Code generated by protoc-gen-micro. DO NOT EDIT.
// source: accounts.proto
package proto
import (
fmt "fmt"
proto "github.com/golang/protobuf/proto"
empty "github.com/golang/protobuf/ptypes/empty"
_ "github.com/golang/protobuf/ptypes/timestamp"
_ "google.golang.org/genproto/googleapis/api/annotations"
_ "google.golang.org/genproto/protobuf/field_mask"
math "math"
)
import (
context "context"
api "github.com/micro/go-micro/v2/api"
client "github.com/micro/go-micro/v2/client"
server "github.com/micro/go-micro/v2/server"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
// Reference imports to suppress errors if they are not otherwise used.
var _ api.Endpoint
var _ context.Context
var _ client.Option
var _ server.Option
// Api Endpoints for AccountsService service
func NewAccountsServiceEndpoints() []*api.Endpoint {
return []*api.Endpoint{
&api.Endpoint{
Name: "AccountsService.ListAccounts",
Path: []string{"/api/v0/accounts/accounts-list"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
},
&api.Endpoint{
Name: "AccountsService.GetAccount",
Path: []string{"/api/v0/accounts/accounts-get"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
},
&api.Endpoint{
Name: "AccountsService.CreateAccount",
Path: []string{"/api/v0/accounts/accounts-create"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
},
&api.Endpoint{
Name: "AccountsService.UpdateAccount",
Path: []string{"/api/v0/accounts/accounts-update"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
},
&api.Endpoint{
Name: "AccountsService.DeleteAccount",
Path: []string{"/api/v0/accounts/accounts-delete"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
},
}
}
// Client API for AccountsService service
type AccountsService interface {
// Lists accounts
ListAccounts(ctx context.Context, in *ListAccountsRequest, opts ...client.CallOption) (*ListAccountsResponse, error)
// Gets an account
GetAccount(ctx context.Context, in *GetAccountRequest, opts ...client.CallOption) (*Account, error)
// Creates an account
CreateAccount(ctx context.Context, in *CreateAccountRequest, opts ...client.CallOption) (*Account, error)
// Updates an account
UpdateAccount(ctx context.Context, in *UpdateAccountRequest, opts ...client.CallOption) (*Account, error)
// Deletes an account
DeleteAccount(ctx context.Context, in *DeleteAccountRequest, opts ...client.CallOption) (*empty.Empty, error)
}
type accountsService struct {
c client.Client
name string
}
func NewAccountsService(name string, c client.Client) AccountsService {
return &accountsService{
c: c,
name: name,
}
}
func (c *accountsService) ListAccounts(ctx context.Context, in *ListAccountsRequest, opts ...client.CallOption) (*ListAccountsResponse, error) {
req := c.c.NewRequest(c.name, "AccountsService.ListAccounts", in)
out := new(ListAccountsResponse)
err := c.c.Call(ctx, req, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *accountsService) GetAccount(ctx context.Context, in *GetAccountRequest, opts ...client.CallOption) (*Account, error) {
req := c.c.NewRequest(c.name, "AccountsService.GetAccount", in)
out := new(Account)
err := c.c.Call(ctx, req, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *accountsService) CreateAccount(ctx context.Context, in *CreateAccountRequest, opts ...client.CallOption) (*Account, error) {
req := c.c.NewRequest(c.name, "AccountsService.CreateAccount", in)
out := new(Account)
err := c.c.Call(ctx, req, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *accountsService) UpdateAccount(ctx context.Context, in *UpdateAccountRequest, opts ...client.CallOption) (*Account, error) {
req := c.c.NewRequest(c.name, "AccountsService.UpdateAccount", in)
out := new(Account)
err := c.c.Call(ctx, req, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *accountsService) DeleteAccount(ctx context.Context, in *DeleteAccountRequest, opts ...client.CallOption) (*empty.Empty, error) {
req := c.c.NewRequest(c.name, "AccountsService.DeleteAccount", in)
out := new(empty.Empty)
err := c.c.Call(ctx, req, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for AccountsService service
type AccountsServiceHandler interface {
// Lists accounts
ListAccounts(context.Context, *ListAccountsRequest, *ListAccountsResponse) error
// Gets an account
GetAccount(context.Context, *GetAccountRequest, *Account) error
// Creates an account
CreateAccount(context.Context, *CreateAccountRequest, *Account) error
// Updates an account
UpdateAccount(context.Context, *UpdateAccountRequest, *Account) error
// Deletes an account
DeleteAccount(context.Context, *DeleteAccountRequest, *empty.Empty) error
}
func RegisterAccountsServiceHandler(s server.Server, hdlr AccountsServiceHandler, opts ...server.HandlerOption) error {
type accountsService interface {
ListAccounts(ctx context.Context, in *ListAccountsRequest, out *ListAccountsResponse) error
GetAccount(ctx context.Context, in *GetAccountRequest, out *Account) error
CreateAccount(ctx context.Context, in *CreateAccountRequest, out *Account) error
UpdateAccount(ctx context.Context, in *UpdateAccountRequest, out *Account) error
DeleteAccount(ctx context.Context, in *DeleteAccountRequest, out *empty.Empty) error
}
type AccountsService struct {
accountsService
}
h := &accountsServiceHandler{hdlr}
opts = append(opts, api.WithEndpoint(&api.Endpoint{
Name: "AccountsService.ListAccounts",
Path: []string{"/api/v0/accounts/accounts-list"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
}))
opts = append(opts, api.WithEndpoint(&api.Endpoint{
Name: "AccountsService.GetAccount",
Path: []string{"/api/v0/accounts/accounts-get"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
}))
opts = append(opts, api.WithEndpoint(&api.Endpoint{
Name: "AccountsService.CreateAccount",
Path: []string{"/api/v0/accounts/accounts-create"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
}))
opts = append(opts, api.WithEndpoint(&api.Endpoint{
Name: "AccountsService.UpdateAccount",
Path: []string{"/api/v0/accounts/accounts-update"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
}))
opts = append(opts, api.WithEndpoint(&api.Endpoint{
Name: "AccountsService.DeleteAccount",
Path: []string{"/api/v0/accounts/accounts-delete"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
}))
return s.Handle(s.NewHandler(&AccountsService{h}, opts...))
}
type accountsServiceHandler struct {
AccountsServiceHandler
}
func (h *accountsServiceHandler) ListAccounts(ctx context.Context, in *ListAccountsRequest, out *ListAccountsResponse) error {
return h.AccountsServiceHandler.ListAccounts(ctx, in, out)
}
func (h *accountsServiceHandler) GetAccount(ctx context.Context, in *GetAccountRequest, out *Account) error {
return h.AccountsServiceHandler.GetAccount(ctx, in, out)
}
func (h *accountsServiceHandler) CreateAccount(ctx context.Context, in *CreateAccountRequest, out *Account) error {
return h.AccountsServiceHandler.CreateAccount(ctx, in, out)
}
func (h *accountsServiceHandler) UpdateAccount(ctx context.Context, in *UpdateAccountRequest, out *Account) error {
return h.AccountsServiceHandler.UpdateAccount(ctx, in, out)
}
func (h *accountsServiceHandler) DeleteAccount(ctx context.Context, in *DeleteAccountRequest, out *empty.Empty) error {
return h.AccountsServiceHandler.DeleteAccount(ctx, in, out)
}
// Api Endpoints for GroupsService service
func NewGroupsServiceEndpoints() []*api.Endpoint {
return []*api.Endpoint{
&api.Endpoint{
Name: "GroupsService.ListGroups",
Path: []string{"/api/v0/accounts/groups-list"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
},
&api.Endpoint{
Name: "GroupsService.GetGroup",
Path: []string{"/api/v0/accounts/groups-get"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
},
&api.Endpoint{
Name: "GroupsService.CreateGroup",
Path: []string{"/api/v0/accounts/groups-create"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
},
&api.Endpoint{
Name: "GroupsService.UpdateGroup",
Path: []string{"/api/v0/accounts/groups-update"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
},
&api.Endpoint{
Name: "GroupsService.DeleteGroup",
Path: []string{"/api/v0/accounts/groups-delete"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
},
&api.Endpoint{
Name: "GroupsService.AddMember",
Path: []string{"/api/v0/groups/{group_id=*}/members/$ref"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
},
&api.Endpoint{
Name: "GroupsService.RemoveMember",
Path: []string{"/api/v0/groups/{group_id=*}/members/{account_id}/$ref"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
},
&api.Endpoint{
Name: "GroupsService.ListMembers",
Path: []string{"/api/v0/groups/{id=*}/members/$ref"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
},
}
}
// Client API for GroupsService service
type GroupsService interface {
// Lists groups
ListGroups(ctx context.Context, in *ListGroupsRequest, opts ...client.CallOption) (*ListGroupsResponse, error)
// Gets an groups
GetGroup(ctx context.Context, in *GetGroupRequest, opts ...client.CallOption) (*Group, error)
// Creates a group
CreateGroup(ctx context.Context, in *CreateGroupRequest, opts ...client.CallOption) (*Group, error)
// Updates a group
UpdateGroup(ctx context.Context, in *UpdateGroupRequest, opts ...client.CallOption) (*Group, error)
// Deletes a group
DeleteGroup(ctx context.Context, in *DeleteGroupRequest, opts ...client.CallOption) (*empty.Empty, error)
// group:addmember https://docs.microsoft.com/en-us/graph/api/group-post-members?view=graph-rest-1.0&tabs=http
AddMember(ctx context.Context, in *AddMemberRequest, opts ...client.CallOption) (*Group, error)
// group:removemember https://docs.microsoft.com/en-us/graph/api/group-delete-members?view=graph-rest-1.0
RemoveMember(ctx context.Context, in *RemoveMemberRequest, opts ...client.CallOption) (*Group, error)
// group:listmembers https://docs.microsoft.com/en-us/graph/api/group-list-members?view=graph-rest-1.0
ListMembers(ctx context.Context, in *ListMembersRequest, opts ...client.CallOption) (*ListMembersResponse, error)
}
type groupsService struct {
c client.Client
name string
}
func NewGroupsService(name string, c client.Client) GroupsService {
return &groupsService{
c: c,
name: name,
}
}
func (c *groupsService) ListGroups(ctx context.Context, in *ListGroupsRequest, opts ...client.CallOption) (*ListGroupsResponse, error) {
req := c.c.NewRequest(c.name, "GroupsService.ListGroups", in)
out := new(ListGroupsResponse)
err := c.c.Call(ctx, req, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *groupsService) GetGroup(ctx context.Context, in *GetGroupRequest, opts ...client.CallOption) (*Group, error) {
req := c.c.NewRequest(c.name, "GroupsService.GetGroup", in)
out := new(Group)
err := c.c.Call(ctx, req, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *groupsService) CreateGroup(ctx context.Context, in *CreateGroupRequest, opts ...client.CallOption) (*Group, error) {
req := c.c.NewRequest(c.name, "GroupsService.CreateGroup", in)
out := new(Group)
err := c.c.Call(ctx, req, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *groupsService) UpdateGroup(ctx context.Context, in *UpdateGroupRequest, opts ...client.CallOption) (*Group, error) {
req := c.c.NewRequest(c.name, "GroupsService.UpdateGroup", in)
out := new(Group)
err := c.c.Call(ctx, req, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *groupsService) DeleteGroup(ctx context.Context, in *DeleteGroupRequest, opts ...client.CallOption) (*empty.Empty, error) {
req := c.c.NewRequest(c.name, "GroupsService.DeleteGroup", in)
out := new(empty.Empty)
err := c.c.Call(ctx, req, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *groupsService) AddMember(ctx context.Context, in *AddMemberRequest, opts ...client.CallOption) (*Group, error) {
req := c.c.NewRequest(c.name, "GroupsService.AddMember", in)
out := new(Group)
err := c.c.Call(ctx, req, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *groupsService) RemoveMember(ctx context.Context, in *RemoveMemberRequest, opts ...client.CallOption) (*Group, error) {
req := c.c.NewRequest(c.name, "GroupsService.RemoveMember", in)
out := new(Group)
err := c.c.Call(ctx, req, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *groupsService) ListMembers(ctx context.Context, in *ListMembersRequest, opts ...client.CallOption) (*ListMembersResponse, error) {
req := c.c.NewRequest(c.name, "GroupsService.ListMembers", in)
out := new(ListMembersResponse)
err := c.c.Call(ctx, req, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for GroupsService service
type GroupsServiceHandler interface {
// Lists groups
ListGroups(context.Context, *ListGroupsRequest, *ListGroupsResponse) error
// Gets an groups
GetGroup(context.Context, *GetGroupRequest, *Group) error
// Creates a group
CreateGroup(context.Context, *CreateGroupRequest, *Group) error
// Updates a group
UpdateGroup(context.Context, *UpdateGroupRequest, *Group) error
// Deletes a group
DeleteGroup(context.Context, *DeleteGroupRequest, *empty.Empty) error
// group:addmember https://docs.microsoft.com/en-us/graph/api/group-post-members?view=graph-rest-1.0&tabs=http
AddMember(context.Context, *AddMemberRequest, *Group) error
// group:removemember https://docs.microsoft.com/en-us/graph/api/group-delete-members?view=graph-rest-1.0
RemoveMember(context.Context, *RemoveMemberRequest, *Group) error
// group:listmembers https://docs.microsoft.com/en-us/graph/api/group-list-members?view=graph-rest-1.0
ListMembers(context.Context, *ListMembersRequest, *ListMembersResponse) error
}
func RegisterGroupsServiceHandler(s server.Server, hdlr GroupsServiceHandler, opts ...server.HandlerOption) error {
type groupsService interface {
ListGroups(ctx context.Context, in *ListGroupsRequest, out *ListGroupsResponse) error
GetGroup(ctx context.Context, in *GetGroupRequest, out *Group) error
CreateGroup(ctx context.Context, in *CreateGroupRequest, out *Group) error
UpdateGroup(ctx context.Context, in *UpdateGroupRequest, out *Group) error
DeleteGroup(ctx context.Context, in *DeleteGroupRequest, out *empty.Empty) error
AddMember(ctx context.Context, in *AddMemberRequest, out *Group) error
RemoveMember(ctx context.Context, in *RemoveMemberRequest, out *Group) error
ListMembers(ctx context.Context, in *ListMembersRequest, out *ListMembersResponse) error
}
type GroupsService struct {
groupsService
}
h := &groupsServiceHandler{hdlr}
opts = append(opts, api.WithEndpoint(&api.Endpoint{
Name: "GroupsService.ListGroups",
Path: []string{"/api/v0/accounts/groups-list"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
}))
opts = append(opts, api.WithEndpoint(&api.Endpoint{
Name: "GroupsService.GetGroup",
Path: []string{"/api/v0/accounts/groups-get"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
}))
opts = append(opts, api.WithEndpoint(&api.Endpoint{
Name: "GroupsService.CreateGroup",
Path: []string{"/api/v0/accounts/groups-create"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
}))
opts = append(opts, api.WithEndpoint(&api.Endpoint{
Name: "GroupsService.UpdateGroup",
Path: []string{"/api/v0/accounts/groups-update"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
}))
opts = append(opts, api.WithEndpoint(&api.Endpoint{
Name: "GroupsService.DeleteGroup",
Path: []string{"/api/v0/accounts/groups-delete"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
}))
opts = append(opts, api.WithEndpoint(&api.Endpoint{
Name: "GroupsService.AddMember",
Path: []string{"/api/v0/groups/{group_id=*}/members/$ref"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
}))
opts = append(opts, api.WithEndpoint(&api.Endpoint{
Name: "GroupsService.RemoveMember",
Path: []string{"/api/v0/groups/{group_id=*}/members/{account_id}/$ref"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
}))
opts = append(opts, api.WithEndpoint(&api.Endpoint{
Name: "GroupsService.ListMembers",
Path: []string{"/api/v0/groups/{id=*}/members/$ref"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
}))
return s.Handle(s.NewHandler(&GroupsService{h}, opts...))
}
type groupsServiceHandler struct {
GroupsServiceHandler
}
func (h *groupsServiceHandler) ListGroups(ctx context.Context, in *ListGroupsRequest, out *ListGroupsResponse) error {
return h.GroupsServiceHandler.ListGroups(ctx, in, out)
}
func (h *groupsServiceHandler) GetGroup(ctx context.Context, in *GetGroupRequest, out *Group) error {
return h.GroupsServiceHandler.GetGroup(ctx, in, out)
}
func (h *groupsServiceHandler) CreateGroup(ctx context.Context, in *CreateGroupRequest, out *Group) error {
return h.GroupsServiceHandler.CreateGroup(ctx, in, out)
}
func (h *groupsServiceHandler) UpdateGroup(ctx context.Context, in *UpdateGroupRequest, out *Group) error {
return h.GroupsServiceHandler.UpdateGroup(ctx, in, out)
}
func (h *groupsServiceHandler) DeleteGroup(ctx context.Context, in *DeleteGroupRequest, out *empty.Empty) error {
return h.GroupsServiceHandler.DeleteGroup(ctx, in, out)
}
func (h *groupsServiceHandler) AddMember(ctx context.Context, in *AddMemberRequest, out *Group) error {
return h.GroupsServiceHandler.AddMember(ctx, in, out)
}
func (h *groupsServiceHandler) RemoveMember(ctx context.Context, in *RemoveMemberRequest, out *Group) error {
return h.GroupsServiceHandler.RemoveMember(ctx, in, out)
}
func (h *groupsServiceHandler) ListMembers(ctx context.Context, in *ListMembersRequest, out *ListMembersResponse) error {
return h.GroupsServiceHandler.ListMembers(ctx, in, out)
}
// Api Endpoints for IndexService service
func NewIndexServiceEndpoints() []*api.Endpoint {
return []*api.Endpoint{
&api.Endpoint{
Name: "IndexService.RebuildIndex",
Path: []string{"/api/v0/index/rebuild"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
},
}
}
// Client API for IndexService service
type IndexService interface {
RebuildIndex(ctx context.Context, in *RebuildIndexRequest, opts ...client.CallOption) (*RebuildIndexResponse, error)
}
type indexService struct {
c client.Client
name string
}
func NewIndexService(name string, c client.Client) IndexService {
return &indexService{
c: c,
name: name,
}
}
func (c *indexService) RebuildIndex(ctx context.Context, in *RebuildIndexRequest, opts ...client.CallOption) (*RebuildIndexResponse, error) {
req := c.c.NewRequest(c.name, "IndexService.RebuildIndex", in)
out := new(RebuildIndexResponse)
err := c.c.Call(ctx, req, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for IndexService service
type IndexServiceHandler interface {
RebuildIndex(context.Context, *RebuildIndexRequest, *RebuildIndexResponse) error
}
func RegisterIndexServiceHandler(s server.Server, hdlr IndexServiceHandler, opts ...server.HandlerOption) error {
type indexService interface {
RebuildIndex(ctx context.Context, in *RebuildIndexRequest, out *RebuildIndexResponse) error
}
type IndexService struct {
indexService
}
h := &indexServiceHandler{hdlr}
opts = append(opts, api.WithEndpoint(&api.Endpoint{
Name: "IndexService.RebuildIndex",
Path: []string{"/api/v0/index/rebuild"},
Method: []string{"POST"},
Body: "*",
Handler: "rpc",
}))
return s.Handle(s.NewHandler(&IndexService{h}, opts...))
}
type indexServiceHandler struct {
IndexServiceHandler
}
func (h *indexServiceHandler) RebuildIndex(ctx context.Context, in *RebuildIndexRequest, out *RebuildIndexResponse) error {
return h.IndexServiceHandler.RebuildIndex(ctx, in, out)
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-671
View File
@@ -1,671 +0,0 @@
syntax = "proto3";
option go_package = "pkg/proto/v0;proto";
package settings;
import "google/api/field_behavior.proto";
import "google/api/annotations.proto";
import "google/protobuf/empty.proto";
import "google/protobuf/field_mask.proto";
import "google/protobuf/timestamp.proto";
// Follow recommended Methods for rpc APIs https://cloud.google.com/apis/design/resources?hl=de#methods
// https://cloud.google.com/apis/design/standard_methods?hl=de#list
// https://cloud.google.com/apis/design/naming_convention?hl=de
service AccountsService {
// Lists accounts
rpc ListAccounts(ListAccountsRequest) returns (ListAccountsResponse) {
// List method maps to HTTP GET
option (google.api.http) = {
post: "/api/v0/accounts/accounts-list",
body: "*"
};
}
// Gets an account
rpc GetAccount(GetAccountRequest) returns (Account) {
option (google.api.http) = {
post: "/api/v0/accounts/accounts-get",
body: "*"
};
}
// Creates an account
rpc CreateAccount(CreateAccountRequest) returns (Account) {
// Create maps to HTTP POST. URL path as the collection name.
// HTTP request body contains the resource
option (google.api.http) = {
post: "/api/v0/accounts/accounts-create"
body: "*"
};
}
// Updates an account
rpc UpdateAccount(UpdateAccountRequest) returns (Account) {
// Update maps to HTTP PATCH. Resource name is mapped to a URL path.
// Resource is contained in the HTTP request body
option (google.api.http) = {
post: "/api/v0/accounts/accounts-update"
body: "*"
};
};
// Deletes an account
rpc DeleteAccount(DeleteAccountRequest) returns (google.protobuf.Empty) {
// Delete maps to HTTP DELETE. Resource name maps to the URL path.
// There is no request body
option (google.api.http) = {
post: "/api/v0/accounts/accounts-delete",
body: "*"
};
}
}
service GroupsService {
// Lists groups
rpc ListGroups(ListGroupsRequest) returns (ListGroupsResponse) {
// List method maps to HTTP GET
option (google.api.http) = {
post: "/api/v0/accounts/groups-list",
body: "*"
};
}
// Gets an groups
rpc GetGroup(GetGroupRequest) returns (Group) {
option (google.api.http) = {
post: "/api/v0/accounts/groups-get",
body: "*"
};
}
// Creates a group
rpc CreateGroup(CreateGroupRequest) returns (Group) {
// Create maps to HTTP POST. URL path as the collection name.
// HTTP request body contains the resource
option (google.api.http) = {
post: "/api/v0/accounts/groups-create"
body: "*"
};
}
// Updates a group
rpc UpdateGroup(UpdateGroupRequest) returns (Group) {
// Update maps to HTTP PATCH. Resource name is mapped to a URL path.
// Resource is contained in the HTTP request body
option (google.api.http) = {
post: "/api/v0/accounts/groups-update"
body: "*"
};
};
// Deletes a group
rpc DeleteGroup(DeleteGroupRequest) returns (google.protobuf.Empty) {
// Delete maps to HTTP DELETE. Resource name maps to the URL path.
// There is no request body
option (google.api.http) = {
post: "/api/v0/accounts/groups-delete",
body: "*"
};
}
// additional group methods: https://docs.microsoft.com/en-us/graph/api/resources/group?view=graph-rest-1.0#methods
// references are accessed using $ref, see http://docs.oasis-open.org/odata/odata/v4.0/cs01/part2-url-conventions/odata-v4.0-cs01-part2-url-conventions.html#_Toc365046422
// or the stack overflow question https://stackoverflow.com/questions/49362894/why-is-the-microsoft-graph-api-using-ref-in-the-uri
// group:addmember https://docs.microsoft.com/en-us/graph/api/group-post-members?view=graph-rest-1.0&tabs=http
rpc AddMember(AddMemberRequest) returns (Group) {
// All request parameters go into body.
option (google.api.http) = {
post: "/api/v0/groups/{group_id=*}/members/$ref"
body: "*"
};
}
// group:removemember https://docs.microsoft.com/en-us/graph/api/group-delete-members?view=graph-rest-1.0
rpc RemoveMember(RemoveMemberRequest) returns (Group) {
// All request parameters go into body.
option (google.api.http) = {
// URLs are broken
post: "/api/v0/groups/{group_id=*}/members/{account_id}/$ref"
body: "*"
};
}
// group:listmembers https://docs.microsoft.com/en-us/graph/api/group-list-members?view=graph-rest-1.0
rpc ListMembers(ListMembersRequest) returns (ListMembersResponse) {
// All request parameters go into body.
option (google.api.http) = {
// URLs are broken
post: "/api/v0/groups/{id=*}/members/$ref"
body: "*"
};
}
}
service IndexService {
rpc RebuildIndex(RebuildIndexRequest) returns (RebuildIndexResponse) {
// All request parameters go into body.
option (google.api.http) = {
// URLs are broken
post: "/api/v0/index/rebuild"
body: "*"
};
}
}
message RebuildIndexRequest {
}
message RebuildIndexResponse {
}
message ListAccountsRequest {
// Optional. The maximum number of accounts to return in the response
int32 page_size = 1 [(google.api.field_behavior) = OPTIONAL];
// Optional. A pagination token returned from a previous call to `Get`
// that indicates from where search should continue
string page_token = 2 [(google.api.field_behavior) = OPTIONAL];
// Optional. Used to specify a subset of fields that should be
// returned by a get operation or modified by an update operation.
google.protobuf.FieldMask field_mask = 3;
// Optional. Search criteria used to select the accounts to return.
// If no search criteria is specified then all accounts will be
// returned
//
// TODO update query language
// Query expressions can be used to restrict results based upon
// the account properties where the operators `=`, `NOT`, `AND` and `OR`
// can be used along with the suffix wildcard symbol `*`.
//
// The string properties in a query expression should use escaped quotes
// for values that include whitespace to prevent unexpected behavior.
//
// Some example queries are:
//
// * Query `display_name=Th*` returns accounts whose display_name
// starts with "Th"
// * Query `email=foo@example.com` returns accounts with
// `email` set to `foo@example.com`
// * Query `display_name=\\"Test String\\"` returns accounts with
// display names that include both "Test" and "String"
string query = 4 [(google.api.field_behavior) = OPTIONAL];
}
message ListAccountsResponse {
// The field name should match the noun "accounts" in the method name. There
// will be a maximum number of items returned based on the page_size field
// in the request
repeated Account accounts = 1;
// Token to retrieve the next page of results, or empty if there are no
// more results in the list
string next_page_token = 2;
}
message GetAccountRequest {
string id = 1;
}
message CreateAccountRequest {
// The account resource to create
Account account = 1;
}
message UpdateAccountRequest {
// The account resource which replaces the resource on the server
Account account = 1;
// The update mask applies to the resource. For the `FieldMask` definition,
// see https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask
google.protobuf.FieldMask update_mask = 2;
}
message DeleteAccountRequest {
string id = 1;
}
// Account follows the properties of the ms graph api user resuorce.
// See https://docs.microsoft.com/en-us/graph/api/resources/user?view=graph-rest-1.0#properties
message Account {
// Note that field numbers in the range 1 through 15 take one byte to encode, including the field number and the field's type
// The unique identifier for the user. Key. Not nullable. Non reassignable. Read-only.
string id = 1;
// *true* if the account is enabled; otherwise, *false*. This property is required when a user is created. Supports $filter.
bool account_enabled = 2;
// A resource account is also known as a /disabled user object/ in Azure AD, and can be used to represent resources in general.
// In Exchange it might be used to represent conference rooms, for example, and allow them to have a phone number.
// You could give printers or machines with a sync client resource accounts as well.
// A resource account can be homed in Microsoft 365 or on premises using Skype for Business Server 2019.
// *true* if the user is a resource account; otherwise, *false*. Null value should be considered false.
bool is_resource_account = 3;
// Indicates whether the account was created as
// - a regular school or work account ("" / emptystring),
// - a local account, fully managed by ocis (LocalAccount), includes synced accounts or
// - an external account (Invitation),
// - self-service sign-up using email verification (EmailVerified). Read-only.
string creation_type = 4;
// Represents the identities that can be used to sign in to this account.
// An identity can be provided by OCIS (also known as a local account), by organizations, or by social identity providers such as Facebook, Google, and Microsoft, and is tied to an account.
// May contain multiple items with the same signInType value. Supports $filter.
repeated Identities identities = 5;
// posixaccount properties
// The name displayed in the address book for the account.
// This is usually the combination of the user's first name, middle initial and last name.
// This property is required when a user is created and it cannot be cleared during updates.
// Supports $filter and $orderby.
// posixaccount MUST cn
string display_name = 6;
// The username
// posixaccount MUST uid
string preferred_name = 7;
// TODO rename to on_premise_? or move to extension? see https://docs.microsoft.com/en-us/graph/extensibility-open-users
// used for exposing the user using ldap
// posixaccount MUST uidnumber
int64 uid_number = 8;
// used for exposing the user using ldap
// posixaccount MUST gidnumber
int64 gid_number = 9;
// posixaccount MUST homedirectory
// constructed dynamically in glauth
// posixaccount MAY loginshell
// posixaccount MAY gecos
// For the GECOS field:
// - User's full name (or application name, if the account is for a program) -> displayname (description)
// - Building and room number or contact person -> -
// - Office telephone number -> -
// - Any other contact information (pager number, fax, etc.) -> mail
// eg "Albert Einstein (Beware! I'm doing science!),,,einstein@example.com" as the gecos
// The SMTP address for the user, for example, "jeff@contoso.onmicrosoft.com". Read-Only. Supports $filter.
// inetorgperson MAY mail
string mail = 10;
// A description, useful for resource accounts
// posixaccount MAY description
string description = 11;
// Specifies the password profile for the user.
// The profile contains the user’s password. This property is required when a user is created.
// The password in the profile must satisfy minimum requirements as specified by the passwordPolicies property.
// By default, a strong password is required.
// posixaccount MAY authPassword
PasswordProfile password_profile = 12;
// The groups, directory roles and administrative units that the user is a member of. Read-only. Nullable.
// should we only respond with repeated strings of ids? no clients should a proper filter mask!
repeated Group memberOf = 13;
// Field numbers in the range 16 through 2047 take two bytes. So you should reserve the field numbers 1 through 15 for very frequently occurring message elements. Remember to leave some room for frequently occurring elements that might be added in the future.
// The created date of the account object.
google.protobuf.Timestamp created_date_time = 16;
// The date and time the user was deleted. Returned only on $select.
google.protobuf.Timestamp deleted_date_time = 17;
// properties for sync
// *true* if this object is synced from an on-premises directory;
// *false* if this object was originally synced from an on-premises directory but is no longer synced;
// null if this object has never been synced from an on-premises directory (default). Read-only
bool on_premises_sync_enabled = 20;
// This property is used to associate an on-premises LDAP user to the ocis account object.
// This property must be specified when creating a new user account in the Graph if you are using a federated domain for the user’s userPrincipalName (UPN) property.
// Important: The $ and _ characters cannot be used when specifying this property. Supports $filter.
string on_premises_immutable_id = 21;
// Contains the on-premises security identifier (SID) for the user that was synchronized from on-premises to the cloud. Read-only.
string on_premises_security_identifier = 22;
// Contains the on-premises LDAP `distinguished name` or `DN`.
// The property is only populated for customers who are synchronizing their on-premises directory to ocis-accounts. Read-only.
string on_premises_distinguished_name = 23;
// Contains the on-premises `samAccountName` synchronized from the on-premises directory.
// The property is only populated for customers who are synchronizing their on-premises directory to ocis-accounts. Read-only.
string on_premises_sam_account_name = 24;
// Contains the on-premises `domainFQDN`, also called `dnsDomainName` synchronized from the on-premises directory
// The property is only populated for customers who are synchronizing their on-premises directory to ocis-accounts. Read-only.
string on_premises_domain_name = 25;
// Contains the on-premises userPrincipalName synchronized from the on-premises directory.
// The property is only populated for customers who are synchronizing their on-premises directory to ocis-accounts. Read-only.
string on_premises_user_principal_name = 26;
// Contains extensionAttributes 1-15 for the user. Note that the individual extension attributes are neither selectable nor filterable.
// For an onPremisesSyncEnabled user, this set of properties is mastered on-premises and is read-only.
// For a cloud-only user (where onPremisesSyncEnabled is false), these properties may be set during creation or update.
//onPremisesExtensionAttributes onPremisesExtensionAttributes = 27
// Indicates the last time at which the object was synced with the on-premises directory; Read-only.
google.protobuf.Timestamp on_premises_last_sync_date_time = 28;
// Errors when using synchronization during provisioning.
repeated OnPremisesProvisioningError on_premises_provisioning_errors = 29;
// TODO do we need to sync uidnumber and gidnumber from the external ldap? we may assign different numbers so eos has a non colliding namespace.
// we can sync them to the (uid|gid)_number fileds but what if they changed in the external ldap and now collide?
// move those properties to a posixaccount message so we can exchange that part with an external (readonly or writeable) ldap server?
// For an external user invited to the tenant using the invitation API, this property represents the invited user's invitation status.
// For invited users, the state can be `PendingAcceptance` or `Accepted`, or "" / emptystring for all other users.
// Returned only on $select. Supports $filter with the supported values. For example: $filter=externalUserState eq 'PendingAcceptance'.
string external_user_state = 40;
// Shows the timestamp for the latest change to the externalUserState property. Returned only on $select.
google.protobuf.Timestamp external_user_state_change_date_time = 41;
// Any refresh tokens or sessions tokens (session cookies) issued before this time are invalid, and applications will get
// an error when using an invalid refresh or sessions token to acquire a delegated access token (to access APIs such as Microsoft Graph).
// If this happens, the application will need to acquire a new refresh token by making a request to the authorize endpoint.
// Returned only on $select. Read-only. Use invalidateAllRefreshTokens to reset.
google.protobuf.Timestamp refresh_tokens_valid_from_date_time = 60;
// Any refresh tokens or sessions tokens (session cookies) issued before this time are invalid, and applications will get
// an error when using an invalid refresh or sessions token to acquire a delegated access token (to access APIs such as Microsoft Graph).
// If this happens, the application will need to acquire a new refresh token by making a request to the authorize endpoint.
// Read-only. Use revokeSignInSessions to reset.
google.protobuf.Timestamp sign_in_sessions_valid_from_date_time = 61;
}
// Identities Represents an identity used to sign in to a user account.
// An identity can be provided by ocis, by organizations, or by social identity providers such as Facebook, Google, or Microsoft, that are tied to a user account.
// This enables the user to sign in to the user account with any of those associated identities.
// They are also used to keep a history of old usernames.
message Identities {
// Specifies the user sign-in types in your directory, such as `emailAddress`, `userName` or `federated`.
// Here, federated represents a unique identifier for a user from an issuer, that can be in any format chosen by the issuer.
// Additional validation is enforced on *issuer_assigned_id* when the sign-in type is set to `emailAddress` or `userName`.
// This property can also be set to any custom string.
string sign_in_type = 1;
// Specifies the issuer of the identity, for example facebook.com.
// For local accounts (where signInType is not federated), this property is
// the local B2C tenant default domain name, for example contoso.onmicrosoft.com.
// For external users from other Azure AD organization, this will be the domain of
// the federated organization, for example contoso.com.
// Supports $filter. 512 character limit.
string issuer = 2;
// Specifies the unique identifier assigned to the user by the issuer. The combination of *issuer* and *issuerAssignedId* must be unique within the organization. Represents the sign-in name for the user, when signInType is set to emailAddress or userName (also known as local accounts).
// When *signInType* is set to:
// * `emailAddress`, (or starts with `emailAddress` like `emailAddress1`) *issuerAssignedId* must be a valid email address
// * `userName`, issuer_assigned_id must be a valid local part of an email address
// Supports $filter. 512 character limit.
string issuer_assigned_id = 3;
}
message PasswordProfile {
// The password for the user. This property is required when a user is created.
// It can be updated, but the user will be required to change the password on the next login.
// The password must satisfy minimum requirements as specified by the user’s passwordPolicies property. By default, a strong password is required.
string password = 1;
// The time when this account last changed their password.
google.protobuf.Timestamp last_password_change_date_time = 2;
// Specifies password policies for the user.
//This value is an enumeration with one possible value being “DisableStrongPassword”, which allows weaker passwords than the default policy to be specified.
// “DisablePasswordExpiration” can also be specified.
repeated string password_policies = 3;
// *true* if the user must change her password on the next login; otherwise false.
bool force_change_password_next_sign_in = 4;
// If *true*, at next sign-in, the user must perform a multi-factor authentication (MFA) before being forced to change their password. The behavior is identical to forceChangePasswordNextSignIn except that the user is required to first perform a multi-factor authentication before password change. After a password change, this property will be automatically reset to false. If not set, default is false.
bool force_change_password_next_sign_in_with_mfa = 5;
}
message ListGroupsRequest {
// Optional. The maximum number of groups to return in the response
int32 page_size = 1 [(google.api.field_behavior) = OPTIONAL];
// Optional. A pagination token returned from a previous call to `Get`
// that indicates from where search should continue
string page_token = 2 [(google.api.field_behavior) = OPTIONAL];
// Optional. Used to specify a subset of fields that should be
// returned by a get operation or modified by an update operation.
google.protobuf.FieldMask field_mask = 3;
// Optional. Search criteria used to select the groups to return.
// If no search criteria is specified then all groups will be
// returned
//
// TODO update query language
// Query expressions can be used to restrict results based upon
// the account properties where the operators `=`, `NOT`, `AND` and `OR`
// can be used along with the suffix wildcard symbol `*`.
//
// The string properties in a query expression should use escaped quotes
// for values that include whitespace to prevent unexpected behavior.
//
// Some example queries are:
//
// * Query `display_name=Th*` returns accounts whose display_name
// starts with "Th"
// * Query `display_name=\\"Test String\\"` returns groups with
// display names that include both "Test" and "String"
string query = 4 [(google.api.field_behavior) = OPTIONAL];
}
message ListGroupsResponse {
// The field name should match the noun "group" in the method name. There
// will be a maximum number of items returned based on the page_size field
// in the request
repeated Group groups = 1;
// Token to retrieve the next page of results, or empty if there are no
// more results in the list
string next_page_token = 2;
}
message GetGroupRequest {
string id = 1;
}
message CreateGroupRequest {
// The account resource to create
Group group = 1;
}
message UpdateGroupRequest {
// The group resource which replaces the resource on the server
Group group = 1;
// The update mask applies to the resource. For the `FieldMask` definition,
// see https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask
google.protobuf.FieldMask update_mask = 2;
}
message DeleteGroupRequest {
string id = 1;
}
message AddMemberRequest {
// The id of the group to add a member to
string group_id = 1;
// The account id to add
string account_id = 2;
}
message RemoveMemberRequest {
// The id of the group to remove a member from
string group_id = 1;
// The account id to remove
string account_id = 2;
}
message ListMembersRequest {
int32 page_size = 1 [(google.api.field_behavior) = OPTIONAL];
// Optional. A pagination token returned from a previous call to `Get`
// that indicates from where search should continue
string page_token = 2 [(google.api.field_behavior) = OPTIONAL];
// Optional. Used to specify a subset of fields that should be
// returned by a get operation or modified by an update operation.
google.protobuf.FieldMask field_mask = 3;
// Optional. Search criteria used to select the groups to return.
// If no search criteria is specified then all groups will be
// returned
//
// TODO update query language
// Query expressions can be used to restrict results based upon
// the account properties where the operators `=`, `NOT`, `AND` and `OR`
// can be used along with the suffix wildcard symbol `*`.
//
// The string properties in a query expression should use escaped quotes
// for values that include whitespace to prevent unexpected behavior.
//
// Some example queries are:
//
// * Query `display_name=Th*` returns accounts whose display_name
// starts with "Th"
// * Query `display_name=\\"Test String\\"` returns groups with
// display names that include both "Test" and "String"
string query = 4 [(google.api.field_behavior) = OPTIONAL];
// The id of the group to list members from
string id = 5;
}
message ListMembersResponse {
// The field name should match the noun "members" in the method name. There
// will be a maximum number of items returned based on the page_size field
// in the request
repeated Account members = 1;
// Token to retrieve the next page of results, or empty if there are no
// more results in the list
string next_page_token = 2;
}
message Group {
// The unique identifier for the group.
// Returned by default. Inherited from directoryObject. Key. Not nullable. Read-only.
string id = 1;
// groupofnames
// The display name for the group. This property is required when a group is created and cannot be cleared during updates.
// Returned by default. Supports $filter and $orderby.
// groupofnames MUST cn
string display_name = 2;
// groupofnames MUST/MAY member
// Users, contacts, and groups that are members of this group. HTTP Methods: GET (supported for all groups), POST (supported for security groups and mail-enabled security groups), DELETE (supported only for security groups) Read-only. Nullable.
// TODO accounts (users) only for now, we can add groups with the dedicated message using oneof construct later
repeated Account members = 3;
// groupofnames MAY businessCategory
// groupofnames MAY o
// groupofnames MAY ou
// groupofnames MAY owner, SINGLE-VALUE but there might be multiple owners
repeated Account owners = 4;
// An optional description for the group. Returned by default.
// groupofnames MAY description
string description = 5;
// groupofnames MAY seeAlso
// posixgroup
// used for exposing the user using ldap
// posixgroup MUST gidnumber
int64 gid_number = 6;
// posixgroup MAY authPassword
// posixgroup MAY userPassword
// posixgroup MAY memberUid -> groupofnames member
// posixgroup MAY description -> groupofnames
// Timestamp of when the group was created. The value cannot be modified and is automatically populated when the group is created
// Returned by default. Read-only.
google.protobuf.Timestamp created_date_time = 7;
// For some Azure Active Directory objects (user, group, application), if the object is deleted, it is first logically deleted, and this property is updated with the date and time when the object was deleted. Otherwise this property is null. If the object is restored, this property is updated to null.
// Returned by default. Read-only.
google.protobuf.Timestamp deleted_date_time = 8;
// Timestamp of when the group is set to expire. The value cannot be modified and is automatically populated when the group is created.
// Returned by default. Read-only.
google.protobuf.Timestamp expiration_date_time = 9;
// True if the group is not displayed in certain parts of the Outlook user interface:
// in the Address Book, in address lists for selecting message recipients, and in the Browse Groups dialog for searching groups; false otherwise. Default value is false.
// Returned only on $select.
bool hide_from_address_lists = 10;
// Specifies the visibility of an Office 365 group. Possible values are: Private, Public, or Hiddenmembership; blank values are treated as public. See group visibility options to learn more.
// Visibility can be set only when a group is created; it is not editable.
// Returned by default.
string visibility = 11;
// Field numbers in the range 16 through 2047 take two bytes. So you should reserve the field numbers 1 through 15 for very frequently occurring message elements. Remember to leave some room for frequently occurring elements that might be added in the future.
// properties for sync
// *true* if this group is synced from an on-premises directory;
// *false* if this group was originally synced from an on-premises directory but is no longer synced;
// null if this object has never been synced from an on-premises directory (default).
// Returned by default. Read-only. Supports $filter.
bool on_premises_sync_enabled = 20;
// This property is used to associate an on-premises LDAP user to the ocis account object.
// This property must be specified when creating a new user account in the Graph if you are using a federated domain for the user’s userPrincipalName (UPN) property.
// Important: The $ and _ characters cannot be used when specifying this property. Supports $filter.
string on_premises_immutable_id = 21;
// Contains the on-premises security identifier (SID) for the group that was synchronized from on-premises to the cloud. Returned by default. Read-only.
string on_premises_security_identifier = 22;
// Contains the on-premises LDAP `distinguished name` or `DN`.
// The property is only populated for customers who are synchronizing their on-premises directory to ocis-accounts. Read-only.
string on_premises_distinguished_name = 23;
// Contains the on-premises `samAccountName` synchronized from the on-premises directory.
// The property is only populated for customers who are synchronizing their on-premises directory to ocis-accounts. Returned by default. Read-only.
string on_premises_sam_account_name = 24;
// Contains the on-premises domain FQDN, also called dnsDomainName synchronized from the on-premises directory. The property is only populated for customers who are synchronizing their on-premises directory to Azure Active Directory via Azure AD Connect.
// Returned by default. Read-only.
string on_premises_domain_name = 25;
// Contains the on-premises netBios name synchronized from the on-premises directory. The property is only populated for customers who are synchronizing their on-premises directory to Azure Active Directory via Azure AD Connect.
// Returned by default. Read-only.
string on_premises_net_bios_name = 26;
// Indicates the last time at which the group was synced with the on-premises directory.
// Returned by default. Read-only. Supports $filter.
string on_premises_last_sync_date_time = 27;
// Errors when using synchronization during provisioning.
repeated OnPremisesProvisioningError on_premises_provisioning_errors = 28;
}
message OnPremisesProvisioningError {
// Category of the provisioning error. Note: Currently, there is only one possible value. Possible value: PropertyConflict - indicates a property value is not unique. Other objects contain the same value for the property.
string category = 1;
// The date and time at which the error occurred.
google.protobuf.Timestamp occurred_date_time = 2;
// Name of the directory property causing the error. Current possible values: UserPrincipalName or ProxyAddress
string property_causing_error = 3;
// Value of the property causing the error.
string value = 4;
}
File diff suppressed because it is too large. Load diff
-1
View File
@@ -1 +0,0 @@
checks = ["all", "-ST1003", "-ST1000", "-SA1019"]
-85
View File
@@ -1,85 +0,0 @@
package grpc
import (
"context"
"github.com/micro/cli/v2"
"github.com/owncloud/ocis/accounts/pkg/config"
"github.com/owncloud/ocis/accounts/pkg/metrics"
svc "github.com/owncloud/ocis/accounts/pkg/service/v0"
"github.com/owncloud/ocis/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 {
Name string
Logger log.Logger
Context context.Context
Config *config.Config
Metrics *metrics.Metrics
Flags []cli.Flag
Handler *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
}
}
// Metrics provides a function to set the metrics option.
func Metrics(val *metrics.Metrics) Option {
return func(o *Options) {
o.Metrics = 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...)
}
}
// Handler provides a function to set the handler option.
func Handler(val *svc.Service) Option {
return func(o *Options) {
o.Handler = val
}
}
-35
View File
@@ -1,35 +0,0 @@
package grpc
import (
"github.com/owncloud/ocis/accounts/pkg/proto/v0"
"github.com/owncloud/ocis/ocis-pkg/service/grpc"
)
// Server initializes a new go-micro service ready to run
func Server(opts ...Option) grpc.Service {
options := newOptions(opts...)
handler := options.Handler
service := grpc.NewService(
grpc.Name(options.Config.Server.Name),
grpc.Context(options.Context),
grpc.Address(options.Config.GRPC.Addr),
grpc.Namespace(options.Config.GRPC.Namespace),
grpc.Logger(options.Logger),
grpc.Flags(options.Flags...),
grpc.Version(options.Config.Server.Version),
)
if err := proto.RegisterAccountsServiceHandler(service.Server(), handler); err != nil {
options.Logger.Fatal().Err(err).Msg("could not register service handler")
}
if err := proto.RegisterGroupsServiceHandler(service.Server(), handler); err != nil {
options.Logger.Fatal().Err(err).Msg("could not register groups handler")
}
if err := proto.RegisterIndexServiceHandler(service.Server(), handler); err != nil {
options.Logger.Fatal().Err(err).Msg("could not register index handler")
}
service.Init()
return service
}
-85
View File
@@ -1,85 +0,0 @@
package http
import (
"context"
"github.com/micro/cli/v2"
"github.com/owncloud/ocis/accounts/pkg/config"
"github.com/owncloud/ocis/accounts/pkg/metrics"
svc "github.com/owncloud/ocis/accounts/pkg/service/v0"
"github.com/owncloud/ocis/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 {
Name string
Logger log.Logger
Context context.Context
Config *config.Config
Metrics *metrics.Metrics
Flags []cli.Flag
Handler *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
}
}
// Metrics provides a function to set the metrics option.
func Metrics(val *metrics.Metrics) Option {
return func(o *Options) {
o.Metrics = 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...)
}
}
// Handler provides a function to set the handler option.
func Handler(val *svc.Service) Option {
return func(o *Options) {
o.Handler = val
}
}
-72
View File
@@ -1,72 +0,0 @@
package http
import (
"github.com/go-chi/chi"
"github.com/owncloud/ocis/accounts/pkg/assets"
"github.com/owncloud/ocis/accounts/pkg/proto/v0"
"github.com/owncloud/ocis/accounts/pkg/version"
"github.com/owncloud/ocis/ocis-pkg/account"
"github.com/owncloud/ocis/ocis-pkg/middleware"
"github.com/owncloud/ocis/ocis-pkg/service/http"
)
// Server initializes the http service and server.
func Server(opts ...Option) http.Service {
options := newOptions(opts...)
handler := options.Handler
service := http.NewService(
http.Logger(options.Logger),
http.Name(options.Name),
http.Version(options.Config.Server.Version),
http.Address(options.Config.HTTP.Addr),
http.Namespace(options.Config.HTTP.Namespace),
http.Context(options.Context),
http.Flags(options.Flags...),
)
mux := chi.NewMux()
mux.Use(middleware.RealIP)
mux.Use(middleware.RequestID)
mux.Use(middleware.NoCache)
mux.Use(middleware.Cors)
mux.Use(middleware.Secure)
mux.Use(middleware.ExtractAccountUUID(
account.Logger(options.Logger),
account.JWTSecret(options.Config.TokenManager.JWTSecret)),
)
mux.Use(middleware.Version(
options.Name,
version.String,
))
mux.Use(middleware.Logger(
options.Logger,
))
mux.Use(middleware.Static(
options.Config.HTTP.Root,
assets.New(
assets.Logger(options.Logger),
assets.Config(options.Config),
),
options.Config.HTTP.CacheTTL,
))
mux.Route(options.Config.HTTP.Root, func(r chi.Router) {
proto.RegisterAccountsServiceWeb(r, handler)
proto.RegisterGroupsServiceWeb(r, handler)
})
service.Handle(
"/",
mux,
)
if err := service.Init(); err != nil {
panic(err)
}
return service
}
-839
View File
@@ -1,839 +0,0 @@
package service
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"github.com/owncloud/ocis/ocis-pkg/sync"
"golang.org/x/crypto/bcrypt"
"path"
"regexp"
"strconv"
"time"
"github.com/owncloud/ocis/ocis-pkg/log"
"github.com/gofrs/uuid"
p "github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes/empty"
fieldmask_utils "github.com/mennanov/fieldmask-utils"
merrors "github.com/micro/go-micro/v2/errors"
"github.com/micro/go-micro/v2/metadata"
"github.com/owncloud/ocis/accounts/pkg/proto/v0"
"github.com/owncloud/ocis/accounts/pkg/storage"
"github.com/owncloud/ocis/ocis-pkg/middleware"
"github.com/owncloud/ocis/ocis-pkg/roles"
settings "github.com/owncloud/ocis/settings/pkg/proto/v0"
settings_svc "github.com/owncloud/ocis/settings/pkg/service/v0"
"github.com/rs/zerolog"
"google.golang.org/genproto/protobuf/field_mask"
"google.golang.org/protobuf/types/known/timestamppb"
)
// passwordValidCache caches basic auth password validations
var passwordValidCache = sync.NewCache(1024)
// passwordValidCacheExpiration defines the entry lifetime
const passwordValidCacheExpiration = 10 * time.Minute
// an auth request is currently hardcoded and has to match this regex
// login eq \"teddy\" and password eq \"F&1!b90t111!\"
var authQuery = regexp.MustCompile(`^login eq '(.*)' and password eq '(.*)'$`) // TODO how is ' escaped in the password?
func (s Service) expandMemberOf(a *proto.Account) {
if a == nil {
return
}
expanded := []*proto.Group{}
for i := range a.MemberOf {
g := &proto.Group{}
// TODO resolve by name, when a create or update is issued they may not have an id? fall back to searching the group id in the index?
if err := s.repo.LoadGroup(context.Background(), a.MemberOf[i].Id, g); err == nil {
g.Members = nil // always hide members when expanding
expanded = append(expanded, g)
} else {
// log errors but continue execution for now
s.log.Error().Err(err).Str("id", a.MemberOf[i].Id).Msg("could not load group")
}
}
a.MemberOf = expanded
}
func (s Service) hasAccountManagementPermissions(ctx context.Context) bool {
// get roles from context
roleIDs, ok := roles.ReadRoleIDsFromContext(ctx)
if !ok {
/**
* FIXME: with this we are skipping permission checks on all requests that are coming in without roleIDs in the
* metadata context. This is a huge security impairment, as that's the case not only for grpc requests but also
* for unauthenticated http requests and http requests coming in without hitting the ocis-proxy first.
*/
// TODO add system role for internal requests.
// - at least the proxy needs to look up account info
// - glauth needs to make bind requests
// tracked as OCIS-454
return true
}
// check if permission is present in roles of the authenticated account
return s.RoleManager.FindPermissionByID(ctx, roleIDs, AccountManagementPermissionID) != nil
}
func (s Service) hasSelfManagementPermissions(ctx context.Context) bool {
// get roles from context
roleIDs, ok := roles.ReadRoleIDsFromContext(ctx)
if !ok {
return false
}
// check if permission is present in roles of the authenticated account
return s.RoleManager.FindPermissionByID(ctx, roleIDs, SelfManagementPermissionID) != nil
}
// serviceUserToIndex temporarily adds a service user to the index, which is supposed to be removed before the lock on the handler function is released
func (s Service) serviceUserToIndex() (teardownServiceUser func()) {
if s.Config.ServiceUser.Username != "" && s.Config.ServiceUser.UUID != "" {
_, err := s.index.Add(s.getInMemoryServiceUser())
if err != nil {
s.log.Logger.Err(err).Msg("service user was configured but failed to be added to the index")
} else {
return func() {
_ = s.index.Delete(s.getInMemoryServiceUser())
}
}
}
return func() {}
}
func (s Service) getInMemoryServiceUser() proto.Account {
return proto.Account{
AccountEnabled: true,
Id: s.Config.ServiceUser.UUID,
PreferredName: s.Config.ServiceUser.Username,
OnPremisesSamAccountName: s.Config.ServiceUser.Username,
DisplayName: s.Config.ServiceUser.Username,
UidNumber: s.Config.ServiceUser.UID,
GidNumber: s.Config.ServiceUser.GID,
}
}
// ListAccounts implements the AccountsServiceHandler interface
// the query contains account properties
func (s Service) ListAccounts(ctx context.Context, in *proto.ListAccountsRequest, out *proto.ListAccountsResponse) (err error) {
hasSelf := s.hasSelfManagementPermissions(ctx)
hasManagement := s.hasAccountManagementPermissions(ctx)
if !hasSelf && !hasManagement {
return merrors.Forbidden(s.id, "no permission for ListAccounts")
}
onlySelf := hasSelf && !hasManagement
teardownServiceUser := s.serviceUserToIndex()
defer teardownServiceUser()
match, authRequest := getAuthQueryMatch(in.Query)
if authRequest {
password := match[2]
if len(password) == 0 {
return merrors.Unauthorized(s.id, "account not found or invalid credentials")
}
ids, err := s.index.FindBy(&proto.Account{}, "OnPremisesSamAccountName", match[1])
if err != nil || len(ids) > 1 {
return merrors.Unauthorized(s.id, "account not found or invalid credentials")
}
if len(ids) == 0 {
ids, err = s.index.FindBy(&proto.Account{}, "Mail", match[1])
if err != nil || len(ids) != 1 {
return merrors.Unauthorized(s.id, "account not found or invalid credentials")
}
}
a := &proto.Account{}
err = s.repo.LoadAccount(ctx, ids[0], a)
if err != nil || a.PasswordProfile == nil || len(a.PasswordProfile.Password) == 0 {
return merrors.Unauthorized(s.id, "account not found or invalid credentials")
}
// isPasswordValid uses bcrypt.CompareHashAndPassword which is slow by design.
// if every request that matches authQuery regex needs to do this step over and over again,
// this is secure but also slow. In this implementation we keep it same secure but increase the speed.
//
// flow:
// - request comes in
// - it creates a sha256 based on found account PasswordProfile.LastPasswordChangeDateTime and requested password (v)
// - it checks if the cache already contains an entry that matches found account Id // account PasswordProfile.LastPasswordChangeDateTime (k)
// - if no entry exists it runs the bcrypt.CompareHashAndPassword as before and if everything is ok it stores the
// result by the (k) as key and (v) as value. If not it errors
// - if a entry is found it checks if the given value matches (v). If it doesnt match, the cache entry gets removed
// and it errors.
{
var suspicious bool
kh := sha256.New()
kh.Write([]byte(a.Id))
k := hex.EncodeToString(kh.Sum([]byte(a.PasswordProfile.LastPasswordChangeDateTime.String())))
vh := sha256.New()
vh.Write([]byte(a.PasswordProfile.Password))
v := vh.Sum([]byte(password))
e := passwordValidCache.Load(k)
if e == nil {
suspicious = !isPasswordValid(s.log, a.PasswordProfile.Password, password)
} else if !bytes.Equal(e.V.([]byte), v) {
suspicious = true
}
if suspicious {
passwordValidCache.Delete(k)
return merrors.Unauthorized(s.id, "account not found or invalid credentials")
}
if e == nil {
passwordValidCache.Store(k, v, time.Now().Add(passwordValidCacheExpiration))
}
}
a.PasswordProfile.Password = ""
out.Accounts = []*proto.Account{a}
return nil
}
if onlySelf {
// limit list to own account id
if aid, ok := metadata.Get(ctx, middleware.AccountID); ok {
in.Query = "id eq '" + aid + "'"
} else {
return merrors.InternalServerError(s.id, "account id not in context")
}
}
if in.Query == "" {
err = s.repo.LoadAccounts(ctx, &out.Accounts)
if err != nil {
s.log.Err(err).Msg("failed to load all accounts from storage")
return merrors.InternalServerError(s.id, "failed to load all accounts")
}
for i := range out.Accounts {
a := out.Accounts[i]
// TODO add groups only if requested
// if in.FieldMask ...
s.expandMemberOf(a)
if a.PasswordProfile != nil {
a.PasswordProfile.Password = ""
}
}
return nil
}
searchResults, err := s.findAccountsByQuery(ctx, in.Query)
out.Accounts = make([]*proto.Account, 0, len(searchResults))
for _, hit := range searchResults {
a := &proto.Account{}
if hit == s.Config.ServiceUser.UUID {
acc := s.getInMemoryServiceUser()
a = &acc
} else if err = s.repo.LoadAccount(ctx, hit, a); err != nil {
s.log.Error().Err(err).Str("account", hit).Msg("could not load account, skipping")
continue
}
s.debugLogAccount(a).Msg("found account")
// TODO add groups if requested
// if in.FieldMask ...
s.expandMemberOf(a)
// remove password before returning
if a.PasswordProfile != nil {
a.PasswordProfile.Password = ""
}
out.Accounts = append(out.Accounts, a)
}
return
}
func (s Service) findAccountsByQuery(ctx context.Context, query string) ([]string, error) {
return s.index.Query(&proto.Account{}, query)
}
// GetAccount implements the AccountsServiceHandler interface
func (s Service) GetAccount(ctx context.Context, in *proto.GetAccountRequest, out *proto.Account) (err error) {
hasSelf := s.hasSelfManagementPermissions(ctx)
hasManagement := s.hasAccountManagementPermissions(ctx)
if !hasSelf && !hasManagement {
return merrors.Forbidden(s.id, "no permission for GetAccount")
}
onlySelf := hasSelf && !hasManagement
var id string
if id, err = cleanupID(in.Id); err != nil {
return merrors.InternalServerError(s.id, "could not clean up account id: %v", err.Error())
}
if onlySelf {
// limit get to own account id
if aid, ok := metadata.Get(ctx, middleware.AccountID); ok {
if id != aid {
return merrors.Forbidden(s.id, "no permission for GetAccount of another user")
}
} else {
return merrors.InternalServerError(s.id, "account id not in context")
}
}
if err = s.repo.LoadAccount(ctx, id, out); err != nil {
if storage.IsNotFoundErr(err) {
return merrors.NotFound(s.id, "account not found: %v", err.Error())
}
s.log.Error().Err(err).Str("id", id).Msg("could not load account")
return merrors.InternalServerError(s.id, "could not load account: %v", err.Error())
}
s.debugLogAccount(out).Msg("found account")
// TODO add groups if requested
// if in.FieldMask ...
s.expandMemberOf(out)
// remove password
if out.PasswordProfile != nil {
out.PasswordProfile.Password = ""
}
return
}
// CreateAccount implements the AccountsServiceHandler interface
func (s Service) CreateAccount(ctx context.Context, in *proto.CreateAccountRequest, out *proto.Account) (err error) {
if !s.hasAccountManagementPermissions(ctx) {
return merrors.Forbidden(s.id, "no permission for CreateAccount")
}
var id string
if in.Account == nil {
return merrors.InternalServerError(s.id, "invalid account: empty")
}
p.Merge(out, in.Account)
if out.Id == "" {
out.Id = uuid.Must(uuid.NewV4()).String()
}
if err = validateAccount(s.id, out); err != nil {
return err
}
if id, err = cleanupID(out.Id); err != nil {
return merrors.InternalServerError(s.id, "could not clean up account id: %v", err.Error())
}
exists, err := s.accountExists(ctx, out.PreferredName, out.Mail, out.Id)
if err != nil {
return merrors.InternalServerError(s.id, "could not check if account exists: %v", err.Error())
}
if exists {
return merrors.Conflict(s.id, "account already exists")
}
if out.PasswordProfile != nil {
if out.PasswordProfile.Password != "" {
// encrypt password
hashed, err := bcrypt.GenerateFromPassword([]byte(in.Account.PasswordProfile.Password), s.Config.Server.HashDifficulty)
if err != nil {
s.log.Error().Err(err).Str("id", id).Msg("could not hash password")
return merrors.InternalServerError(s.id, "could not hash password: %v", err.Error())
}
out.PasswordProfile.Password = string(hashed)
in.Account.PasswordProfile.Password = ""
}
if err := passwordPoliciesValid(out.PasswordProfile.PasswordPolicies); err != nil {
return merrors.BadRequest(s.id, "%s", err)
}
}
// extract group id
// TODO groups should be ignored during create, use groups.AddMember? return error?
// write and index account - note: don't do anything else in between!
if err = s.repo.WriteAccount(ctx, out); err != nil {
s.log.Error().Err(err).Str("id", id).Msg("could not persist new account")
s.debugLogAccount(out).Msg("could not persist new account")
return merrors.InternalServerError(s.id, "could not persist new account: %v", err.Error())
}
indexResults, err := s.index.Add(out)
if err != nil {
s.rollbackCreateAccount(ctx, out)
return merrors.Conflict(s.id, "Account already exists %v", err.Error())
}
s.log.Debug().Interface("account", out).Msg("account after indexing")
for _, r := range indexResults {
if r.Field == "UidNumber" {
id, err := strconv.Atoi(path.Base(r.Value))
if err != nil {
s.rollbackCreateAccount(ctx, out)
return err
}
out.UidNumber = int64(id)
break
}
}
if out.GidNumber == 0 {
out.GidNumber = userDefaultGID
}
r := proto.ListGroupsResponse{}
err = s.ListGroups(ctx, &proto.ListGroupsRequest{}, &r)
if err != nil {
// rollback account creation
return err
}
for _, group := range r.Groups {
if group.GidNumber == out.GidNumber {
out.MemberOf = append(out.MemberOf, group)
}
}
//acc.MemberOf = append(acc.MemberOf, &group)
if err := s.repo.WriteAccount(context.Background(), out); err != nil {
return err
}
if out.PasswordProfile != nil {
out.PasswordProfile.Password = ""
}
// TODO: assign user role to all new users for now, as create Account request does not have any role field
if s.RoleService == nil {
return merrors.InternalServerError(s.id, "could not assign role to account: roleService not configured")
}
if _, err = s.RoleService.AssignRoleToUser(ctx, &settings.AssignRoleToUserRequest{
AccountUuid: out.Id,
RoleId: settings_svc.BundleUUIDRoleUser,
}); err != nil {
return merrors.InternalServerError(s.id, "could not assign role to account: %v", err.Error())
}
return
}
// rollbackCreateAccount tries to rollback changes made by `CreateAccount` if parts of it failed.
func (s Service) rollbackCreateAccount(ctx context.Context, acc *proto.Account) {
err := s.index.Delete(acc)
if err != nil {
s.log.Err(err).Msg("failed to rollback account from indices")
}
err = s.repo.DeleteAccount(ctx, acc.Id)
if err != nil {
s.log.Err(err).Msg("failed to rollback account from repo")
}
}
// UpdateAccount implements the AccountsServiceHandler interface
// read only fields are ignored
// TODO how can we unset specific values? using the update mask
func (s Service) UpdateAccount(ctx context.Context, in *proto.UpdateAccountRequest, out *proto.Account) (err error) {
hasSelf := s.hasSelfManagementPermissions(ctx)
hasManagement := s.hasAccountManagementPermissions(ctx)
if !hasSelf && !hasManagement {
return merrors.Forbidden(s.id, "no permission for UpdateAccount")
}
onlySelf := hasSelf && !hasManagement
var id string
if in.Account == nil {
return merrors.BadRequest(s.id, "account missing")
}
if in.Account.Id == "" {
return merrors.BadRequest(s.id, "account id missing")
}
if id, err = cleanupID(in.Account.Id); err != nil {
return merrors.InternalServerError(s.id, "could not clean up account id: %v", err.Error())
}
if onlySelf {
// limit update to own account id
if aid, ok := metadata.Get(ctx, middleware.AccountID); ok {
if id != aid {
return merrors.Forbidden(s.id, "no permission to UpdateAccount of another user")
}
} else {
return merrors.InternalServerError(s.id, "account id not in context")
}
}
if err = s.repo.LoadAccount(ctx, id, out); err != nil {
if storage.IsNotFoundErr(err) {
return merrors.NotFound(s.id, "account not found: %v", err.Error())
}
s.log.Error().Err(err).Str("id", id).Msg("could not load account")
return merrors.InternalServerError(s.id, "could not load account: %v", err.Error())
}
t := time.Now()
tsnow := &timestamppb.Timestamp{
Seconds: t.Unix(),
Nanos: int32(t.Nanosecond()),
}
var validMask fieldmask_utils.FieldFilterContainer
if onlySelf {
if validMask, err = validateUpdate(in.UpdateMask, selfUpdatableAccountPaths); err != nil {
return merrors.BadRequest(s.id, "%s", err)
}
} else {
if validMask, err = validateUpdate(in.UpdateMask, updatableAccountPaths); err != nil {
return merrors.BadRequest(s.id, "%s", err)
}
}
if _, exists := validMask.Filter("PreferredName"); exists {
if err = validateAccountPreferredName(s.id, in.Account); err != nil {
return err
}
}
if _, exists := validMask.Filter("OnPremisesSamAccountName"); exists {
if err = validateAccountOnPremisesSamAccountName(s.id, in.Account); err != nil {
return err
}
}
if _, exists := validMask.Filter("Mail"); exists {
if in.Account.Mail != "" {
if err = validateAccountEmail(s.id, in.Account); err != nil {
return err
}
}
}
if err := fieldmask_utils.StructToStruct(validMask, in.Account, out); err != nil {
return merrors.InternalServerError(s.id, "%s", err)
}
if in.Account.PasswordProfile != nil {
if out.PasswordProfile == nil {
out.PasswordProfile = &proto.PasswordProfile{}
}
if in.Account.PasswordProfile.Password != "" {
// encrypt password
hashed, err := bcrypt.GenerateFromPassword([]byte(in.Account.PasswordProfile.Password), s.Config.Server.HashDifficulty)
if err != nil {
in.Account.PasswordProfile.Password = ""
s.log.Error().Err(err).Str("id", id).Msg("could not hash password")
return merrors.InternalServerError(s.id, "could not hash password: %v", err.Error())
}
out.PasswordProfile.Password = string(hashed)
in.Account.PasswordProfile.Password = ""
}
if err := passwordPoliciesValid(in.Account.PasswordProfile.PasswordPolicies); err != nil {
return merrors.BadRequest(s.id, "%s", err)
}
// lastPasswordChangeDateTime calculated, see password
out.PasswordProfile.LastPasswordChangeDateTime = tsnow
}
// out.RefreshTokensValidFromDateTime TODO use to invalidate all existing sessions
// out.SignInSessionsValidFromDateTime TODO use to invalidate all existing sessions
// ... TODO on prem for sync
if out.ExternalUserState != in.Account.ExternalUserState {
out.ExternalUserState = in.Account.ExternalUserState
out.ExternalUserStateChangeDateTime = tsnow
}
// We need to reload the old account state to be able to compute the update
old := &proto.Account{}
if err = s.repo.LoadAccount(ctx, id, old); err != nil {
s.log.Error().Err(err).Str("id", out.Id).Msg("could not load old account representation during update, maybe the account got deleted meanwhile?")
return merrors.InternalServerError(s.id, "could not load current account for update: %v", err.Error())
}
if err = s.repo.WriteAccount(ctx, out); err != nil {
s.log.Error().Err(err).Str("id", out.Id).Msg("could not persist updated account")
return merrors.InternalServerError(s.id, "could not persist updated account: %v", err.Error())
}
if err = s.index.Update(old, out); err != nil {
s.log.Error().Err(err).Str("id", id).Msg("could not index new account")
return merrors.InternalServerError(s.id, "could not index updated account: %v", err.Error())
}
// remove password
if out.PasswordProfile != nil {
out.PasswordProfile.Password = ""
}
return
}
// whitelist of all paths/fields which can be updated by users themself
var selfUpdatableAccountPaths = map[string]struct{}{
"DisplayName": {},
"Description": {},
"Mail": {}, // read only?,
"PasswordProfile.Password": {},
}
// whitelist of all paths/fields which can be updated by clients
var updatableAccountPaths = map[string]struct{}{
"AccountEnabled": {},
"IsResourceAccount": {},
"Identities": {},
"DisplayName": {},
"PreferredName": {},
"UidNumber": {},
"GidNumber": {},
"Description": {},
"Mail": {}, // read only?,
"PasswordProfile.Password": {},
"PasswordProfile.PasswordPolicies": {},
"PasswordProfile.ForceChangePasswordNextSignIn": {},
"PasswordProfile.ForceChangePasswordNextSignInWithMfa": {},
"OnPremisesSyncEnabled": {},
"OnPremisesSamAccountName": {},
}
// DeleteAccount implements the AccountsServiceHandler interface
func (s Service) DeleteAccount(ctx context.Context, in *proto.DeleteAccountRequest, out *empty.Empty) (err error) {
if !s.hasAccountManagementPermissions(ctx) {
return merrors.Forbidden(s.id, "no permission for DeleteAccount")
}
var id string
if id, err = cleanupID(in.Id); err != nil {
return merrors.InternalServerError(s.id, "could not clean up account id: %v", err.Error())
}
a := &proto.Account{}
if err = s.repo.LoadAccount(ctx, id, a); err != nil {
if storage.IsNotFoundErr(err) {
return merrors.NotFound(s.id, "account not found: %v", err.Error())
}
s.log.Error().Err(err).Str("id", id).Msg("could not load account")
return merrors.InternalServerError(s.id, "could not load account: %v", err.Error())
}
// delete member relationship in groups
for i := range a.MemberOf {
err = s.RemoveMember(ctx, &proto.RemoveMemberRequest{
GroupId: a.MemberOf[i].Id,
AccountId: id,
}, a.MemberOf[i])
if err != nil {
s.log.Error().Err(err).Str("accountid", id).Str("groupid", a.MemberOf[i].Id).Msg("could not remove group member, skipping")
}
}
if err = s.repo.DeleteAccount(ctx, id); err != nil {
if storage.IsNotFoundErr(err) {
return merrors.NotFound(s.id, "account not found: %v", err.Error())
}
s.log.Error().Err(err).Str("id", id).Str("accountId", id).Msg("could not remove account")
return merrors.InternalServerError(s.id, "could not remove account: %v", err.Error())
}
if err = s.index.Delete(a); err != nil {
s.log.Error().Err(err).Str("id", id).Str("accountId", id).Msg("could not remove account from index")
return merrors.InternalServerError(s.id, "could not remove account from index: %v", err.Error())
}
s.log.Info().Str("id", id).Msg("deleted account")
return
}
func validateAccount(serviceID string, a *proto.Account) error {
if err := validateAccountPreferredName(serviceID, a); err != nil {
return err
}
if err := validateAccountOnPremisesSamAccountName(serviceID, a); err != nil {
return err
}
if err := validateAccountEmail(serviceID, a); err != nil {
return err
}
return nil
}
func validateAccountPreferredName(serviceID string, a *proto.Account) error {
if !isValidUsername(a.PreferredName) {
return merrors.BadRequest(serviceID, "preferred_name '%s' must be at least the local part of an email", a.PreferredName)
}
return nil
}
func validateAccountOnPremisesSamAccountName(serviceID string, a *proto.Account) error {
if !isValidUsername(a.OnPremisesSamAccountName) {
return merrors.BadRequest(serviceID, "on_premises_sam_account_name '%s' must be at least the local part of an email", a.OnPremisesSamAccountName)
}
return nil
}
func validateAccountEmail(serviceID string, a *proto.Account) error {
if !isValidEmail(a.Mail) {
return merrors.BadRequest(serviceID, "mail '%s' must be a valid email", a.Mail)
}
return nil
}
// We want to allow email addresses as usernames so they show up when using them in ACLs on storages that allow intergration with our glauth LDAP service
// so we are adding a few restrictions from https://stackoverflow.com/questions/6949667/what-are-the-real-rules-for-linux-usernames-on-centos-6-and-rhel-6
// names should not start with numbers
var usernameRegex = regexp.MustCompile("^[a-zA-Z_][a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]*(@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)*$")
func isValidUsername(e string) bool {
if len(e) < 1 && len(e) > 254 {
return false
}
return usernameRegex.MatchString(e)
}
// regex from https://www.w3.org/TR/2016/REC-html51-20161101/sec-forms.html#valid-e-mail-address
var emailRegex = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
func isValidEmail(e string) bool {
if len(e) < 3 && len(e) > 254 {
return false
}
return emailRegex.MatchString(e)
}
const (
policyDisableStrongPassword = "DisableStrongPassword"
policyDisablePasswordExpiration = "DisablePasswordExpiration"
)
func passwordPoliciesValid(policies []string) error {
for _, v := range policies {
if v != policyDisableStrongPassword && v != policyDisablePasswordExpiration {
return fmt.Errorf("invalid password-policy %s", v)
}
}
return nil
}
// validateUpdate takes a update field-mask and validates it against a whitelist of updatable paths.
// Returns a FieldFilter on success which can be passed to the fieldmask_utils..StructToStruct. An error is returned
// if the mask tries to update no whitelisted fields.
//
// Given an empty or nil mask we assume that the client wants to update all whitelisted fields.
//
func validateUpdate(mask *field_mask.FieldMask, updatablePaths map[string]struct{}) (fieldmask_utils.FieldFilterContainer, error) {
nop := func(s string) string { return s }
// Assume that the client wants to update all updatable path if
// no field-mask is given, so we create a mask with all paths
if mask == nil || len(mask.Paths) == 0 {
paths := make([]string, 0, len(updatablePaths))
for fieldName := range updatablePaths {
paths = append(paths, fieldName)
}
return fieldmask_utils.MaskFromPaths(paths, nop)
}
// Check that only allowed fields are updated
for _, v := range mask.Paths {
if _, ok := updatablePaths[v]; !ok {
return nil, fmt.Errorf("can not update field %s, either unknown or readonly", v)
}
}
return fieldmask_utils.MaskFromPaths(mask.Paths, nop)
}
// debugLogAccount returns a debug-log event with detailed account-info, and filtered password data
func (s Service) debugLogAccount(a *proto.Account) *zerolog.Event {
return s.log.Debug().Fields(map[string]interface{}{
"Id": a.Id,
"Mail": a.Mail,
"DisplayName": a.DisplayName,
"AccountEnabled": a.AccountEnabled,
"IsResourceAccount": a.IsResourceAccount,
"Identities": a.Identities,
"PreferredName": a.PreferredName,
"UidNumber": a.UidNumber,
"GidNumber": a.GidNumber,
"Description": a.Description,
"OnPremisesSyncEnabled": a.OnPremisesSyncEnabled,
"OnPremisesSamAccountName": a.OnPremisesSamAccountName,
"OnPremisesUserPrincipalName": a.OnPremisesUserPrincipalName,
"OnPremisesSecurityIdentifier": a.OnPremisesSecurityIdentifier,
"OnPremisesDistinguishedName": a.OnPremisesDistinguishedName,
"OnPremisesLastSyncDateTime": a.OnPremisesLastSyncDateTime,
"MemberOf": a.MemberOf,
"CreatedDateTime": a.CreatedDateTime,
"DeletedDateTime": a.DeletedDateTime,
})
}
func (s Service) accountExists(ctx context.Context, username, mail, id string) (exists bool, err error) {
var ids []string
ids, err = s.index.FindBy(&proto.Account{}, "preferred_name", username)
if err != nil {
return false, err
}
if len(ids) > 0 {
return true, nil
}
ids, err = s.index.FindBy(&proto.Account{}, "on_premises_sam_account_name", username)
if err != nil {
return false, err
}
if len(ids) > 0 {
return true, nil
}
ids, err = s.index.FindBy(&proto.Account{}, "mail", mail)
if err != nil {
return false, err
}
if len(ids) > 0 {
return true, nil
}
a := &proto.Account{}
err = s.repo.LoadAccount(ctx, id, a)
if err == nil {
return true, nil
}
if !storage.IsNotFoundErr(err) {
return true, err
}
return false, nil
}
func getAuthQueryMatch(query string) (match []string, authRequest bool) {
match = authQuery.FindStringSubmatch(query)
return match, len(match) == 3
}
func isPasswordValid(logger log.Logger, hash string, pwd string) (ok bool) {
defer func() {
if r := recover(); r != nil {
logger.Error().Err(fmt.Errorf("%s", r)).Str("hash", hash).Msg("password lib panicked")
}
}()
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(pwd)) == nil
}
@@ -1,366 +0,0 @@
package service
import (
"context"
"encoding/json"
"log"
"net/http"
"os"
"testing"
"time"
"github.com/golang/protobuf/ptypes/empty"
"github.com/micro/go-micro/v2/client"
merrors "github.com/micro/go-micro/v2/errors"
"github.com/micro/go-micro/v2/metadata"
"github.com/owncloud/ocis/accounts/pkg/config"
"github.com/owncloud/ocis/accounts/pkg/proto/v0"
olog "github.com/owncloud/ocis/ocis-pkg/log"
"github.com/owncloud/ocis/ocis-pkg/middleware"
"github.com/owncloud/ocis/ocis-pkg/roles"
settings "github.com/owncloud/ocis/settings/pkg/proto/v0"
ssvc "github.com/owncloud/ocis/settings/pkg/service/v0"
"github.com/stretchr/testify/assert"
)
const dataPath = "/var/tmp/ocis-accounts-tests"
var (
roleServiceMock settings.RoleService
s *Service
)
func init() {
cfg := config.New()
cfg.Server.Name = "accounts"
cfg.Repo.Disk.Path = dataPath
logger := olog.NewLogger(olog.Color(true), olog.Pretty(true))
roleServiceMock = buildRoleServiceMock()
roleManager := roles.NewManager(
roles.Logger(logger),
roles.RoleService(roleServiceMock),
roles.CacheTTL(time.Hour),
roles.CacheSize(1024),
)
s, _ = New(
Logger(logger),
Config(cfg),
RoleService(roleServiceMock),
RoleManager(&roleManager),
)
}
func setup() (teardown func()) {
return func() {
if err := os.RemoveAll(dataPath); err != nil {
log.Printf("could not delete data root: %s", dataPath)
} else {
log.Println("data root deleted")
}
}
}
// TestPermissionsListAccounts checks permission handling on ListAccounts
func TestPermissionsListAccounts(t *testing.T) {
var scenarios = []struct {
name string
roleIDs []string
query string
permissionError error
}{
// TODO: remove this test when https://github.com/owncloud/ocis/accounts/pull/111 is merged
// replace with two tests:
// 1: "ListAccounts fails with 403 when roleIDs don't exist in context"
// 2: "ListAccounts fails with 403 when ('no admin role in context' AND 'empty query')"
{
"ListAccounts succeeds when no roleIDs in context",
nil,
"",
nil,
},
{
"ListAccounts fails when no admin roleID in context",
[]string{ssvc.BundleUUIDRoleUser, ssvc.BundleUUIDRoleGuest},
"",
merrors.Forbidden(s.id, "no permission for ListAccounts"),
},
{
"ListAccounts succeeds when admin roleID in context",
[]string{ssvc.BundleUUIDRoleAdmin},
"",
nil,
},
}
for _, scenario := range scenarios {
t.Run(scenario.name, func(t *testing.T) {
teardown := setup()
defer teardown()
ctx := buildTestCtx(t, scenario.roleIDs)
request := &proto.ListAccountsRequest{
Query: scenario.query,
}
response := &proto.ListAccountsResponse{}
err := s.ListAccounts(ctx, request, response)
if scenario.permissionError != nil {
assert.Equal(t, scenario.permissionError, err)
} else if err != nil {
// we are only checking permissions here, so just check that the error code is not 403
merr := merrors.FromError(err)
assert.NotEqual(t, http.StatusForbidden, merr.GetCode())
}
})
}
}
// TestPermissionsGetAccount checks permission handling on GetAccount
// TODO: remove this test function entirely, when https://github.com/owncloud/ocis/accounts/pull/111 is merged. GetAccount will not have permission checks for the time being.
func TestPermissionsGetAccount(t *testing.T) {
var scenarios = []struct {
name string
roleIDs []string
permissionError error
}{
{
"GetAccount succeeds when no role IDs in context",
nil,
nil,
},
{
"GetAccount fails when no admin roleID in context",
[]string{ssvc.BundleUUIDRoleUser, ssvc.BundleUUIDRoleGuest},
merrors.Forbidden(s.id, "no permission for GetAccount"),
},
{
"GetAccount succeeds when admin roleID in context",
[]string{ssvc.BundleUUIDRoleAdmin},
nil,
},
}
for _, scenario := range scenarios {
t.Run(scenario.name, func(t *testing.T) {
teardown := setup()
defer teardown()
ctx := buildTestCtx(t, scenario.roleIDs)
request := &proto.GetAccountRequest{}
response := &proto.Account{}
err := s.GetAccount(ctx, request, response)
if scenario.permissionError != nil {
assert.Equal(t, scenario.permissionError, err)
} else if err != nil {
// we are only checking permissions here, so just check that the error code is not 403
merr := merrors.FromError(err)
assert.NotEqual(t, http.StatusForbidden, merr.GetCode())
}
})
}
}
// TestPermissionsCreateAccount checks permission handling on CreateAccount
func TestPermissionsCreateAccount(t *testing.T) {
var scenarios = []struct {
name string
roleIDs []string
permissionError error
}{
// TODO: remove this test when https://github.com/owncloud/ocis/accounts/pull/111 is merged
// replace with two tests:
// 1: "CreateAccount fails with 403 when roleIDs don't exist in context"
// 2: "CreateAccount fails with 403 when no admin role in context"
{
"CreateAccount succeeds when no role IDs in context",
nil,
nil,
},
{
"CreateAccount fails when no admin roleID in context",
[]string{ssvc.BundleUUIDRoleUser, ssvc.BundleUUIDRoleGuest},
merrors.Forbidden(s.id, "no permission for CreateAccount"),
},
{
"CreateAccount succeeds when admin roleID in context",
[]string{ssvc.BundleUUIDRoleAdmin},
nil,
},
}
for _, scenario := range scenarios {
t.Run(scenario.name, func(t *testing.T) {
teardown := setup()
defer teardown()
ctx := buildTestCtx(t, scenario.roleIDs)
request := &proto.CreateAccountRequest{}
response := &proto.Account{}
err := s.CreateAccount(ctx, request, response)
if scenario.permissionError != nil {
assert.Equal(t, scenario.permissionError, err)
} else if err != nil {
// we are only checking permissions here, so just check that the error code is not 403
merr := merrors.FromError(err)
assert.NotEqual(t, http.StatusForbidden, merr.GetCode())
}
})
}
}
// TestPermissionsUpdateAccount checks permission handling on UpdateAccount
func TestPermissionsUpdateAccount(t *testing.T) {
var scenarios = []struct {
name string
roleIDs []string
permissionError error
}{
// TODO: remove this test when https://github.com/owncloud/ocis/accounts/pull/111 is merged
// replace with two tests:
// 1: "UpdateAccount fails with 403 when roleIDs don't exist in context"
// 2: "UpdateAccount fails with 403 when no admin role in context"
{
"UpdateAccount succeeds when no role IDs in context",
nil,
nil,
},
{
"UpdateAccount fails when no admin roleID in context",
[]string{ssvc.BundleUUIDRoleUser, ssvc.BundleUUIDRoleGuest},
merrors.Forbidden(s.id, "no permission for UpdateAccount"),
},
{
"UpdateAccount succeeds when admin roleID in context",
[]string{ssvc.BundleUUIDRoleAdmin},
nil,
},
}
for _, scenario := range scenarios {
t.Run(scenario.name, func(t *testing.T) {
teardown := setup()
defer teardown()
ctx := buildTestCtx(t, scenario.roleIDs)
request := &proto.UpdateAccountRequest{}
response := &proto.Account{}
err := s.UpdateAccount(ctx, request, response)
if scenario.permissionError != nil {
assert.Equal(t, scenario.permissionError, err)
} else if err != nil {
// we are only checking permissions here, so just check that the error code is not 403
merr := merrors.FromError(err)
assert.NotEqual(t, http.StatusForbidden, merr.GetCode())
}
})
}
}
// TestPermissionsDeleteAccount checks permission handling on DeleteAccount
func TestPermissionsDeleteAccount(t *testing.T) {
var scenarios = []struct {
name string
roleIDs []string
permissionError error
}{
// TODO: remove this test when https://github.com/owncloud/ocis/accounts/pull/111 is merged
// replace with two tests:
// 1: "DeleteAccount fails with 403 when roleIDs don't exist in context"
// 2: "DeleteAccount fails with 403 when no admin role in context"
{
"DeleteAccount succeeds when no role IDs in context",
nil,
nil,
},
{
"DeleteAccount fails when no admin roleID in context",
[]string{ssvc.BundleUUIDRoleUser, ssvc.BundleUUIDRoleGuest},
merrors.Forbidden(s.id, "no permission for DeleteAccount"),
},
{
"DeleteAccount succeeds when admin roleID in context",
[]string{ssvc.BundleUUIDRoleAdmin},
nil,
},
}
for _, scenario := range scenarios {
t.Run(scenario.name, func(t *testing.T) {
teardown := setup()
defer teardown()
ctx := buildTestCtx(t, scenario.roleIDs)
request := &proto.DeleteAccountRequest{}
response := &empty.Empty{}
err := s.DeleteAccount(ctx, request, response)
if scenario.permissionError != nil {
assert.Equal(t, scenario.permissionError, err)
} else if err != nil {
// we are only checking permissions here, so just check that the error code is not 403
merr := merrors.FromError(err)
assert.NotEqual(t, http.StatusForbidden, merr.GetCode())
}
})
}
}
func buildTestCtx(t *testing.T, roleIDs []string) context.Context {
ctx := context.Background()
if roleIDs != nil {
roleIDs, err := json.Marshal(roleIDs)
assert.NoError(t, err)
ctx = metadata.Set(ctx, middleware.RoleIDs, string(roleIDs))
}
return ctx
}
func buildRoleServiceMock() settings.RoleService {
defaultRoles := map[string]*settings.Bundle{
ssvc.BundleUUIDRoleAdmin: {
Id: ssvc.BundleUUIDRoleAdmin,
Type: settings.Bundle_TYPE_ROLE,
Resource: &settings.Resource{
Type: settings.Resource_TYPE_SYSTEM,
},
Settings: []*settings.Setting{
{
Id: AccountManagementPermissionID,
},
},
},
ssvc.BundleUUIDRoleUser: {
Id: ssvc.BundleUUIDRoleUser,
Type: settings.Bundle_TYPE_ROLE,
Resource: &settings.Resource{
Type: settings.Resource_TYPE_SYSTEM,
},
Settings: []*settings.Setting{},
},
ssvc.BundleUUIDRoleGuest: {
Id: ssvc.BundleUUIDRoleGuest,
Type: settings.Bundle_TYPE_ROLE,
Resource: &settings.Resource{
Type: settings.Resource_TYPE_SYSTEM,
},
Settings: []*settings.Setting{},
},
}
return settings.MockRoleService{
ListRolesFunc: func(ctx context.Context, req *settings.ListBundlesRequest, opts ...client.CallOption) (res *settings.ListBundlesResponse, err error) {
payload := make([]*settings.Bundle, 0)
for _, roleID := range req.BundleIds {
if defaultRoles[roleID] != nil {
payload = append(payload, defaultRoles[roleID])
}
}
return &settings.ListBundlesResponse{
Bundles: payload,
}, nil
},
AssignRoleToUserFunc: func(ctx context.Context, req *settings.AssignRoleToUserRequest, opts ...client.CallOption) (res *settings.AssignRoleToUserResponse, err error) {
// mock can be empty. function is called during service start. actual role assignments not needed for the tests.
return &settings.AssignRoleToUserResponse{
Assignment: &settings.UserRoleAssignment{},
}, nil
},
}
}
-382
View File
@@ -1,382 +0,0 @@
package service
import (
"context"
"path"
"strconv"
"github.com/gofrs/uuid"
p "github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes/empty"
merrors "github.com/micro/go-micro/v2/errors"
"github.com/owncloud/ocis/accounts/pkg/proto/v0"
"github.com/owncloud/ocis/accounts/pkg/storage"
)
func (s Service) expandMembers(g *proto.Group) {
if g == nil {
return
}
expanded := []*proto.Account{}
for i := range g.Members {
// TODO resolve by name, when a create or update is issued they may not have an id? fall back to searching the group id in the index?
a := &proto.Account{}
if err := s.repo.LoadAccount(context.Background(), g.Members[i].Id, a); err == nil {
expanded = append(expanded, a)
} else {
// log errors but con/var/tmp/ocis-accounts-store-408341811tinue execution for now
s.log.Error().Err(err).Str("id", g.Members[i].Id).Msg("could not load account")
}
}
g.Members = expanded
}
// deflateMembers replaces the users of a group with an instance that only contains the id
func (s Service) deflateMembers(g *proto.Group) {
if g == nil {
return
}
deflated := []*proto.Account{}
for i := range g.Members {
if g.Members[i].Id != "" {
deflated = append(deflated, &proto.Account{Id: g.Members[i].Id})
} else {
// TODO fetch and use an id when group only has a name but no id
s.log.Error().Str("id", g.Id).Interface("account", g.Members[i]).Msg("resolving members by name is not implemented yet")
}
}
g.Members = deflated
}
// ListGroups implements the GroupsServiceHandler interface
func (s Service) ListGroups(ctx context.Context, in *proto.ListGroupsRequest, out *proto.ListGroupsResponse) (err error) {
if in.Query == "" {
err = s.repo.LoadGroups(ctx, &out.Groups)
if err != nil {
s.log.Err(err).Msg("failed to load all groups from storage")
return merrors.InternalServerError(s.id, "failed to load all groups")
}
for i := range out.Groups {
a := out.Groups[i]
// TODO add accounts only if requested
// if in.FieldMask ...
s.expandMembers(a)
}
return nil
}
searchResults, err := s.findGroupsByQuery(ctx, in.Query)
out.Groups = make([]*proto.Group, 0, len(searchResults))
for _, hit := range searchResults {
g := &proto.Group{}
if err = s.repo.LoadGroup(ctx, hit, g); err != nil {
s.log.Error().Err(err).Str("group", hit).Msg("could not load group, skipping")
continue
}
s.log.Debug().Interface("group", g).Msg("found group")
// TODO add accounts if requested
// if in.FieldMask ...
s.expandMembers(g)
out.Groups = append(out.Groups, g)
}
return
}
func (s Service) findGroupsByQuery(ctx context.Context, query string) ([]string, error) {
return s.index.Query(&proto.Group{}, query)
}
// GetGroup implements the GroupsServiceHandler interface
func (s Service) GetGroup(c context.Context, in *proto.GetGroupRequest, out *proto.Group) (err error) {
var id string
if id, err = cleanupID(in.Id); err != nil {
return merrors.InternalServerError(s.id, "could not clean up group id: %v", err.Error())
}
if err = s.repo.LoadGroup(c, id, out); err != nil {
if storage.IsNotFoundErr(err) {
return merrors.NotFound(s.id, "group not found: %v", err.Error())
}
s.log.Error().Err(err).Str("id", id).Msg("could not load group")
return merrors.InternalServerError(s.id, "could not load group: %v", err.Error())
}
s.log.Debug().Interface("group", out).Msg("found group")
// TODO only add accounts if requested
// if in.FieldMask ...
s.expandMembers(out)
return
}
// CreateGroup implements the GroupsServiceHandler interface
func (s Service) CreateGroup(c context.Context, in *proto.CreateGroupRequest, out *proto.Group) (err error) {
if in.Group == nil {
return merrors.InternalServerError(s.id, "invalid group: empty")
}
p.Merge(out, in.Group)
if out.Id == "" {
out.Id = uuid.Must(uuid.NewV4()).String()
}
if _, err = cleanupID(out.Id); err != nil {
return merrors.InternalServerError(s.id, "could not clean up account id: %v", err.Error())
}
s.deflateMembers(out)
if err = s.repo.WriteGroup(c, out); err != nil {
s.log.Error().Err(err).Interface("group", out).Msg("could not persist new group")
return merrors.InternalServerError(s.id, "could not persist new group: %v", err.Error())
}
indexResults, err := s.index.Add(out)
if err != nil {
s.rollbackCreateGroup(c, out)
return merrors.InternalServerError(s.id, "could not index new group: %v", err.Error())
}
for _, r := range indexResults {
if r.Field == "GidNumber" {
gid, err := strconv.Atoi(path.Base(r.Value))
if err != nil {
s.rollbackCreateGroup(c, out)
return err
}
out.GidNumber = int64(gid)
return s.repo.WriteGroup(context.Background(), out)
}
}
return
}
// rollbackCreateGroup tries to rollback changes made by `CreateGroup` if parts of it failed.
func (s Service) rollbackCreateGroup(ctx context.Context, group *proto.Group) {
err := s.index.Delete(group)
if err != nil {
s.log.Err(err).Msg("failed to rollback group from indices")
}
err = s.repo.DeleteGroup(ctx, group.Id)
if err != nil {
s.log.Err(err).Msg("failed to rollback group from repo")
}
}
// UpdateGroup implements the GroupsServiceHandler interface
func (s Service) UpdateGroup(c context.Context, in *proto.UpdateGroupRequest, out *proto.Group) (err error) {
return merrors.InternalServerError(s.id, "not implemented")
}
// DeleteGroup implements the GroupsServiceHandler interface
func (s Service) DeleteGroup(c context.Context, in *proto.DeleteGroupRequest, out *empty.Empty) (err error) {
var id string
if id, err = cleanupID(in.Id); err != nil {
return merrors.InternalServerError(s.id, "could not clean up group id: %v", err.Error())
}
g := &proto.Group{}
if err = s.repo.LoadGroup(c, id, g); err != nil {
if storage.IsNotFoundErr(err) {
return merrors.NotFound(s.id, "group not found: %v", err.Error())
}
return merrors.InternalServerError(s.id, "could not load group: %v", err.Error())
}
// delete memberof relationship in users
for i := range g.Members {
err = s.RemoveMember(c, &proto.RemoveMemberRequest{
AccountId: g.Members[i].Id,
GroupId: id,
}, g)
if err != nil {
s.log.Error().Err(err).Str("groupid", id).Str("accountid", g.Members[i].Id).Msg("could not remove account memberof, skipping")
}
}
if err = s.repo.DeleteGroup(c, id); err != nil {
if storage.IsNotFoundErr(err) {
return merrors.NotFound(s.id, "group not found: %v", err.Error())
}
return merrors.InternalServerError(s.id, "could not load group: %v", err.Error())
}
if err = s.index.Delete(g); err != nil {
s.log.Error().Err(err).Str("id", id).Msg("could not remove group from index")
return merrors.InternalServerError(s.id, "could not remove group from index: %v", err.Error())
}
s.log.Info().Str("id", id).Msg("deleted group")
return
}
// AddMember implements the GroupsServiceHandler interface
func (s Service) AddMember(c context.Context, in *proto.AddMemberRequest, out *proto.Group) (err error) {
// cleanup ids
var groupID string
if groupID, err = cleanupID(in.GroupId); err != nil {
return merrors.InternalServerError(s.id, "could not clean up group id: %v", err.Error())
}
var accountID string
if accountID, err = cleanupID(in.AccountId); err != nil {
return merrors.InternalServerError(s.id, "could not clean up account id: %v", err.Error())
}
// load structs
a := &proto.Account{}
if err = s.repo.LoadAccount(c, accountID, a); err != nil {
if storage.IsNotFoundErr(err) {
return merrors.NotFound(s.id, "group not found: %v", err.Error())
}
return merrors.InternalServerError(s.id, "could not load group: %v", err.Error())
}
g := &proto.Group{}
if err = s.repo.LoadGroup(c, groupID, g); err != nil {
if storage.IsNotFoundErr(err) {
return merrors.NotFound(s.id, "could not load group: %v", err.Error())
}
return merrors.InternalServerError(s.id, "could not load group: %v", err.Error())
}
// check if we need to add the account to the group
alreadyRelated := false
for i := range g.Members {
if g.Members[i].Id == a.Id {
alreadyRelated = true
}
}
aref := &proto.Account{
Id: a.Id,
}
if !alreadyRelated {
g.Members = append(g.Members, aref)
}
// check if we need to add the group to the account
alreadyRelated = false
for i := range a.MemberOf {
if a.MemberOf[i].Id == g.Id {
alreadyRelated = true
break
}
}
// only store the reference to prevent recurision when marshaling json
gref := &proto.Group{
Id: g.Id,
}
if !alreadyRelated {
a.MemberOf = append(a.MemberOf, gref)
}
if err = s.repo.WriteAccount(c, a); err != nil {
return merrors.InternalServerError(s.id, "could not persist account: %v", err.Error())
}
if err = s.repo.WriteGroup(c, g); err != nil {
return merrors.InternalServerError(s.id, "could not persist group: %v", err.Error())
}
// FIXME update index!
// TODO rollback changes when only one of them failed?
// TODO store relation in another file?
// TODO return error if they are already related?
return nil
}
// RemoveMember implements the GroupsServiceHandler interface
func (s Service) RemoveMember(c context.Context, in *proto.RemoveMemberRequest, out *proto.Group) (err error) {
// cleanup ids
var groupID string
if groupID, err = cleanupID(in.GroupId); err != nil {
return merrors.InternalServerError(s.id, "could not clean up group id: %v", err.Error())
}
var accountID string
if accountID, err = cleanupID(in.AccountId); err != nil {
return merrors.InternalServerError(s.id, "could not clean up account id: %v", err.Error())
}
// load structs
a := &proto.Account{}
if err = s.repo.LoadAccount(c, accountID, a); err != nil {
if storage.IsNotFoundErr(err) {
return merrors.NotFound(s.id, "could not load account: %v", err.Error())
}
s.log.Error().Err(err).Str("id", accountID).Msg("could not load account")
return merrors.InternalServerError(s.id, "could not load account: %v", err.Error())
}
g := &proto.Group{}
if err = s.repo.LoadGroup(c, groupID, g); err != nil {
if storage.IsNotFoundErr(err) {
return merrors.NotFound(s.id, "could not load group: %v", err.Error())
}
s.log.Error().Err(err).Str("id", groupID).Msg("could not load group")
return merrors.InternalServerError(s.id, "could not load group: %v", err.Error())
}
//remove the account from the group if it exists
newMembers := []*proto.Account{}
for i := range g.Members {
if g.Members[i].Id != a.Id {
newMembers = append(newMembers, g.Members[i])
}
}
g.Members = newMembers
// remove the group from the account if it exists
newGroups := []*proto.Group{}
for i := range a.MemberOf {
if a.MemberOf[i].Id != g.Id {
newGroups = append(newGroups, a.MemberOf[i])
}
}
a.MemberOf = newGroups
if err = s.repo.WriteAccount(c, a); err != nil {
s.log.Error().Err(err).Interface("account", a).Msg("could not persist account")
return merrors.InternalServerError(s.id, "could not persist account: %v", err.Error())
}
if err = s.repo.WriteGroup(c, g); err != nil {
s.log.Error().Err(err).Interface("group", g).Msg("could not persist group")
return merrors.InternalServerError(s.id, "could not persist group: %v", err.Error())
}
// FIXME update index!
// TODO rollback changes when only one of them failed?
// TODO store relation in another file?
// TODO return error if they are not related?
return nil
}
// ListMembers implements the GroupsServiceHandler interface
func (s Service) ListMembers(c context.Context, in *proto.ListMembersRequest, out *proto.ListMembersResponse) (err error) {
// cleanup ids
var groupID string
if groupID, err = cleanupID(in.Id); err != nil {
return merrors.InternalServerError(s.id, "could not clean up group id: %v", err.Error())
}
g := &proto.Group{}
if err = s.repo.LoadGroup(c, groupID, g); err != nil {
if storage.IsNotFoundErr(err) {
return merrors.NotFound(s.id, "group not found: %v", err.Error())
}
s.log.Error().Err(err).Str("id", groupID).Msg("could not load group")
return merrors.InternalServerError(s.id, "could not load group: %v", err.Error())
}
// TODO only expand accounts if requested
// if in.FieldMask ...
s.expandMembers(g)
out.Members = g.Members
return
}
-108
View File
@@ -1,108 +0,0 @@
package service
import (
"context"
"fmt"
"github.com/owncloud/ocis/accounts/pkg/storage"
"github.com/owncloud/ocis/accounts/pkg/proto/v0"
"github.com/owncloud/ocis/ocis-pkg/indexer"
"github.com/owncloud/ocis/ocis-pkg/indexer/config"
"github.com/owncloud/ocis/ocis-pkg/indexer/option"
)
// RebuildIndex deletes all indices (in memory and on storage) and rebuilds them from scratch.
func (s Service) RebuildIndex(ctx context.Context, request *proto.RebuildIndexRequest, response *proto.RebuildIndexResponse) error {
if err := s.index.Reset(); err != nil {
return fmt.Errorf("failed to delete index containers: %w", err)
}
c, err := configFromSvc(s.Config)
if err != nil {
return err
}
if err := recreateContainers(s.index, c); err != nil {
return fmt.Errorf("failed to recreate index containers: %w", err)
}
if err := reindexDocuments(ctx, s.repo, s.index); err != nil {
return fmt.Errorf("failed to reindex documents: %w", err)
}
return nil
}
// recreateContainers adds all indices to the indexer that we have for this service.
func recreateContainers(idx *indexer.Indexer, cfg *config.Config) error {
// Accounts
if err := idx.AddIndex(&proto.Account{}, "Id", "Id", "accounts", "non_unique", nil, true); err != nil {
return err
}
if err := idx.AddIndex(&proto.Account{}, "DisplayName", "Id", "accounts", "non_unique", nil, true); err != nil {
return err
}
if err := idx.AddIndex(&proto.Account{}, "Mail", "Id", "accounts", "unique", nil, true); err != nil {
return err
}
if err := idx.AddIndex(&proto.Account{}, "OnPremisesSamAccountName", "Id", "accounts", "unique", nil, true); err != nil {
return err
}
if err := idx.AddIndex(&proto.Account{}, "PreferredName", "Id", "accounts", "unique", nil, true); err != nil {
return err
}
if err := idx.AddIndex(&proto.Account{}, "UidNumber", "Id", "accounts", "autoincrement", &option.Bound{
Lower: cfg.Index.UID.Lower,
Upper: cfg.Index.UID.Upper,
}, false); err != nil {
return err
}
// Groups
if err := idx.AddIndex(&proto.Group{}, "OnPremisesSamAccountName", "Id", "groups", "unique", nil, true); err != nil {
return err
}
if err := idx.AddIndex(&proto.Group{}, "DisplayName", "Id", "groups", "non_unique", nil, true); err != nil {
return err
}
if err := idx.AddIndex(&proto.Group{}, "GidNumber", "Id", "groups", "autoincrement", &option.Bound{
Lower: cfg.Index.GID.Lower,
Upper: cfg.Index.GID.Upper,
}, false); err != nil {
return err
}
return nil
}
// reindexDocuments loads all existing documents and adds them to the index.
func reindexDocuments(ctx context.Context, repo storage.Repo, index *indexer.Indexer) error {
accounts := make([]*proto.Account, 0)
if err := repo.LoadAccounts(ctx, &accounts); err != nil {
return err
}
for i := range accounts {
_, err := index.Add(accounts[i])
if err != nil {
return err
}
}
groups := make([]*proto.Group, 0)
if err := repo.LoadGroups(ctx, &groups); err != nil {
return err
}
for i := range groups {
_, err := index.Add(groups[i])
if err != nil {
return err
}
}
return nil
}
-57
View File
@@ -1,57 +0,0 @@
package service
import (
"github.com/owncloud/ocis/accounts/pkg/config"
"github.com/owncloud/ocis/ocis-pkg/log"
"github.com/owncloud/ocis/ocis-pkg/roles"
settings "github.com/owncloud/ocis/settings/pkg/proto/v0"
)
// 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
RoleService settings.RoleService
RoleManager *roles.Manager
}
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
}
}
// RoleService provides a function to set the RoleService option.
func RoleService(val settings.RoleService) Option {
return func(o *Options) {
o.RoleService = val
}
}
// RoleManager provides a function to set the RoleManager option.
func RoleManager(val *roles.Manager) Option {
return func(o *Options) {
o.RoleManager = val
}
}
-104
View File
@@ -1,104 +0,0 @@
package service
import (
"context"
"github.com/owncloud/ocis/ocis-pkg/service/grpc"
olog "github.com/owncloud/ocis/ocis-pkg/log"
settings "github.com/owncloud/ocis/settings/pkg/proto/v0"
ssvc "github.com/owncloud/ocis/settings/pkg/service/v0"
)
const (
// AccountManagementPermissionID is the hardcoded setting UUID for the account management permission
AccountManagementPermissionID string = "8e587774-d929-4215-910b-a317b1e80f73"
// AccountManagementPermissionName is the hardcoded setting name for the account management permission
AccountManagementPermissionName string = "account-management"
// GroupManagementPermissionID is the hardcoded setting UUID for the group management permission
GroupManagementPermissionID string = "522adfbe-5908-45b4-b135-41979de73245"
// GroupManagementPermissionName is the hardcoded setting name for the group management permission
GroupManagementPermissionName string = "group-management"
// SelfManagementPermissionID is the hardcoded setting UUID for the self management permission
SelfManagementPermissionID string = "e03070e9-4362-4cc6-a872-1c7cb2eb2b8e"
// SelfManagementPermissionName is the hardcoded setting name for the self management permission
SelfManagementPermissionName string = "self-management"
)
// RegisterPermissions registers permissions for account management and group management with the settings service.
func RegisterPermissions(l *olog.Logger) {
service := settings.NewBundleService("com.owncloud.api.settings", grpc.DefaultClient)
permissionRequests := generateAccountManagementPermissionsRequests()
for i := range permissionRequests {
res, err := service.AddSettingToBundle(context.Background(), &permissionRequests[i])
bundleID := permissionRequests[i].BundleId
if err != nil {
l.Err(err).Str("bundle", bundleID).Str("setting", permissionRequests[i].Setting.Id).Msg("error adding permission to bundle")
} else {
l.Info().Str("bundle", bundleID).Str("setting", res.Setting.Id).Msg("successfully added permission to bundle")
}
}
}
func generateAccountManagementPermissionsRequests() []settings.AddSettingToBundleRequest {
return []settings.AddSettingToBundleRequest{
{
BundleId: ssvc.BundleUUIDRoleAdmin,
Setting: &settings.Setting{
Id: AccountManagementPermissionID,
Name: AccountManagementPermissionName,
DisplayName: "Account Management",
Description: "This permission gives full access to everything that is related to account management.",
Resource: &settings.Resource{
Type: settings.Resource_TYPE_USER,
Id: "all",
},
Value: &settings.Setting_PermissionValue{
PermissionValue: &settings.Permission{
Operation: settings.Permission_OPERATION_READWRITE,
Constraint: settings.Permission_CONSTRAINT_ALL,
},
},
},
},
{
BundleId: ssvc.BundleUUIDRoleAdmin,
Setting: &settings.Setting{
Id: GroupManagementPermissionID,
Name: GroupManagementPermissionName,
DisplayName: "Group Management",
Description: "This permission gives full access to everything that is related to group management.",
Resource: &settings.Resource{
Type: settings.Resource_TYPE_GROUP,
Id: "all",
},
Value: &settings.Setting_PermissionValue{
PermissionValue: &settings.Permission{
Operation: settings.Permission_OPERATION_READWRITE,
Constraint: settings.Permission_CONSTRAINT_ALL,
},
},
},
},
{
BundleId: ssvc.BundleUUIDRoleUser,
Setting: &settings.Setting{
Id: SelfManagementPermissionID,
Name: SelfManagementPermissionName,
DisplayName: "Self Management",
Description: "This permission gives access to self management.",
Resource: &settings.Resource{
Type: settings.Resource_TYPE_USER,
Id: "me",
},
Value: &settings.Setting_PermissionValue{
PermissionValue: &settings.Permission{
Operation: settings.Permission_OPERATION_READWRITE,
Constraint: settings.Permission_CONSTRAINT_OWN,
},
},
},
},
}
}
-436
View File
@@ -1,436 +0,0 @@
package service
import (
"context"
"errors"
"path"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/owncloud/ocis/ocis-pkg/service/grpc"
"github.com/owncloud/ocis/accounts/pkg/storage"
"github.com/owncloud/ocis/ocis-pkg/indexer"
idxcfg "github.com/owncloud/ocis/ocis-pkg/indexer/config"
idxerrs "github.com/owncloud/ocis/ocis-pkg/indexer/errors"
"github.com/owncloud/ocis/accounts/pkg/config"
"github.com/owncloud/ocis/accounts/pkg/proto/v0"
"github.com/owncloud/ocis/ocis-pkg/log"
"github.com/owncloud/ocis/ocis-pkg/roles"
settings "github.com/owncloud/ocis/settings/pkg/proto/v0"
settings_svc "github.com/owncloud/ocis/settings/pkg/service/v0"
)
// userDefaultGID is the default integer representing the "users" group.
const userDefaultGID = 30000
// New returns a new instance of Service
func New(opts ...Option) (s *Service, err error) {
options := newOptions(opts...)
logger := options.Logger
cfg := options.Config
roleService := options.RoleService
if roleService == nil {
roleService = settings.NewRoleService("com.owncloud.api.settings", grpc.DefaultClient)
}
roleManager := options.RoleManager
if roleManager == nil {
m := roles.NewManager(
roles.CacheSize(1024),
roles.CacheTTL(time.Hour*24*7),
roles.Logger(options.Logger),
roles.RoleService(roleService),
)
roleManager = &m
}
s = &Service{
id: cfg.GRPC.Namespace + "." + cfg.Server.Name,
log: logger,
Config: cfg,
RoleService: roleService,
RoleManager: roleManager,
repo: createMetadataStorage(cfg, logger),
}
if s.index, err = s.buildIndex(); err != nil {
return nil, err
}
if err = s.createDefaultAccounts(); err != nil {
return nil, err
}
if err = s.createDefaultGroups(); err != nil {
return nil, err
}
// TODO watch folders for new records
return
}
func (s Service) buildIndex() (*indexer.Indexer, error) {
var indexcfg *idxcfg.Config
indexcfg, err := configFromSvc(s.Config)
if err != nil {
return nil, err
}
idx := indexer.CreateIndexer(indexcfg)
if err := recreateContainers(idx, indexcfg); err != nil {
return nil, err
}
return idx, nil
}
// configFromSvc creates an index config out of a service configuration. This intermediate step exists
// because the index config was mapped after the service config.
func configFromSvc(cfg *config.Config) (*idxcfg.Config, error) {
c := idxcfg.New()
defer func(cfg *config.Config) {
l := log.NewLogger(log.Color(cfg.Log.Color), log.Pretty(cfg.Log.Pretty), log.Level(cfg.Log.Level))
if r := recover(); r != nil {
l.Error().
Str("panic", "recovered from panic while parsing index config from service configuration").
Interface("svc_config", cfg).
Msg("recovered from panic")
}
}(cfg)
if (config.Repo{}) != cfg.Repo {
if (config.Disk{}) != cfg.Repo.Disk {
c.Repo = idxcfg.Repo{
Disk: idxcfg.Disk{
Path: cfg.Repo.Disk.Path,
},
}
}
if (config.CS3{}) != cfg.Repo.CS3 {
c.Repo = idxcfg.Repo{
CS3: idxcfg.CS3{
ProviderAddr: cfg.Repo.CS3.ProviderAddr,
DataURL: cfg.Repo.CS3.DataURL,
DataPrefix: cfg.Repo.CS3.DataPrefix,
JWTSecret: cfg.Repo.CS3.JWTSecret,
},
}
}
if (config.Index{}) != cfg.Index {
c.Index = idxcfg.Index{
UID: idxcfg.Bound{
Lower: cfg.Index.UID.Lower,
},
GID: idxcfg.Bound{
Lower: cfg.Index.GID.Lower,
},
}
}
if (config.ServiceUser{}) != cfg.ServiceUser {
c.ServiceUser = cfg.ServiceUser
}
}
return c, nil
}
func (s Service) createDefaultAccounts() (err error) {
accounts := []proto.Account{
{
Id: "4c510ada-c86b-4815-8820-42cdf82c3d51",
PreferredName: "einstein",
OnPremisesSamAccountName: "einstein",
Mail: "einstein@example.org",
DisplayName: "Albert Einstein",
UidNumber: 20000,
GidNumber: 30000,
PasswordProfile: &proto.PasswordProfile{
Password: "$2a$11$4WNffzgU/WrIRiDnwu8OnOwgOIIUqR/2Ptvp7WJAQCTSgSrylyuvC",
},
AccountEnabled: true,
MemberOf: []*proto.Group{
{Id: "509a9dcd-bb37-4f4f-a01a-19dca27d9cfa"}, // users
{Id: "6040aa17-9c64-4fef-9bd0-77234d71bad0"}, // sailing-lovers
{Id: "dd58e5ec-842e-498b-8800-61f2ec6f911f"}, // violin-haters
{Id: "262982c1-2362-4afa-bfdf-8cbfef64a06e"}, // physics-lovers
},
},
{
Id: "f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c",
PreferredName: "marie",
OnPremisesSamAccountName: "marie",
Mail: "marie@example.org",
DisplayName: "Marie Curie",
UidNumber: 20001,
GidNumber: 30000,
PasswordProfile: &proto.PasswordProfile{
Password: "$2a$11$Wu2XcDnE6G2No8C88FVWluNHyXuQQi0cHzSe82Vni8AdwIO12fphC",
},
AccountEnabled: true,
MemberOf: []*proto.Group{
{Id: "509a9dcd-bb37-4f4f-a01a-19dca27d9cfa"}, // users
{Id: "7b87fd49-286e-4a5f-bafd-c535d5dd997a"}, // radium-lovers
{Id: "cedc21aa-4072-4614-8676-fa9165f598ff"}, // polonium-lovers
{Id: "262982c1-2362-4afa-bfdf-8cbfef64a06e"}, // physics-lovers
},
},
{
Id: "932b4540-8d16-481e-8ef4-588e4b6b151c",
PreferredName: "richard",
OnPremisesSamAccountName: "richard",
Mail: "richard@example.org",
DisplayName: "Richard Feynman",
UidNumber: 20002,
GidNumber: 30000,
PasswordProfile: &proto.PasswordProfile{
Password: "$2a$11$6Lak4zh1xUkpObg2rrOotOTdQYGj2Uu/sowcVLhub.8qYIr.CxzEW",
},
AccountEnabled: true,
MemberOf: []*proto.Group{
{Id: "509a9dcd-bb37-4f4f-a01a-19dca27d9cfa"}, // users
{Id: "a1726108-01f8-4c30-88df-2b1a9d1cba1a"}, // quantum-lovers
{Id: "167cbee2-0518-455a-bfb2-031fe0621e5d"}, // philosophy-haters
{Id: "262982c1-2362-4afa-bfdf-8cbfef64a06e"}, // physics-lovers
},
},
// admin user(s)
{
Id: "058bff95-6708-4fe5-91e4-9ea3d377588b",
PreferredName: "moss",
OnPremisesSamAccountName: "moss",
Mail: "moss@example.org",
DisplayName: "Maurice Moss",
UidNumber: 20003,
GidNumber: 30000,
PasswordProfile: &proto.PasswordProfile{
Password: "$2a$11$jvI6PHuvrimpcCHzL2Q2WOqfm1FGdYAuSYZBDahr/B48fpiFxyDy2",
},
AccountEnabled: true,
MemberOf: []*proto.Group{
{Id: "509a9dcd-bb37-4f4f-a01a-19dca27d9cfa"}, // users
},
},
{
Id: "ddc2004c-0977-11eb-9d3f-a793888cd0f8",
PreferredName: "admin",
OnPremisesSamAccountName: "admin",
Mail: "admin@example.org",
DisplayName: "Admin",
UidNumber: 20004,
GidNumber: 30000,
PasswordProfile: &proto.PasswordProfile{
Password: "$2a$11$En9VIUtqOdDyUl.LuUq2KeuBb5A2n8zE0lkJ2v6IDRSaOamhNq6Uu",
},
AccountEnabled: true,
MemberOf: []*proto.Group{
{Id: "509a9dcd-bb37-4f4f-a01a-19dca27d9cfa"}, // users
},
},
// technical users for kopano and reva
{
Id: "820ba2a1-3f54-4538-80a4-2d73007e30bf",
PreferredName: "konnectd",
OnPremisesSamAccountName: "konnectd",
Mail: "idp@example.org",
DisplayName: "Kopano Konnectd",
UidNumber: 10000,
GidNumber: 15000,
PasswordProfile: &proto.PasswordProfile{
Password: "$2a$11$ntoTP2W/kyQIuoYpH5mRBuNzaEERYWSwn/zCsY5rtffen4d41y9.6",
},
AccountEnabled: true,
MemberOf: []*proto.Group{
{Id: "34f38767-c937-4eb6-b847-1c175829a2a0"}, // sysusers
},
},
{
Id: "bc596f3c-c955-4328-80a0-60d018b4ad57",
PreferredName: "reva",
OnPremisesSamAccountName: "reva",
Mail: "storage@example.org",
DisplayName: "Reva Inter Operability Platform",
UidNumber: 10001,
GidNumber: 15000,
PasswordProfile: &proto.PasswordProfile{
Password: "$2a$11$40xzy3rO8Tq4j2VkFbKz8Ow19BRaqaixEjAR0IbvQXxtOvMtkjwzy",
},
AccountEnabled: true,
MemberOf: []*proto.Group{
{Id: "34f38767-c937-4eb6-b847-1c175829a2a0"}, // sysusers
},
},
}
for i := range accounts {
if err := s.repo.WriteAccount(context.Background(), &accounts[i]); err != nil {
return err
}
results, err := s.index.Add(&accounts[i])
if err != nil {
if idxerrs.IsAlreadyExistsErr(err) {
continue
} else {
return err
}
}
// TODO: can be removed again as soon as we respect the predefined UIDs and GIDs from the account. Then no autoincrement is happening, therefore we don't need to update accounts.
changed := false
for _, r := range results {
if r.Field == "UidNumber" || r.Field == "GidNumber" {
id, err := strconv.ParseInt(path.Base(r.Value), 10, 0)
if err != nil {
return err
}
if r.Field == "UidNumber" {
accounts[i].UidNumber = id
} else {
accounts[i].GidNumber = id
}
changed = true
}
}
if changed {
if err := s.repo.WriteAccount(context.Background(), &accounts[i]); err != nil {
return err
}
}
}
// set role for admin users and regular users
assignRoleToUser("058bff95-6708-4fe5-91e4-9ea3d377588b", settings_svc.BundleUUIDRoleAdmin, s.RoleService, s.log)
for _, accountID := range []string{
"058bff95-6708-4fe5-91e4-9ea3d377588b", //moss
"ddc2004c-0977-11eb-9d3f-a793888cd0f8", //admin
"820ba2a1-3f54-4538-80a4-2d73007e30bf", //konnectd
"bc596f3c-c955-4328-80a0-60d018b4ad57", //reva
} {
assignRoleToUser(accountID, settings_svc.BundleUUIDRoleAdmin, s.RoleService, s.log)
}
for _, accountID := range []string{
"4c510ada-c86b-4815-8820-42cdf82c3d51", //einstein
"f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c", //marie
"932b4540-8d16-481e-8ef4-588e4b6b151c", //richard
} {
assignRoleToUser(accountID, settings_svc.BundleUUIDRoleUser, s.RoleService, s.log)
}
return nil
}
func (s Service) createDefaultGroups() (err error) {
groups := []proto.Group{
{Id: "34f38767-c937-4eb6-b847-1c175829a2a0", GidNumber: 15000, OnPremisesSamAccountName: "sysusers", DisplayName: "Technical users", Description: "A group for technical users. They should not show up in sharing dialogs.", Members: []*proto.Account{
{Id: "820ba2a1-3f54-4538-80a4-2d73007e30bf"}, // konnectd
{Id: "bc596f3c-c955-4328-80a0-60d018b4ad57"}, // reva
}},
{Id: "509a9dcd-bb37-4f4f-a01a-19dca27d9cfa", GidNumber: 30000, OnPremisesSamAccountName: "users", DisplayName: "Users", Description: "A group every normal user belongs to.", Members: []*proto.Account{
{Id: "4c510ada-c86b-4815-8820-42cdf82c3d51"}, // einstein
{Id: "f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c"}, // marie
{Id: "932b4540-8d16-481e-8ef4-588e4b6b151c"}, // feynman
}},
{Id: "6040aa17-9c64-4fef-9bd0-77234d71bad0", GidNumber: 30001, OnPremisesSamAccountName: "sailing-lovers", DisplayName: "Sailing lovers", Members: []*proto.Account{
{Id: "4c510ada-c86b-4815-8820-42cdf82c3d51"}, // einstein
}},
{Id: "dd58e5ec-842e-498b-8800-61f2ec6f911f", GidNumber: 30002, OnPremisesSamAccountName: "violin-haters", DisplayName: "Violin haters", Members: []*proto.Account{
{Id: "4c510ada-c86b-4815-8820-42cdf82c3d51"}, // einstein
}},
{Id: "7b87fd49-286e-4a5f-bafd-c535d5dd997a", GidNumber: 30003, OnPremisesSamAccountName: "radium-lovers", DisplayName: "Radium lovers", Members: []*proto.Account{
{Id: "f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c"}, // marie
}},
{Id: "cedc21aa-4072-4614-8676-fa9165f598ff", GidNumber: 30004, OnPremisesSamAccountName: "polonium-lovers", DisplayName: "Polonium lovers", Members: []*proto.Account{
{Id: "f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c"}, // marie
}},
{Id: "a1726108-01f8-4c30-88df-2b1a9d1cba1a", GidNumber: 30005, OnPremisesSamAccountName: "quantum-lovers", DisplayName: "Quantum lovers", Members: []*proto.Account{
{Id: "932b4540-8d16-481e-8ef4-588e4b6b151c"}, // feynman
}},
{Id: "167cbee2-0518-455a-bfb2-031fe0621e5d", GidNumber: 30006, OnPremisesSamAccountName: "philosophy-haters", DisplayName: "Philosophy haters", Members: []*proto.Account{
{Id: "932b4540-8d16-481e-8ef4-588e4b6b151c"}, // feynman
}},
{Id: "262982c1-2362-4afa-bfdf-8cbfef64a06e", GidNumber: 30007, OnPremisesSamAccountName: "physics-lovers", DisplayName: "Physics lovers", Members: []*proto.Account{
{Id: "4c510ada-c86b-4815-8820-42cdf82c3d51"}, // einstein
{Id: "f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c"}, // marie
{Id: "932b4540-8d16-481e-8ef4-588e4b6b151c"}, // feynman
}},
}
for i := range groups {
if err := s.repo.WriteGroup(context.Background(), &groups[i]); err != nil {
return err
}
results, err := s.index.Add(&groups[i])
if err != nil {
if idxerrs.IsAlreadyExistsErr(err) {
continue
} else {
return err
}
}
// TODO: can be removed again as soon as we respect the predefined GIDs from the group. Then no autoincrement is happening, therefore we don't need to update groups.
for _, r := range results {
if r.Field == "GidNumber" {
gid, err := strconv.ParseInt(path.Base(r.Value), 10, 0)
if err != nil {
return err
}
groups[i].GidNumber = gid
if err := s.repo.WriteGroup(context.Background(), &groups[i]); err != nil {
return err
}
break
}
}
}
return nil
}
func assignRoleToUser(accountID, roleID string, rs settings.RoleService, logger log.Logger) (ok bool) {
_, err := rs.AssignRoleToUser(context.Background(), &settings.AssignRoleToUserRequest{
AccountUuid: accountID,
RoleId: roleID,
})
if err != nil {
logger.Error().Err(err).Str("accountID", accountID).Str("roleID", roleID).Msg("could not set role for account")
return false
}
return true
}
func createMetadataStorage(cfg *config.Config, logger log.Logger) storage.Repo {
// for now we detect the used storage implementation based on which storage is configured
// the config with defaults needs to be checked last
if cfg.Repo.Disk.Path != "" {
return storage.NewDiskRepo(cfg, logger)
}
repo, err := storage.NewCS3Repo(cfg)
if err != nil {
logger.Fatal().Err(err).Msg("cs3 storage was configured but failed to start")
}
return repo
}
// Service implements the AccountsServiceHandler interface
type Service struct {
id string
log log.Logger
Config *config.Config
index *indexer.Indexer
RoleService settings.RoleService
RoleManager *roles.Manager
repo storage.Repo
}
func cleanupID(id string) (string, error) {
id = filepath.Clean(id)
if id == "." || strings.Contains(id, "/") {
return "", errors.New("invalid id " + id)
}
return id, nil
}
-194
View File
@@ -1,194 +0,0 @@
package service
import (
"context"
olog "github.com/owncloud/ocis/ocis-pkg/log"
"github.com/owncloud/ocis/ocis-pkg/service/grpc"
settings "github.com/owncloud/ocis/settings/pkg/proto/v0"
ssvc "github.com/owncloud/ocis/settings/pkg/service/v0"
)
const (
settingUUIDProfileLanguage = "aa8cfbe5-95d4-4f7e-a032-c3c01f5f062f"
)
// RegisterSettingsBundles pushes the settings bundle definitions for this extension to the ocis-settings service.
func RegisterSettingsBundles(l *olog.Logger) {
service := settings.NewBundleService("com.owncloud.api.settings", grpc.DefaultClient)
bundleRequests := []settings.SaveBundleRequest{
generateBundleProfileRequest(),
}
for i := range bundleRequests {
res, err := service.SaveBundle(context.Background(), &bundleRequests[i])
if err != nil {
l.Err(err).Str("bundle", bundleRequests[i].Bundle.Id).Msg("Error registering bundle")
} else {
l.Info().Str("bundle", res.Bundle.Id).Msg("Successfully registered bundle")
}
}
permissionRequests := generateProfilePermissionsRequests()
for i := range permissionRequests {
res, err := service.AddSettingToBundle(context.Background(), &permissionRequests[i])
bundleID := permissionRequests[i].BundleId
if err != nil {
l.Err(err).Str("bundle", bundleID).Str("setting", permissionRequests[i].Setting.Id).Msg("Error adding setting to bundle")
} else {
l.Info().Str("bundle", bundleID).Str("setting", res.Setting.Id).Msg("Successfully added setting to bundle")
}
}
}
var languageSetting = settings.Setting_SingleChoiceValue{
SingleChoiceValue: &settings.SingleChoiceList{
Options: []*settings.ListOption{
{
Value: &settings.ListOptionValue{
Option: &settings.ListOptionValue_StringValue{
StringValue: "cs",
},
},
DisplayValue: "Czech",
},
{
Value: &settings.ListOptionValue{
Option: &settings.ListOptionValue_StringValue{
StringValue: "de",
},
},
DisplayValue: "Deutsch",
},
{
Value: &settings.ListOptionValue{
Option: &settings.ListOptionValue_StringValue{
StringValue: "en",
},
},
DisplayValue: "English",
},
{
Value: &settings.ListOptionValue{
Option: &settings.ListOptionValue_StringValue{
StringValue: "es",
},
},
DisplayValue: "Español",
},
{
Value: &settings.ListOptionValue{
Option: &settings.ListOptionValue_StringValue{
StringValue: "fr",
},
},
DisplayValue: "Français",
},
{
Value: &settings.ListOptionValue{
Option: &settings.ListOptionValue_StringValue{
StringValue: "gl",
},
},
DisplayValue: "Galego",
},
{
Value: &settings.ListOptionValue{
Option: &settings.ListOptionValue_StringValue{
StringValue: "it",
},
},
DisplayValue: "Italiano",
},
},
},
}
func generateBundleProfileRequest() settings.SaveBundleRequest {
return settings.SaveBundleRequest{
Bundle: &settings.Bundle{
Id: "2a506de7-99bd-4f0d-994e-c38e72c28fd9",
Name: "profile",
Extension: "ocis-accounts",
Type: settings.Bundle_TYPE_DEFAULT,
Resource: &settings.Resource{
Type: settings.Resource_TYPE_SYSTEM,
},
DisplayName: "Profile",
Settings: []*settings.Setting{
{
Id: settingUUIDProfileLanguage,
Name: "language",
DisplayName: "Language",
Description: "User language",
Resource: &settings.Resource{
Type: settings.Resource_TYPE_USER,
},
Value: &languageSetting,
},
},
},
}
}
func generateProfilePermissionsRequests() []settings.AddSettingToBundleRequest {
// TODO: we don't want to set up permissions for settings manually in the future. Instead each setting should come with
// a set of default permissions for the default roles (guest, user, admin).
return []settings.AddSettingToBundleRequest{
{
BundleId: ssvc.BundleUUIDRoleAdmin,
Setting: &settings.Setting{
Id: "7d81f103-0488-4853-bce5-98dcce36d649",
Name: "language-readwrite",
DisplayName: "Permission to read and set the language (anyone)",
Resource: &settings.Resource{
Type: settings.Resource_TYPE_SETTING,
Id: settingUUIDProfileLanguage,
},
Value: &settings.Setting_PermissionValue{
PermissionValue: &settings.Permission{
Operation: settings.Permission_OPERATION_READWRITE,
Constraint: settings.Permission_CONSTRAINT_ALL,
},
},
},
},
{
BundleId: ssvc.BundleUUIDRoleUser,
Setting: &settings.Setting{
Id: "640e00d2-4df8-41bd-b1c2-9f30a01e0e99",
Name: "language-readwrite",
DisplayName: "Permission to read and set the language (self)",
Resource: &settings.Resource{
Type: settings.Resource_TYPE_SETTING,
Id: settingUUIDProfileLanguage,
},
Value: &settings.Setting_PermissionValue{
PermissionValue: &settings.Permission{
Operation: settings.Permission_OPERATION_READWRITE,
Constraint: settings.Permission_CONSTRAINT_OWN,
},
},
},
},
{
BundleId: ssvc.BundleUUIDRoleGuest,
Setting: &settings.Setting{
Id: "ca878636-8b1a-4fae-8282-8617a4c13597",
Name: "language-readwrite",
DisplayName: "Permission to read and set the language (self)",
Resource: &settings.Resource{
Type: settings.Resource_TYPE_SETTING,
Id: settingUUIDProfileLanguage,
},
Value: &settings.Setting_PermissionValue{
PermissionValue: &settings.Permission{
Operation: settings.Permission_OPERATION_READWRITE,
Constraint: settings.Permission_CONSTRAINT_OWN,
},
},
},
},
}
}
-1
View File
@@ -1 +0,0 @@
checks = ["all", "-ST1003", "-ST1000", "-SA1019"]
-76
View File
@@ -1,76 +0,0 @@
package service
import (
"context"
"github.com/golang/protobuf/ptypes/empty"
v0proto "github.com/owncloud/ocis/accounts/pkg/proto/v0"
"go.opencensus.io/trace"
)
// NewTracing returns a service that instruments traces.
func NewTracing(next v0proto.AccountsServiceHandler) v0proto.AccountsServiceHandler {
return tracing{
next: next,
}
}
type tracing struct {
next v0proto.AccountsServiceHandler
}
func (t tracing) ListAccounts(ctx context.Context, req *v0proto.ListAccountsRequest, rsp *v0proto.ListAccountsResponse) error {
ctx, span := trace.StartSpan(ctx, "Accounts.ListAccounts")
defer span.End()
span.Annotate([]trace.Attribute{
trace.Int64Attribute("page_size", int64(req.PageSize)),
trace.StringAttribute("page_token", req.PageToken),
trace.StringAttribute("field_mask", req.FieldMask.String()),
}, "Execute Accounts.ListAccount handler")
return t.next.ListAccounts(ctx, req, rsp)
}
func (t tracing) GetAccount(ctx context.Context, req *v0proto.GetAccountRequest, acc *v0proto.Account) error {
ctx, span := trace.StartSpan(ctx, "Accounts.GetAccount")
defer span.End()
span.Annotate([]trace.Attribute{
trace.StringAttribute("id", req.Id),
}, "Execute Accounts.GetAccount handler")
return t.next.GetAccount(ctx, req, acc)
}
func (t tracing) CreateAccount(ctx context.Context, req *v0proto.CreateAccountRequest, acc *v0proto.Account) error {
ctx, span := trace.StartSpan(ctx, "Accounts.CreateAccount")
defer span.End()
span.Annotate([]trace.Attribute{
trace.StringAttribute("account", req.Account.String()),
}, "Execute Accounts.CreateAccount handler")
return t.next.CreateAccount(ctx, req, acc)
}
func (t tracing) UpdateAccount(ctx context.Context, req *v0proto.UpdateAccountRequest, acc *v0proto.Account) error {
ctx, span := trace.StartSpan(ctx, "Accounts.UpdateAccount")
defer span.End()
span.Annotate([]trace.Attribute{
trace.StringAttribute("account", req.Account.String()),
}, "Execute Accounts.UpdateAccount handler")
return t.next.UpdateAccount(ctx, req, acc)
}
func (t tracing) DeleteAccount(ctx context.Context, req *v0proto.DeleteAccountRequest, e *empty.Empty) error {
ctx, span := trace.StartSpan(ctx, "Accounts.DeleteAccount")
defer span.End()
span.Annotate([]trace.Attribute{
trace.StringAttribute("id", req.Id),
}, "Execute Accounts.DeleteAccout handler")
return t.next.DeleteAccount(ctx, req, e)
}
-392
View File
@@ -1,392 +0,0 @@
package storage
import (
"bytes"
"context"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"path"
"path/filepath"
"strconv"
"strings"
user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
v1beta11 "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
"github.com/cs3org/reva/pkg/rgrpc/todo/pool"
"github.com/cs3org/reva/pkg/token"
"github.com/cs3org/reva/pkg/token/manager/jwt"
"github.com/owncloud/ocis/accounts/pkg/config"
"github.com/owncloud/ocis/accounts/pkg/proto/v0"
olog "github.com/owncloud/ocis/ocis-pkg/log"
"google.golang.org/grpc/metadata"
)
// CS3Repo provides a cs3 implementation of the Repo interface
type CS3Repo struct {
cfg *config.Config
tm token.Manager
storageProvider provider.ProviderAPIClient
dataProvider dataProviderClient // Used to create and download data via http, bypassing reva upload protocol
}
// NewCS3Repo creates a new cs3 repo
func NewCS3Repo(cfg *config.Config) (Repo, error) {
tokenManager, err := jwt.New(map[string]interface{}{
"secret": cfg.TokenManager.JWTSecret,
})
if err != nil {
return nil, err
}
client, err := pool.GetStorageProviderServiceClient(cfg.Repo.CS3.ProviderAddr)
if err != nil {
return nil, err
}
return CS3Repo{
cfg: cfg,
tm: tokenManager,
storageProvider: client,
dataProvider: dataProviderClient{
client: http.Client{
Transport: http.DefaultTransport,
},
},
}, nil
}
// WriteAccount writes an account via cs3 and modifies the provided account (e.g. with a generated id).
func (r CS3Repo) WriteAccount(ctx context.Context, a *proto.Account) (err error) {
t, err := r.authenticate(ctx)
if err != nil {
return err
}
ctx = metadata.AppendToOutgoingContext(ctx, token.TokenHeader, t)
if err := r.makeRootDirIfNotExist(ctx, accountsFolder); err != nil {
return err
}
var by []byte
if by, err = json.Marshal(a); err != nil {
return err
}
resp, err := r.dataProvider.put(r.accountURL(a.Id), bytes.NewReader(by), t)
if err != nil {
return err
}
if err = resp.Body.Close(); err != nil {
return err
}
return nil
}
// LoadAccount loads an account via cs3 by id and writes it to the provided account
func (r CS3Repo) LoadAccount(ctx context.Context, id string, a *proto.Account) (err error) {
t, err := r.authenticate(ctx)
if err != nil {
return err
}
return r.loadAccount(id, t, a)
}
// LoadAccounts loads all the accounts from the cs3 api
func (r CS3Repo) LoadAccounts(ctx context.Context, a *[]*proto.Account) (err error) {
t, err := r.authenticate(ctx)
if err != nil {
return err
}
ctx = metadata.AppendToOutgoingContext(ctx, token.TokenHeader, t)
res, err := r.storageProvider.ListContainer(ctx, &provider.ListContainerRequest{
Ref: &provider.Reference{
Spec: &provider.Reference_Path{Path: path.Join("/meta", accountsFolder)},
},
})
if err != nil {
return err
}
log := olog.NewLogger(olog.Pretty(r.cfg.Log.Pretty), olog.Color(r.cfg.Log.Color), olog.Level(r.cfg.Log.Level))
for i := range res.Infos {
acc := &proto.Account{}
err := r.loadAccount(filepath.Base(res.Infos[i].Path), t, acc)
if err != nil {
log.Err(err).Msg("could not load account")
continue
}
*a = append(*a, acc)
}
return nil
}
func (r CS3Repo) loadAccount(id string, t string, a *proto.Account) error {
resp, err := r.dataProvider.get(r.accountURL(id), t)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return &notFoundErr{"account", id}
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if err = resp.Body.Close(); err != nil {
return err
}
return json.Unmarshal(b, &a)
}
// DeleteAccount deletes an account via cs3 by id
func (r CS3Repo) DeleteAccount(ctx context.Context, id string) (err error) {
t, err := r.authenticate(ctx)
if err != nil {
return err
}
ctx = metadata.AppendToOutgoingContext(ctx, token.TokenHeader, t)
resp, err := r.storageProvider.Delete(ctx, &provider.DeleteRequest{
Ref: &provider.Reference{
Spec: &provider.Reference_Path{Path: path.Join("/meta", accountsFolder, id)},
},
})
if err != nil {
return err
}
// TODO Handle other error codes?
if resp.Status.Code == v1beta11.Code_CODE_NOT_FOUND {
return &notFoundErr{"account", id}
}
return nil
}
// WriteGroup writes a group via cs3 and modifies the provided group (e.g. with a generated id).
func (r CS3Repo) WriteGroup(ctx context.Context, g *proto.Group) (err error) {
t, err := r.authenticate(ctx)
if err != nil {
return err
}
ctx = metadata.AppendToOutgoingContext(ctx, token.TokenHeader, t)
if err := r.makeRootDirIfNotExist(ctx, groupsFolder); err != nil {
return err
}
var by []byte
if by, err = json.Marshal(g); err != nil {
return err
}
resp, err := r.dataProvider.put(r.groupURL(g.Id), bytes.NewReader(by), t)
if err != nil {
return err
}
if err = resp.Body.Close(); err != nil {
return err
}
return nil
}
// LoadGroup loads a group via cs3 by id and writes it to the provided group
func (r CS3Repo) LoadGroup(ctx context.Context, id string, g *proto.Group) (err error) {
t, err := r.authenticate(ctx)
if err != nil {
return err
}
return r.loadGroup(id, t, g)
}
// LoadGroups loads all the groups from the cs3 api
func (r CS3Repo) LoadGroups(ctx context.Context, g *[]*proto.Group) (err error) {
t, err := r.authenticate(ctx)
if err != nil {
return err
}
ctx = metadata.AppendToOutgoingContext(ctx, token.TokenHeader, t)
res, err := r.storageProvider.ListContainer(ctx, &provider.ListContainerRequest{
Ref: &provider.Reference{
Spec: &provider.Reference_Path{Path: path.Join("/meta", groupsFolder)},
},
})
if err != nil {
return err
}
log := olog.NewLogger(olog.Pretty(r.cfg.Log.Pretty), olog.Color(r.cfg.Log.Color), olog.Level(r.cfg.Log.Level))
for i := range res.Infos {
grp := &proto.Group{}
err := r.loadGroup(filepath.Base(res.Infos[i].Path), t, grp)
if err != nil {
log.Err(err).Msg("could not load account")
continue
}
*g = append(*g, grp)
}
return nil
}
func (r CS3Repo) loadGroup(id string, t string, g *proto.Group) error {
resp, err := r.dataProvider.get(r.groupURL(id), t)
if err != nil {
return err
}
if resp.StatusCode == http.StatusNotFound {
return &notFoundErr{"group", id}
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if err = resp.Body.Close(); err != nil {
return err
}
return json.Unmarshal(b, &g)
}
// DeleteGroup deletes a group via cs3 by id
func (r CS3Repo) DeleteGroup(ctx context.Context, id string) (err error) {
t, err := r.authenticate(ctx)
if err != nil {
return err
}
ctx = metadata.AppendToOutgoingContext(ctx, token.TokenHeader, t)
resp, err := r.storageProvider.Delete(ctx, &provider.DeleteRequest{
Ref: &provider.Reference{
Spec: &provider.Reference_Path{Path: path.Join("/meta", groupsFolder, id)},
},
})
if err != nil {
return err
}
// TODO Handle other error codes?
if resp.Status.Code == v1beta11.Code_CODE_NOT_FOUND {
return &notFoundErr{"group", id}
}
return err
}
func (r CS3Repo) authenticate(ctx context.Context) (token string, err error) {
return AuthenticateCS3(ctx, r.cfg.ServiceUser, r.tm)
}
// AuthenticateCS3 mints an auth token for communicating with cs3 storage based on a service user from config
func AuthenticateCS3(ctx context.Context, su config.ServiceUser, tm token.Manager) (token string, err error) {
u := &user.User{
Id: &user.UserId{
OpaqueId: su.UUID,
},
Groups: []string{},
Opaque: &types.Opaque{
Map: map[string]*types.OpaqueEntry{
"uid": {
Decoder: "plain",
Value: []byte(strconv.FormatInt(su.UID, 10)),
},
"gid": {
Decoder: "plain",
Value: []byte(strconv.FormatInt(su.GID, 10)),
},
},
},
}
return tm.MintToken(ctx, u)
}
func (r CS3Repo) accountURL(id string) string {
return singleJoiningSlash(r.cfg.Repo.CS3.DataURL, path.Join(r.cfg.Repo.CS3.DataPrefix, accountsFolder, id))
}
func (r CS3Repo) groupURL(id string) string {
return singleJoiningSlash(r.cfg.Repo.CS3.DataURL, path.Join(r.cfg.Repo.CS3.DataPrefix, groupsFolder, id))
}
func (r CS3Repo) makeRootDirIfNotExist(ctx context.Context, folder string) error {
return MakeDirIfNotExist(ctx, r.storageProvider, folder)
}
// MakeDirIfNotExist will create a root node in the metadata storage. Requires an authenticated context.
func MakeDirIfNotExist(ctx context.Context, sp provider.ProviderAPIClient, folder string) error {
var rootPathRef = &provider.Reference{
Spec: &provider.Reference_Path{Path: path.Join("/meta", folder)},
}
resp, err := sp.Stat(ctx, &provider.StatRequest{
Ref: rootPathRef,
})
if err != nil {
return err
}
if resp.Status.Code == v1beta11.Code_CODE_NOT_FOUND {
_, err := sp.CreateContainer(ctx, &provider.CreateContainerRequest{
Ref: rootPathRef,
})
if err != nil {
return err
}
}
return nil
}
// TODO: this is copied from proxy. Find a better solution or move it to ocis-pkg
func singleJoiningSlash(a, b string) string {
aslash := strings.HasSuffix(a, "/")
bslash := strings.HasPrefix(b, "/")
switch {
case aslash && bslash:
return a + b[1:]
case !aslash && !bslash:
return a + "/" + b
}
return a + b
}
type dataProviderClient struct {
client http.Client
}
func (d dataProviderClient) put(url string, body io.Reader, token string) (*http.Response, error) {
req, err := http.NewRequest(http.MethodPut, url, body)
if err != nil {
return nil, err
}
req.Header.Add("x-access-token", token)
return d.client.Do(req)
}
func (d dataProviderClient) get(url string, token string) (*http.Response, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
req.Header.Add("x-access-token", token)
return d.client.Do(req)
}
-74
View File
@@ -1,74 +0,0 @@
package storage
// Uncomment to test locally, requires started metadata-storage for now
//import (
// "context"
// "github.com/owncloud/ocis/accounts/pkg/config"
// "github.com/owncloud/ocis/accounts/pkg/proto/v0"
// "github.com/stretchr/testify/assert"
// "testing"
//)
//
//var cfg = &config.Config{
// TokenManager: config.TokenManager{
// JWTSecret: "Pive-Fumkiu4",
// },
// Repo: config.Repo{
// CS3: config.CS3{
// ProviderAddr: "0.0.0.0:9215",
// DataURL: "http://localhost:9216",
// DataPrefix: "data",
// },
// },
//}
//
//func TestCS3Repo_WriteAccount(t *testing.T) {
// r, err := NewCS3Repo("hello", cfg)
// assert.NoError(t, err)
//
// err = r.WriteAccount(context.Background(), &proto.Account{
// Id: "fefef-egegweg-gegeg",
// AccountEnabled: true,
// DisplayName: "Mike Jones",
// Mail: "mike@example.com",
// })
//
// assert.NoError(t, err)
//}
//
//func TestCS3Repo_LoadAccount(t *testing.T) {
// r, err := NewCS3Repo("hello", cfg)
// assert.NoError(t, err)
//
// err = r.WriteAccount(context.Background(), &proto.Account{
// Id: "fefef-egegweg-gegeg",
// AccountEnabled: true,
// DisplayName: "Mike Jones",
// Mail: "mike@example.com",
// })
//
// acc := &proto.Account{}
// err = r.LoadAccount(context.Background(), "fefef-egegweg-gegeg", acc)
//
// assert.NoError(t, err)
// assert.Equal(t, "fefef-egegweg-gegeg", acc.Id)
// assert.Equal(t, "Mike Jones", acc.DisplayName)
// assert.Equal(t, "mike@example.com", acc.Mail)
//}
//
//func TestCS3Repo_DeleteAccount(t *testing.T) {
// r, err := NewCS3Repo("hello", cfg)
// assert.NoError(t, err)
//
// err = r.WriteAccount(context.Background(), &proto.Account{
// Id: "delete-me-id",
// AccountEnabled: true,
// DisplayName: "Mike Jones",
// Mail: "mike@example.com",
// })
//
// err = r.DeleteAccount(context.Background(), "delete-me-id")
//
// assert.NoError(t, err)
//}
-201
View File
@@ -1,201 +0,0 @@
package storage
import (
"context"
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
"sync"
"github.com/owncloud/ocis/accounts/pkg/config"
"github.com/owncloud/ocis/accounts/pkg/proto/v0"
olog "github.com/owncloud/ocis/ocis-pkg/log"
)
var groupLock sync.Mutex
// DiskRepo provides a local filesystem implementation of the Repo interface
type DiskRepo struct {
cfg *config.Config
log olog.Logger
}
// NewDiskRepo creates a new disk repo
func NewDiskRepo(cfg *config.Config, log olog.Logger) DiskRepo {
paths := []string{
filepath.Join(cfg.Repo.Disk.Path, accountsFolder),
filepath.Join(cfg.Repo.Disk.Path, groupsFolder),
}
for i := range paths {
if _, err := os.Stat(paths[i]); err != nil {
if os.IsNotExist(err) {
if err = os.MkdirAll(paths[i], 0700); err != nil {
log.Fatal().Err(err).Msgf("could not create data folder %v", paths[i])
}
}
}
}
return DiskRepo{
cfg: cfg,
log: log,
}
}
// WriteAccount to the local filesystem
func (r DiskRepo) WriteAccount(ctx context.Context, a *proto.Account) (err error) {
// leave only the group id
r.deflateMemberOf(a)
var bytes []byte
if bytes, err = json.Marshal(a); err != nil {
return err
}
path := filepath.Join(r.cfg.Repo.Disk.Path, accountsFolder, a.Id)
return ioutil.WriteFile(path, bytes, 0600)
}
// LoadAccount from the local filesystem
func (r DiskRepo) LoadAccount(ctx context.Context, id string, a *proto.Account) (err error) {
path := filepath.Join(r.cfg.Repo.Disk.Path, accountsFolder, id)
var data []byte
if data, err = ioutil.ReadFile(path); err != nil {
if os.IsNotExist(err) {
err = &notFoundErr{"account", id}
}
return
}
return json.Unmarshal(data, a)
}
// LoadAccounts loads all the accounts from the local filesystem
func (r DiskRepo) LoadAccounts(ctx context.Context, a *[]*proto.Account) (err error) {
root := filepath.Join(r.cfg.Repo.Disk.Path, accountsFolder)
infos, err := ioutil.ReadDir(root)
if err != nil {
return err
}
for i := range infos {
acc := &proto.Account{}
if e := r.LoadAccount(ctx, infos[i].Name(), acc); e != nil {
r.log.Err(e).Msg("could not load account")
continue
}
*a = append(*a, acc)
}
return nil
}
// DeleteAccount from the local filesystem
func (r DiskRepo) DeleteAccount(ctx context.Context, id string) (err error) {
path := filepath.Join(r.cfg.Repo.Disk.Path, accountsFolder, id)
if err = os.Remove(path); err != nil {
if os.IsNotExist(err) {
err = &notFoundErr{"account", id}
}
}
return
}
// WriteGroup to the local filesystem
func (r DiskRepo) WriteGroup(ctx context.Context, g *proto.Group) (err error) {
// leave only the member id
r.deflateMembers(g)
var bytes []byte
if bytes, err = json.Marshal(g); err != nil {
return err
}
path := filepath.Join(r.cfg.Repo.Disk.Path, groupsFolder, g.Id)
groupLock.Lock()
defer groupLock.Unlock()
return ioutil.WriteFile(path, bytes, 0600)
}
// LoadGroup from the local filesystem
func (r DiskRepo) LoadGroup(ctx context.Context, id string, g *proto.Group) (err error) {
path := filepath.Join(r.cfg.Repo.Disk.Path, groupsFolder, id)
groupLock.Lock()
defer groupLock.Unlock()
var data []byte
if data, err = ioutil.ReadFile(path); err != nil {
if os.IsNotExist(err) {
err = &notFoundErr{"group", id}
}
return
}
return json.Unmarshal(data, g)
}
// LoadGroups loads all the groups from the local filesystem
func (r DiskRepo) LoadGroups(ctx context.Context, g *[]*proto.Group) (err error) {
root := filepath.Join(r.cfg.Repo.Disk.Path, groupsFolder)
infos, err := ioutil.ReadDir(root)
if err != nil {
return err
}
for i := range infos {
grp := &proto.Group{}
if e := r.LoadGroup(ctx, infos[i].Name(), grp); e != nil {
r.log.Err(e).Msg("could not load group")
continue
}
*g = append(*g, grp)
}
return nil
}
// DeleteGroup from the local filesystem
func (r DiskRepo) DeleteGroup(ctx context.Context, id string) (err error) {
path := filepath.Join(r.cfg.Repo.Disk.Path, groupsFolder, id)
if err = os.Remove(path); err != nil {
if os.IsNotExist(err) {
err = &notFoundErr{"account", id}
}
}
return
}
// deflateMemberOf replaces the groups of a user with an instance that only contains the id
func (r DiskRepo) deflateMemberOf(a *proto.Account) {
if a == nil {
return
}
var deflated []*proto.Group
for i := range a.MemberOf {
if a.MemberOf[i].Id != "" {
deflated = append(deflated, &proto.Group{Id: a.MemberOf[i].Id})
} else {
// TODO fetch and use an id when group only has a name but no id
r.log.Error().Str("id", a.Id).Interface("group", a.MemberOf[i]).Msg("resolving groups by name is not implemented yet")
}
}
a.MemberOf = deflated
}
// deflateMembers replaces the users of a group with an instance that only contains the id
func (r DiskRepo) deflateMembers(g *proto.Group) {
if g == nil {
return
}
var deflated []*proto.Account
for i := range g.Members {
if g.Members[i].Id != "" {
deflated = append(deflated, &proto.Account{Id: g.Members[i].Id})
} else {
// TODO fetch and use an id when group only has a name but no id
r.log.Error().Str("id", g.Id).Interface("account", g.Members[i]).Msg("resolving members by name is not implemented yet")
}
}
g.Members = deflated
}
-19
View File
@@ -1,19 +0,0 @@
package storage
import (
"fmt"
)
type notFoundErr struct {
typ, id string
}
func (e *notFoundErr) Error() string {
return fmt.Sprintf("%s with id %s not found", e.typ, e.id)
}
// IsNotFoundErr can be returned by repo Load and Delete operations
func IsNotFoundErr(e error) bool {
_, ok := e.(*notFoundErr)
return ok
}
-24
View File
@@ -1,24 +0,0 @@
package storage
import (
"context"
"github.com/owncloud/ocis/accounts/pkg/proto/v0"
)
const (
accountsFolder = "accounts"
groupsFolder = "groups"
)
// Repo defines the storage operations
type Repo interface {
WriteAccount(ctx context.Context, a *proto.Account) (err error)
LoadAccount(ctx context.Context, id string, a *proto.Account) (err error)
LoadAccounts(ctx context.Context, a *[]*proto.Account) (err error)
DeleteAccount(ctx context.Context, id string) (err error)
WriteGroup(ctx context.Context, g *proto.Group) (err error)
LoadGroup(ctx context.Context, id string, g *proto.Group) (err error)
LoadGroups(ctx context.Context, g *[]*proto.Group) (err error)
DeleteGroup(ctx context.Context, id string) (err error)
}
-19
View File
@@ -1,19 +0,0 @@
package version
import (
"time"
)
var (
// String gets defined by the build system.
String = "0.0.0"
// Date indicates the build date.
Date = "00000000"
)
// Compiled returns the compile time of this service.
func Compiled() time.Time {
t, _ := time.Parse("20060102", Date)
return t
}
-5
View File
@@ -1,5 +0,0 @@
# backend
-r '^(cmd|pkg)/.*\.go$' -R '^node_modules/' -s -- sh -c 'make bin/ocis-accounts && bin/ocis-accounts server --asset-path assets/'
# frontend
-r '^ui/.*\.(vue|js)$' -R '^node_modules/' -- sh -c 'yarn build && make generate'
-52
View File
@@ -1,52 +0,0 @@
import vue from 'rollup-plugin-vue'
import { terser } from 'rollup-plugin-terser'
import replace from '@rollup/plugin-replace'
import filesize from 'rollup-plugin-filesize'
import resolve from 'rollup-plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
import babel from 'rollup-plugin-babel'
import json from '@rollup/plugin-json'
import builtins from '@erquhart/rollup-plugin-node-builtins'
import globals from 'rollup-plugin-node-globals'
const production = !process.env.ROLLUP_WATCH
// We can't really do much about circular dependencies in node_modules
function onwarn (warning) {
if (warning.code !== 'CIRCULAR_DEPENDENCY') {
console.error(`(!) ${warning.message}`)
}
}
export default {
input: 'ui/app.js',
output: {
file: 'assets/accounts.js',
format: 'amd',
sourcemap: !production
},
onwarn,
plugins: [
vue(),
replace({
'process.env.NODE_ENV': JSON.stringify('production')
}),
resolve({
mainFields: ['browser', 'jsnext', 'module', 'main'],
include: 'node_modules/**',
preferBuiltins: true
}),
babel({
exclude: 'node_modules/**',
runtimeHelpers: true
}),
commonjs({
include: 'node_modules/**'
}),
json(),
globals(),
builtins(),
production && terser(),
production && filesize()
]
}
-76
View File
@@ -1,76 +0,0 @@
---
title: "Configuration"
date: "{{ date "2006-01-02T15:04:05-0700" now }}"
weight: 20
geekdocRepo: https://github.com/owncloud/ocis
geekdocEditPath: edit/master/accounts/templates
geekdocFilePath: CONFIGURATION.tmpl
---
{{- define "options"}}
{{ $fnName := (last . ).Flags -}}
{{ range $opt := first . }}{{ with list $fnName $opt -}}
{{ $o := last . -}}
{{ if eq $o.FnName $fnName -}}
-{{ $o.Name }} | {{ range $i, $e := $o.Env }} {{ if $i }}, {{ end }}${{ $e }}{{ end }}
: {{ $o.Usage }}. {{- if $o.Default }} Default: `{{ $o.Default }}`.{{ end }}
{{ end -}}
{{ end -}}
{{ end -}}
{{ end }}
{{`{{< toc >}}`}}
## Configuration
### Configuration using config files
Out of the box extensions will attempt to read configuration details from:
```console
/etc/ocis
$HOME/.ocis
./config
```
For this configuration to be picked up, have a look at your extension `root` command and look for which default config name it has assigned. *i.e: ocis-accounts reads `accounts.json | yaml | toml ...`*.
So far we support the file formats `JSON` and `YAML`, if you want to get a full example configuration just take a look at [our repository](https://github.com/owncloud/ocis/tree/master/config), there you can always see the latest configuration format. These example configurations include all available options and the default values. The configuration file will be automatically loaded if it's placed at `/etc/ocis/ocis.yml`, `${HOME}/.ocis/ocis.yml` or `$(pwd)/config/ocis.yml`.
### Environment variables
If you prefer to configure the service with environment variables you can see the available variables below.
If multiple variables are listed for one option, they are in order of precedence. This means the leftmost variable will always win if given.
### Commandline flags
If you prefer to configure the service with commandline flags you can see the available variables below. Command line flags are only working when calling the subcommand directly.
{{ $options := .Options -}}
{{ range $com := .Commands }}{{ with (list $options $com) -}}
{{ $c := last . -}}
{{ if eq $c.Name "accounts" -}}
## Root Command
{{ $c.Usage }}
Usage: `accounts [global options] command [command options] [arguments...]`
{{ template "options" . -}}
## Sub Commands
{{ end -}}
{{ end -}}
{{ end -}}
{{- range $com := .Commands }}{{ with (list $options $com) -}}
{{- $c := last . }}
{{- if ne $c.Name "accounts" -}}
### accounts {{ $c.Name }}
{{ $c.Usage }}
Usage: `accounts {{ $c.Name }} [command options] [arguments...]`
{{ template "options" . }}
{{- end -}}
{{- end -}}
{{- end -}}
-31
View File
@@ -1,31 +0,0 @@
// Copyright (c) 2015, Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
syntax = "proto3";
package google.api;
import "google/api/http.proto";
import "google/protobuf/descriptor.proto";
option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations";
option java_multiple_files = true;
option java_outer_classname = "AnnotationsProto";
option java_package = "com.google.api";
option objc_class_prefix = "GAPI";
extend google.protobuf.MethodOptions {
// See `HttpRule`.
HttpRule http = 72295728;
}
-79
View File
@@ -1,79 +0,0 @@
// Copyright 2019 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
syntax = "proto3";
package google.api;
import "google/protobuf/descriptor.proto";
option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations";
option java_multiple_files = true;
option java_outer_classname = "FieldBehaviorProto";
option java_package = "com.google.api";
option objc_class_prefix = "GAPI";
extend google.protobuf.FieldOptions {
// A designation of a specific field behavior (required, output only, etc.)
// in protobuf messages.
//
// Examples:
//
// string name = 1 [(google.api.field_behavior) = REQUIRED];
// State state = 1 [(google.api.field_behavior) = OUTPUT_ONLY];
// google.protobuf.Duration ttl = 1
// [(google.api.field_behavior) = INPUT_ONLY];
// google.protobuf.Timestamp expire_time = 1
// [(google.api.field_behavior) = OUTPUT_ONLY,
// (google.api.field_behavior) = IMMUTABLE];
repeated google.api.FieldBehavior field_behavior = 1052;
}
// An indicator of the behavior of a given field (for example, that a field
// is required in requests, or given as output but ignored as input).
// This **does not** change the behavior in protocol buffers itself; it only
// denotes the behavior and may affect how API tooling handles the field.
//
// Note: This enum **may** receive new values in the future.
enum FieldBehavior {
// Conventional default for enums. Do not use this.
FIELD_BEHAVIOR_UNSPECIFIED = 0;
// Specifically denotes a field as optional.
// While all fields in protocol buffers are optional, this may be specified
// for emphasis if appropriate.
OPTIONAL = 1;
// Denotes a field as required.
// This indicates that the field **must** be provided as part of the request,
// and failure to do so will cause an error (usually `INVALID_ARGUMENT`).
REQUIRED = 2;
// Denotes a field as output only.
// This indicates that the field is provided in responses, but including the
// field in a request does nothing (the server *must* ignore it and
// *must not* throw an error as a result of the field's presence).
OUTPUT_ONLY = 3;
// Denotes a field as input only.
// This indicates that the field is provided in requests, and the
// corresponding field is not included in output.
INPUT_ONLY = 4;
// Denotes a field as immutable.
// This indicates that the field may be set once in a request to create a
// resource, but may not be changed thereafter.
IMMUTABLE = 5;
}
-376
View File
@@ -1,376 +0,0 @@
// Copyright 2019 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
syntax = "proto3";
package google.api;
option cc_enable_arenas = true;
option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations";
option java_multiple_files = true;
option java_outer_classname = "HttpProto";
option java_package = "com.google.api";
option objc_class_prefix = "GAPI";
// Defines the HTTP configuration for an API service. It contains a list of
// [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method
// to one or more HTTP REST API methods.
message Http {
// A list of HTTP configuration rules that apply to individual API methods.
//
// **NOTE:** All service configuration rules follow "last one wins" order.
repeated HttpRule rules = 1;
// When set to true, URL path parameters will be fully URI-decoded except in
// cases of single segment matches in reserved expansion, where "%2F" will be
// left encoded.
//
// The default behavior is to not decode RFC 6570 reserved characters in multi
// segment matches.
bool fully_decode_reserved_expansion = 2;
}
// # gRPC Transcoding
//
// gRPC Transcoding is a feature for mapping between a gRPC method and one or
// more HTTP REST endpoints. It allows developers to build a single API service
// that supports both gRPC APIs and REST APIs. Many systems, including [Google
// APIs](https://github.com/googleapis/googleapis),
// [Cloud Endpoints](https://cloud.google.com/endpoints), [gRPC
// Gateway](https://github.com/grpc-ecosystem/grpc-gateway),
// and [Envoy](https://github.com/envoyproxy/envoy) proxy support this feature
// and use it for large scale production services.
//
// `HttpRule` defines the schema of the gRPC/REST mapping. The mapping specifies
// how different portions of the gRPC request message are mapped to the URL
// path, URL query parameters, and HTTP request body. It also controls how the
// gRPC response message is mapped to the HTTP response body. `HttpRule` is
// typically specified as an `google.api.http` annotation on the gRPC method.
//
// Each mapping specifies a URL path template and an HTTP method. The path
// template may refer to one or more fields in the gRPC request message, as long
// as each field is a non-repeated field with a primitive (non-message) type.
// The path template controls how fields of the request message are mapped to
// the URL path.
//
// Example:
//
// service Messaging {
// rpc GetMessage(GetMessageRequest) returns (Message) {
// option (google.api.http) = {
// get: "/v1/{name=messages/*}"
// };
// }
// }
// message GetMessageRequest {
// string name = 1; // Mapped to URL path.
// }
// message Message {
// string text = 1; // The resource content.
// }
//
// This enables an HTTP REST to gRPC mapping as below:
//
// HTTP | gRPC
// -----|-----
// `GET /v1/messages/123456` | `GetMessage(name: "messages/123456")`
//
// Any fields in the request message which are not bound by the path template
// automatically become HTTP query parameters if there is no HTTP request body.
// For example:
//
// service Messaging {
// rpc GetMessage(GetMessageRequest) returns (Message) {
// option (google.api.http) = {
// get:"/v1/messages/{message_id}"
// };
// }
// }
// message GetMessageRequest {
// message SubMessage {
// string subfield = 1;
// }
// string message_id = 1; // Mapped to URL path.
// int64 revision = 2; // Mapped to URL query parameter `revision`.
// SubMessage sub = 3; // Mapped to URL query parameter `sub.subfield`.
// }
//
// This enables a HTTP JSON to RPC mapping as below:
//
// HTTP | gRPC
// -----|-----
// `GET /v1/messages/123456?revision=2&sub.subfield=foo` |
// `GetMessage(message_id: "123456" revision: 2 sub: SubMessage(subfield:
// "foo"))`
//
// Note that fields which are mapped to URL query parameters must have a
// primitive type or a repeated primitive type or a non-repeated message type.
// In the case of a repeated type, the parameter can be repeated in the URL
// as `...?param=A&param=B`. In the case of a message type, each field of the
// message is mapped to a separate parameter, such as
// `...?foo.a=A&foo.b=B&foo.c=C`.
//
// For HTTP methods that allow a request body, the `body` field
// specifies the mapping. Consider a REST update method on the
// message resource collection:
//
// service Messaging {
// rpc UpdateMessage(UpdateMessageRequest) returns (Message) {
// option (google.api.http) = {
// patch: "/v1/messages/{message_id}"
// body: "message"
// };
// }
// }
// message UpdateMessageRequest {
// string message_id = 1; // mapped to the URL
// Message message = 2; // mapped to the body
// }
//
// The following HTTP JSON to RPC mapping is enabled, where the
// representation of the JSON in the request body is determined by
// protos JSON encoding:
//
// HTTP | gRPC
// -----|-----
// `PATCH /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id:
// "123456" message { text: "Hi!" })`
//
// The special name `*` can be used in the body mapping to define that
// every field not bound by the path template should be mapped to the
// request body. This enables the following alternative definition of
// the update method:
//
// service Messaging {
// rpc UpdateMessage(Message) returns (Message) {
// option (google.api.http) = {
// patch: "/v1/messages/{message_id}"
// body: "*"
// };
// }
// }
// message Message {
// string message_id = 1;
// string text = 2;
// }
//
//
// The following HTTP JSON to RPC mapping is enabled:
//
// HTTP | gRPC
// -----|-----
// `PATCH /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id:
// "123456" text: "Hi!")`
//
// Note that when using `*` in the body mapping, it is not possible to
// have HTTP parameters, as all fields not bound by the path end in
// the body. This makes this option more rarely used in practice when
// defining REST APIs. The common usage of `*` is in custom methods
// which don't use the URL at all for transferring data.
//
// It is possible to define multiple HTTP methods for one RPC by using
// the `additional_bindings` option. Example:
//
// service Messaging {
// rpc GetMessage(GetMessageRequest) returns (Message) {
// option (google.api.http) = {
// get: "/v1/messages/{message_id}"
// additional_bindings {
// get: "/v1/users/{user_id}/messages/{message_id}"
// }
// };
// }
// }
// message GetMessageRequest {
// string message_id = 1;
// string user_id = 2;
// }
//
// This enables the following two alternative HTTP JSON to RPC mappings:
//
// HTTP | gRPC
// -----|-----
// `GET /v1/messages/123456` | `GetMessage(message_id: "123456")`
// `GET /v1/users/me/messages/123456` | `GetMessage(user_id: "me" message_id:
// "123456")`
//
// ## Rules for HTTP mapping
//
// 1. Leaf request fields (recursive expansion nested messages in the request
// message) are classified into three categories:
// - Fields referred by the path template. They are passed via the URL path.
// - Fields referred by the [HttpRule.body][google.api.HttpRule.body]. They are passed via the HTTP
// request body.
// - All other fields are passed via the URL query parameters, and the
// parameter name is the field path in the request message. A repeated
// field can be represented as multiple query parameters under the same
// name.
// 2. If [HttpRule.body][google.api.HttpRule.body] is "*", there is no URL query parameter, all fields
// are passed via URL path and HTTP request body.
// 3. If [HttpRule.body][google.api.HttpRule.body] is omitted, there is no HTTP request body, all
// fields are passed via URL path and URL query parameters.
//
// ### Path template syntax
//
// Template = "/" Segments [ Verb ] ;
// Segments = Segment { "/" Segment } ;
// Segment = "*" | "**" | LITERAL | Variable ;
// Variable = "{" FieldPath [ "=" Segments ] "}" ;
// FieldPath = IDENT { "." IDENT } ;
// Verb = ":" LITERAL ;
//
// The syntax `*` matches a single URL path segment. The syntax `**` matches
// zero or more URL path segments, which must be the last part of the URL path
// except the `Verb`.
//
// The syntax `Variable` matches part of the URL path as specified by its
// template. A variable template must not contain other variables. If a variable
// matches a single path segment, its template may be omitted, e.g. `{var}`
// is equivalent to `{var=*}`.
//
// The syntax `LITERAL` matches literal text in the URL path. If the `LITERAL`
// contains any reserved character, such characters should be percent-encoded
// before the matching.
//
// If a variable contains exactly one path segment, such as `"{var}"` or
// `"{var=*}"`, when such a variable is expanded into a URL path on the client
// side, all characters except `[-_.~0-9a-zA-Z]` are percent-encoded. The
// server side does the reverse decoding. Such variables show up in the
// [Discovery
// Document](https://developers.google.com/discovery/v1/reference/apis) as
// `{var}`.
//
// If a variable contains multiple path segments, such as `"{var=foo/*}"`
// or `"{var=**}"`, when such a variable is expanded into a URL path on the
// client side, all characters except `[-_.~/0-9a-zA-Z]` are percent-encoded.
// The server side does the reverse decoding, except "%2F" and "%2f" are left
// unchanged. Such variables show up in the
// [Discovery
// Document](https://developers.google.com/discovery/v1/reference/apis) as
// `{+var}`.
//
// ## Using gRPC API Service Configuration
//
// gRPC API Service Configuration (service config) is a configuration language
// for configuring a gRPC service to become a user-facing product. The
// service config is simply the YAML representation of the `google.api.Service`
// proto message.
//
// As an alternative to annotating your proto file, you can configure gRPC
// transcoding in your service config YAML files. You do this by specifying a
// `HttpRule` that maps the gRPC method to a REST endpoint, achieving the same
// effect as the proto annotation. This can be particularly useful if you
// have a proto that is reused in multiple services. Note that any transcoding
// specified in the service config will override any matching transcoding
// configuration in the proto.
//
// Example:
//
// http:
// rules:
// # Selects a gRPC method and applies HttpRule to it.
// - selector: example.v1.Messaging.GetMessage
// get: /v1/messages/{message_id}/{sub.subfield}
//
// ## Special notes
//
// When gRPC Transcoding is used to map a gRPC to JSON REST endpoints, the
// proto to JSON conversion must follow the [proto3
// specification](https://developers.google.com/protocol-buffers/docs/proto3#json).
//
// While the single segment variable follows the semantics of
// [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2 Simple String
// Expansion, the multi segment variable **does not** follow RFC 6570 Section
// 3.2.3 Reserved Expansion. The reason is that the Reserved Expansion
// does not expand special characters like `?` and `#`, which would lead
// to invalid URLs. As the result, gRPC Transcoding uses a custom encoding
// for multi segment variables.
//
// The path variables **must not** refer to any repeated or mapped field,
// because client libraries are not capable of handling such variable expansion.
//
// The path variables **must not** capture the leading "/" character. The reason
// is that the most common use case "{var}" does not capture the leading "/"
// character. For consistency, all path variables must share the same behavior.
//
// Repeated message fields must not be mapped to URL query parameters, because
// no client library can support such complicated mapping.
//
// If an API needs to use a JSON array for request or response body, it can map
// the request or response body to a repeated field. However, some gRPC
// Transcoding implementations may not support this feature.
message HttpRule {
// Selects a method to which this rule applies.
//
// Refer to [selector][google.api.DocumentationRule.selector] for syntax details.
string selector = 1;
// Determines the URL pattern is matched by this rules. This pattern can be
// used with any of the {get|put|post|delete|patch} methods. A custom method
// can be defined using the 'custom' field.
oneof pattern {
// Maps to HTTP GET. Used for listing and getting information about
// resources.
string get = 2;
// Maps to HTTP PUT. Used for replacing a resource.
string put = 3;
// Maps to HTTP POST. Used for creating a resource or performing an action.
string post = 4;
// Maps to HTTP DELETE. Used for deleting a resource.
string delete = 5;
// Maps to HTTP PATCH. Used for updating a resource.
string patch = 6;
// The custom pattern is used for specifying an HTTP method that is not
// included in the `pattern` field, such as HEAD, or "*" to leave the
// HTTP method unspecified for this rule. The wild-card rule is useful
// for services that provide content to Web (HTML) clients.
CustomHttpPattern custom = 8;
}
// The name of the request field whose value is mapped to the HTTP request
// body, or `*` for mapping all request fields not captured by the path
// pattern to the HTTP body, or omitted for not having any HTTP request body.
//
// NOTE: the referred field must be present at the top-level of the request
// message type.
string body = 7;
// Optional. The name of the response field whose value is mapped to the HTTP
// response body. When omitted, the entire response message will be used
// as the HTTP response body.
//
// NOTE: The referred field must be present at the top-level of the response
// message type.
string response_body = 12;
// Additional HTTP bindings for the selector. Nested bindings must
// not contain an `additional_bindings` field themselves (that is,
// the nesting may only be one level deep).
repeated HttpRule additional_bindings = 11;
}
// A custom pattern is used for defining custom HTTP verb.
message CustomHttpPattern {
// The name of this custom HTTP verb.
string kind = 1;
// The path matched by this custom verb.
string path = 2;
}
-909
View File
@@ -1,909 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// The messages in this file describe the definitions found in .proto files.
// A valid .proto file can be translated directly to a FileDescriptorProto
// without any other information (e.g. without reading its imports).
syntax = "proto2";
package google.protobuf;
option go_package = "github.com/golang/protobuf/protoc-gen-go/descriptor;descriptor";
option java_package = "com.google.protobuf";
option java_outer_classname = "DescriptorProtos";
option csharp_namespace = "Google.Protobuf.Reflection";
option objc_class_prefix = "GPB";
option cc_enable_arenas = true;
// descriptor.proto must be optimized for speed because reflection-based
// algorithms don't work during bootstrapping.
option optimize_for = SPEED;
// The protocol compiler can output a FileDescriptorSet containing the .proto
// files it parses.
message FileDescriptorSet {
repeated FileDescriptorProto file = 1;
}
// Describes a complete .proto file.
message FileDescriptorProto {
optional string name = 1; // file name, relative to root of source tree
optional string package = 2; // e.g. "foo", "foo.bar", etc.
// Names of files imported by this file.
repeated string dependency = 3;
// Indexes of the public imported files in the dependency list above.
repeated int32 public_dependency = 10;
// Indexes of the weak imported files in the dependency list.
// For Google-internal migration only. Do not use.
repeated int32 weak_dependency = 11;
// All top-level definitions in this file.
repeated DescriptorProto message_type = 4;
repeated EnumDescriptorProto enum_type = 5;
repeated ServiceDescriptorProto service = 6;
repeated FieldDescriptorProto extension = 7;
optional FileOptions options = 8;
// This field contains optional information about the original source code.
// You may safely remove this entire field without harming runtime
// functionality of the descriptors -- the information is needed only by
// development tools.
optional SourceCodeInfo source_code_info = 9;
// The syntax of the proto file.
// The supported values are "proto2" and "proto3".
optional string syntax = 12;
}
// Describes a message type.
message DescriptorProto {
optional string name = 1;
repeated FieldDescriptorProto field = 2;
repeated FieldDescriptorProto extension = 6;
repeated DescriptorProto nested_type = 3;
repeated EnumDescriptorProto enum_type = 4;
message ExtensionRange {
optional int32 start = 1; // Inclusive.
optional int32 end = 2; // Exclusive.
optional ExtensionRangeOptions options = 3;
}
repeated ExtensionRange extension_range = 5;
repeated OneofDescriptorProto oneof_decl = 8;
optional MessageOptions options = 7;
// Range of reserved tag numbers. Reserved tag numbers may not be used by
// fields or extension ranges in the same message. Reserved ranges may
// not overlap.
message ReservedRange {
optional int32 start = 1; // Inclusive.
optional int32 end = 2; // Exclusive.
}
repeated ReservedRange reserved_range = 9;
// Reserved field names, which may not be used by fields in the same message.
// A given name may only be reserved once.
repeated string reserved_name = 10;
}
message ExtensionRangeOptions {
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
// Describes a field within a message.
message FieldDescriptorProto {
enum Type {
// 0 is reserved for errors.
// Order is weird for historical reasons.
TYPE_DOUBLE = 1;
TYPE_FLOAT = 2;
// Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
// negative values are likely.
TYPE_INT64 = 3;
TYPE_UINT64 = 4;
// Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
// negative values are likely.
TYPE_INT32 = 5;
TYPE_FIXED64 = 6;
TYPE_FIXED32 = 7;
TYPE_BOOL = 8;
TYPE_STRING = 9;
// Tag-delimited aggregate.
// Group type is deprecated and not supported in proto3. However, Proto3
// implementations should still be able to parse the group wire format and
// treat group fields as unknown fields.
TYPE_GROUP = 10;
TYPE_MESSAGE = 11; // Length-delimited aggregate.
// New in version 2.
TYPE_BYTES = 12;
TYPE_UINT32 = 13;
TYPE_ENUM = 14;
TYPE_SFIXED32 = 15;
TYPE_SFIXED64 = 16;
TYPE_SINT32 = 17; // Uses ZigZag encoding.
TYPE_SINT64 = 18; // Uses ZigZag encoding.
}
enum Label {
// 0 is reserved for errors
LABEL_OPTIONAL = 1;
LABEL_REQUIRED = 2;
LABEL_REPEATED = 3;
}
optional string name = 1;
optional int32 number = 3;
optional Label label = 4;
// If type_name is set, this need not be set. If both this and type_name
// are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP.
optional Type type = 5;
// For message and enum types, this is the name of the type. If the name
// starts with a '.', it is fully-qualified. Otherwise, C++-like scoping
// rules are used to find the type (i.e. first the nested types within this
// message are searched, then within the parent, on up to the root
// namespace).
optional string type_name = 6;
// For extensions, this is the name of the type being extended. It is
// resolved in the same manner as type_name.
optional string extendee = 2;
// For numeric types, contains the original text representation of the value.
// For booleans, "true" or "false".
// For strings, contains the default text contents (not escaped in any way).
// For bytes, contains the C escaped value. All bytes >= 128 are escaped.
// TODO(kenton): Base-64 encode?
optional string default_value = 7;
// If set, gives the index of a oneof in the containing type's oneof_decl
// list. This field is a member of that oneof.
optional int32 oneof_index = 9;
// JSON name of this field. The value is set by protocol compiler. If the
// user has set a "json_name" option on this field, that option's value
// will be used. Otherwise, it's deduced from the field's name by converting
// it to camelCase.
optional string json_name = 10;
optional FieldOptions options = 8;
// If true, this is a proto3 "optional". When a proto3 field is optional, it
// tracks presence regardless of field type.
//
// When proto3_optional is true, this field must be belong to a oneof to
// signal to old proto3 clients that presence is tracked for this field. This
// oneof is known as a "synthetic" oneof, and this field must be its sole
// member (each proto3 optional field gets its own synthetic oneof). Synthetic
// oneofs exist in the descriptor only, and do not generate any API. Synthetic
// oneofs must be ordered after all "real" oneofs.
//
// For message fields, proto3_optional doesn't create any semantic change,
// since non-repeated message fields always track presence. However it still
// indicates the semantic detail of whether the user wrote "optional" or not.
// This can be useful for round-tripping the .proto file. For consistency we
// give message fields a synthetic oneof also, even though it is not required
// to track presence. This is especially important because the parser can't
// tell if a field is a message or an enum, so it must always create a
// synthetic oneof.
//
// Proto2 optional fields do not set this flag, because they already indicate
// optional with `LABEL_OPTIONAL`.
optional bool proto3_optional = 17;
}
// Describes a oneof.
message OneofDescriptorProto {
optional string name = 1;
optional OneofOptions options = 2;
}
// Describes an enum type.
message EnumDescriptorProto {
optional string name = 1;
repeated EnumValueDescriptorProto value = 2;
optional EnumOptions options = 3;
// Range of reserved numeric values. Reserved values may not be used by
// entries in the same enum. Reserved ranges may not overlap.
//
// Note that this is distinct from DescriptorProto.ReservedRange in that it
// is inclusive such that it can appropriately represent the entire int32
// domain.
message EnumReservedRange {
optional int32 start = 1; // Inclusive.
optional int32 end = 2; // Inclusive.
}
// Range of reserved numeric values. Reserved numeric values may not be used
// by enum values in the same enum declaration. Reserved ranges may not
// overlap.
repeated EnumReservedRange reserved_range = 4;
// Reserved enum value names, which may not be reused. A given name may only
// be reserved once.
repeated string reserved_name = 5;
}
// Describes a value within an enum.
message EnumValueDescriptorProto {
optional string name = 1;
optional int32 number = 2;
optional EnumValueOptions options = 3;
}
// Describes a service.
message ServiceDescriptorProto {
optional string name = 1;
repeated MethodDescriptorProto method = 2;
optional ServiceOptions options = 3;
}
// Describes a method of a service.
message MethodDescriptorProto {
optional string name = 1;
// Input and output type names. These are resolved in the same way as
// FieldDescriptorProto.type_name, but must refer to a message type.
optional string input_type = 2;
optional string output_type = 3;
optional MethodOptions options = 4;
// Identifies if client streams multiple client messages
optional bool client_streaming = 5 [default = false];
// Identifies if server streams multiple server messages
optional bool server_streaming = 6 [default = false];
}
// ===================================================================
// Options
// Each of the definitions above may have "options" attached. These are
// just annotations which may cause code to be generated slightly differently
// or may contain hints for code that manipulates protocol messages.
//
// Clients may define custom options as extensions of the *Options messages.
// These extensions may not yet be known at parsing time, so the parser cannot
// store the values in them. Instead it stores them in a field in the *Options
// message called uninterpreted_option. This field must have the same name
// across all *Options messages. We then use this field to populate the
// extensions when we build a descriptor, at which point all protos have been
// parsed and so all extensions are known.
//
// Extension numbers for custom options may be chosen as follows:
// * For options which will only be used within a single application or
// organization, or for experimental options, use field numbers 50000
// through 99999. It is up to you to ensure that you do not use the
// same number for multiple options.
// * For options which will be published and used publicly by multiple
// independent entities, e-mail protobuf-global-extension-registry@google.com
// to reserve extension numbers. Simply provide your project name (e.g.
// Objective-C plugin) and your project website (if available) -- there's no
// need to explain how you intend to use them. Usually you only need one
// extension number. You can declare multiple options with only one extension
// number by putting them in a sub-message. See the Custom Options section of
// the docs for examples:
// https://developers.google.com/protocol-buffers/docs/proto#options
// If this turns out to be popular, a web service will be set up
// to automatically assign option numbers.
message FileOptions {
// Sets the Java package where classes generated from this .proto will be
// placed. By default, the proto package is used, but this is often
// inappropriate because proto packages do not normally start with backwards
// domain names.
optional string java_package = 1;
// If set, all the classes from the .proto file are wrapped in a single
// outer class with the given name. This applies to both Proto1
// (equivalent to the old "--one_java_file" option) and Proto2 (where
// a .proto always translates to a single class, but you may want to
// explicitly choose the class name).
optional string java_outer_classname = 8;
// If set true, then the Java code generator will generate a separate .java
// file for each top-level message, enum, and service defined in the .proto
// file. Thus, these types will *not* be nested inside the outer class
// named by java_outer_classname. However, the outer class will still be
// generated to contain the file's getDescriptor() method as well as any
// top-level extensions defined in the file.
optional bool java_multiple_files = 10 [default = false];
// This option does nothing.
optional bool java_generate_equals_and_hash = 20 [deprecated=true];
// If set true, then the Java2 code generator will generate code that
// throws an exception whenever an attempt is made to assign a non-UTF-8
// byte sequence to a string field.
// Message reflection will do the same.
// However, an extension field still accepts non-UTF-8 byte sequences.
// This option has no effect on when used with the lite runtime.
optional bool java_string_check_utf8 = 27 [default = false];
// Generated classes can be optimized for speed or code size.
enum OptimizeMode {
SPEED = 1; // Generate complete code for parsing, serialization,
// etc.
CODE_SIZE = 2; // Use ReflectionOps to implement these methods.
LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime.
}
optional OptimizeMode optimize_for = 9 [default = SPEED];
// Sets the Go package where structs generated from this .proto will be
// placed. If omitted, the Go package will be derived from the following:
// - The basename of the package import path, if provided.
// - Otherwise, the package statement in the .proto file, if present.
// - Otherwise, the basename of the .proto file, without extension.
optional string go_package = 11;
// Should generic services be generated in each language? "Generic" services
// are not specific to any particular RPC system. They are generated by the
// main code generators in each language (without additional plugins).
// Generic services were the only kind of service generation supported by
// early versions of google.protobuf.
//
// Generic services are now considered deprecated in favor of using plugins
// that generate code specific to your particular RPC system. Therefore,
// these default to false. Old code which depends on generic services should
// explicitly set them to true.
optional bool cc_generic_services = 16 [default = false];
optional bool java_generic_services = 17 [default = false];
optional bool py_generic_services = 18 [default = false];
optional bool php_generic_services = 42 [default = false];
// Is this file deprecated?
// Depending on the target platform, this can emit Deprecated annotations
// for everything in the file, or it will be completely ignored; in the very
// least, this is a formalization for deprecating files.
optional bool deprecated = 23 [default = false];
// Enables the use of arenas for the proto messages in this file. This applies
// only to generated classes for C++.
optional bool cc_enable_arenas = 31 [default = true];
// Sets the objective c class prefix which is prepended to all objective c
// generated classes from this .proto. There is no default.
optional string objc_class_prefix = 36;
// Namespace for generated classes; defaults to the package.
optional string csharp_namespace = 37;
// By default Swift generators will take the proto package and CamelCase it
// replacing '.' with underscore and use that to prefix the types/symbols
// defined. When this options is provided, they will use this value instead
// to prefix the types/symbols defined.
optional string swift_prefix = 39;
// Sets the php class prefix which is prepended to all php generated classes
// from this .proto. Default is empty.
optional string php_class_prefix = 40;
// Use this option to change the namespace of php generated classes. Default
// is empty. When this option is empty, the package name will be used for
// determining the namespace.
optional string php_namespace = 41;
// Use this option to change the namespace of php generated metadata classes.
// Default is empty. When this option is empty, the proto file name will be
// used for determining the namespace.
optional string php_metadata_namespace = 44;
// Use this option to change the package of ruby generated classes. Default
// is empty. When this option is not set, the package name will be used for
// determining the ruby package.
optional string ruby_package = 45;
// The parser stores options it doesn't recognize here.
// See the documentation for the "Options" section above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message.
// See the documentation for the "Options" section above.
extensions 1000 to max;
reserved 38;
}
message MessageOptions {
// Set true to use the old proto1 MessageSet wire format for extensions.
// This is provided for backwards-compatibility with the MessageSet wire
// format. You should not use this for any other reason: It's less
// efficient, has fewer features, and is more complicated.
//
// The message must be defined exactly as follows:
// message Foo {
// option message_set_wire_format = true;
// extensions 4 to max;
// }
// Note that the message cannot have any defined fields; MessageSets only
// have extensions.
//
// All extensions of your type must be singular messages; e.g. they cannot
// be int32s, enums, or repeated messages.
//
// Because this is an option, the above two restrictions are not enforced by
// the protocol compiler.
optional bool message_set_wire_format = 1 [default = false];
// Disables the generation of the standard "descriptor()" accessor, which can
// conflict with a field of the same name. This is meant to make migration
// from proto1 easier; new code should avoid fields named "descriptor".
optional bool no_standard_descriptor_accessor = 2 [default = false];
// Is this message deprecated?
// Depending on the target platform, this can emit Deprecated annotations
// for the message, or it will be completely ignored; in the very least,
// this is a formalization for deprecating messages.
optional bool deprecated = 3 [default = false];
// Whether the message is an automatically generated map entry type for the
// maps field.
//
// For maps fields:
// map<KeyType, ValueType> map_field = 1;
// The parsed descriptor looks like:
// message MapFieldEntry {
// option map_entry = true;
// optional KeyType key = 1;
// optional ValueType value = 2;
// }
// repeated MapFieldEntry map_field = 1;
//
// Implementations may choose not to generate the map_entry=true message, but
// use a native map in the target language to hold the keys and values.
// The reflection APIs in such implementations still need to work as
// if the field is a repeated message field.
//
// NOTE: Do not set the option in .proto files. Always use the maps syntax
// instead. The option should only be implicitly set by the proto compiler
// parser.
optional bool map_entry = 7;
reserved 8; // javalite_serializable
reserved 9; // javanano_as_lite
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message FieldOptions {
// The ctype option instructs the C++ code generator to use a different
// representation of the field than it normally would. See the specific
// options below. This option is not yet implemented in the open source
// release -- sorry, we'll try to include it in a future version!
optional CType ctype = 1 [default = STRING];
enum CType {
// Default mode.
STRING = 0;
CORD = 1;
STRING_PIECE = 2;
}
// The packed option can be enabled for repeated primitive fields to enable
// a more efficient representation on the wire. Rather than repeatedly
// writing the tag and type for each element, the entire array is encoded as
// a single length-delimited blob. In proto3, only explicit setting it to
// false will avoid using packed encoding.
optional bool packed = 2;
// The jstype option determines the JavaScript type used for values of the
// field. The option is permitted only for 64 bit integral and fixed types
// (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING
// is represented as JavaScript string, which avoids loss of precision that
// can happen when a large value is converted to a floating point JavaScript.
// Specifying JS_NUMBER for the jstype causes the generated JavaScript code to
// use the JavaScript "number" type. The behavior of the default option
// JS_NORMAL is implementation dependent.
//
// This option is an enum to permit additional types to be added, e.g.
// goog.math.Integer.
optional JSType jstype = 6 [default = JS_NORMAL];
enum JSType {
// Use the default type.
JS_NORMAL = 0;
// Use JavaScript strings.
JS_STRING = 1;
// Use JavaScript numbers.
JS_NUMBER = 2;
}
// Should this field be parsed lazily? Lazy applies only to message-type
// fields. It means that when the outer message is initially parsed, the
// inner message's contents will not be parsed but instead stored in encoded
// form. The inner message will actually be parsed when it is first accessed.
//
// This is only a hint. Implementations are free to choose whether to use
// eager or lazy parsing regardless of the value of this option. However,
// setting this option true suggests that the protocol author believes that
// using lazy parsing on this field is worth the additional bookkeeping
// overhead typically needed to implement it.
//
// This option does not affect the public interface of any generated code;
// all method signatures remain the same. Furthermore, thread-safety of the
// interface is not affected by this option; const methods remain safe to
// call from multiple threads concurrently, while non-const methods continue
// to require exclusive access.
//
//
// Note that implementations may choose not to check required fields within
// a lazy sub-message. That is, calling IsInitialized() on the outer message
// may return true even if the inner message has missing required fields.
// This is necessary because otherwise the inner message would have to be
// parsed in order to perform the check, defeating the purpose of lazy
// parsing. An implementation which chooses not to check required fields
// must be consistent about it. That is, for any particular sub-message, the
// implementation must either *always* check its required fields, or *never*
// check its required fields, regardless of whether or not the message has
// been parsed.
optional bool lazy = 5 [default = false];
// Is this field deprecated?
// Depending on the target platform, this can emit Deprecated annotations
// for accessors, or it will be completely ignored; in the very least, this
// is a formalization for deprecating fields.
optional bool deprecated = 3 [default = false];
// For Google-internal migration only. Do not use.
optional bool weak = 10 [default = false];
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
reserved 4; // removed jtype
}
message OneofOptions {
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message EnumOptions {
// Set this option to true to allow mapping different tag names to the same
// value.
optional bool allow_alias = 2;
// Is this enum deprecated?
// Depending on the target platform, this can emit Deprecated annotations
// for the enum, or it will be completely ignored; in the very least, this
// is a formalization for deprecating enums.
optional bool deprecated = 3 [default = false];
reserved 5; // javanano_as_lite
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message EnumValueOptions {
// Is this enum value deprecated?
// Depending on the target platform, this can emit Deprecated annotations
// for the enum value, or it will be completely ignored; in the very least,
// this is a formalization for deprecating enum values.
optional bool deprecated = 1 [default = false];
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message ServiceOptions {
// Note: Field numbers 1 through 32 are reserved for Google's internal RPC
// framework. We apologize for hoarding these numbers to ourselves, but
// we were already using them long before we decided to release Protocol
// Buffers.
// Is this service deprecated?
// Depending on the target platform, this can emit Deprecated annotations
// for the service, or it will be completely ignored; in the very least,
// this is a formalization for deprecating services.
optional bool deprecated = 33 [default = false];
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message MethodOptions {
// Note: Field numbers 1 through 32 are reserved for Google's internal RPC
// framework. We apologize for hoarding these numbers to ourselves, but
// we were already using them long before we decided to release Protocol
// Buffers.
// Is this method deprecated?
// Depending on the target platform, this can emit Deprecated annotations
// for the method, or it will be completely ignored; in the very least,
// this is a formalization for deprecating methods.
optional bool deprecated = 33 [default = false];
// Is this method side-effect-free (or safe in HTTP parlance), or idempotent,
// or neither? HTTP based RPC implementation may choose GET verb for safe
// methods, and PUT verb for idempotent methods instead of the default POST.
enum IdempotencyLevel {
IDEMPOTENCY_UNKNOWN = 0;
NO_SIDE_EFFECTS = 1; // implies idempotent
IDEMPOTENT = 2; // idempotent, but may have side effects
}
optional IdempotencyLevel idempotency_level = 34
[default = IDEMPOTENCY_UNKNOWN];
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
// A message representing a option the parser does not recognize. This only
// appears in options protos created by the compiler::Parser class.
// DescriptorPool resolves these when building Descriptor objects. Therefore,
// options protos in descriptor objects (e.g. returned by Descriptor::options(),
// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions
// in them.
message UninterpretedOption {
// The name of the uninterpreted option. Each string represents a segment in
// a dot-separated name. is_extension is true iff a segment represents an
// extension (denoted with parentheses in options specs in .proto files).
// E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents
// "foo.(bar.baz).qux".
message NamePart {
required string name_part = 1;
required bool is_extension = 2;
}
repeated NamePart name = 2;
// The value of the uninterpreted option, in whatever type the tokenizer
// identified it as during parsing. Exactly one of these should be set.
optional string identifier_value = 3;
optional uint64 positive_int_value = 4;
optional int64 negative_int_value = 5;
optional double double_value = 6;
optional bytes string_value = 7;
optional string aggregate_value = 8;
}
// ===================================================================
// Optional source code info
// Encapsulates information about the original source file from which a
// FileDescriptorProto was generated.
message SourceCodeInfo {
// A Location identifies a piece of source code in a .proto file which
// corresponds to a particular definition. This information is intended
// to be useful to IDEs, code indexers, documentation generators, and similar
// tools.
//
// For example, say we have a file like:
// message Foo {
// optional string foo = 1;
// }
// Let's look at just the field definition:
// optional string foo = 1;
// ^ ^^ ^^ ^ ^^^
// a bc de f ghi
// We have the following locations:
// span path represents
// [a,i) [ 4, 0, 2, 0 ] The whole field definition.
// [a,b) [ 4, 0, 2, 0, 4 ] The label (optional).
// [c,d) [ 4, 0, 2, 0, 5 ] The type (string).
// [e,f) [ 4, 0, 2, 0, 1 ] The name (foo).
// [g,h) [ 4, 0, 2, 0, 3 ] The number (1).
//
// Notes:
// - A location may refer to a repeated field itself (i.e. not to any
// particular index within it). This is used whenever a set of elements are
// logically enclosed in a single code segment. For example, an entire
// extend block (possibly containing multiple extension definitions) will
// have an outer location whose path refers to the "extensions" repeated
// field without an index.
// - Multiple locations may have the same path. This happens when a single
// logical declaration is spread out across multiple places. The most
// obvious example is the "extend" block again -- there may be multiple
// extend blocks in the same scope, each of which will have the same path.
// - A location's span is not always a subset of its parent's span. For
// example, the "extendee" of an extension declaration appears at the
// beginning of the "extend" block and is shared by all extensions within
// the block.
// - Just because a location's span is a subset of some other location's span
// does not mean that it is a descendant. For example, a "group" defines
// both a type and a field in a single declaration. Thus, the locations
// corresponding to the type and field and their components will overlap.
// - Code which tries to interpret locations should probably be designed to
// ignore those that it doesn't understand, as more types of locations could
// be recorded in the future.
repeated Location location = 1;
message Location {
// Identifies which part of the FileDescriptorProto was defined at this
// location.
//
// Each element is a field number or an index. They form a path from
// the root FileDescriptorProto to the place where the definition. For
// example, this path:
// [ 4, 3, 2, 7, 1 ]
// refers to:
// file.message_type(3) // 4, 3
// .field(7) // 2, 7
// .name() // 1
// This is because FileDescriptorProto.message_type has field number 4:
// repeated DescriptorProto message_type = 4;
// and DescriptorProto.field has field number 2:
// repeated FieldDescriptorProto field = 2;
// and FieldDescriptorProto.name has field number 1:
// optional string name = 1;
//
// Thus, the above path gives the location of a field name. If we removed
// the last element:
// [ 4, 3, 2, 7 ]
// this path refers to the whole field declaration (from the beginning
// of the label to the terminating semicolon).
repeated int32 path = 1 [packed = true];
// Always has exactly three or four elements: start line, start column,
// end line (optional, otherwise assumed same as start line), end column.
// These are packed into a single field for efficiency. Note that line
// and column numbers are zero-based -- typically you will want to add
// 1 to each before displaying to a user.
repeated int32 span = 2 [packed = true];
// If this SourceCodeInfo represents a complete declaration, these are any
// comments appearing before and after the declaration which appear to be
// attached to the declaration.
//
// A series of line comments appearing on consecutive lines, with no other
// tokens appearing on those lines, will be treated as a single comment.
//
// leading_detached_comments will keep paragraphs of comments that appear
// before (but not connected to) the current element. Each paragraph,
// separated by empty lines, will be one comment element in the repeated
// field.
//
// Only the comment content is provided; comment markers (e.g. //) are
// stripped out. For block comments, leading whitespace and an asterisk
// will be stripped from the beginning of each line other than the first.
// Newlines are included in the output.
//
// Examples:
//
// optional int32 foo = 1; // Comment attached to foo.
// // Comment attached to bar.
// optional int32 bar = 2;
//
// optional string baz = 3;
// // Comment attached to baz.
// // Another line attached to baz.
//
// // Comment attached to qux.
// //
// // Another line attached to qux.
// optional double qux = 4;
//
// // Detached comment for corge. This is not leading or trailing comments
// // to qux or corge because there are blank lines separating it from
// // both.
//
// // Detached comment for corge paragraph 2.
//
// optional string corge = 5;
// /* Block comment attached
// * to corge. Leading asterisks
// * will be removed. */
// /* Block comment attached to
// * grault. */
// optional int32 grault = 6;
//
// // ignored detached comments.
optional string leading_comments = 3;
optional string trailing_comments = 4;
repeated string leading_detached_comments = 6;
}
}
// Describes the relationship between generated code and its original source
// file. A GeneratedCodeInfo message is associated with only one generated
// source file, but may contain references to different source .proto files.
message GeneratedCodeInfo {
// An Annotation connects some span of text in generated code to an element
// of its generating .proto file.
repeated Annotation annotation = 1;
message Annotation {
// Identifies the element in the original source .proto file. This field
// is formatted the same as SourceCodeInfo.Location.path.
repeated int32 path = 1 [packed = true];
// Identifies the filesystem path to the original source .proto.
optional string source_file = 2;
// Identifies the starting offset in bytes in the generated code
// that relates to the identified object.
optional int32 begin = 3;
// Identifies the ending offset in bytes in the generated code that
// relates to the identified offset. The end offset should be one past
// the last relevant byte (so the length of the text = end - begin).
optional int32 end = 4;
}
}
-52
View File
@@ -1,52 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto3";
package google.protobuf;
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
option go_package = "github.com/golang/protobuf/ptypes/empty";
option java_package = "com.google.protobuf";
option java_outer_classname = "EmptyProto";
option java_multiple_files = true;
option objc_class_prefix = "GPB";
option cc_enable_arenas = true;
// A generic empty message that you can re-use to avoid defining duplicated
// empty messages in your APIs. A typical example is to use it as the request
// or the response type of an API method. For instance:
//
// service Foo {
// rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
// }
//
// The JSON representation for `Empty` is empty JSON object `{}`.
message Empty {}
-245
View File
@@ -1,245 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto3";
package google.protobuf;
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
option java_package = "com.google.protobuf";
option java_outer_classname = "FieldMaskProto";
option java_multiple_files = true;
option objc_class_prefix = "GPB";
option go_package = "google.golang.org/genproto/protobuf/field_mask;field_mask";
option cc_enable_arenas = true;
// `FieldMask` represents a set of symbolic field paths, for example:
//
// paths: "f.a"
// paths: "f.b.d"
//
// Here `f` represents a field in some root message, `a` and `b`
// fields in the message found in `f`, and `d` a field found in the
// message in `f.b`.
//
// Field masks are used to specify a subset of fields that should be
// returned by a get operation or modified by an update operation.
// Field masks also have a custom JSON encoding (see below).
//
// # Field Masks in Projections
//
// When used in the context of a projection, a response message or
// sub-message is filtered by the API to only contain those fields as
// specified in the mask. For example, if the mask in the previous
// example is applied to a response message as follows:
//
// f {
// a : 22
// b {
// d : 1
// x : 2
// }
// y : 13
// }
// z: 8
//
// The result will not contain specific values for fields x,y and z
// (their value will be set to the default, and omitted in proto text
// output):
//
//
// f {
// a : 22
// b {
// d : 1
// }
// }
//
// A repeated field is not allowed except at the last position of a
// paths string.
//
// If a FieldMask object is not present in a get operation, the
// operation applies to all fields (as if a FieldMask of all fields
// had been specified).
//
// Note that a field mask does not necessarily apply to the
// top-level response message. In case of a REST get operation, the
// field mask applies directly to the response, but in case of a REST
// list operation, the mask instead applies to each individual message
// in the returned resource list. In case of a REST custom method,
// other definitions may be used. Where the mask applies will be
// clearly documented together with its declaration in the API. In
// any case, the effect on the returned resource/resources is required
// behavior for APIs.
//
// # Field Masks in Update Operations
//
// A field mask in update operations specifies which fields of the
// targeted resource are going to be updated. The API is required
// to only change the values of the fields as specified in the mask
// and leave the others untouched. If a resource is passed in to
// describe the updated values, the API ignores the values of all
// fields not covered by the mask.
//
// If a repeated field is specified for an update operation, new values will
// be appended to the existing repeated field in the target resource. Note that
// a repeated field is only allowed in the last position of a `paths` string.
//
// If a sub-message is specified in the last position of the field mask for an
// update operation, then new value will be merged into the existing sub-message
// in the target resource.
//
// For example, given the target message:
//
// f {
// b {
// d: 1
// x: 2
// }
// c: [1]
// }
//
// And an update message:
//
// f {
// b {
// d: 10
// }
// c: [2]
// }
//
// then if the field mask is:
//
// paths: ["f.b", "f.c"]
//
// then the result will be:
//
// f {
// b {
// d: 10
// x: 2
// }
// c: [1, 2]
// }
//
// An implementation may provide options to override this default behavior for
// repeated and message fields.
//
// In order to reset a field's value to the default, the field must
// be in the mask and set to the default value in the provided resource.
// Hence, in order to reset all fields of a resource, provide a default
// instance of the resource and set all fields in the mask, or do
// not provide a mask as described below.
//
// If a field mask is not present on update, the operation applies to
// all fields (as if a field mask of all fields has been specified).
// Note that in the presence of schema evolution, this may mean that
// fields the client does not know and has therefore not filled into
// the request will be reset to their default. If this is unwanted
// behavior, a specific service may require a client to always specify
// a field mask, producing an error if not.
//
// As with get operations, the location of the resource which
// describes the updated values in the request message depends on the
// operation kind. In any case, the effect of the field mask is
// required to be honored by the API.
//
// ## Considerations for HTTP REST
//
// The HTTP kind of an update operation which uses a field mask must
// be set to PATCH instead of PUT in order to satisfy HTTP semantics
// (PUT must only be used for full updates).
//
// # JSON Encoding of Field Masks
//
// In JSON, a field mask is encoded as a single string where paths are
// separated by a comma. Fields name in each path are converted
// to/from lower-camel naming conventions.
//
// As an example, consider the following message declarations:
//
// message Profile {
// User user = 1;
// Photo photo = 2;
// }
// message User {
// string display_name = 1;
// string address = 2;
// }
//
// In proto a field mask for `Profile` may look as such:
//
// mask {
// paths: "user.display_name"
// paths: "photo"
// }
//
// In JSON, the same mask is represented as below:
//
// {
// mask: "user.displayName,photo"
// }
//
// # Field Masks and Oneof Fields
//
// Field masks treat fields in oneofs just as regular fields. Consider the
// following message:
//
// message SampleMessage {
// oneof test_oneof {
// string name = 4;
// SubMessage sub_message = 9;
// }
// }
//
// The field mask can be:
//
// mask {
// paths: "name"
// }
//
// Or:
//
// mask {
// paths: "sub_message"
// }
//
// Note that oneof type names ("test_oneof" in this case) cannot be used in
// paths.
//
// ## Field Mask Verification
//
// The implementation of any API method which has a FieldMask type field in the
// request should verify the included field paths, and return an
// `INVALID_ARGUMENT` error if any path is unmappable.
message FieldMask {
// The set of field mask paths.
repeated string paths = 1;
}
-138
View File
@@ -1,138 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto3";
package google.protobuf;
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
option cc_enable_arenas = true;
option go_package = "github.com/golang/protobuf/ptypes/timestamp";
option java_package = "com.google.protobuf";
option java_outer_classname = "TimestampProto";
option java_multiple_files = true;
option objc_class_prefix = "GPB";
// A Timestamp represents a point in time independent of any time zone or local
// calendar, encoded as a count of seconds and fractions of seconds at
// nanosecond resolution. The count is relative to an epoch at UTC midnight on
// January 1, 1970, in the proleptic Gregorian calendar which extends the
// Gregorian calendar backwards to year one.
//
// All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap
// second table is needed for interpretation, using a [24-hour linear
// smear](https://developers.google.com/time/smear).
//
// The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By
// restricting to that range, we ensure that we can convert to and from [RFC
// 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings.
//
// # Examples
//
// Example 1: Compute Timestamp from POSIX `time()`.
//
// Timestamp timestamp;
// timestamp.set_seconds(time(NULL));
// timestamp.set_nanos(0);
//
// Example 2: Compute Timestamp from POSIX `gettimeofday()`.
//
// struct timeval tv;
// gettimeofday(&tv, NULL);
//
// Timestamp timestamp;
// timestamp.set_seconds(tv.tv_sec);
// timestamp.set_nanos(tv.tv_usec * 1000);
//
// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
//
// FILETIME ft;
// GetSystemTimeAsFileTime(&ft);
// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
//
// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
// Timestamp timestamp;
// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
//
// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
//
// long millis = System.currentTimeMillis();
//
// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
// .setNanos((int) ((millis % 1000) * 1000000)).build();
//
//
// Example 5: Compute Timestamp from current time in Python.
//
// timestamp = Timestamp()
// timestamp.GetCurrentTime()
//
// # JSON Mapping
//
// In JSON format, the Timestamp type is encoded as a string in the
// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
// where {year} is always expressed using four digits while {month}, {day},
// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
// is required. A proto3 JSON serializer should always use UTC (as indicated by
// "Z") when printing the Timestamp type and a proto3 JSON parser should be
// able to accept both UTC and other timezones (as indicated by an offset).
//
// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
// 01:30 UTC on January 15, 2017.
//
// In JavaScript, one can convert a Date object to this format using the
// standard
// [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)
// method. In Python, a standard `datetime.datetime` object can be converted
// to this format using
// [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with
// the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use
// the Joda Time's [`ISODateTimeFormat.dateTime()`](
// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime%2D%2D
// ) to obtain a formatter capable of generating timestamps in this format.
//
//
message Timestamp {
// Represents seconds of UTC time since Unix epoch
// 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
// 9999-12-31T23:59:59Z inclusive.
int64 seconds = 1;
// Non-negative fractions of a second at nanosecond resolution. Negative
// second values with fractions must still have non-negative nanos values
// that count forward in time. Must be from 0 to 999,999,999
// inclusive.
int32 nanos = 2;
}
-7
View File
@@ -1,7 +0,0 @@
// +build tools
package main
import (
_ "github.com/restic/calens"
)
-40
View File
@@ -1,40 +0,0 @@
import 'regenerator-runtime/runtime'
import App from './components/App.vue'
import store from './store'
const appInfo = {
name: 'Accounts',
id: 'accounts',
icon: 'text-vcard',
isFileEditor: false,
extensions: []
}
const routes = [
{
name: 'accounts',
path: '/',
components: {
app: App
}
}
]
const navItems = [
{
name: 'Accounts',
iconMaterial: appInfo.icon,
route: {
name: 'accounts',
path: `/${appInfo.id}/`
},
menu: 'apps'
}
]
export default {
appInfo,
routes,
navItems,
store
}
-723
View File
@@ -1,723 +0,0 @@
/* eslint-disable */
import axios from 'axios'
import qs from 'qs'
let domain = ''
export const getDomain = () => {
return domain
}
export const setDomain = ($domain) => {
domain = $domain
}
export const request = (method, url, body, queryParameters, form, config) => {
method = method.toLowerCase()
let keys = Object.keys(queryParameters)
let queryUrl = url
if (keys.length > 0) {
queryUrl = url + '?' + qs.stringify(queryParameters)
}
// let queryUrl = url+(keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
if (body) {
return axios[method](queryUrl, body, config)
} else if (method === 'get') {
return axios[method](queryUrl, config)
} else {
return axios[method](queryUrl, qs.stringify(form), config)
}
}
/*==========================================================
*
==========================================================*/
/**
* Creates an account
* request: AccountsService_CreateAccount
* url: AccountsService_CreateAccountURL
* method: AccountsService_CreateAccount_TYPE
* raw_url: AccountsService_CreateAccount_RAW_URL
* @param body -
*/
export const AccountsService_CreateAccount = function(parameters = {}) {
const domain = parameters.$domain ? parameters.$domain : getDomain()
const config = parameters.$config
let path = '/api/v0/accounts/accounts-create'
let body
let queryParameters = {}
let form = {}
if (parameters['body'] !== undefined) {
body = parameters['body']
}
if (parameters['body'] === undefined) {
return Promise.reject(new Error('Missing required parameter: body'))
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
});
}
return request('post', domain + path, body, queryParameters, form, config)
}
export const AccountsService_CreateAccount_RAW_URL = function() {
return '/api/v0/accounts/accounts-create'
}
export const AccountsService_CreateAccount_TYPE = function() {
return 'post'
}
export const AccountsService_CreateAccountURL = function(parameters = {}) {
let queryParameters = {}
const domain = parameters.$domain ? parameters.$domain : getDomain()
let path = '/api/v0/accounts/accounts-create'
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
})
}
let keys = Object.keys(queryParameters)
return domain + path + (keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
}
/**
* Deletes an account
* request: AccountsService_DeleteAccount
* url: AccountsService_DeleteAccountURL
* method: AccountsService_DeleteAccount_TYPE
* raw_url: AccountsService_DeleteAccount_RAW_URL
* @param body -
*/
export const AccountsService_DeleteAccount = function(parameters = {}) {
const domain = parameters.$domain ? parameters.$domain : getDomain()
const config = parameters.$config
let path = '/api/v0/accounts/accounts-delete'
let body
let queryParameters = {}
let form = {}
if (parameters['body'] !== undefined) {
body = parameters['body']
}
if (parameters['body'] === undefined) {
return Promise.reject(new Error('Missing required parameter: body'))
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
});
}
return request('post', domain + path, body, queryParameters, form, config)
}
export const AccountsService_DeleteAccount_RAW_URL = function() {
return '/api/v0/accounts/accounts-delete'
}
export const AccountsService_DeleteAccount_TYPE = function() {
return 'post'
}
export const AccountsService_DeleteAccountURL = function(parameters = {}) {
let queryParameters = {}
const domain = parameters.$domain ? parameters.$domain : getDomain()
let path = '/api/v0/accounts/accounts-delete'
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
})
}
let keys = Object.keys(queryParameters)
return domain + path + (keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
}
/**
* Gets an account
* request: AccountsService_GetAccount
* url: AccountsService_GetAccountURL
* method: AccountsService_GetAccount_TYPE
* raw_url: AccountsService_GetAccount_RAW_URL
* @param body -
*/
export const AccountsService_GetAccount = function(parameters = {}) {
const domain = parameters.$domain ? parameters.$domain : getDomain()
const config = parameters.$config
let path = '/api/v0/accounts/accounts-get'
let body
let queryParameters = {}
let form = {}
if (parameters['body'] !== undefined) {
body = parameters['body']
}
if (parameters['body'] === undefined) {
return Promise.reject(new Error('Missing required parameter: body'))
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
});
}
return request('post', domain + path, body, queryParameters, form, config)
}
export const AccountsService_GetAccount_RAW_URL = function() {
return '/api/v0/accounts/accounts-get'
}
export const AccountsService_GetAccount_TYPE = function() {
return 'post'
}
export const AccountsService_GetAccountURL = function(parameters = {}) {
let queryParameters = {}
const domain = parameters.$domain ? parameters.$domain : getDomain()
let path = '/api/v0/accounts/accounts-get'
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
})
}
let keys = Object.keys(queryParameters)
return domain + path + (keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
}
/**
* Lists accounts
* request: AccountsService_ListAccounts
* url: AccountsService_ListAccountsURL
* method: AccountsService_ListAccounts_TYPE
* raw_url: AccountsService_ListAccounts_RAW_URL
* @param body -
*/
export const AccountsService_ListAccounts = function(parameters = {}) {
const domain = parameters.$domain ? parameters.$domain : getDomain()
const config = parameters.$config
let path = '/api/v0/accounts/accounts-list'
let body
let queryParameters = {}
let form = {}
if (parameters['body'] !== undefined) {
body = parameters['body']
}
if (parameters['body'] === undefined) {
return Promise.reject(new Error('Missing required parameter: body'))
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
});
}
return request('post', domain + path, body, queryParameters, form, config)
}
export const AccountsService_ListAccounts_RAW_URL = function() {
return '/api/v0/accounts/accounts-list'
}
export const AccountsService_ListAccounts_TYPE = function() {
return 'post'
}
export const AccountsService_ListAccountsURL = function(parameters = {}) {
let queryParameters = {}
const domain = parameters.$domain ? parameters.$domain : getDomain()
let path = '/api/v0/accounts/accounts-list'
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
})
}
let keys = Object.keys(queryParameters)
return domain + path + (keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
}
/**
* Updates an account
* request: AccountsService_UpdateAccount
* url: AccountsService_UpdateAccountURL
* method: AccountsService_UpdateAccount_TYPE
* raw_url: AccountsService_UpdateAccount_RAW_URL
* @param body -
*/
export const AccountsService_UpdateAccount = function(parameters = {}) {
const domain = parameters.$domain ? parameters.$domain : getDomain()
const config = parameters.$config
let path = '/api/v0/accounts/accounts-update'
let body
let queryParameters = {}
let form = {}
if (parameters['body'] !== undefined) {
body = parameters['body']
}
if (parameters['body'] === undefined) {
return Promise.reject(new Error('Missing required parameter: body'))
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
});
}
return request('post', domain + path, body, queryParameters, form, config)
}
export const AccountsService_UpdateAccount_RAW_URL = function() {
return '/api/v0/accounts/accounts-update'
}
export const AccountsService_UpdateAccount_TYPE = function() {
return 'post'
}
export const AccountsService_UpdateAccountURL = function(parameters = {}) {
let queryParameters = {}
const domain = parameters.$domain ? parameters.$domain : getDomain()
let path = '/api/v0/accounts/accounts-update'
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
})
}
let keys = Object.keys(queryParameters)
return domain + path + (keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
}
/**
* Lists groups
* request: GroupsService_ListGroups
* url: GroupsService_ListGroupsURL
* method: GroupsService_ListGroups_TYPE
* raw_url: GroupsService_ListGroups_RAW_URL
* @param pageSize - Optional. The maximum number of groups to return in the response.
* @param pageToken - Optional. A pagination token returned from a previous call to `Get`
that indicates from where search should continue.
* @param fieldMaskPaths - The set of field mask paths.
* @param query - Optional. Search criteria used to select the groups to return.
If no search criteria is specified then all groups will be
returned. TODO update query language
Query expressions can be used to restrict results based upon
the account properties where the operators `=`, `NOT`, `AND` and `OR`
can be used along with the suffix wildcard symbol `*`.
The string properties in a query expression should use escaped quotes
for values that include whitespace to prevent unexpected behavior.
Some example queries are:
* Query `display_name=Th*` returns accounts whose display_name
starts with "Th"
* Query `display_name=\\"Test String\\"` returns groups with
display names that include both "Test" and "String"
*/
export const GroupsService_ListGroups = function(parameters = {}) {
const domain = parameters.$domain ? parameters.$domain : getDomain()
const config = parameters.$config
let path = '/v0/groups'
let body
let queryParameters = {}
let form = {}
if (parameters['pageSize'] !== undefined) {
queryParameters['page_size'] = parameters['pageSize']
}
if (parameters['pageToken'] !== undefined) {
queryParameters['page_token'] = parameters['pageToken']
}
if (parameters['fieldMaskPaths'] !== undefined) {
queryParameters['field_mask.paths'] = parameters['fieldMaskPaths']
}
if (parameters['query'] !== undefined) {
queryParameters['query'] = parameters['query']
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
});
}
return request('get', domain + path, body, queryParameters, form, config)
}
export const GroupsService_ListGroups_RAW_URL = function() {
return '/v0/groups'
}
export const GroupsService_ListGroups_TYPE = function() {
return 'get'
}
export const GroupsService_ListGroupsURL = function(parameters = {}) {
let queryParameters = {}
const domain = parameters.$domain ? parameters.$domain : getDomain()
let path = '/v0/groups'
if (parameters['pageSize'] !== undefined) {
queryParameters['page_size'] = parameters['pageSize']
}
if (parameters['pageToken'] !== undefined) {
queryParameters['page_token'] = parameters['pageToken']
}
if (parameters['fieldMaskPaths'] !== undefined) {
queryParameters['field_mask.paths'] = parameters['fieldMaskPaths']
}
if (parameters['query'] !== undefined) {
queryParameters['query'] = parameters['query']
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
})
}
let keys = Object.keys(queryParameters)
return domain + path + (keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
}
/**
* Creates a group
* request: GroupsService_CreateGroup
* url: GroupsService_CreateGroupURL
* method: GroupsService_CreateGroup_TYPE
* raw_url: GroupsService_CreateGroup_RAW_URL
* @param body - The account resource to create
*/
export const GroupsService_CreateGroup = function(parameters = {}) {
const domain = parameters.$domain ? parameters.$domain : getDomain()
const config = parameters.$config
let path = '/v0/groups'
let body
let queryParameters = {}
let form = {}
if (parameters['body'] !== undefined) {
body = parameters['body']
}
if (parameters['body'] === undefined) {
return Promise.reject(new Error('Missing required parameter: body'))
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
});
}
return request('post', domain + path, body, queryParameters, form, config)
}
export const GroupsService_CreateGroup_RAW_URL = function() {
return '/v0/groups'
}
export const GroupsService_CreateGroup_TYPE = function() {
return 'post'
}
export const GroupsService_CreateGroupURL = function(parameters = {}) {
let queryParameters = {}
const domain = parameters.$domain ? parameters.$domain : getDomain()
let path = '/v0/groups'
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
})
}
let keys = Object.keys(queryParameters)
return domain + path + (keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
}
/**
* Updates a group
* request: GroupsService_UpdateGroup
* url: GroupsService_UpdateGroupURL
* method: GroupsService_UpdateGroup_TYPE
* raw_url: GroupsService_UpdateGroup_RAW_URL
* @param groupId - The unique identifier for the group.
Returned by default. Inherited from directoryObject. Key. Not nullable. Read-only.
* @param body - The group resource which replaces the resource on the server
*/
export const GroupsService_UpdateGroup = function(parameters = {}) {
const domain = parameters.$domain ? parameters.$domain : getDomain()
const config = parameters.$config
let path = '/v0/groups/{group.id}'
let body
let queryParameters = {}
let form = {}
path = path.replace('{group.id}', `${parameters['groupId']}`)
if (parameters['groupId'] === undefined) {
return Promise.reject(new Error('Missing required parameter: groupId'))
}
if (parameters['body'] !== undefined) {
body = parameters['body']
}
if (parameters['body'] === undefined) {
return Promise.reject(new Error('Missing required parameter: body'))
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
});
}
return request('patch', domain + path, body, queryParameters, form, config)
}
export const GroupsService_UpdateGroup_RAW_URL = function() {
return '/v0/groups/{group.id}'
}
export const GroupsService_UpdateGroup_TYPE = function() {
return 'patch'
}
export const GroupsService_UpdateGroupURL = function(parameters = {}) {
let queryParameters = {}
const domain = parameters.$domain ? parameters.$domain : getDomain()
let path = '/v0/groups/{group.id}'
path = path.replace('{group.id}', `${parameters['groupId']}`)
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
})
}
let keys = Object.keys(queryParameters)
return domain + path + (keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
}
/**
* Gets an groups
* request: GroupsService_GetGroup
* url: GroupsService_GetGroupURL
* method: GroupsService_GetGroup_TYPE
* raw_url: GroupsService_GetGroup_RAW_URL
* @param id -
*/
export const GroupsService_GetGroup = function(parameters = {}) {
const domain = parameters.$domain ? parameters.$domain : getDomain()
const config = parameters.$config
let path = '/v0/groups/{id}'
let body
let queryParameters = {}
let form = {}
path = path.replace('{id}', `${parameters['id']}`)
if (parameters['id'] === undefined) {
return Promise.reject(new Error('Missing required parameter: id'))
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
});
}
return request('get', domain + path, body, queryParameters, form, config)
}
export const GroupsService_GetGroup_RAW_URL = function() {
return '/v0/groups/{id}'
}
export const GroupsService_GetGroup_TYPE = function() {
return 'get'
}
export const GroupsService_GetGroupURL = function(parameters = {}) {
let queryParameters = {}
const domain = parameters.$domain ? parameters.$domain : getDomain()
let path = '/v0/groups/{id}'
path = path.replace('{id}', `${parameters['id']}`)
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
})
}
let keys = Object.keys(queryParameters)
return domain + path + (keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
}
/**
* Deletes a group
* request: GroupsService_DeleteGroup
* url: GroupsService_DeleteGroupURL
* method: GroupsService_DeleteGroup_TYPE
* raw_url: GroupsService_DeleteGroup_RAW_URL
* @param id -
*/
export const GroupsService_DeleteGroup = function(parameters = {}) {
const domain = parameters.$domain ? parameters.$domain : getDomain()
const config = parameters.$config
let path = '/v0/groups/{id}'
let body
let queryParameters = {}
let form = {}
path = path.replace('{id}', `${parameters['id']}`)
if (parameters['id'] === undefined) {
return Promise.reject(new Error('Missing required parameter: id'))
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
});
}
return request('delete', domain + path, body, queryParameters, form, config)
}
export const GroupsService_DeleteGroup_RAW_URL = function() {
return '/v0/groups/{id}'
}
export const GroupsService_DeleteGroup_TYPE = function() {
return 'delete'
}
export const GroupsService_DeleteGroupURL = function(parameters = {}) {
let queryParameters = {}
const domain = parameters.$domain ? parameters.$domain : getDomain()
let path = '/v0/groups/{id}'
path = path.replace('{id}', `${parameters['id']}`)
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
})
}
let keys = Object.keys(queryParameters)
return domain + path + (keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
}
/**
* group:listmembers https://docs.microsoft.com/en-us/graph/api/group-list-members?view=graph-rest-1.0
* request: GroupsService_ListMembers
* url: GroupsService_ListMembersURL
* method: GroupsService_ListMembers_TYPE
* raw_url: GroupsService_ListMembers_RAW_URL
* @param id - The group id
* @param pageSize -
* @param pageToken - Optional. A pagination token returned from a previous call to `Get`
that indicates from where search should continue.
* @param fieldMaskPaths - The set of field mask paths.
* @param query - Optional. Search criteria used to select the groups to return.
If no search criteria is specified then all groups will be
returned. TODO update query language
Query expressions can be used to restrict results based upon
the account properties where the operators `=`, `NOT`, `AND` and `OR`
can be used along with the suffix wildcard symbol `*`.
The string properties in a query expression should use escaped quotes
for values that include whitespace to prevent unexpected behavior.
Some example queries are:
* Query `display_name=Th*` returns accounts whose display_name
starts with "Th"
* Query `display_name=\\"Test String\\"` returns groups with
display names that include both "Test" and "String"
*/
export const GroupsService_ListMembers = function(parameters = {}) {
const domain = parameters.$domain ? parameters.$domain : getDomain()
const config = parameters.$config
let path = '/v0/groups/{id}/members/$ref'
let body
let queryParameters = {}
let form = {}
path = path.replace('{id}', `${parameters['id']}`)
if (parameters['id'] === undefined) {
return Promise.reject(new Error('Missing required parameter: id'))
}
if (parameters['pageSize'] !== undefined) {
queryParameters['page_size'] = parameters['pageSize']
}
if (parameters['pageToken'] !== undefined) {
queryParameters['page_token'] = parameters['pageToken']
}
if (parameters['fieldMaskPaths'] !== undefined) {
queryParameters['field_mask.paths'] = parameters['fieldMaskPaths']
}
if (parameters['query'] !== undefined) {
queryParameters['query'] = parameters['query']
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
});
}
return request('get', domain + path, body, queryParameters, form, config)
}
export const GroupsService_ListMembers_RAW_URL = function() {
return '/v0/groups/{id}/members/$ref'
}
export const GroupsService_ListMembers_TYPE = function() {
return 'get'
}
export const GroupsService_ListMembersURL = function(parameters = {}) {
let queryParameters = {}
const domain = parameters.$domain ? parameters.$domain : getDomain()
let path = '/v0/groups/{id}/members/$ref'
path = path.replace('{id}', `${parameters['id']}`)
if (parameters['pageSize'] !== undefined) {
queryParameters['page_size'] = parameters['pageSize']
}
if (parameters['pageToken'] !== undefined) {
queryParameters['page_token'] = parameters['pageToken']
}
if (parameters['fieldMaskPaths'] !== undefined) {
queryParameters['field_mask.paths'] = parameters['fieldMaskPaths']
}
if (parameters['query'] !== undefined) {
queryParameters['query'] = parameters['query']
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
})
}
let keys = Object.keys(queryParameters)
return domain + path + (keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
}
/**
* group:addmember https://docs.microsoft.com/en-us/graph/api/group-post-members?view=graph-rest-1.0&tabs=http
* request: GroupsService_AddMember
* url: GroupsService_AddMemberURL
* method: GroupsService_AddMember_TYPE
* raw_url: GroupsService_AddMember_RAW_URL
* @param id - The account id to add
* @param body -
*/
export const GroupsService_AddMember = function(parameters = {}) {
const domain = parameters.$domain ? parameters.$domain : getDomain()
const config = parameters.$config
let path = '/v0/groups/{id}/members/$ref'
let body
let queryParameters = {}
let form = {}
path = path.replace('{id}', `${parameters['id']}`)
if (parameters['id'] === undefined) {
return Promise.reject(new Error('Missing required parameter: id'))
}
if (parameters['body'] !== undefined) {
body = parameters['body']
}
if (parameters['body'] === undefined) {
return Promise.reject(new Error('Missing required parameter: body'))
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
});
}
return request('post', domain + path, body, queryParameters, form, config)
}
export const GroupsService_AddMember_RAW_URL = function() {
return '/v0/groups/{id}/members/$ref'
}
export const GroupsService_AddMember_TYPE = function() {
return 'post'
}
export const GroupsService_AddMemberURL = function(parameters = {}) {
let queryParameters = {}
const domain = parameters.$domain ? parameters.$domain : getDomain()
let path = '/v0/groups/{id}/members/$ref'
path = path.replace('{id}', `${parameters['id']}`)
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
})
}
let keys = Object.keys(queryParameters)
return domain + path + (keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
}
/**
* group:removemember https://docs.microsoft.com/en-us/graph/api/group-delete-members?view=graph-rest-1.0
* request: GroupsService_RemoveMember
* url: GroupsService_RemoveMemberURL
* method: GroupsService_RemoveMember_TYPE
* raw_url: GroupsService_RemoveMember_RAW_URL
* @param id - The group id
* @param accountId - The account id to remove
*/
export const GroupsService_RemoveMember = function(parameters = {}) {
const domain = parameters.$domain ? parameters.$domain : getDomain()
const config = parameters.$config
let path = '/v0/groups/{id}/members/{account_id}/$ref'
let body
let queryParameters = {}
let form = {}
path = path.replace('{id}', `${parameters['id']}`)
if (parameters['id'] === undefined) {
return Promise.reject(new Error('Missing required parameter: id'))
}
path = path.replace('{account_id}', `${parameters['accountId']}`)
if (parameters['accountId'] === undefined) {
return Promise.reject(new Error('Missing required parameter: accountId'))
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
});
}
return request('delete', domain + path, body, queryParameters, form, config)
}
export const GroupsService_RemoveMember_RAW_URL = function() {
return '/v0/groups/{id}/members/{account_id}/$ref'
}
export const GroupsService_RemoveMember_TYPE = function() {
return 'delete'
}
export const GroupsService_RemoveMemberURL = function(parameters = {}) {
let queryParameters = {}
const domain = parameters.$domain ? parameters.$domain : getDomain()
let path = '/v0/groups/{id}/members/{account_id}/$ref'
path = path.replace('{id}', `${parameters['id']}`)
path = path.replace('{account_id}', `${parameters['accountId']}`)
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
})
}
let keys = Object.keys(queryParameters)
return domain + path + (keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
}
-627
View File
@@ -1,627 +0,0 @@
/* eslint-disable */
import axios from 'axios'
import qs from 'qs'
let domain = ''
export const getDomain = () => {
return domain
}
export const setDomain = ($domain) => {
domain = $domain
}
export const request = (method, url, body, queryParameters, form, config) => {
method = method.toLowerCase()
let keys = Object.keys(queryParameters)
let queryUrl = url
if (keys.length > 0) {
queryUrl = url + '?' + qs.stringify(queryParameters)
}
// let queryUrl = url+(keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
if (body) {
return axios[method](queryUrl, body, config)
} else if (method === 'get') {
return axios[method](queryUrl, config)
} else {
return axios[method](queryUrl, qs.stringify(form), config)
}
}
/*==========================================================
*
==========================================================*/
/**
*
* request: RoleService_AssignRoleToUser
* url: RoleService_AssignRoleToUserURL
* method: RoleService_AssignRoleToUser_TYPE
* raw_url: RoleService_AssignRoleToUser_RAW_URL
* @param body -
*/
export const RoleService_AssignRoleToUser = function(parameters = {}) {
const domain = parameters.$domain ? parameters.$domain : getDomain()
const config = parameters.$config
let path = '/api/v0/settings/assignments-add'
let body
let queryParameters = {}
let form = {}
if (parameters['body'] !== undefined) {
body = parameters['body']
}
if (parameters['body'] === undefined) {
return Promise.reject(new Error('Missing required parameter: body'))
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
});
}
return request('post', domain + path, body, queryParameters, form, config)
}
export const RoleService_AssignRoleToUser_RAW_URL = function() {
return '/api/v0/settings/assignments-add'
}
export const RoleService_AssignRoleToUser_TYPE = function() {
return 'post'
}
export const RoleService_AssignRoleToUserURL = function(parameters = {}) {
let queryParameters = {}
const domain = parameters.$domain ? parameters.$domain : getDomain()
let path = '/api/v0/settings/assignments-add'
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
})
}
let keys = Object.keys(queryParameters)
return domain + path + (keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
}
/**
*
* request: RoleService_ListRoleAssignments
* url: RoleService_ListRoleAssignmentsURL
* method: RoleService_ListRoleAssignments_TYPE
* raw_url: RoleService_ListRoleAssignments_RAW_URL
* @param body -
*/
export const RoleService_ListRoleAssignments = function(parameters = {}) {
const domain = parameters.$domain ? parameters.$domain : getDomain()
const config = parameters.$config
let path = '/api/v0/settings/assignments-list'
let body
let queryParameters = {}
let form = {}
if (parameters['body'] !== undefined) {
body = parameters['body']
}
if (parameters['body'] === undefined) {
return Promise.reject(new Error('Missing required parameter: body'))
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
});
}
return request('post', domain + path, body, queryParameters, form, config)
}
export const RoleService_ListRoleAssignments_RAW_URL = function() {
return '/api/v0/settings/assignments-list'
}
export const RoleService_ListRoleAssignments_TYPE = function() {
return 'post'
}
export const RoleService_ListRoleAssignmentsURL = function(parameters = {}) {
let queryParameters = {}
const domain = parameters.$domain ? parameters.$domain : getDomain()
let path = '/api/v0/settings/assignments-list'
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
})
}
let keys = Object.keys(queryParameters)
return domain + path + (keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
}
/**
*
* request: RoleService_RemoveRoleFromUser
* url: RoleService_RemoveRoleFromUserURL
* method: RoleService_RemoveRoleFromUser_TYPE
* raw_url: RoleService_RemoveRoleFromUser_RAW_URL
* @param body -
*/
export const RoleService_RemoveRoleFromUser = function(parameters = {}) {
const domain = parameters.$domain ? parameters.$domain : getDomain()
const config = parameters.$config
let path = '/api/v0/settings/assignments-remove'
let body
let queryParameters = {}
let form = {}
if (parameters['body'] !== undefined) {
body = parameters['body']
}
if (parameters['body'] === undefined) {
return Promise.reject(new Error('Missing required parameter: body'))
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
});
}
return request('post', domain + path, body, queryParameters, form, config)
}
export const RoleService_RemoveRoleFromUser_RAW_URL = function() {
return '/api/v0/settings/assignments-remove'
}
export const RoleService_RemoveRoleFromUser_TYPE = function() {
return 'post'
}
export const RoleService_RemoveRoleFromUserURL = function(parameters = {}) {
let queryParameters = {}
const domain = parameters.$domain ? parameters.$domain : getDomain()
let path = '/api/v0/settings/assignments-remove'
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
})
}
let keys = Object.keys(queryParameters)
return domain + path + (keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
}
/**
*
* request: BundleService_GetBundle
* url: BundleService_GetBundleURL
* method: BundleService_GetBundle_TYPE
* raw_url: BundleService_GetBundle_RAW_URL
* @param body -
*/
export const BundleService_GetBundle = function(parameters = {}) {
const domain = parameters.$domain ? parameters.$domain : getDomain()
const config = parameters.$config
let path = '/api/v0/settings/bundle-get'
let body
let queryParameters = {}
let form = {}
if (parameters['body'] !== undefined) {
body = parameters['body']
}
if (parameters['body'] === undefined) {
return Promise.reject(new Error('Missing required parameter: body'))
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
});
}
return request('post', domain + path, body, queryParameters, form, config)
}
export const BundleService_GetBundle_RAW_URL = function() {
return '/api/v0/settings/bundle-get'
}
export const BundleService_GetBundle_TYPE = function() {
return 'post'
}
export const BundleService_GetBundleURL = function(parameters = {}) {
let queryParameters = {}
const domain = parameters.$domain ? parameters.$domain : getDomain()
let path = '/api/v0/settings/bundle-get'
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
})
}
let keys = Object.keys(queryParameters)
return domain + path + (keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
}
/**
*
* request: BundleService_SaveBundle
* url: BundleService_SaveBundleURL
* method: BundleService_SaveBundle_TYPE
* raw_url: BundleService_SaveBundle_RAW_URL
* @param body -
*/
export const BundleService_SaveBundle = function(parameters = {}) {
const domain = parameters.$domain ? parameters.$domain : getDomain()
const config = parameters.$config
let path = '/api/v0/settings/bundle-save'
let body
let queryParameters = {}
let form = {}
if (parameters['body'] !== undefined) {
body = parameters['body']
}
if (parameters['body'] === undefined) {
return Promise.reject(new Error('Missing required parameter: body'))
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
});
}
return request('post', domain + path, body, queryParameters, form, config)
}
export const BundleService_SaveBundle_RAW_URL = function() {
return '/api/v0/settings/bundle-save'
}
export const BundleService_SaveBundle_TYPE = function() {
return 'post'
}
export const BundleService_SaveBundleURL = function(parameters = {}) {
let queryParameters = {}
const domain = parameters.$domain ? parameters.$domain : getDomain()
let path = '/api/v0/settings/bundle-save'
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
})
}
let keys = Object.keys(queryParameters)
return domain + path + (keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
}
/**
*
* request: BundleService_AddSettingToBundle
* url: BundleService_AddSettingToBundleURL
* method: BundleService_AddSettingToBundle_TYPE
* raw_url: BundleService_AddSettingToBundle_RAW_URL
* @param body -
*/
export const BundleService_AddSettingToBundle = function(parameters = {}) {
const domain = parameters.$domain ? parameters.$domain : getDomain()
const config = parameters.$config
let path = '/api/v0/settings/bundles-add-setting'
let body
let queryParameters = {}
let form = {}
if (parameters['body'] !== undefined) {
body = parameters['body']
}
if (parameters['body'] === undefined) {
return Promise.reject(new Error('Missing required parameter: body'))
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
});
}
return request('post', domain + path, body, queryParameters, form, config)
}
export const BundleService_AddSettingToBundle_RAW_URL = function() {
return '/api/v0/settings/bundles-add-setting'
}
export const BundleService_AddSettingToBundle_TYPE = function() {
return 'post'
}
export const BundleService_AddSettingToBundleURL = function(parameters = {}) {
let queryParameters = {}
const domain = parameters.$domain ? parameters.$domain : getDomain()
let path = '/api/v0/settings/bundles-add-setting'
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
})
}
let keys = Object.keys(queryParameters)
return domain + path + (keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
}
/**
*
* request: BundleService_ListBundles
* url: BundleService_ListBundlesURL
* method: BundleService_ListBundles_TYPE
* raw_url: BundleService_ListBundles_RAW_URL
* @param body -
*/
export const BundleService_ListBundles = function(parameters = {}) {
const domain = parameters.$domain ? parameters.$domain : getDomain()
const config = parameters.$config
let path = '/api/v0/settings/bundles-list'
let body
let queryParameters = {}
let form = {}
if (parameters['body'] !== undefined) {
body = parameters['body']
}
if (parameters['body'] === undefined) {
return Promise.reject(new Error('Missing required parameter: body'))
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
});
}
return request('post', domain + path, body, queryParameters, form, config)
}
export const BundleService_ListBundles_RAW_URL = function() {
return '/api/v0/settings/bundles-list'
}
export const BundleService_ListBundles_TYPE = function() {
return 'post'
}
export const BundleService_ListBundlesURL = function(parameters = {}) {
let queryParameters = {}
const domain = parameters.$domain ? parameters.$domain : getDomain()
let path = '/api/v0/settings/bundles-list'
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
})
}
let keys = Object.keys(queryParameters)
return domain + path + (keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
}
/**
*
* request: BundleService_RemoveSettingFromBundle
* url: BundleService_RemoveSettingFromBundleURL
* method: BundleService_RemoveSettingFromBundle_TYPE
* raw_url: BundleService_RemoveSettingFromBundle_RAW_URL
* @param body -
*/
export const BundleService_RemoveSettingFromBundle = function(parameters = {}) {
const domain = parameters.$domain ? parameters.$domain : getDomain()
const config = parameters.$config
let path = '/api/v0/settings/bundles-remove-setting'
let body
let queryParameters = {}
let form = {}
if (parameters['body'] !== undefined) {
body = parameters['body']
}
if (parameters['body'] === undefined) {
return Promise.reject(new Error('Missing required parameter: body'))
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
});
}
return request('post', domain + path, body, queryParameters, form, config)
}
export const BundleService_RemoveSettingFromBundle_RAW_URL = function() {
return '/api/v0/settings/bundles-remove-setting'
}
export const BundleService_RemoveSettingFromBundle_TYPE = function() {
return 'post'
}
export const BundleService_RemoveSettingFromBundleURL = function(parameters = {}) {
let queryParameters = {}
const domain = parameters.$domain ? parameters.$domain : getDomain()
let path = '/api/v0/settings/bundles-remove-setting'
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
})
}
let keys = Object.keys(queryParameters)
return domain + path + (keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
}
/**
*
* request: RoleService_ListRoles
* url: RoleService_ListRolesURL
* method: RoleService_ListRoles_TYPE
* raw_url: RoleService_ListRoles_RAW_URL
* @param body -
*/
export const RoleService_ListRoles = function(parameters = {}) {
const domain = parameters.$domain ? parameters.$domain : getDomain()
const config = parameters.$config
let path = '/api/v0/settings/roles-list'
let body
let queryParameters = {}
let form = {}
if (parameters['body'] !== undefined) {
body = parameters['body']
}
if (parameters['body'] === undefined) {
return Promise.reject(new Error('Missing required parameter: body'))
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
});
}
return request('post', domain + path, body, queryParameters, form, config)
}
export const RoleService_ListRoles_RAW_URL = function() {
return '/api/v0/settings/roles-list'
}
export const RoleService_ListRoles_TYPE = function() {
return 'post'
}
export const RoleService_ListRolesURL = function(parameters = {}) {
let queryParameters = {}
const domain = parameters.$domain ? parameters.$domain : getDomain()
let path = '/api/v0/settings/roles-list'
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
})
}
let keys = Object.keys(queryParameters)
return domain + path + (keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
}
/**
*
* request: ValueService_GetValue
* url: ValueService_GetValueURL
* method: ValueService_GetValue_TYPE
* raw_url: ValueService_GetValue_RAW_URL
* @param body -
*/
export const ValueService_GetValue = function(parameters = {}) {
const domain = parameters.$domain ? parameters.$domain : getDomain()
const config = parameters.$config
let path = '/api/v0/settings/values-get'
let body
let queryParameters = {}
let form = {}
if (parameters['body'] !== undefined) {
body = parameters['body']
}
if (parameters['body'] === undefined) {
return Promise.reject(new Error('Missing required parameter: body'))
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
});
}
return request('post', domain + path, body, queryParameters, form, config)
}
export const ValueService_GetValue_RAW_URL = function() {
return '/api/v0/settings/values-get'
}
export const ValueService_GetValue_TYPE = function() {
return 'post'
}
export const ValueService_GetValueURL = function(parameters = {}) {
let queryParameters = {}
const domain = parameters.$domain ? parameters.$domain : getDomain()
let path = '/api/v0/settings/values-get'
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
})
}
let keys = Object.keys(queryParameters)
return domain + path + (keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
}
/**
*
* request: ValueService_GetValueByUniqueIdentifiers
* url: ValueService_GetValueByUniqueIdentifiersURL
* method: ValueService_GetValueByUniqueIdentifiers_TYPE
* raw_url: ValueService_GetValueByUniqueIdentifiers_RAW_URL
* @param body -
*/
export const ValueService_GetValueByUniqueIdentifiers = function(parameters = {}) {
const domain = parameters.$domain ? parameters.$domain : getDomain()
const config = parameters.$config
let path = '/api/v0/settings/values-get-by-unique-identifiers'
let body
let queryParameters = {}
let form = {}
if (parameters['body'] !== undefined) {
body = parameters['body']
}
if (parameters['body'] === undefined) {
return Promise.reject(new Error('Missing required parameter: body'))
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
});
}
return request('post', domain + path, body, queryParameters, form, config)
}
export const ValueService_GetValueByUniqueIdentifiers_RAW_URL = function() {
return '/api/v0/settings/values-get-by-unique-identifiers'
}
export const ValueService_GetValueByUniqueIdentifiers_TYPE = function() {
return 'post'
}
export const ValueService_GetValueByUniqueIdentifiersURL = function(parameters = {}) {
let queryParameters = {}
const domain = parameters.$domain ? parameters.$domain : getDomain()
let path = '/api/v0/settings/values-get-by-unique-identifiers'
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
})
}
let keys = Object.keys(queryParameters)
return domain + path + (keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
}
/**
*
* request: ValueService_ListValues
* url: ValueService_ListValuesURL
* method: ValueService_ListValues_TYPE
* raw_url: ValueService_ListValues_RAW_URL
* @param body -
*/
export const ValueService_ListValues = function(parameters = {}) {
const domain = parameters.$domain ? parameters.$domain : getDomain()
const config = parameters.$config
let path = '/api/v0/settings/values-list'
let body
let queryParameters = {}
let form = {}
if (parameters['body'] !== undefined) {
body = parameters['body']
}
if (parameters['body'] === undefined) {
return Promise.reject(new Error('Missing required parameter: body'))
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
});
}
return request('post', domain + path, body, queryParameters, form, config)
}
export const ValueService_ListValues_RAW_URL = function() {
return '/api/v0/settings/values-list'
}
export const ValueService_ListValues_TYPE = function() {
return 'post'
}
export const ValueService_ListValuesURL = function(parameters = {}) {
let queryParameters = {}
const domain = parameters.$domain ? parameters.$domain : getDomain()
let path = '/api/v0/settings/values-list'
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
})
}
let keys = Object.keys(queryParameters)
return domain + path + (keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
}
/**
*
* request: ValueService_SaveValue
* url: ValueService_SaveValueURL
* method: ValueService_SaveValue_TYPE
* raw_url: ValueService_SaveValue_RAW_URL
* @param body -
*/
export const ValueService_SaveValue = function(parameters = {}) {
const domain = parameters.$domain ? parameters.$domain : getDomain()
const config = parameters.$config
let path = '/api/v0/settings/values-save'
let body
let queryParameters = {}
let form = {}
if (parameters['body'] !== undefined) {
body = parameters['body']
}
if (parameters['body'] === undefined) {
return Promise.reject(new Error('Missing required parameter: body'))
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
});
}
return request('post', domain + path, body, queryParameters, form, config)
}
export const ValueService_SaveValue_RAW_URL = function() {
return '/api/v0/settings/values-save'
}
export const ValueService_SaveValue_TYPE = function() {
return 'post'
}
export const ValueService_SaveValueURL = function(parameters = {}) {
let queryParameters = {}
const domain = parameters.$domain ? parameters.$domain : getDomain()
let path = '/api/v0/settings/values-save'
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
queryParameters[parameterName] = parameters.$queryParameters[parameterName]
})
}
let keys = Object.keys(queryParameters)
return domain + path + (keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '')
}
-71
View File
@@ -1,71 +0,0 @@
<template>
<div>
<div class="uk-flex uk-flex-column uk-height-1-1" id="accounts-app">
<template v-if="isInitialized">
<div class="oc-app-bar">
<accounts-batch-actions
v-if="isAnyAccountSelected"
:number-of-selected-accounts="numberOfSelectedAccounts"
:selected-accounts="selectedAccounts"
/>
<accounts-create v-else />
</div>
<oc-grid class="uk-flex-1 uk-overflow-auto">
<div class="uk-width-expand">
<accounts-list :accounts="accounts" />
</div>
</oc-grid>
</template>
<template v-else-if="hasFailed">
<oc-alert variation="warning" no-close class="oc-m" id="accounts-list-loading-failed">
<oc-icon name="warning" variation="warning" class="uk-float-left oc-mr-s" />
<translate>You don't have permissions to manage accounts.</translate>
</oc-alert>
</template>
<oc-loader id="accounts-list-loader" v-else />
</div>
</div>
</template>
<script>
import { mapGetters, mapActions, mapState } from 'vuex'
import AccountsList from './accounts/AccountsList.vue'
import AccountsCreate from './accounts/AccountsCreate.vue'
import AccountsBatchActions from './accounts/AccountsBatchActions.vue'
export default {
name: 'App',
components: { AccountsBatchActions, AccountsList, AccountsCreate },
computed: {
...mapGetters('Accounts', ['isInitialized', 'hasFailed', 'getAccountsSorted', 'isAnyAccountSelected']),
...mapState('Accounts', ['selectedAccounts']),
accounts () {
return this.getAccountsSorted
},
numberOfSelectedAccounts () {
return this.selectedAccounts.length
}
},
methods: {
...mapActions('Accounts', ['initialize'])
},
created () {
this.initialize()
}
}
</script>
<style>
/* TODO: After https://github.com/owncloud/owncloud-design-system/pull/418 gets merged
there won't be an extra span and this won't be needed anymore */
.accounts-selection-actions-btn > span {
display: flex;
align-items: center;
}
/* TODO: Adjust in ODS */
.oc-dropdown-menu {
width: 150px;
}
</style>
@@ -1,138 +0,0 @@
<template>
<oc-grid key="selected-accounts-info" gutter="small" class="uk-flex-middle">
<span v-text="selectionInfoText" />
<span>|</span>
<div>
<oc-button v-text="$gettext('Clear selection')" variation="raw" @click="RESET_ACCOUNTS_SELECTION" />
</div>
<oc-grid gutter="small" id="accounts-batch-actions">
<div v-for="action in actions" :key="action.label">
<oc-alert v-if="isConfirmationInProgress[action.id]" :variation="action.confirmation.variation || 'default'" noClose class="uk-flex uk-flex-middle tmp-alert-fixes">
<span>{{ action.confirmation.message }}</span>
<oc-button size="small" :id="action.confirmation.cancel.id" @click="action.confirmation.cancel.handler" :variation="action.confirmation.cancel.variation || 'default'">
{{ action.confirmation.cancel.label }}
</oc-button>
<oc-button size="small" :id="action.confirmation.confirm.id" @click="action.confirmation.confirm.handler" :variation="action.confirmation.confirm.variation || 'default'">
{{ action.confirmation.confirm.label }}
</oc-button>
</oc-alert>
<oc-button v-else :id="action.id" @click="action.handler" :variation="action.variation || 'default'" :icon="action.icon">
{{ action.label }}
</oc-button>
</div>
</oc-grid>
</oc-grid>
</template>
<script>
import { mapActions, mapMutations } from 'vuex'
export default {
name: 'AccountsBatchActions',
props: {
numberOfSelectedAccounts: {
type: Number,
required: true
},
selectedAccounts: {
type: Array,
required: true
}
},
data: () => {
return {
isConfirmationInProgress: {}
}
},
computed: {
selectionInfoText () {
const translated = this.$ngettext('%{ amount } selected user', '%{ amount } selected users', this.numberOfSelectedAccounts)
return this.$gettextInterpolate(translated, { amount: this.numberOfSelectedAccounts })
},
actions () {
const actions = []
const numberOfDisabledAccounts = this.selectedAccounts.filter(account => !account.accountEnabled).length
const isAnyAccountDisabled = numberOfDisabledAccounts > 0
const isAnyAccountEnabled = numberOfDisabledAccounts < this.numberOfSelectedAccounts
if (isAnyAccountDisabled) {
actions.push({
id: 'accounts-batch-action-enable',
label: this.$gettext('Activate'),
icon: 'ready',
handler: () => this.setAccountActivated(true)
})
}
if (isAnyAccountEnabled) {
actions.push({
id: 'accounts-batch-action-disable',
label: this.$gettext('Block'),
icon: 'deprecated',
handler: () => this.setAccountActivated(false)
})
}
const idDeleteAction = 'accounts-batch-action-delete'
actions.push({
id: idDeleteAction,
label: this.$gettext('Delete'),
icon: 'delete',
handler: () => this.showConfirmationRequest(idDeleteAction),
confirmation: {
variation: 'danger',
message: this.$ngettext(
'Delete the selected account?',
'Delete the selected accounts?',
this.numberOfSelectedAccounts
),
cancel: {
id: 'accounts-batch-action-delete-cancel',
label: this.$gettext('Cancel'),
variation: 'secondary',
handler: () => this.hideConfirmationRequest(idDeleteAction)
},
confirm: {
id: 'accounts-batch-action-delete-confirm',
label: this.$gettext('Confirm'),
variation: 'danger',
handler: this.deleteAccounts
}
}
})
return actions
}
},
methods: {
...mapActions('Accounts', ['setAccountActivated', 'deleteAccounts']),
...mapMutations('Accounts', ['RESET_ACCOUNTS_SELECTION']),
showConfirmationRequest (actionId) {
this.isConfirmationInProgress = { ...this.isConfirmationInProgress, [actionId]: true }
},
hideConfirmationRequest (actionId) {
this.isConfirmationInProgress = { ...this.isConfirmationInProgress, [actionId]: false }
}
}
}
</script>
<style lang="scss" scoped>
.tmp-alert-fixes {
padding: 4px 11px 5px !important;
border-radius: 3px !important;
background-color: #fff !important;
border: 1px solid rgb(224, 0, 0) !important;
color: rgb(224, 0, 0) !important;
font-size: 1.1rem !important;
font-weight: 600 !important;
line-height: 1.4 !important;
}
.tmp-alert-fixes > *:not(:last-child) {
margin-right: 8px;
}
.tmp-alert-fixes > button {
padding: 0.2rem 0.5rem;
}
</style>
@@ -1,202 +0,0 @@
<template>
<div>
<oc-grid v-if="isFormInProgress" gutter="small">
<label>
<oc-text-input
id="accounts-new-account-input-username"
type="text"
v-model="formData.username"
:error-message="formValidation.usernameError"
:placeholder="$gettext('Username')"
:disabled="isRequestInProgress"
@keydown.enter="createAccount"
/>
</label>
<label>
<oc-text-input
id="accounts-new-account-input-email"
type="email"
v-model="formData.email"
:error-message="formValidation.emailError"
:placeholder="$gettext('Email')"
:disabled="isRequestInProgress"
@keydown.enter="createAccount"
/>
</label>
<label>
<oc-text-input
id="accounts-new-account-input-password"
type="password"
v-model="formData.password"
:error-message="formValidation.passwordError"
:placeholder="$gettext('Password')"
:disabled="isRequestInProgress"
@keydown.enter="createAccount"
/>
</label>
<div>
<oc-button
v-text="$gettext('Cancel')"
@click="cancelForm"
:disabled="isRequestInProgress"
/>
</div>
<div>
<oc-button
id="accounts-new-account-button-confirm"
variation="primary"
:disabled="isRequestInProgress"
@click="createAccount"
gap-size="small"
:class="{ 'border-ods-tmp-fix': !isRequestInProgress }"
>
<oc-spinner
v-if="isRequestInProgress"
key="account-creation-in-progress"
size="small"
aria-hidden="true"
/>
<span v-text="isRequestInProgress ? $gettext('Creating') : $gettext('Create')" />
</oc-button>
</div>
</oc-grid>
<oc-grid v-else gutter="small">
<div>
<oc-button
id="accounts-new-account-trigger"
key="create-accounts-button"
variation="primary"
gap-size="small"
@click="setFormInProgress(true)"
>
<oc-icon name="add" />
<translate>Create new account</translate>
</oc-button>
</div>
</oc-grid>
</div>
</template>
<script>
import isEmail from 'validator/es/lib/isEmail'
import isEmpty from 'validator/es/lib/isEmpty'
import debounce from 'debounce'
import { mapActions } from 'vuex'
export default {
name: 'AccountsCreate',
data: () => ({
isFormInProgress: false,
isRequestInProgress: false,
formData: {
username: '',
email: '',
password: ''
},
formValidation: {
usernameError: '',
emailError: '',
passwordError: ''
}
}),
methods: {
...mapActions('Accounts', ['createNewAccount']),
setFormInProgress (inProgress) {
this.isFormInProgress = inProgress
},
cancelForm () {
this.isRequestInProgress = false
this.setFormInProgress(false)
this.formData = {
username: '',
email: '',
password: ''
}
this.formValidation = {
usernameError: '',
emailError: '',
passwordError: ''
}
},
createAccount () {
// note: use bitwise AND because we want all checks to be performed
if (!(this.checkUsername() & this.checkEmail() & this.checkPassword())) {
return
}
this.isRequestInProgress = true
this.createNewAccount(this.formData)
.then((success) => {
if (success) {
this.cancelForm()
}
})
.finally(() => {
this.isRequestInProgress = false
})
},
checkUsername () {
if (isEmpty(this.formData.username)) {
debounce(this.formValidation.usernameError = this.$gettext('Username cannot be empty'), 500)
return false
}
// hacky check: we want to allow emails and the username part of emails as username
if (!isEmail(this.formData.username) && !isEmail(this.formData.username + '@validate.it')) {
debounce(this.formValidation.usernameError = this.$gettext('Invalid username'), 500)
return false
}
this.formValidation.usernameError = ''
return true
},
checkEmail () {
if (isEmpty(this.formData.email)) {
debounce(this.formValidation.emailError = this.$gettext('Email cannot be empty'), 500)
return false
}
if (!isEmail(this.formData.email)) {
debounce(this.formValidation.emailError = this.$gettext('Invalid email address'), 500)
return false
}
this.formValidation.emailError = ''
return true
},
checkPassword () {
// Later on some restrictions might be applied here
if (isEmpty(this.formData.password)) {
debounce(this.formValidation.passwordError = this.$gettext('Password cannot be empty'), 500)
return false
}
this.formValidation.passwordError = ''
return true
}
},
onDestroy () {
this.cancelForm()
}
}
</script>
<style>
#accounts-new-account-button-confirm > span {
display: flex;
align-items: center;
}
</style>
<style scoped>
.border-ods-tmp-fix {
/* TODO: somehow the primary button receives a 2px border-width. remove it until we fix it in ODS. */
border-width: 0 !important;
}
</style>
@@ -1,66 +0,0 @@
<template>
<div>
<oc-table middle divider>
<oc-table-group>
<oc-table-row class="fix-table-header">
<oc-table-cell shrink type="head" class="uk-text-center">
<oc-checkbox
class="oc-ml-s"
:value="areAllAccountsSelected"
@input="toggleSelectionAll"
:label="$gettext('Select all users')"
hide-label
/>
</oc-table-cell>
<oc-table-cell shrink type="head" />
<oc-table-cell type="head" v-text="$gettext('Username')" />
<oc-table-cell type="head" v-text="$gettext('Display name')" />
<oc-table-cell type="head" v-text="$gettext('Email')" />
<oc-table-cell type="head" v-text="$gettext('Role')" />
<oc-table-cell shrink type="head" v-text="$gettext('Activated')" />
</oc-table-row>
</oc-table-group>
<oc-table-group>
<accounts-list-row
v-for="account in accounts"
:key="`account-list-row-${account.id}`"
:account="account"
/>
</oc-table-group>
</oc-table>
</div>
</template>
<script>
import { mapActions, mapGetters, mapMutations } from 'vuex'
import AccountsListRow from './AccountsListRow.vue'
export default {
name: 'AccountsList',
components: {
AccountsListRow
},
props: {
accounts: {
type: Array,
required: true
}
},
computed: {
...mapGetters('Accounts', ['areAllAccountsSelected'])
},
methods: {
...mapActions('Accounts', ['toggleSelectionAll']),
...mapMutations('Accounts', ['RESET_ACCOUNTS_SELECTION'])
},
beforeDestroy () {
this.RESET_ACCOUNTS_SELECTION()
}
}
</script>
<style scoped>
.fix-table-header > th {
text-transform: none;
}
</style>
@@ -1,162 +0,0 @@
<template>
<oc-table-row>
<oc-table-cell>
<oc-checkbox
class="oc-ml-s"
size="large"
:value="selectedAccounts"
:option="account"
@input="TOGGLE_SELECTION_ACCOUNT(account)"
:label="selectAccountLabel"
hide-label
/>
</oc-table-cell>
<oc-table-cell>
<avatar :user-name="account.displayName || account.onPremisesSamAccountName" :userid="account.id" :width="35" />
</oc-table-cell>
<oc-table-cell v-text="account.onPremisesSamAccountName" />
<oc-table-cell v-text="account.displayName || '-'" />
<oc-table-cell v-text="account.mail" />
<oc-table-cell>
<oc-button :id="`accounts-roles-select-trigger-${account.id}`" class="accounts-roles-select-trigger" variation="raw">
<span class="uk-flex uk-flex-middle accounts-roles-current-role">
{{ currentRole ? currentRole.displayName : $gettext('Select role') }}
<oc-icon name="expand_more" aria-hidden="true" />
</span>
</oc-button>
<oc-drop
:drop-id="`accounts-roles-select-dropdown-${account.id}`"
:toggle="`#accounts-roles-select-trigger-${account.id}`"
mode="click"
close-on-click
:options="{ delayHide: 0 }"
>
<ul class="uk-list">
<li v-for="role in roles" :key="role.id">
<oc-radio
class="accounts-roles-dropdown-role"
v-model="currentRole"
:option="role"
@input="changeRole(role.id)"
:label="role.displayName"
/>
</li>
</ul>
</oc-drop>
</oc-table-cell>
<oc-table-cell class="uk-text-center">
<oc-icon
v-if="account.accountEnabled"
key="account-icon-enabled"
name="ready"
variation="success"
:aria-label="$gettext('Account is activated')"
class="accounts-status-indicator-enabled"
/>
<oc-icon
v-else
name="deprecated"
key="account-icon-disabled"
variation="danger"
:aria-label="$gettext('Account is blocked')"
class="accounts-status-indicator-disabled"
/>
</oc-table-cell>
</oc-table-row>
</template>
<script>
import { mapGetters, mapState, mapActions, mapMutations } from 'vuex'
import { isObjectEmpty } from '../../helpers/utils'
import { injectAuthToken } from '../../helpers/auth'
// eslint-disable-next-line camelcase
import { RoleService_AssignRoleToUser, RoleService_ListRoleAssignments } from '../../client/settings'
import Avatar from './Avatar.vue'
export default {
name: 'AccountsListRow',
components: { Avatar },
props: {
account: {
type: Object,
required: true
}
},
data () {
return {
currentRole: null
}
},
computed: {
...mapGetters(['user', 'getServerForJsClient']),
...mapState('Accounts', ['roles', 'selectedAccounts']),
selectAccountLabel () {
const translated = this.$gettext('Select %{ account }')
return this.$gettextInterpolate(translated, { account: this.account.displayName }, true)
}
},
created () {
this.getUsersCurrentRole()
},
methods: {
...mapActions(['showMessage']),
...mapMutations('Accounts', ['TOGGLE_SELECTION_ACCOUNT']),
async changeRole (roleId) {
injectAuthToken(this.user.token)
const response = await RoleService_AssignRoleToUser({
$domain: this.getServerForJsClient,
body: {
account_uuid: this.account.id,
role_id: roleId
}
})
if (response.status === 201) {
const roleId = response.data.assignment.roleId
this.currentRole = this.roles.find(role => {
return role.id === roleId
})
} else {
this.showMessage({
title: this.$gettext('Failed to change role.'),
desc: response.statusText,
status: 'danger'
})
}
},
async getUsersCurrentRole () {
injectAuthToken(this.user.token)
const response = await RoleService_ListRoleAssignments({
$domain: this.getServerForJsClient,
body: {
account_uuid: this.account.id
}
})
if (response.status === 201) {
const assignedRole = response.data
if (isObjectEmpty(assignedRole)) {
return
}
this.currentRole = this.roles.find(role => {
return role.id === assignedRole.assignments[0].roleId
})
}
}
}
}
</script>
-130
View File
@@ -1,130 +0,0 @@
<template>
<component :is="type" v-if="enabled">
<oc-spinner
v-if="loading"
key="avatar-loading"
size="small"
:aria-label="$gettext('Loading')"
:style="`width: ${width}px; height: ${width}px;`"
/>
<oc-avatar
v-else
key="avatar-loaded"
:width="width"
:src="avatarSource"
:user-name="userName"
/>
</component>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
/**
* FIXME: this component has been copied over from ownCloud Web. It should be moved over to ODS, then we can reuse it in
* this extension.
*/
name: 'Avatar',
props: {
/**
* The html element used for the avatar container.
* `div, span`
*/
type: {
type: String,
default: 'div',
validator: value => {
return value.match(/(div|span)/)
}
},
userName: {
type: String,
default: ''
},
userid: {
/**
* Allow empty string to show placeholder
*/
type: String,
default: ''
},
width: {
type: Number,
required: false,
default: 42
}
},
data () {
return {
/**
* Set to object URL when loaded, or on failure, icon placeholder is shown
*/
avatarSource: '',
/**
* Shows spinner in place whilst loading avatar from server
*/
loading: true
}
},
computed: {
...mapGetters(['getToken']),
enabled: function () {
return this.$root.config.enableAvatars || true
}
},
watch: {
userid: function (userid, old) {
this.setUser(userid)
}
},
mounted: function () {
// Handled mounted situation. Userid might not be set yet so try placeholder
if (this.userid !== '') {
this.setUser(this.userid)
} else {
this.loading = false
}
},
methods: {
/**
* Load a new avatar from this userid
*/
setUser (userid) {
this.loading = true
this.avatarSource = ''
if (!this.enabled || userid === '') {
this.loading = false
return
}
const headers = new Headers()
const instance = this.$root.config.server || window.location.origin
const url = instance + '/remote.php/dav/avatars/' + this.userid + '/128.png'
headers.append('Authorization', 'Bearer ' + this.getToken)
headers.append('X-Requested-With', 'XMLHttpRequest')
fetch(url, { headers })
.then(response => {
if (response.ok) {
return response.blob()
}
if (response.status !== 404) {
throw new Error(`Unexpected status code ${response.status}`)
}
})
.then(blob => {
this.loading = false
if (blob) {
this.avatarSource = window.URL.createObjectURL(blob)
} else {
// 404, none found
this.avatarSource = ''
}
})
.catch(error => {
this.avatarSource = ''
this.loading = false
console.error(`Error loading avatar image for user "${this.userid}": `, error.message)
})
}
}
}
</script>
-12
View File
@@ -1,12 +0,0 @@
import axios from 'axios'
export function injectAuthToken (token) {
axios.interceptors.request.use(config => {
if (typeof config.headers.Authorization === 'undefined') {
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
}
return config
})
}
-8
View File
@@ -1,8 +0,0 @@
/**
* Asserts wheter the given object is empty
* @param {Object} obj Object to be checked
* @returns {Boolean}
*/
export function isObjectEmpty (obj) {
return Object.keys(obj).length === 0 && obj.constructor === Object
}
-262
View File
@@ -1,262 +0,0 @@
/* eslint-disable camelcase */
import {
AccountsService_ListAccounts,
AccountsService_UpdateAccount,
AccountsService_CreateAccount,
AccountsService_DeleteAccount
} from '../client/accounts'
import { RoleService_ListRoles } from '../client/settings'
/* eslint-enable camelcase */
import { injectAuthToken } from '../helpers/auth'
const state = {
config: null,
initialized: false,
failed: false,
accounts: {},
roles: null,
selectedAccounts: []
}
const getters = {
config: state => state.config,
isInitialized: state => state.initialized,
hasFailed: state => state.failed,
getAccountsSorted: state => {
return Object.values(state.accounts).sort((a1, a2) => {
if (a1.onPremisesSamAccountName === a2.onPremisesSamAccountName) {
return a1.id.localeCompare(a2.id)
}
return a1.onPremisesSamAccountName.localeCompare(a2.onPremisesSamAccountName)
})
},
areAllAccountsSelected: state => state.accounts.length === state.selectedAccounts.length,
isAnyAccountSelected: state => state.selectedAccounts.length > 0,
getServerForJsClient: (state, getters, rootState, rootGetters) => rootGetters.configuration.server.replace(/\/$/, '')
}
const mutations = {
LOAD_CONFIG (state, config) {
state.config = config
},
SET_INITIALIZED (state, value) {
state.initialized = value
},
SET_FAILED (state, value) {
state.failed = value
},
SET_ACCOUNTS (state, accounts) {
state.accounts = accounts
},
SET_ROLES (state, roles) {
state.roles = roles
},
TOGGLE_SELECTION_ACCOUNT (state, account) {
const accountIndex = state.selectedAccounts.indexOf(account)
accountIndex > -1 ? state.selectedAccounts.splice(accountIndex, 1) : state.selectedAccounts.push(account)
},
SET_SELECTED_ACCOUNTS (state, accounts) {
state.selectedAccounts = accounts
},
UPDATE_ACCOUNT (state, updatedAccount) {
const accountIndex = state.accounts.findIndex(account => account.id === updatedAccount.id)
state.accounts.splice(accountIndex, 1, updatedAccount)
},
RESET_ACCOUNTS_SELECTION (state) {
state.selectedAccounts = []
},
PUSH_NEW_ACCOUNT (state, account) {
state.accounts.push(account)
},
DELETE_ACCOUNT (state, accountId) {
const accountIndex = state.accounts.findIndex(account => account.id === accountId)
state.accounts.splice(accountIndex, 1)
}
}
const actions = {
loadConfig ({ commit }, config) {
commit('LOAD_CONFIG', config)
},
async initialize ({ commit, dispatch, getters }) {
await Promise.all([
dispatch('fetchAccounts'),
dispatch('fetchRoles')
])
if (!getters.hasFailed) {
commit('SET_INITIALIZED', true)
}
},
async fetchAccounts ({ commit, getters, rootGetters }) {
injectAuthToken(rootGetters.user.token)
try {
const response = await AccountsService_ListAccounts({
$domain: getters.getServerForJsClient,
body: {}
})
if (response.status === 201) {
const accounts = response.data.accounts
commit('SET_ACCOUNTS', accounts || [])
return
}
} catch (e) {
}
commit('SET_FAILED', true)
},
async fetchRoles ({ commit, getters, rootGetters }) {
injectAuthToken(rootGetters.user.token)
try {
const response = await RoleService_ListRoles({
$domain: getters.getServerForJsClient,
body: {}
})
if (response.status === 201) {
const roles = response.data.bundles
commit('SET_ROLES', roles || [])
return
}
} catch (e) {
}
commit('SET_FAILED', true)
},
toggleSelectionAll ({ commit, getters, state }) {
getters.areAllAccountsSelected ? commit('RESET_ACCOUNTS_SELECTION') : commit('SET_SELECTED_ACCOUNTS', [...state.accounts])
},
async setAccountActivated ({ commit, dispatch, state, getters, rootGetters }, activated) {
const failedAccounts = []
injectAuthToken(rootGetters.user.token)
for (const account of state.selectedAccounts) {
if (account.accountEnabled === activated) {
continue
}
try {
const response = await AccountsService_UpdateAccount({
$domain: getters.getServerForJsClient,
body: {
account: {
id: account.id,
accountEnabled: activated
},
update_mask: {
paths: ['AccountEnabled']
}
}
})
if (response.status === 201) {
commit('UPDATE_ACCOUNT', { ...account, accountEnabled: activated })
} else {
failedAccounts.push({ account: account.username })
}
} catch (error) {
failedAccounts.push({ account: account.username })
}
}
if (failedAccounts.length > 0) {
let errorTitle = ''
if (failedAccounts.length === 1) {
errorTitle = activated ? 'Failed to activate account.' : 'Failed to block account.'
} else {
errorTitle = activated ? 'Failed to activate accounts.' : 'Failed to block accounts.'
}
dispatch('showMessage', {
title: errorTitle,
status: 'danger'
}, { root: true })
return Promise.resolve(false)
}
commit('RESET_ACCOUNTS_SELECTION')
return Promise.resolve(true)
},
async createNewAccount ({ getters, rootGetters, commit, dispatch }, account) {
injectAuthToken(rootGetters.user.token)
try {
const response = await AccountsService_CreateAccount({
$domain: getters.getServerForJsClient,
body: {
account: {
on_premises_sam_account_name: account.username,
preferred_name: account.username,
mail: account.email,
password_profile: {
password: account.password
},
account_enabled: true,
display_name: account.username
}
}
})
if (response.status === 201) {
commit('PUSH_NEW_ACCOUNT', response.data)
return Promise.resolve(true)
}
} catch (error) {
dispatch('showMessage', {
title: 'Failed to create account.',
status: 'danger'
}, { root: true })
return Promise.reject(error)
}
return Promise.resolve(false)
},
async deleteAccounts ({ getters, rootGetters, state, commit, dispatch }) {
const failedAccounts = []
injectAuthToken(rootGetters.user.token)
for (const account of state.selectedAccounts) {
try {
const response = await AccountsService_DeleteAccount({
$domain: getters.getServerForJsClient,
body: {
id: account.id
}
})
if (response.status === 201 || response.status === 204) {
commit('DELETE_ACCOUNT', account.id)
} else {
failedAccounts.push({ account: account.username })
}
} catch (error) {
failedAccounts.push({ account: account.username })
}
}
if (failedAccounts.length > 0) {
const errorTitle = failedAccounts.length === 1 ? 'Failed to delete account.' : 'Failed to delete accounts.'
dispatch('showMessage', {
title: errorTitle,
status: 'danger'
}, { root: true })
return Promise.resolve(false)
}
commit('RESET_ACCOUNTS_SELECTION')
return Promise.resolve(true)
}
}
export default {
namespaced: true,
state,
getters,
actions,
mutations
}
@@ -1,75 +0,0 @@
Feature: Accounts
Scenario: admin checks accounts list
Given user "Moss" has logged in using the webUI
When the user browses to the accounts page
Then user "einstein" should be displayed in the accounts list on the WebUI
And user "konnectd" should be displayed in the accounts list on the WebUI
And user "marie" should be displayed in the accounts list on the WebUI
And user "reva" should be displayed in the accounts list on the WebUI
And user "richard" should be displayed in the accounts list on the WebUI
Scenario: admin changes non-admin user's role to admin
Given user "Moss" has logged in using the webUI
When the user browses to the accounts page
Then user "einstein" should be displayed in the accounts list on the WebUI
When the user changes the role of user "einstein" to "Admin" using the WebUI
Then the displayed role of user "einstein" should be "Admin" on the WebUI
When the user reloads the current page of the webUI
Then the displayed role of user "einstein" should be "Admin" on the WebUI
@skip @issue-product-167
Scenario: regular user should not be able to see accounts list
Given user "Marie" has logged in using the webUI
When the user browses to the accounts page
Then the user should not be able to see the accounts list on the WebUI
@skip @issue-product-167
Scenario: guest user should not be able to see accounts list
Given user "Moss" has logged in using the webUI
When the user browses to the accounts page
Then user "einstein" should be displayed in the accounts list on the WebUI
When the user changes the role of user "einstein" to "Guest" using the WebUI
And the user logs out of the webUI
And user "Einstein" logs in using the webUI
And the user browses to the accounts page
Then the user should not be able to see the accounts list on the WebUI
# We want to separate this into own scenarios but because we do not have clean env for each scenario yet
# we are resetting it manually by combining them into one
Scenario: disable/enable account
Given user "Moss" has logged in using the webUI
When the user browses to the accounts page
Then user "einstein" should be displayed in the accounts list on the WebUI
When the user disables user "einstein" using the WebUI
Then the status indicator of user "einstein" should be "disabled" on the WebUI
# And user "einstein" should not be able to log in
When the user enables user "einstein" using the WebUI
Then the status indicator of user "einstein" should be "enabled" on the WebUI
# And user "einstein" should be able to log in
Scenario: disable/enable multiple accounts
Given user "Moss" has logged in using the webUI
When the user browses to the accounts page
Then user "einstein" should be displayed in the accounts list on the WebUI
And user "marie" should be displayed in the accounts list on the WebUI
When the user disables users "einstein,marie" using the WebUI
Then the status indicator of users "einstein,marie" should be "disabled" on the WebUI
# And user "einstein" should not be able to log in
# And user "marie" should not be able to log in
When the user enables users "einstein,marie" using the WebUI
Then the status indicator of user "einstein,marie" should be "enabled" on the WebUI
# And user "einstein" should be able to log in
# And user "marie" should be able to log in
Scenario: create a user
Given user "Moss" has logged in using the webUI
And the user browses to the accounts page
When the user creates a new user with username "bob", email "bob@example.org" and password "bob" using the WebUI
Then user "bob" should be displayed in the accounts list on the WebUI
Scenario: delete a user
Given user "Moss" has logged in using the webUI
And the user browses to the accounts page
When the user deletes user "bob" using the WebUI
Then user "bob" should not be displayed in the accounts list on the WebUI
Loaded 100 of 1593 files, more files were not shown because too many files have changed in this diff. Show more