Compare commits

..

1 Commits

Author SHA1 Message Date
b44b4ab7be fix(deps): update sentry-javascript monorepo to v7.104.0 2024-03-01 00:07:29 +00:00
42 changed files with 181 additions and 982 deletions

View File

@ -44,4 +44,3 @@ ENV VIKUNJA_SERVICE_ROOTPATH=/app/vikunja/
ENV VIKUNJA_DATABASE_PATH=/db/vikunja.db
COPY --from=apibuilder /build/vikunja-* vikunja
COPY --from=apibuilder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/

View File

@ -6,7 +6,7 @@ service:
# The duration of the issued JWT tokens in seconds.
# The default is 259200 seconds (3 Days).
jwtttl: 259200
# The duration of the "remember me" time in seconds. When the login request is made with
# The duration of the "remember me" time in seconds. When the login request is made with
# the long param set, the token returned will be valid for this period.
# The default is 2592000 seconds (30 Days).
jwtttllong: 2592000
@ -48,7 +48,7 @@ service:
# If enabled, vikunja will send an email to everyone who is either assigned to a task or created it when a task reminder
# is due.
enableemailreminders: true
# If true, will allow users to request the complete deletion of their account. When using external authentication methods
# If true, will allow users to request the complete deletion of their account. When using external authentication methods
# it may be required to coordinate with them in order to delete the account. This setting will not affect the cli commands
# for user deletion.
enableuserdeletion: true
@ -109,7 +109,7 @@ database:
typesense:
# Whether to enable the Typesense integration. If true, all tasks will be synced to the configured Typesense
# instance and all search and filtering will run through Typesense instead of only through the database.
# Typesense allows fast fulltext search including fuzzy matching support. It may return different results than
# Typesense allows fast fulltext search including fuzzy matching support. It may return different results than
# what you'd get with a database-only search.
enabled: false
# The url to the Typesense instance you want to use. Can be hosted locally or in Typesense Cloud as long
@ -203,7 +203,7 @@ ratelimit:
# Possible values are "keyvalue", "memory" or "redis".
# When choosing "keyvalue" this setting follows the one configured in the "keyvalue" section.
store: keyvalue
# The number of requests a user can make from the same IP to all unauthenticated routes (login, register,
# The number of requests a user can make from the same IP to all unauthenticated routes (login, register,
# password confirmation, email verification, password reset request) per minute. This limit cannot be disabled.
# You should only change this if you know what you're doing.
noauthlimit: 10
@ -301,11 +301,13 @@ auth:
enabled: true
# OpenID configuration will allow users to authenticate through a third-party OpenID Connect compatible provider.<br/>
# The provider needs to support the `openid`, `profile` and `email` scopes.<br/>
# **Note:** Some openid providers (like Gitlab) only make the email of the user available through OpenID if they have set it to be publicly visible.
# **Note:** Some openid providers (like gitlab) only make the email of the user available through openid claims if they have set it to be publicly visible.
# If the email is not public in those cases, authenticating will fail.
# **Note 2:** The frontend expects the third party to rediect the user <frontend-url>/auth/openid/<auth key> after authentication. Please make sure to configure the redirect url in your third party auth service accordingly if you're using the default vikunja frontend.
# The frontend will automatically provide the API with the redirect url, composed from the current url where it's hosted.
# If you want to use the desktop client with OpenID, make sure to allow redirects to `127.0.0.1`.
# **Note 2:** The frontend expects to be redirected after authentication by the third party
# to <frontend-url>/auth/openid/<auth key>. Please make sure to configure the redirect url in your third party
# auth service accordingly if you're using the default vikunja frontend.
# The frontend will automatically provide the api with the redirect url, composed from the current url where it's hosted.
# If you want to use the desktop client with openid, make sure to allow redirects to `127.0.0.1`.
# Take a look at the [default config file](https://kolaente.dev/vikunja/vikunja/src/branch/main/config.yml.sample) for more information about how to configure openid authentication.
openid:
# Enable or disable OpenID Connect authentication
@ -323,10 +325,6 @@ auth:
clientid:
# The client secret used to authenticate Vikunja at the OpenID Connect provider.
clientsecret:
# The scope necessary to use oidc.
# If you want to use the Feature to create and assign to vikunja teams via oidc, you have to add the custom "vikunja_scope" and check [openid.md](https://vikunja.io/docs/openid/).
# e.g. scope: openid email profile vikunja_scope
scope: openid email profile
# Prometheus metrics endpoint
metrics:

15
docker/entrypoint.sh Normal file
View File

@ -0,0 +1,15 @@
#!/usr/bin/env sh
set -e
if [ -n "$PUID" ] && [ "$PUID" -ne 0 ] && \
[ -n "$PGID" ] && [ "$PGID" -ne 0 ] ; then
echo "info: creating the new user vikunja with $PUID:$PGID"
groupmod -g "$PGID" -o vikunja
usermod -u "$PUID" -o vikunja
chown -R vikunja:vikunja ./files/
chown vikunja:vikunja .
exec su vikunja -c /app/vikunja/vikunja "$@"
else
echo "info: creation of non-root user is skipped"
exec /app/vikunja/vikunja "$@"
fi

View File

@ -94,7 +94,7 @@ Environment path: `VIKUNJA_SERVICE_JWTTTL`
### jwtttllong
The duration of the "remember me" time in seconds. When the login request is made with
The duration of the "remember me" time in seconds. When the login request is made with
the long param set, the token returned will be valid for this period.
The default is 2592000 seconds (30 Days).
@ -289,7 +289,7 @@ Environment path: `VIKUNJA_SERVICE_ENABLEEMAILREMINDERS`
### enableuserdeletion
If true, will allow users to request the complete deletion of their account. When using external authentication methods
If true, will allow users to request the complete deletion of their account. When using external authentication methods
it may be required to coordinate with them in order to delete the account. This setting will not affect the cli commands
for user deletion.
@ -406,7 +406,7 @@ Environment path: `VIKUNJA_SENTRY_FRONTENDDSN`
### type
Database type to use. Supported values are mysql, postgres and sqlite. Vikunja is able to run with MySQL 8.0+, Mariadb 10.2+, PostgreSQL 12+, and sqlite.
Database type to use. Supported types are mysql, postgres and sqlite.
Default: `sqlite`
@ -569,7 +569,7 @@ Environment path: `VIKUNJA_DATABASE_TLS`
Whether to enable the Typesense integration. If true, all tasks will be synced to the configured Typesense
instance and all search and filtering will run through Typesense instead of only through the database.
Typesense allows fast fulltext search including fuzzy matching support. It may return different results than
Typesense allows fast fulltext search including fuzzy matching support. It may return different results than
what you'd get with a database-only search.
Default: `false`
@ -1024,7 +1024,7 @@ Environment path: `VIKUNJA_RATELIMIT_STORE`
### noauthlimit
The number of requests a user can make from the same IP to all unauthenticated routes (login, register,
The number of requests a user can make from the same IP to all unauthenticated routes (login, register,
password confirmation, email verification, password reset request) per minute. This limit cannot be disabled.
You should only change this if you know what you're doing.
@ -1209,11 +1209,13 @@ Environment path: `VIKUNJA_AUTH_LOCAL`
OpenID configuration will allow users to authenticate through a third-party OpenID Connect compatible provider.<br/>
The provider needs to support the `openid`, `profile` and `email` scopes.<br/>
**Note:** Some openid providers (like Gitlab) only make the email of the user available through OpenID if they have set it to be publicly visible.
**Note:** Some openid providers (like gitlab) only make the email of the user available through openid claims if they have set it to be publicly visible.
If the email is not public in those cases, authenticating will fail.
**Note 2:** The frontend expects the third party to rediect the user <frontend-url>/auth/openid/<auth key> after authentication. Please make sure to configure the redirect url in your third party auth service accordingly if you're using the default vikunja frontend.
The frontend will automatically provide the API with the redirect url, composed from the current url where it's hosted.
If you want to use the desktop client with OpenID, make sure to allow redirects to `127.0.0.1`.
**Note 2:** The frontend expects to be redirected after authentication by the third party
to <frontend-url>/auth/openid/<auth key>. Please make sure to configure the redirect url in your third party
auth service accordingly if you're using the default vikunja frontend.
The frontend will automatically provide the api with the redirect url, composed from the current url where it's hosted.
If you want to use the desktop client with openid, make sure to allow redirects to `127.0.0.1`.
Take a look at the [default config file](https://kolaente.dev/vikunja/vikunja/src/branch/main/config.yml.sample) for more information about how to configure openid authentication.
Default: `<empty>`

View File

@ -10,7 +10,7 @@ menu:
# OpenID example configurations
On this page you will find examples about how to set up Vikunja with a third-party OAuth 2.0 provider using OpenID Connect.
On this page you will find examples about how to set up Vikunja with a third-party OpenID provider.
To add another example, please [edit this document](https://kolaente.dev/vikunja/vikunja/src/branch/main/docs/content/doc/setup/openid-examples.md) and send a PR.
{{< table_of_contents >}}
@ -67,7 +67,7 @@ Google config:
Note that there currently seems to be no way to stop creation of new users, even when `enableregistration` is `false` in the configuration. This means that this approach works well only with an "Internal Organization" app for Google Workspace, which limits the allowed users to organizational accounts only. External / public applications will potentially allow every Google user to register.
## Keycloak
## Keycloak
Vikunja Config:
```yaml
@ -111,7 +111,4 @@ auth:
clientsecret: "" # copy from Authentik
```
**Note:** The `authurl` that Vikunja requires is not the `Authorize URL` that you can see in the Provider.
OpenID Discovery is used to find the correct endpoint to use automatically, by accessing the `OpenID Configuration URL` (usually `https://authentik.mydomain.com/application/o/vikunja/.well-known/openid-configuration`).
Use this URL without the `.well-known/openid-configuration` as the `authurl`.
Typically this URL can be found in the metadata section within your identity provider.
**Note:** The `authurl` that Vikunja requires is not the `Authorize URL` that you can see in the Provider. Vikunja uses Open ID Discovery to find the correct endpoint to use. Vikunja does this by automatically accessing the `OpenID Configuration URL` (usually `https://authentik.mydomain.com/application/o/vikunja/.well-known/openid-configuration`). Use this URL without the `.well-known/openid-configuration` as the `authurl`.

View File

@ -1,180 +0,0 @@
---
date: "2022-08-09:00:00+02:00"
title: "OpenID"
draft: false
type: "doc"
menu:
sidebar:
parent: "setup"
---
# OpenID
Vikunja allows for authentication with an external identity source such as Authentik, Keycloak or similar via the
[OpenID Connect](https://openid.net/developers/specs/) standard.
{{< table_of_contents >}}
## OpenID Connect Overview
OpenID Connect is a standardized identity layer built on top of the more generic OAuth 2.0 specification, simplying interaction between the involved parties significantly.
While the [OpenID specification](https://openid.net/specs/openid-connect-core-1_0.html#Overview) is worth a read, we summarize the most important basics here.
The involved parties are:
- **Resource Owner:** typically the end-user
- **Resource Server:** the application server handling requests from the client, the Vikunja API in our case
- **Client:** the application or client accessing the RS on behalf of the RO. Vikunja web frontend or any of the apps
- **Authorization Server:** the server verifying the user identity and issuing tokens. These docs also use the words `OAuth 2.0 provider`, `Identity Provider` interchangeably.
After the user is authenticated, the provider issues a token to the user, containing various claims.
There's different types of tokens (ID token, access token, refresh token), and all of them are created as [JSON Web Token](https://www.rfc-editor.org/info/rfc7519).
Claims in turn are assertions containing information about the token bearer, usually the user.
**Scopes** are requested by the client when redirecting the end-user to the Authorization Server for authentication, and indirectly control which claims are included in the resulting tokens.
There's certain default scopes, but its also possible to define custom scopes, which are used by the feature assigning users to Teams automatically.
## Configuring OIDC Authentication
To achieve authentication via an external provider, it is required to (a) configure a confidential Client on your OAuth 2.0 provider and (b) configure Vikunja to authenticate against this provider.
[Example configurations]({{< ref "openid-examples.md">}}) are provided for various different identity providers, below you can find generic guides though.
OpenID Connect defines various flow types indicating how exactly the interaction between the involved parties work, Vikunja makes use of the standard **Authorization Code Flow**.
### Step 1: Configure your Authorization Server
The first step is to configure the Authorization Server to correctly handle requests coming from Vikunja.
In general, this involves the following steps at a minimum:
- Create a confidential client and obtain the client ID and client secret
- Configure (whitelist) redirect URLs that can be used by Vikunja
- Make sure the required scopes (`openid profile email` are the default scopes used by Vikunja) are supported
- Optional: configure an additional scope for automatic team assignment, see below for details
More detailled instructions for various different identity providers can be [found here]({{< ref "openid-examples.md">}})
### Step 2: Configure Vikunja
Vikunja has to be configured to use the identity provider. Please note that there is currently no option to configure these settings via environment variables, they have to be defined using the configuration file. The configuration schema is as follows:
```yaml
auth:
openid:
enabled: true
redirecturl: https://vikunja.mydomain.com/auth/openid/ <---- slash at the end is important
providers:
- name: <provider-name>
authurl: <auth-url>
clientid: <vikunja client-id>
clientsecret: <vikunja client-secret>
scope: openid profile email
```
The values for `authurl` can be obtained from the Metadata of your provider, while `clientid` and `clientsecret` are obtained when configuring the client.
The scope usually doesn't need to be specified or changed, unless you want to configure the automatic team assignment.
Optionally it is possible to disable local authentication and therefore forcing users to login via OpenID connect:
```yaml
auth:
local:
enabled: false
```
## Automatically assign users to teams
Vikunja is capable of automatically adding users to a team based on OIDC claims added by the identity provider.
If configured, Vikunja will sync teams, automatically create new ones and make sure the members are part of the configured teams.
Teams which exist only because they were created from oidc attributes are not editable in Vikunja.
To distinguish between teams created in Vikunja and teams generated automatically via oidc, generated teams have an `oidcID` assigned internally.
Within the UI, the teams created through OIDC get a `(OIDC)` suffix to make them distinguishable from locally created teams.
On a high level, you need to make sure that the **ID token** issued by your identity provider contains a `vikunja_groups` claim, following the structure defined below.
It depends on the provider being used as well as the preferences of the administrator how this is achieved.
Typically you'd want to request an additional scope (e.g. `vikunja_scope`) which then triggers the identity provider to add the claim.
If the `vikunja_groups` is part of the **ID token**, Vikunja will start the procedure and import teams and team memberships.
The claim structure expexted by Vikunja is as follows:
```json
{
"vikunja_groups": [
{
"name": "team 1",
"oidcID": 33349
},
{
"name": "team 2",
"oidcID": 35933
}
]
}
```
For each team, you need to define a team `name` and an `oidcID`, where the `oidcID` can be any string with a length of less than 250 characters.
The `oidcID` is used to uniquely identify the team, so please make sure to keep this unique.
Below you'll find two example implementations for Authentik and Keycloak.
If you've successfully implemented this with another identity provider, please let us know and submit a PR to improve the docs.
### Setup in Authentik
To configure automatic team management through Authentik, we assume you have already [set up Authentik]({{< ref "openid-examples.md">}}#authentik) as an OIDC provider for authentication with Vikunja.
To use Authentik's group assignment feature, follow these steps:
1. Edit [your config]({{< ref "config.md">}}) to include the following scopes: `openid profile email vikunja_scope`
2. Open `<your authentik url>/if/admin/#/core/property-mappings`
3. Create a new property mapping called `vikunja_scope` as scope mapping. There is a field `expression` to enter python expressions that will be delivered with the oidc token.
4. Write a small script like the following to add group information to `vikunja_scope`:
```python
groupsDict = {"vikunja_groups": []}
for group in request.user.ak_groups.all():
groupsDict["vikunja_groups"].append({"name": group.name, "oidcID": group.num_pk})
return groupsDict
```
5. In Authentik's menu on the left, go to Applications > Providers > Select the Vikunja provider. Then click on "Edit", on the bottom open "Advanced protocol settings", select the newly created property mapping under "Scopes". Save the provider.
Now when you log into Vikunja via Authentik it will show you a list of scopes you are claiming.
You should see the description you entered on the OIDC provider's admin area.
Proceed to vikunja and open the teams page in the sidebar menu.
You should see "(OIDC)" written next to each team you were assigned through OIDC.
### Setup in Keycloak
The kind people from Makerspace Darmstadt e.V. have written [a guide on how to create a mapper for Vikunja here](https://github.com/makerspace-darmstadt/keycloak-vikunja-mapper).
## Use cases
All examples assume one team called "Team 1" to be configured within your provider.
* *Token delivers team.name +team.oidcID and Vikunja team does not exist:* \
New team will be created called "Team 1" with attribute oidcID: "33929"
2. *In Vikunja Team with name "team 1" already exists in vikunja, but has no oidcID set:* \
new team will be created called "team 1" with attribute oidcID: "33929"
3. *In Vikunja Team with name "team 1" already exists in vikunja, but has different oidcID set:* \
new team will be created called "team 1" with attribute oidcID: "33929"
4. *In Vikunja Team with oidcID "33929" already exists in vikunja, but has different name than "team1":* \
new team will be created called "team 1" with attribute oidcID: "33929"
5. *Scope vikunja_scope is not set:* \
nothing happens
6. *oidcID is not set:* \
You'll get error.
Custom Scope malformed
"The custom scope set by the OIDC provider is malformed. Please make sure the openid provider sets the data correctly for your scope. Check especially to have set an oidcID."
7. *In Vikunja I am in "team 3" with oidcID "", but the token does not deliver any data for "team 3":* \
You will stay in team 3 since it was not set by the oidc provider
8. *In Vikunja I am in "team 3" with oidcID "12345", but the token does not deliver any data for "team 3"*:\
You will be signed out of all teams, which have an oidcID set and are not contained in the token.
Especially if you've been the last team member, the team will be deleted.

View File

@ -44,7 +44,6 @@ This document describes the different errors Vikunja can return.
| 1020 | 412 | This user account is disabled. |
| 1021 | 412 | This account is managed by a third-party authentication provider. |
| 1021 | 412 | The username must not contain spaces. |
| 1022 | 412 | The custom scope set by the OIDC provider is malformed. Please make sure the openid provider sets the data correctly for your scope. Check especially to have set an oidcID. |
## Validation
@ -107,9 +106,6 @@ This document describes the different errors Vikunja can return.
| 6005 | 409 | The user is already a member of that team. |
| 6006 | 400 | Cannot delete the last team member. |
| 6007 | 403 | The team does not have access to the project to perform that action. |
| 6008 | 400 | There are no teams found with that team name. |
| 6009 | 400 | There is no oidc team with that team name and oidcId. |
| 6010 | 400 | There are no oidc teams found for the user. |
## User Project Access

View File

@ -58,8 +58,8 @@
"@infectoone/vue-ganttastic": "2.2.0",
"@intlify/unplugin-vue-i18n": "2.0.0",
"@kyvg/vue3-notification": "3.2.0",
"@sentry/tracing": "7.103.0",
"@sentry/vue": "7.103.0",
"@sentry/tracing": "7.104.0",
"@sentry/vue": "7.104.0",
"@tiptap/core": "2.2.4",
"@tiptap/extension-blockquote": "2.2.4",
"@tiptap/extension-bold": "2.2.4",

View File

@ -35,11 +35,11 @@ dependencies:
specifier: 3.2.0
version: 3.2.0(vue@3.4.21)
'@sentry/tracing':
specifier: 7.103.0
version: 7.103.0
specifier: 7.104.0
version: 7.104.0
'@sentry/vue':
specifier: 7.103.0
version: 7.103.0(vue@3.4.21)
specifier: 7.104.0
version: 7.104.0(vue@3.4.21)
'@tiptap/core':
specifier: 2.2.4
version: 2.2.4(@tiptap/pm@2.2.4)
@ -4209,45 +4209,45 @@ packages:
resolution: {integrity: sha512-RbhOOTCNoCrbfkRyoXODZp75MlpiHMgbE5MEBZAnnnLyQNgrigEj4p0lzsMDyc1zVsJDLrivB58tgg3emX0eEA==}
dev: true
/@sentry-internal/feedback@7.103.0:
resolution: {integrity: sha512-2nYoCfP7FpiUR+xxO5y5BL2ajHrhM4fL7HSup6QKNn7gI7vLyllYOOuYFNHhSmsXCD0i00U8DBClGLcn+6DQqw==}
/@sentry-internal/feedback@7.104.0:
resolution: {integrity: sha512-+OWqm+X9ZfEQQmxVoZsc9lpzd85pabAT+bEj57StRMTnfdRbD9TippS20nCD9N2Ql5v2/41NfiPONMejGbnOwg==}
engines: {node: '>=12'}
dependencies:
'@sentry/core': 7.103.0
'@sentry/types': 7.103.0
'@sentry/utils': 7.103.0
'@sentry/core': 7.104.0
'@sentry/types': 7.104.0
'@sentry/utils': 7.104.0
dev: false
/@sentry-internal/replay-canvas@7.103.0:
resolution: {integrity: sha512-EyDRMdlSqtwY8zGFhOWwl+nwwo98hlhJz+bpF5PQ6VmFpbplh6Wqfx2p+cPXQr40TGMMC4+vPFlSWTOMjcO9zQ==}
/@sentry-internal/replay-canvas@7.104.0:
resolution: {integrity: sha512-gfdnkFIpxAveKNghkvRCqv+hSiBkxYVoyFZLTvUPuM9Cmvmket1/PpnuWMC2jNtCEewG3gxkPDd4EaT9oa1HZQ==}
engines: {node: '>=12'}
dependencies:
'@sentry/core': 7.103.0
'@sentry/replay': 7.103.0
'@sentry/types': 7.103.0
'@sentry/utils': 7.103.0
'@sentry/core': 7.104.0
'@sentry/replay': 7.104.0
'@sentry/types': 7.104.0
'@sentry/utils': 7.104.0
dev: false
/@sentry-internal/tracing@7.103.0:
resolution: {integrity: sha512-sZ/Wao8HOvGaBs7WlOdflMpHGAFkOBWL6hBiirHaOy5d+IDm7n7et5U6zhvcfiyYBO4nY36gy1Tg5mw+aNO0Vw==}
/@sentry-internal/tracing@7.104.0:
resolution: {integrity: sha512-2z7OijM1J5ndJUiJJElC3iH9qb/Eb8eYm2v8oJhM8WVdc5uCKfrQuYHNgGOnmY2FOCfEUlTmMQGpDw7DJ67L5w==}
engines: {node: '>=8'}
dependencies:
'@sentry/core': 7.103.0
'@sentry/types': 7.103.0
'@sentry/utils': 7.103.0
'@sentry/core': 7.104.0
'@sentry/types': 7.104.0
'@sentry/utils': 7.104.0
dev: false
/@sentry/browser@7.103.0:
resolution: {integrity: sha512-lP3Oplnwo1lY8ltk8SWzQURbxnSfVhYA099mVs1T95sdwXS16Za6SX7Ld/9T506ZW/WyoU4VCq7eKtG2kPFhMQ==}
/@sentry/browser@7.104.0:
resolution: {integrity: sha512-HsqO+mr1SowGoP0VbuWrQ2DZT0t5PLomy7LEYa6+4lbOemnY+5YV2NSwBTKbjYysvKipSwaRtPhXrsXsMaz8Bg==}
engines: {node: '>=8'}
dependencies:
'@sentry-internal/feedback': 7.103.0
'@sentry-internal/replay-canvas': 7.103.0
'@sentry-internal/tracing': 7.103.0
'@sentry/core': 7.103.0
'@sentry/replay': 7.103.0
'@sentry/types': 7.103.0
'@sentry/utils': 7.103.0
'@sentry-internal/feedback': 7.104.0
'@sentry-internal/replay-canvas': 7.104.0
'@sentry-internal/tracing': 7.104.0
'@sentry/core': 7.104.0
'@sentry/replay': 7.104.0
'@sentry/types': 7.104.0
'@sentry/utils': 7.104.0
dev: false
/@sentry/cli@2.19.1:
@ -4266,53 +4266,53 @@ packages:
- supports-color
dev: true
/@sentry/core@7.103.0:
resolution: {integrity: sha512-LCI+PIDoF/RLqN41fNXum3ilmS6ukni6L7t38vSdibbe2G0804EbPLtOIpv2PkS8E6CFuRW5zOb+8OwEAAtZWw==}
/@sentry/core@7.104.0:
resolution: {integrity: sha512-XPndD6IGQGd07/EntvYVzOWQUo/Gd7L3DwYFeEKeBv6ByWjbBNmVZFRhU0GPPsCHKyW9yMU9OO9diLSS4ijsRg==}
engines: {node: '>=8'}
dependencies:
'@sentry/types': 7.103.0
'@sentry/utils': 7.103.0
'@sentry/types': 7.104.0
'@sentry/utils': 7.104.0
dev: false
/@sentry/replay@7.103.0:
resolution: {integrity: sha512-I37komyb+DruQG8lPPPOFxLLbOijNXeTxiWLsIn+KFZqRtKqxxQWdNnk56V4YSTpFzxnMEFMRCpXhncuTWu4LA==}
/@sentry/replay@7.104.0:
resolution: {integrity: sha512-HmWBr/u+SNeULxCxM8lJb2iqhjizeLGJtuKSShPEguEXIUT4kzdoqLh6wn7BAjiKzhmyjrnBcosR5LUqJtGYZQ==}
engines: {node: '>=12'}
dependencies:
'@sentry-internal/tracing': 7.103.0
'@sentry/core': 7.103.0
'@sentry/types': 7.103.0
'@sentry/utils': 7.103.0
'@sentry-internal/tracing': 7.104.0
'@sentry/core': 7.104.0
'@sentry/types': 7.104.0
'@sentry/utils': 7.104.0
dev: false
/@sentry/tracing@7.103.0:
resolution: {integrity: sha512-wlL9XidxcjC1dWXj7KSdYMgPgK+ry4dYy+YoW9gqRL+FbS6BJebV73Tni+5zponzCW+LMWP/IgMIB9IZt0WWTQ==}
/@sentry/tracing@7.104.0:
resolution: {integrity: sha512-p1mmqNKrCVlA4b6js3twZotAIdS1cLXh05oU9WmSAW3iDo1Vf9QO5+/9K1Vh3a9fPQt3nDJeD/OgAb7C4VBIsA==}
engines: {node: '>=8'}
dependencies:
'@sentry-internal/tracing': 7.103.0
'@sentry-internal/tracing': 7.104.0
dev: false
/@sentry/types@7.103.0:
resolution: {integrity: sha512-NCvKyx8d2AGBQKPARrJemZmZ16DiMo688OEikZg4BbvFNDUzK5Egm2BH0vfLDhbNkU19o3maJowrYo42m8r9Zw==}
/@sentry/types@7.104.0:
resolution: {integrity: sha512-5bs0xe0+GZR4QBm9Nrqw59o0sv3kBtCosrZDVxBru/dQbrfnB+/kVorvuM0rV3+coNITTKcKDegSZmK1d2uOGQ==}
engines: {node: '>=8'}
dev: false
/@sentry/utils@7.103.0:
resolution: {integrity: sha512-phkUJt3F0UOkVq+M4GfdAh2ewI3ASrNiJddx9aO7GnT0aDwwVBHZltnqt95qgAB8W+BipTSt1dAh8yUbbq1Ceg==}
/@sentry/utils@7.104.0:
resolution: {integrity: sha512-ZVg+xZirI9DlOi0NegNVocswdh/8p6QkzlQzDQY2LP2CC6JQdmwi64o0S4rPH4YIHNKQJTpIjduoxeKgd1EO5g==}
engines: {node: '>=8'}
dependencies:
'@sentry/types': 7.103.0
'@sentry/types': 7.104.0
dev: false
/@sentry/vue@7.103.0(vue@3.4.21):
resolution: {integrity: sha512-o5DlC+B6Yq39KY8SguyX2LWM+daPmjzv5teIx+Vj/MOXRb84gooEqgGvHTO/dlR7qhP89aSw7GRdnjyV+WO5WQ==}
/@sentry/vue@7.104.0(vue@3.4.21):
resolution: {integrity: sha512-tm8AyMkO1IWuDIaS4DQ67g5PNRSBHNcEGQafv0MQc6pKan5ClI5lolrT83Rg5Huu/jgvZm41h7ssq5nFo8OmUA==}
engines: {node: '>=8'}
peerDependencies:
vue: 2.x || 3.x
dependencies:
'@sentry/browser': 7.103.0
'@sentry/core': 7.103.0
'@sentry/types': 7.103.0
'@sentry/utils': 7.103.0
'@sentry/browser': 7.104.0
'@sentry/core': 7.104.0
'@sentry/types': 7.104.0
'@sentry/utils': 7.104.0
vue: 3.4.21(typescript@5.3.3)
dev: false

View File

@ -26,7 +26,7 @@
class="base-button"
:href="href"
rel="noreferrer noopener nofollow"
:target="openExternalInNewTab ? '_blank' : undefined"
target="_blank"
>
<slot />
</a>
@ -69,7 +69,6 @@ export interface BaseButtonProps extends /* @vue-ignore */ HTMLAttributes {
disabled?: boolean
to?: RouteLocationRaw
href?: string
openExternalInNewTab?: boolean
}
export interface BaseButtonEmits {
@ -79,7 +78,6 @@ export interface BaseButtonEmits {
const {
type = BASE_BUTTON_TYPES_MAP.BUTTON,
disabled = false,
openExternalInNewTab = true,
} = defineProps<BaseButtonProps>()
const emit = defineEmits<BaseButtonEmits>()

View File

@ -122,7 +122,7 @@ const labelStore = useLabelStore()
labelStore.loadAllLabels()
const projectStore = useProjectStore()
projectStore.loadAllProjects()
projectStore.loadProjects()
</script>
<style lang="scss" scoped>

View File

@ -11,17 +11,14 @@ export function getRedirectUrlFromCurrentFrontendPath(provider: IProvider): stri
export const redirectToProvider = (provider: IProvider) => {
console.log({provider})
const redirectUrl = getRedirectUrlFromCurrentFrontendPath(provider)
const state = createRandomID(24)
localStorage.setItem('state', state)
let scope = 'openid email profile'
if (provider.scope !== null){
scope = provider.scope
}
window.location.href = `${provider.authUrl}?client_id=${provider.clientId}&redirect_uri=${redirectUrl}&response_type=code&scope=${scope}&state=${state}`
window.location.href = `${provider.authUrl}?client_id=${provider.clientId}&redirect_uri=${redirectUrl}&response_type=code&scope=openid email profile&state=${state}`
}
export const redirectToProviderOnLogout = (provider: IProvider) => {
if (provider.logoutUrl.length > 0) {
window.location.href = `${provider.logoutUrl}`

View File

@ -9,7 +9,6 @@ export interface ITeam extends IAbstract {
description: string
members: ITeamMember[]
right: Right
oidcId: string
createdBy: IUser
created: Date

View File

@ -13,7 +13,6 @@ export default class TeamModel extends AbstractModel<ITeam> implements ITeam {
description = ''
members: ITeamMember[] = []
right: Right = RIGHTS.READ
oidcId = ''
createdBy: IUser = {} // FIXME: seems wrong
created: Date = null

View File

@ -111,13 +111,13 @@ export function useSavedFilter(projectId?: MaybeRef<IProject['id']>) {
async function createFilter() {
filter.value = await filterService.create(filter.value)
await projectStore.loadAllProjects()
await projectStore.loadProjects()
router.push({name: 'project.index', params: {projectId: getProjectId(filter.value)}})
}
async function saveFilter() {
const response = await filterService.update(filter.value)
await projectStore.loadAllProjects()
await projectStore.loadProjects()
success({message: t('filters.edit.success')})
response.filters = objectToSnakeCase(response.filters)
filter.value = response
@ -130,7 +130,7 @@ export function useSavedFilter(projectId?: MaybeRef<IProject['id']>) {
async function deleteFilter() {
await filterService.delete(filter.value)
await projectStore.loadAllProjects()
await projectStore.loadProjects()
success({message: t('filters.delete.success')})
router.push({name: 'projects.index'})
}

View File

@ -175,28 +175,20 @@ export const useProjectStore = defineStore('project', () => {
}
}
async function loadAllProjects() {
async function loadProjects() {
const cancel = setModuleLoading(setIsLoading)
const projectService = new ProjectService()
const loadedProjects: IProject[] = []
let page = 1
try {
do {
const newProjects = await projectService.getAll({}, {is_archived: true}, page) as IProject[]
loadedProjects.push(...newProjects)
page++
} while (page <= projectService.totalPages)
const loadedProjects = await projectService.getAll({}, {is_archived: true}) as IProject[]
projects.value = {}
setProjects(loadedProjects)
loadedProjects.forEach(p => add(p))
return loadedProjects
} finally {
cancel()
}
projects.value = {}
setProjects(loadedProjects)
loadedProjects.forEach(p => add(p))
return loadedProjects
}
function getAncestors(project: IProject): IProject[] {
@ -230,7 +222,7 @@ export const useProjectStore = defineStore('project', () => {
setProjects,
removeProjectById,
toggleProjectFavorite,
loadAllProjects,
loadProjects,
createProject,
updateProject,
deleteProject,

View File

@ -473,7 +473,7 @@ export const useTaskStore = defineStore('task', () => {
task = await taskService.update(task)
// reloading the projects list so that the Favorites project shows up or is hidden when there are (or are not) favorite tasks
await projectStore.loadAllProjects()
await projectStore.loadProjects()
return task
}

View File

@ -4,5 +4,4 @@ export interface IProvider {
authUrl: string;
clientId: string;
logoutUrl: string;
scope: string;
}

View File

@ -27,7 +27,6 @@
:loading="migrationService.loading"
:disabled="migrationService.loading || undefined"
:href="authUrl"
:open-external-in-new-tab="false"
>
{{ $t('migrate.getStarted') }}
</x-button>
@ -213,7 +212,7 @@ async function migrate() {
const result = await migrationFileService.migrate(migrationConfig as File)
message.value = result.message
const projectStore = useProjectStore()
return projectStore.loadAllProjects()
return projectStore.loadProjects()
}
await migrationService.migrate(migrationConfig as MigrationConfig)

View File

@ -4,7 +4,7 @@
:class="{ 'is-loading': teamService.loading }"
>
<card
v-if="userIsAdmin && !team.oidcId"
v-if="userIsAdmin"
class="is-fullwidth"
:title="title"
>
@ -77,7 +77,7 @@
:padding="false"
>
<div
v-if="userIsAdmin && !team.oidcId"
v-if="userIsAdmin"
class="p-4"
>
<div class="field has-addons">

View File

@ -17,13 +17,11 @@
class="teams box"
>
<li
v-for="t in teams"
:key="t.id"
v-for="team in teams"
:key="team.id"
>
<router-link :to="{name: 'teams.edit', params: {id: t.id}}">
<p>
{{ t.name }}
</p>
<router-link :to="{name: 'teams.edit', params: {id: team.id}}">
{{ team.name }}
</router-link>
</li>
</ul>
@ -65,7 +63,7 @@ ul.teams {
li {
list-style: none;
margin: 0;
border-bottom: 1px solid var(--grey-200);
border-bottom: 1px solid $border;
a {
color: var(--text);

View File

@ -286,15 +286,16 @@ function toggleGroupPermissionsFromChild(group: string, checked: boolean) {
:key="group"
class="mb-2"
>
<strong class="is-capitalized">{{ formatPermissionTitle(group) }}</strong><br>
<template
v-if="Object.keys(routes).length >= 1"
v-if="Object.keys(routes).length > 1"
>
<Fancycheckbox
v-model="newTokenPermissionsGroup[group]"
class="mr-2 is-capitalized has-text-weight-bold"
class="mr-2 is-italic"
@update:modelValue="checked => selectPermissionGroup(group, checked)"
>
{{ formatPermissionTitle(group) }}
{{ $t('user.settings.apiTokens.selectAll') }}
</Fancycheckbox>
<br>
</template>
@ -304,7 +305,7 @@ function toggleGroupPermissionsFromChild(group: string, checked: boolean) {
>
<Fancycheckbox
v-model="newTokenPermissions[group][route]"
class="ml-4 mr-2 is-capitalized"
class="mr-2 is-capitalized"
@update:modelValue="checked => toggleGroupPermissionsFromChild(group, checked)"
>
{{ formatPermissionTitle(route) }}

View File

@ -25,6 +25,7 @@ import (
"context"
"crypto/sha256"
"fmt"
"github.com/iancoleman/strcase"
"io"
"os"
"os/exec"
@ -33,8 +34,6 @@ import (
"strings"
"time"
"github.com/iancoleman/strcase"
"github.com/magefile/mage/mg"
"golang.org/x/sync/errgroup"
"gopkg.in/yaml.v3"

View File

@ -55,7 +55,3 @@
team_id: 13
user_id: 10
created: 2018-12-01 15:13:12
-
team_id: 14
user_id: 10
created: 2018-12-01 15:13:12

View File

@ -28,8 +28,4 @@
created_by_id: 7
- id: 13
name: testteam13
created_by_id: 7
- id: 14
name: testteam14
created_by_id: 7
oidc_id: 14
created_by_id: 7

View File

@ -1,43 +0,0 @@
// Vikunja is a to-do list application to facilitate your life.
// Copyright 2018-present Vikunja and contributors. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public Licensee as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public Licensee for more details.
//
// You should have received a copy of the GNU Affero General Public Licensee
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package migration
import (
"src.techknowlogick.com/xormigrate"
"xorm.io/xorm"
)
type teams20230104152903 struct {
OidcID string `xorm:"varchar(250) null" maxLength:"250" json:"oidc_id"`
}
func (teams20230104152903) TableName() string {
return "teams"
}
func init() {
migrations = append(migrations, &xormigrate.Migration{
ID: "20230104152903",
Description: "Adding OidcID to teams",
Migrate: func(tx *xorm.Engine) error {
return tx.Sync2(teams20230104152903{})
},
Rollback: func(tx *xorm.Engine) error {
return nil
},
})
}

View File

@ -1059,6 +1059,7 @@ func (err ErrTeamNameCannotBeEmpty) HTTPError() web.HTTPError {
return web.HTTPError{HTTPCode: http.StatusBadRequest, Code: ErrCodeTeamNameCannotBeEmpty, Message: "The team name cannot be empty"}
}
// ErrTeamDoesNotExist represents an error where a team does not exist
type ErrTeamDoesNotExist struct {
TeamID int64
}
@ -1177,54 +1178,6 @@ func (err ErrTeamDoesNotHaveAccessToProject) HTTPError() web.HTTPError {
return web.HTTPError{HTTPCode: http.StatusForbidden, Code: ErrCodeTeamDoesNotHaveAccessToProject, Message: "This team does not have access to the project."}
}
// ErrOIDCTeamDoesNotExist represents an error where a team with specified name and specified oidcId property does not exist
type ErrOIDCTeamDoesNotExist struct {
OidcID string
Name string
}
// IsErrOIDCTeamDoesNotExist checks if an error is ErrOIDCTeamDoesNotExist.
func IsErrOIDCTeamDoesNotExist(err error) bool {
_, ok := err.(ErrOIDCTeamDoesNotExist)
return ok
}
// ErrTeamDoesNotExist represents an error where a team does not exist
func (err ErrOIDCTeamDoesNotExist) Error() string {
return fmt.Sprintf("No team with that name and valid oidcId could be found. [Team Name: %v] [OidcID : %v] ", err.Name, err.OidcID)
}
// ErrCodeTeamDoesNotExist holds the unique world-error code of this error
const ErrCodeOIDCTeamDoesNotExist = 6008
// HTTPError holds the http error description
func (err ErrOIDCTeamDoesNotExist) HTTPError() web.HTTPError {
return web.HTTPError{HTTPCode: http.StatusNotFound, Code: ErrCodeTeamDoesNotExist, Message: "No team with that name and valid oidcId could be found."}
}
// ErrOIDCTeamsDoNotExistForUser represents an error where an oidcTeam does not exist for the user
type ErrOIDCTeamsDoNotExistForUser struct {
UserID int64
}
// IsErrOIDCTeamsDoNotExistForUser checks if an error is ErrOIDCTeamsDoNotExistForUser.
func IsErrOIDCTeamsDoNotExistForUser(err error) bool {
_, ok := err.(ErrOIDCTeamsDoNotExistForUser)
return ok
}
func (err ErrOIDCTeamsDoNotExistForUser) Error() string {
return fmt.Sprintf("No teams with property oidcId could be found for user [User ID: %d]", err.UserID)
}
// ErrCodeTeamDoesNotExist holds the unique world-error code of this error
const ErrCodeOIDCTeamsDoNotExistForUser = 6009
// HTTPError holds the http error description
func (err ErrOIDCTeamsDoNotExistForUser) HTTPError() web.HTTPError {
return web.HTTPError{HTTPCode: http.StatusNotFound, Code: ErrCodeTeamDoesNotExist, Message: "No Teams with property oidcId could be found for User."}
}
// ====================
// User <-> Project errors
// ====================

View File

@ -316,8 +316,8 @@ func GetProjectSimplByTaskID(s *xorm.Session, taskID int64) (l *Project, err err
return &project, nil
}
// GetProjectsMapSimplByTaskIDs gets a list of projects by a task ids
func GetProjectsMapSimplByTaskIDs(s *xorm.Session, taskIDs []int64) (ps map[int64]*Project, err error) {
// GetProjectsSimplByTaskIDs gets a list of projects by a task ids
func GetProjectsSimplByTaskIDs(s *xorm.Session, taskIDs []int64) (ps map[int64]*Project, err error) {
ps = make(map[int64]*Project)
err = s.
Select("projects.*").
@ -328,18 +328,8 @@ func GetProjectsMapSimplByTaskIDs(s *xorm.Session, taskIDs []int64) (ps map[int6
return
}
func GetProjectsSimplByTaskIDs(s *xorm.Session, taskIDs []int64) (ps []*Project, err error) {
err = s.
Select("projects.*").
Table(Project{}).
Join("INNER", "tasks", "projects.id = tasks.project_id").
In("tasks.id", taskIDs).
Find(&ps)
return
}
// GetProjectsMapByIDs returns a map of projects from a slice with project ids
func GetProjectsMapByIDs(s *xorm.Session, projectIDs []int64) (projects map[int64]*Project, err error) {
// GetProjectsByIDs returns a map of projects from a slice with project ids
func GetProjectsByIDs(s *xorm.Session, projectIDs []int64) (projects map[int64]*Project, err error) {
projects = make(map[int64]*Project, len(projectIDs))
if len(projectIDs) == 0 {
@ -350,17 +340,6 @@ func GetProjectsMapByIDs(s *xorm.Session, projectIDs []int64) (projects map[int6
return
}
func GetProjectsByIDs(s *xorm.Session, projectIDs []int64) (projects []*Project, err error) {
projects = make([]*Project, 0, len(projectIDs))
if len(projectIDs) == 0 {
return
}
err = s.In("id", projectIDs).Find(&projects)
return
}
type projectOptions struct {
search string
user *user.User
@ -476,7 +455,7 @@ SELECT DISTINCT * FROM all_projects ORDER BY position `+limitSQL, args...).Find(
totalCount, err = s.
SQL(`WITH RECURSIVE all_projects as (`+baseQuery+`)
SELECT COUNT(DISTINCT all_projects.id) FROM all_projects`, args...).
SELECT count(*) FROM all_projects GROUP BY all_projects.id`, args...).
Count(&Project{})
if err != nil {
return nil, 0, err
@ -580,7 +559,7 @@ func addProjectDetails(s *xorm.Session, projects []*Project, a web.Auth) (err er
return err
}
subscriptions, err := GetSubscriptionsForProjects(s, projects, a)
subscriptions, err := GetSubscriptions(s, SubscriptionEntityProject, projectIDs, a)
if err != nil {
log.Errorf("An error occurred while getting project subscriptions for a project: %s", err.Error())
subscriptions = make(map[int64][]*Subscription)

View File

@ -223,11 +223,7 @@ func GetSubscriptions(s *xorm.Session, entityType SubscriptionEntityType, entity
switch entityType {
case SubscriptionEntityProject:
projects, err := GetProjectsByIDs(s, entityIDs)
if err != nil {
return nil, err
}
return GetSubscriptionsForProjects(s, projects, u)
return getSubscriptionsForProjects(s, entityIDs, u)
case SubscriptionEntityTask:
subs, err := getSubscriptionsForTasks(s, entityIDs, u)
if err != nil {
@ -236,34 +232,22 @@ func GetSubscriptions(s *xorm.Session, entityType SubscriptionEntityType, entity
// If the task does not have a subscription directly or from its project, get the one
// from the parent and return it instead.
var taskIDsWithoutSubscription []int64
for _, eID := range entityIDs {
if _, has := subs[eID]; has {
continue
}
taskIDsWithoutSubscription = append(taskIDsWithoutSubscription, eID)
}
projects, err := GetProjectsSimplByTaskIDs(s, taskIDsWithoutSubscription)
if err != nil {
return nil, err
}
tasks, err := GetTasksSimpleByIDs(s, taskIDsWithoutSubscription)
if err != nil {
return nil, err
}
projectSubscriptions, err := GetSubscriptionsForProjects(s, projects, u)
if err != nil {
return nil, err
}
for _, task := range tasks {
sub, has := projectSubscriptions[task.ProjectID]
if has {
subs[task.ID] = sub
task, err := GetTaskByIDSimple(s, eID)
if err != nil {
return nil, err
}
projectSubscriptions, err := getSubscriptionsForProjects(s, []int64{task.ProjectID}, u)
if err != nil {
return nil, err
}
for _, subscription := range projectSubscriptions {
subs[eID] = subscription // The first project subscription is the subscription we're looking for
break
}
}
@ -273,59 +257,48 @@ func GetSubscriptions(s *xorm.Session, entityType SubscriptionEntityType, entity
return
}
func GetSubscriptionsForProjects(s *xorm.Session, projects []*Project, a web.Auth) (projectsToSubscriptions map[int64][]*Subscription, err error) {
u, is := a.(*user.User)
if u != nil && !is {
return
}
func getSubscriptionsForProjects(s *xorm.Session, projectIDs []int64, u *user.User) (projectsToSubscriptions map[int64][]*Subscription, err error) {
origEntityIDs := projectIDs
var ps = make(map[int64]*Project)
origProjectIDs := make([]int64, 0, len(projects))
allProjectIDs := make([]int64, 0, len(projects))
for _, p := range projects {
ps[p.ID] = p
origProjectIDs = append(origProjectIDs, p.ID)
allProjectIDs = append(allProjectIDs, p.ID)
}
// We can't just use the projects we have, we need to fetch the parents
// because they may not be loaded in the same object
for _, p := range projects {
if p.ParentProjectID == 0 {
for _, eID := range projectIDs {
if eID < 1 {
continue
}
if _, has := ps[p.ParentProjectID]; has {
ps[eID], err = GetProjectSimpleByID(s, eID)
if err != nil && IsErrProjectDoesNotExist(err) {
// If the project does not exist, it might got deleted. There could still be subscribers though.
delete(ps, eID)
continue
}
err = ps[p.ID].GetAllParentProjects(s)
if err != nil {
return nil, err
}
err = ps[eID].GetAllParentProjects(s)
if err != nil {
return nil, err
}
parentIDs := []int64{}
var parent = ps[p.ID].ParentProject
var parent = ps[eID].ParentProject
for parent != nil {
parentIDs = append(parentIDs, parent.ID)
parent = parent.ParentProject
}
// Now we have all parent ids
allProjectIDs = append(allProjectIDs, parentIDs...) // the child project id is already in there
projectIDs = append(projectIDs, parentIDs...) // the child project id is already in there
}
var subscriptions []*Subscription
if u != nil {
err = s.
Where("user_id = ?", u.ID).
And(getSubscriberCondForEntities(SubscriptionEntityProject, allProjectIDs)).
And(getSubscriberCondForEntities(SubscriptionEntityProject, projectIDs)).
Find(&subscriptions)
} else {
err = s.
And(getSubscriberCondForEntities(SubscriptionEntityProject, allProjectIDs)).
And(getSubscriberCondForEntities(SubscriptionEntityProject, projectIDs)).
Find(&subscriptions)
}
if err != nil {
@ -340,7 +313,7 @@ func GetSubscriptionsForProjects(s *xorm.Session, projects []*Project, a web.Aut
// Rearrange so that subscriptions trickle down
for _, eID := range origProjectIDs {
for _, eID := range origEntityIDs {
// If the current project does not have a subscription, climb up the tree until a project has one,
// then use that subscription for all child projects
_, has := projectsToSubscriptions[eID]

View File

@ -139,7 +139,7 @@ func RegisterOverdueReminderCron() {
}
}
projects, err := GetProjectsMapSimplByTaskIDs(s, taskIDs)
projects, err := GetProjectsSimplByTaskIDs(s, taskIDs)
if err != nil {
log.Errorf("[Undone Overdue Tasks Reminder] Could not get projects for tasks: %s", err)
return

View File

@ -173,7 +173,7 @@ func getTasksWithRemindersDueAndTheirUsers(s *xorm.Session, now time.Time) (remi
seen := make(map[int64]map[int64]bool)
projects, err := GetProjectsMapSimplByTaskIDs(s, taskIDs)
projects, err := GetProjectsSimplByTaskIDs(s, taskIDs)
if err != nil {
return
}

View File

@ -356,11 +356,6 @@ func GetTaskSimple(s *xorm.Session, t *Task) (task Task, err error) {
return
}
func GetTasksSimpleByIDs(s *xorm.Session, ids []int64) (tasks []*Task, err error) {
err = s.In("id", ids).Find(&tasks)
return
}
// GetTasksByIDs returns all tasks for a project of ids
func (bt *BulkTask) GetTasksByIDs(s *xorm.Session) (err error) {
for _, id := range bt.IDs {
@ -591,7 +586,7 @@ func addMoreInfoToTasks(s *xorm.Session, taskMap map[int64]*Task, a web.Auth) (e
}
// Get all identifiers
projects, err := GetProjectsMapByIDs(s, projectIDs)
projects, err := GetProjectsByIDs(s, projectIDs)
if err != nil {
return err
}

View File

@ -44,6 +44,7 @@ func (tm *TeamMember) Create(s *xorm.Session, a web.Auth) (err error) {
if err != nil {
return err
}
// Check if the user exists
member, err := user2.GetUserByUsername(s, tm.Username)
if err != nil {
@ -108,12 +109,6 @@ func (tm *TeamMember) Delete(s *xorm.Session, _ web.Auth) (err error) {
return
}
func (tm *TeamMember) MembershipExists(s *xorm.Session) (exists bool, err error) {
return s.
Where("team_id = ? AND user_id = ?", tm.TeamID, tm.UserID).
Exist(&TeamMember{})
}
// Update toggles a team member's admin status
// @Summary Toggle a team member's admin status
// @Description If a user is team admin, this will make them member and vise-versa.

View File

@ -38,8 +38,6 @@ type Team struct {
// The team's description.
Description string `xorm:"longtext null" json:"description"`
CreatedByID int64 `xorm:"bigint not null INDEX" json:"-"`
// The team's oidc id delivered by the oidc provider
OidcID string `xorm:"varchar(250) null" maxLength:"250" json:"oidc_id"`
// The user who created this team.
CreatedBy *user.User `xorm:"-" json:"created_by"`
@ -88,18 +86,11 @@ func (*TeamMember) TableName() string {
// TeamUser is the team member type
type TeamUser struct {
user.User `xorm:"extends"`
// Whether the member is an admin of the team. See the docs for more about what a team admin can do
// Whether or not the member is an admin of the team. See the docs for more about what a team admin can do
Admin bool `json:"admin"`
TeamID int64 `json:"-"`
}
// OIDCTeam is the relevant data for a team and is delivered by oidc token
type OIDCTeam struct {
Name string
OidcID string
Description string
}
// GetTeamByID gets a team by its ID
func GetTeamByID(s *xorm.Session, id int64) (team *Team, err error) {
if id < 1 {
@ -129,34 +120,6 @@ func GetTeamByID(s *xorm.Session, id int64) (team *Team, err error) {
return
}
// GetTeamByOidcIDAndName gets teams where oidc_id and name match parameters
// For oidc team creation oidcID and Name need to be set
func GetTeamByOidcIDAndName(s *xorm.Session, oidcID string, teamName string) (*Team, error) {
team := &Team{}
has, err := s.
Table("teams").
Where("oidc_id = ? AND name = ?", oidcID, teamName).
Get(team)
if !has || err != nil {
return nil, ErrOIDCTeamDoesNotExist{teamName, oidcID}
}
return team, nil
}
func FindAllOidcTeamIDsForUser(s *xorm.Session, userID int64) (ts []int64, err error) {
err = s.
Table("team_members").
Where("user_id = ? ", userID).
Join("RIGHT", "teams", "teams.id = team_members.team_id").
Where("teams.oidc_id != ? AND teams.oidc_id IS NOT NULL", "").
Cols("teams.id").
Find(&ts)
if ts == nil || err != nil {
return ts, err
}
return ts, nil
}
func addMoreInfoToTeams(s *xorm.Session, teams []*Team) (err error) {
if len(teams) == 0 {
@ -307,6 +270,7 @@ func (t *Team) Create(s *xorm.Session, a web.Auth) (err error) {
return
}
// Insert the current user as member and admin
tm := TeamMember{TeamID: t.ID, Username: doer.Username, Admin: true}
if err = tm.Create(s, doer); err != nil {
return err

View File

@ -21,22 +21,21 @@ import (
"encoding/json"
"errors"
"net/http"
"strconv"
"strings"
"code.vikunja.io/web/handler"
"code.vikunja.io/api/pkg/db"
"xorm.io/xorm"
"code.vikunja.io/api/pkg/log"
"code.vikunja.io/api/pkg/models"
"code.vikunja.io/api/pkg/modules/auth"
"code.vikunja.io/api/pkg/user"
"code.vikunja.io/api/pkg/utils"
"github.com/coreos/go-oidc/v3/oidc"
petname "github.com/dustinkirkland/golang-petname"
"github.com/labstack/echo/v4"
"golang.org/x/oauth2"
"xorm.io/xorm"
)
// Callback contains the callback after an auth request was made and redirected
@ -54,17 +53,16 @@ type Provider struct {
AuthURL string `json:"auth_url"`
LogoutURL string `json:"logout_url"`
ClientID string `json:"client_id"`
Scope string `json:"scope"`
ClientSecret string `json:"-"`
openIDProvider *oidc.Provider
Oauth2Config *oauth2.Config `json:"-"`
}
type claims struct {
Email string `json:"email"`
Name string `json:"name"`
PreferredUsername string `json:"preferred_username"`
Nickname string `json:"nickname"`
VikunjaGroups []map[string]interface{} `json:"vikunja_groups"`
Email string `json:"email"`
Name string `json:"name"`
PreferredUsername string `json:"preferred_username"`
Nickname string `json:"nickname"`
}
func init() {
@ -98,7 +96,6 @@ func HandleCallback(c echo.Context) error {
// Check if the provider exists
providerKey := c.Param("provider")
provider, err := GetProvider(providerKey)
log.Debugf("Provider: %v", provider)
if err != nil {
log.Error(err)
return handler.HandleHTTPError(err, c)
@ -148,7 +145,6 @@ func HandleCallback(c echo.Context) error {
// Extract custom claims
cl := &claims{}
err = idToken.Claims(cl)
if err != nil {
log.Errorf("Error getting token claims for provider %s: %v", provider.Name, err)
@ -202,182 +198,16 @@ func HandleCallback(c echo.Context) error {
return handler.HandleHTTPError(err, c)
}
// does the oidc token contain well formed "vikunja_groups" through vikunja_scope
log.Debugf("Checking for vikunja_groups in token %v", cl.VikunjaGroups)
teamData, errs := getTeamDataFromToken(cl.VikunjaGroups, provider)
if len(teamData) > 0 {
for _, err := range errs {
log.Errorf("Error creating teams for user and vikunja groups %s: %v", cl.VikunjaGroups, err)
}
// find old teams for user through oidc
oldOidcTeams, err := models.FindAllOidcTeamIDsForUser(s, u.ID)
if err != nil {
log.Debugf("No oidc teams found for user %v", err)
}
oidcTeams, err := AssignOrCreateUserToTeams(s, u, teamData)
if err != nil {
log.Errorf("Could not proceed with group routine %v", err)
}
teamIDsToLeave := utils.NotIn(oldOidcTeams, oidcTeams)
err = RemoveUserFromTeamsByIds(s, u, teamIDsToLeave)
if err != nil {
log.Errorf("Found error while leaving teams %v", err)
}
errs := RemoveEmptySSOTeams(s, teamIDsToLeave)
if len(errs) > 0 {
for _, err := range errs {
log.Errorf("Found error while removing empty teams %v", err)
}
}
}
err = s.Commit()
if err != nil {
_ = s.Rollback()
log.Errorf("Error creating new team for provider %s: %v", provider.Name, err)
return handler.HandleHTTPError(err, c)
}
// Create token
return auth.NewUserAuthTokenResponse(u, c, false)
}
func AssignOrCreateUserToTeams(s *xorm.Session, u *user.User, teamData []*models.OIDCTeam) (oidcTeams []int64, err error) {
if len(teamData) == 0 {
return
}
// check if we have seen these teams before.
// find or create Teams and assign user as teammember.
teams, err := GetOrCreateTeamsByOIDCAndNames(s, teamData, u)
if err != nil {
log.Errorf("Error verifying team for %v, got %v. Error: %v", u.Name, teams, err)
return nil, err
}
for _, team := range teams {
tm := models.TeamMember{TeamID: team.ID, UserID: u.ID, Username: u.Username}
exists, _ := tm.MembershipExists(s)
if !exists {
err = tm.Create(s, u)
if err != nil {
log.Errorf("Could not assign user %s to team %s: %v", u.Username, team.Name, err)
}
}
oidcTeams = append(oidcTeams, team.ID)
}
return oidcTeams, err
}
func RemoveEmptySSOTeams(s *xorm.Session, teamIDs []int64) (errs []error) {
for _, teamID := range teamIDs {
count, err := s.Where("team_id = ?", teamID).Count(&models.TeamMember{})
if count == 0 && err == nil {
log.Debugf("SSO team with id %v has no members. It will be deleted", teamID)
_, _err := s.Where("id = ?", teamID).Delete(&models.Team{})
if _err != nil {
errs = append(errs, _err)
}
}
}
return errs
}
func RemoveUserFromTeamsByIds(s *xorm.Session, u *user.User, teamIDs []int64) (err error) {
if len(teamIDs) < 1 {
return nil
}
log.Debugf("Removing team_member with user_id %v from team_ids %v", u.ID, teamIDs)
_, err = s.In("team_id", teamIDs).And("user_id = ?", u.ID).Delete(&models.TeamMember{})
return err
}
func getTeamDataFromToken(groups []map[string]interface{}, provider *Provider) (teamData []*models.OIDCTeam, errs []error) {
teamData = []*models.OIDCTeam{}
errs = []error{}
for _, team := range groups {
var name string
var description string
var oidcID string
_, exists := team["name"]
if exists {
name = team["name"].(string)
}
_, exists = team["description"]
if exists {
description = team["description"].(string)
}
_, exists = team["oidcID"]
if exists {
switch t := team["oidcID"].(type) {
case string:
oidcID = team["oidcID"].(string)
case int64:
oidcID = strconv.FormatInt(team["oidcID"].(int64), 10)
case float64:
oidcID = strconv.FormatFloat(team["oidcID"].(float64), 'f', -1, 64)
default:
log.Errorf("No oidcID assigned for %v or type %v not supported", team, t)
}
}
if name == "" || oidcID == "" {
log.Errorf("Claim of your custom scope does not hold name or oidcID for automatic group assignment through oidc provider. Please check %s", provider.Name)
errs = append(errs, &user.ErrOpenIDCustomScopeMalformed{})
continue
}
teamData = append(teamData, &models.OIDCTeam{Name: name, OidcID: oidcID, Description: description})
}
return teamData, errs
}
func getOIDCTeamName(name string) string {
return name + " (OIDC)"
}
func CreateOIDCTeam(s *xorm.Session, teamData *models.OIDCTeam, u *user.User) (team *models.Team, err error) {
team = &models.Team{
Name: getOIDCTeamName(teamData.Name),
Description: teamData.Description,
OidcID: teamData.OidcID,
}
err = team.Create(s, u)
return team, err
}
// GetOrCreateTeamsByOIDCAndNames returns a slice of teams which were generated from the oidc data. If a team did not exist previously it is automatically created.
func GetOrCreateTeamsByOIDCAndNames(s *xorm.Session, teamData []*models.OIDCTeam, u *user.User) (te []*models.Team, err error) {
te = []*models.Team{}
// Procedure can only be successful if oidcID is set
for _, oidcTeam := range teamData {
team, err := models.GetTeamByOidcIDAndName(s, oidcTeam.OidcID, oidcTeam.Name)
if err != nil && !models.IsErrOIDCTeamDoesNotExist(err) {
return nil, err
}
if err != nil && models.IsErrOIDCTeamDoesNotExist(err) {
log.Debugf("Team with oidc_id %v and name %v does not exist. Creating team… ", oidcTeam.OidcID, oidcTeam.Name)
newTeam, err := CreateOIDCTeam(s, oidcTeam, u)
if err != nil {
return te, err
}
te = append(te, newTeam)
continue
}
if team.Name != getOIDCTeamName(oidcTeam.Name) {
team.Name = getOIDCTeamName(oidcTeam.Name)
err = team.Update(s, u)
if err != nil {
return nil, err
}
}
log.Debugf("Team with oidc_id %v and name %v already exists.", team.OidcID, team.Name)
te = append(te, team)
}
return te, err
}
func getOrCreateUser(s *xorm.Session, cl *claims, issuer, subject string) (u *user.User, err error) {
// Check if the user exists for that issuer and subject
u, err = user.GetUserWithEmail(s, &user.User{
Issuer: issuer,

View File

@ -20,9 +20,7 @@ import (
"testing"
"code.vikunja.io/api/pkg/db"
"code.vikunja.io/api/pkg/models"
"code.vikunja.io/api/pkg/user"
"code.vikunja.io/api/pkg/utils"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@ -97,145 +95,4 @@ func TestGetOrCreateUser(t *testing.T) {
"email": cl.Email,
}, false)
})
t.Run("existing user, non existing team", func(t *testing.T) {
db.LoadAndAssertFixtures(t)
s := db.NewSession()
defer s.Close()
team := "new sso team"
oidcID := "47404"
cl := &claims{
Email: "other-email-address@some.service.com",
VikunjaGroups: []map[string]interface{}{
{"name": team, "oidcID": oidcID},
},
}
u, err := getOrCreateUser(s, cl, "https://some.service.com", "12345")
require.NoError(t, err)
teamData, errs := getTeamDataFromToken(cl.VikunjaGroups, nil)
for _, err := range errs {
require.NoError(t, err)
}
require.NoError(t, err)
oidcTeams, err := AssignOrCreateUserToTeams(s, u, teamData)
require.NoError(t, err)
err = s.Commit()
require.NoError(t, err)
db.AssertExists(t, "users", map[string]interface{}{
"id": u.ID,
"email": cl.Email,
}, false)
db.AssertExists(t, "teams", map[string]interface{}{
"id": oidcTeams,
"name": team + " (OIDC)",
}, false)
})
t.Run("existing user, assign to existing team", func(t *testing.T) {
db.LoadAndAssertFixtures(t)
s := db.NewSession()
defer s.Close()
team := "testteam14"
oidcID := "14"
cl := &claims{
Email: "other-email-address@some.service.com",
VikunjaGroups: []map[string]interface{}{
{"name": team, "oidcID": oidcID},
},
}
u := &user.User{ID: 10}
teamData, errs := getTeamDataFromToken(cl.VikunjaGroups, nil)
for _, err := range errs {
require.NoError(t, err)
}
oidcTeams, err := AssignOrCreateUserToTeams(s, u, teamData)
require.NoError(t, err)
err = s.Commit()
require.NoError(t, err)
db.AssertExists(t, "team_members", map[string]interface{}{
"team_id": oidcTeams,
"user_id": u.ID,
}, false)
})
t.Run("existing user, remove from existing team", func(t *testing.T) {
db.LoadAndAssertFixtures(t)
s := db.NewSession()
defer s.Close()
cl := &claims{
Email: "other-email-address@some.service.com",
VikunjaGroups: []map[string]interface{}{},
}
u := &user.User{ID: 10}
teamData, errs := getTeamDataFromToken(cl.VikunjaGroups, nil)
if len(errs) > 0 {
for _, err := range errs {
require.NoError(t, err)
}
}
oldOidcTeams, err := models.FindAllOidcTeamIDsForUser(s, u.ID)
require.NoError(t, err)
oidcTeams, err := AssignOrCreateUserToTeams(s, u, teamData)
require.NoError(t, err)
teamIDsToLeave := utils.NotIn(oldOidcTeams, oidcTeams)
require.NoError(t, err)
err = RemoveUserFromTeamsByIds(s, u, teamIDsToLeave)
require.NoError(t, err)
errs = RemoveEmptySSOTeams(s, teamIDsToLeave)
for _, err = range errs {
require.NoError(t, err)
}
errs = RemoveEmptySSOTeams(s, teamIDsToLeave)
for _, err = range errs {
require.NoError(t, err)
}
err = s.Commit()
require.NoError(t, err)
db.AssertMissing(t, "team_members", map[string]interface{}{
"team_id": oidcTeams,
"user_id": u.ID,
})
})
t.Run("existing user, remove from existing team and delete team", func(t *testing.T) {
db.LoadAndAssertFixtures(t)
s := db.NewSession()
defer s.Close()
cl := &claims{
Email: "other-email-address@some.service.com",
VikunjaGroups: []map[string]interface{}{},
}
u := &user.User{ID: 10}
teamData, errs := getTeamDataFromToken(cl.VikunjaGroups, nil)
if len(errs) > 0 {
for _, err := range errs {
require.NoError(t, err)
}
}
oldOidcTeams, err := models.FindAllOidcTeamIDsForUser(s, u.ID)
require.NoError(t, err)
oidcTeams, err := AssignOrCreateUserToTeams(s, u, teamData)
require.NoError(t, err)
teamIDsToLeave := utils.NotIn(oldOidcTeams, oidcTeams)
require.NoError(t, err)
err = RemoveUserFromTeamsByIds(s, u, teamIDsToLeave)
require.NoError(t, err)
errs = RemoveEmptySSOTeams(s, teamIDsToLeave)
for _, err := range errs {
require.NoError(t, err)
}
err = s.Commit()
require.NoError(t, err)
db.AssertMissing(t, "teams", map[string]interface{}{
"id": oidcTeams,
})
})
}

View File

@ -125,10 +125,6 @@ func getProviderFromMap(pi map[string]interface{}) (provider *Provider, err erro
logoutURL = ""
}
scope, _ := pi["scope"].(string)
if scope == "" {
scope = "openid profile email"
}
provider = &Provider{
Name: pi["name"].(string),
Key: k,
@ -136,7 +132,6 @@ func getProviderFromMap(pi map[string]interface{}) (provider *Provider, err erro
OriginalAuthURL: pi["authurl"].(string),
ClientSecret: pi["clientsecret"].(string),
LogoutURL: logoutURL,
Scope: scope,
}
cl, is := pi["clientid"].(int)

View File

@ -8300,11 +8300,6 @@ const docTemplate = `{
"maxLength": 250,
"minLength": 1
},
"oidc_id": {
"description": "The team's oidc id delivered by the oidc provider",
"type": "string",
"maxLength": 250
},
"updated": {
"description": "A timestamp when this relation was last updated. You cannot change this value.",
"type": "string"
@ -8367,7 +8362,7 @@ const docTemplate = `{
"type": "object",
"properties": {
"admin": {
"description": "Whether the member is an admin of the team. See the docs for more about what a team admin can do",
"description": "Whether or not the member is an admin of the team. See the docs for more about what a team admin can do",
"type": "boolean"
},
"created": {
@ -8435,11 +8430,6 @@ const docTemplate = `{
"maxLength": 250,
"minLength": 1
},
"oidc_id": {
"description": "The team's oidc id delivered by the oidc provider",
"type": "string",
"maxLength": 250
},
"right": {
"$ref": "#/definitions/models.Right"
},
@ -8583,9 +8573,6 @@ const docTemplate = `{
},
"name": {
"type": "string"
},
"scope": {
"type": "string"
}
}
},

View File

@ -8292,11 +8292,6 @@
"maxLength": 250,
"minLength": 1
},
"oidc_id": {
"description": "The team's oidc id delivered by the oidc provider",
"type": "string",
"maxLength": 250
},
"updated": {
"description": "A timestamp when this relation was last updated. You cannot change this value.",
"type": "string"
@ -8359,7 +8354,7 @@
"type": "object",
"properties": {
"admin": {
"description": "Whether the member is an admin of the team. See the docs for more about what a team admin can do",
"description": "Whether or not the member is an admin of the team. See the docs for more about what a team admin can do",
"type": "boolean"
},
"created": {
@ -8427,11 +8422,6 @@
"maxLength": 250,
"minLength": 1
},
"oidc_id": {
"description": "The team's oidc id delivered by the oidc provider",
"type": "string",
"maxLength": 250
},
"right": {
"$ref": "#/definitions/models.Right"
},
@ -8575,9 +8565,6 @@
},
"name": {
"type": "string"
},
"scope": {
"type": "string"
}
}
},

View File

@ -904,10 +904,6 @@ definitions:
maxLength: 250
minLength: 1
type: string
oidc_id:
description: The team's oidc id delivered by the oidc provider
maxLength: 250
type: string
updated:
description: A timestamp when this relation was last updated. You cannot change
this value.
@ -958,8 +954,8 @@ definitions:
models.TeamUser:
properties:
admin:
description: Whether the member is an admin of the team. See the docs for
more about what a team admin can do
description: Whether or not the member is an admin of the team. See the docs
for more about what a team admin can do
type: boolean
created:
description: A timestamp when this task was created. You cannot change this
@ -1011,10 +1007,6 @@ definitions:
maxLength: 250
minLength: 1
type: string
oidc_id:
description: The team's oidc id delivered by the oidc provider
maxLength: 250
type: string
right:
$ref: '#/definitions/models.Right'
updated:
@ -1124,8 +1116,6 @@ definitions:
type: string
name:
type: string
scope:
type: string
type: object
todoist.Migration:
properties:

View File

@ -426,32 +426,6 @@ func (err *ErrNoOpenIDEmailProvided) HTTPError() web.HTTPError {
}
}
// ErrNoOpenIDEmailProvided represents a "NoEmailProvided" kind of error.
type ErrOpenIDCustomScopeMalformed struct {
}
// IsErrNoEmailProvided checks if an error is a ErrNoOpenIDEmailProvided.
func IsErrOpenIDCustomScopeMalformed(err error) bool {
_, ok := err.(*ErrOpenIDCustomScopeMalformed)
return ok
}
func (err *ErrOpenIDCustomScopeMalformed) Error() string {
return "Custom Scope malformed"
}
// ErrCodeNoOpenIDEmailProvided holds the unique world-error code of this error
const ErrCodeOpenIDCustomScopeMalformed = 1022
// HTTPError holds the http error description
func (err *ErrOpenIDCustomScopeMalformed) HTTPError() web.HTTPError {
return web.HTTPError{
HTTPCode: http.StatusPreconditionFailed,
Code: ErrCodeOpenIDCustomScopeMalformed,
Message: "The custom scope set by the OIDC provider is malformed. Please make sure the openid provider sets the data correctly for your scope. Check especially to have set an oidcID",
}
}
// ErrAccountDisabled represents a "AccountDisabled" kind of error.
type ErrAccountDisabled struct {
UserID int64

View File

@ -1,37 +0,0 @@
// Vikunja is a to-do list application to facilitate your life.
// Copyright 2018-present Vikunja and contributors. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public Licensee as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public Licensee for more details.
//
// You should have received a copy of the GNU Affero General Public Licensee
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package utils
// find the elements which appear in slice1, but not in slice2
func NotIn(slice1 []int64, slice2 []int64) []int64 {
var diff []int64
for _, s1 := range slice1 {
found := false
for _, s2 := range slice2 {
if s1 == s2 {
found = true
break
}
}
// int64 not found. We add it to return slice
if !found {
diff = append(diff, s1)
}
}
return diff
}