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
Ruby agile-developmentangularbcfboardsbug-trackerganttgantt-chartifcissue-trackerjira-alternativekanbanopenprojectproduct-managementproject-managementproject-planningroadmaprubyscrumtimelineworkflows
finalized prototypical implementation of named ical tokens for testing purposes
Jonas Jabarie1fa9eaf72e3
diff --git a/app/controllers/my_controller.rb b/app/controllers/my_controller.rbindex d565839e04f..87ce406b02a 100644--- a/app/controllers/my_controller.rb+++ b/app/controllers/my_controller.rb@@ -130,15 +130,15 @@ class MyController < ApplicationControllerredirect_to action: 'access_token'end- def revoke_all_ical_tokens_of_query- query = Query.find(params[:query_id])+ def revoke_ical_token+ ical_token = current_user.ical_tokens.find(params[:id])+ query = ical_token.query+ name = ical_token.ical_token_query_assignment.name- ical_tokens_of_query = current_user.ical_tokens- .joins(:ical_token_query_assignment)- .where(ical_token_query_assignments: { query_id: query.id })- ical_tokens_of_query.destroy_all+ ical_token.destroy- flash[:info] = t('my.access_token.notice_ical_tokens_reverted',+ flash[:info] = t('my.access_token.notice_ical_tokens_reverted',+ token_name: name,calendar_name: query.name,project_name: query.project.name)diff --git a/app/models/token/ical.rb b/app/models/token/ical.rbindex a3053bbf861..5ca7d5856e7 100644--- a/app/models/token/ical.rb+++ b/app/models/token/ical.rb@@ -29,21 +29,22 @@module Tokenclass ICal < HashedToken# restrict the usage of one ical token to one query (calendar)- has_one :ical_token_query_assignment, dependent: :destroy, foreign_key: :ical_token_id+ has_one :ical_token_query_assignment, required: true, dependent: :destroy, foreign_key: :ical_token_id+ accepts_nested_attributes_for :ical_token_query_assignment+has_one :query, through: :ical_token_query_assignmenthas_one :project, through: :query- validate :query_assignment_must_exist-class << self- def create_and_return_value(user, query)- create(user:, query:).plain_value+ def create_and_return_value(user, query, token_name)+ # using the ! here to raise an exception if the token could+ # 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: query, name: token_name, user_id: user.id+ }).plain_valueendend-- def query_assignment_must_exist- errors.add(:base, "IcalTokenQueryAssignment must exist") unless ical_token_query_assignment.present?- end# Prevent deleting previous tokens# Every time an ical url is generated, a new ical token will be generated for this url as welldiff --git a/app/views/my/access_token.html.erb b/app/views/my/access_token.html.erbindex bab0c8fe406..015692f637a 100644--- a/app/views/my/access_token.html.erb+++ b/app/views/my/access_token.html.erb@@ -111,22 +111,23 @@ See COPYRIGHT and LICENSE files for more details.<% end %><% if @ical_tokens_grouped_by_query.any? %><% @ical_tokens_grouped_by_query.each do |query_id, tokens| %>- <% latest = tokens.sort_by(&:created_at).last %>- <tr>- <td><%= t(:label_ical_access_key_description, calendar_name: latest.query.name, project_name: latest.query.project.name) %></td>- <td>- <span title="<%= format_time(latest.created_at) %>">- <%= format_time(latest.created_at.to_s) %> (<%= t(:label_ical_access_key_latest) %>)- </span>- </td>- <td><%= I18n.t('my_account.access_tokens.indefinite_expiration') %></td>- <td>- <%= link_to t(:label_ical_access_key_revoke_all),- { action: 'revoke_all_ical_tokens_of_query', query_id: query_id },- method: :delete,- class: 'icon icon-delete' %>- </td>- </tr>+ <% tokens.sort_by(&:created_at).each do |token| %>+ <tr>+ <td><%= t(:label_ical_access_key_description, token_name: token.ical_token_query_assignment.name, calendar_name: token.query.name, project_name: token.query.project.name) %></td>+ <td>+ <span title="<%= format_time(token.created_at) %>">+ <%= format_time(token.created_at.to_s) %>+ </span>+ </td>+ <td><%= I18n.t('my_account.access_tokens.indefinite_expiration') %></td>+ <td>+ <%= link_to t(:label_ical_access_key_revoke),+ { action: 'revoke_ical_token', id: token.id },+ method: :delete,+ class: 'icon icon-delete' %>+ </td>+ </tr>+ <% end %><% end %><% else %><tr>diff --git a/config/locales/en.yml b/config/locales/en.ymlindex b7e41295083..aa8b0a60e91 100644--- a/config/locales/en.yml+++ b/config/locales/en.yml@@ -300,7 +300,7 @@ en:notice_reset_token: "A new %{type} token has been generated. Your access token is:"token_value_warning: "Note: This is the only time you will see this token, make sure to copy it now."no_results_title_text: There are currently no access tokens available.- notice_ical_tokens_reverted: All iCalendar tokens for calendar %{calendar_name} of project %{project_name} have been revoked. All previously used iCalendar URLs for this calendar are now invalid.+ notice_ical_tokens_reverted: "iCalendar token \"%{token_name}\" for calendar \"%{calendar_name}\" of project \"%{project_name}\" has been revoked. The iCalendar URL with this token is now invalid."news:index:@@ -1589,11 +1589,11 @@ en:label_api_access_key_created_on: "API access key created %{value} ago"label_api_access_key_type: "API"label_ical_access_key_type: "iCalendar"- label_ical_access_key_description: "iCalendar token(s) for calendar \"%{calendar_name}\" of project \"%{project_name}\""+ label_ical_access_key_description: "iCalendar token \"%{token_name}\" for \"%{calendar_name}\" in \"%{project_name}\""label_ical_access_key_not_present: "iCalendar token(s) not present."label_ical_access_key_generation_hint: "Automatically generated when subscribing to a calendar."label_ical_access_key_latest: "latest"- label_ical_access_key_revoke_all: "Revoke all"+ label_ical_access_key_revoke: "Revoke"label_applied_status: "Applied status"label_archive_project: "Archive project"label_ascending: "Ascending"diff --git a/config/locales/js-en.yml b/config/locales/js-en.ymlindex 86fc7f51517..9606cec2b49 100644--- a/config/locales/js-en.yml+++ b/config/locales/js-en.yml@@ -361,9 +361,13 @@ en: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: "You can also share this URL with external users. However, anyone with this link will be able to view work package details without an account or password."+ 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: "Token name"+ token_name_placeholder: "Type a name for this token, e.g. 'My calendar application'"+ token_name_description_text: "The token name will be used to identify the token in the list of <a href=\"my/access_token\", target=\"_blank\">iCalendar tokens</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"+ token_name_already_in_use_error_text: "This name is already in use for this query. Please select another name."copy_url_success_text: "URL copied to clipboard"copy_url_error_text: "couldn't be copied to clipboard"diff --git a/config/routes.rb b/config/routes.rbindex d3b1b19944c..6cdbceceaf9 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -551,7 +551,7 @@ OpenProject::Application.routes.draw dopost '/my/generate_rss_key', action: 'generate_rss_key'post '/my/generate_api_key', action: 'generate_api_key'- delete '/my/revoke_all_ical_tokens_of_query', action: 'revoke_all_ical_tokens_of_query'+ delete '/my/revoke_ical_token', action: 'revoke_ical_token'get '/my/access_token', action: 'access_token'enddiff --git a/frontend/src/app/core/apiv3/endpoints/queries/apiv3-queries-paths.ts b/frontend/src/app/core/apiv3/endpoints/queries/apiv3-queries-paths.tsindex 032d1780f19..24f43da992f 100644--- a/frontend/src/app/core/apiv3/endpoints/queries/apiv3-queries-paths.ts+++ b/frontend/src/app/core/apiv3/endpoints/queries/apiv3-queries-paths.ts@@ -137,8 +137,9 @@ export class ApiV3QueriesPaths extends ApiV3ResourceCollection<QueryResource, Ap* Get the ical url of the given query for the requesting user with the ical token** @param query+ * @param tokenName*/- public getIcalUrl(query:QueryResource):Promise<unknown> {- return query.icalUrl();+ public getIcalUrl(query:QueryResource, tokenName:String):Promise<unknown> {+ return query.icalUrl({ token_name: tokenName });}}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.htmlindex e6fee41fe16..54507891a94 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@@ -1,35 +1,67 @@-<div+<form+ name="getIcalUrlForm"+ (submit)="generateAndCopyUrl($event)"class="spot-modal loading-indicator--location op-query-get-ical-url"- data-indicator-name="modal"><div class="spot-modal--header">{{text.label_ical_sharing}}</div><div class="spot-divider"></div><div class="spot-modal--body spot-container">- <p>- {{text.description_ical_sharing}}- </p>- <div tabindex="0" class="-error op-toast">+ <div tabindex="0" class="-warning op-toast"><div role="alert" aria-atomic="true" class="op-toast--content"><p><span>{{text.ical_sharing_warning}}</span></p></div></div>++ <p>+ {{text.description_ical_sharing}}+ </p>++ <!-- <label class="form--label -bold" for="name" [textContent]="text.token_name"></label> -->++ <h5>{{text.token_name}}</h5>++ <p [innerHtml]="text.token_name_description_text"></p>++ <div class="form--field -required ">+ <div class="form--field-container">+ <div class="form--text-field-container">+ <input+ class="form--text-field"+ type="text"+ name="name"+ id="name"+ #tokenNameField+ [(ngModel)]="tokenName"+ [placeholder]="text.token_name_placeholder"+ required+ />+ </div>+ </div>+ </div>++ <div *ngIf="hasErrors">+ <p class="error-text">+ {{text.token_name_already_in_use_error_text}}+ </p>+ </div>+</div><div class="spot-action-bar"><div class="spot-action-bar--right">- <button class="button button_no-margin spot-modal--cancel-button spot-action-bar--action"+ <button type="button" class="button button_no-margin spot-modal--cancel-button spot-action-bar--action"[textContent]="text.button_cancel"(click)="closeMe($event)"></button>- <button class="button button_no-margin -highlight -with-icon icon-copy spot-action-bar--action"- (click)="generateAndCopyUrl()"+ <button type="submit" class="button button_no-margin -highlight -with-icon icon-copy spot-action-bar--action"+ (click)="generateAndCopyUrl($event)"[textContent]="text.button_copy"- [disabled]="isBusy">+ [disabled]="isBusy || !tokenName"></button></div></div>-</div>+</form>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.sassindex 0eb61622ae6..298ca3ad5f7 100644--- 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@@ -1,4 +1,12 @@.op-query-get-ical-url.ical-urlword-break: break-word+ .form--text-field+ // TODO: find default error styling approach+ &.-error+ border: 2px solid red+ background: #fedada+ .error-text+ color: red+ font-size: 0.8remdiff --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.tsindex 5751c5789a6..971f8ff7308 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@@ -34,7 +34,7 @@ import { OpModalComponent } from 'core-app/shared/components/modal/modal.componeimport { OpModalLocalsToken } from 'core-app/shared/components/modal/modal.service';import { OpModalLocalsMap } from 'core-app/shared/components/modal/modal.types';import {- ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, Inject, OnInit,+ ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, Inject, OnInit, ViewChild} from '@angular/core';import { I18nService } from 'core-app/core/i18n/i18n.service';import { IsolatedQuerySpace } from 'core-app/features/work-packages/directives/query-space/isolated-query-space';@@ -49,14 +49,25 @@ import { timeout } from 'rxjs/operators';changeDetection: ChangeDetectionStrategy.OnPush,})export class QueryGetIcalUrlModalComponent extends OpModalComponent implements OnInit {+ public tokenName = '';+public query:QueryResource;public isBusy = false;+ public hasErrors = false;+++ @ViewChild('tokenNameField', { static: true }) tokenNameField:ElementRef;+public text = {label_ical_sharing: this.I18n.t('js.ical_sharing_modal.title'),description_ical_sharing: this.I18n.t('js.ical_sharing_modal.description'),ical_sharing_warning: this.I18n.t('js.ical_sharing_modal.warning'),+ token_name: this.I18n.t('js.ical_sharing_modal.token_name_label'),+ token_name_placeholder: this.I18n.t('js.ical_sharing_modal.token_name_placeholder'),+ token_name_description_text: this.I18n.t('js.ical_sharing_modal.token_name_description_text'),+ token_name_already_in_use_error_text: this.I18n.t('js.ical_sharing_modal.token_name_already_in_use_error_text'),button_copy: this.I18n.t('js.ical_sharing_modal.copy_url_label'),copy_success_text: this.I18n.t('js.ical_sharing_modal.copy_url_success_text'),button_cancel: this.I18n.t('js.button_cancel'),@@ -95,6 +106,10 @@ export class QueryGetIcalUrlModalComponent extends OpModalComponent implements O}}+ public onOpen():void {+ this.tokenNameField.nativeElement.focus();+ }+public copyUrlAndCloseModal(url:string):void {void navigator.clipboard.writeText(url).then(() => {@@ -109,7 +124,7 @@ export class QueryGetIcalUrlModalComponent extends OpModalComponent implements O});}- public generateAndCopyUrl():void {+ public generateAndCopyUrl(event:any):void {if (this.isBusy) {return;}@@ -121,20 +136,23 @@ export class QueryGetIcalUrlModalComponent extends OpModalComponent implements Oconst promise = this.apiV3Service.queries- .getIcalUrl(this.query);+ .getIcalUrl(this.query, this.tokenName);void promise.then((response:HalResource) => {icalUrl = String(response.icalUrl.href);this.copyUrlAndCloseModal(icalUrl);})- .catch(() => {- this.isBusy = false;- this.cdRef.detectChanges();+ .catch((error:any) => {+ this.halNotification.handleRawError(error)- this.toastService.addError(- this.I18n.t('js.ical_sharing_modal.ical_generation_error_text')- );- });+ this.hasErrors = true++ const el = this.tokenNameField.nativeElement;+ el.classList.add('-error'); //TODO: find default error styling approach++ this.cdRef.detectChanges();+ })+ .then(() => this.isBusy = false); // Same as .finally()}}diff --git a/lib/api/v3/queries/queries_api.rb b/lib/api/v3/queries/queries_api.rbindex 5e6fc9028b6..842b1e75112 100644--- a/lib/api/v3/queries/queries_api.rb+++ b/lib/api/v3/queries/queries_api.rb@@ -161,33 +161,53 @@ module APInamespace :ical_url dopost do++ params do+ requires :token_name, type: String, desc: 'The name which should be used for the ical token'+ end+authorize_by_policy(:share_via_ical)+ # TODO: use representer in order to properly generate following response+ # TODO: write test for this+# 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(user: current_user,query_id: @query.id,- project_id: @query.project_id+ project_id: @query.project_id,+ token_name: params[:token_name])- # TODO: use representer in order to properly generate following response- # TODO: write test for this- {- "_type": "QueryICalUrl",- "_links": {- "self": {- "href": api_v3_paths.query_ical_url(@query.id)- },- "query": {- "href": api_v3_paths.query(@query.id)- },- "icalUrl": {- "href": call.result,- "format": "text/calendar"+ if call.success?+ {+ "_type": "QueryICalUrl",+ "_links": {+ "self": {+ "href": api_v3_paths.query_ical_url(@query.id)+ },+ "query": {+ "href": api_v3_paths.query(@query.id)+ },+ "icalUrl": {+ "href": call.result,+ "format": "text/calendar"+ }+ }+ }+ else+ error!({+ "_type": "Error",+ "errorIdentifier": "urn:openproject-org:api:v3:errors:PropertyConstraintViolation",+ "message": call.message,+ "_embedded": {+ "details": {+ "attribute": "name"+ }}- }- }+ })+ endendenddiff --git a/modules/calendar/app/models/ical_token_query_assignment.rb b/modules/calendar/app/models/ical_token_query_assignment.rbindex 6631970ae3c..baf168f189f 100644--- a/modules/calendar/app/models/ical_token_query_assignment.rb+++ b/modules/calendar/app/models/ical_token_query_assignment.rb@@ -27,7 +27,38 @@#++class IcalTokenQueryAssignment < ApplicationRecord- # TODO: dependent_destroy from query model+ # TODO: dependent_destroy from query model? --> already defined on database levelbelongs_to :ical_token, class_name: 'Token::ICal'belongs_to :query++ 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+ ical_token&.user_id || user_id+ end++ def unique_name_per_user_and_query+ name_already_taken_for_query_and_user = self.class.joins(ical_token: :user)+ .where(name: name, query_id: query_id, ical_token: { user_id: ical_token_user_id })+ .exists?++ if name_already_taken_for_query_and_user+ errors.add(:name, "has already been taken for this query and user")+ end+ endenddiff --git a/modules/calendar/app/services/calendar/generate_ical_url.rb b/modules/calendar/app/services/calendar/generate_ical_url.rbindex 00bb8d972e3..1df694c3c37 100644--- a/modules/calendar/app/services/calendar/generate_ical_url.rb+++ b/modules/calendar/app/services/calendar/generate_ical_url.rb@@ -29,18 +29,23 @@module Calendarclass GenerateIcalUrl < ::BaseServices::BaseCallable- def perform(user:, query_id:, project_id:)- new_ical_token = create_ical_token(user, query_id)- new_ical_url = create_ical_url(query_id, project_id, new_ical_token)-- ServiceResult.success(result: new_ical_url)+ def perform(user:, query_id:, project_id:, token_name:)+ begin+ new_ical_token = create_ical_token(user, query_id, token_name)+ new_ical_url = create_ical_url(query_id, project_id, new_ical_token)+ ServiceResult.success(result: new_ical_url)+ rescue => e+ # in case a the query is not found or the ical_token could not be created+ # an exception is raised which needs to be passed as a failure here+ ServiceResult.failure(message: e.message)+ endendprotected- def create_ical_token(user, query_id)+ def create_ical_token(user, query_id, token_name)query = Query.find(query_id)- Token::ICal.create_and_return_value(user, query)+ Token::ICal.create_and_return_value(user, query, token_name)enddef create_ical_url(query_id, project_id, ical_token)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.rbnew file mode 100644index 00000000000..64ec97557cb--- /dev/null+++ b/modules/calendar/db/migrate/20230502094813_add_name_to_ical_tokens.rb@@ -0,0 +1,8 @@+class AddNameToIcalTokens < ActiveRecord::Migration[7.0]+ def change+ # 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+enddiff --git a/modules/calendar/spec/services/resolve_and_authorize_query_spec.rb b/modules/calendar/spec/services/resolve_and_authorize_query_spec.rbindex 0a608990852..2942f24e066 100644--- a/modules/calendar/spec/services/resolve_and_authorize_query_spec.rb+++ b/modules/calendar/spec/services/resolve_and_authorize_query_spec.rb@@ -60,10 +60,14 @@ describe Calendar::ResolveAndAuthorizeQueryService, type: :model dopublic: false)endlet(:ical_token_instance_for_query1) do- Token::ICal.create(user: user, query: query1)+ Token::ICal.create(user: user,+ ical_token_query_assignment_attributes: { query: query1, name: "My Token" }+ )endlet(:ical_token_instance_for_query2) do- Token::ICal.create(user: user, query: query2)+ Token::ICal.create(user: user,+ ical_token_query_assignment_attributes: { query: query2, name: "My Token" }+ )endcontext 'if ical token belongs to query' do@@ -131,10 +135,14 @@ describe Calendar::ResolveAndAuthorizeQueryService, type: :model dopublic: false)endlet(:ical_token_instance_for_query1) do- Token::ICal.create(user: user, query: query1)+ Token::ICal.create(user: user,+ ical_token_query_assignment_attributes: { query: query1, name: "My Token" }+ )endlet(:ical_token_instance_for_query2) do- Token::ICal.create(user: user, query: query2)+ Token::ICal.create(user: user,+ ical_token_query_assignment_attributes: { query: query2, name: "My Token" }+ )endcontext 'if ical token belongs to query' do@@ -182,7 +190,9 @@ describe Calendar::ResolveAndAuthorizeQueryService, type: :model dopublic: false)endlet(:ical_token_instance_of_user_2_for_query1) do- Token::ICal.create(user: user2, query: query1)+ Token::ICal.create(user: user2,+ ical_token_query_assignment_attributes: { query: query1, name: "My Token" }+ )endcontext 'if ical token belongs to query' do@@ -212,7 +222,9 @@ describe Calendar::ResolveAndAuthorizeQueryService, type: :model dopublic: false)endlet(:ical_token_instance_for_query1) do- Token::ICal.create(user: user, query: query1)+ Token::ICal.create(user: user,+ ical_token_query_assignment_attributes: { query: query1, name: "My Token" }+ )endcontext 'if query id is invalid' dodiff --git a/modules/calendar/spec/services/resolve_ical_token_service_spec.rb b/modules/calendar/spec/services/resolve_ical_token_service_spec.rbindex 13e596efabb..aa00faa707a 100644--- a/modules/calendar/spec/services/resolve_ical_token_service_spec.rb+++ b/modules/calendar/spec/services/resolve_ical_token_service_spec.rb@@ -33,7 +33,7 @@ describe Calendar::ResolveIcalTokenService, type: :model dolet(:project) { create(:project) }let(:query) { create(:query, project:) }- let(:valid_ical_token_value) { Token::ICal.create_and_return_value(user, query) }+ let(:valid_ical_token_value) { Token::ICal.create_and_return_value(user, query, "My Token") }let(:invalid_ical_token_value) { valid_ical_token_value[0..-2] }let(:instance) dodiff --git a/spec/models/token/ical_token_spec.rb b/spec/models/token/ical_token_spec.rbindex 30c2e563872..f228b362d6b 100644--- a/spec/models/token/ical_token_spec.rb+++ b/spec/models/token/ical_token_spec.rb@@ -32,46 +32,160 @@ describe Token::ICal dolet(:user) { build(:user) }let(:project) { build(:project) }let(:query) { build(:query, project:) }+ let(:name) { 'unique_name' }it 'inherits from Token::HashedToken' doexpect(described_class).to be < Token::HashedTokenenddescribe 'in contrast to HashedToken' do- it 'needs to be assigned to a query' do+ it 'needs to be assigned to a query with a name' do# ical tokens are only valid for a specific query (scoped to a query)# thus an ical_token cannot be created without such an assignment- ical_token1 = described_class.create(user:)+ ical_token1 = described_class.create(user: user)- expect(ical_token1.errors[:base].first).to eq("IcalTokenQueryAssignment must exist")+ expect(ical_token1.errors[:ical_token_query_assignment].first).to eq("must exist")expect(described_class.where(user_id: user.id)).to be_empty++ # ical tokens need to have a name+ # thus an ical_token cannot be created without a name although a query is given+ ical_token2 = described_class.create(+ user: user,+ ical_token_query_assignment_attributes: { query: query, user_id: user.id }+ )++ expect(ical_token2.errors["ical_token_query_assignment.name"].first).to eq("can't be blank.")+ expect(described_class.where(user_id: user.id)).to be_empty++ # if a query and name is given, the token can be created+ ical_token3 = described_class.create(+ user: user,+ ical_token_query_assignment_attributes: { query: query, name: name, user_id: user.id}+ )+ expect(ical_token3.errors).to be_empty+ expect(ical_token3.query).to eq query+ expect(ical_token3.ical_token_query_assignment.name).to eq name+ expect(described_class.where(user_id: user.id)).to contain_exactly(+ ical_token3+ )end- it 'a user can have N ical tokens per query' do+ it 'a user can have N ical tokens per query with different names' do# Every time an ical url is generated, a new ical token will be generated for this url as well# the existing ical tokens (and thus urls) should still be valid# until the user decides to revert all existing ical tokens of a query# therefore a user needs to be allowed to have N ical tokens per query- ical_token1 = described_class.create(user:, query:)- ical_token2 = described_class.create(user:, query:)+ ical_token1 = described_class.create(+ user: user,+ ical_token_query_assignment_attributes: { query: query, name: "#{name}_1", user_id: user.id}+ )+ ical_token2 = described_class.create(+ user: user,+ ical_token_query_assignment_attributes: { query: query, name: "#{name}_2", user_id: user.id}+ )expect(described_class.where(user_id: user.id)).to contain_exactly(ical_token1, ical_token2)- query2 = build(:query, project:)+ query2 = create(:query, project: project)- ical_token3 = described_class.create(user:, query: query2)- ical_token4 = described_class.create(user:, query: query2)+ ical_token3 = described_class.create(+ user: user,+ ical_token_query_assignment_attributes: { query: query2, name: "#{name}_3", user_id: user.id}+ )+ ical_token4 = described_class.create(+ user: user,+ ical_token_query_assignment_attributes: { query: query2, name: "#{name}_4", user_id: user.id}+ )expect(described_class.where(user_id: user.id)).to contain_exactly(ical_token1, ical_token2, ical_token3, ical_token4)end++ it 'a user cannot have N ical tokens per query with the same name' do+ ical_token1 = described_class.create(+ user: user,+ ical_token_query_assignment_attributes: { query: query, name: "#{name}_1", user_id: user.id}+ )+ ical_token2 = described_class.create(+ user: user,+ ical_token_query_assignment_attributes: { query: query, name: "#{name}_1", user_id: user.id}+ )++ expect(ical_token2.errors["ical_token_query_assignment.name"].first).to eq(+ "has already been taken for this query and user"+ )++ expect(described_class.where(user_id: user.id)).to contain_exactly(+ ical_token1+ )++ # name can be used for another query though:++ query2 = create(:query, project: project)++ ical_token3 = described_class.create(+ user: user,+ ical_token_query_assignment_attributes: { query: query2, name: "#{name}_1", user_id: user.id}+ )++ expect(described_class.where(user_id: user.id)).to contain_exactly(+ ical_token1, ical_token3+ )+ end++ describe '#create_and_return_value method' do+ it 'expects the query and token name and returns a token value' do+ expect do+ ical_token1_value = described_class.create_and_return_value(+ user,+ query,+ name+ )+ end.to change { described_class.where(user_id: user.id).count }.by(1)+++ ical_token1 = described_class.where(user_id: user.id).last++ expect(described_class.find_by_plaintext_value(ical_token1_value)).to eq ical_token1++ expect(ical_token1.query).to eq query+ expect(ical_token1.ical_token_query_assignment.name).to eq name+ end++ it 'does not return a token value if token was not successfully persisted' do+ expect do+ ical_token1_value = described_class.create_and_return_value(+ user,+ query,+ name+ )+ # same name cannot be used twice for the same query and user+ # -> token will not be persisted and no value should be returned+ ical_token2_value = described_class.create_and_return_value(+ user,+ query,+ name+ )+ end.to change { described_class.where(user_id: user.id).count }.by(1)++ expect(ical_token1_value).to be_present+ expect(ical_token2_value).to be_nil++ ical_token1 = described_class.where(user_id: user.id).last+ expect(described_class.find_by_plaintext_value(ical_token1_value)).to eq ical_token1+ expect(described_class.find_by_plaintext_value(ical_token2_value)).to be_nil+ end+ endenddescribe 'behaves like Token::HashedToken if created with query assignment' do- subject { described_class.new user:, query: }+ subject { described_class.new(+ user: user,+ ical_token_query_assignment_attributes: { query: query, name: name, user_id: user.id}+ )}# TODO: following code is copy pasted from hashed_token_spec# in order to make sure the token behaves in the same way in it's basics