Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

implemented review feedback from @ulferts

Jonas Jabari71ab22939266
diff --git a/app/contracts/queries/ical_sharing_contract.rb b/app/contracts/queries/ical_sharing_contract.rb
new file mode 100644
index 00000000000..35d76b01a41
--- /dev/null
+++ b/app/contracts/queries/ical_sharing_contract.rb
@@ -0,0 +1,62 @@
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2023 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# 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 General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See COPYRIGHT and LICENSE files for more details.
+#++
+
+module Queries
+ class ICalSharingContract < ::BaseContract
+ validate :user_allowed_to_subscribe_to_query_via_ical
+
+ protected
+
+ def user_allowed_to_subscribe_to_query_via_ical
+ return if user_allowed_to_use_ical_sharing? && query_visible_for_user? && token_valid_for_query?
+
+ errors.add :base, :error_unauthorized
+ end
+
+ def user_allowed_to_use_ical_sharing?
+ QueryPolicy.new(user).allowed?(model, :share_via_ical)
+ end
+
+ def query_visible_for_user?
+ begin
+ User.execute_as(user) do
+ Query
+ .visible(user)
+ .find(model.id)
+ .present?
+ end
+ rescue
+ false
+ end
+ end
+
+ def token_valid_for_query?
+ options[:ical_token].query.id == model.id
+ end
+ end
+end
diff --git a/app/models/query.rb b/app/models/query.rb
index 0879f703c29..d8c0406b113 100644
--- a/app/models/query.rb
+++ b/app/models/query.rb
@@ -37,11 +37,17 @@ class Query < ApplicationRecord
belongs_to :user
has_many :views,
dependent: :destroy
+ has_many :ical_token_query_assignments
+ has_many :ical_tokens,
+ through: :ical_token_query_assignments,
+ class_name: 'Token::ICal'
serialize :filters, Queries::WorkPackages::FilterSerializer
serialize :column_names, Array
serialize :sort_criteria, Array
+ before_destroy :destroy_ical_tokens
+
validates :name,
presence: true,
length: { maximum: 255 }
@@ -460,4 +466,11 @@ class Query < ApplicationRecord
def valid_timestamps_subset!
self.timestamps &= allowed_timestamps
end
+
+ # dependent::destroy does not work for has_many :through associations
+ def destroy_ical_tokens
+ ical_tokens.each do |token|
+ token.destroy
+ end
+ end
end
diff --git a/app/models/token/ical.rb b/app/models/token/ical.rb
index 13a89ce46ca..91aa47cfb97 100644
--- a/app/models/token/ical.rb
+++ b/app/models/token/ical.rb
@@ -42,7 +42,7 @@ module Token
# not be created due to errors in the ical_token_query_assignment
# otherwise a hashed token value of a not persisted token would be returned
create!(user:, ical_token_query_assignment_attributes: {
- query:, name: token_name, user_id: user.id
+ query:, name: token_name
}).plain_value
end
end
diff --git a/config/locales/js-en.yml b/config/locales/js-en.yml
index d8d4948df2e..d518018604e 100644
--- a/config/locales/js-en.yml
+++ b/config/locales/js-en.yml
@@ -358,17 +358,16 @@ en:
ical_sharing_modal:
title: "Subscribe to iCalendar"
- inital_setup_error_message: "An error occured while fetching data"
- inital_setup_error_message: "An error occured while fetching data"
+ inital_setup_error_message: "An error occured while fetching data."
description: "You can use the iCalendar URL to import or subscribe to this calendar in an external client and view up-to-date work package information from there."
warning: "Please don't share this URL with external users. Anyone with this link will be able to view work package details without an account or password."
token_name_label: "Name"
token_name_placeholder: "Type iCalendar name"
token_name_description_text: "This name will be used to distinguish it form other tokens in the <a href=\"my/access_token\", target=\"_blank\">access tokens list</a>. It can only be used once per calendar."
copy_url_label: "Copy URL"
- ical_generation_error_text: "An error occured while generating the iCal URL"
- copy_url_success_text: "URL copied to clipboard"
- copy_url_error_text: "Due to browser errors, the URL couldn't be copied to clipboard. Please copy it manually:"
+ ical_generation_error_text: "An error occured while generating the iCal URL."
+ copy_url_success_text: "URL copied to clipboard."
+ copy_url_error_text: "Due to browser errors, the URL couldn't be copied to the clipboard. Please copy it manually: %{icalUrl}"
label_activate: "Activate"
label_assignee: 'Assignee'
diff --git a/frontend/src/app/features/calendar/openproject-calendar.module.ts b/frontend/src/app/features/calendar/openproject-calendar.module.ts
index d835d04ff5a..d358fa50bd9 100644
--- a/frontend/src/app/features/calendar/openproject-calendar.module.ts
+++ b/frontend/src/app/features/calendar/openproject-calendar.module.ts
@@ -28,6 +28,7 @@
import { OpSharedModule } from 'core-app/shared/shared.module';
import { NgModule } from '@angular/core';
+import { ReactiveFormsModule } from '@angular/forms';
import { FullCalendarModule } from '@fullcalendar/angular';
import { WorkPackagesCalendarComponent } from 'core-app/features/calendar/wp-calendar/wp-calendar.component';
import { OpenprojectWorkPackagesModule } from 'core-app/features/work-packages/openproject-work-packages.module';
@@ -38,6 +39,7 @@ import { OpenprojectTimeEntriesModule } from 'core-app/shared/components/time_en
import { WorkPackagesCalendarPageComponent } from 'core-app/features/calendar/wp-calendar-page/wp-calendar-page.component';
import { CALENDAR_ROUTES } from 'core-app/features/calendar/calendar.routes';
import { CalendarSidemenuComponent } from './sidemenu/calendar-sidemenu.component';
+import { QueryGetIcalUrlModalComponent } from 'core-app/shared/components/modals/get-ical-url-modal/query-get-ical-url.modal';
@NgModule({
imports: [
@@ -58,6 +60,9 @@ import { CalendarSidemenuComponent } from './sidemenu/calendar-sidemenu.componen
// Calendar component
FullCalendarModule,
+
+ // Angular reactive forms, required for QueryGetIcalUrlModalComponent
+ ReactiveFormsModule
],
declarations: [
// Work package calendars
@@ -65,6 +70,7 @@ import { CalendarSidemenuComponent } from './sidemenu/calendar-sidemenu.componen
WorkPackagesCalendarComponent,
TimeEntryCalendarComponent,
CalendarSidemenuComponent,
+ QueryGetIcalUrlModalComponent
],
exports: [
WorkPackagesCalendarComponent,
diff --git a/frontend/src/app/features/hal/resources/query-resource.ts b/frontend/src/app/features/hal/resources/query-resource.ts
index edade8e9793..d10b387245d 100644
--- a/frontend/src/app/features/hal/resources/query-resource.ts
+++ b/frontend/src/app/features/hal/resources/query-resource.ts
@@ -119,6 +119,7 @@ export class QueryResource extends HalResource {
export interface QueryResourceLinks {
updateImmediately?(attributes:any):Promise<any>;
+ icalUrl(payload:unknown):Promise<{ icalUrl:{ href:string } }>;
}
export interface QueryResource extends QueryResourceLinks {}
diff --git a/frontend/src/app/features/work-packages/openproject-work-packages.module.ts b/frontend/src/app/features/work-packages/openproject-work-packages.module.ts
index 5e6f8b84a96..f46ac10142a 100644
--- a/frontend/src/app/features/work-packages/openproject-work-packages.module.ts
+++ b/frontend/src/app/features/work-packages/openproject-work-packages.module.ts
@@ -30,7 +30,6 @@ import {
Injector,
NgModule,
} from '@angular/core';
-import { ReactiveFormsModule } from '@angular/forms';
import { OpSharedModule } from 'core-app/shared/shared.module';
import { OpenprojectFieldsModule } from 'core-app/shared/components/fields/openproject-fields.module';
import { OpenprojectModalModule } from 'core-app/shared/components/modal/modal.module';
@@ -126,7 +125,6 @@ import { OpenprojectAutocompleterModule } from 'core-app/shared/components/autoc
import { OpWpTabsModule } from 'core-app/features/work-packages/components/wp-tabs/wp-tabs.module';
import { EditFieldControlsModule } from 'core-app/shared/components/fields/edit/field-controls/edit-field-controls.module';
import { WpTableExportModalComponent } from 'core-app/shared/components/modals/export-modal/wp-table-export.modal';
-import { QueryGetIcalUrlModalComponent } from 'core-app/shared/components/modals/get-ical-url-modal/query-get-ical-url.modal';
import { WpButtonMacroModalComponent } from 'core-app/shared/components/modals/editor/macro-wp-button-modal/wp-button-macro.modal';
import { QuerySharingModalComponent } from 'core-app/shared/components/modals/share-modal/query-sharing.modal';
import { SaveQueryModalComponent } from 'core-app/shared/components/modals/save-modal/save-query.modal';
@@ -212,7 +210,6 @@ import { OpBaselineLegendsComponent } from 'core-app/features/work-packages/comp
EditFieldControlsModule,
OpenprojectTabsModule,
OpenprojectStoragesModule,
- ReactiveFormsModule,
],
providers: [
// Notification service
@@ -394,7 +391,6 @@ import { OpBaselineLegendsComponent } from 'core-app/features/work-packages/comp
WpTableConfigurationHighlightingTabComponent,
WpTableConfigurationRelationSelectorComponent,
WpTableExportModalComponent,
- QueryGetIcalUrlModalComponent,
QuerySharingFormComponent,
QuerySharingModalComponent,
SaveQueryModalComponent,
diff --git a/frontend/src/app/shared/components/modals/get-ical-url-modal/query-get-ical-url.modal.html b/frontend/src/app/shared/components/modals/get-ical-url-modal/query-get-ical-url.modal.html
index 945cdc9ae7b..2cbb629649c 100644
--- a/frontend/src/app/shared/components/modals/get-ical-url-modal/query-get-ical-url.modal.html
+++ b/frontend/src/app/shared/components/modals/get-ical-url-modal/query-get-ical-url.modal.html
@@ -26,6 +26,7 @@
formControlName="name"
slot="input"
[placeholder]="text.token_name_placeholder"
+ opAutofocus
></spot-text-field>
<div
diff --git a/frontend/src/app/shared/components/modals/get-ical-url-modal/query-get-ical-url.modal.sass b/frontend/src/app/shared/components/modals/get-ical-url-modal/query-get-ical-url.modal.sass
deleted file mode 100644
index 0eb61622ae6..00000000000
--- a/frontend/src/app/shared/components/modals/get-ical-url-modal/query-get-ical-url.modal.sass
+++ /dev/null
@@ -1,4 +0,0 @@
-.op-query-get-ical-url
- .ical-url
- word-break: break-word
-
diff --git a/frontend/src/app/shared/components/modals/get-ical-url-modal/query-get-ical-url.modal.ts b/frontend/src/app/shared/components/modals/get-ical-url-modal/query-get-ical-url.modal.ts
index cc41c188aad..45d662da8e9 100644
--- a/frontend/src/app/shared/components/modals/get-ical-url-modal/query-get-ical-url.modal.ts
+++ b/frontend/src/app/shared/components/modals/get-ical-url-modal/query-get-ical-url.modal.ts
@@ -53,7 +53,6 @@ interface TokenNameFormValue {
@Component({
templateUrl: './query-get-ical-url.modal.html',
- styleUrls: ['./query-get-ical-url.modal.sass'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
@@ -105,10 +104,7 @@ export class QueryGetIcalUrlModalComponent extends OpModalComponent implements O
ngOnInit():void {
super.ngOnInit();
- this.query = this.querySpace.query.value!;
-
- // TODO: I'm not sure if this is an error we actually need to catch
- if (!this.query) {
+ if (!this.querySpace.query.value) {
this.toastService.addError(
this.I18n.t('js.ical_sharing_modal.inital_setup_error_message'),
);
@@ -116,6 +112,8 @@ export class QueryGetIcalUrlModalComponent extends OpModalComponent implements O
setTimeout(() => {
this.closeMe();
}, 10);
+ } else {
+ this.query = this.querySpace.query.value!;
}
}
@@ -123,7 +121,7 @@ export class QueryGetIcalUrlModalComponent extends OpModalComponent implements O
if (!navigator.clipboard) {
// fallback for browsers that don't support clipboard API at all
this.toastService.addWarning(
- `${this.I18n.t('js.ical_sharing_modal.copy_url_error_text')} ${url}`,
+ this.I18n.t('js.ical_sharing_modal.copy_url_error_text', { icalUrl: url })
);
} else {
void navigator.clipboard.writeText(url)
@@ -133,7 +131,7 @@ export class QueryGetIcalUrlModalComponent extends OpModalComponent implements O
.catch(() => {
// fallback when running into e.g. browser permission errors
this.toastService.addWarning(
- `${this.I18n.t('js.ical_sharing_modal.copy_url_error_text')} ${url}`,
+ this.I18n.t('js.ical_sharing_modal.copy_url_error_text', { icalUrl: url })
);
});
}
diff --git a/lib/api/v3/queries/ical_url/query_ical_url_api.rb b/lib/api/v3/queries/ical_url/query_ical_url_api.rb
index 6f667317663..5f5271cc5d4 100644
--- a/lib/api/v3/queries/ical_url/query_ical_url_api.rb
+++ b/lib/api/v3/queries/ical_url/query_ical_url_api.rb
@@ -46,9 +46,8 @@ module API
post do
authorize_by_policy(:share_via_ical)
- # QUESTION: currently the generated URL points to controller action in calendar module
- # correct approach? or should it be implemented as a API here?
- call = ::Calendar::GenerateICalUrl.new.call(
+
+ call = ::Calendar::GenerateICalUrlService.new.call(
user: current_user,
query_id: @query.id,
project_id: @query.project_id,
@@ -61,7 +60,6 @@ module API
status 201
- # QUESTION: is it ok to use a Struct here?
ical_url_data = Struct.new(:ical_url, :query)
QueryICalUrlRepresenter.new(
diff --git a/lib/api/v3/queries/ical_url/query_ical_url_representer.rb b/lib/api/v3/queries/ical_url/query_ical_url_representer.rb
index aeaa85f8d68..e2a54c41e89 100644
--- a/lib/api/v3/queries/ical_url/query_ical_url_representer.rb
+++ b/lib/api/v3/queries/ical_url/query_ical_url_representer.rb
@@ -46,11 +46,10 @@ module API
end
link :icalUrl do
- # TODO: this is returning an absolute url
- # --> valid approach to render it as href in a link?
{
href: represented.ical_url,
- method: :get
+ method: :get,
+ type: "text/calendar"
}
end
diff --git a/modules/calendar/app/models/ical_token_query_assignment.rb b/modules/calendar/app/models/ical_token_query_assignment.rb
index e56f1c98def..98351546960 100644
--- a/modules/calendar/app/models/ical_token_query_assignment.rb
+++ b/modules/calendar/app/models/ical_token_query_assignment.rb
@@ -28,40 +28,20 @@
class ICalTokenQueryAssignment < ApplicationRecord
self.table_name = 'ical_token_query_assignments'
- # TODO: dependent_destroy from query model? --> already defined on database level
- belongs_to :ical_token, class_name: 'Token::ICal'
- belongs_to :query
+
+ belongs_to :ical_token, class_name: 'Token::ICal', required: true
+ belongs_to :query, required: true
validates :name, presence: true
validate :unique_name_per_user_and_query
- attr_accessor :user_id
-
- def ical_token_user_id
- # when creating an ical_token with nested params for ical_token_query_assignment
- # the user_id from the parent ical_token is not accessible
- # thererfore we need to pass it as an attribute like
- # Token::ICal.create(
- # user: user,
- # ical_token_query_assignment_attributes: { query: query, name: name, user_id: user.id }
- # )
- # ical_token.user_id is nil in this case and unique_name_per_user_and_query would fail
- # we therefore use the explicit user_id attribute
- #
- # when the ical_token and assignment are already created
- # we can access the user_id of the ical_token directly instead
- result = ical_token&.user_id || user_id
-
- if result.nil?
- raise "No user_id given while saving the ical_token_query_assignment"
- else
- result
- end
- end
-
def unique_name_per_user_and_query
- name_already_taken_for_query_and_user = self.class.joins(ical_token: :user)
- .exists?(name:, query_id:, ical_token: { user_id: ical_token_user_id })
+ if ical_token.nil? || ical_token.user_id.nil?
+ raise "Cannot validate uniqueness of name for #{self.class} without ical_token.user_id"
+ end
+
+ name_already_taken_for_query_and_user = self.class.joins(:ical_token)
+ .exists?(name:, query_id:, ical_token: { user_id: ical_token.user_id })
if name_already_taken_for_query_and_user
errors.add(:name, :not_unique)
diff --git a/modules/calendar/app/services/calendar/create_ical_service.rb b/modules/calendar/app/services/calendar/create_ical_service.rb
index 14e957b795a..a0ca2a371ab 100644
--- a/modules/calendar/app/services/calendar/create_ical_service.rb
+++ b/modules/calendar/app/services/calendar/create_ical_service.rb
@@ -27,13 +27,13 @@
#++
require 'icalendar'
-require 'rails-html-sanitizer'
module Calendar
class CreateICalService < ::BaseServices::BaseCallable
+ include ActionView::Helpers::SanitizeHelper
include TextFormattingHelper
- def perform(work_packages:, calendar_name: "OpenProject Calendar")
+ def perform(work_packages:, calendar_name:)
ical_string = create_ical_string(work_packages, calendar_name)
ServiceResult.success(result: ical_string)
@@ -48,8 +48,8 @@ module Calendar
calendar.x_wr_calname = calendar_name
work_packages.each do |work_package|
- event = create_event(work_package)
- event = add_attendee_value(event, work_package)
+ event = Icalendar::Event.new
+ event = add_values_to_event(event, work_package)
calendar.add_event(event)
end
@@ -57,17 +57,17 @@ module Calendar
calendar.to_ical
end
- def create_event(work_package)
- event = Icalendar::Event.new
+ def add_values_to_event(event, work_package)
event.uid = event_uid_value(work_package)
event.organizer = organizer_value(work_package)
event.summary = summary_value(work_package)
+ event.dtstamp = dtstamp_value(work_package)
event.dtstart = dtstart_value(work_package)
event.dtend = dtend_value(work_package)
event.location = location_value(work_package)
event.description = description_value(work_package)
- event
+ add_attendee_value(event, work_package)
end
def event_uid_value(work_package)
@@ -75,17 +75,28 @@ module Calendar
end
def attendee_value(work_package)
- [work_package.assigned_to&.name]
+ Icalendar::Values::CalAddress.new(
+ "mailto:#{work_package.assigned_to&.mail}",
+ cn: work_package.assigned_to&.name
+ )
end
def organizer_value(work_package)
- work_package.author&.name
+ Icalendar::Values::CalAddress.new(
+ "mailto:#{work_package.author&.mail}",
+ cn: work_package.author&.name
+ )
end
def summary_value(work_package)
work_package.name
end
+ def dtstamp_value(work_package)
+ # https://datatracker.ietf.org/doc/html/rfc5545#section-3.8.7.2
+ Icalendar::Values::DateTime.new(work_package.updated_at, 'tzid' => 'UTC')
+ end
+
def dtstart_value(work_package)
Icalendar::Values::Date.new(start_date(work_package))
end
@@ -117,58 +128,6 @@ module Calendar
OpenProject::StaticRouting::UrlHelpers.host
end
- def description_value(work_package)
- map = map_description_values(work_package)
-
- [
- map[:project], map[:type], map[:status],
- map[:assignee], map[:priority], map[:description]
- ].join("\n")
- end
-
- def map_description_values(work_package)
- map = {}
- map[:project] = translated_project_name(work_package)
- map[:type] = translated_type_name(work_package)
- map[:status] = translated_status_name(work_package)
- map[:assignee] = translated_assigne_name(work_package)
- map[:priority] = translated_priority_name(work_package)
- map[:description] = truncated_work_package_description_value(work_package)
-
- map
- end
-
- def translated_project_name(work_package)
- "#{I18n::t('activerecord.models.project')}: #{work_package.project.name}"
- end
-
- def translated_type_name(work_package)
- "#{I18n::t('activerecord.models.type')}: #{work_package.type&.name}"
- end
-
- def translated_status_name(work_package)
- "#{I18n::t('attributes.status')}: #{work_package.status&.name}"
- end
-
- def translated_assigne_name(work_package)
- "#{I18n::t('attributes.assignee')}: #{work_package.assigned_to&.name}"
- end
-
- def translated_priority_name(work_package)
- "#{I18n::t('activerecord.attributes.work_package.priority')}: #{work_package.priority&.name}"
- end
-
- def translated_description_name
- I18n::t("attributes.description")
- end
-
- def truncated_work_package_description_value(work_package)
- if work_package.description.present?
- stripped_text = truncate_formatted_text(work_package.description.to_s, length: 250)
- "\n#{translated_description_name}:\n #{stripped_text}"
- end
- end
-
def add_attendee_value(event, work_package)
# event.attendee = [work_package.assigned_to&.name] # causing thunderbird error "id is null"
event.attendee = attendee_value(work_package) if work_package.assigned_to.present?
@@ -176,36 +135,34 @@ module Calendar
event
end
- # override from text_formatting_helper
- # didn't work in this context -> got error "undefined method `full_sanitizer`"
- # furthermore the replacement of \n with <br> is not desired in the context of iCalendar files
- def truncate_formatted_text(text, length: 120)
- # rubocop:disable Rails/OutputSafety
- stripped_text = sanitizer_instance.sanitize(format_text(text)).html_safe
-
- if length
- truncate_multiline(stripped_text, length)
- else
- stripped_text
+ def description_value(work_package)
+ %i[
+ project
+ type
+ status
+ assigned_to
+ priority
+ ].map do |attribute|
+ translated_attribute_name_and_value(work_package, attribute)
end
- .strip
- .html_safe
- # rubocop:enable Rails/OutputSafety
+ .push(truncated_work_package_description_value(work_package))
+ .join("\n")
end
- # override from text_formatting_helper
- # the original method was statically truncating at 120 characters
- def truncate_multiline(string, length)
- if string.to_s =~ /\A(.{#{length}}).*?$/m
- "#{$1}..."
- else
- string
- end
+ def translated_attribute_name_and_value(work_package, attribute)
+ "#{WorkPackage.human_attribute_name(attribute)}: #{work_package.public_send(attribute)&.name}"
end
- # got error "undefined method `full_sanitizer`" without this when calling `strip_tags`
- def sanitizer_instance
- @sanitizer_instance ||= Rails::Html::FullSanitizer.new
+ def truncated_work_package_description_value(work_package)
+ return if work_package.description.blank?
+
+ stripped_text = truncate_formatted_text(
+ work_package.description.to_s,
+ length: 250,
+ replace_newlines: false
+ )
+
+ "\n#{WorkPackage.human_attribute_name(:description)}:\n #{stripped_text}"
end
end
end
diff --git a/modules/calendar/app/services/calendar/generate_ical_url.rb b/modules/calendar/app/services/calendar/generate_ical_url_service.rb
similarity index 95%
rename from modules/calendar/app/services/calendar/generate_ical_url.rb
rename to modules/calendar/app/services/calendar/generate_ical_url_service.rb
index 544fb224841..2641fd76f3a 100644
--- a/modules/calendar/app/services/calendar/generate_ical_url.rb
+++ b/modules/calendar/app/services/calendar/generate_ical_url_service.rb
@@ -27,7 +27,7 @@
#++
module Calendar
- class GenerateICalUrl < ::BaseServices::BaseCallable
+ class GenerateICalUrlService < ::BaseServices::BaseCallable
def perform(user:, query_id:, project_id:, token_name:)
new_ical_token = create_ical_token(user, query_id, token_name)
@@ -47,7 +47,7 @@ module Calendar
Token::ICal.create(user:,
ical_token_query_assignment_attributes: {
- query:, name:, user_id: user.id
+ query:, name:
})
end
diff --git a/modules/calendar/app/services/calendar/ical_response_service.rb b/modules/calendar/app/services/calendar/ical_response_service.rb
index 9a9bf086728..cefdaa6ca00 100644
--- a/modules/calendar/app/services/calendar/ical_response_service.rb
+++ b/modules/calendar/app/services/calendar/ical_response_service.rb
@@ -28,44 +28,30 @@
module Calendar
class ICalResponseService < ::BaseServices::BaseCallable
- ICAL_CACHE_EXPIRES_IN = 0.minutes # cache disabled for now by setting to 0.minute
+ include Contracted
- def perform(ical_token_string:, query_id:)
- ical_string = resolve_from_cache_or_regenerate(ical_token_string, query_id)
-
- if ical_string.present?
- ServiceResult.success(result: ical_string)
- else
- ServiceResult.failure
- end
- end
-
- protected
-
- def cache_key(ical_token_string, query_id)
- "ical-response-#{query_id}-#{ical_token_string}"
+ def initialize(*args)
+ super
+ self.contract_class = Queries::ICalSharingContract
end
- def resolve_from_cache_or_regenerate(ical_token_string, query_id)
- OpenProject::Cache.fetch(
- cache_key(ical_token_string, query_id),
- expires_in: ICAL_CACHE_EXPIRES_IN
- ) do
- regenerate_ical_string(ical_token_string, query_id)
- end
- end
-
- def regenerate_ical_string(ical_token_string, query_id)
+ def perform(ical_token_string:, query_id:)
ical_token_instance = resolve_ical_token(ical_token_string)
+
user = ical_token_instance.user
+ query = Query.find(query_id)
- User.execute_as(user) do
- query = resolve_and_authorize_query(ical_token_instance, query_id)
- work_packages = resolve_work_packages(query)
- create_ical_string(work_packages, query.name)
+ ical_string = nil
+
+ success, errors = validate_and_yield(query, user, options: { ical_token: ical_token_instance }) do
+ ical_string = ical_generation(query, user)
end
+
+ ServiceResult.new(success:, result: ical_string, errors:)
end
+ protected
+
def resolve_ical_token(ical_token_string)
call = ::Calendar::ResolveICalTokenService.new.call(
ical_token_string:
@@ -75,14 +61,11 @@ module Calendar
ical_token_instance
end
- def resolve_and_authorize_query(ical_token_instance, query_id)
- call = ::Calendar::ResolveAndAuthorizeQueryService.new.call(
- ical_token_instance:,
- query_id:
- )
- query = call.result if call.success?
-
- query
+ def ical_generation(query, user)
+ User.execute_as(user) do
+ work_packages = resolve_work_packages(query)
+ create_ical_string(work_packages, query.name)
+ end
end
def resolve_work_packages(query)
diff --git a/modules/calendar/app/services/calendar/resolve_and_authorize_query_service.rb b/modules/calendar/app/services/calendar/resolve_and_authorize_query_service.rb
deleted file mode 100644
index 4276d446688..00000000000
--- a/modules/calendar/app/services/calendar/resolve_and_authorize_query_service.rb
+++ /dev/null
@@ -1,79 +0,0 @@
-#-- copyright
-# OpenProject is an open source project management software.
-# Copyright (C) 2012-2023 the OpenProject GmbH
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License version 3.
-#
-# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
-# Copyright (C) 2006-2013 Jean-Philippe Lang
-# Copyright (C) 2010-2013 the ChiliProject Team
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# 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 General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-# See COPYRIGHT and LICENSE files for more details.
-#++
-
-module Calendar
- class ResolveAndAuthorizeQueryService < ::BaseServices::BaseCallable
- def perform(ical_token_instance:, query_id:)
- # TODO: move logic to contract
-
- if ical_token_instance.nil?
- raise ActiveRecord::RecordNotFound
- end
-
- query = resolve_query(query_id, ical_token_instance)
-
- token_valid_for_query = token_valid_for_query?(ical_token_instance, query)
- sharing_permitted = ical_sharing_permitted?(ical_token_instance.user, query)
-
- query = remove_date_range_filter(query)
-
- if sharing_permitted && token_valid_for_query
- ServiceResult.success(result: query)
- else
- # TODO: raise specific auth error
- raise ActiveRecord::RecordNotFound
- end
- end
-
- private
-
- def resolve_query(query_id, ical_token_instance)
- Query
- .visible(ical_token_instance.user) # authorization
- .find(query_id)
- end
-
- def token_valid_for_query?(ical_token_instance, query)
- ical_token_instance.query == query
- end
-
- def ical_sharing_permitted?(user, query)
- QueryPolicy.new(user).allowed?(query, :share_via_ical)
- end
-
- def remove_date_range_filter(query)
- # TODO:
- # Is this the correct way of unscoping the calendar view state
- # in order to get all workpackages from the query?
- query.filters = query.filters
- .reject { |filter| filter.name == :dates_interval }
-
- query
- end
- end
-end
diff --git a/modules/calendar/app/services/calendar/resolve_work_packages_service.rb b/modules/calendar/app/services/calendar/resolve_work_packages_service.rb
index 08512285a87..6dc47da8551 100644
--- a/modules/calendar/app/services/calendar/resolve_work_packages_service.rb
+++ b/modules/calendar/app/services/calendar/resolve_work_packages_service.rb
@@ -31,13 +31,27 @@ module Calendar
def perform(query:)
raise ActiveRecord::RecordNotFound if query.nil?
+ query = remove_date_range_filter(query)
+
work_packages = query.results.work_packages.includes(
- :project, :assigned_to, :author, :priority, :status
+ :project, :assigned_to, :author, :priority, :status, :type
)
work_packages_with_dates = work_packages
.where.not(start_date: nil, due_date: nil)
ServiceResult.success(result: work_packages_with_dates)
end
+
+ protected
+
+ def remove_date_range_filter(query)
+ # TODO:
+ # Is this the correct way of unscoping the calendar view state
+ # in order to get all workpackages from the query?
+ query.filters = query.filters
+ .reject { |filter| filter.name == :dates_interval }
+
+ query
+ end
end
end
diff --git a/modules/calendar/config/routes.rb b/modules/calendar/config/routes.rb
index 17c34c53172..7a3fb244028 100644
--- a/modules/calendar/config/routes.rb
+++ b/modules/calendar/config/routes.rb
@@ -5,7 +5,6 @@ OpenProject::Application.routes.draw do
only: %i[index destroy],
as: :calendars do
get '/new' => 'calendar/calendars#show', on: :collection, as: 'new'
- # TODO: discuss if other controller should be used
get '/ical' => 'calendar/ical#show', on: :member, as: 'ical'
get '(/*state)' => 'calendar/calendars#show', on: :member, as: ''
end
diff --git a/modules/calendar/db/migrate/20230502094813_add_name_to_ical_tokens.rb b/modules/calendar/db/migrate/20230502094813_add_name_to_ical_tokens.rb
index 57bb8ff76a3..6f7778034ec 100644
--- a/modules/calendar/db/migrate/20230502094813_add_name_to_ical_tokens.rb
+++ b/modules/calendar/db/migrate/20230502094813_add_name_to_ical_tokens.rb
@@ -1,8 +1,15 @@
class AddNameToICalTokens < ActiveRecord::Migration[7.0]
- def change
+ def up
# Add column with default value to avoid null values for existing records in preview environment
add_column :ical_token_query_assignments, :name, :string, null: false, default: 'Not provided in earlier version'
# Remove default value after migration and applying it to existing records
change_column_default :ical_token_query_assignments, :name, nil
end
+
+ def down
+ remove_column :ical_token_query_assignments, :name
+ # Remove all ical tokens as they have been created with a name before and
+ # are not intended to be used without a name
+ Token::ICal.delete_all
+ end
end
diff --git a/modules/calendar/spec/services/create_ical_service_spec.rb b/modules/calendar/spec/services/create_ical_service_spec.rb
index faab38d0ddd..baa88f4f1e6 100644
--- a/modules/calendar/spec/services/create_ical_service_spec.rb
+++ b/modules/calendar/spec/services/create_ical_service_spec.rb
@@ -91,45 +91,45 @@ describe Calendar::CreateICalService, type: :model do
CALSCALE:GREGORIAN
X-WR-CALNAME:#{query_name}
BEGIN:VEVENT
- DTSTAMP:#{freezed_date_time.strftime('%Y%m%dT%H%M%S')}Z
+ DTSTAMP:#{work_package_with_due_date.updated_at.utc.strftime('%Y%m%dT%H%M%SZ')}
UID:#{work_package_with_due_date.id}@localhost:3000
DTSTART;VALUE=DATE:#{work_package_with_due_date.due_date.strftime('%Y%m%d')}
DTEND;VALUE=DATE:#{(work_package_with_due_date.due_date + 1.day).strftime('%Y%m%d')}
DESCRIPTION:Project: #{project.name}\nType: None\nStatus: #{work_package_with_due_date.status.name}\nAssignee: \nPriority: #{work_package_with_due_date.priority.name}\n\nDescription:\n #{work_package_with_due_date.description}
LOCATION:http://localhost:3000/work_packages/#{work_package_with_due_date.id}
- ORGANIZER:#{work_package_with_due_date.author&.name}
+ ORGANIZER;CN=#{work_package_with_due_date.author.name}:mailto:#{work_package_with_due_date.author.mail}
SUMMARY:#{work_package_with_due_date.name}
END:VEVENT
BEGIN:VEVENT
- DTSTAMP:#{freezed_date_time.strftime('%Y%m%dT%H%M%S')}Z
+ DTSTAMP:#{work_package_with_start_date.updated_at.strftime('%Y%m%dT%H%M%SZ')}
UID:#{work_package_with_start_date.id}@localhost:3000
DTSTART;VALUE=DATE:#{work_package_with_start_date.start_date.strftime('%Y%m%d')}
DTEND;VALUE=DATE:#{(work_package_with_start_date.start_date + 1.day).strftime('%Y%m%d')}
DESCRIPTION:Project: #{project.name}\nType: None\nStatus: #{work_package_with_start_date.status.name}\nAssignee: \nPriority: #{work_package_with_start_date.priority.name}\n\nDescription:\n #{work_package_with_start_date.description}
LOCATION:http://localhost:3000/work_packages/#{work_package_with_start_date.id}
- ORGANIZER:#{work_package_with_start_date.author&.name}
+ ORGANIZER;CN=#{work_package_with_start_date.author.name}:mailto:#{work_package_with_start_date.author.mail}
SUMMARY:#{work_package_with_start_date.name}
END:VEVENT
BEGIN:VEVENT
- DTSTAMP:#{freezed_date_time.strftime('%Y%m%dT%H%M%S')}Z
+ DTSTAMP:#{work_package_with_start_and_due_date.updated_at.strftime('%Y%m%dT%H%M%SZ')}
UID:#{work_package_with_start_and_due_date.id}@localhost:3000
DTSTART;VALUE=DATE:#{work_package_with_start_and_due_date.start_date.strftime('%Y%m%d')}
DTEND;VALUE=DATE:#{(work_package_with_start_and_due_date.due_date + 1.day).strftime('%Y%m%d')}
DESCRIPTION:Project: #{project.name}\nType: None\nStatus: #{work_package_with_start_and_due_date.status.name}\nAssignee: \nPriority: #{work_package_with_start_and_due_date.priority.name}\n\nDescription:\n #{work_package_with_start_and_due_date.description}
LOCATION:http://localhost:3000/work_packages/#{work_package_with_start_and_due_date.id}
- ORGANIZER:#{work_package_with_start_and_due_date.author&.name}
+ ORGANIZER;CN=#{work_package_with_start_and_due_date.author.name}:mailto:#{work_package_with_start_and_due_date.author.mail}
SUMMARY:#{work_package_with_start_and_due_date.name}
END:VEVENT
BEGIN:VEVENT
- DTSTAMP:#{freezed_date_time.strftime('%Y%m%dT%H%M%S')}Z
+ DTSTAMP:#{work_package_with_due_date_and_assignee.updated_at.strftime('%Y%m%dT%H%M%SZ')}
UID:#{work_package_with_due_date_and_assignee.id}@localhost:3000
DTSTART;VALUE=DATE:#{work_package_with_due_date_and_assignee.due_date.strftime('%Y%m%d')}
DTEND;VALUE=DATE:#{(work_package_with_due_date_and_assignee.due_date + 1.day).strftime('%Y%m%d')}
DESCRIPTION:Project: #{project.name}\nType: None\nStatus: #{work_package_with_due_date_and_assignee.status.name}\nAssignee: #{work_package_with_due_date_and_assignee.assigned_to.name}\nPriority: #{work_package_with_due_date_and_assignee.priority.name}\n\nDescription:\n #{work_package_with_due_date_and_assignee.description}
LOCATION:http://localhost:3000/work_packages/#{work_package_with_due_date_and_assignee.id}
- ORGANIZER:#{work_package_with_due_date_and_assignee.author&.name}
+ ORGANIZER;CN=#{work_package_with_due_date_and_assignee.author.name}:mailto:#{work_package_with_due_date_and_assignee.author.mail}
SUMMARY:#{work_package_with_due_date_and_assignee.name}
- ATTENDEE:#{work_package_with_due_date_and_assignee.assigned_to.name}
+ ATTENDEE;CN=#{work_package_with_due_date_and_assignee.assigned_to.name}:mailto:#{work_package_with_due_date_and_assignee.assigned_to.mail}
END:VEVENT
END:VCALENDAR
EOICAL
diff --git a/modules/calendar/spec/services/resolve_and_authorize_query_spec.rb b/modules/calendar/spec/services/resolve_and_authorize_query_spec.rb
deleted file mode 100644
index cab5adb46ea..00000000000
--- a/modules/calendar/spec/services/resolve_and_authorize_query_spec.rb
+++ /dev/null
@@ -1,343 +0,0 @@
-#-- copyright
-# OpenProject is an open source project management software.
-# Copyright (C) 2012-2023 the OpenProject GmbH
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License version 3.
-#
-# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
-# Copyright (C) 2006-2013 Jean-Philippe Lang
-# Copyright (C) 2010-2013 the ChiliProject Team
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# 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 General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-# See COPYRIGHT and LICENSE files for more details.
-#++
-
-require 'spec_helper'
-
-describe Calendar::ResolveAndAuthorizeQueryService, type: :model do
- let(:sufficient_permissions) { %i[view_work_packages share_calendars] }
- let(:insufficient_permissions) { %i[view_work_packages] }
- let(:project) { create(:project) }
- let(:user) do
- create(:user,
- member_in_project: project,
- member_with_permissions: sufficient_permissions)
- end
- let(:private_query) do
- create(:query,
- project:,
- user:,
- public: false) # privat query
- end
- let(:public_query) do
- create(:query,
- project:,
- user:,
- public: true) # public query
- end
- let(:ical_token_instance_for_private_query) do
- Token::ICal.create(user:,
- ical_token_query_assignment_attributes: { query: private_query, name: "My Token",
- user_id: user.id })
- end
- let(:ical_token_instance_for_public_query) do
- Token::ICal.create(user:,
- ical_token_query_assignment_attributes: { query: public_query, name: "My Token",
- user_id: user.id })
- end
-
- let(:instance) do
- described_class.new
- end
-
- shared_examples 'not found' do
- it 'raises ActiveRecord::RecordNotFound' do
- expect { subject }.to raise_error(ActiveRecord::RecordNotFound)
- end
- end
-
- context 'if user is authenticated to read from query and user is permitted to use ical sharing' do
- context 'if ical token belongs to query' do
- context 'if user owns the query which is private' do
- subject do
- instance.call(
- query_id: private_query.id,
- ical_token_instance: ical_token_instance_for_private_query
- )
- end
-
- it 'returns the query as result' do
- expect(subject.result)
- .to eq private_query
- end
-
- it 'is a success' do
- expect(subject)
- .to be_success
- end
- end
-
- context 'if user owns the query which is public' do
- subject do
- instance.call(
- query_id: public_query.id,
- ical_token_instance: ical_token_instance_for_public_query
- )
- end
-
- it 'returns the query as result' do
- expect(subject.result)
- .to eq public_query
- end
-
- it 'is a success' do
- expect(subject)
- .to be_success
- end
- end
- end
-
- context 'if ical token does NOT belong to query' do
- context 'if user owns the query which is private' do
- subject do
- instance.call(
- query_id: private_query.id,
- ical_token_instance: ical_token_instance_for_public_query
- )
- end
-
- it_behaves_like "not found"
- end
-
- context 'if user owns the query which is public' do
- subject do
- instance.call(
- query_id: public_query.id,
- ical_token_instance: ical_token_instance_for_private_query
- )
- end
-
- it_behaves_like "not found"
- end
- end
-
- context 'if ical token is nil' do
- context 'if query is private' do
- subject do
- instance.call(
- query_id: private_query.id,
- ical_token_instance: nil
- )
- end
-
- it_behaves_like "not found"
- end
-
- context 'if query is public' do
- subject do
- instance.call(
- query_id: public_query.id,
- ical_token_instance: nil
- )
- end
-
- it_behaves_like "not found"
- end
- end
- end
-
- context 'if user is authenticated to read from query but is NOT permitted to use ical sharing' do
- let(:user) do
- create(:user,
- member_in_project: project,
- member_with_permissions: insufficient_permissions)
- end
-
- context 'if ical token belongs to query' do
- context 'if user owns the query which is private' do
- subject do
- instance.call(
- query_id: private_query.id,
- ical_token_instance: ical_token_instance_for_private_query
- )
- end
-
- it_behaves_like "not found"
- end
-
- context 'if user owns the query which is public' do
- subject do
- instance.call(
- query_id: public_query.id,
- ical_token_instance: ical_token_instance_for_public_query
- )
- end
-
- it_behaves_like "not found"
- end
- end
-
- context 'if ical token does NOT belong to query' do
- context 'if user owns the query which is private' do
- subject do
- instance.call(
- query_id: private_query.id,
- ical_token_instance: ical_token_instance_for_public_query
- )
- end
-
- it_behaves_like "not found"
- end
-
- context 'if user owns the query which is public' do
- subject do
- instance.call(
- query_id: public_query.id,
- ical_token_instance: ical_token_instance_for_private_query
- )
- end
-
- it_behaves_like "not found"
- end
- end
- end
-
- context 'if user is not member of the project (anymore)' do
- let(:project2) { create(:project) }
- let(:user) do
- create(:user,
- member_in_project: project2,
- member_with_permissions: sufficient_permissions)
- end
-
- # queries (privat and public) owned by user
- # but user is not part of the project anymore
-
- context 'if query is private' do
- subject do
- instance.call(
- query_id: private_query.id,
- ical_token_instance: ical_token_instance_for_private_query
- )
- end
-
- it_behaves_like "not found"
- end
-
- context 'if query is public' do
- subject do
- instance.call(
- query_id: public_query.id,
- ical_token_instance: ical_token_instance_for_public_query
- )
- end
-
- it_behaves_like "not found"
- end
- end
-
- context 'if query id is invalid or nil' do
- context 'if query id is invalid' do
- subject do
- instance.call(
- query_id: SecureRandom.hex,
- ical_token_instance: ical_token_instance_for_private_query
- )
- end
-
- it_behaves_like "not found"
- end
-
- context 'if query id is nil' do
- subject do
- instance.call(
- query_id: nil,
- ical_token_instance: ical_token_instance_for_private_query
- )
- end
-
- it_behaves_like "not found"
- end
- end
-
- context 'if user does not own the query' do
- let(:user) do
- create(:user,
- member_in_project: project,
- member_with_permissions: sufficient_permissions)
- end
- let(:another_user) do
- create(:user,
- member_in_project: project,
- member_with_permissions: sufficient_permissions)
- end
- let(:private_query_of_user) do
- create(:query,
- project:,
- user:,
- public: false)
- end
- let(:public_query_of_user) do
- create(:query,
- project:,
- user:,
- public: true)
- end
- let(:ical_token_instance_of_another_user_for_private_query_of_user) do
- Token::ICal.create(user: another_user,
- ical_token_query_assignment_attributes: {
- query: private_query_of_user, name: "My Token", user_id: another_user.id
- })
- end
- let(:ical_token_instance_of_another_user_for_public_query_of_user) do
- Token::ICal.create(user: another_user,
- ical_token_query_assignment_attributes: {
- query: public_query_of_user, name: "My Token", user_id: another_user.id
- })
- end
-
- context 'if query is private' do
- subject do
- instance.call(
- query_id: private_query_of_user.id,
- ical_token_instance: ical_token_instance_of_another_user_for_private_query_of_user
- )
- end
-
- it_behaves_like "not found"
- end
-
- context 'if query is public' do
- subject do
- instance.call(
- query_id: public_query_of_user.id,
- ical_token_instance: ical_token_instance_of_another_user_for_public_query_of_user
- )
- end
-
- it 'returns the query as result' do
- expect(subject.result)
- .to eq public_query_of_user
- end
-
- it 'is a success' do
- expect(subject)
- .to be_success
- end
- end
- end
-end
diff --git a/spec/contracts/queries/ical_sharing_contract_spec.rb b/spec/contracts/queries/ical_sharing_contract_spec.rb
new file mode 100644
index 00000000000..388b682516a
--- /dev/null
+++ b/spec/contracts/queries/ical_sharing_contract_spec.rb
@@ -0,0 +1,145 @@
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2023 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# 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 General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See COPYRIGHT and LICENSE files for more details.
+#++
+
+require 'spec_helper'
+require 'contracts/shared/model_contract_shared_context'
+require_relative 'shared_contract_examples'
+
+describe Queries::ICalSharingContract do
+ include_context 'ModelContract shared context'
+ include_context 'with queries contract'
+
+ let(:project) { create(:project) }
+ let(:query) do
+ create(:query, project:, public:, user:)
+ end
+ let(:current_user) do
+ create(:user,
+ member_in_project: project,
+ member_with_permissions: permissions)
+ end
+ let(:ical_token) { create(:ical_token, user: current_user, query:, name: "Some Token") }
+
+ # override as this contract additionally needs the ical_token
+ let(:contract) { described_class.new(query, current_user, options: { ical_token: ical_token }) }
+
+ describe 'private query' do
+ let(:public) { false }
+
+ context 'when user is author' do
+ let(:user) { current_user }
+
+ context 'when user has no permission to share via ical' do
+ let(:permissions) { %i(view_work_packages view_calendar manage_calendars) }
+
+ it_behaves_like 'contract user is unauthorized'
+ end
+
+ context 'when user has permission to share via' do
+ let(:permissions) { %i(view_work_packages share_calendars) }
+
+ it_behaves_like 'contract is valid'
+ end
+
+ context 'when ical_token is not scoped to query' do
+ let(:other_query) do
+ create(:query, project:, public:, user:)
+ end
+ let(:ical_token) { create(:ical_token, query: other_query, user: current_user, name: "Some Token") }
+
+ context 'when user has no permission to share via ical' do
+ let(:permissions) { %i(view_work_packages view_calendar manage_calendars) }
+
+ it_behaves_like 'contract user is unauthorized'
+ end
+
+ context 'when user has permission to share via ical' do
+ let(:permissions) { %i(view_work_packages share_calendars) }
+
+ it_behaves_like 'contract user is unauthorized'
+ end
+ end
+ end
+
+ context 'when author is someone else' do
+ let(:user) { create(:user) } # other user as owner of query
+ let(:permissions) { %i(view_work_packages share_calendars) } # all necessary permissions
+
+ it_behaves_like 'contract user is unauthorized' # unauthorized as user is not author
+ end
+ end
+
+ describe 'public query' do
+ let(:public) { true }
+ let(:user) { current_user }
+
+ context 'when user has no permission to share via ical' do
+ let(:permissions) { %i(view_work_packages view_calendar manage_calendars) }
+
+ it_behaves_like 'contract user is unauthorized'
+
+ context 'when author is someone else' do
+ let(:user) { create(:user) } # other user as owner of query
+
+ it_behaves_like 'contract user is unauthorized' # authorized as query is public
+ end
+ end
+
+ context 'when user has permission to share via ical' do
+ let(:permissions) { %i(view_work_packages share_calendars) }
+
+ it_behaves_like 'contract is valid'
+
+ context 'when author is someone else' do
+ let(:user) { create(:user) } # other user as owner of query
+
+ it_behaves_like 'contract is valid' # authorized as query is public
+ end
+ end
+ end
+
+ describe 'project membership' do
+ let(:public) { false }
+ let(:other_project) { create(:project) }
+ let(:current_user) do
+ create(:user,
+ member_in_project: other_project,
+ member_with_permissions: permissions)
+ end
+
+ context 'when user is author but not member of project (anymore)' do
+ let(:user) { current_user }
+
+ context 'when user has no permission to share via ical' do
+ let(:permissions) { %i(view_work_packages view_calendar manage_calendars) }
+
+ it_behaves_like 'contract user is unauthorized'
+ end
+ end
+ end
+end
diff --git a/spec/factories/ical_token_query_assignment_factory.rb b/spec/factories/ical_token_query_assignment_factory.rb
new file mode 100644
index 00000000000..8367ca5e100
--- /dev/null
+++ b/spec/factories/ical_token_query_assignment_factory.rb
@@ -0,0 +1,34 @@
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2023 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# 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 General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See COPYRIGHT and LICENSE files for more details.
+#++
+
+FactoryBot.define do
+ factory :ical_token_query_assignment do
+ association :ical_token
+ association :query
+ end
+end
diff --git a/spec/factories/token_factory.rb b/spec/factories/token_factory.rb
index 4d693816188..bf56e2748b9 100644
--- a/spec/factories/token_factory.rb
+++ b/spec/factories/token_factory.rb
@@ -62,4 +62,21 @@ FactoryBot.define do
end
end
end
+
+ factory :ical_token, class: '::Token::ICal' do
+ association :user
+
+ transient do
+ query { nil }
+ name { nil }
+ end
+
+ after(:build) do |token, evaluator|
+ token.ical_token_query_assignment = build(:ical_token_query_assignment,
+ query: evaluator.query,
+ name: evaluator.name,
+ ical_token: token
+ )
+ end
+ end
end
diff --git a/spec/models/query_spec.rb b/spec/models/query_spec.rb
index fe99934f936..82e1ca1c0d5 100644
--- a/spec/models/query_spec.rb
+++ b/spec/models/query_spec.rb
@@ -872,4 +872,32 @@ describe Query,
it_behaves_like 'does not add a subproject id filter'
end
end
+
+ describe 'ical tokens' do
+ let(:user) { create(:user) }
+ let(:query) { create(:query, user:) }
+
+ context 'when present' do
+ let(:ical_token) { create(:ical_token, user:, query:, name: "Some Token") }
+
+ it 'can be accessed via relation' do
+ expect(query.ical_tokens).to contain_exactly(ical_token)
+ end
+
+ it 'are destroyed when query is destroyed' do
+ expect do
+ query.destroy!
+ end.to change { Token::ICal.where(id: ical_token.id).count }.by(-1)
+ expect(ICalTokenQueryAssignment.all).to be_empty
+ end
+ end
+
+ context 'when not present' do
+ it 'do not cause errors on query.destroy' do
+ expect do
+ query.destroy!
+ end.not_to raise_error
+ end
+ end
+ end
end
diff --git a/spec/models/token/ical_token_spec.rb b/spec/models/token/ical_token_spec.rb
index 119aa67fa4a..2f9ff81fa74 100644
--- a/spec/models/token/ical_token_spec.rb
+++ b/spec/models/token/ical_token_spec.rb
@@ -51,7 +51,7 @@ describe Token::ICal do
# thus an ical_token cannot be created without a name although a query is given
ical_token2 = described_class.create(
user:,
- ical_token_query_assignment_attributes: { query:, user_id: user.id }
+ ical_token_query_assignment_attributes: { query: }
)
expect(ical_token2.errors["ical_token_query_assignment.name"].first).to eq("is mandatory. Please select a name.")
@@ -60,7 +60,7 @@ describe Token::ICal do
# if a query and name is given, the token can be created
ical_token3 = described_class.create(
user:,
- ical_token_query_assignment_attributes: { query:, name:, user_id: user.id }
+ ical_token_query_assignment_attributes: { query:, name: }
)
expect(ical_token3.errors).to be_empty
expect(ical_token3.query).to eq query
@@ -77,11 +77,11 @@ describe Token::ICal do
# therefore a user needs to be allowed to have N ical tokens per query
ical_token1 = described_class.create(
user:,
- ical_token_query_assignment_attributes: { query:, name: "#{name}_1", user_id: user.id }
+ ical_token_query_assignment_attributes: { query:, name: "#{name}_1" }
)
ical_token2 = described_class.create(
user:,
- ical_token_query_assignment_attributes: { query:, name: "#{name}_2", user_id: user.id }
+ ical_token_query_assignment_attributes: { query:, name: "#{name}_2" }
)
expect(described_class.where(user_id: user.id)).to contain_exactly(
@@ -92,11 +92,11 @@ describe Token::ICal do
ical_token3 = described_class.create(
user:,
- ical_token_query_assignment_attributes: { query: query2, name: "#{name}_3", user_id: user.id }
+ ical_token_query_assignment_attributes: { query: query2, name: "#{name}_3" }
)
ical_token4 = described_class.create(
user:,
- ical_token_query_assignment_attributes: { query: query2, name: "#{name}_4", user_id: user.id }
+ ical_token_query_assignment_attributes: { query: query2, name: "#{name}_4" }
)
expect(described_class.where(user_id: user.id)).to contain_exactly(
@@ -107,11 +107,11 @@ describe Token::ICal do
it 'a user cannot have N ical tokens per query with the same name' do
ical_token1 = described_class.create(
user:,
- ical_token_query_assignment_attributes: { query:, name: "#{name}_1", user_id: user.id }
+ ical_token_query_assignment_attributes: { query:, name: "#{name}_1" }
)
ical_token2 = described_class.create(
user:,
- ical_token_query_assignment_attributes: { query:, name: "#{name}_1", user_id: user.id }
+ ical_token_query_assignment_attributes: { query:, name: "#{name}_1" }
)
expect(ical_token2.errors["ical_token_query_assignment.name"].first).to eq(
@@ -128,7 +128,7 @@ describe Token::ICal do
ical_token3 = described_class.create(
user:,
- ical_token_query_assignment_attributes: { query: query2, name: "#{name}_1", user_id: user.id }
+ ical_token_query_assignment_attributes: { query: query2, name: "#{name}_1" }
)
expect(described_class.where(user_id: user.id)).to contain_exactly(
@@ -188,13 +188,59 @@ describe Token::ICal do
# rubocop:enable Rails/DynamicFindBy
end
end
+
+ describe 'dependent destroyed' do
+ context 'when associated query is destroyed' do
+ it 'the ical_token is destroyed as well' do
+ ical_token = described_class.create(
+ user:,
+ ical_token_query_assignment_attributes: { query:, name: }
+ )
+ expect do
+ query.destroy!
+ end.to change { described_class.count }.by(-1)
+
+ expect(described_class.all).to be_empty
+ expect(ICalTokenQueryAssignment.all).to be_empty
+ end
+ end
+
+ context 'when associated user is destroyed' do
+ it 'the ical_token is destroyed as well' do
+ ical_token = described_class.create(
+ user:,
+ ical_token_query_assignment_attributes: { query:, name: }
+ )
+ expect do
+ user.destroy!
+ end.to change { described_class.count }.by(-1)
+
+ expect(described_class.all).to be_empty
+ expect(ICalTokenQueryAssignment.all).to be_empty
+ end
+ end
+
+ context 'when ical_token is destroyed' do
+ it 'the ical_token_query_assignment is destroyed as well' do
+ ical_token = described_class.create(
+ user:,
+ ical_token_query_assignment_attributes: { query:, name: }
+ )
+ expect do
+ ical_token.destroy!
+ end.to change { ICalTokenQueryAssignment.count }.by(-1)
+
+ expect(ICalTokenQueryAssignment.all).to be_empty
+ end
+ end
+ end
end
describe 'behaves like Token::HashedToken if created with query assignment' do
subject do
described_class.new(
user:,
- ical_token_query_assignment_attributes: { query:, name:, user_id: user.id }
+ ical_token_query_assignment_attributes: { query:, name: }
)
end
diff --git a/spec/requests/api/v3/queries/ical_url/query_ical_url_api_spec.rb b/spec/requests/api/v3/queries/ical_url/query_ical_url_api_spec.rb
index f90d9e0fa6c..3abdd5c68a2 100644
--- a/spec/requests/api/v3/queries/ical_url/query_ical_url_api_spec.rb
+++ b/spec/requests/api/v3/queries/ical_url/query_ical_url_api_spec.rb
@@ -37,7 +37,7 @@ describe 'API v3 Query ICal Url' do
let(:project) { create(:project) }
let(:role) { create(:role, permissions:) }
# TODO: check OpenProject::Configuration.ical_subscriptions_enabled configuration
- # TODO: :view_work_packages permission is mandatory, otherwise a 404 is returned. Why?
+ # :view_work_packages permission is mandatory, otherwise a 404 is returned.
let(:permissions) { %i[view_work_packages share_calendars] }
let(:user) do
create(:user,
@@ -118,7 +118,7 @@ describe 'API v3 Query ICal Url' do
end
context 'when user has insufficient permissions' do
- # TODO: :view_work_packages permission is mandatory, otherwise a 404 is returned. Why?
+ # :view_work_packages permission is mandatory, otherwise a 404 is returned.
let(:permissions) { [:view_work_packages] } # share_calendars is missing
it_behaves_like 'unauthorized access'