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
Save trial key in db to get user data from Augur
Inga Maiafd66b175622
diff --git a/app/controllers/enterprises_controller.rb b/app/controllers/enterprises_controller.rbindex 7fa9b74823c..96850fef502 100644--- a/app/controllers/enterprises_controller.rb+++ b/app/controllers/enterprises_controller.rb@@ -31,6 +31,8 @@ class EnterprisesController < ApplicationControllerlayout 'admin'menu_item :enterprise+ helper_method :gon+before_action :augur_content_security_policybefore_action :chargebee_content_security_policybefore_action :youtube_content_security_policy@@ -40,6 +42,10 @@ class EnterprisesController < ApplicationControllerdef show@current_token = EnterpriseToken.current@token = @current_token || EnterpriseToken.new++ if @current_token.blank?+ initialize_gon+ endenddef create@@ -59,6 +65,20 @@ class EnterprisesController < ApplicationControllerendend+ def create_trial_key+ @trial_key = params[:trial_key]+ Token::EnterpriseTrialToken.create(user_id: current_user.id, value: @trial_key)+ end++ def initialize_gon+ @trial_key = Token::EnterpriseTrialToken.find_by!(user_id: current_user.id)+ if @trial_key+ gon.ee_trial_key = {+ value: @trial_key.value+ }+ end+ end+privatedef default_breadcrumbdiff --git a/app/models/token/enterprise_trial_token.rb b/app/models/token/enterprise_trial_token.rbnew file mode 100644index 00000000000..0a06d4c096c--- /dev/null+++ b/app/models/token/enterprise_trial_token.rb@@ -0,0 +1,41 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2020 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-2017 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 docs/COPYRIGHT.rdoc for more details.+#++++require_dependency 'token/base'++module Token+ class EnterpriseTrialToken < Base+ include ExpirableToken++ def self.validity_time+ 1.days+ end+ end+enddiff --git a/app/views/enterprises/_current.html.erb b/app/views/enterprises/_current.html.erbindex b34724c4b25..6438288896c 100644--- a/app/views/enterprises/_current.html.erb+++ b/app/views/enterprises/_current.html.erb@@ -1,6 +1,6 @@<enterprise-active-trial data-subscriber="<%= @current_token.subscriber %>"data-email="<%= @current_token.mail %>"- data-restrictions="<%= @current_token.restrictions %>"+ data-user-count="<%= @current_token.restrictions[:active_user_count] %>"data-starts-at="<%= format_date @current_token.starts_at %>"data-expires-at="<%= format_date @current_token.expires_at %>"></enterprise-active-trial>diff --git a/app/views/enterprises/_info.html.erb b/app/views/enterprises/_info.html.erbindex b430f42b6b3..21e5187d6f7 100644--- a/app/views/enterprises/_info.html.erb+++ b/app/views/enterprises/_info.html.erb@@ -32,6 +32,10 @@ See docs/COPYRIGHT.rdoc for more details.</script><% end %>+<%= nonced_javascript_tag do %>+ <%= include_gon(need_tag: false) -%>+<% end %>+<enterprise-base></enterprise-base><div class='upsale--actions'>diff --git a/config/locales/js-en.yml b/config/locales/js-en.ymlindex cae48321968..6bd63abb251 100644--- a/config/locales/js-en.yml+++ b/config/locales/js-en.yml@@ -204,7 +204,7 @@ en:label_status:email_not_received: "You did not receive an email? Resend email or"try_another_email: "try with another email address"- try_another_email_hint: "Please be aware that your old email and confirmation link gets invalid if you try again with a new one."+ try_another_email_hint: "Please be aware that your previous email address gets invalid if you try again with a new one."next_steps: "Next steps"next_step: "In the next step we will send you an email to the email-address provided."resend_link: "Resend"diff --git a/config/routes.rb b/config/routes.rbindex bc644b0b215..f8741dae1f3 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -340,6 +340,9 @@ OpenProject::Application.routes.draw doresource :announcements, only: %i[edit update]constraints(Enterprise) doresource :enterprise, only: %i[show create destroy]+ scope controller: 'enterprises' do+ post 'enterprise/create_trial_key' => 'enterprises#create_trial_key'+ endendresources :enumerationsdiff --git a/frontend/src/app/components/enterprise/enterprise-active-trial/ee-active-trial.component.html b/frontend/src/app/components/enterprise/enterprise-active-trial/ee-active-trial.component.htmlindex f4620e10c5a..fb1878b81c5 100644--- a/frontend/src/app/components/enterprise/enterprise-active-trial/ee-active-trial.component.html+++ b/frontend/src/app/components/enterprise/enterprise-active-trial/ee-active-trial.component.html@@ -13,15 +13,14 @@<span>{{ email }}</span></div></div>- <!-- TODO % Hash(@current_token.restrictions).each do |key, value| %-->- <div class="attributes-key-value--key">{{ text.label_maximum_users}}</div>- <div class="attributes-key-value--value-container">+ <div *ngIf="userCount" class="attributes-key-value--key">{{ text.label_maximum_users }}</div>+ <div *ngIf="userCount" class="attributes-key-value--value-container"><div class="attributes-key-value--value -text">- <span>10</span>+ <span>{{ userCount }}</span></div></div>- <div class="attributes-key-value--key">{{ text.label_starts_at }}</div>- <div class="attributes-key-value--value-container">+ <div *ngIf="startsAt" class="attributes-key-value--key">{{ text.label_starts_at }}</div>+ <div *ngIf="startsAt" class="attributes-key-value--value-container"><div class="attributes-key-value--value -text"><span>{{ startsAt }}</span></div>diff --git a/frontend/src/app/components/enterprise/enterprise-active-trial/ee-active-trial.component.ts b/frontend/src/app/components/enterprise/enterprise-active-trial/ee-active-trial.component.tsindex 048330e1688..5c908e9e997 100644--- a/frontend/src/app/components/enterprise/enterprise-active-trial/ee-active-trial.component.ts+++ b/frontend/src/app/components/enterprise/enterprise-active-trial/ee-active-trial.component.ts@@ -46,7 +46,7 @@ export class EEActiveTrialComponent implements OnInit {};public subscriber = this.elementRef.nativeElement.dataset['subscriber'];public email = this.elementRef.nativeElement.dataset['email'];- public restrictions = this.elementRef.nativeElement.dataset['restrictions'];+ public userCount = this.elementRef.nativeElement.dataset['userCount'];public startsAt = this.elementRef.nativeElement.dataset['startsAt'];public expiresAt = this.elementRef.nativeElement.dataset['expiresAt'];@@ -56,14 +56,14 @@ export class EEActiveTrialComponent implements OnInit {}ngOnInit() {- // TODO iterate over all restrictions- console.log('restrictions: ', this.restrictions);// trial is not active yetif (!this.subscriber) {- this.subscriber = this.eeTrialService.savedUserData.subscriber;- this.email = this.eeTrialService.savedUserData.email;- this.startsAt = '-';- this.expiresAt = '-';+ // get user data from service+ setTimeout(() => {+ let savedData = this.eeTrialService.trialForm.value;+ this.subscriber = savedData.first_name + ' ' + savedData.last_name;+ this.email = savedData.email;+ }, 500);}}}diff --git a/frontend/src/app/components/enterprise/enterprise-base.component.html b/frontend/src/app/components/enterprise/enterprise-base.component.htmlindex 184886cbe70..7ce8341d454 100644--- a/frontend/src/app/components/enterprise/enterprise-base.component.html+++ b/frontend/src/app/components/enterprise/enterprise-base.component.html@@ -3,7 +3,7 @@{{ text.you_contribute }}</p>-<div *ngIf="eeTrialService.status === 'mailSubmitted'">+<div *ngIf="eeTrialService.status"><enterprise-trial-waiting></enterprise-trial-waiting><p class="confirmation-hint">{{ text.email_not_received }}<a (click)="openTrialModal()">{{ text.try_another_email }}.</a><br>diff --git a/frontend/src/app/components/enterprise/enterprise-base.component.ts b/frontend/src/app/components/enterprise/enterprise-base.component.tsindex 5d6250bd06e..ee811393165 100644--- a/frontend/src/app/components/enterprise/enterprise-base.component.ts+++ b/frontend/src/app/components/enterprise/enterprise-base.component.ts@@ -59,7 +59,7 @@ export class EnterpriseBaseComponent {public openTrialModal() {// cancel request and open first modal windowthis.eeTrialService.cancelled = true;- this.eeTrialService.status = undefined;+ this.eeTrialService.modalOpen = true;this.opModalService.show(EnterpriseTrialModal, this.injector);}}diff --git a/frontend/src/app/components/enterprise/enterprise-modal/enterprise-trial.modal.html b/frontend/src/app/components/enterprise/enterprise-modal/enterprise-trial.modal.htmlindex 042bf33a43c..a17e2e90a19 100644--- a/frontend/src/app/components/enterprise/enterprise-modal/enterprise-trial.modal.html+++ b/frontend/src/app/components/enterprise/enterprise-modal/enterprise-trial.modal.html@@ -12,11 +12,11 @@<div class="op-modal--modal-body"><!-- first modal window -->- <div *ngIf="!eeTrialService.status">+ <div *ngIf="!eeTrialService.status || eeTrialService.cancelled"><enterprise-trial-form></enterprise-trial-form></div><!-- second modal window -->- <div *ngIf="eeTrialService.status === 'mailSubmitted'">+ <div *ngIf="eeTrialService.status === 'mailSubmitted' && !eeTrialService.cancelled"><enterprise-trial-waiting></enterprise-trial-waiting></div><!-- third modal window -->@@ -38,13 +38,13 @@</div><div class="op-modal--modal-footer">- <div *ngIf="!eeTrialService.status; else mailSubmitted">+ <div *ngIf="!eeTrialService.status || eeTrialService.cancelled; else mailSubmitted"><button class="confirm-form-submit--continue button -highlight"(click)="onSubmit()"[disabled]="!trialForm || trialForm.invalid"[textContent]="text.button_submit"[attr.title]="text.button_submit"- [hidden]="eeTrialService.status === 'mailSubmitted'">+ [hidden]="eeTrialService.status === 'mailSubmitted' && !eeTrialService.cancelled"></button><button class="confirm-form-submit--cancel button"(click)="closeModal($event)"diff --git a/frontend/src/app/components/enterprise/enterprise-modal/enterprise-trial.modal.ts b/frontend/src/app/components/enterprise/enterprise-modal/enterprise-trial.modal.tsindex 8312ee14c5d..73e7f688ce5 100644--- a/frontend/src/app/components/enterprise/enterprise-modal/enterprise-trial.modal.ts+++ b/frontend/src/app/components/enterprise/enterprise-modal/enterprise-trial.modal.ts@@ -115,6 +115,7 @@ export class EnterpriseTrialModal extends OpModalComponent implements AfterViewIif (this.eeTrialService.status === 'startTrial' || this.eeTrialService.confirmed) {window.location.reload();}+ this.eeTrialService.modalOpen = false;}public trustedEEVideoURL() {diff --git a/frontend/src/app/components/enterprise/enterprise-trial.service.ts b/frontend/src/app/components/enterprise/enterprise-trial.service.tsindex 02e8942e440..32745836ad0 100644--- a/frontend/src/app/components/enterprise/enterprise-trial.service.ts+++ b/frontend/src/app/components/enterprise/enterprise-trial.service.ts@@ -3,57 +3,63 @@ import {I18nService} from "core-app/modules/common/i18n/i18n.service";import {HttpClient, HttpErrorResponse} from "@angular/common/http";import {PathHelperService} from "core-app/modules/common/path-helper/path-helper.service";import {NotificationsService} from "core-app/modules/common/notifications/notifications.service";-import {FormBuilder, FormControl, FormGroup} from "@angular/forms";+import {FormBuilder, FormGroup} from "@angular/forms";@Injectable()export class EnterpriseTrialService {- private localStorageKey = 'openProject-enterprise-trial';-public text = {resend_success: this.I18n.t('js.admin.enterprise.trial.resend_success'),resend_warning: this.I18n.t('js.admin.enterprise.trial.resend_warning')};- public savedUserData:any; // saved data in local storagepublic trialForm:FormGroup;+ public initialData:any;public baseUrlAugur = 'https://augur.openproject-edge.com';public trialLink:string;public resendLink:string;+ public modalOpen = false;public confirmed:boolean;public cancelled = false;public status:'mailSubmitted'|'startTrial'|undefined;public errorMsg:string|undefined;+ // retry confirmation+ private delay = 5000; // wait 5s until next request+ private retries = 60; // keep trying for 5 minutes+constructor(readonly I18n:I18nService,protected http:HttpClient,readonly pathHelper:PathHelperService,protected notificationsService:NotificationsService,readonly formBuilder:FormBuilder) {- this.savedUserData = window.OpenProject.guardedLocalStorage(this.localStorageKey);+ this.initialize();+ }++ // check if a user already submitted user data+ // initialize the trial form with this data saved in Augur+ private initialize():void {+ this.initialData = this.loadGonData();// user has already submitted a valid mail and received a confirmation link- if (this.savedUserData) {- this.savedUserData = JSON.parse(this.savedUserData);- this.resendLink = this.savedUserData.resend_link;- this.status = 'mailSubmitted';+ if (this.initialData) {+ this.trialLink = this.baseUrlAugur + '/public/v1/trials/' + this.initialData.value;+ this.getUserDataFromAugur(this.initialData.value);}}- // sends POST request with form object- // receives an enterprise trial link to access a token+ // send POST request with form object+ // receive an enterprise trial link to access a tokenpublic sendForm(form:FormGroup) {this.trialForm = form;- const delay = 5000; // wait 5s until next request- const retries = 60; // keep trying for 5 minutes// POST /public/v1/trials/- this.http.post(this.baseUrlAugur + '/public/v1/trials', form.value)+ this.http.post(this.baseUrlAugur + '/public/v1/trials', this.trialForm.value).toPromise().then((enterpriseTrial:any) => {this.trialLink = enterpriseTrial._links.self.href;- this.retryConfirmation(delay, retries);+ this.retryConfirmation(this.delay, this.retries);}).catch((error:HttpErrorResponse) => {// mail is invalid or user already created a trial@@ -66,62 +72,85 @@ export class EnterpriseTrialService {});}- // gets a token from the trial link if user confirmed mail+ // get a token from the trial link if user confirmed mailprivate getToken() {// 2) GET /public/v1/trials/:idthis.http- .get<any>(this.baseUrlAugur + this.trialLink)+ .get<any>(this.trialLink).toPromise().then((res:any) => {// show confirmed status and enable continue btnthis.confirmed = true;+ // TODO: delete user data from gon;+ (window as any).gon.ee_trial_key = undefined;// returns token if mail was confirmed// -> if token is new (token_retrieved: false) save token in backendif (!res.token_retrieved) {this.saveToken(res.token);}++ // load page if mail was confirmed and modal window is not open+ if (!this.modalOpen) {+ setTimeout(() => { // display confirmed status before reloading+ window.location.reload();+ }, 500);+ }}).catch((error:HttpErrorResponse) => {// returns error 422 while waiting of confirmationif (error.status === 422 && error.error.identifier === 'waiting_for_email_verification') {+ // get resend button link+ this.resendLink = error.error._links.resend.href;+ // save a key for the requested trial+ if (!this.status) { // only do it once+ this.saveTrialKey(this.resendLink);+ }// open next modal window -> status waitingthis.status = 'mailSubmitted';this.confirmed = false;-- // get resend button link- this.resendLink = error.error._links.resend.href;-- this.savedUserData = {- 'subscriber': this.trialForm.value.first_name + ' ' + this.trialForm.value.last_name,- 'email': this.trialForm.value.email,- 'resend_link': this.resendLink- };- window.OpenProject.guardedLocalStorage(this.localStorageKey, JSON.stringify(this.savedUserData));-} else if (_.get(error, 'error._type') === 'Error') {- this.notificationsService.addWarning(error.error.message);+ this.notificationsService.addError(error.error.message);} else {// backend returned an unsuccessful response code- this.notificationsService.addWarning(error.error || I18n.t('js.error.internal'));+ this.notificationsService.addError(error.error || I18n.t('js.error.internal'));}});}- // saves received token in controller+ // save a part of the resend link in db+ // which allows to remember if a user has already requested a trial token+ // and to ask for the corresponding user data saved in Augur+ private saveTrialKey(resendlink:string) {+ // extract token from resend link+ let trialKey = resendlink.split('/')[6];+ // save requested token+ return this.http.post(+ this.pathHelper.api.v3.appBasePath + '/admin/enterprise/create_trial_key',+ { trial_key: trialKey },+ { withCredentials: true }+ )+ .toPromise()+ .catch((e:any) => {+ this.notificationsService.addError(e.error.message || e.message || e);+ });+ }++ // save received token in controllerprivate saveToken(token:string) {// POST /admin/enterprise (params[:enterprise_token][:encoded_token])- this.http.post(this.pathHelper.api.v3.appBasePath + '/admin/enterprise', { enterprise_token: { encoded_token: token } }, { withCredentials: true })+ this.http.post(+ this.pathHelper.api.v3.appBasePath + '/admin/enterprise',+ { enterprise_token: { encoded_token: token } },+ { withCredentials: true }+ ).toPromise()- .then((res:any) => {- window.localStorage.removeItem(this.localStorageKey);- }).catch((error:HttpErrorResponse) => {- this.notificationsService.addWarning(error.error || I18n.t('js.error.internal'));+ this.notificationsService.addError(error.error || I18n.t('js.error.internal'));});}- // retries request while waiting for mail confirmation+ // retry request while waiting for mail confirmationpublic retryConfirmation(delay:number, retries:number) {if (this.cancelled || this.confirmed) {// stop if action was cancelled or confirmation link was clicked@@ -138,18 +167,42 @@ export class EnterpriseTrialService {}}- // resends mail if resend link has been clicked+ // resend mail if resend link has been clickedpublic resendMail() {- this.http.post(this.baseUrlAugur + this.resendLink, {})+ this.http.post(this.resendLink, {}).toPromise()- .then((enterpriseTrial:any) => {+ .then(() => {this.notificationsService.addSuccess(this.text.resend_success);this.cancelled = false;- this.retryConfirmation(5000, 60);+ this.retryConfirmation(this.delay, this.retries);}).catch((error:HttpErrorResponse) => {- this.notificationsService.addWarning(this.text.resend_warning);+ this.cancelled = false;+ this.notificationsService.addError(this.text.resend_warning);});}++ // use the trial key saved in the db+ // to get the user data from Augur+ private getUserDataFromAugur(trialKey:string) {+ this.http+ .get<any>(this.baseUrlAugur + '/public/v1/trials/' + trialKey + '/details')+ .toPromise()+ .then((userData:any) => {+ this.trialForm = this.formBuilder.group(userData);+ this.retryConfirmation(this.delay, this.retries);+ })+ .catch((error:HttpErrorResponse) => {+ this.cancelled = true;+ });+ }++ private loadGonData():{value:string}|null {+ try {+ return (window as any).gon.ee_trial_key;+ } catch (e) {+ return null;+ }+ }}\ No newline at end of file