From 5ccfb4f4080c3dcde8af8f8096fd2ebb0fb53fd1 Mon Sep 17 00:00:00 2001 From: Harvey Kandola Date: Thu, 23 Jun 2016 20:31:45 -0700 Subject: [PATCH 01/32] forked https://github.com/documize/ember-simple-auth --- app/package.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/package.json b/app/package.json index 81dfd832..67574b1b 100644 --- a/app/package.json +++ b/app/package.json @@ -39,6 +39,7 @@ "ember-export-application-global": "^1.0.5", "ember-load-initializers": "^0.5.1", "ember-resolver": "^2.0.3", + "ember-simple-auth": "git+https://github.com/documize/ember-simple-auth.git#21e638f9e33267d8944835002ee96884d34d568a", "loader.js": "^4.0.1" }, "ember-addon": { @@ -46,4 +47,4 @@ "lib/intercom" ] } -} \ No newline at end of file +} From c4404bc7b0876fe3e69158372bf0b6f2d89e631b Mon Sep 17 00:00:00 2001 From: Harvey Kandola Date: Sat, 25 Jun 2016 10:37:19 -0700 Subject: [PATCH 02/32] Create ajax.js --- app/app/services/ajax.js | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 app/app/services/ajax.js diff --git a/app/app/services/ajax.js b/app/app/services/ajax.js new file mode 100644 index 00000000..7f1a15ea --- /dev/null +++ b/app/app/services/ajax.js @@ -0,0 +1,7 @@ +import AjaxService from 'ember-ajax/services/ajax'; +import config from '../config/environment'; + +export default AjaxService.extend({ + host: config.host, + namespace: config.namespace +}); From e25fb2dce5da91f23bf17d77fb16758648dfe6f9 Mon Sep 17 00:00:00 2001 From: Harvey Kandola Date: Sat, 25 Jun 2016 10:37:44 -0700 Subject: [PATCH 03/32] Create app-meta.js --- app/app/services/app-meta.js | 40 ++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 app/app/services/app-meta.js diff --git a/app/app/services/app-meta.js b/app/app/services/app-meta.js new file mode 100644 index 00000000..d1b89f19 --- /dev/null +++ b/app/app/services/app-meta.js @@ -0,0 +1,40 @@ +import Ember from 'ember'; +import config from '../config/environment'; + +const { + String: { htmlSafe }, + RSVP: { resolve }, + inject: { service } +} = Ember; + +export default Ember.Service.extend({ + ajax: service(), + + url: `${config.apiHost}/${config.apiNamespace}`, + orgId: '', + title: '', + version: '', + message: '', + allowAnonymousAccess: false, + + boot() { + let dbhash; + if (is.not.null(document.head.querySelector("[property=dbhash]"))) { + dbhash = document.head.querySelector("[property=dbhash]").content; + } + + let isInSetupMode = dbhash && dbhash !== "{{.DBhash}}"; + if (isInSetupMode) { + this.setProperites({ + title: htmlSafe("Documize Setup"), + allowAnonymousAccess: false + }); + return resolve(); + } + + return this.get('ajax').request('public/meta') + .then((response) => { + this.setProperties(response); + }); + } +}); From 7e31b459b32a571383b60ffda3bd9ba5b50211d4 Mon Sep 17 00:00:00 2001 From: Harvey Kandola Date: Sat, 25 Jun 2016 10:38:41 -0700 Subject: [PATCH 04/32] Update session.js --- app/app/services/session.js | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/app/app/services/session.js b/app/app/services/session.js index 53599916..dee0fac4 100644 --- a/app/app/services/session.js +++ b/app/app/services/session.js @@ -194,5 +194,25 @@ export default Ember.Service.extend({ }); } }); + + let token = this.getSessionItem('token'); + + // TODO: the rest should be done through ESA + if (is.not.undefined(token)) { + // We now validate current token + + return this.get('ajax').request(`public/validate?token=${token}`, { + method: 'GET', + contentType: 'json' + }).then((user) => { + this.setSession(token, models.UserModel.create(user)); + this.set('ready', true); + }).catch((reason) => { + if (netUtil.isAjaxAccessError(reason)) { + localStorage.clear(); + window.location.href = "/auth/login"; + } + }); + } } }); From 86aaead1ce90594f4d1bfcf6cf5872d2b30da003 Mon Sep 17 00:00:00 2001 From: Harvey Kandola Date: Sat, 25 Jun 2016 10:39:50 -0700 Subject: [PATCH 05/32] Update application.js --- app/app/routes/application.js | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/app/app/routes/application.js b/app/app/routes/application.js index bdc1c112..872ca6e5 100644 --- a/app/app/routes/application.js +++ b/app/app/routes/application.js @@ -12,9 +12,15 @@ import Ember from 'ember'; import netUtil from '../utils/net'; +const { + inject: { service } +} = Ember; + export default Ember.Route.extend({ - userService: Ember.inject.service('user'), - sessionService: Ember.inject.service('session'), + userService: service('user'), + sessionService: service('session'), + appMeta: service(), + transitioning: false, beforeModel: function(transition) { @@ -22,7 +28,7 @@ export default Ember.Route.extend({ let session = this.get('sessionService'); // Session ready? - return session.boot().then(function() { + return this.get('appMeta').boot().then(function() { // Need to authenticate? if (!session.get("appMeta.allowAnonymousAccess") && !session.get("authenticated") && is.not.startWith(transition.targetName, 'auth.')) { From 69c760d35113d5d69ed583697730d2653ebbc56b Mon Sep 17 00:00:00 2001 From: zinyando Date: Mon, 27 Jun 2016 14:42:37 +0200 Subject: [PATCH 06/32] Correct apiHost and apiNamespace in ajax service --- app/app/services/ajax.js | 4 ++-- app/config/environment.js | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/app/app/services/ajax.js b/app/app/services/ajax.js index 7f1a15ea..0f44201d 100644 --- a/app/app/services/ajax.js +++ b/app/app/services/ajax.js @@ -2,6 +2,6 @@ import AjaxService from 'ember-ajax/services/ajax'; import config from '../config/environment'; export default AjaxService.extend({ - host: config.host, - namespace: config.namespace + host: config.apiHost, + namespace: config.apiNamespace }); diff --git a/app/config/environment.js b/app/config/environment.js index dd786758..79c01dda 100644 --- a/app/config/environment.js +++ b/app/config/environment.js @@ -44,6 +44,7 @@ module.exports = function(environment) { }; ENV.apiHost = "https://localhost:5001"; + ENV.apiNamespace = "api"; } if (environment === 'test') { From 7cce377f93a2f0085e794599cb74a5be7fdec386 Mon Sep 17 00:00:00 2001 From: zinyando Date: Mon, 27 Jun 2016 14:47:48 +0200 Subject: [PATCH 07/32] Clean up --- app/app/services/app-meta.js | 2 +- app/app/services/session.js | 40 ++++++++++++++++++------------------ 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/app/app/services/app-meta.js b/app/app/services/app-meta.js index d1b89f19..b93b127d 100644 --- a/app/app/services/app-meta.js +++ b/app/app/services/app-meta.js @@ -33,7 +33,7 @@ export default Ember.Service.extend({ } return this.get('ajax').request('public/meta') - .then((response) => { + .then((response) => { this.setProperties(response); }); } diff --git a/app/app/services/session.js b/app/app/services/session.js index dee0fac4..80bceaf0 100644 --- a/app/app/services/session.js +++ b/app/app/services/session.js @@ -139,6 +139,26 @@ export default Ember.Service.extend({ // Application boot process boot() { + let token = this.getSessionItem('token'); + + // TODO: the rest should be done through ESA + if (is.not.undefined(token)) { + // We now validate current token + + return this.get('ajax').request(`public/validate?token=${token}`, { + method: 'GET', + contentType: 'json' + }).then((user) => { + this.setSession(token, models.UserModel.create(user)); + this.set('ready', true); + }).catch((reason) => { + if (netUtil.isAjaxAccessError(reason)) { + localStorage.clear(); + window.location.href = "/auth/login"; + } + }); + } + let self = this; let dbhash = ""; @@ -194,25 +214,5 @@ export default Ember.Service.extend({ }); } }); - - let token = this.getSessionItem('token'); - - // TODO: the rest should be done through ESA - if (is.not.undefined(token)) { - // We now validate current token - - return this.get('ajax').request(`public/validate?token=${token}`, { - method: 'GET', - contentType: 'json' - }).then((user) => { - this.setSession(token, models.UserModel.create(user)); - this.set('ready', true); - }).catch((reason) => { - if (netUtil.isAjaxAccessError(reason)) { - localStorage.clear(); - window.location.href = "/auth/login"; - } - }); - } } }); From 10dbeeefbb44ec890a09d11359a57b8ac88f5a24 Mon Sep 17 00:00:00 2001 From: zinyando Date: Tue, 28 Jun 2016 15:29:29 +0200 Subject: [PATCH 08/32] Refactor to use ember-ajax host and namespace --- app/app/services/document.js | 59 ++++++++++++-------------------- app/app/services/folder.js | 34 ++++++------------ app/app/services/organization.js | 7 ++-- app/app/services/search.js | 2 +- app/app/services/section.js | 9 ++--- app/app/services/session.js | 12 +++---- app/app/services/template.js | 16 +++------ app/app/services/user.js | 21 +++++------- 8 files changed, 57 insertions(+), 103 deletions(-) diff --git a/app/app/services/document.js b/app/app/services/document.js index e8e38766..49df0ae5 100644 --- a/app/app/services/document.js +++ b/app/app/services/document.js @@ -18,9 +18,7 @@ export default Ember.Service.extend({ // Returns document model for specified document id. getDocument(documentId) { - let url = this.get('sessionService').appMeta.getUrl(`documents/${documentId}`); - - return this.get('ajax').request(url, { + return this.get('ajax').request(`documents/${documentId}`, { method: "GET" }).then((response) => { return models.DocumentModel.create(response); @@ -29,10 +27,7 @@ export default Ember.Service.extend({ // Returns all documents for specified folder. getAllByFolder(folderId) { - let appMeta = this.get('sessionService.appMeta'); - let url = appMeta.getUrl(`documents?folder=${folderId}`); - - return this.get('ajax').request(url, { + return this.get('ajax').request(`documents?folder=${folderId}`, { method: "GET" }).then((response) => { let documents = Ember.ArrayProxy.create({ @@ -50,9 +45,7 @@ export default Ember.Service.extend({ // getDocumentsByTag returns all documents for specified tag (not folder!). getAllByTag(tag) { - let url = this.get('sessionService').appMeta.getUrl(`documents?filter=tag&tag=${tag}`); - - return this.get('ajax').request(url, { + return this.get('ajax').request(`documents?filter=tag&tag=${tag}`, { method: "GET" }).then((response) => { let documents = Ember.ArrayProxy.create({ @@ -71,16 +64,15 @@ export default Ember.Service.extend({ // saveDocument updates an existing document record. save(doc) { let id = doc.get('id'); - let url = this.get('sessionService').appMeta.getUrl(`documents/${id}`); - return this.get('ajax').request(url, { + return this.get('ajax').request(`documents/${id}`, { method: 'PUT', data: JSON.stringify(doc) }); }, getBatchedPages: function(documentId, payload) { - let url = this.get('sessionService').appMeta.getUrl("documents/" + documentId + "/pages/batch"); + let url = `documents/${documentId}/pages/batch`; return this.get('ajax').request(url, { method: 'POST', @@ -95,7 +87,7 @@ export default Ember.Service.extend({ }, changePageSequence: function(documentId, payload) { - var url = this.get('sessionService').appMeta.getUrl("documents/" + documentId + "/pages/sequence"); + let url = `documents/${documentId}/pages/sequence`; return this.get('ajax').post(url, { data: JSON.stringify(payload), @@ -104,7 +96,7 @@ export default Ember.Service.extend({ }, changePageLevel(documentId, payload) { - let url = this.get('sessionService').appMeta.getUrl("documents/" + documentId + "/pages/level"); + let url = `documents/${documentId}/pages/level`; return this.get('ajax').post(url, { data: JSON.stringify(payload), @@ -113,7 +105,7 @@ export default Ember.Service.extend({ }, deleteDocument: function(documentId) { - let url = this.get('sessionService').appMeta.getUrl("documents/" + documentId); + let url = `documents/${documentId}`; return this.get('ajax').request(url, { method: 'DELETE' @@ -122,7 +114,7 @@ export default Ember.Service.extend({ updatePage: function(documentId, pageId, payload, skipRevision) { var revision = skipRevision ? "?r=true" : "?r=false"; - let url = this.get('sessionService').appMeta.getUrl("documents/" + documentId + "/pages/" + pageId + revision); + let url = `documents/${documentId}/pages/${pageId}${revision}` return this.get('ajax').request(url, { method: 'PUT', @@ -133,7 +125,7 @@ export default Ember.Service.extend({ // addPage inserts new page to an existing document. addPage: function(documentId, payload) { - let url = this.get('sessionService').appMeta.getUrl("documents/" + documentId + "/pages"); + let url = `documents/${documentId}/pages`; return this.get('ajax').post(url, { data: JSON.stringify(payload), @@ -143,7 +135,7 @@ export default Ember.Service.extend({ // Nukes multiple pages from the document. deletePages: function(documentId, pageId, payload) { - let url = this.get('sessionService').appMeta.getUrl("documents/" + documentId + "/pages/" + pageId); + let url = `documents/${documentId}/pages/${pageId}`; return this.get('ajax').post(url, { data: JSON.stringify(payload), @@ -153,7 +145,7 @@ export default Ember.Service.extend({ // Nukes a single page from the document. deletePage: function(documentId, pageId) { - let url = this.get('sessionService').appMeta.getUrl("documents/" + documentId + "/pages/" + pageId); + let url = `documents/${documentId}/pages/${pageId}`; return this.get('ajax').request(url, { method: 'DELETE' @@ -161,7 +153,7 @@ export default Ember.Service.extend({ }, getPageRevisions(documentId, pageId) { - let url = this.get('sessionService').appMeta.getUrl("documents/" + documentId + "/pages/" + pageId + "/revisions"); + let url = `documents/${documentId}/pages/${pageId}/revisions`; return this.get('ajax').request(url, { method: "GET" @@ -169,7 +161,7 @@ export default Ember.Service.extend({ }, getPageRevisionDiff(documentId, pageId, revisionId) { - let url = this.get('sessionService').appMeta.getUrl("documents/" + documentId + "/pages/" + pageId + "/revisions/" + revisionId); + let url = `documents/${documentId}/pages/${pageId}/revisions/${revisionId}`; return this.get('ajax').request(url, { method: "GET", @@ -178,7 +170,7 @@ export default Ember.Service.extend({ }, rollbackPage(documentId, pageId, revisionId) { - let url = this.get('sessionService').appMeta.getUrl("documents/" + documentId + "/pages/" + pageId + "/revisions/" + revisionId); + let url = `documents/${documentId}/pages/${pageId}/revisions/${revisionId}`; return this.get('ajax').request(url, { method: "POST" @@ -187,18 +179,16 @@ export default Ember.Service.extend({ // document meta referes to number of views, edits, approvals, etc. getMeta(documentId) { - let url = this.get('sessionService').appMeta.getUrl(`documents/${documentId}/meta`); - return this.get('ajax').request(url, { + return this.get('ajax').request(`documents/${documentId}/meta`, { method: "GET" }); }, // Returns all pages without the content getTableOfContents(documentId) { - let url = this.get('sessionService').appMeta.getUrl(`documents/${documentId}/pages?content=0`); - return this.get('ajax').request(url, { + return this.get('ajax').request(`documents/${documentId}/pages?content=0`, { method: 'GET' }).then((response) => { let data = []; @@ -212,9 +202,8 @@ export default Ember.Service.extend({ // Returns all document pages with content getPages(documentId) { - let url = this.get('sessionService').appMeta.getUrl(`documents/${documentId}/pages`); - return this.get('ajax').request(url, { + return this.get('ajax').request(`documents/${documentId}/pages`, { method: 'GET' }).then((response) => { let pages = []; @@ -229,9 +218,8 @@ export default Ember.Service.extend({ // Returns document page with content getPage(documentId, pageId) { - let url = this.get('sessionService').appMeta.getUrl(`documents/${documentId}/pages/${pageId}`); - return this.get('ajax').request(url, { + return this.get('ajax').request(`documents/${documentId}/pages/${pageId}`, { method: 'GET' }).then((response) => { let page = models.PageModel.create(response); @@ -241,9 +229,8 @@ export default Ember.Service.extend({ // Returns document page meta object getPageMeta(documentId, pageId) { - let url = this.get('sessionService').appMeta.getUrl(`documents/${documentId}/pages/${pageId}/meta`); - return this.get('ajax').request(url, { + return this.get('ajax').request(`documents/${documentId}/pages/${pageId}/meta`, { method: 'GET' }).then((response) => { let meta = models.PageMetaModel.create(response); @@ -253,9 +240,8 @@ export default Ember.Service.extend({ // document attachments without the actual content getAttachments(documentId) { - let url = this.get('sessionService').appMeta.getUrl(`documents/${documentId}/attachments`); - return this.get('ajax').request(url, { + return this.get('ajax').request(`documents/${documentId}/attachments`, { method: 'GET' }).then((response) => { let data = []; @@ -268,9 +254,8 @@ export default Ember.Service.extend({ // nuke an attachment deleteAttachment(documentId, attachmentId) { - let url = this.get('sessionService').appMeta.getUrl(`documents/${documentId}/attachments/${attachmentId}`); - return this.get('ajax').request(url, { + return this.get('ajax').request(`documents/${documentId}/attachments/${attachmentId}`, { method: 'DELETE' }); }, diff --git a/app/app/services/folder.js b/app/app/services/folder.js index 5e8ab247..4ab9e2a0 100644 --- a/app/app/services/folder.js +++ b/app/app/services/folder.js @@ -23,10 +23,8 @@ export default BaseService.extend({ // Add a new folder. add(folder) { - let appMeta = this.get('sessionService.appMeta'); - let url = appMeta.getUrl(`folders`); - return this.get('ajax').post(url, { + return this.get('ajax').post(`folders`, { contentType: 'json', data: JSON.stringify(folder) }).then((folder)=>{ @@ -37,10 +35,8 @@ export default BaseService.extend({ // Returns folder model for specified folder id. getFolder(id) { - let appMeta = this.get('sessionService.appMeta'); - let url = appMeta.getUrl(`folders/${id}`); - return this.get('ajax').request(url, { + return this.get('ajax').request(`folders/${id}`, { method: 'GET' }).then((response)=>{ let folder = models.FolderModel.create(response); @@ -64,9 +60,8 @@ export default BaseService.extend({ // Updates an existing folder record. save(folder) { let id = folder.get('id'); - let url = this.get('sessionService').appMeta.getUrl(`folders/${id}`); - return this.get('ajax').request(url, { + return this.get('ajax').request(`folders/${id}`, { method: 'PUT', contentType: 'json', data: JSON.stringify(folder) @@ -74,7 +69,7 @@ export default BaseService.extend({ }, remove: function(folderId, moveToId) { - var url = this.get('sessionService').appMeta.getUrl('folders/' + folderId + "/move/" + moveToId); + let url = `folders/${folderId}/move/${moveToId}`; return this.get('ajax').request(url, { method: 'DELETE' @@ -82,7 +77,7 @@ export default BaseService.extend({ }, onboard: function(folderId, payload) { - var url = this.get('sessionService').appMeta.getUrl('public/share/' + folderId); + let url = `public/share/${folderId}`; return this.get('ajax').post(url, { contentType: "application/json", @@ -92,9 +87,7 @@ export default BaseService.extend({ // getProtectedFolderInfo returns non-private folders and who has access to them. getProtectedFolderInfo: function() { - var url = this.get('sessionService').appMeta.getUrl('folders?filter=viewers'); - - return this.get('ajax').request(url, { + return this.get('ajax').request(`folders?filter=viewers`, { method: "GET" }).then((response)=>{ let data = []; @@ -108,10 +101,8 @@ export default BaseService.extend({ // reloads and caches folders. reload() { - let appMeta = this.get('sessionService.appMeta'); - let url = appMeta.getUrl(`folders`); - return this.get('ajax').request(url, { + return this.get('ajax').request(`folders`, { method: "GET" }).then((response)=>{ let data = []; @@ -125,9 +116,8 @@ export default BaseService.extend({ // so who can see/edit this folder? getPermissions(folderId) { - let url = this.get('sessionService').appMeta.getUrl(`folders/${folderId}/permissions`); - return this.get('ajax').request(url, { + return this.get('ajax').request(`folders/${folderId}/permissions`, { method: "GET" }).then((response)=>{ let data = []; @@ -141,9 +131,8 @@ export default BaseService.extend({ // persist folder permissions savePermissions(folderId, payload) { - let url = this.get('sessionService').appMeta.getUrl(`folders/${folderId}/permissions`); - return this.get('ajax').request(url, { + return this.get('ajax').request(`folders/${folderId}/permissions`, { method: 'PUT', contentType: 'json', data: JSON.stringify(payload) @@ -152,9 +141,8 @@ export default BaseService.extend({ // share this folder with new users! share(folderId, invitation) { - let url = this.get('sessionService').appMeta.getUrl(`folders/${folderId}/invitation`); - return this.get('ajax').post(url, { + return this.get('ajax').post(`folders/${folderId}/invitation`, { contentType: 'json', data: JSON.stringify(invitation) }); @@ -175,7 +163,7 @@ export default BaseService.extend({ userId = "0"; } - let url = this.get('sessionService').appMeta.getUrl('users/' + userId + "/permissions"); + let url = `users/${userId}/permissions`; return this.get('ajax').request(url).then((folderPermissions) => { // safety check diff --git a/app/app/services/organization.js b/app/app/services/organization.js index ba3d8964..8035429d 100644 --- a/app/app/services/organization.js +++ b/app/app/services/organization.js @@ -18,9 +18,7 @@ export default Ember.Service.extend({ // Returns attributes for specified org id. getOrg(id) { - let url = this.get('sessionService').appMeta.getUrl(`organizations/${id}`); - - return this.get('ajax').request(url, { + return this.get('ajax').request(`organizations/${id}`, { method: 'GET' }).then((response) =>{ let org = models.OrganizationModel.create(response); @@ -31,13 +29,12 @@ export default Ember.Service.extend({ // Updates an existing organization record. save(org) { let id = org.get('id'); - let url = this.get('sessionService').appMeta.getUrl(`organizations/${id}`); // refresh on-screen data this.get('sessionService').get('appMeta').setSafe('message', org.message); this.get('sessionService').get('appMeta').setSafe('title', org.title); - return this.get('ajax').request(url, { + return this.get('ajax').request(`organizations/${id}`, { method: 'PUT', data: JSON.stringify(org) }); diff --git a/app/app/services/search.js b/app/app/services/search.js index e2bd5935..a669a67c 100644 --- a/app/app/services/search.js +++ b/app/app/services/search.js @@ -17,7 +17,7 @@ export default Ember.Service.extend({ // getUsers returns all users for organization. find(keywords) { - let url = this.get('sessionService').appMeta.getUrl("search?keywords=" + encodeURIComponent(keywords)); + let url = "search?keywords=" + encodeURIComponent(keywords); return this.get('ajax').request(url, { method: "GET" diff --git a/app/app/services/section.js b/app/app/services/section.js index cdb2e131..9ea55d7c 100644 --- a/app/app/services/section.js +++ b/app/app/services/section.js @@ -19,9 +19,7 @@ export default BaseService.extend({ // Returns all available sections. getAll() { - let url = this.get('sessionService').appMeta.getUrl(`sections`); - - return this.get('ajax').request(url,{ + return this.get('ajax').request(`sections`,{ method: 'GET' }).then((response)=>{ let data = []; @@ -38,8 +36,7 @@ export default BaseService.extend({ fetch(page, method, data) { let documentId = page.get('documentId'); let section = page.get('contentType'); - let endpoint = `sections?documentID=${documentId}§ion=${section}&method=${method}`; - let url = this.get('sessionService').appMeta.getUrl(endpoint); + let url = `sections?documentID=${documentId}§ion=${section}&method=${method}`; return this.get('ajax').post(url, { data: JSON.stringify(data), @@ -49,7 +46,7 @@ export default BaseService.extend({ // Did any dynamic sections change? Fetch and send up for rendering? refresh(documentId) { - let url = this.get('sessionService').appMeta.getUrl(`sections/refresh?documentID=${documentId}`); + let url = `sections/refresh?documentID=${documentId}`; return this.get('ajax').request(url, { method: 'GET' diff --git a/app/app/services/session.js b/app/app/services/session.js index 80bceaf0..64cbdd0a 100644 --- a/app/app/services/session.js +++ b/app/app/services/session.js @@ -51,7 +51,6 @@ export default Ember.Service.extend({ // Authentication login: function(credentials) { - let url = this.appMeta.getUrl('public/authenticate'); let domain = netUtil.getSubdomain(); this.clearSession(); @@ -65,7 +64,7 @@ export default Ember.Service.extend({ 'Authorization': 'Basic ' + encoded }; - return this.get('ajax').post(url, { + return this.get('ajax').post('public/authenticate', { headers }).then((response)=>{ this.setSession(response.token, models.UserModel.create(response.user)); @@ -76,7 +75,6 @@ export default Ember.Service.extend({ // SSO in the form of 'domain:email:password' sso: function(credentials) { - let url = this.appMeta.getUrl('public/authenticate'); this.clearSession(); if (is.empty(credentials.email) || is.empty(credentials.password)) { @@ -87,7 +85,7 @@ export default Ember.Service.extend({ 'Authorization': 'Basic ' + credentials }; - return this.get('ajax').post(url, { + return this.get('ajax').post('public/authenticate', { headers }).then((response)=>{ this.setSession(response.token, models.UserModel.create(response.user)); @@ -184,9 +182,7 @@ export default Ember.Service.extend({ }); } - let url = this.get('appMeta').getUrl("public/meta"); - - return this.get('ajax').request(url) + return this.get('ajax').request("public/meta") .then((response) => { this.get('appMeta').set('orgId', response.orgId); this.get('appMeta').setSafe('title', response.title); @@ -198,7 +194,7 @@ export default Ember.Service.extend({ if (is.not.undefined(token)) { // We now validate current token - let tokenCheckUrl = this.get('appMeta').getUrl(`public/validate?token=${token}`); + let tokenCheckUrl = `public/validate?token=${token}`; return this.get('ajax').request(tokenCheckUrl, { method: 'GET', diff --git a/app/app/services/template.js b/app/app/services/template.js index ec99a59b..eeea0646 100644 --- a/app/app/services/template.js +++ b/app/app/services/template.js @@ -17,8 +17,7 @@ export default Ember.Service.extend({ ajax: Ember.inject.service(), importStockTemplate: function(folderId, templateId) { - - let url = this.get('sessionService').appMeta.getUrl("templates/" + templateId + "/folder/" + folderId + "?type=stock"); + let url = `templates/${templateId}/folder/${folderId}?type=stock`; return this.get('ajax').request(url, { method: "POST" @@ -26,7 +25,7 @@ export default Ember.Service.extend({ }, importSavedTemplate: function(folderId, templateId) { - let url = this.get('sessionService').appMeta.getUrl("templates/" + templateId + "/folder/" + folderId + "?type=saved"); + let url = `templates/${templateId}/folder/${folderId}?type=saved`; return this.get('ajax').post(url).then((doc)=>{ let docModel = models.DocumentModel.create(doc); @@ -35,9 +34,7 @@ export default Ember.Service.extend({ }, getSavedTemplates() { - let url = this.get('sessionService').appMeta.getUrl("templates"); - - return this.get('ajax').request(url, { + return this.get('ajax').request(`templates`, { method: 'GET' }).then((response) => { if (is.not.array(response)) { @@ -57,22 +54,19 @@ export default Ember.Service.extend({ }, getStockTemplates() { - let url = this.get('sessionService').appMeta.getUrl("templates/stock"); - - return this.get('ajax').request(url, { + return this.get('ajax').request(`templates/stock`, { method: 'GET' }); }, saveAsTemplate(documentId, name, excerpt) { - let url = this.get('sessionService').appMeta.getUrl("templates"); let payload = { DocumentID: documentId, Name: name, Excerpt: excerpt }; - return this.get('ajax').request(url, { + return this.get('ajax').request(`templates`, { method: 'POST', data: JSON.stringify(payload) }).then(() => { diff --git a/app/app/services/user.js b/app/app/services/user.js index d6a39b07..fec97987 100644 --- a/app/app/services/user.js +++ b/app/app/services/user.js @@ -18,9 +18,8 @@ export default Ember.Service.extend({ // Adds a new user. add(user) { - let url = this.get('sessionService').appMeta.getUrl(`users`); - return this.get('ajax').request(url, { + return this.get('ajax').request(`users`, { type: 'POST', data: JSON.stringify(user), contentType: 'json' @@ -31,7 +30,7 @@ export default Ember.Service.extend({ // Returns user model for specified user id. getUser(userId) { - let url = this.get('sessionService').appMeta.getUrl(`users/${userId}`); + let url = `users/${userId}`; return this.get('ajax').request(url, { type: 'GET' @@ -42,9 +41,7 @@ export default Ember.Service.extend({ // Returns all users for organization. getAll() { - let url = this.get('sessionService').appMeta.getUrl(`users`); - - return this.get('ajax').request(url).then((response) => { + return this.get('ajax').request(`users`).then((response) => { return response.map(function(obj){ return models.UserModel.create(obj); }); @@ -53,7 +50,7 @@ export default Ember.Service.extend({ // Returns all users that can see folder. getFolderUsers(folderId) { - let url = this.get('sessionService').appMeta.getUrl(`users/folder/${folderId}`); + let url = `users/folder/${folderId}`; return this.get('ajax').request(url, { method: "GET" @@ -70,7 +67,7 @@ export default Ember.Service.extend({ // Updates an existing user record. save(user) { let userId = user.get('id'); - let url = this.get('sessionService').appMeta.getUrl(`users/${userId}`); + let url = `users/${userId}`; return this.get('ajax').request(url, { type: 'PUT', @@ -81,7 +78,7 @@ export default Ember.Service.extend({ // updatePassword changes the password for the specified user. updatePassword(userId, password) { - let url = this.get('sessionService').appMeta.getUrl(`users/${userId}/password`); + let url = `users/${userId}/password`; return this.get('ajax').post(url, { data: password @@ -90,7 +87,7 @@ export default Ember.Service.extend({ // Removes the specified user. remove(userId) { - let url = this.get('sessionService').appMeta.getUrl(`users/${userId}`); + let url = `users/${userId}`; return this.get('ajax').request(url, { method: 'DELETE' @@ -99,7 +96,7 @@ export default Ember.Service.extend({ // Request password reset. forgotPassword(email) { - let url = this.get('sessionService').appMeta.getUrl('public/forgot'); + let url = `public/forgot`; if (is.empty(email)) { return Ember.RSVP.reject("invalid"); @@ -118,7 +115,7 @@ export default Ember.Service.extend({ // Set new password. resetPassword(token, password) { - var url = this.get('sessionService').appMeta.getUrl('public/reset/' + token); + var url = `public/reset/${token}`; if (is.empty(token) || is.empty(password)) { return Ember.RSVP.reject("invalid"); From cbac8d2d5998f43ddbfc12f763f478b042394f22 Mon Sep 17 00:00:00 2001 From: zinyando Date: Tue, 28 Jun 2016 22:15:03 +0200 Subject: [PATCH 09/32] Refactor login to use ember-simple-auth --- app/app/authenticators/documize.js | 33 ++++ app/app/components/folder/folder-toolbar.js | 6 +- app/app/components/layout/zone-navigation.js | 29 +-- app/app/pods/auth/login/controller.js | 25 +-- app/app/routes/application.js | 10 +- app/app/services/ajax.js | 20 +- app/app/services/app-meta.js | 2 +- app/app/services/folder.js | 10 +- app/app/services/session.js | 188 +++---------------- app/config/environment.js | 154 +++++++-------- 10 files changed, 196 insertions(+), 281 deletions(-) create mode 100644 app/app/authenticators/documize.js diff --git a/app/app/authenticators/documize.js b/app/app/authenticators/documize.js new file mode 100644 index 00000000..1039bb6c --- /dev/null +++ b/app/app/authenticators/documize.js @@ -0,0 +1,33 @@ +import Ember from 'ember'; +import Base from 'ember-simple-auth/authenticators/base'; +import encodingUtil from '../utils/encoding'; +import netUtil from '../utils/net'; +import models from '../utils/model'; + +const { + isPresent +} = Ember; + +export default Base.extend({ + serverTokenEndpoint: `public/authenticate`, + + ajax: Ember.inject.service(), + + authenticate({password, email}) { + let domain = netUtil.getSubdomain(); + + if (!isPresent(password) || !isPresent(email)) { + return Ember.RSVP.reject("invalid"); + } + + var encoded = encodingUtil.Base64.encode(`${domain}:${email}:${password}`); + + var headers = { + 'Authorization': 'Basic ' + encoded + }; + + return this.get('ajax').post('public/authenticate', { + headers + }); + } +}); diff --git a/app/app/components/folder/folder-toolbar.js b/app/app/components/folder/folder-toolbar.js index 5ece1015..b523bba0 100644 --- a/app/app/components/folder/folder-toolbar.js +++ b/app/app/components/folder/folder-toolbar.js @@ -13,6 +13,10 @@ import Ember from 'ember'; import NotifierMixin from '../../mixins/notifier'; import TooltipMixin from '../../mixins/tooltip'; +const { + computed +} = Ember; + export default Ember.Component.extend(NotifierMixin, TooltipMixin, { documentService: Ember.inject.service('document'), templateService: Ember.inject.service('template'), @@ -22,7 +26,7 @@ export default Ember.Component.extend(NotifierMixin, TooltipMixin, { busy: false, importedDocuments: [], savedTemplates: [], - isFolderOwner: false, + isFolderOwner: computed.equal('folder.userId', 'session.user.id'), moveFolderId: "", didReceiveAttrs() { diff --git a/app/app/components/layout/zone-navigation.js b/app/app/components/layout/zone-navigation.js index 0c7acc0e..cf52fc08 100644 --- a/app/app/components/layout/zone-navigation.js +++ b/app/app/components/layout/zone-navigation.js @@ -15,15 +15,16 @@ import netUtil from '../../utils/net'; export default Ember.Component.extend({ folderService: Ember.inject.service('folder'), folder: null, + appMeta: Ember.inject.service(), - didInitAttrs() { - let self = this; - if (this.session.authenticated) { - this.session.user.accounts.forEach(function(account) { - account.active = account.orgId === self.session.appMeta.orgId; - }); - } - }, + didInitAttrs() { + if (this.get("session.authenticated")) { + this.get("session.user.accounts").forEach((account)=>{ + // TODO: do not mutate account.active here + account.active = account.orgId === this.get("appMeta.orgId"); + }); + } + }, didReceiveAttrs() { if (this.get('folder') === null) { @@ -31,10 +32,10 @@ export default Ember.Component.extend({ } }, - actions: { - switchAccount(domain) { - this.audit.record('switched-account'); - window.location.href = netUtil.getAppUrl(domain); - } - } + actions: { + switchAccount(domain) { + this.audit.record('switched-account'); + window.location.href = netUtil.getAppUrl(domain); + } + } }); diff --git a/app/app/pods/auth/login/controller.js b/app/app/pods/auth/login/controller.js index 3eefa5d5..a66fcf53 100644 --- a/app/app/pods/auth/login/controller.js +++ b/app/app/pods/auth/login/controller.js @@ -4,6 +4,8 @@ export default Ember.Controller.extend({ email: "", password: "", invalidCredentials: false, + session: Ember.inject.service('session'), + audit: Ember.inject.service('audit'), reset() { this.setProperties({ @@ -20,24 +22,13 @@ export default Ember.Controller.extend({ actions: { login() { - let self = this; let creds = this.getProperties('email', 'password'); - this.session.login(creds).then(function() { - self.set('invalidCredentials', false); - self.audit.record("logged-in"); - - var previousTransition = self.session.get('previousTransition'); - - if (previousTransition) { - previousTransition.retry(); - self.session.set('previousTransition', null); - } else { - self.transitionToRoute('folders.folder'); - } - }, function() { - self.set('invalidCredentials', true); - }); + this.get('session').authenticate('authenticator:documize', creds) + .then((response) => { + this.get('audit').record("logged-in"); + return response; + }); } } -}); \ No newline at end of file +}); diff --git a/app/app/routes/application.js b/app/app/routes/application.js index 872ca6e5..82d778f5 100644 --- a/app/app/routes/application.js +++ b/app/app/routes/application.js @@ -11,26 +11,28 @@ import Ember from 'ember'; import netUtil from '../utils/net'; +import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin'; const { inject: { service } } = Ember; -export default Ember.Route.extend({ +export default Ember.Route.extend(ApplicationRouteMixin, { userService: service('user'), - sessionService: service('session'), + session: service('session'), appMeta: service(), transitioning: false, beforeModel: function(transition) { let self = this; - let session = this.get('sessionService'); + let session = this.get('session'); + let appMeta = this.get('appMeta'); // Session ready? return this.get('appMeta').boot().then(function() { // Need to authenticate? - if (!session.get("appMeta.allowAnonymousAccess") && !session.get("authenticated") && + if (!appMeta.get("allowAnonymousAccess") && !session.get("isAuthenticated") && is.not.startWith(transition.targetName, 'auth.')) { if (!self.transitioning) { session.set('previousTransition', transition); diff --git a/app/app/services/ajax.js b/app/app/services/ajax.js index 0f44201d..d83a4533 100644 --- a/app/app/services/ajax.js +++ b/app/app/services/ajax.js @@ -1,7 +1,25 @@ import AjaxService from 'ember-ajax/services/ajax'; import config from '../config/environment'; +const { + computed, + inject: { service } +} = Ember; + export default AjaxService.extend({ + session: service(), host: config.apiHost, - namespace: config.apiNamespace + namespace: config.apiNamespace, + + headers: Ember.computed('session.session.content.authenticated.token', { + get() { + let headers = {}; + const token = this.get('session.session.content.authenticated.token'); + if (token) { + headers['authorization'] = token; + } + + return headers; + } + }) }); diff --git a/app/app/services/app-meta.js b/app/app/services/app-meta.js index b93b127d..ca0f64f5 100644 --- a/app/app/services/app-meta.js +++ b/app/app/services/app-meta.js @@ -15,7 +15,7 @@ export default Ember.Service.extend({ title: '', version: '', message: '', - allowAnonymousAccess: false, + allowAnonymousAccess: null, boot() { let dbhash; diff --git a/app/app/services/folder.js b/app/app/services/folder.js index 4ab9e2a0..d4574009 100644 --- a/app/app/services/folder.js +++ b/app/app/services/folder.js @@ -13,6 +13,10 @@ import Ember from 'ember'; import models from '../utils/model'; import BaseService from '../services/base'; +const { + get +} = Ember; + export default BaseService.extend({ sessionService: Ember.inject.service('session'), ajax: Ember.inject.service(), @@ -155,10 +159,10 @@ export default BaseService.extend({ } this.set('currentFolder', folder); - this.get('sessionService').storeSessionItem("folder", folder.get('id')); + this.get('sessionService').storeSessionItem("folder", get(folder, 'id')); this.set('canEditCurrentFolder', false); - let userId = this.get('sessionService').user.get('id'); + let userId = this.get('sessionService.user.id'); if (userId === "") { userId = "0"; } @@ -194,7 +198,7 @@ export default BaseService.extend({ } }); Ember.run(() => { - this.set('canEditCurrentFolder', canEdit && this.get('sessionService').authenticated); + this.set('canEditCurrentFolder', canEdit && this.get('sessionService.authenticated')); }); }); }, diff --git a/app/app/services/session.js b/app/app/services/session.js index 64cbdd0a..05052cdb 100644 --- a/app/app/services/session.js +++ b/app/app/services/session.js @@ -13,18 +13,31 @@ import Ember from 'ember'; import encodingUtil from '../utils/encoding'; import netUtil from '../utils/net'; import models from '../utils/model'; +import SimpleAuthSession from 'ember-simple-auth/services/session'; -export default Ember.Service.extend({ - ready: false, - appMeta: null, - isMac: false, - isMobile: false, - previousTransition: null, - user: null, - authenticated: false, +const { + inject: { service }, + computed: { oneWay } +} = Ember; + +export default SimpleAuthSession.extend({ + ajax: service(), + appMeta: service(), + + authenticated: oneWay('isAuthenticated'), + user: oneWay('session.content.authenticated.user'), folderPermissions: null, currentFolder: null, - ajax: Ember.inject.service(), + + authenticate() { + return this._super(...arguments) + .then(function({token, user}){ + return { + token, + user: models.User.create(user) + }; + }); + }, isAdmin: function() { if (this.authenticated && is.not.null(this.user) && this.user.id !== "") { @@ -40,86 +53,8 @@ export default Ember.Service.extend({ return false; }.property('user'), - // Boot up - init: function() { - this.set('user', models.UserModel.create()); - this.appMeta = models.AppMeta.create(); - - this.set('isMac', is.mac()); - this.set('isMobile', is.mobile()); - }, - - // Authentication - login: function(credentials) { - let domain = netUtil.getSubdomain(); - - this.clearSession(); - - if (is.empty(credentials.email) || is.empty(credentials.password)) { - return Ember.RSVP.reject("invalid"); - } - - var encoded = encodingUtil.Base64.encode(domain + ":" + credentials.email + ":" + credentials.password); - var headers = { - 'Authorization': 'Basic ' + encoded - }; - - return this.get('ajax').post('public/authenticate', { - headers - }).then((response)=>{ - this.setSession(response.token, models.UserModel.create(response.user)); - this.get('ready', true); - return response; - }); - }, - - // SSO in the form of 'domain:email:password' - sso: function(credentials) { - this.clearSession(); - - if (is.empty(credentials.email) || is.empty(credentials.password)) { - return Ember.RSVP.reject("invalid"); - } - - var headers = { - 'Authorization': 'Basic ' + credentials - }; - - return this.get('ajax').post('public/authenticate', { - headers - }).then((response)=>{ - this.setSession(response.token, models.UserModel.create(response.user)); - this.get('ready', true); - return response; - }); - }, - - // Goodbye - logout: function() { - this.clearSession(); - }, - - // Session management - setSession: function(token, user) { - this.set('user', user); - this.set('authenticated', true); - - this.storeSessionItem('token', token); - this.storeSessionItem('user', JSON.stringify(user)); - - let self = this; - - $.ajaxPrefilter(function(options, originalOptions, jqXHR) { - // We only tack on auth header for Documize API calls - if (is.startWith(options.url, self.get('appMeta.url'))) { - jqXHR.setRequestHeader('Authorization', 'Bearer ' + token); - } - }); - }, - clearSession: function() { - this.set('user', null); - this.set('authenticated', false); + // TODO: clear session properly with ESA localStorage.clear(); }, @@ -133,82 +68,5 @@ export default Ember.Service.extend({ clearSessionItem: function(key) { delete localStorage[key]; - }, - - // Application boot process - boot() { - let token = this.getSessionItem('token'); - - // TODO: the rest should be done through ESA - if (is.not.undefined(token)) { - // We now validate current token - - return this.get('ajax').request(`public/validate?token=${token}`, { - method: 'GET', - contentType: 'json' - }).then((user) => { - this.setSession(token, models.UserModel.create(user)); - this.set('ready', true); - }).catch((reason) => { - if (netUtil.isAjaxAccessError(reason)) { - localStorage.clear(); - window.location.href = "/auth/login"; - } - }); - } - - let self = this; - let dbhash = ""; - - if (is.not.null(document.head.querySelector("[property=dbhash]"))) { - dbhash = document.head.querySelector("[property=dbhash]").content; - } - - if (dbhash.length > 0 && dbhash !== "{{.DBhash}}") { - self.get('appMeta').set('orgId', "response.orgId"); - self.get('appMeta').setSafe('title', "Documize Setup"); - self.get('appMeta').set('version', "response.version"); - self.get('appMeta').setSafe('message', "response.message"); - self.get('appMeta').set('allowAnonymousAccess', false); - self.set('ready', true); - return new Ember.RSVP.Promise(function(resolve) { - resolve(); - }); - } - - if (this.get('ready')) { - return new Ember.RSVP.Promise(function(resolve) { - resolve(); - }); - } - - return this.get('ajax').request("public/meta") - .then((response) => { - this.get('appMeta').set('orgId', response.orgId); - this.get('appMeta').setSafe('title', response.title); - this.get('appMeta').set('version', response.version); - this.get('appMeta').setSafe('message', response.message); - this.get('appMeta').set('allowAnonymousAccess', response.allowAnonymousAccess); - - let token = this.getSessionItem('token'); - - if (is.not.undefined(token)) { - // We now validate current token - let tokenCheckUrl = `public/validate?token=${token}`; - - return this.get('ajax').request(tokenCheckUrl, { - method: 'GET', - contentType: 'json' - }).then((user) => { - this.setSession(token, models.UserModel.create(user)); - this.set('ready', true); - }).catch((reason) => { - if (netUtil.isAjaxAccessError(reason)) { - localStorage.clear(); - window.location.href = "/auth/login"; - } - }); - } - }); } }); diff --git a/app/config/environment.js b/app/config/environment.js index 79c01dda..2d90e9e9 100644 --- a/app/config/environment.js +++ b/app/config/environment.js @@ -13,83 +13,87 @@ module.exports = function(environment) { - var ENV = { - modulePrefix: 'documize', - podModulePrefix: 'documize/pods', - locationType: 'auto', - environment: environment, - baseURL: '/', - apiHost: '', - apiNamespace: '', - contentSecurityPolicyHeader: 'Content-Security-Policy-Report-Only', + var ENV = { + modulePrefix: 'documize', + podModulePrefix: 'documize/pods', + locationType: 'auto', + environment: environment, + baseURL: '/', + apiHost: '', + apiNamespace: '', + contentSecurityPolicyHeader: 'Content-Security-Policy-Report-Only', - EmberENV: { - FEATURES: {} - }, - "ember-cli-mirage": { - enabled: false - }, - APP: { - // Allows to disable audit service in tests - auditEnabled: true, - intercomKey: "" - } + EmberENV: { + FEATURES: {} + }, + "ember-cli-mirage": { + enabled: false + }, + 'ember-simple-auth': { + authenticationRoute: 'auth.login', + routeAfterAuthentication: 'folders.folder' + }, + APP: { + // Allows to disable audit service in tests + auditEnabled: true, + intercomKey: "" + } + }; + + if (environment === 'development') { + ENV.APP.LOG_TRANSITIONS = true; + ENV.APP.LOG_TRANSITIONS_INTERNAL = true; + ENV['ember-cli-mirage'] = { + enabled: false }; - if (environment === 'development') { - ENV.APP.LOG_TRANSITIONS = true; - ENV.APP.LOG_TRANSITIONS_INTERNAL = true; - ENV['ember-cli-mirage'] = { - enabled: false - }; - - ENV.apiHost = "https://localhost:5001"; - ENV.apiNamespace = "api"; - } - - if (environment === 'test') { - ENV.APP.LOG_RESOLVER = false; - ENV.APP.LOG_ACTIVE_GENERATION = false; - ENV.APP.LOG_VIEW_LOOKUPS = false; - // ENV.APP.LOG_TRANSITIONS = false; - // ENV.APP.LOG_TRANSITIONS_INTERNAL = false; - - ENV.baseURL = '/'; - ENV.locationType = 'none'; - ENV.APP.rootElement = '#ember-testing'; - ENV['ember-cli-mirage'] = { - enabled: true - }; - ENV.APP.auditEnabled = false; - - ENV.apiHost = "https://localhost:5001"; - } - - if (environment === 'production') { - ENV.APP.LOG_RESOLVER = false; - ENV.APP.LOG_ACTIVE_GENERATION = false; - ENV.APP.LOG_VIEW_LOOKUPS = false; - ENV.APP.LOG_TRANSITIONS = false; - ENV.APP.LOG_TRANSITIONS_INTERNAL = false; - - ENV.apiHost = ""; - } - - process.argv.forEach(function(element) { - if (element !== undefined) { - if (element.startsWith("intercom=")) { - element = element.replace("intercom=", ""); - ENV.APP.intercomKey = element; - } - if (element.startsWith("apiHost=")) { - element = element.replace("apiHost=", ""); - ENV.apiHost = element; - } - } - }); - + ENV.apiHost = "https://localhost:5001"; ENV.apiNamespace = "api"; - ENV.contentSecurityPolicy = null; + } - return ENV; -}; \ No newline at end of file + if (environment === 'test') { + ENV.APP.LOG_RESOLVER = false; + ENV.APP.LOG_ACTIVE_GENERATION = false; + ENV.APP.LOG_VIEW_LOOKUPS = false; + // ENV.APP.LOG_TRANSITIONS = false; + // ENV.APP.LOG_TRANSITIONS_INTERNAL = false; + + ENV.baseURL = '/'; + ENV.locationType = 'none'; + ENV.APP.rootElement = '#ember-testing'; + ENV['ember-cli-mirage'] = { + enabled: true + }; + ENV.APP.auditEnabled = false; + + ENV.apiHost = "https://localhost:5001"; + } + + if (environment === 'production') { + ENV.APP.LOG_RESOLVER = false; + ENV.APP.LOG_ACTIVE_GENERATION = false; + ENV.APP.LOG_VIEW_LOOKUPS = false; + ENV.APP.LOG_TRANSITIONS = false; + ENV.APP.LOG_TRANSITIONS_INTERNAL = false; + + ENV.apiHost = ""; + } + + process.argv.forEach(function(element) { + if (element !== undefined) { + if (element.startsWith("intercom=")) { + element = element.replace("intercom=", ""); + ENV.APP.intercomKey = element; + } + if (element.startsWith("apiHost=")) { + element = element.replace("apiHost=", ""); + ENV.apiHost = element; + } + } + }); + + ENV.apiNamespace = "api"; + ENV.contentSecurityPolicy = null; + + return ENV; +}; From 1e22c7cbe73c611ecd82dd7d7ff8b0a4be9d8344 Mon Sep 17 00:00:00 2001 From: zinyando Date: Tue, 28 Jun 2016 23:09:59 +0200 Subject: [PATCH 10/32] WIP fix session.get property issues --- app/app/authenticators/documize.js | 10 +++- app/app/pods/folders/route.js | 3 +- app/app/routes/application.js | 84 ++++++++++++------------------ app/app/services/app-meta.js | 7 +-- app/app/services/session.js | 38 +++++--------- app/config/environment.js | 3 +- 6 files changed, 63 insertions(+), 82 deletions(-) diff --git a/app/app/authenticators/documize.js b/app/app/authenticators/documize.js index 1039bb6c..082914e7 100644 --- a/app/app/authenticators/documize.js +++ b/app/app/authenticators/documize.js @@ -5,7 +5,8 @@ import netUtil from '../utils/net'; import models from '../utils/model'; const { - isPresent + isPresent, + RSVP: { resolve, reject } } = Ember; export default Base.extend({ @@ -13,6 +14,13 @@ export default Base.extend({ ajax: Ember.inject.service(), + restore(data) { + if (data) { + return resolve(data) + } + return reject(); + }, + authenticate({password, email}) { let domain = netUtil.getSubdomain(); diff --git a/app/app/pods/folders/route.js b/app/app/pods/folders/route.js index 380ba8d3..cd49151f 100644 --- a/app/app/pods/folders/route.js +++ b/app/app/pods/folders/route.js @@ -1,6 +1,7 @@ import Ember from 'ember'; +import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; -export default Ember.Route.extend({ +export default Ember.Route.extend(AuthenticatedRouteMixin, { folderService: Ember.inject.service('folder'), folder: {}, diff --git a/app/app/routes/application.js b/app/app/routes/application.js index 82d778f5..40d173cc 100644 --- a/app/app/routes/application.js +++ b/app/app/routes/application.js @@ -9,66 +9,50 @@ // // https://documize.com + import Ember from 'ember'; -import netUtil from '../utils/net'; import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin'; const { - inject: { service } + inject: { service } } = Ember; export default Ember.Route.extend(ApplicationRouteMixin, { - userService: service('user'), - session: service('session'), - appMeta: service(), - - transitioning: false, - - beforeModel: function(transition) { - let self = this; - let session = this.get('session'); - let appMeta = this.get('appMeta'); - - // Session ready? - return this.get('appMeta').boot().then(function() { - // Need to authenticate? - if (!appMeta.get("allowAnonymousAccess") && !session.get("isAuthenticated") && - is.not.startWith(transition.targetName, 'auth.')) { - if (!self.transitioning) { - session.set('previousTransition', transition); - self.set('transitioning', true); - } - - transition.abort(); - self.transitionTo('auth.login'); - } - }); + appMeta: service(), + session: service(), + beforeModel() { + return this.get('appMeta').boot().then( data => { + if ( data.allowAnonymousAccess ) { + return this.get('session').authenticate('authenticator:anonymous', data); + } + return; + }); + }, + + actions: { + willTransition: function( /*transition*/ ) { + $("#zone-sidebar").css('height', 'auto'); + Mousetrap.reset(); }, - actions: { - willTransition: function( /*transition*/ ) { - $("#zone-sidebar").css('height', 'auto'); - Mousetrap.reset(); - }, + didTransition() { + Ember.run.schedule("afterRender",this,function() { + $("#zone-sidebar").css('height', $(document).height() - $("#zone-navigation").height() - $("#zone-header").height() - 35); + }); - didTransition() { - Ember.run.schedule("afterRender",this,function() { - $("#zone-sidebar").css('height', $(document).height() - $("#zone-navigation").height() - $("#zone-header").height() - 35); - }); + return true; + }, - return true; - }, - - error(error, transition) { // jshint ignore: line - if (error) { - if (netUtil.isAjaxAccessError(error)) { - localStorage.clear(); - return this.transitionTo('auth.login'); - } - } - - // Return true to bubble this event to any parent route. - return true; + error(error, transition) { // jshint ignore: line + if (error) { + if (netUtil.isAjaxAccessError(error)) { + localStorage.clear(); + return this.transitionTo('auth.login'); } - }, + } + + // Return true to bubble this event to any parent route. + return true; + } + }, }); diff --git a/app/app/services/app-meta.js b/app/app/services/app-meta.js index ca0f64f5..823ba906 100644 --- a/app/app/services/app-meta.js +++ b/app/app/services/app-meta.js @@ -15,7 +15,7 @@ export default Ember.Service.extend({ title: '', version: '', message: '', - allowAnonymousAccess: null, + allowAnonymousAccess: false, boot() { let dbhash; @@ -33,8 +33,9 @@ export default Ember.Service.extend({ } return this.get('ajax').request('public/meta') - .then((response) => { + .then((response) => { this.setProperties(response); - }); + return response; + }); } }); diff --git a/app/app/services/session.js b/app/app/services/session.js index 05052cdb..56603975 100644 --- a/app/app/services/session.js +++ b/app/app/services/session.js @@ -17,7 +17,8 @@ import SimpleAuthSession from 'ember-simple-auth/services/session'; const { inject: { service }, - computed: { oneWay } + computed: { oneWay, or }, + computed } = Ember; export default SimpleAuthSession.extend({ @@ -25,34 +26,19 @@ export default SimpleAuthSession.extend({ appMeta: service(), authenticated: oneWay('isAuthenticated'), - user: oneWay('session.content.authenticated.user'), + isAdmin: oneWay('user.admin'), + isEditor: or('user.admin', 'user.editor'), + + user: computed('session.content.authenticated.user', function(){ + let user = this.get('session.content.authenticated.user'); + if (user) { + return models.UserModel.create(user); + } + }), + folderPermissions: null, currentFolder: null, - authenticate() { - return this._super(...arguments) - .then(function({token, user}){ - return { - token, - user: models.User.create(user) - }; - }); - }, - - isAdmin: function() { - if (this.authenticated && is.not.null(this.user) && this.user.id !== "") { - return this.user.admin; - } - return false; - }.property('user'), - - isEditor: function() { - if (this.authenticated && is.not.null(this.user) && this.user.id !== "") { - return this.user.editor || this.user.admin; - } - return false; - }.property('user'), - clearSession: function() { // TODO: clear session properly with ESA localStorage.clear(); diff --git a/app/config/environment.js b/app/config/environment.js index 2d90e9e9..67d740bc 100644 --- a/app/config/environment.js +++ b/app/config/environment.js @@ -31,7 +31,8 @@ module.exports = function(environment) { }, 'ember-simple-auth': { authenticationRoute: 'auth.login', - routeAfterAuthentication: 'folders.folder' + routeAfterAuthentication: 'folders.folder', + routeIfAlreadyAuthenticated: 'folders.folder' }, APP: { // Allows to disable audit service in tests From 0ddbe70935cf92f3da66a729a257345985002a12 Mon Sep 17 00:00:00 2001 From: zinyando Date: Thu, 30 Jun 2016 12:45:50 +0200 Subject: [PATCH 11/32] Add simple-auth route mixins --- app/app/pods/auth/logout/route.js | 7 +++-- app/app/pods/auth/share/route.js | 3 +- app/app/pods/customize/folders/route.js | 3 +- app/app/pods/customize/general/route.js | 10 ++++-- app/app/pods/customize/route.js | 4 +-- app/app/pods/customize/users/route.js | 3 +- app/app/pods/document/edit/route.js | 5 +-- app/app/pods/document/index/route.js | 5 +-- app/app/pods/document/route.js | 3 +- app/app/pods/document/wizard/route.js | 3 +- app/app/pods/folders/folder/route.js | 3 +- app/app/pods/folders/route.js | 3 +- app/app/pods/folders/settings/route.js | 3 +- app/app/pods/not-found/route.js | 3 +- app/app/pods/profile/route.js | 42 ++++++++++++++----------- app/app/pods/search/route.js | 4 +-- app/app/pods/setup/route.js | 2 +- app/app/pods/widgets/route.js | 4 +-- app/app/routes/application.js | 2 +- 19 files changed, 67 insertions(+), 45 deletions(-) diff --git a/app/app/pods/auth/logout/route.js b/app/app/pods/auth/logout/route.js index cb5e8ba3..9b9fa898 100644 --- a/app/app/pods/auth/logout/route.js +++ b/app/app/pods/auth/logout/route.js @@ -2,14 +2,17 @@ import Ember from 'ember'; import config from 'documize/config/environment'; export default Ember.Route.extend({ + session: Ember.inject.service(), + appMeta: Ember.inject.service(), + activate: function(){ - this.session.logout(); + this.get('session').invalidate(); this.audit.record("logged-in"); this.audit.stop(); if (config.environment === 'test') { this.transitionTo('auth.login'); }else{ - window.document.location = this.session.appMeta.allowAnonymousAccess ? "/" : "/auth/login"; + window.document.location = this.get("appMeta.allowAnonymousAccess") ? "/" : "/auth/login"; } } }); diff --git a/app/app/pods/auth/share/route.js b/app/app/pods/auth/share/route.js index 1e9869e8..2d4b7503 100644 --- a/app/app/pods/auth/share/route.js +++ b/app/app/pods/auth/share/route.js @@ -1,6 +1,7 @@ import Ember from 'ember'; +import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; -export default Ember.Route.extend({ +export default Ember.Route.extend(AuthenticatedRouteMixin, { model: function(params) { this.set('folderId', params.id); this.set('slug', params.slug); diff --git a/app/app/pods/customize/folders/route.js b/app/app/pods/customize/folders/route.js index 87920662..a5b8a3a6 100644 --- a/app/app/pods/customize/folders/route.js +++ b/app/app/pods/customize/folders/route.js @@ -1,6 +1,7 @@ import Ember from 'ember'; +import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; -export default Ember.Route.extend({ +export default Ember.Route.extend(AuthenticatedRouteMixin, { folderService: Ember.inject.service('folder'), beforeModel() { diff --git a/app/app/pods/customize/general/route.js b/app/app/pods/customize/general/route.js index a4659df0..f58f3021 100644 --- a/app/app/pods/customize/general/route.js +++ b/app/app/pods/customize/general/route.js @@ -1,16 +1,20 @@ import Ember from 'ember'; +import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; -export default Ember.Route.extend({ +export default Ember.Route.extend(AuthenticatedRouteMixin, { orgService: Ember.inject.service('organization'), + appMeta: Ember.inject.service(), + session: Ember.inject.service(), beforeModel() { - if (!this.session.isAdmin) { + if (!this.get("session.isAdmin")) { this.transitionTo('auth.login'); } }, model() { - return this.get('orgService').getOrg(this.session.appMeta.get('orgId')); + let orgId = this.get("appMeta.orgId"); + return this.get('orgService').getOrg(orgId); }, activate() { diff --git a/app/app/pods/customize/route.js b/app/app/pods/customize/route.js index 1f6a1416..f49002d0 100644 --- a/app/app/pods/customize/route.js +++ b/app/app/pods/customize/route.js @@ -1,8 +1,8 @@ /*global is*/ import Ember from 'ember'; +import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; -export default Ember.Route.extend( -{ +export default Ember.Route.extend(AuthenticatedRouteMixin, { beforeModel: function(transition) { if (is.equal(transition.targetName, 'customize.index')) { diff --git a/app/app/pods/customize/users/route.js b/app/app/pods/customize/users/route.js index 444762c2..4f385c09 100644 --- a/app/app/pods/customize/users/route.js +++ b/app/app/pods/customize/users/route.js @@ -1,6 +1,7 @@ import Ember from 'ember'; +import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; -export default Ember.Route.extend({ +export default Ember.Route.extend(AuthenticatedRouteMixin, { userService: Ember.inject.service('user'), beforeModel: function() { diff --git a/app/app/pods/document/edit/route.js b/app/app/pods/document/edit/route.js index f0c6b802..83d06b96 100644 --- a/app/app/pods/document/edit/route.js +++ b/app/app/pods/document/edit/route.js @@ -1,6 +1,7 @@ import Ember from 'ember'; +import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; -export default Ember.Route.extend({ +export default Ember.Route.extend(AuthenticatedRouteMixin, { documentService: Ember.inject.service('document'), folderService: Ember.inject.service('folder'), @@ -16,4 +17,4 @@ export default Ember.Route.extend({ meta: self.get('documentService').getPageMeta(self.paramsFor('document').document_id, params.page_id) }); } -}); \ No newline at end of file +}); diff --git a/app/app/pods/document/index/route.js b/app/app/pods/document/index/route.js index a6970a6d..f7dc11e5 100644 --- a/app/app/pods/document/index/route.js +++ b/app/app/pods/document/index/route.js @@ -1,7 +1,8 @@ import Ember from 'ember'; +import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; // import models from '../../../utils/model'; -export default Ember.Route.extend({ +export default Ember.Route.extend(AuthenticatedRouteMixin, { documentService: Ember.inject.service('document'), folderService: Ember.inject.service('folder'), userService: Ember.inject.service('user'), @@ -106,4 +107,4 @@ export default Ember.Route.extend({ deactivate() { Ember.$('html').removeClass('background-color-white'); } -}); \ No newline at end of file +}); diff --git a/app/app/pods/document/route.js b/app/app/pods/document/route.js index e72642cd..155d4920 100644 --- a/app/app/pods/document/route.js +++ b/app/app/pods/document/route.js @@ -1,6 +1,7 @@ import Ember from 'ember'; +import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; -export default Ember.Route.extend({ +export default Ember.Route.extend(AuthenticatedRouteMixin, { documentService: Ember.inject.service('document'), model: function(params) { diff --git a/app/app/pods/document/wizard/route.js b/app/app/pods/document/wizard/route.js index fe460b1a..9ec0fe68 100644 --- a/app/app/pods/document/wizard/route.js +++ b/app/app/pods/document/wizard/route.js @@ -1,6 +1,7 @@ import Ember from 'ember'; +import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; -export default Ember.Route.extend({ +export default Ember.Route.extend(AuthenticatedRouteMixin, { documentService: Ember.inject.service('document'), folderService: Ember.inject.service('folder'), sectionService: Ember.inject.service('section'), diff --git a/app/app/pods/folders/folder/route.js b/app/app/pods/folders/folder/route.js index 9f99bc98..429c9800 100644 --- a/app/app/pods/folders/folder/route.js +++ b/app/app/pods/folders/folder/route.js @@ -1,6 +1,7 @@ import Ember from 'ember'; +import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; -export default Ember.Route.extend({ +export default Ember.Route.extend(AuthenticatedRouteMixin, { documentService: Ember.inject.service('document'), folderService: Ember.inject.service('folder'), diff --git a/app/app/pods/folders/route.js b/app/app/pods/folders/route.js index cd49151f..8ef4415b 100644 --- a/app/app/pods/folders/route.js +++ b/app/app/pods/folders/route.js @@ -3,6 +3,7 @@ import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-rout export default Ember.Route.extend(AuthenticatedRouteMixin, { folderService: Ember.inject.service('folder'), + localStorage: Ember.inject.service(), folder: {}, model: function() { @@ -13,7 +14,7 @@ export default Ember.Route.extend(AuthenticatedRouteMixin, { let self = this; if (is.empty(this.paramsFor('folders.folder'))) { - var lastFolder = this.session.getSessionItem("folder"); + var lastFolder = this.get('localStorage').getSessionItem("folder"); if (is.not.undefined(lastFolder)) { this.get('folderService').getFolder(lastFolder).then(function(folder) { diff --git a/app/app/pods/folders/settings/route.js b/app/app/pods/folders/settings/route.js index 4ecfa128..56a14d6e 100644 --- a/app/app/pods/folders/settings/route.js +++ b/app/app/pods/folders/settings/route.js @@ -1,8 +1,9 @@ import Ember from 'ember'; import models from '../../../utils/model'; import NotifierMixin from '../../../mixins/notifier'; +import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; -export default Ember.Route.extend(NotifierMixin, { +export default Ember.Route.extend(NotifierMixin, AuthenticatedRouteMixin, { folderService: Ember.inject.service('folder'), userService: Ember.inject.service('user'), folder: {}, diff --git a/app/app/pods/not-found/route.js b/app/app/pods/not-found/route.js index 2d0e9ae5..dae8fd4d 100644 --- a/app/app/pods/not-found/route.js +++ b/app/app/pods/not-found/route.js @@ -1,6 +1,7 @@ import Ember from 'ember'; +import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; -export default Ember.Route.extend({ +export default Ember.Route.extend(AuthenticatedRouteMixin, { beforeModel: function() { this.transitionTo('folders'); diff --git a/app/app/pods/profile/route.js b/app/app/pods/profile/route.js index 851ac21f..468d1c94 100644 --- a/app/app/pods/profile/route.js +++ b/app/app/pods/profile/route.js @@ -1,25 +1,29 @@ import Ember from 'ember'; +import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; -export default Ember.Route.extend({ - userService: Ember.inject.service('user'), - folderService: Ember.inject.service('folder'), +export default Ember.Route.extend(AuthenticatedRouteMixin, { + userService: Ember.inject.service('user'), + folderService: Ember.inject.service('folder'), + session: Ember.inject.service(), - beforeModel: function() { - if (!this.session.authenticated) { - this.transitionTo('auth.login'); - } - }, - model: function() { - return this.get('userService').getUser(this.session.user.id); - }, - - afterModel: function(model) { - this.browser.setTitleWithoutSuffix(model.get('fullname')); - }, - - setupController(controller, model) { - controller.set('model', model); - controller.set("folder", this.get('folderService.currentFolder')); + beforeModel: function() { + if (!this.get("session").authenticated) { + this.transitionTo('auth.login'); } + }, + + model: function() { + return this.get('userService').getUser(this.get("session.session.authenticated.user.id")); + debugger; + }, + + afterModel: function(model) { + this.browser.setTitleWithoutSuffix(model.get('fullname')); + }, + + setupController(controller, model) { + controller.set('model', model); + controller.set("folder", this.get('folderService.currentFolder')); + } }); diff --git a/app/app/pods/search/route.js b/app/app/pods/search/route.js index 580776c8..585deb19 100644 --- a/app/app/pods/search/route.js +++ b/app/app/pods/search/route.js @@ -1,5 +1,5 @@ // Copyright (c) 2015 Documize Inc. import Ember from 'ember'; +import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; -export default Ember.Route.extend({ -}); +export default Ember.Route.extend(AuthenticatedRouteMixin); diff --git a/app/app/pods/setup/route.js b/app/app/pods/setup/route.js index a40ebd8c..d33439e1 100644 --- a/app/app/pods/setup/route.js +++ b/app/app/pods/setup/route.js @@ -29,4 +29,4 @@ export default Ember.Route.extend({ activate() { document.title = "Setup Documize database '" + document.head.querySelector("[property=dbname]").content + "'"; } -}); \ No newline at end of file +}); diff --git a/app/app/pods/widgets/route.js b/app/app/pods/widgets/route.js index 26d9f312..c89c0208 100644 --- a/app/app/pods/widgets/route.js +++ b/app/app/pods/widgets/route.js @@ -1,4 +1,4 @@ import Ember from 'ember'; +import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; -export default Ember.Route.extend({ -}); +export default Ember.Route.extend(AuthenticatedRouteMixin); diff --git a/app/app/routes/application.js b/app/app/routes/application.js index 40d173cc..a59fd75c 100644 --- a/app/app/routes/application.js +++ b/app/app/routes/application.js @@ -28,7 +28,7 @@ export default Ember.Route.extend(ApplicationRouteMixin, { return; }); }, - + actions: { willTransition: function( /*transition*/ ) { $("#zone-sidebar").css('height', 'auto'); From fd42473f991c1c40c9577a838101f7002e23ac4b Mon Sep 17 00:00:00 2001 From: zinyando Date: Thu, 30 Jun 2016 12:47:03 +0200 Subject: [PATCH 12/32] Update session stub --- app/tests/helpers/stub-session.js | 207 +++--------------- app/tests/unit/services/local-storage-test.js | 12 + 2 files changed, 47 insertions(+), 172 deletions(-) create mode 100644 app/tests/unit/services/local-storage-test.js diff --git a/app/tests/helpers/stub-session.js b/app/tests/helpers/stub-session.js index 85cfa1a9..933616ae 100644 --- a/app/tests/helpers/stub-session.js +++ b/app/tests/helpers/stub-session.js @@ -1,200 +1,63 @@ +// Copyright 2016 Documize Inc. . All rights reserved. +// +// This software (Documize Community Edition) is licensed under +// GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html +// +// You can operate outside the AGPL restrictions by purchasing +// Documize Enterprise Edition and obtaining a commercial license +// by contacting . +// +// https://documize.com + import Ember from 'ember'; -import models from 'documize/utils/model'; import encodingUtil from 'documize/utils/encoding'; import netUtil from 'documize/utils/net'; +import models from 'documize/utils/model'; +import SimpleAuthSession from 'ember-simple-auth/services/session'; -const Session = Ember.Service.extend({ +const { + inject: { service }, + computed: { oneWay, or }, + computed +} = Ember; + +const Session = SimpleAuthSession.extend({ + ajax: service(), + appMeta: service(), + + authenticated: oneWay('isAuthenticated'), + isAdmin: oneWay('user.admin'), + isEditor: or('user.admin', 'user.editor'), + + user: computed('session.content.authenticated.user', function(){ + let user = this.get('session.content.authenticated.user'); + if (user) { + return models.UserModel.create(user); + } + }), - ready: false, - appMeta: null, - isMac: false, - isMobile: false, - previousTransition: null, - user: null, - authenticated: false, folderPermissions: null, currentFolder: null, - ajax: Ember.inject.service(), - - isAdmin: function() { - if (this.authenticated && is.not.null(this.user) && this.user.id !== "") { - return this.user.admin; - } - return false; - }.property('user'), - - isEditor: function() { - if (this.authenticated && is.not.null(this.user) && this.user.id !== "") { - return this.user.editor || this.user.admin; - } - return false; - }.property('user'), - - // Boot up - init: function() { - this.set('user', models.UserModel.create()); - this.appMeta = models.AppMeta.create(); - - this.set('isMac', is.mac()); - this.set('isMobile', is.mobile()); - }, - - login: function(credentials) { - let url = this.appMeta.getUrl('public/authenticate'); - let domain = netUtil.getSubdomain(); - - this.clearSession(); - - if (is.empty(credentials.email) || is.empty(credentials.password)) { - return Ember.RSVP.reject("invalid"); - } - - var encoded = encodingUtil.Base64.encode(domain + ":" + credentials.email + ":" + credentials.password); - var headers = { - 'Authorization': 'Basic ' + encoded - }; - - return this.get('ajax').post(url, { - headers - }).then((response)=>{ - this.setSession(response.token, models.UserModel.create(response.user)); - this.get('ready', true); - return response; - }); - }, - - sso: function(credentials) { - let url = this.appMeta.getUrl('public/authenticate'); - this.clearSession(); - - if (is.empty(credentials.email) || is.empty(credentials.password)) { - return Ember.RSVP.reject("invalid"); - } - - var headers = { - 'Authorization': 'Basic ' + credentials - }; - - return this.get('ajax').post(url, { - headers - }).then((response)=>{ - this.setSession(response.token, models.UserModel.create(response.user)); - this.get('ready', true); - return response; - }); - }, - - // Goodbye - logout: function() { - this.clearSession(); - }, - - // Session management - setSession: function(token, user) { - this.set('user', user); - this.set('authenticated', true); - - this.storeSessionItem('token', token); - this.storeSessionItem('user', JSON.stringify(user)); - - let self = this; - - $.ajaxPrefilter(function(options, originalOptions, jqXHR) { - // We only tack on auth header for Documize API calls - if (is.startWith(options.url, self.get('appMeta.url'))) { - jqXHR.setRequestHeader('Authorization', 'Bearer ' + token); - } - }); - }, clearSession: function() { - this.set('user', null); - this.set('authenticated', false); + // TODO: clear session properly with ESA // localStorage.clear(); }, storeSessionItem: function() { // localStorage[key] = data; - // console.log(data); }, getSessionItem: function() { // return localStorage[key]; - // console.log(data); }, clearSessionItem: function() { // delete localStorage[key]; - }, - - boot() { - let self = this; - let dbhash = ""; - - if (is.not.null(document.head.querySelector("[property=dbhash]"))) { - dbhash = document.head.querySelector("[property=dbhash]").content; - } - - if (dbhash.length > 0 && dbhash !== "{{.DBhash}}") { - self.get('appMeta').set('orgId', "response.orgId"); - self.get('appMeta').setSafe('title', "Documize Setup"); - self.get('appMeta').set('version', "response.version"); - self.get('appMeta').setSafe('message', "response.message"); - self.get('appMeta').set('allowAnonymousAccess', false); - self.set('ready', true); - return new Ember.RSVP.Promise(function(resolve) { - resolve(); - }); - } - - if (this.get('ready')) { - return new Ember.RSVP.Promise(function(resolve) { - resolve(); - }); - } - - // var blockedPopupTest = window.open("http://maintenance.documize.com", "directories=no,height=1,width=1,menubar=no,resizable=no,scrollbars=no,status=no,titlebar=no,top=0,location=no"); - // - // if (!blockedPopupTest) { - // this.set('popupBlocked', true); - // } else { - // blockedPopupTest.close(); - // this.set('popupBlocked', false); - // } - - let url = this.get('appMeta').getUrl("public/meta"); - - return this.get('ajax').request(url) - .then((response) => { - this.get('appMeta').set('orgId', response.orgId); - this.get('appMeta').setSafe('title', response.title); - this.get('appMeta').set('version', response.version); - this.get('appMeta').setSafe('message', response.message); - this.get('appMeta').set('allowAnonymousAccess', response.allowAnonymousAccess); - - let token = this.getSessionItem('token'); - - if (is.not.undefined(token)) { - // We now validate current token - let tokenCheckUrl = this.get('appMeta').getUrl(`public/validate?token=${token}`); - - return this.get('ajax').request(tokenCheckUrl, { - method: 'GET', - contentType: 'json' - }).then((user) => { - this.setSession(token, models.UserModel.create(user)); - this.set('ready', true); - }).catch((reason) => { - if (reason.status === 401 || reason.status === 403) { - // localStorage.clear(); - window.location.href = "/auth/login"; - } - }); - } - }); } }); + export default Ember.Test.registerAsyncHelper('stubSession', function(app, test, attrs={}) { test.register('service:session', Session.extend(attrs)); }); diff --git a/app/tests/unit/services/local-storage-test.js b/app/tests/unit/services/local-storage-test.js new file mode 100644 index 00000000..a6b2a5d8 --- /dev/null +++ b/app/tests/unit/services/local-storage-test.js @@ -0,0 +1,12 @@ +import { moduleFor, test } from 'ember-qunit'; + +moduleFor('service:local-storage', 'Unit | Service | local storage', { + // Specify the other units that are required for this test. + // needs: ['service:foo'] +}); + +// Replace this with your real tests. +test('it exists', function(assert) { + let service = this.subject(); + assert.ok(service); +}); From 5bd92b7f632d3128e883140c90198d796885dd8f Mon Sep 17 00:00:00 2001 From: zinyando Date: Thu, 30 Jun 2016 12:48:37 +0200 Subject: [PATCH 13/32] Add documize and anonymous autheticators --- app/app/authenticators/anonymous.js | 12 ++++++++++ app/app/authenticators/documize.js | 36 +++++++++++++++++------------ 2 files changed, 33 insertions(+), 15 deletions(-) create mode 100644 app/app/authenticators/anonymous.js diff --git a/app/app/authenticators/anonymous.js b/app/app/authenticators/anonymous.js new file mode 100644 index 00000000..a4e5147c --- /dev/null +++ b/app/app/authenticators/anonymous.js @@ -0,0 +1,12 @@ +import Ember from 'ember'; +import Base from 'ember-simple-auth/authenticators/base'; + +const { + RSVP: { resolve } +} = Ember; + +export default Base.extend({ + authenticate(data) { + return resolve(data); + } +}); diff --git a/app/app/authenticators/documize.js b/app/app/authenticators/documize.js index 082914e7..7cfe3886 100644 --- a/app/app/authenticators/documize.js +++ b/app/app/authenticators/documize.js @@ -6,36 +6,42 @@ import models from '../utils/model'; const { isPresent, - RSVP: { resolve, reject } + RSVP: { resolve, reject }, + inject: { service } } = Ember; export default Base.extend({ - serverTokenEndpoint: `public/authenticate`, - ajax: Ember.inject.service(), + ajax: service(), + appMeta: service(), restore(data) { + // TODO: verify authentication data if (data) { - return resolve(data) + return resolve(data); } return reject(); }, authenticate({password, email}) { - let domain = netUtil.getSubdomain(); + let domain = netUtil.getSubdomain(); - if (!isPresent(password) || !isPresent(email)) { - return Ember.RSVP.reject("invalid"); - } + if (!isPresent(password) || !isPresent(email)) { + return Ember.RSVP.reject("invalid"); + } - var encoded = encodingUtil.Base64.encode(`${domain}:${email}:${password}`); + var encoded = encodingUtil.Base64.encode(`${domain}:${email}:${password}`); - var headers = { - 'Authorization': 'Basic ' + encoded - }; + var headers = { + 'Authorization': 'Basic ' + encoded + }; - return this.get('ajax').post('public/authenticate', { - headers - }); + return this.get('ajax').post('public/authenticate', { + headers + }); + }, + + invalidate() { + return resolve(); } }); From 37e3434158f962aadca5998a4a23e38bbc8cfff5 Mon Sep 17 00:00:00 2001 From: zinyando Date: Thu, 30 Jun 2016 12:49:54 +0200 Subject: [PATCH 14/32] Create new local-storage service --- app/app/services/local-storage.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 app/app/services/local-storage.js diff --git a/app/app/services/local-storage.js b/app/app/services/local-storage.js new file mode 100644 index 00000000..0939d28e --- /dev/null +++ b/app/app/services/local-storage.js @@ -0,0 +1,16 @@ +import Ember from 'ember'; + +export default Ember.Service.extend({ + + storeSessionItem: function(key, data) { + localStorage[key] = data; + }, + + getSessionItem: function(key) { + return localStorage[key]; + }, + + clearSessionItem: function(key) { + delete localStorage[key]; + } +}); From d1714db6f8f0475963fa4428ab946a909f935328 Mon Sep 17 00:00:00 2001 From: zinyando Date: Thu, 30 Jun 2016 12:50:42 +0200 Subject: [PATCH 15/32] Fix calls to session and appMeta services --- .../components/document/document-toolbar.js | 6 ++-- app/app/components/folder/folder-settings.js | 9 +++--- app/app/components/folder/start-document.js | 7 ++-- .../components/section/wysiwyg/type-editor.js | 9 +++--- app/app/pods/auth/login/controller.js | 2 ++ app/app/services/app-meta.js | 4 +++ app/app/services/folder.js | 4 ++- app/app/services/organization.js | 8 +++-- app/app/services/session.js | 32 ++++--------------- 9 files changed, 40 insertions(+), 41 deletions(-) diff --git a/app/app/components/document/document-toolbar.js b/app/app/components/document/document-toolbar.js index 0baff562..050b8521 100644 --- a/app/app/components/document/document-toolbar.js +++ b/app/app/components/document/document-toolbar.js @@ -15,6 +15,7 @@ import TooltipMixin from '../../mixins/tooltip'; export default Ember.Component.extend(NotifierMixin, TooltipMixin, { userService: Ember.inject.service('user'), + localStorage: Ember.inject.service(), drop: null, users: [], saveTemplate: { @@ -43,11 +44,12 @@ export default Ember.Component.extend(NotifierMixin, TooltipMixin, { if (this.get('isEditor')) { let self = this; let documentId = this.get('document.id'); - let uploadUrl = this.session.appMeta.getUrl(`documents/${documentId}/attachments`); + let url = this.get('appMeta.url'); + let uploadUrl = `${url}/documents/${documentId}/attachments`; let dzone = new Dropzone("#attachment-button > i", { headers: { - 'Authorization': 'Bearer ' + self.session.getSessionItem('token') + 'Authorization': 'Bearer ' + self.get('localStorage').getSessionItem('session.session.authenticated.token') }, url: uploadUrl, method: "post", diff --git a/app/app/components/folder/folder-settings.js b/app/app/components/folder/folder-settings.js index 7460bbd7..5339437d 100644 --- a/app/app/components/folder/folder-settings.js +++ b/app/app/components/folder/folder-settings.js @@ -1,11 +1,11 @@ // Copyright 2016 Documize Inc. . All rights reserved. // -// This software (Documize Community Edition) is licensed under +// This software (Documize Community Edition) is licensed under // GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html // // You can operate outside the AGPL restrictions by purchasing // Documize Enterprise Edition and obtaining a commercial license -// by contacting . +// by contacting . // // https://documize.com @@ -13,6 +13,7 @@ import Ember from 'ember'; export default Ember.Component.extend({ folderService: Ember.inject.service('folder'), + appMeta: Ember.inject.service(), users: [], folders: [], folder: {}, @@ -23,7 +24,7 @@ export default Ember.Component.extend({ permissions: {}, getDefaultInvitationMessage() { - return "Hey there, I am sharing the " + this.folder.get('name') + " (in " + this.session.appMeta.title + ") with you so we can both access the same documents."; + return "Hey there, I am sharing the " + this.folder.get('name') + " (in " + this.get("appMeta.title") + ") with you so we can both access the same documents."; }, willRender() { @@ -106,4 +107,4 @@ export default Ember.Component.extend({ this.sendAction("onPermission", this.get('folder'), message, this.get('permissions')); } } -}); \ No newline at end of file +}); diff --git a/app/app/components/folder/start-document.js b/app/app/components/folder/start-document.js index e4376e1c..8bc4c071 100644 --- a/app/app/components/folder/start-document.js +++ b/app/app/components/folder/start-document.js @@ -13,12 +13,14 @@ import Ember from 'ember'; import NotifierMixin from '../../mixins/notifier'; export default Ember.Component.extend(NotifierMixin, { + localStorage: Ember.inject.service(), tagName: 'span', selectedTemplate: { id: "0" }, canEditTemplate: "", drop: null, + appMeta: Ember.inject.service(), didReceiveAttrs() { this.send('setTemplate', this.get('savedTemplates')[0]); @@ -71,13 +73,14 @@ export default Ember.Component.extend(NotifierMixin, { let self = this; let folderId = this.get('folder.id'); - let importUrl = this.session.appMeta.getUrl('import/folder/' + folderId); + let url = this.get('appMeta.url'); + let importUrl = `${url}/import/folder/${folderId}`; Dropzone.options.uploadDocuments = false; let dzone = new Dropzone("#upload-documents", { headers: { - 'Authorization': 'Bearer ' + self.session.getSessionItem('token') + 'Authorization': 'Bearer ' + self.get('localStorage').getSessionItem('session.session.authenticated.token') }, url: importUrl, method: "post", diff --git a/app/app/components/section/wysiwyg/type-editor.js b/app/app/components/section/wysiwyg/type-editor.js index bbb1a356..ae6e77b5 100644 --- a/app/app/components/section/wysiwyg/type-editor.js +++ b/app/app/components/section/wysiwyg/type-editor.js @@ -1,11 +1,11 @@ // Copyright 2016 Documize Inc. . All rights reserved. // -// This software (Documize Community Edition) is licensed under +// This software (Documize Community Edition) is licensed under // GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html // // You can operate outside the AGPL restrictions by purchasing // Documize Enterprise Edition and obtaining a commercial license -// by contacting . +// by contacting . // // https://documize.com @@ -13,6 +13,7 @@ import Ember from 'ember'; export default Ember.Component.extend({ pageBody: "", + appMeta: Ember.inject.service(), didReceiveAttrs() { this.set('pageBody', this.get('meta.rawBody')); @@ -76,7 +77,7 @@ export default Ember.Component.extend({ }; if (typeof tinymce === 'undefined') { - $.getScript(this.session.appMeta.getBaseUrl("tinymce/tinymce.min.js?v=430"), function() { + $.getScript(this.get("appMeta").getBaseUrl("tinymce/tinymce.min.js?v=430"), function() { window.tinymce.dom.Event.domLoaded = true; tinymce.baseURL = "//" + window.location.host + "/tinymce"; tinymce.suffix = ".min"; @@ -110,4 +111,4 @@ export default Ember.Component.extend({ this.attrs.onAction(page, meta); } } -}); \ No newline at end of file +}); diff --git a/app/app/pods/auth/login/controller.js b/app/app/pods/auth/login/controller.js index a66fcf53..925f4e38 100644 --- a/app/app/pods/auth/login/controller.js +++ b/app/app/pods/auth/login/controller.js @@ -28,6 +28,8 @@ export default Ember.Controller.extend({ .then((response) => { this.get('audit').record("logged-in"); return response; + }).catch(() => { + this.set('invalidCredentials', true); }); } } diff --git a/app/app/services/app-meta.js b/app/app/services/app-meta.js index 823ba906..aff21d9c 100644 --- a/app/app/services/app-meta.js +++ b/app/app/services/app-meta.js @@ -17,6 +17,10 @@ export default Ember.Service.extend({ message: '', allowAnonymousAccess: false, + getBaseUrl(endpoint) { + return [this.get('host'), endpoint].join('/'); + }, + boot() { let dbhash; if (is.not.null(document.head.querySelector("[property=dbhash]"))) { diff --git a/app/app/services/folder.js b/app/app/services/folder.js index d4574009..fbd4f4f4 100644 --- a/app/app/services/folder.js +++ b/app/app/services/folder.js @@ -20,6 +20,8 @@ const { export default BaseService.extend({ sessionService: Ember.inject.service('session'), ajax: Ember.inject.service(), + localStorage: Ember.inject.service(), + // selected folder currentFolder: null, @@ -159,7 +161,7 @@ export default BaseService.extend({ } this.set('currentFolder', folder); - this.get('sessionService').storeSessionItem("folder", get(folder, 'id')); + this.get('localStorage').storeSessionItem("folder", get(folder, 'id')); this.set('canEditCurrentFolder', false); let userId = this.get('sessionService.user.id'); diff --git a/app/app/services/organization.js b/app/app/services/organization.js index 8035429d..cfe86fea 100644 --- a/app/app/services/organization.js +++ b/app/app/services/organization.js @@ -15,6 +15,7 @@ import models from '../utils/model'; export default Ember.Service.extend({ sessionService: Ember.inject.service('session'), ajax: Ember.inject.service(), + appMeta: Ember.inject.service(), // Returns attributes for specified org id. getOrg(id) { @@ -30,9 +31,10 @@ export default Ember.Service.extend({ save(org) { let id = org.get('id'); - // refresh on-screen data - this.get('sessionService').get('appMeta').setSafe('message', org.message); - this.get('sessionService').get('appMeta').setSafe('title', org.title); + this.get('appMeta').setProperties({ + message: org.message, + title: org.title + }); return this.get('ajax').request(`organizations/${id}`, { method: 'PUT', diff --git a/app/app/services/session.js b/app/app/services/session.js index 56603975..95aaaa39 100644 --- a/app/app/services/session.js +++ b/app/app/services/session.js @@ -10,14 +10,12 @@ // https://documize.com import Ember from 'ember'; -import encodingUtil from '../utils/encoding'; -import netUtil from '../utils/net'; import models from '../utils/model'; import SimpleAuthSession from 'ember-simple-auth/services/session'; const { inject: { service }, - computed: { oneWay, or }, + computed: { oneWay, or, notEmpty }, computed } = Ember; @@ -25,34 +23,18 @@ export default SimpleAuthSession.extend({ ajax: service(), appMeta: service(), - authenticated: oneWay('isAuthenticated'), + authenticated: notEmpty('user.id'), isAdmin: oneWay('user.admin'), isEditor: or('user.admin', 'user.editor'), - user: computed('session.content.authenticated.user', function(){ - let user = this.get('session.content.authenticated.user'); - if (user) { + user: computed('isAuthenticated', 'session.content.authenticated.user', function(){ + if (this.get('isAuthenticated')) { + let user = this.get('session.content.authenticated.user') || { id: '' }; return models.UserModel.create(user); } + }), folderPermissions: null, - currentFolder: null, - - clearSession: function() { - // TODO: clear session properly with ESA - localStorage.clear(); - }, - - storeSessionItem: function(key, data) { - localStorage[key] = data; - }, - - getSessionItem: function(key) { - return localStorage[key]; - }, - - clearSessionItem: function(key) { - delete localStorage[key]; - } + currentFolder: null }); From 8a4d0f7e70e2a48d838556e7dd18c211a93b9c48 Mon Sep 17 00:00:00 2001 From: zinyando Date: Thu, 30 Jun 2016 16:45:45 +0200 Subject: [PATCH 16/32] Add restore method to anonymous authenticator --- app/app/authenticators/anonymous.js | 3 +++ app/app/authenticators/documize.js | 1 + 2 files changed, 4 insertions(+) diff --git a/app/app/authenticators/anonymous.js b/app/app/authenticators/anonymous.js index a4e5147c..dfce16cb 100644 --- a/app/app/authenticators/anonymous.js +++ b/app/app/authenticators/anonymous.js @@ -6,6 +6,9 @@ const { } = Ember; export default Base.extend({ + restore(data) { + return resolve(data); + }, authenticate(data) { return resolve(data); } diff --git a/app/app/authenticators/documize.js b/app/app/authenticators/documize.js index 7cfe3886..8fada227 100644 --- a/app/app/authenticators/documize.js +++ b/app/app/authenticators/documize.js @@ -24,6 +24,7 @@ export default Base.extend({ }, authenticate({password, email}) { + debugger; let domain = netUtil.getSubdomain(); if (!isPresent(password) || !isPresent(email)) { From dc164f2f631c866715e70537dcf9718e97c2aca5 Mon Sep 17 00:00:00 2001 From: zinyando Date: Thu, 30 Jun 2016 17:17:44 +0200 Subject: [PATCH 17/32] Prevent tooltips from showing when anonymous is set to true --- app/app/authenticators/documize.js | 1 - app/app/mixins/tooltip.js | 12 +++++++++--- app/app/pods/auth/login/controller.js | 1 + 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/app/app/authenticators/documize.js b/app/app/authenticators/documize.js index 8fada227..7cfe3886 100644 --- a/app/app/authenticators/documize.js +++ b/app/app/authenticators/documize.js @@ -24,7 +24,6 @@ export default Base.extend({ }, authenticate({password, email}) { - debugger; let domain = netUtil.getSubdomain(); if (!isPresent(password) || !isPresent(email)) { diff --git a/app/app/mixins/tooltip.js b/app/app/mixins/tooltip.js index 45f3c9b6..bb7a0a04 100644 --- a/app/app/mixins/tooltip.js +++ b/app/app/mixins/tooltip.js @@ -1,11 +1,11 @@ // Copyright 2016 Documize Inc. . All rights reserved. // -// This software (Documize Community Edition) is licensed under +// This software (Documize Community Edition) is licensed under // GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html // // You can operate outside the AGPL restrictions by purchasing // Documize Enterprise Edition and obtaining a commercial license -// by contacting . +// by contacting . // // https://documize.com @@ -15,9 +15,15 @@ export default Ember.Mixin.create({ tooltips: [], addTooltip(elem) { + + if(elem == null) { + return; + } + let t = new Tooltip({ target: elem }); + let tt = this.get('tooltips'); tt.push(t); }, @@ -33,4 +39,4 @@ export default Ember.Mixin.create({ this.set('tooltips', tt); } -}); \ No newline at end of file +}); diff --git a/app/app/pods/auth/login/controller.js b/app/app/pods/auth/login/controller.js index 925f4e38..f51ab1ce 100644 --- a/app/app/pods/auth/login/controller.js +++ b/app/app/pods/auth/login/controller.js @@ -27,6 +27,7 @@ export default Ember.Controller.extend({ this.get('session').authenticate('authenticator:documize', creds) .then((response) => { this.get('audit').record("logged-in"); + this.transitionToRoute('folders.folder'); return response; }).catch(() => { this.set('invalidCredentials', true); From 42a88bb4419b2efe5e0b77dffd65010099b7dd45 Mon Sep 17 00:00:00 2001 From: zinyando Date: Fri, 1 Jul 2016 18:06:31 +0200 Subject: [PATCH 18/32] Add and use authenticateUser session helper --- app/tests/helpers/authenticate-user.js | 38 ++++++++++++++++++++++ app/tests/helpers/module-for-acceptance.js | 1 - app/tests/helpers/start-app.js | 1 + 3 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 app/tests/helpers/authenticate-user.js diff --git a/app/tests/helpers/authenticate-user.js b/app/tests/helpers/authenticate-user.js new file mode 100644 index 00000000..6b859266 --- /dev/null +++ b/app/tests/helpers/authenticate-user.js @@ -0,0 +1,38 @@ +import Ember from 'ember'; +import { authenticateSession } from 'documize/tests/helpers/ember-simple-auth'; + +const { + merge +} = Ember; + +export default Ember.Test.registerAsyncHelper('authenticateUser', function(app, attrs = {}) { + authenticateSession(app, merge({ + token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkb21haW4iOiIiLCJleHAiOjE0NjQwMjM2NjcsImlzcyI6IkRvY3VtaXplIiwib3JnIjoiVnpNdXlFd18zV3FpYWZjRCIsInN1YiI6IndlYmFwcCIsInVzZXIiOiJWek11eUV3XzNXcWlhZmNFIn0.NXZ6bo8mtvdZF_b9HavbidVUJqhmBA1zr0fSAPvbah0", + user: { + "id": "VzMuyEw_3WqiafcE", + "created": "2016-05-11T15:08:24Z", + "revised": "2016-05-11T15:08:24Z", + "firstname": "Lennex", + "lastname": "Zinyando", + "email": "brizdigital@gmail.com", + "initials": "LZ", + "active": true, + "editor": true, + "admin": true, + "accounts": [{ + "id": "VzMuyEw_3WqiafcF", + "created": "2016-05-11T15:08:24Z", + "revised": "2016-05-11T15:08:24Z", + "admin": true, + "editor": true, + "userId": "VzMuyEw_3WqiafcE", + "orgId": "VzMuyEw_3WqiafcD", + "company": "EmberSherpa", + "title": "EmberSherpa", + "message": "This Documize instance contains all our team documentation", + "domain": "" + }] + } + }, attrs) + ); +}); diff --git a/app/tests/helpers/module-for-acceptance.js b/app/tests/helpers/module-for-acceptance.js index 6d6818e0..f532ceec 100644 --- a/app/tests/helpers/module-for-acceptance.js +++ b/app/tests/helpers/module-for-acceptance.js @@ -7,7 +7,6 @@ export default function(name, options = {}) { beforeEach() { this.application = startApp(); stubAudit(this); - stubSession(this); stubUserNotification(this); if (options.beforeEach) { diff --git a/app/tests/helpers/start-app.js b/app/tests/helpers/start-app.js index 024b70d1..f3ec7b64 100644 --- a/app/tests/helpers/start-app.js +++ b/app/tests/helpers/start-app.js @@ -7,6 +7,7 @@ import './user-login'; import './wait-to-appear'; import './wait-to-disappear'; import './stub-user-notification'; +import './authenticate-user'; export default function startApp(attrs) { let application; From f02ca796f6244886585a7cae6fd1136fb9f45a64 Mon Sep 17 00:00:00 2001 From: zinyando Date: Fri, 1 Jul 2016 18:07:42 +0200 Subject: [PATCH 19/32] Remove login helper from tests and use authenticateUser helper --- app/tests/acceptance/documents-space-test.js | 126 +++++++++---------- app/tests/acceptance/user-profile-test.js | 4 +- app/tests/acceptance/user-settings-test.js | 10 +- 3 files changed, 70 insertions(+), 70 deletions(-) diff --git a/app/tests/acceptance/documents-space-test.js b/app/tests/acceptance/documents-space-test.js index dc7051ef..1032b690 100644 --- a/app/tests/acceptance/documents-space-test.js +++ b/app/tests/acceptance/documents-space-test.js @@ -1,13 +1,13 @@ -import { test } from 'qunit'; +import { test, skip } from 'qunit'; import moduleForAcceptance from 'documize/tests/helpers/module-for-acceptance'; moduleForAcceptance('Acceptance | Documents space'); -test('Adding a new folder space', function(assert) { +skip('Adding a new folder space', function(assert) { server.create('meta', { allowAnonymousAccess: false }); server.createList('folder', 2); server.createList('permission', 4); - userLogin(); + authenticateUser(); visit('/s/VzMuyEw_3WqiafcG/my-project'); andThen(function() { @@ -27,36 +27,36 @@ test('Adding a new folder space', function(assert) { }); }); -// test('Adding a document to a space', function(assert) { -// server.create('meta', { allowAnonymousAccess: false }); -// server.createList('folder', 2); -// server.createList('permission', 4); -// userLogin(); -// visit('/s/VzMuyEw_3WqiafcG/my-project'); -// -// andThen(function() { -// -// let numberOfDocuments = find('.documents-list li').length; -// assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project'); -// assert.equal(numberOfDocuments, 2, '2 documents listed'); -// }); -// -// click('#start-document-button'); -// click('.actions div:contains(Add)', 'body'); -// -// andThen(function() { -// let numberOfDocuments = find('.documents-list li').length; -// assert.equal(numberOfDocuments, 3, '3 documents listed'); -// assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project'); -// // return pauseTest(); -// }); -// }); +skip('Adding a document to a space', function(assert) { + server.create('meta', { allowAnonymousAccess: false }); + server.createList('folder', 2); + server.createList('permission', 4); + authenticateUser(); + visit('/s/VzMuyEw_3WqiafcG/my-project'); + + andThen(function() { + + let numberOfDocuments = find('.documents-list li').length; + assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project'); + assert.equal(numberOfDocuments, 2, '2 documents listed'); + }); + + click('#start-document-button'); + click('.actions div:contains(Add)', 'body'); + + andThen(function() { + let numberOfDocuments = find('.documents-list li').length; + assert.equal(numberOfDocuments, 3, '3 documents listed'); + assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project'); + // return pauseTest(); + }); +}); test('visiting space settings page', function(assert) { server.create('meta', { allowAnonymousAccess: false }); server.createList('folder', 2); server.createList('permission', 4); - userLogin(); + authenticateUser(); visit('/s/VzMuyEw_3WqiafcG/my-project'); click('#folder-settings-button'); @@ -72,7 +72,7 @@ test('changing space name', function(assert) { server.create('meta', { allowAnonymousAccess: false }); server.createList('folder', 2); server.createList('permission', 4); - userLogin(); + authenticateUser(); visit('/s/VzMuyEw_3WqiafcG/my-project/settings'); fillIn('#folderName', 'Test Space'); @@ -90,7 +90,7 @@ test('sharing a space', function(assert) { server.create('meta', { allowAnonymousAccess: false }); server.createList('folder', 2); server.createList('permission', 4); - userLogin(); + authenticateUser(); visit('/s/VzMuyEw_3WqiafcG/my-project/settings'); click(('.sidebar-menu .options li:contains(Share)')); @@ -109,7 +109,7 @@ test('changing space permissions', function(assert) { server.create('meta', { allowAnonymousAccess: false }); server.createList('folder', 2); server.createList('permission', 4); - userLogin(); + authenticateUser(); andThen(function() { let numberOfPublicFolders = find('.folders-list div:first .list a').length; assert.equal(numberOfPublicFolders, 1, '1 folder listed as public'); @@ -136,7 +136,7 @@ test('deleting a space', function(assert) { server.create('meta', { allowAnonymousAccess: false }); server.createList('folder', 2); server.createList('permission', 4); - userLogin(); + authenticateUser(); visit('/s/VzMuyEw_3WqiafcG/my-project/settings'); click('.sidebar-menu .options li:contains(Delete)'); @@ -147,37 +147,37 @@ test('deleting a space', function(assert) { }); }); -// test('deleting a document', function(assert) { -// server.create('meta', { allowAnonymousAccess: false }); -// server.createList('folder', 2); -// server.createList('permission', 4); -// userLogin(); -// visit('/s/VzMuyEw_3WqiafcG/my-project'); -// -// andThen(function() { -// let deleteButton = find('#delete-documents-button'); -// let numberOfDocuments = find('.documents-list li'); -// assert.equal(numberOfDocuments.length, 2, '2 documents are displayed'); -// assert.equal(deleteButton.length, 0, 'Delete button not displayed'); -// }); -// -// click('.documents-list li:first .checkbox'); -// -// andThen(function() { -// let deleteButton = find('#delete-documents-button'); -// assert.equal(deleteButton.length, 1, 'Delete button displayed after selecting document'); -// }); -// -// click('#delete-documents-button'); -// -// waitToAppear('.drop-content'); -// click('.actions div:contains(Delete)', 'body'); -// -// andThen(function() { -// let numberOfDocuments = find('.documents-list li'); -// assert.equal(numberOfDocuments.length, 1, '1 documents is displayed'); -// }); -// }); +skip('deleting a document', function(assert) { + server.create('meta', { allowAnonymousAccess: false }); + server.createList('folder', 2); + server.createList('permission', 4); + authenticateUser(); + visit('/s/VzMuyEw_3WqiafcG/my-project'); + + andThen(function() { + let deleteButton = find('#delete-documents-button'); + let numberOfDocuments = find('.documents-list li'); + assert.equal(numberOfDocuments.length, 2, '2 documents are displayed'); + assert.equal(deleteButton.length, 0, 'Delete button not displayed'); + }); + + click('.documents-list li:first .checkbox'); + + andThen(function() { + let deleteButton = find('#delete-documents-button'); + assert.equal(deleteButton.length, 1, 'Delete button displayed after selecting document'); + }); + + click('#delete-documents-button'); + + waitToAppear('.drop-content'); + click('.actions div:contains(Delete)', 'body'); + + andThen(function() { + let numberOfDocuments = find('.documents-list li'); + assert.equal(numberOfDocuments.length, 1, '1 documents is displayed'); + }); +}); function checkForCommonAsserts() { findWithAssert('.sidebar-menu'); diff --git a/app/tests/acceptance/user-profile-test.js b/app/tests/acceptance/user-profile-test.js index a0be37c7..944ddf55 100644 --- a/app/tests/acceptance/user-profile-test.js +++ b/app/tests/acceptance/user-profile-test.js @@ -5,7 +5,7 @@ moduleForAcceptance('Acceptance | user profile'); test('visiting /profile', function(assert) { server.createList('folder', 2); - userLogin(); + authenticateUser(); visit('/profile'); andThen(function() { @@ -18,7 +18,7 @@ test('visiting /profile', function(assert) { test('changing user details and email ', function(assert) { server.createList('folder', 2); - userLogin(); + authenticateUser(); visit('/profile'); andThen(function() { diff --git a/app/tests/acceptance/user-settings-test.js b/app/tests/acceptance/user-settings-test.js index 95328d58..acac7376 100644 --- a/app/tests/acceptance/user-settings-test.js +++ b/app/tests/acceptance/user-settings-test.js @@ -5,7 +5,7 @@ moduleForAcceptance('Acceptance | User Settings'); test('visiting /settings/general', function(assert) { server.create('meta', { allowAnonymousAccess: false }); - userLogin(); + authenticateUser(); visit('/settings/general'); andThen(function() { @@ -18,7 +18,7 @@ test('visiting /settings/general', function(assert) { test('changing the Website title and description', function(assert) { server.create('meta', { allowAnonymousAccess: false }); - userLogin(); + authenticateUser(); visit('/settings/general'); andThen(function() { @@ -39,7 +39,7 @@ test('changing the Website title and description', function(assert) { test('visiting /settings/folders', function(assert) { server.create('meta', { allowAnonymousAccess: false }); - userLogin(); + authenticateUser(); visit('/settings/folders'); andThen(function() { @@ -50,7 +50,7 @@ test('visiting /settings/folders', function(assert) { test('visiting /settings/users', function(assert) { server.create('meta', { allowAnonymousAccess: false }); - userLogin(); + authenticateUser(); visit('/settings/users'); andThen(function() { @@ -64,7 +64,7 @@ test('visiting /settings/users', function(assert) { test('add a new user', function(assert) { server.create('meta', { allowAnonymousAccess: false }); - userLogin(); + authenticateUser(); visit('/settings/users'); andThen(function() { From bc0de90bfac201fd0812045165a161a3ff1c0822 Mon Sep 17 00:00:00 2001 From: zinyando Date: Mon, 4 Jul 2016 11:19:19 +0200 Subject: [PATCH 20/32] Add authenticateUser to tests jshint --- app/tests/.jshintrc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/tests/.jshintrc b/app/tests/.jshintrc index ce9a4986..6be92267 100644 --- a/app/tests/.jshintrc +++ b/app/tests/.jshintrc @@ -31,7 +31,8 @@ "waitToAppear", "waitToAppear", "stubUserNotification", - "is" + "is", + "authenticateUser" ], "node": false, "browser": false, From 96baf84f1d5f6bb3ef9fbec2d6f8d2ea14694468 Mon Sep 17 00:00:00 2001 From: zinyando Date: Mon, 4 Jul 2016 12:01:15 +0200 Subject: [PATCH 21/32] Fix isFolderOwner issue --- app/app/components/folder/folder-toolbar.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/app/components/folder/folder-toolbar.js b/app/app/components/folder/folder-toolbar.js index b523bba0..ea1140c1 100644 --- a/app/app/components/folder/folder-toolbar.js +++ b/app/app/components/folder/folder-toolbar.js @@ -21,6 +21,7 @@ export default Ember.Component.extend(NotifierMixin, TooltipMixin, { documentService: Ember.inject.service('document'), templateService: Ember.inject.service('template'), folderService: Ember.inject.service('folder'), + session: Ember.inject.service(), folder: {}, busy: false, @@ -30,7 +31,7 @@ export default Ember.Component.extend(NotifierMixin, TooltipMixin, { moveFolderId: "", didReceiveAttrs() { - this.set('isFolderOwner', this.get('folder.userId') === this.session.user.id); + this.set('isFolderOwner', this.get('folder.userId') === this.get("session.user.id")); let self = this; From 5333cf22f48c832fea86f16eb634eb938b924493 Mon Sep 17 00:00:00 2001 From: zinyando Date: Mon, 4 Jul 2016 12:58:29 +0200 Subject: [PATCH 22/32] WIP Test fixes --- app/app/pods/profile/controller.js | 1 + app/tests/acceptance/documents-space-test.js | 1 + app/tests/acceptance/user-profile-test.js | 2 +- app/tests/acceptance/user-settings-test.js | 3 +- app/tests/helpers/start-app.js | 1 - app/tests/helpers/stub-session.js | 63 -------------------- 6 files changed, 4 insertions(+), 67 deletions(-) delete mode 100644 app/tests/helpers/stub-session.js diff --git a/app/app/pods/profile/controller.js b/app/app/pods/profile/controller.js index 90321893..befce44f 100644 --- a/app/app/pods/profile/controller.js +++ b/app/app/pods/profile/controller.js @@ -3,6 +3,7 @@ import Ember from 'ember'; export default Ember.Controller.extend({ userService: Ember.inject.service('user'), password: { password: "", confirmation: ""}, + session: Ember.inject.service(), actions: { save: function() { diff --git a/app/tests/acceptance/documents-space-test.js b/app/tests/acceptance/documents-space-test.js index 1032b690..4a28d3a8 100644 --- a/app/tests/acceptance/documents-space-test.js +++ b/app/tests/acceptance/documents-space-test.js @@ -74,6 +74,7 @@ test('changing space name', function(assert) { server.createList('permission', 4); authenticateUser(); visit('/s/VzMuyEw_3WqiafcG/my-project/settings'); + return pauseTest(); fillIn('#folderName', 'Test Space'); click('.button-blue'); diff --git a/app/tests/acceptance/user-profile-test.js b/app/tests/acceptance/user-profile-test.js index 944ddf55..b4a72cc5 100644 --- a/app/tests/acceptance/user-profile-test.js +++ b/app/tests/acceptance/user-profile-test.js @@ -23,7 +23,7 @@ test('changing user details and email ', function(assert) { andThen(function() { assert.equal(currentURL(), '/profile'); - assert.equal(find('.name').text().trim(), 'Lennex Zinyando', 'Profile name displayed'); + assert.equal(find('.content .name').text().trim(), 'Lennex Zinyando', 'Profile name displayed'); assert.equal(find('#firstname').val(), 'Lennex', 'Firstaname input displays correct value'); assert.equal(find('#lastname').val(), 'Zinyando', 'Lastname input displays correct value'); assert.equal(find('#email').val(), 'brizdigital@gmail.com', 'Email input displays correct value'); diff --git a/app/tests/acceptance/user-settings-test.js b/app/tests/acceptance/user-settings-test.js index acac7376..f4fa0d95 100644 --- a/app/tests/acceptance/user-settings-test.js +++ b/app/tests/acceptance/user-settings-test.js @@ -95,6 +95,5 @@ function checkForCommonAsserts() { findWithAssert('.sidebar-menu'); findWithAssert('#user-button'); findWithAssert('#accounts-button'); - findWithAssert('a:contains(Dashboard)'); - findWithAssert('a:contains(Settings)'); + findWithAssert('.info .title'); } diff --git a/app/tests/helpers/start-app.js b/app/tests/helpers/start-app.js index f3ec7b64..1d1582e3 100644 --- a/app/tests/helpers/start-app.js +++ b/app/tests/helpers/start-app.js @@ -1,7 +1,6 @@ import Ember from 'ember'; import Application from '../../app'; import config from '../../config/environment'; -import './stub-session'; import './stub-audit'; import './user-login'; import './wait-to-appear'; diff --git a/app/tests/helpers/stub-session.js b/app/tests/helpers/stub-session.js deleted file mode 100644 index 933616ae..00000000 --- a/app/tests/helpers/stub-session.js +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2016 Documize Inc. . All rights reserved. -// -// This software (Documize Community Edition) is licensed under -// GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html -// -// You can operate outside the AGPL restrictions by purchasing -// Documize Enterprise Edition and obtaining a commercial license -// by contacting . -// -// https://documize.com - -import Ember from 'ember'; -import encodingUtil from 'documize/utils/encoding'; -import netUtil from 'documize/utils/net'; -import models from 'documize/utils/model'; -import SimpleAuthSession from 'ember-simple-auth/services/session'; - -const { - inject: { service }, - computed: { oneWay, or }, - computed -} = Ember; - -const Session = SimpleAuthSession.extend({ - ajax: service(), - appMeta: service(), - - authenticated: oneWay('isAuthenticated'), - isAdmin: oneWay('user.admin'), - isEditor: or('user.admin', 'user.editor'), - - user: computed('session.content.authenticated.user', function(){ - let user = this.get('session.content.authenticated.user'); - if (user) { - return models.UserModel.create(user); - } - }), - - folderPermissions: null, - currentFolder: null, - - clearSession: function() { - // TODO: clear session properly with ESA - // localStorage.clear(); - }, - - storeSessionItem: function() { - // localStorage[key] = data; - }, - - getSessionItem: function() { - // return localStorage[key]; - }, - - clearSessionItem: function() { - // delete localStorage[key]; - } -}); - - -export default Ember.Test.registerAsyncHelper('stubSession', function(app, test, attrs={}) { - test.register('service:session', Session.extend(attrs)); -}); From 53f7edf533b8dbfdc3269eb3a0d97a4fad9d19b9 Mon Sep 17 00:00:00 2001 From: zinyando Date: Mon, 4 Jul 2016 16:56:10 +0200 Subject: [PATCH 23/32] Fix document space tests --- app/tests/acceptance/documents-space-test.js | 33 +++++++++++++------- 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/app/tests/acceptance/documents-space-test.js b/app/tests/acceptance/documents-space-test.js index 4a28d3a8..37976322 100644 --- a/app/tests/acceptance/documents-space-test.js +++ b/app/tests/acceptance/documents-space-test.js @@ -73,14 +73,15 @@ test('changing space name', function(assert) { server.createList('folder', 2); server.createList('permission', 4); authenticateUser(); - visit('/s/VzMuyEw_3WqiafcG/my-project/settings'); - return pauseTest(); + visit('/s/VzMuyEw_3WqiafcG/my-project'); + + click('#folder-settings-button'); fillIn('#folderName', 'Test Space'); click('.button-blue'); andThen(function() { - let spaceName = find('.breadcrumb-menu .selected').text().trim(); + let spaceName = find('.info .title').text().trim(); checkForCommonAsserts(); assert.equal(spaceName, 'Test Space', 'Space name has been changed'); assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project/settings'); @@ -92,7 +93,9 @@ test('sharing a space', function(assert) { server.createList('folder', 2); server.createList('permission', 4); authenticateUser(); - visit('/s/VzMuyEw_3WqiafcG/my-project/settings'); + visit('/s/VzMuyEw_3WqiafcG/my-project'); + + click('#folder-settings-button'); click(('.sidebar-menu .options li:contains(Share)')); fillIn('#inviteEmail', 'share-test@gmail.com'); @@ -111,25 +114,29 @@ test('changing space permissions', function(assert) { server.createList('folder', 2); server.createList('permission', 4); authenticateUser(); + + visit('/s/VzMygEw_3WrtFzto/test'); andThen(function() { - let numberOfPublicFolders = find('.folders-list div:first .list a').length; + let numberOfPublicFolders = find('.sidebar-menu .folders-list .section .list:first a').length; assert.equal(numberOfPublicFolders, 1, '1 folder listed as public'); - assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project'); + assert.equal(currentURL(), '/s/VzMygEw_3WrtFzto/test'); }); - visit('/s/VzMygEw_3WrtFzto/test/settings'); - click(('.sidebar-menu .options li:contains(Permissions)')); + click('#folder-settings-button'); + + click('.sidebar-menu .options li:contains(Permissions)'); click('tr:contains(Everyone) #canView-'); click('tr:contains(Everyone) #canEdit-'); click('.button-blue'); - visit('/s/VzMuyEw_3WqiafcG/my-project'); + visit('/s/VzMygEw_3WrtFzto/test'); + // return pauseTest(); andThen(function() { - let numberOfPublicFolders = find('.folders-list div:first .list a').length; + let numberOfPublicFolders = find('.folders-list div:contains(EVERYONE) .list a').length; assert.equal(numberOfPublicFolders, 2, '2 folder listed as public'); - assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project'); + assert.equal(currentURL(), '/s/VzMygEw_3WrtFzto/test'); }); }); @@ -138,7 +145,9 @@ test('deleting a space', function(assert) { server.createList('folder', 2); server.createList('permission', 4); authenticateUser(); - visit('/s/VzMuyEw_3WqiafcG/my-project/settings'); + visit('/s/VzMuyEw_3WqiafcG/my-project'); + + click('#folder-settings-button'); click('.sidebar-menu .options li:contains(Delete)'); From 881da18e8a561d79e77616dfa3569171406723f5 Mon Sep 17 00:00:00 2001 From: zinyando Date: Mon, 4 Jul 2016 16:57:14 +0200 Subject: [PATCH 24/32] Add missing isMac and isMobile flags to session service --- app/app/services/session.js | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/app/app/services/session.js b/app/app/services/session.js index 95aaaa39..8bf7d180 100644 --- a/app/app/services/session.js +++ b/app/app/services/session.js @@ -23,10 +23,17 @@ export default SimpleAuthSession.extend({ ajax: service(), appMeta: service(), + isMac: false, + isMobile: false, authenticated: notEmpty('user.id'), isAdmin: oneWay('user.admin'), isEditor: or('user.admin', 'user.editor'), + init: function() { + this.set('isMac', is.mac()); + this.set('isMobile', is.mobile()); + }, + user: computed('isAuthenticated', 'session.content.authenticated.user', function(){ if (this.get('isAuthenticated')) { let user = this.get('session.content.authenticated.user') || { id: '' }; From e26108b90b590d600f577310557c75c100205bbb Mon Sep 17 00:00:00 2001 From: zinyando Date: Tue, 5 Jul 2016 16:52:20 +0200 Subject: [PATCH 25/32] Add SSO test --- .../acceptance/anon-access-disabled-test.js | 5 +-- .../acceptance/anon-access-enabled-test.js | 16 +++---- app/tests/acceptance/authentication-test.js | 24 ++++++++--- app/tests/acceptance/documents-space-test.js | 43 +++++++++---------- app/tests/acceptance/user-profile-test.js | 10 ++--- app/tests/acceptance/user-settings-test.js | 26 +++++------ 6 files changed, 67 insertions(+), 57 deletions(-) diff --git a/app/tests/acceptance/anon-access-disabled-test.js b/app/tests/acceptance/anon-access-disabled-test.js index 5a260c6a..1eb81d29 100644 --- a/app/tests/acceptance/anon-access-disabled-test.js +++ b/app/tests/acceptance/anon-access-disabled-test.js @@ -3,13 +3,12 @@ import moduleForAcceptance from 'documize/tests/helpers/module-for-acceptance'; moduleForAcceptance('Acceptance | Anon access disabled'); - -test('visiting / when not authenticated and with { allowAnonymousAccess: false } takes user to login', function(assert) { +test('visiting / when not authenticated and with { allowAnonymousAccess: false } takes user to login', function (assert) { server.create('meta', { allowAnonymousAccess: false }); server.createList('folder', 2); visit('/'); - andThen(function() { + andThen(function () { assert.equal(currentURL(), '/auth/login'); findWithAssert('#authEmail'); findWithAssert('#authPassword'); diff --git a/app/tests/acceptance/anon-access-enabled-test.js b/app/tests/acceptance/anon-access-enabled-test.js index 5ec94855..55016bcc 100644 --- a/app/tests/acceptance/anon-access-enabled-test.js +++ b/app/tests/acceptance/anon-access-enabled-test.js @@ -3,33 +3,33 @@ import moduleForAcceptance from 'documize/tests/helpers/module-for-acceptance'; moduleForAcceptance('Acceptance | Anon access enabled'); -test('visiting / when not authenticated and with { allowAnonymousAccess: true } takes user to folder view', function(assert) { +test('visiting / when not authenticated and with { allowAnonymousAccess: true } takes user to folder view', function (assert) { server.create('meta', { allowAnonymousAccess: true }); server.createList('folder', 2); visit('/'); // return pauseTest(); - andThen(function() { + andThen(function () { assert.equal(find('.login').length, 1, 'Login button is displayed'); assert.equal(find('.documents-list .document').length, 2, '2 document displayed'); - assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project', 'Dashboard and public spaces are displayed without being signed in'); + assert.equal(currentURL(), '/s/VzMygEw_3WrtFzto/test', 'Dashboard and public spaces are displayed without being signed in'); }); }); -test('visiting / when authenticated and with { allowAnonymousAccess: true } takes user to dashboard', function(assert) { +test('visiting / when authenticated and with { allowAnonymousAccess: true } takes user to dashboard', function (assert) { server.create('meta', { allowAnonymousAccess: true }); server.createList('folder', 2); visit('/'); - andThen(function() { + andThen(function () { assert.equal(find('.login').length, 1, 'Login button is displayed'); - assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project', 'Dashboard displayed without being signed in'); + assert.equal(currentURL(), '/s/VzMygEw_3WrtFzto/test', 'Dashboard displayed without being signed in'); }); userLogin(); - andThen(function() { + andThen(function () { assert.equal(find('.login').length, 0, 'Login button is not displayed'); - assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project', 'Dashboard is displayed after user is signed in'); + assert.equal(currentURL(), '/s/VzMygEw_3WrtFzto/test', 'Dashboard is displayed after user is signed in'); }); }); diff --git a/app/tests/acceptance/authentication-test.js b/app/tests/acceptance/authentication-test.js index 2a53d7e0..1dad3283 100644 --- a/app/tests/acceptance/authentication-test.js +++ b/app/tests/acceptance/authentication-test.js @@ -3,7 +3,7 @@ import moduleForAcceptance from 'documize/tests/helpers/module-for-acceptance'; moduleForAcceptance('Acceptance | Authentication'); -test('visiting /auth/login and logging in', function(assert) { +test('visiting /auth/login and logging in', function (assert) { server.create('meta', { allowAnonymousAccess: false }); server.createList('folder', 2); visit('/auth/login'); @@ -12,19 +12,31 @@ test('visiting /auth/login and logging in', function(assert) { fillIn('#authPassword', 'zinyando123'); click('button'); - andThen(function() { - assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project', 'Login successfull'); + andThen(function () { + assert.equal(currentURL(), '/s/VzMygEw_3WrtFzto/test', 'Login successfull'); }); }); -test('logging out a user', function(assert) { +test('logging out a user', function (assert) { server.create('meta', { allowAnonymousAccess: false }); server.createList('folder', 2); userLogin(); visit('/auth/logout'); - andThen(function() { - assert.equal(currentURL(), '/auth/login', 'Login successfull'); + andThen(function () { + assert.equal(currentURL(), '/auth/login', 'Logging out successfull'); + }); +}); + +test('sso login', function (assert) { + server.create('meta', { allowAnonymousAccess: false }); + server.createList('folder', 2); + userLogin(); + + visit('/auth/sso/OmJyaXpkaWdpdGFsQGdtYWlsLmNvbTp6aW55YW5kbzEyMw=='); + + andThen(function () { + assert.equal(currentURL(), '/s/VzMygEw_3WrtFzto/test', 'Login successfull'); }); }); diff --git a/app/tests/acceptance/documents-space-test.js b/app/tests/acceptance/documents-space-test.js index 37976322..e7549177 100644 --- a/app/tests/acceptance/documents-space-test.js +++ b/app/tests/acceptance/documents-space-test.js @@ -3,14 +3,14 @@ import moduleForAcceptance from 'documize/tests/helpers/module-for-acceptance'; moduleForAcceptance('Acceptance | Documents space'); -skip('Adding a new folder space', function(assert) { +skip('Adding a new folder space', function (assert) { server.create('meta', { allowAnonymousAccess: false }); server.createList('folder', 2); server.createList('permission', 4); authenticateUser(); visit('/s/VzMuyEw_3WqiafcG/my-project'); - andThen(function() { + andThen(function () { let personalSpaces = find('.section div:contains(PERSONAL)').length; assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project'); assert.equal(personalSpaces, 1, '1 personal space is listed'); @@ -22,19 +22,19 @@ skip('Adding a new folder space', function(assert) { click('.actions div:contains(Add)', 'body'); - andThen(function() { + andThen(function () { assert.equal(currentURL(), '/s/V0Vy5Uw_3QeDAMW9/test-folder'); }); }); -skip('Adding a document to a space', function(assert) { +skip('Adding a document to a space', function (assert) { server.create('meta', { allowAnonymousAccess: false }); server.createList('folder', 2); server.createList('permission', 4); authenticateUser(); visit('/s/VzMuyEw_3WqiafcG/my-project'); - andThen(function() { + andThen(function () { let numberOfDocuments = find('.documents-list li').length; assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project'); @@ -44,7 +44,7 @@ skip('Adding a document to a space', function(assert) { click('#start-document-button'); click('.actions div:contains(Add)', 'body'); - andThen(function() { + andThen(function () { let numberOfDocuments = find('.documents-list li').length; assert.equal(numberOfDocuments, 3, '3 documents listed'); assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project'); @@ -52,7 +52,7 @@ skip('Adding a document to a space', function(assert) { }); }); -test('visiting space settings page', function(assert) { +test('visiting space settings page', function (assert) { server.create('meta', { allowAnonymousAccess: false }); server.createList('folder', 2); server.createList('permission', 4); @@ -61,14 +61,14 @@ test('visiting space settings page', function(assert) { click('#folder-settings-button'); - andThen(function() { + andThen(function () { checkForCommonAsserts(); assert.equal(find('#folderName').val().trim(), 'My Project', 'Space name displayed in input box'); assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project/settings'); }); }); -test('changing space name', function(assert) { +test('changing space name', function (assert) { server.create('meta', { allowAnonymousAccess: false }); server.createList('folder', 2); server.createList('permission', 4); @@ -80,7 +80,7 @@ test('changing space name', function(assert) { fillIn('#folderName', 'Test Space'); click('.button-blue'); - andThen(function() { + andThen(function () { let spaceName = find('.info .title').text().trim(); checkForCommonAsserts(); assert.equal(spaceName, 'Test Space', 'Space name has been changed'); @@ -88,7 +88,7 @@ test('changing space name', function(assert) { }); }); -test('sharing a space', function(assert) { +test('sharing a space', function (assert) { server.create('meta', { allowAnonymousAccess: false }); server.createList('folder', 2); server.createList('permission', 4); @@ -101,22 +101,21 @@ test('sharing a space', function(assert) { fillIn('#inviteEmail', 'share-test@gmail.com'); click('.button-blue'); - andThen(function() { + andThen(function () { checkForCommonAsserts(); assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project/settings'); }); }); - // Test will pass after moving to factories -test('changing space permissions', function(assert) { +test('changing space permissions', function (assert) { server.create('meta', { allowAnonymousAccess: false }); server.createList('folder', 2); server.createList('permission', 4); authenticateUser(); visit('/s/VzMygEw_3WrtFzto/test'); - andThen(function() { + andThen(function () { let numberOfPublicFolders = find('.sidebar-menu .folders-list .section .list:first a').length; assert.equal(numberOfPublicFolders, 1, '1 folder listed as public'); assert.equal(currentURL(), '/s/VzMygEw_3WrtFzto/test'); @@ -133,14 +132,14 @@ test('changing space permissions', function(assert) { visit('/s/VzMygEw_3WrtFzto/test'); // return pauseTest(); - andThen(function() { + andThen(function () { let numberOfPublicFolders = find('.folders-list div:contains(EVERYONE) .list a').length; assert.equal(numberOfPublicFolders, 2, '2 folder listed as public'); assert.equal(currentURL(), '/s/VzMygEw_3WrtFzto/test'); }); }); -test('deleting a space', function(assert) { +test('deleting a space', function (assert) { server.create('meta', { allowAnonymousAccess: false }); server.createList('folder', 2); server.createList('permission', 4); @@ -151,20 +150,20 @@ test('deleting a space', function(assert) { click('.sidebar-menu .options li:contains(Delete)'); - andThen(function() { + andThen(function () { checkForCommonAsserts(); assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project/settings'); }); }); -skip('deleting a document', function(assert) { +skip('deleting a document', function (assert) { server.create('meta', { allowAnonymousAccess: false }); server.createList('folder', 2); server.createList('permission', 4); authenticateUser(); visit('/s/VzMuyEw_3WqiafcG/my-project'); - andThen(function() { + andThen(function () { let deleteButton = find('#delete-documents-button'); let numberOfDocuments = find('.documents-list li'); assert.equal(numberOfDocuments.length, 2, '2 documents are displayed'); @@ -173,7 +172,7 @@ skip('deleting a document', function(assert) { click('.documents-list li:first .checkbox'); - andThen(function() { + andThen(function () { let deleteButton = find('#delete-documents-button'); assert.equal(deleteButton.length, 1, 'Delete button displayed after selecting document'); }); @@ -183,7 +182,7 @@ skip('deleting a document', function(assert) { waitToAppear('.drop-content'); click('.actions div:contains(Delete)', 'body'); - andThen(function() { + andThen(function () { let numberOfDocuments = find('.documents-list li'); assert.equal(numberOfDocuments.length, 1, '1 documents is displayed'); }); diff --git a/app/tests/acceptance/user-profile-test.js b/app/tests/acceptance/user-profile-test.js index b4a72cc5..bc9da034 100644 --- a/app/tests/acceptance/user-profile-test.js +++ b/app/tests/acceptance/user-profile-test.js @@ -3,12 +3,12 @@ import moduleForAcceptance from 'documize/tests/helpers/module-for-acceptance'; moduleForAcceptance('Acceptance | user profile'); -test('visiting /profile', function(assert) { +test('visiting /profile', function (assert) { server.createList('folder', 2); authenticateUser(); visit('/profile'); - andThen(function() { + andThen(function () { assert.equal(currentURL(), '/profile'); assert.equal(find('#firstname').val(), 'Lennex', 'Firstaname input displays correct value'); assert.equal(find('#lastname').val(), 'Zinyando', 'Lastname input displays correct value'); @@ -16,12 +16,12 @@ test('visiting /profile', function(assert) { }); }); -test('changing user details and email ', function(assert) { +test('changing user details and email ', function (assert) { server.createList('folder', 2); authenticateUser(); visit('/profile'); - andThen(function() { + andThen(function () { assert.equal(currentURL(), '/profile'); assert.equal(find('.content .name').text().trim(), 'Lennex Zinyando', 'Profile name displayed'); assert.equal(find('#firstname').val(), 'Lennex', 'Firstaname input displays correct value'); @@ -34,7 +34,7 @@ test('changing user details and email ', function(assert) { fillIn('#email', 'test.user@domain.com'); click('.button-blue'); - andThen(function() { + andThen(function () { assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project'); assert.equal(find('.content .name').text().trim(), 'Test User', 'Profile name displayed'); }); diff --git a/app/tests/acceptance/user-settings-test.js b/app/tests/acceptance/user-settings-test.js index f4fa0d95..ff4bca6a 100644 --- a/app/tests/acceptance/user-settings-test.js +++ b/app/tests/acceptance/user-settings-test.js @@ -1,14 +1,14 @@ -import { test} from 'qunit'; +import { test } from 'qunit'; import moduleForAcceptance from 'documize/tests/helpers/module-for-acceptance'; moduleForAcceptance('Acceptance | User Settings'); -test('visiting /settings/general', function(assert) { +test('visiting /settings/general', function (assert) { server.create('meta', { allowAnonymousAccess: false }); authenticateUser(); visit('/settings/general'); - andThen(function() { + andThen(function () { assert.equal(currentURL(), '/settings/general'); assert.equal(find('#siteTitle').val(), 'EmberSherpa', 'Website title input is filled in correctly'); assert.equal(find('textarea').val(), 'This Documize instance contains all our team documentation', 'Message is set correctly'); @@ -16,12 +16,12 @@ test('visiting /settings/general', function(assert) { }); }); -test('changing the Website title and description', function(assert) { +test('changing the Website title and description', function (assert) { server.create('meta', { allowAnonymousAccess: false }); authenticateUser(); visit('/settings/general'); - andThen(function() { + andThen(function () { let websiteTitle = find('.content .title').text().trim(); let websiteTitleInput = find('#siteTitle').val(); assert.equal(websiteTitleInput, websiteTitle, 'Website title is set to EmberSherpa'); @@ -30,30 +30,30 @@ test('changing the Website title and description', function(assert) { fillIn('#siteTitle', 'Documize Tests'); click('.button-blue'); - andThen(function() { + andThen(function () { let websiteTitle = find('.content .title').text().trim(); let websiteTitleInput = find('#siteTitle').val(); assert.equal(websiteTitleInput, websiteTitle, 'Website title is set to Documize Tests'); }); }); -test('visiting /settings/folders', function(assert) { +test('visiting /settings/folders', function (assert) { server.create('meta', { allowAnonymousAccess: false }); authenticateUser(); visit('/settings/folders'); - andThen(function() { + andThen(function () { checkForCommonAsserts(); assert.equal(currentURL(), '/settings/folders'); }); }); -test('visiting /settings/users', function(assert) { +test('visiting /settings/users', function (assert) { server.create('meta', { allowAnonymousAccess: false }); authenticateUser(); visit('/settings/users'); - andThen(function() { + andThen(function () { checkForCommonAsserts(); findWithAssert('.user-list'); let numberOfUsers = find('.user-list tr').length; @@ -62,12 +62,12 @@ test('visiting /settings/users', function(assert) { }); }); -test('add a new user', function(assert) { +test('add a new user', function (assert) { server.create('meta', { allowAnonymousAccess: false }); authenticateUser(); visit('/settings/users'); - andThen(function() { + andThen(function () { checkForCommonAsserts(); findWithAssert('.user-list'); let numberOfUsers = find('.user-list tr').length; @@ -83,7 +83,7 @@ test('add a new user', function(assert) { // waitToAppear('.user-notification:contains(Added)'); // waitToDisappear('.user-notification:contains(Added)'); - andThen(function() { + andThen(function () { let numberOfUsers = find('.user-list tr').length; assert.equal(numberOfUsers, 4, '3 Users listed'); assert.equal(currentURL(), '/settings/users'); From 3dccfc6a2415360bd086780750fc817918e137c7 Mon Sep 17 00:00:00 2001 From: zinyando Date: Tue, 5 Jul 2016 16:54:31 +0200 Subject: [PATCH 26/32] Fix SSO issue --- app/app/authenticators/documize.js | 22 +++++-- app/app/pods/auth/sso/route.js | 31 ++++------ app/app/pods/folders/folder/controller.js | 54 ++++++++--------- app/app/pods/folders/settings/route.js | 61 ++++++++++---------- app/app/router.js | 12 ++-- app/app/routes/application.js | 70 +++++++++++------------ app/app/services/session.js | 2 +- 7 files changed, 128 insertions(+), 124 deletions(-) diff --git a/app/app/authenticators/documize.js b/app/app/authenticators/documize.js index 7cfe3886..e68591eb 100644 --- a/app/app/authenticators/documize.js +++ b/app/app/authenticators/documize.js @@ -23,14 +23,26 @@ export default Base.extend({ return reject(); }, - authenticate({password, email}) { + authenticate(credentials) { let domain = netUtil.getSubdomain(); - if (!isPresent(password) || !isPresent(email)) { - return Ember.RSVP.reject("invalid"); - } + let encoded; - var encoded = encodingUtil.Base64.encode(`${domain}:${email}:${password}`); + if (typeof credentials === 'object') { + + let { password, email } = credentials; + + if (!isPresent(password) || !isPresent(email)) { + return Ember.RSVP.reject("invalid"); + } + + encoded = encodingUtil.Base64.encode(`${domain}:${email}:${password}`); + } else if (typeof credentials === 'string') { + encoded = credentials; + } else { + return Ember.RSVP.reject("invalid"); + + } var headers = { 'Authorization': 'Basic ' + encoded diff --git a/app/app/pods/auth/sso/route.js b/app/app/pods/auth/sso/route.js index 99757766..83372b42 100644 --- a/app/app/pods/auth/sso/route.js +++ b/app/app/pods/auth/sso/route.js @@ -1,24 +1,15 @@ import Ember from 'ember'; export default Ember.Route.extend({ - beforeModel() { - this.session.clearSession(); + session: Ember.inject.service(), + + model({ token }) { + this.get("session").authenticate('authenticator:documize', token) + .then(() => { + this.transitionTo('folders.folder'); + }, () => { + this.transitionTo('auth.login'); + console.log(">>>>> Documize SSO failure"); + }); }, - - model(params) { - let token = params.token; - - if (is.undefined(token) || is.null(token) || token.length === 0) { - return; - } - - let self = this; - - this.session.sso(decodeURIComponent(token)).then(function() { - self.transitionTo('folders.folder'); - }, function() { - self.transitionTo('auth.login'); - console.log(">>>>> Documize SSO failure"); - }); - }, -}); \ No newline at end of file +}); diff --git a/app/app/pods/folders/folder/controller.js b/app/app/pods/folders/folder/controller.js index 8237cb61..0ac0a7b4 100644 --- a/app/app/pods/folders/folder/controller.js +++ b/app/app/pods/folders/folder/controller.js @@ -3,8 +3,8 @@ import NotifierMixin from '../../../mixins/notifier'; export default Ember.Controller.extend(NotifierMixin, { documentService: Ember.inject.service('document'), - folderService: Ember.inject.service('folder'), - hasSelectedDocuments: false, + folderService: Ember.inject.service('folder'), + hasSelectedDocuments: false, selectedDocuments: [], actions: { @@ -12,56 +12,56 @@ export default Ember.Controller.extend(NotifierMixin, { this.get('target.router').refresh(); }, - onDocumentsChecked(documents) { + onDocumentsChecked(documents) { this.set('selectedDocuments', documents); this.set('hasSelectedDocuments', documents.length > 0); }, onMoveDocument(folder) { let self = this; - let documents = this.get('selectedDocuments'); + let documents = this.get('selectedDocuments'); - documents.forEach(function(documentId) { - self.get('documentService').getDocument(documentId).then(function(doc) { + documents.forEach(function (documentId) { + self.get('documentService').getDocument(documentId).then(function (doc) { doc.set('folderId', folder); - self.get('documentService').save(doc).then(function() { + self.get('documentService').save(doc).then(function () { self.get('target.router').refresh(); }); }); }); - this.set('selectedDocuments', []); - this.set('hasSelectedDocuments', false); - this.send("showNotification", "Moved"); + this.set('selectedDocuments', []); + this.set('hasSelectedDocuments', false); + this.send("showNotification", "Moved"); }, - onDeleteDocument() { - let documents = this.get('selectedDocuments'); - let self = this; + onDeleteDocument() { + let documents = this.get('selectedDocuments'); + let self = this; - documents.forEach(function(document) { - self.get('documentService').deleteDocument(document).then(function() { - self.get('target.router').refresh(); - }); - }); + documents.forEach(function (document) { + self.get('documentService').deleteDocument(document).then(function () { + self.get('target.router').refresh(); + }); + }); - this.set('selectedDocuments', []); - this.set('hasSelectedDocuments', false); - this.send("showNotification", "Deleted"); - }, + this.set('selectedDocuments', []); + this.set('hasSelectedDocuments', false); + this.send("showNotification", "Deleted"); + }, showDocument(folder, document) { this.transitionToRoute('document', folder.get('id'), folder.get('slug'), document.get('id'), document.get('slug')); }, - onFolderAdd(folder) { - let self = this; - this.showNotification("Added"); + onFolderAdd(folder) { + let self = this; + this.showNotification("Added"); - this.get('folderService').add({ name: folder }).then(function(newFolder) { + this.get('folderService').add({ name: folder }).then(function (newFolder) { self.get('folderService').setCurrentFolder(newFolder); self.transitionToRoute('folders.folder', newFolder.get('id'), newFolder.get('slug')); }); } } -}); +}); \ No newline at end of file diff --git a/app/app/pods/folders/settings/route.js b/app/app/pods/folders/settings/route.js index 56a14d6e..013af42f 100644 --- a/app/app/pods/folders/settings/route.js +++ b/app/app/pods/folders/settings/route.js @@ -3,18 +3,18 @@ import models from '../../../utils/model'; import NotifierMixin from '../../../mixins/notifier'; import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; -export default Ember.Route.extend(NotifierMixin, AuthenticatedRouteMixin, { +export default Ember.Route.extend(NotifierMixin, { folderService: Ember.inject.service('folder'), userService: Ember.inject.service('user'), folder: {}, - tab: "", + tab: "", - beforeModel: function(transition) { + beforeModel: function (transition) { this.tab = is.not.undefined(transition.queryParams.tab) ? transition.queryParams.tab : "tabGeneral"; }, model(params) { - return this.get('folderService').getFolder(params.folder_id); + return this.get('folderService').getFolder(params.folder_id); }, setupController(controller, model) { @@ -22,17 +22,17 @@ export default Ember.Route.extend(NotifierMixin, AuthenticatedRouteMixin, { this.folder = model; controller.set('model', model); - controller.set('tabGeneral', false); - controller.set('tabShare', false); - controller.set('tabPermissions', false); - controller.set('tabDelete', false); - controller.set(this.get('tab'), true); + controller.set('tabGeneral', false); + controller.set('tabShare', false); + controller.set('tabPermissions', false); + controller.set('tabDelete', false); + controller.set(this.get('tab'), true); - this.get('folderService').getAll().then(function(folders) { + this.get('folderService').getAll().then(function (folders) { controller.set('folders', folders.rejectBy('id', model.get('id'))); }); - this.get('userService').getAll().then(function(users) { + this.get('userService').getAll().then(function (users) { controller.set('users', users); var folderPermissions = []; @@ -48,7 +48,7 @@ export default Ember.Route.extend(NotifierMixin, AuthenticatedRouteMixin, { folderPermissions.pushObject(u); - users.forEach(function(user, index) /* jshint ignore:line */ { + users.forEach(function (user, index) /* jshint ignore:line */ { if (user.get('active')) { var u = models.FolderPermissionModel.create({ userId: user.get('id'), @@ -64,8 +64,8 @@ export default Ember.Route.extend(NotifierMixin, AuthenticatedRouteMixin, { } }); - self.get('folderService').getPermissions(model.id).then(function(permissions) { - permissions.forEach(function(permission, index) /* jshint ignore:line */ { + self.get('folderService').getPermissions(model.id).then(function (permissions) { + permissions.forEach(function (permission, index) /* jshint ignore:line */ { var folderPermission = folderPermissions.findBy('userId', permission.userId); if (is.not.undefined(folderPermission)) { Ember.set(folderPermission, 'orgId', permission.orgId); @@ -82,45 +82,46 @@ export default Ember.Route.extend(NotifierMixin, AuthenticatedRouteMixin, { }, actions: { - onRename: function(folder) { - let self = this; - this.get('folderService').save(folder).then(function() { - self.showNotification("Renamed"); - }); + onRename: function (folder) { + let self = this; + this.get('folderService').save(folder).then(function () { + self.showNotification("Renamed"); + }); }, onRemove(moveId) { let self = this; - this.get('folderService').remove(this.folder.get('id'), moveId).then(function() { /* jshint ignore:line */ + this.get('folderService').remove(this.folder.get('id'), moveId).then(function () { /* jshint ignore:line */ self.showNotification("Deleted"); self.session.clearSessionItem('folder'); - self.get('folderService').getFolder(moveId).then(function(folder) { + self.get('folderService').getFolder(moveId).then(function (folder) { self.get('folderService').setCurrentFolder(folder); self.transitionTo('folders.folder', folder.get('id'), folder.get('slug')); }); }); }, - onShare: function(invitation) { + onShare: function (invitation) { let self = this; - this.get('folderService').share(this.folder.get('id'), invitation).then(function() { - self.showNotification("Shared"); + this.get('folderService').share(this.folder.get('id'), invitation).then(function () { + self.showNotification("Shared"); }); }, - onPermission: function(folder, message, permissions) { + onPermission: function (folder, message, permissions) { var self = this; - var data = permissions.map(function(obj){ return obj.getProperties('orgId', 'folderId' , 'userId', 'canEdit', 'canView'); }); + var data = permissions.map(function (obj) { + return obj.getProperties('orgId', 'folderId', 'userId', 'canEdit', 'canView'); }); var payload = { Message: message, Roles: data }; - this.get('folderService').savePermissions(folder.get('id'), payload).then(function() { - self.showNotification("Saved"); + this.get('folderService').savePermissions(folder.get('id'), payload).then(function () { + self.showNotification("Saved"); }); - var hasEveryone = _.find(data, function(permission) { + var hasEveryone = _.find(data, function (permission) { return permission.userId === "" && (permission.canView || permission.canEdit); }); @@ -134,7 +135,7 @@ export default Ember.Route.extend(NotifierMixin, AuthenticatedRouteMixin, { } } - this.get('folderService').save(folder).then(function() { + this.get('folderService').save(folder).then(function () { // window.location.href = "/folder/" + folder.get('id') + "/" + folder.get('slug'); }); } diff --git a/app/app/router.js b/app/app/router.js index 88bf5a71..d2e6049d 100644 --- a/app/app/router.js +++ b/app/app/router.js @@ -16,10 +16,10 @@ var Router = Ember.Router.extend({ location: config.locationType }); -export default Router.map(function() { +export default Router.map(function () { this.route('folders', { path: '/' - }, function() { + }, function () { this.route('folder', { path: 's/:folder_id/:folder_slug' }); @@ -30,7 +30,7 @@ export default Router.map(function() { this.route('document', { path: 's/:folder_id/:folder_slug/d/:document_id/:document_slug' - }, function() { + }, function () { this.route('edit', { path: 'edit/:page_id' }); @@ -41,7 +41,7 @@ export default Router.map(function() { this.route('customize', { path: 'settings' - }, function() { + }, function () { this.route('general', { path: 'general' }); @@ -59,7 +59,7 @@ export default Router.map(function() { this.route('auth', { path: 'auth' - }, function() { + }, function () { this.route('sso', { path: 'sso/:token' }); @@ -98,5 +98,5 @@ export default Router.map(function() { path: '/*wildcard' }); - this.route('pods', function() {}); + this.route('pods', function () {}); }); diff --git a/app/app/routes/application.js b/app/app/routes/application.js index a59fd75c..03c03270 100644 --- a/app/app/routes/application.js +++ b/app/app/routes/application.js @@ -9,50 +9,50 @@ // // https://documize.com - import Ember from 'ember'; import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin'; +import netUtil from '../utils/net'; const { - inject: { service } + inject: { service } } = Ember; export default Ember.Route.extend(ApplicationRouteMixin, { - appMeta: service(), - session: service(), - beforeModel() { - return this.get('appMeta').boot().then( data => { - if ( data.allowAnonymousAccess ) { - return this.get('session').authenticate('authenticator:anonymous', data); - } - return; - }); - }, - - actions: { - willTransition: function( /*transition*/ ) { - $("#zone-sidebar").css('height', 'auto'); - Mousetrap.reset(); + appMeta: service(), + session: service(), + beforeModel() { + return this.get('appMeta').boot().then(data => { + if (data.allowAnonymousAccess) { + return this.get('session').authenticate('authenticator:anonymous', data); + } + return; + }); }, - didTransition() { - Ember.run.schedule("afterRender",this,function() { - $("#zone-sidebar").css('height', $(document).height() - $("#zone-navigation").height() - $("#zone-header").height() - 35); - }); + actions: { + willTransition: function ( /*transition*/ ) { + $("#zone-sidebar").css('height', 'auto'); + Mousetrap.reset(); + }, - return true; - }, + didTransition() { + Ember.run.schedule("afterRender", this, function () { + $("#zone-sidebar").css('height', $(document).height() - $("#zone-navigation").height() - $("#zone-header").height() - 35); + }); - error(error, transition) { // jshint ignore: line - if (error) { - if (netUtil.isAjaxAccessError(error)) { - localStorage.clear(); - return this.transitionTo('auth.login'); + return true; + }, + + error(error, transition) { // jshint ignore: line + if (error) { + if (netUtil.isAjaxAccessError(error)) { + localStorage.clear(); + return this.transitionTo('auth.login'); + } + } + + // Return true to bubble this event to any parent route. + return true; } - } - - // Return true to bubble this event to any parent route. - return true; - } - }, -}); + }, +}); \ No newline at end of file diff --git a/app/app/services/session.js b/app/app/services/session.js index 8bf7d180..5c6e2d04 100644 --- a/app/app/services/session.js +++ b/app/app/services/session.js @@ -32,7 +32,7 @@ export default SimpleAuthSession.extend({ init: function() { this.set('isMac', is.mac()); this.set('isMobile', is.mobile()); - }, + }, user: computed('isAuthenticated', 'session.content.authenticated.user', function(){ if (this.get('isAuthenticated')) { From 7955da433c85948561487d10225ee1b5eff9ccdd Mon Sep 17 00:00:00 2001 From: zinyando Date: Wed, 6 Jul 2016 00:36:29 +0200 Subject: [PATCH 27/32] WIP fix sso test --- app/app/authenticators/documize.js | 72 +- app/app/pods/auth/sso/route.js | 21 +- app/mirage/config.js | 808 +++++++++--------- .../acceptance/anon-access-enabled-test.js | 41 +- app/tests/acceptance/authentication-test.js | 59 +- app/tests/acceptance/documents-space-test.js | 264 +++--- 6 files changed, 654 insertions(+), 611 deletions(-) diff --git a/app/app/authenticators/documize.js b/app/app/authenticators/documize.js index e68591eb..fbcc8e3f 100644 --- a/app/app/authenticators/documize.js +++ b/app/app/authenticators/documize.js @@ -5,55 +5,55 @@ import netUtil from '../utils/net'; import models from '../utils/model'; const { - isPresent, - RSVP: { resolve, reject }, - inject: { service } + isPresent, + RSVP: { resolve, reject }, + inject: { service } } = Ember; export default Base.extend({ - ajax: service(), - appMeta: service(), + ajax: service(), + appMeta: service(), - restore(data) { - // TODO: verify authentication data - if (data) { - return resolve(data); - } - return reject(); - }, + restore(data) { + // TODO: verify authentication data + if (data) { + return resolve(data); + } + return reject(); + }, - authenticate(credentials) { - let domain = netUtil.getSubdomain(); + authenticate(credentials) { + let domain = netUtil.getSubdomain(); - let encoded; + let encoded; - if (typeof credentials === 'object') { + if (typeof credentials === 'object') { - let { password, email } = credentials; + let { password, email } = credentials; - if (!isPresent(password) || !isPresent(email)) { - return Ember.RSVP.reject("invalid"); - } + if (!isPresent(password) || !isPresent(email)) { + return Ember.RSVP.reject("invalid"); + } - encoded = encodingUtil.Base64.encode(`${domain}:${email}:${password}`); - } else if (typeof credentials === 'string') { - encoded = credentials; - } else { - return Ember.RSVP.reject("invalid"); + encoded = encodingUtil.Base64.encode(`${domain}:${email}:${password}`); + } else if (typeof credentials === 'string') { + encoded = credentials; + } else { + return Ember.RSVP.reject("invalid"); - } + } - var headers = { - 'Authorization': 'Basic ' + encoded - }; + var headers = { + 'Authorization': 'Basic ' + encoded + }; - return this.get('ajax').post('public/authenticate', { - headers - }); - }, + return this.get('ajax').post('public/authenticate', { + headers + }); + }, - invalidate() { - return resolve(); - } + invalidate() { + return resolve(); + } }); diff --git a/app/app/pods/auth/sso/route.js b/app/app/pods/auth/sso/route.js index 83372b42..d6347f42 100644 --- a/app/app/pods/auth/sso/route.js +++ b/app/app/pods/auth/sso/route.js @@ -1,15 +1,16 @@ import Ember from 'ember'; export default Ember.Route.extend({ - session: Ember.inject.service(), + session: Ember.inject.service(), - model({ token }) { - this.get("session").authenticate('authenticator:documize', token) - .then(() => { - this.transitionTo('folders.folder'); - }, () => { - this.transitionTo('auth.login'); - console.log(">>>>> Documize SSO failure"); - }); - }, + model({ token }) { + this.get("session").authenticate('authenticator:documize', token) + .then(() => { + this.transitionTo('folders.folder'); + }) + .catch(() => { + this.transitionTo('auth.login'); + console.log(">>>>> Documize SSO failure"); + }); + } }); diff --git a/app/mirage/config.js b/app/mirage/config.js index c56d0f64..e9095281 100644 --- a/app/mirage/config.js +++ b/app/mirage/config.js @@ -1,421 +1,455 @@ -export default function() { +import Mirage from 'ember-cli-mirage'; - this.passthrough('https://widget.intercom.io/widget/%7Bapp_id%7D'); - this.urlPrefix = 'https://localhost:5001'; // make this `http://localhost:8080`, for example, if your API is on a different server - this.namespace = 'api'; // make this `api`, for example, if your API is namespaced - // this.timing = 400; // delay for each request, automatically set to 0 during testing +export default function () { - this.get('/public/meta', function(schema) { - return schema.db.meta[0]; - }); + this.passthrough('https://widget.intercom.io/widget/%7Bapp_id%7D'); + this.urlPrefix = 'https://localhost:5001'; // make this `http://localhost:8080`, for example, if your API is on a different server + this.namespace = 'api'; // make this `api`, for example, if your API is namespaced + // this.timing = 400; // delay for each request, automatically set to 0 during testing - this.get('/public/validate', function(schema, request) { - let serverToken = request.queryParams.token; - let token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkb21haW4iOiIiLCJleHAiOjE0NjQwMjM2NjcsImlzcyI6IkRvY3VtaXplIiwib3JnIjoiVnpNdXlFd18zV3FpYWZjRCIsInN1YiI6IndlYmFwcCIsInVzZXIiOiJWek11eUV3XzNXcWlhZmNFIn0.NXZ6bo8mtvdZF_b9HavbidVUJqhmBA1zr0fSAPvbah0"; + this.get('/public/meta', function (schema) { + return schema.db.meta[0]; + }); - if (token = serverToken) { - return { - "id": "VzMuyEw_3WqiafcE", - "created": "2016-05-11T15:08:24Z", - "revised": "2016-05-11T15:08:24Z", - "firstname": "Lennex", - "lastname": "Zinyando", - "email": "brizdigital@gmail.com", - "initials": "LZ", - "active": true, - "editor": true, - "admin": true, - "accounts": [{ - "id": "VzMuyEw_3WqiafcF", - "created": "2016-05-11T15:08:24Z", - "revised": "2016-05-11T15:08:24Z", - "admin": true, - "editor": true, - "userId": "VzMuyEw_3WqiafcE", - "orgId": "VzMuyEw_3WqiafcD", - "company": "EmberSherpa", - "title": "EmberSherpa", - "message": "This Documize instance contains all our team documentation", - "domain": "" - }] - }; - } - }); + this.get('/public/validate', function (schema, request) { + let serverToken = request.queryParams.token; + let token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkb21haW4iOiIiLCJleHAiOjE0NjQwMjM2NjcsImlzcyI6IkRvY3VtaXplIiwib3JnIjoiVnpNdXlFd18zV3FpYWZjRCIsInN1YiI6IndlYmFwcCIsInVzZXIiOiJWek11eUV3XzNXcWlhZmNFIn0.NXZ6bo8mtvdZF_b9HavbidVUJqhmBA1zr0fSAPvbah0"; - this.get('/users/0/permissions', function() { - return [{ - "folderId": "VzMygEw_3WrtFzto", - "userId": "", - "canView": true, - "canEdit": false - }]; - }); + if (token = serverToken) { + return { + "id": "VzMuyEw_3WqiafcE", + "created": "2016-05-11T15:08:24Z", + "revised": "2016-05-11T15:08:24Z", + "firstname": "Lennex", + "lastname": "Zinyando", + "email": "brizdigital@gmail.com", + "initials": "LZ", + "active": true, + "editor": true, + "admin": true, + "accounts": [{ + "id": "VzMuyEw_3WqiafcF", + "created": "2016-05-11T15:08:24Z", + "revised": "2016-05-11T15:08:24Z", + "admin": true, + "editor": true, + "userId": "VzMuyEw_3WqiafcE", + "orgId": "VzMuyEw_3WqiafcD", + "company": "EmberSherpa", + "title": "EmberSherpa", + "message": "This Documize instance contains all our team documentation", + "domain": "" + }] + }; + } + }); - this.get('/templates', function() { - return []; - }); + this.get('/users/0/permissions', function () { + return [{ + "folderId": "VzMygEw_3WrtFzto", + "userId": "", + "canView": true, + "canEdit": false + }]; + }); - this.get('/documents', function(schema, request) { - let folder_id = request.queryParams.folder; + this.get('/templates', function () { + return []; + }); - if (folder_id = "VzMuyEw_3WqiafcG") { - return [{ - "id": "VzMwX0w_3WrtFztd", - "created": "2016-05-11T13:15:11Z", - "revised": "2016-05-11T13:22:16Z", - "orgId": "VzMuyEw_3WqiafcD", - "folderId": "VzMuyEw_3WqiafcG", - "userId": "VzMuyEw_3WqiafcE", - "job": "", - "location": "template-0", - "name": "Empty Document", - "excerpt": "My test document", - "tags": "", - "template": false - }, { - "id": "VzMvJEw_3WqiafcI", - "created": "2016-05-11T13:09:56Z", - "revised": "2016-05-11T13:09:56Z", - "orgId": "VzMuyEw_3WqiafcD", - "folderId": "VzMuyEw_3WqiafcG", - "userId": "VzMuyEw_3WqiafcE", - "job": "0bf9b076-cb74-4e8e-75be-8ee2d24a8171", - "location": "/var/folders/d6/kr81d2fs5bsbm8rz2p092fy80000gn/T/documize/_uploads/0bf9b076-cb74-4e8e-75be-8ee2d24a8171/README.md", - "name": "README", - "excerpt": "To Document/ Instructions. GO. go- bindata- assetsfs. SSL.", - "tags": "", - "template": false - }]; - } else if (folder_id = "VzMygEw_3WrtFzto") { - return { - "id": "VzMygEw_3WrtFzto", - "created": "2016-05-11T13:24:17Z", - "revised": "2016-05-11T13:25:51Z", - "name": "Test", - "orgId": "VzMuyEw_3WqiafcD", - "userId": "VzMuyEw_3WqiafcE", - "folderType": 1 - }; - } else if (folder_id = 'V0Vy5Uw_3QeDAMW9'){ - return null; - } - }); + this.get('/documents', function (schema, request) { + let folder_id = request.queryParams.folder; - this.get('/folders', function(schema) { - return schema.db.folders; - }); + if (folder_id = "VzMuyEw_3WqiafcG") { + return [{ + "id": "VzMwX0w_3WrtFztd", + "created": "2016-05-11T13:15:11Z", + "revised": "2016-05-11T13:22:16Z", + "orgId": "VzMuyEw_3WqiafcD", + "folderId": "VzMuyEw_3WqiafcG", + "userId": "VzMuyEw_3WqiafcE", + "job": "", + "location": "template-0", + "name": "Empty Document", + "excerpt": "My test document", + "tags": "", + "template": false + }, { + "id": "VzMvJEw_3WqiafcI", + "created": "2016-05-11T13:09:56Z", + "revised": "2016-05-11T13:09:56Z", + "orgId": "VzMuyEw_3WqiafcD", + "folderId": "VzMuyEw_3WqiafcG", + "userId": "VzMuyEw_3WqiafcE", + "job": "0bf9b076-cb74-4e8e-75be-8ee2d24a8171", + "location": "/var/folders/d6/kr81d2fs5bsbm8rz2p092fy80000gn/T/documize/_uploads/0bf9b076-cb74-4e8e-75be-8ee2d24a8171/README.md", + "name": "README", + "excerpt": "To Document/ Instructions. GO. go- bindata- assetsfs. SSL.", + "tags": "", + "template": false + }]; + } else if (folder_id = "VzMygEw_3WrtFzto") { + return { + "id": "VzMygEw_3WrtFzto", + "created": "2016-05-11T13:24:17Z", + "revised": "2016-05-11T13:25:51Z", + "name": "Test", + "orgId": "VzMuyEw_3WqiafcD", + "userId": "VzMuyEw_3WqiafcE", + "folderType": 1 + }; + } else if (folder_id = 'V0Vy5Uw_3QeDAMW9') { + return null; + } + }); - this.post('/folders', function(schema, request) { - var name = JSON.parse(request.requestBody).name; - let newFolder = { - "id":"V0Vy5Uw_3QeDAMW9", - "created":"2016-05-25T09:39:49Z", - "revised":"2016-05-25T09:39:49Z", - "name":name, - "orgId":"VzMuyEw_3WqiafcD", - "userId":"VzMuyEw_3WqiafcE", - "folderType":2 - }; + this.get('/folders', function (schema) { + return schema.db.folders; + }); - let folder = schema.db.folders.insert(newFolder); - return folder; - }); + this.post('/folders', function (schema, request) { + var name = JSON.parse(request.requestBody).name; + let newFolder = { + "id": "V0Vy5Uw_3QeDAMW9", + "created": "2016-05-25T09:39:49Z", + "revised": "2016-05-25T09:39:49Z", + "name": name, + "orgId": "VzMuyEw_3WqiafcD", + "userId": "VzMuyEw_3WqiafcE", + "folderType": 2 + }; - this.post('/public/authenticate', () => { - return { - "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkb21haW4iOiIiLCJleHAiOjE0NjQwMjM2NjcsImlzcyI6IkRvY3VtaXplIiwib3JnIjoiVnpNdXlFd18zV3FpYWZjRCIsInN1YiI6IndlYmFwcCIsInVzZXIiOiJWek11eUV3XzNXcWlhZmNFIn0.NXZ6bo8mtvdZF_b9HavbidVUJqhmBA1zr0fSAPvbah0", - "user": { - "id": "VzMuyEw_3WqiafcE", - "created": "2016-05-11T15:08:24Z", - "revised": "2016-05-11T15:08:24Z", - "firstname": "Lennex", - "lastname": "Zinyando", - "email": "brizdigital@gmail.com", - "initials": "LZ", - "active": true, - "editor": true, - "admin": true, - "accounts": [{ - "id": "VzMuyEw_3WqiafcF", - "created": "2016-05-11T15:08:24Z", - "revised": "2016-05-11T15:08:24Z", - "admin": true, - "editor": true, - "userId": "VzMuyEw_3WqiafcE", - "orgId": "VzMuyEw_3WqiafcD", - "company": "EmberSherpa", - "title": "EmberSherpa", - "message": "This Documize instance contains all our team documentation", - "domain": "" - }] - } - }; - }); + let folder = schema.db.folders.insert(newFolder); + return folder; + }); - this.get('/users/VzMuyEw_3WqiafcE/permissions', (schema) => { - return schema.db.permissions; - }); + this.post('/public/authenticate', (schema, request) => { + debugger; + let authorization = request.requestHeaders.Authorization; + let expectedAuthorization = "Basic OmJyaXpkaWdpdGFsQGdtYWlsLmNvbTp6aW55YW5kbzEyMw=="; - this.get('/folders/VzMuyEw_3WqiafcG/permissions', () => { - return [ - { - "folderId":"VzMuyEw_3WqiafcG", - "userId":"VzMuyEw_3WqiafcE", - "canView":true, - "canEdit":true - } - ]; - }); + if (expectedAuthorization == authorization) { + return { + "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkb21haW4iOiIiLCJleHAiOjE0NjQwMjM2NjcsImlzcyI6IkRvY3VtaXplIiwib3JnIjoiVnpNdXlFd18zV3FpYWZjRCIsInN1YiI6IndlYmFwcCIsInVzZXIiOiJWek11eUV3XzNXcWlhZmNFIn0.NXZ6bo8mtvdZF_b9HavbidVUJqhmBA1zr0fSAPvbah0", + "user": { + "id": "VzMuyEw_3WqiafcE", + "created": "2016-05-11T15:08:24Z", + "revised": "2016-05-11T15:08:24Z", + "firstname": "Lennex", + "lastname": "Zinyando", + "email": "brizdigital@gmail.com", + "initials": "LZ", + "active": true, + "editor": true, + "admin": true, + "accounts": [{ + "id": "VzMuyEw_3WqiafcF", + "created": "2016-05-11T15:08:24Z", + "revised": "2016-05-11T15:08:24Z", + "admin": true, + "editor": true, + "userId": "VzMuyEw_3WqiafcE", + "orgId": "VzMuyEw_3WqiafcD", + "company": "EmberSherpa", + "title": "EmberSherpa", + "message": "This Documize instance contains all our team documentation", + "domain": "" + }] + } + }; + } else if (expectedAuthorization != authorization) { + return new Mirage.Response(400); + } else { + return { + "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkb21haW4iOiIiLCJleHAiOjE0NjQwMjM2NjcsImlzcyI6IkRvY3VtaXplIiwib3JnIjoiVnpNdXlFd18zV3FpYWZjRCIsInN1YiI6IndlYmFwcCIsInVzZXIiOiJWek11eUV3XzNXcWlhZmNFIn0.NXZ6bo8mtvdZF_b9HavbidVUJqhmBA1zr0fSAPvbah0", + "user": { + "id": "VzMuyEw_3WqiafcE", + "created": "2016-05-11T15:08:24Z", + "revised": "2016-05-11T15:08:24Z", + "firstname": "Lennex", + "lastname": "Zinyando", + "email": "brizdigital@gmail.com", + "initials": "LZ", + "active": true, + "editor": true, + "admin": true, + "accounts": [{ + "id": "VzMuyEw_3WqiafcF", + "created": "2016-05-11T15:08:24Z", + "revised": "2016-05-11T15:08:24Z", + "admin": true, + "editor": true, + "userId": "VzMuyEw_3WqiafcE", + "orgId": "VzMuyEw_3WqiafcD", + "company": "EmberSherpa", + "title": "EmberSherpa", + "message": "This Documize instance contains all our team documentation", + "domain": "" + }] + } + }; + } - this.put('/folders/VzMygEw_3WrtFzto/permissions', () => { - return [ - { - "orgId":"VzMuyEw_3WqiafcD", - "folderId":"VzMygEw_3WrtFzto", - "userId":"", - "canEdit":true, - "canView":true - },{ - "orgId":"VzMuyEw_3WqiafcD", - "folderId":"VzMygEw_3WrtFzto", - "userId":"VzMyp0w_3WrtFztq", - "canEdit":false, - "canView":false - },{ - "orgId":"", - "folderId":"VzMygEw_3WrtFzto", - "userId":"VzMuyEw_3WqiafcE", - "canEdit":true, - "canView":true - } - ]; - }); + }); - this.get('/folders/VzMygEw_3WrtFzto/permissions', () => { - return [ - { - "folderId":"VzMygEw_3WrtFzto", - "userId":"VzMuyEw_3WqiafcE", - "canView":true, - "canEdit":true - } - ]; - }); + this.get('/users/VzMuyEw_3WqiafcE/permissions', (schema) => { + return schema.db.permissions; + }); - this.put('/folders/:id', (schema, request) => { - let id = request.params.id; - let attrs = JSON.parse(request.requestBody); - let folder = schema.db.folders.update(id, attrs); - return folder; - }); + this.get('/folders/VzMuyEw_3WqiafcG/permissions', () => { + return [{ + "folderId": "VzMuyEw_3WqiafcG", + "userId": "VzMuyEw_3WqiafcE", + "canView": true, + "canEdit": true + }]; + }); - this.put('/folders/V0Vy5Uw_3QeDAMW9', () => { - return { - "id":"V0Vy5Uw_3QeDAMW9", - "created":"2016-05-25T09:39:49Z", - "revised":"2016-05-25T09:39:49Z", - "name":"Test Folder", - "orgId":"VzMuyEw_3WqiafcD", - "userId":"VzMuyEw_3WqiafcE", - "folderType":2 - }; - }); + this.put('/folders/VzMygEw_3WrtFzto/permissions', () => { + return [{ + "orgId": "VzMuyEw_3WqiafcD", + "folderId": "VzMygEw_3WrtFzto", + "userId": "", + "canEdit": true, + "canView": true + }, { + "orgId": "VzMuyEw_3WqiafcD", + "folderId": "VzMygEw_3WrtFzto", + "userId": "VzMyp0w_3WrtFztq", + "canEdit": false, + "canView": false + }, { + "orgId": "", + "folderId": "VzMygEw_3WrtFzto", + "userId": "VzMuyEw_3WqiafcE", + "canEdit": true, + "canView": true + }]; + }); - this.get('folders/:id', (schema, request) => { - let id = request.params.id; - return schema.db.folders.find(id); - }); + this.get('/folders/VzMygEw_3WrtFzto/permissions', () => { + return [{ + "folderId": "VzMygEw_3WrtFzto", + "userId": "VzMuyEw_3WqiafcE", + "canView": true, + "canEdit": true + }]; + }); - this.get('/organizations/VzMuyEw_3WqiafcD', () => { - return { - "id": "VzMuyEw_3WqiafcD", - "created": "2016-05-11T15:08:24Z", - "revised": "2016-05-23T11:23:20Z", - "title": "EmberSherpa", - "message": "This Documize instance contains all our team documentation", - "url": "", - "domain": "", - "email": "brizdigital@gmail.com", - "allowAnonymousAccess": false - }; - }); + this.put('/folders/:id', (schema, request) => { + let id = request.params.id; + let attrs = JSON.parse(request.requestBody); + let folder = schema.db.folders.update(id, attrs); + return folder; + }); - this.put('/organizations/VzMuyEw_3WqiafcD', (schema, request) => { - let title = JSON.parse(request.requestBody).title; - let message = JSON.parse(request.requestBody).title; - let allowAnonymousAccess = JSON.parse(request.requestBody).allowAnonymousAccess; + this.put('/folders/V0Vy5Uw_3QeDAMW9', () => { + return { + "id": "V0Vy5Uw_3QeDAMW9", + "created": "2016-05-25T09:39:49Z", + "revised": "2016-05-25T09:39:49Z", + "name": "Test Folder", + "orgId": "VzMuyEw_3WqiafcD", + "userId": "VzMuyEw_3WqiafcE", + "folderType": 2 + }; + }); - return { - "id": "VzMuyEw_3WqiafcD", - "created": "2016-05-11T15:08:24Z", - "revised": "2016-05-23T11:23:20Z", - "title": `${title}`, - "message": `${message}`, - "url": "", - "domain": "", - "email": "brizdigital@gmail.com", - "allowAnonymousAccess": `${allowAnonymousAccess}` - }; - }); + this.get('folders/:id', (schema, request) => { + let id = request.params.id; + return schema.db.folders.find(id); + }); - this.get('/users', () => { - return [{ - "id": "VzMyp0w_3WrtFztq", - "created": "2016-05-11T13:24:55Z", - "revised": "2016-05-11T13:33:47Z", - "firstname": "Len", - "lastname": "Random", - "email": "zinyando@gmail.com", - "initials": "LR", - "active": true, - "editor": true, - "admin": false, - "accounts": [{ - "id": "VzMyp0w_3WrtFztr", - "created": "2016-05-11T13:24:55Z", - "revised": "2016-05-11T13:24:55Z", - "admin": false, - "editor": true, - "userId": "VzMyp0w_3WrtFztq", - "orgId": "VzMuyEw_3WqiafcD", - "company": "EmberSherpa", - "title": "EmberSherpa", - "message": "This Documize instance contains all our team documentation", - "domain": "" - }] - }, { - "id": "VzMuyEw_3WqiafcE", - "created": "2016-05-11T15:08:24Z", - "revised": "2016-05-11T15:08:24Z", - "firstname": "Lennex", - "lastname": "Zinyando", - "email": "brizdigital@gmail.com", - "initials": "LZ", - "active": true, - "editor": true, - "admin": true, - "accounts": [{ - "id": "VzMuyEw_3WqiafcF", - "created": "2016-05-11T15:08:24Z", - "revised": "2016-05-11T15:08:24Z", - "admin": true, - "editor": true, - "userId": "VzMuyEw_3WqiafcE", - "orgId": "VzMuyEw_3WqiafcD", - "company": "EmberSherpa", - "title": "EmberSherpa", - "message": "This Documize instance contains all our team documentation", - "domain": "" - }] - }]; - }); + this.get('/organizations/VzMuyEw_3WqiafcD', () => { + return { + "id": "VzMuyEw_3WqiafcD", + "created": "2016-05-11T15:08:24Z", + "revised": "2016-05-23T11:23:20Z", + "title": "EmberSherpa", + "message": "This Documize instance contains all our team documentation", + "url": "", + "domain": "", + "email": "brizdigital@gmail.com", + "allowAnonymousAccess": false + }; + }); - this.post('/users', (schema, request) => { - let firstname = JSON.parse(request.requestBody).firstname; - let lastname = JSON.parse(request.requestBody).lastname; - let email = JSON.parse(request.requestBody).email; + this.put('/organizations/VzMuyEw_3WqiafcD', (schema, request) => { + let title = JSON.parse(request.requestBody).title; + let message = JSON.parse(request.requestBody).title; + let allowAnonymousAccess = JSON.parse(request.requestBody).allowAnonymousAccess; - return { - "id":"V0RmtUw_3QeDAMW7", - "created":"2016-05-24T14:35:33Z", - "revised":"2016-05-24T14:35:33Z", - "firstname":`${firstname}`, - "lastname":`${lastname}`, - "email":`${email}`, - "initials":"TU", - "active":true, - "editor":true, - "admin":false, - "accounts":[{ - "id":"V0RmtUw_3QeDAMW8", - "created":"2016-05-24T14:35:34Z", - "revised":"2016-05-24T14:35:34Z", - "admin":false, - "editor":true, - "userId":"V0RmtUw_3QeDAMW7", - "orgId":"VzMuyEw_3WqiafcD", - "company":"EmberSherpa", - "title":"EmberSherpa", - "message":"This Documize instance contains all our team documentation", - "domain":"" - } - ]}; - }); + return { + "id": "VzMuyEw_3WqiafcD", + "created": "2016-05-11T15:08:24Z", + "revised": "2016-05-23T11:23:20Z", + "title": `${title}`, + "message": `${message}`, + "url": "", + "domain": "", + "email": "brizdigital@gmail.com", + "allowAnonymousAccess": `${allowAnonymousAccess}` + }; + }); - this.get('/users/VzMuyEw_3WqiafcE', () => { + this.get('/users', () => { + return [{ + "id": "VzMyp0w_3WrtFztq", + "created": "2016-05-11T13:24:55Z", + "revised": "2016-05-11T13:33:47Z", + "firstname": "Len", + "lastname": "Random", + "email": "zinyando@gmail.com", + "initials": "LR", + "active": true, + "editor": true, + "admin": false, + "accounts": [{ + "id": "VzMyp0w_3WrtFztr", + "created": "2016-05-11T13:24:55Z", + "revised": "2016-05-11T13:24:55Z", + "admin": false, + "editor": true, + "userId": "VzMyp0w_3WrtFztq", + "orgId": "VzMuyEw_3WqiafcD", + "company": "EmberSherpa", + "title": "EmberSherpa", + "message": "This Documize instance contains all our team documentation", + "domain": "" + }] + }, { + "id": "VzMuyEw_3WqiafcE", + "created": "2016-05-11T15:08:24Z", + "revised": "2016-05-11T15:08:24Z", + "firstname": "Lennex", + "lastname": "Zinyando", + "email": "brizdigital@gmail.com", + "initials": "LZ", + "active": true, + "editor": true, + "admin": true, + "accounts": [{ + "id": "VzMuyEw_3WqiafcF", + "created": "2016-05-11T15:08:24Z", + "revised": "2016-05-11T15:08:24Z", + "admin": true, + "editor": true, + "userId": "VzMuyEw_3WqiafcE", + "orgId": "VzMuyEw_3WqiafcD", + "company": "EmberSherpa", + "title": "EmberSherpa", + "message": "This Documize instance contains all our team documentation", + "domain": "" + }] + }]; + }); - return { - "id":"VzMuyEw_3WqiafcE", - "created":"2016-05-11T15:08:24Z", - "revised":"2016-05-11T15:08:24Z", - "firstname":"Lennex", - "lastname":"Zinyando", - "email":"brizdigital@gmail.com", - "initials":"LZ", - "active":true, - "editor":true, - "admin":true, - "accounts":[{ - "id":"VzMuyEw_3WqiafcF", - "created":"2016-05-11T15:08:24Z", - "revised":"2016-05-11T15:08:24Z", - "admin":true, - "editor":true, - "userId":"VzMuyEw_3WqiafcE", - "orgId":"VzMuyEw_3WqiafcD", - "company":"EmberSherpa", - "title":"EmberSherpa", - "message":"This Documize instance contains all our team documentation", - "domain":"" - } - ]}; - }); + this.post('/users', (schema, request) => { + let firstname = JSON.parse(request.requestBody).firstname; + let lastname = JSON.parse(request.requestBody).lastname; + let email = JSON.parse(request.requestBody).email; - this.put('/users/VzMuyEw_3WqiafcE', (schema, request) => { - let firstname = JSON.parse(request.requestBody).firstname; - let lastname = JSON.parse(request.requestBody).lastname; - let email = JSON.parse(request.requestBody).email; + return { + "id": "V0RmtUw_3QeDAMW7", + "created": "2016-05-24T14:35:33Z", + "revised": "2016-05-24T14:35:33Z", + "firstname": `${firstname}`, + "lastname": `${lastname}`, + "email": `${email}`, + "initials": "TU", + "active": true, + "editor": true, + "admin": false, + "accounts": [{ + "id": "V0RmtUw_3QeDAMW8", + "created": "2016-05-24T14:35:34Z", + "revised": "2016-05-24T14:35:34Z", + "admin": false, + "editor": true, + "userId": "V0RmtUw_3QeDAMW7", + "orgId": "VzMuyEw_3WqiafcD", + "company": "EmberSherpa", + "title": "EmberSherpa", + "message": "This Documize instance contains all our team documentation", + "domain": "" + }] + }; + }); - return { - "id":"VzMuyEw_3WqiafcE", - "created":"2016-05-11T15:08:24Z", - "revised":"2016-05-11T15:08:24Z", - "firstname":`${firstname}`, - "lastname":`${lastname}`, - "email":`${email}`, - "initials":"LZ", - "active":true, - "editor":true, - "admin":true, - "accounts":[{ - "id":"VzMuyEw_3WqiafcF", - "created":"2016-05-11T15:08:24Z", - "revised":"2016-05-11T15:08:24Z", - "admin":true, - "editor":true, - "userId":"VzMuyEw_3WqiafcE", - "orgId":"VzMuyEw_3WqiafcD", - "company":"EmberSherpa", - "title":"EmberSherpa", - "message":"This Documize instance contains all our team documentation", - "domain":"" - } - ]}; - }); + this.get('/users/VzMuyEw_3WqiafcE', () => { - this.post('/folders/VzMuyEw_3WqiafcG/invitation', () => { - return {}; - }); + return { + "id": "VzMuyEw_3WqiafcE", + "created": "2016-05-11T15:08:24Z", + "revised": "2016-05-11T15:08:24Z", + "firstname": "Lennex", + "lastname": "Zinyando", + "email": "brizdigital@gmail.com", + "initials": "LZ", + "active": true, + "editor": true, + "admin": true, + "accounts": [{ + "id": "VzMuyEw_3WqiafcF", + "created": "2016-05-11T15:08:24Z", + "revised": "2016-05-11T15:08:24Z", + "admin": true, + "editor": true, + "userId": "VzMuyEw_3WqiafcE", + "orgId": "VzMuyEw_3WqiafcD", + "company": "EmberSherpa", + "title": "EmberSherpa", + "message": "This Documize instance contains all our team documentation", + "domain": "" + }] + }; + }); - /** - very helpful for debugging - */ - this.handledRequest = function(verb, path) { - console.log(`👊${verb} ${path}`); - }; + this.put('/users/VzMuyEw_3WqiafcE', (schema, request) => { + let firstname = JSON.parse(request.requestBody).firstname; + let lastname = JSON.parse(request.requestBody).lastname; + let email = JSON.parse(request.requestBody).email; - this.unhandledRequest = function(verb, path) { - console.log(`🔥${verb} ${path}`); - }; + return { + "id": "VzMuyEw_3WqiafcE", + "created": "2016-05-11T15:08:24Z", + "revised": "2016-05-11T15:08:24Z", + "firstname": `${firstname}`, + "lastname": `${lastname}`, + "email": `${email}`, + "initials": "LZ", + "active": true, + "editor": true, + "admin": true, + "accounts": [{ + "id": "VzMuyEw_3WqiafcF", + "created": "2016-05-11T15:08:24Z", + "revised": "2016-05-11T15:08:24Z", + "admin": true, + "editor": true, + "userId": "VzMuyEw_3WqiafcE", + "orgId": "VzMuyEw_3WqiafcD", + "company": "EmberSherpa", + "title": "EmberSherpa", + "message": "This Documize instance contains all our team documentation", + "domain": "" + }] + }; + }); + + this.post('/folders/VzMuyEw_3WqiafcG/invitation', () => { + return {}; + }); + + /** + very helpful for debugging + */ + this.handledRequest = function (verb, path) { + console.log(`👊${verb} ${path}`); + }; + + this.unhandledRequest = function (verb, path) { + console.log(`🔥${verb} ${path}`); + }; } diff --git a/app/tests/acceptance/anon-access-enabled-test.js b/app/tests/acceptance/anon-access-enabled-test.js index 55016bcc..7fb214e8 100644 --- a/app/tests/acceptance/anon-access-enabled-test.js +++ b/app/tests/acceptance/anon-access-enabled-test.js @@ -4,32 +4,31 @@ import moduleForAcceptance from 'documize/tests/helpers/module-for-acceptance'; moduleForAcceptance('Acceptance | Anon access enabled'); test('visiting / when not authenticated and with { allowAnonymousAccess: true } takes user to folder view', function (assert) { - server.create('meta', { allowAnonymousAccess: true }); - server.createList('folder', 2); - visit('/'); - // return pauseTest(); + server.create('meta', { allowAnonymousAccess: true }); + server.createList('folder', 2); + visit('/'); - andThen(function () { - assert.equal(find('.login').length, 1, 'Login button is displayed'); - assert.equal(find('.documents-list .document').length, 2, '2 document displayed'); - assert.equal(currentURL(), '/s/VzMygEw_3WrtFzto/test', 'Dashboard and public spaces are displayed without being signed in'); - }); + andThen(function () { + assert.equal(find('.login').length, 1, 'Login button is displayed'); + assert.equal(find('.documents-list .document').length, 2, '2 document displayed'); + assert.equal(currentURL(), '/s/VzMygEw_3WrtFzto/test', 'Dashboard and public spaces are displayed without being signed in'); + }); }); test('visiting / when authenticated and with { allowAnonymousAccess: true } takes user to dashboard', function (assert) { - server.create('meta', { allowAnonymousAccess: true }); - server.createList('folder', 2); - visit('/'); + server.create('meta', { allowAnonymousAccess: true }); + server.createList('folder', 2); + visit('/'); - andThen(function () { - assert.equal(find('.login').length, 1, 'Login button is displayed'); - assert.equal(currentURL(), '/s/VzMygEw_3WrtFzto/test', 'Dashboard displayed without being signed in'); - }); + andThen(function () { + assert.equal(find('.login').length, 1, 'Login button is displayed'); + assert.equal(currentURL(), '/s/VzMygEw_3WrtFzto/test', 'Dashboard displayed without being signed in'); + }); - userLogin(); + userLogin(); - andThen(function () { - assert.equal(find('.login').length, 0, 'Login button is not displayed'); - assert.equal(currentURL(), '/s/VzMygEw_3WrtFzto/test', 'Dashboard is displayed after user is signed in'); - }); + andThen(function () { + assert.equal(find('.login').length, 0, 'Login button is not displayed'); + assert.equal(currentURL(), '/s/VzMygEw_3WrtFzto/test', 'Dashboard is displayed after user is signed in'); + }); }); diff --git a/app/tests/acceptance/authentication-test.js b/app/tests/acceptance/authentication-test.js index 1dad3283..3386a36c 100644 --- a/app/tests/acceptance/authentication-test.js +++ b/app/tests/acceptance/authentication-test.js @@ -4,39 +4,50 @@ import moduleForAcceptance from 'documize/tests/helpers/module-for-acceptance'; moduleForAcceptance('Acceptance | Authentication'); test('visiting /auth/login and logging in', function (assert) { - server.create('meta', { allowAnonymousAccess: false }); - server.createList('folder', 2); - visit('/auth/login'); + server.create('meta', { allowAnonymousAccess: false }); + server.createList('folder', 2); + visit('/auth/login'); - fillIn('#authEmail', 'brizdigital@gmail.com'); - fillIn('#authPassword', 'zinyando123'); - click('button'); + fillIn('#authEmail', 'brizdigital@gmail.com'); + fillIn('#authPassword', 'zinyando123'); + click('button'); - andThen(function () { - assert.equal(currentURL(), '/s/VzMygEw_3WrtFzto/test', 'Login successfull'); - }); + andThen(function () { + assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project', 'Login successful'); + }); }); test('logging out a user', function (assert) { - server.create('meta', { allowAnonymousAccess: false }); - server.createList('folder', 2); - userLogin(); + server.create('meta', { allowAnonymousAccess: false }); + server.createList('folder', 2); + userLogin(); - visit('/auth/logout'); + visit('/auth/logout'); - andThen(function () { - assert.equal(currentURL(), '/auth/login', 'Logging out successfull'); - }); + andThen(function () { + assert.equal(currentURL(), '/auth/login', 'Logging out successful'); + }); }); -test('sso login', function (assert) { - server.create('meta', { allowAnonymousAccess: false }); - server.createList('folder', 2); - userLogin(); +test('successful sso login authenticates redirects to dashboard', function (assert) { + server.create('meta', { allowAnonymousAccess: false }); + server.createList('folder', 2); - visit('/auth/sso/OmJyaXpkaWdpdGFsQGdtYWlsLmNvbTp6aW55YW5kbzEyMw=='); + visit('/auth/sso/OmJyaXpkaWdpdGFsQGdtYWlsLmNvbTp6aW55YW5kbzEyMw=='); + // return pauseTest(); - andThen(function () { - assert.equal(currentURL(), '/s/VzMygEw_3WrtFzto/test', 'Login successfull'); - }); + andThen(function () { + assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project', 'SSO login successful'); + }); +}); + +test('sso login with bad token should redirect to login', function (assert) { + server.create('meta', { allowAnonymousAccess: false }); + server.createList('folder', 2); + + visit('/auth/sso/randomToken1234567890'); + + andThen(function () { + assert.equal(currentURL(), '/auth/login', 'SSO login unsuccessful'); + }); }); diff --git a/app/tests/acceptance/documents-space-test.js b/app/tests/acceptance/documents-space-test.js index e7549177..79574a89 100644 --- a/app/tests/acceptance/documents-space-test.js +++ b/app/tests/acceptance/documents-space-test.js @@ -4,194 +4,192 @@ import moduleForAcceptance from 'documize/tests/helpers/module-for-acceptance'; moduleForAcceptance('Acceptance | Documents space'); skip('Adding a new folder space', function (assert) { - server.create('meta', { allowAnonymousAccess: false }); - server.createList('folder', 2); - server.createList('permission', 4); - authenticateUser(); - visit('/s/VzMuyEw_3WqiafcG/my-project'); + server.create('meta', { allowAnonymousAccess: false }); + server.createList('folder', 2); + server.createList('permission', 4); + authenticateUser(); + visit('/s/VzMuyEw_3WqiafcG/my-project'); - andThen(function () { - let personalSpaces = find('.section div:contains(PERSONAL)').length; - assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project'); - assert.equal(personalSpaces, 1, '1 personal space is listed'); - }); + andThen(function () { + let personalSpaces = find('.section div:contains(PERSONAL)').length; + assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project'); + assert.equal(personalSpaces, 1, '1 personal space is listed'); + }); - click('#add-folder-button'); + click('#add-folder-button'); - fillIn('#new-folder-name', 'body', 'Test Folder'); + fillIn('#new-folder-name', 'body', 'Test Folder'); - click('.actions div:contains(Add)', 'body'); + click('.actions div:contains(Add)', 'body'); - andThen(function () { - assert.equal(currentURL(), '/s/V0Vy5Uw_3QeDAMW9/test-folder'); - }); + andThen(function () { + assert.equal(currentURL(), '/s/V0Vy5Uw_3QeDAMW9/test-folder'); + }); }); skip('Adding a document to a space', function (assert) { - server.create('meta', { allowAnonymousAccess: false }); - server.createList('folder', 2); - server.createList('permission', 4); - authenticateUser(); - visit('/s/VzMuyEw_3WqiafcG/my-project'); + server.create('meta', { allowAnonymousAccess: false }); + server.createList('folder', 2); + server.createList('permission', 4); + authenticateUser(); + visit('/s/VzMuyEw_3WqiafcG/my-project'); - andThen(function () { + andThen(function () { - let numberOfDocuments = find('.documents-list li').length; - assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project'); - assert.equal(numberOfDocuments, 2, '2 documents listed'); - }); + let numberOfDocuments = find('.documents-list li').length; + assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project'); + assert.equal(numberOfDocuments, 2, '2 documents listed'); + }); - click('#start-document-button'); - click('.actions div:contains(Add)', 'body'); + click('#start-document-button'); + click('.actions div:contains(Add)', 'body'); - andThen(function () { - let numberOfDocuments = find('.documents-list li').length; - assert.equal(numberOfDocuments, 3, '3 documents listed'); - assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project'); - // return pauseTest(); - }); + andThen(function () { + let numberOfDocuments = find('.documents-list li').length; + assert.equal(numberOfDocuments, 3, '3 documents listed'); + assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project'); + }); }); test('visiting space settings page', function (assert) { - server.create('meta', { allowAnonymousAccess: false }); - server.createList('folder', 2); - server.createList('permission', 4); - authenticateUser(); - visit('/s/VzMuyEw_3WqiafcG/my-project'); + server.create('meta', { allowAnonymousAccess: false }); + server.createList('folder', 2); + server.createList('permission', 4); + authenticateUser(); + visit('/s/VzMuyEw_3WqiafcG/my-project'); - click('#folder-settings-button'); + click('#folder-settings-button'); - andThen(function () { - checkForCommonAsserts(); - assert.equal(find('#folderName').val().trim(), 'My Project', 'Space name displayed in input box'); - assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project/settings'); - }); + andThen(function () { + checkForCommonAsserts(); + assert.equal(find('#folderName').val().trim(), 'My Project', 'Space name displayed in input box'); + assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project/settings'); + }); }); test('changing space name', function (assert) { - server.create('meta', { allowAnonymousAccess: false }); - server.createList('folder', 2); - server.createList('permission', 4); - authenticateUser(); - visit('/s/VzMuyEw_3WqiafcG/my-project'); + server.create('meta', { allowAnonymousAccess: false }); + server.createList('folder', 2); + server.createList('permission', 4); + authenticateUser(); + visit('/s/VzMuyEw_3WqiafcG/my-project'); - click('#folder-settings-button'); + click('#folder-settings-button'); - fillIn('#folderName', 'Test Space'); - click('.button-blue'); + fillIn('#folderName', 'Test Space'); + click('.button-blue'); - andThen(function () { - let spaceName = find('.info .title').text().trim(); - checkForCommonAsserts(); - assert.equal(spaceName, 'Test Space', 'Space name has been changed'); - assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project/settings'); - }); + andThen(function () { + let spaceName = find('.info .title').text().trim(); + checkForCommonAsserts(); + assert.equal(spaceName, 'Test Space', 'Space name has been changed'); + assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project/settings'); + }); }); test('sharing a space', function (assert) { - server.create('meta', { allowAnonymousAccess: false }); - server.createList('folder', 2); - server.createList('permission', 4); - authenticateUser(); - visit('/s/VzMuyEw_3WqiafcG/my-project'); + server.create('meta', { allowAnonymousAccess: false }); + server.createList('folder', 2); + server.createList('permission', 4); + authenticateUser(); + visit('/s/VzMuyEw_3WqiafcG/my-project'); - click('#folder-settings-button'); + click('#folder-settings-button'); - click(('.sidebar-menu .options li:contains(Share)')); - fillIn('#inviteEmail', 'share-test@gmail.com'); - click('.button-blue'); + click(('.sidebar-menu .options li:contains(Share)')); + fillIn('#inviteEmail', 'share-test@gmail.com'); + click('.button-blue'); - andThen(function () { - checkForCommonAsserts(); - assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project/settings'); - }); + andThen(function () { + checkForCommonAsserts(); + assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project/settings'); + }); }); // Test will pass after moving to factories test('changing space permissions', function (assert) { - server.create('meta', { allowAnonymousAccess: false }); - server.createList('folder', 2); - server.createList('permission', 4); - authenticateUser(); + server.create('meta', { allowAnonymousAccess: false }); + server.createList('folder', 2); + server.createList('permission', 4); + authenticateUser(); - visit('/s/VzMygEw_3WrtFzto/test'); - andThen(function () { - let numberOfPublicFolders = find('.sidebar-menu .folders-list .section .list:first a').length; - assert.equal(numberOfPublicFolders, 1, '1 folder listed as public'); - assert.equal(currentURL(), '/s/VzMygEw_3WrtFzto/test'); - }); + visit('/s/VzMygEw_3WrtFzto/test'); + andThen(function () { + let numberOfPublicFolders = find('.sidebar-menu .folders-list .section .list:first a').length; + assert.equal(numberOfPublicFolders, 1, '1 folder listed as public'); + assert.equal(currentURL(), '/s/VzMygEw_3WrtFzto/test'); + }); - click('#folder-settings-button'); + click('#folder-settings-button'); - click('.sidebar-menu .options li:contains(Permissions)'); + click('.sidebar-menu .options li:contains(Permissions)'); - click('tr:contains(Everyone) #canView-'); - click('tr:contains(Everyone) #canEdit-'); - click('.button-blue'); + click('tr:contains(Everyone) #canView-'); + click('tr:contains(Everyone) #canEdit-'); + click('.button-blue'); - visit('/s/VzMygEw_3WrtFzto/test'); - // return pauseTest(); + visit('/s/VzMygEw_3WrtFzto/test'); - andThen(function () { - let numberOfPublicFolders = find('.folders-list div:contains(EVERYONE) .list a').length; - assert.equal(numberOfPublicFolders, 2, '2 folder listed as public'); - assert.equal(currentURL(), '/s/VzMygEw_3WrtFzto/test'); - }); + andThen(function () { + let numberOfPublicFolders = find('.folders-list div:contains(EVERYONE) .list a').length; + assert.equal(numberOfPublicFolders, 2, '2 folder listed as public'); + assert.equal(currentURL(), '/s/VzMygEw_3WrtFzto/test'); + }); }); test('deleting a space', function (assert) { - server.create('meta', { allowAnonymousAccess: false }); - server.createList('folder', 2); - server.createList('permission', 4); - authenticateUser(); - visit('/s/VzMuyEw_3WqiafcG/my-project'); + server.create('meta', { allowAnonymousAccess: false }); + server.createList('folder', 2); + server.createList('permission', 4); + authenticateUser(); + visit('/s/VzMuyEw_3WqiafcG/my-project'); - click('#folder-settings-button'); + click('#folder-settings-button'); - click('.sidebar-menu .options li:contains(Delete)'); + click('.sidebar-menu .options li:contains(Delete)'); - andThen(function () { - checkForCommonAsserts(); - assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project/settings'); - }); + andThen(function () { + checkForCommonAsserts(); + assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project/settings'); + }); }); skip('deleting a document', function (assert) { - server.create('meta', { allowAnonymousAccess: false }); - server.createList('folder', 2); - server.createList('permission', 4); - authenticateUser(); - visit('/s/VzMuyEw_3WqiafcG/my-project'); + server.create('meta', { allowAnonymousAccess: false }); + server.createList('folder', 2); + server.createList('permission', 4); + authenticateUser(); + visit('/s/VzMuyEw_3WqiafcG/my-project'); - andThen(function () { - let deleteButton = find('#delete-documents-button'); - let numberOfDocuments = find('.documents-list li'); - assert.equal(numberOfDocuments.length, 2, '2 documents are displayed'); - assert.equal(deleteButton.length, 0, 'Delete button not displayed'); - }); + andThen(function () { + let deleteButton = find('#delete-documents-button'); + let numberOfDocuments = find('.documents-list li'); + assert.equal(numberOfDocuments.length, 2, '2 documents are displayed'); + assert.equal(deleteButton.length, 0, 'Delete button not displayed'); + }); - click('.documents-list li:first .checkbox'); + click('.documents-list li:first .checkbox'); - andThen(function () { - let deleteButton = find('#delete-documents-button'); - assert.equal(deleteButton.length, 1, 'Delete button displayed after selecting document'); - }); + andThen(function () { + let deleteButton = find('#delete-documents-button'); + assert.equal(deleteButton.length, 1, 'Delete button displayed after selecting document'); + }); - click('#delete-documents-button'); + click('#delete-documents-button'); - waitToAppear('.drop-content'); - click('.actions div:contains(Delete)', 'body'); + waitToAppear('.drop-content'); + click('.actions div:contains(Delete)', 'body'); - andThen(function () { - let numberOfDocuments = find('.documents-list li'); - assert.equal(numberOfDocuments.length, 1, '1 documents is displayed'); - }); + andThen(function () { + let numberOfDocuments = find('.documents-list li'); + assert.equal(numberOfDocuments.length, 1, '1 documents is displayed'); + }); }); function checkForCommonAsserts() { - findWithAssert('.sidebar-menu'); - findWithAssert('.options li:contains(General)'); - findWithAssert('.options li:contains(Share)'); - findWithAssert('.options li:contains(Permissions)'); - findWithAssert('.options li:contains(Delete)'); + findWithAssert('.sidebar-menu'); + findWithAssert('.options li:contains(General)'); + findWithAssert('.options li:contains(Share)'); + findWithAssert('.options li:contains(Permissions)'); + findWithAssert('.options li:contains(Delete)'); } From ad119eeb4812227e71f03a774105dcc1356fa2cb Mon Sep 17 00:00:00 2001 From: zinyando Date: Wed, 6 Jul 2016 13:01:07 +0200 Subject: [PATCH 28/32] Fix broken tests --- app/mirage/config.js | 1 - app/tests/acceptance/anon-access-enabled-test.js | 6 +++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/app/mirage/config.js b/app/mirage/config.js index e9095281..3b9ae31d 100644 --- a/app/mirage/config.js +++ b/app/mirage/config.js @@ -124,7 +124,6 @@ export default function () { }); this.post('/public/authenticate', (schema, request) => { - debugger; let authorization = request.requestHeaders.Authorization; let expectedAuthorization = "Basic OmJyaXpkaWdpdGFsQGdtYWlsLmNvbTp6aW55YW5kbzEyMw=="; diff --git a/app/tests/acceptance/anon-access-enabled-test.js b/app/tests/acceptance/anon-access-enabled-test.js index 7fb214e8..16de2e54 100644 --- a/app/tests/acceptance/anon-access-enabled-test.js +++ b/app/tests/acceptance/anon-access-enabled-test.js @@ -11,7 +11,7 @@ test('visiting / when not authenticated and with { allowAnonymousAccess: true } andThen(function () { assert.equal(find('.login').length, 1, 'Login button is displayed'); assert.equal(find('.documents-list .document').length, 2, '2 document displayed'); - assert.equal(currentURL(), '/s/VzMygEw_3WrtFzto/test', 'Dashboard and public spaces are displayed without being signed in'); + assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project', 'Dashboard and public spaces are displayed without being signed in'); }); }); @@ -22,13 +22,13 @@ test('visiting / when authenticated and with { allowAnonymousAccess: true } take andThen(function () { assert.equal(find('.login').length, 1, 'Login button is displayed'); - assert.equal(currentURL(), '/s/VzMygEw_3WrtFzto/test', 'Dashboard displayed without being signed in'); + assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project', 'Dashboard displayed without being signed in'); }); userLogin(); andThen(function () { assert.equal(find('.login').length, 0, 'Login button is not displayed'); - assert.equal(currentURL(), '/s/VzMygEw_3WrtFzto/test', 'Dashboard is displayed after user is signed in'); + assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project', 'Dashboard is displayed after user is signed in'); }); }); From a7894d6800734b9ccddf9ea55aaa423e2fc93daf Mon Sep 17 00:00:00 2001 From: zinyando Date: Thu, 7 Jul 2016 14:09:35 +0200 Subject: [PATCH 29/32] Enable log transitions in tests --- app/config/environment.js | 148 +++++++++++++++++++------------------- 1 file changed, 74 insertions(+), 74 deletions(-) diff --git a/app/config/environment.js b/app/config/environment.js index 67d740bc..41c7db3d 100644 --- a/app/config/environment.js +++ b/app/config/environment.js @@ -11,90 +11,90 @@ /* jshint node: true */ -module.exports = function(environment) { +module.exports = function (environment) { - var ENV = { - modulePrefix: 'documize', - podModulePrefix: 'documize/pods', - locationType: 'auto', - environment: environment, - baseURL: '/', - apiHost: '', - apiNamespace: '', - contentSecurityPolicyHeader: 'Content-Security-Policy-Report-Only', + var ENV = { + modulePrefix: 'documize', + podModulePrefix: 'documize/pods', + locationType: 'auto', + environment: environment, + baseURL: '/', + apiHost: '', + apiNamespace: '', + contentSecurityPolicyHeader: 'Content-Security-Policy-Report-Only', - EmberENV: { - FEATURES: {} - }, - "ember-cli-mirage": { - enabled: false - }, - 'ember-simple-auth': { - authenticationRoute: 'auth.login', - routeAfterAuthentication: 'folders.folder', - routeIfAlreadyAuthenticated: 'folders.folder' - }, - APP: { - // Allows to disable audit service in tests - auditEnabled: true, - intercomKey: "" - } - }; + EmberENV: { + FEATURES: {} + }, + "ember-cli-mirage": { + enabled: false + }, + 'ember-simple-auth': { + authenticationRoute: 'auth.login', + routeAfterAuthentication: 'folders.folder', + routeIfAlreadyAuthenticated: 'folders.folder' + }, + APP: { + // Allows to disable audit service in tests + auditEnabled: true, + intercomKey: "" + } + }; - if (environment === 'development') { - ENV.APP.LOG_TRANSITIONS = true; - ENV.APP.LOG_TRANSITIONS_INTERNAL = true; - ENV['ember-cli-mirage'] = { - enabled: false - }; + if (environment === 'development') { + ENV.APP.LOG_TRANSITIONS = true; + ENV.APP.LOG_TRANSITIONS_INTERNAL = true; + ENV['ember-cli-mirage'] = { + enabled: false + }; - ENV.apiHost = "https://localhost:5001"; - ENV.apiNamespace = "api"; - } + ENV.apiHost = "https://localhost:5001"; + ENV.apiNamespace = "api"; + } - if (environment === 'test') { - ENV.APP.LOG_RESOLVER = false; - ENV.APP.LOG_ACTIVE_GENERATION = false; - ENV.APP.LOG_VIEW_LOOKUPS = false; - // ENV.APP.LOG_TRANSITIONS = false; - // ENV.APP.LOG_TRANSITIONS_INTERNAL = false; + if (environment === 'test') { + ENV.APP.LOG_RESOLVER = false; + ENV.APP.LOG_ACTIVE_GENERATION = false; + ENV.APP.LOG_VIEW_LOOKUPS = false; + ENV.APP.LOG_TRANSITIONS = true; + // ENV.APP.LOG_TRANSITIONS_INTERNAL = false; - ENV.baseURL = '/'; - ENV.locationType = 'none'; - ENV.APP.rootElement = '#ember-testing'; - ENV['ember-cli-mirage'] = { - enabled: true - }; - ENV.APP.auditEnabled = false; + ENV.baseURL = '/'; + ENV.locationType = 'none'; + ENV.APP.rootElement = '#ember-testing'; + ENV['ember-cli-mirage'] = { + enabled: true + }; + ENV.APP.auditEnabled = false; - ENV.apiHost = "https://localhost:5001"; - } + ENV.apiHost = "https://localhost:5001"; + } - if (environment === 'production') { - ENV.APP.LOG_RESOLVER = false; - ENV.APP.LOG_ACTIVE_GENERATION = false; - ENV.APP.LOG_VIEW_LOOKUPS = false; - ENV.APP.LOG_TRANSITIONS = false; - ENV.APP.LOG_TRANSITIONS_INTERNAL = false; + if (environment === 'production') { + ENV.APP.LOG_RESOLVER = false; + ENV.APP.LOG_ACTIVE_GENERATION = false; + ENV.APP.LOG_VIEW_LOOKUPS = false; + ENV.APP.LOG_TRANSITIONS = false; + ENV.APP.LOG_TRANSITIONS_INTERNAL = false; - ENV.apiHost = ""; - } + ENV.apiHost = ""; + } - process.argv.forEach(function(element) { - if (element !== undefined) { - if (element.startsWith("intercom=")) { - element = element.replace("intercom=", ""); - ENV.APP.intercomKey = element; - } - if (element.startsWith("apiHost=")) { - element = element.replace("apiHost=", ""); - ENV.apiHost = element; - } - } - }); + process.argv.forEach(function (element) { + if (element !== undefined) { + if (element.startsWith("intercom=")) { + element = element.replace("intercom=", ""); + ENV.APP.intercomKey = element; + } + if (element.startsWith("apiHost=")) { + element = element.replace("apiHost=", ""); + ENV.apiHost = element; + } + } + }); - ENV.apiNamespace = "api"; - ENV.contentSecurityPolicy = null; + ENV.apiNamespace = "api"; + ENV.contentSecurityPolicy = null; - return ENV; + return ENV; }; From f41517872b02c9228ae73c2a4318c2575cc82ff1 Mon Sep 17 00:00:00 2001 From: zinyando Date: Thu, 7 Jul 2016 14:11:03 +0200 Subject: [PATCH 30/32] Fix sso authentication error by refactoring folders route --- app/app/pods/auth/sso/route.js | 5 +- app/app/pods/folders/route.js | 109 ++++++++++---------- app/mirage/config.js | 78 +++++++------- app/tests/acceptance/authentication-test.js | 1 - 4 files changed, 95 insertions(+), 98 deletions(-) diff --git a/app/app/pods/auth/sso/route.js b/app/app/pods/auth/sso/route.js index d6347f42..bc4c426e 100644 --- a/app/app/pods/auth/sso/route.js +++ b/app/app/pods/auth/sso/route.js @@ -7,10 +7,9 @@ export default Ember.Route.extend({ this.get("session").authenticate('authenticator:documize', token) .then(() => { this.transitionTo('folders.folder'); - }) - .catch(() => { + }, () => { this.transitionTo('auth.login'); console.log(">>>>> Documize SSO failure"); }); - } + }, }); diff --git a/app/app/pods/folders/route.js b/app/app/pods/folders/route.js index 8ef4415b..03dbfb60 100644 --- a/app/app/pods/folders/route.js +++ b/app/app/pods/folders/route.js @@ -2,62 +2,67 @@ import Ember from 'ember'; import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; export default Ember.Route.extend(AuthenticatedRouteMixin, { - folderService: Ember.inject.service('folder'), - localStorage: Ember.inject.service(), - folder: {}, + folderService: Ember.inject.service('folder'), + localStorage: Ember.inject.service(), + folder: {}, - model: function() { - return this.get('folderService').getAll(); - }, + model: function () { + return this.get('folderService').getAll(); + }, - afterModel: function(model) { - let self = this; + afterModel: function (model) { + // TODO: replace with ES6 features (remove self this) + // TODO: replace is.* with Ember utilities + // TODO: flatten if/else + // TODO: make sure chain is maintained by returning promies - if (is.empty(this.paramsFor('folders.folder'))) { - var lastFolder = this.get('localStorage').getSessionItem("folder"); + if (is.empty(this.paramsFor('folders.folder'))) { + let lastFolder = this.get('localStorage').getSessionItem("folder"); - if (is.not.undefined(lastFolder)) { - this.get('folderService').getFolder(lastFolder).then(function(folder) { - if (is.undefined(folder) || is.null(folder)) { - self.transitionTo('auth.login'); - } - self.folder = folder; - self.transitionTo('folders.folder', folder.get('id'), folder.get('slug')); - }, function() { - if (model.length > 0) { - var folder = model[0]; - self.folder = folder; - self.transitionTo('folders.folder', folder.get('id'), folder.get('slug')); - } else { - self.transitionTo('auth.login'); - } - }); - } else { - if (model.length > 0) { - var folder = model[0]; - self.folder = folder; - self.transitionTo('folders.folder', folder.get('id'), folder.get('slug')); - } else - { - // has no folders, create default folder - this.get('folderService').add({ name: "My Space" }).then(function(folder) { - self.folder = folder; - self.transitionTo('folders.folder', folder.get('id'), folder.get('slug')); - }); - } - } - } else { - var folderId = this.paramsFor('folders.folder').folder_id; - this.get('folderService').getFolder(folderId).then(function(folder) { - self.folder = folder; - }); - } + //If folder lastFolder is defined + if (Ember.isPresent(lastFolder)) { + return this.get('folderService').getFolder(lastFolder).then((folder) => { + //if Response is null or undefined redirect to login else transitionTo dashboard + if (Ember.isNone(folder)) { + this.transitionTo('auth.login'); + } + this.folder = folder; + this.transitionTo('folders.folder', folder.get('id'), folder.get('slug')); + }).catch(() => { + //if there was an error redirect to login + this.transitionTo('auth.login'); + }); + } - this.browser.setMetaDescription(); - }, + // If model has any folders redirect to dashboard + if (model.length > 0) { + let folder = model[0]; + this.folder = folder; + this.transitionTo('folders.folder', folder.get('id'), folder.get('slug')); + } - setupController(controller, model) { - controller.set('model', model); - controller.set('folder', this.folder); - } + // has no folders, create default folder + return this.get('folderService').add({ name: "My Space" }).then((folder) => { + this.folder = folder; + this.transitionTo('folders.folder', folder.get('id'), folder.get('slug')); + }); + } + + //If folder route has params + if (Ember.isPresent(this.paramsFor('folders.folder'))) { + + let folderId = this.paramsFor('folders.folder').folder_id; + + return this.get('folderService').getFolder(folderId).then((folder) => { + this.folder = folder; + }); + } + + this.browser.setMetaDescription(); + }, + + setupController(controller, model) { + controller.set('model', model); + controller.set('folder', this.folder); + } }); diff --git a/app/mirage/config.js b/app/mirage/config.js index 3b9ae31d..8dd23999 100644 --- a/app/mirage/config.js +++ b/app/mirage/config.js @@ -7,6 +7,8 @@ export default function () { this.namespace = 'api'; // make this `api`, for example, if your API is namespaced // this.timing = 400; // delay for each request, automatically set to 0 during testing + this.logging = true; + this.get('/public/meta', function (schema) { return schema.db.meta[0]; }); @@ -128,37 +130,7 @@ export default function () { let expectedAuthorization = "Basic OmJyaXpkaWdpdGFsQGdtYWlsLmNvbTp6aW55YW5kbzEyMw=="; if (expectedAuthorization == authorization) { - return { - "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkb21haW4iOiIiLCJleHAiOjE0NjQwMjM2NjcsImlzcyI6IkRvY3VtaXplIiwib3JnIjoiVnpNdXlFd18zV3FpYWZjRCIsInN1YiI6IndlYmFwcCIsInVzZXIiOiJWek11eUV3XzNXcWlhZmNFIn0.NXZ6bo8mtvdZF_b9HavbidVUJqhmBA1zr0fSAPvbah0", - "user": { - "id": "VzMuyEw_3WqiafcE", - "created": "2016-05-11T15:08:24Z", - "revised": "2016-05-11T15:08:24Z", - "firstname": "Lennex", - "lastname": "Zinyando", - "email": "brizdigital@gmail.com", - "initials": "LZ", - "active": true, - "editor": true, - "admin": true, - "accounts": [{ - "id": "VzMuyEw_3WqiafcF", - "created": "2016-05-11T15:08:24Z", - "revised": "2016-05-11T15:08:24Z", - "admin": true, - "editor": true, - "userId": "VzMuyEw_3WqiafcE", - "orgId": "VzMuyEw_3WqiafcD", - "company": "EmberSherpa", - "title": "EmberSherpa", - "message": "This Documize instance contains all our team documentation", - "domain": "" - }] - } - }; - } else if (expectedAuthorization != authorization) { - return new Mirage.Response(400); - } else { + console.log("SSO login success"); return { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkb21haW4iOiIiLCJleHAiOjE0NjQwMjM2NjcsImlzcyI6IkRvY3VtaXplIiwib3JnIjoiVnpNdXlFd18zV3FpYWZjRCIsInN1YiI6IndlYmFwcCIsInVzZXIiOiJWek11eUV3XzNXcWlhZmNFIn0.NXZ6bo8mtvdZF_b9HavbidVUJqhmBA1zr0fSAPvbah0", "user": { @@ -189,6 +161,39 @@ export default function () { }; } + if (expectedAuthorization != authorization) { + return new Mirage.Response(401, { 'Content-Type': 'application/json' }, { message: 'Bad Request' }); + } + + return { + "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkb21haW4iOiIiLCJleHAiOjE0NjQwMjM2NjcsImlzcyI6IkRvY3VtaXplIiwib3JnIjoiVnpNdXlFd18zV3FpYWZjRCIsInN1YiI6IndlYmFwcCIsInVzZXIiOiJWek11eUV3XzNXcWlhZmNFIn0.NXZ6bo8mtvdZF_b9HavbidVUJqhmBA1zr0fSAPvbah0", + "user": { + "id": "VzMuyEw_3WqiafcE", + "created": "2016-05-11T15:08:24Z", + "revised": "2016-05-11T15:08:24Z", + "firstname": "Lennex", + "lastname": "Zinyando", + "email": "brizdigital@gmail.com", + "initials": "LZ", + "active": true, + "editor": true, + "admin": true, + "accounts": [{ + "id": "VzMuyEw_3WqiafcF", + "created": "2016-05-11T15:08:24Z", + "revised": "2016-05-11T15:08:24Z", + "admin": true, + "editor": true, + "userId": "VzMuyEw_3WqiafcE", + "orgId": "VzMuyEw_3WqiafcD", + "company": "EmberSherpa", + "title": "EmberSherpa", + "message": "This Documize instance contains all our team documentation", + "domain": "" + }] + } + }; + }); this.get('/users/VzMuyEw_3WqiafcE/permissions', (schema) => { @@ -440,15 +445,4 @@ export default function () { return {}; }); - /** - very helpful for debugging - */ - this.handledRequest = function (verb, path) { - console.log(`👊${verb} ${path}`); - }; - - this.unhandledRequest = function (verb, path) { - console.log(`🔥${verb} ${path}`); - }; - } diff --git a/app/tests/acceptance/authentication-test.js b/app/tests/acceptance/authentication-test.js index 3386a36c..aeb25ba0 100644 --- a/app/tests/acceptance/authentication-test.js +++ b/app/tests/acceptance/authentication-test.js @@ -34,7 +34,6 @@ test('successful sso login authenticates redirects to dashboard', function (asse server.createList('folder', 2); visit('/auth/sso/OmJyaXpkaWdpdGFsQGdtYWlsLmNvbTp6aW55YW5kbzEyMw=='); - // return pauseTest(); andThen(function () { assert.equal(currentURL(), '/s/VzMuyEw_3WqiafcG/my-project', 'SSO login successful'); From 8597dc3dca74fb405b3314285a8476b904351f63 Mon Sep 17 00:00:00 2001 From: zinyando Date: Thu, 7 Jul 2016 14:11:35 +0200 Subject: [PATCH 31/32] Fixes and cleanup --- app/app/components/document/document-view.js | 247 +++++++++--------- app/app/routes/application.js | 68 ++--- app/app/services/local-storage.js | 18 +- .../components/document/document-view.hbs | 2 +- .../components/layout/zone-navigation.hbs | 4 +- 5 files changed, 170 insertions(+), 169 deletions(-) diff --git a/app/app/components/document/document-view.js b/app/app/components/document/document-view.js index 084458e5..bd2ca67d 100644 --- a/app/app/components/document/document-view.js +++ b/app/app/components/document/document-view.js @@ -1,11 +1,11 @@ // Copyright 2016 Documize Inc. . All rights reserved. // -// This software (Documize Community Edition) is licensed under +// This software (Documize Community Edition) is licensed under // GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html // // You can operate outside the AGPL restrictions by purchasing // Documize Enterprise Edition and obtaining a commercial license -// by contacting . +// by contacting . // // https://documize.com @@ -14,149 +14,150 @@ import NotifierMixin from '../../mixins/notifier'; import TooltipMixin from '../../mixins/tooltip'; export default Ember.Component.extend(NotifierMixin, TooltipMixin, { - documentService: Ember.inject.service('document'), - sectionService: Ember.inject.service('section'), - /* Parameters */ - document: null, - // pages: [], - attachments: [], - folder: null, - folders: [], - isEditor: false, - /* Internal */ - drop: null, - deleteAttachment: { - id: "", - name: "", - }, - deletePage: { - id: "", - title: "", - children: false - }, + documentService: Ember.inject.service('document'), + sectionService: Ember.inject.service('section'), + appMeta: Ember.inject.service(), + /* Parameters */ + document: null, + // pages: [], + attachments: [], + folder: null, + folders: [], + isEditor: false, + /* Internal */ + drop: null, + deleteAttachment: { + id: "", + name: "", + }, + deletePage: { + id: "", + title: "", + children: false + }, - noSections: Ember.computed('pages', function() { - return this.get('pages.length') === 0; - }), + noSections: Ember.computed('pages', function () { + return this.get('pages.length') === 0; + }), - didInsertElement() { - let self = this; + didInsertElement() { + let self = this; - this.get('sectionService').refresh(this.get('document.id')).then(function(changes) { - changes.forEach(function(newPage) { - let oldPage = self.get('pages').findBy('id', newPage.get('id')); - if (is.not.undefined(oldPage)) { - oldPage.set('body', newPage.body); - oldPage.set('revised', newPage.revised); - self.showNotification(`Refreshed ${oldPage.title}`); - } - }); - }); - }, + this.get('sectionService').refresh(this.get('document.id')).then(function (changes) { + changes.forEach(function (newPage) { + let oldPage = self.get('pages').findBy('id', newPage.get('id')); + if (is.not.undefined(oldPage)) { + oldPage.set('body', newPage.body); + oldPage.set('revised', newPage.revised); + self.showNotification(`Refreshed ${oldPage.title}`); + } + }); + }); + }, - willDestroyElement() { - this.destroyTooltips(); + willDestroyElement() { + this.destroyTooltips(); - let drop = this.get('drop'); + let drop = this.get('drop'); - if (is.not.null(drop)) { - drop.destroy(); - } - }, + if (is.not.null(drop)) { + drop.destroy(); + } + }, - actions: { - confirmDeleteAttachment(id, name) { - this.set('deleteAttachment', { - id: id, - name: name - }); + actions: { + confirmDeleteAttachment(id, name) { + this.set('deleteAttachment', { + id: id, + name: name + }); - $(".delete-attachment-dialog").css("display", "block"); + $(".delete-attachment-dialog").css("display", "block"); - let drop = new Drop({ - target: $(".delete-attachment-" + id)[0], - content: $(".delete-attachment-dialog")[0], - classes: 'drop-theme-basic', - position: "bottom right", - openOn: "always", - tetherOptions: { - offset: "5px 0", - targetOffset: "10px 0" - }, - remove: false - }); + let drop = new Drop({ + target: $(".delete-attachment-" + id)[0], + content: $(".delete-attachment-dialog")[0], + classes: 'drop-theme-basic', + position: "bottom right", + openOn: "always", + tetherOptions: { + offset: "5px 0", + targetOffset: "10px 0" + }, + remove: false + }); - this.set('drop', drop); - }, + this.set('drop', drop); + }, - cancel() { - let drop = this.get('drop'); - drop.close(); + cancel() { + let drop = this.get('drop'); + drop.close(); - this.set('deleteAttachment', { - id: "", - name: "" - }); - }, + this.set('deleteAttachment', { + id: "", + name: "" + }); + }, - deleteAttachment() { - let attachment = this.get('deleteAttachment'); - let drop = this.get('drop'); - drop.close(); + deleteAttachment() { + let attachment = this.get('deleteAttachment'); + let drop = this.get('drop'); + drop.close(); - this.showNotification(`Deleted ${attachment.name}`); - this.attrs.onAttachmentDeleted(this.get('deleteAttachment').id); - this.set('deleteAttachment', { - id: "", - name: "" - }); + this.showNotification(`Deleted ${attachment.name}`); + this.attrs.onAttachmentDeleted(this.get('deleteAttachment').id); + this.set('deleteAttachment', { + id: "", + name: "" + }); - return true; - }, + return true; + }, - onDeletePage(id) { - let page = this.get('pages').findBy("id", id); + onDeletePage(id) { + let page = this.get('pages').findBy("id", id); - if (is.undefined(page)) { - return; - } + if (is.undefined(page)) { + return; + } - this.set('deletePage', { - id: id, - title: page.get('title'), - children: false - }); + this.set('deletePage', { + id: id, + title: page.get('title'), + children: false + }); - $(".delete-page-dialog").css("display", "block"); + $(".delete-page-dialog").css("display", "block"); - let drop = new Drop({ - target: $("#page-toolbar-" + id)[0], - content: $(".delete-page-dialog")[0], - classes: 'drop-theme-basic', - position: "bottom right", - openOn: "always", - tetherOptions: { - offset: "5px 0", - targetOffset: "10px 0" - }, - remove: false - }); + let drop = new Drop({ + target: $("#page-toolbar-" + id)[0], + content: $(".delete-page-dialog")[0], + classes: 'drop-theme-basic', + position: "bottom right", + openOn: "always", + tetherOptions: { + offset: "5px 0", + targetOffset: "10px 0" + }, + remove: false + }); - this.set('drop', drop); - }, + this.set('drop', drop); + }, - deletePage() { - let drop = this.get('drop'); - drop.close(); + deletePage() { + let drop = this.get('drop'); + drop.close(); - this.attrs.onDeletePage(this.deletePage); - }, + this.attrs.onDeletePage(this.deletePage); + }, - // onTagChange event emitted from document/tag-editor component - onTagChange(tags) { - let doc = this.get('document'); - doc.set('tags', tags); - this.get('documentService').save(doc); - } - } + // onTagChange event emitted from document/tag-editor component + onTagChange(tags) { + let doc = this.get('document'); + doc.set('tags', tags); + this.get('documentService').save(doc); + } + } }); diff --git a/app/app/routes/application.js b/app/app/routes/application.js index 03c03270..3d2c8398 100644 --- a/app/app/routes/application.js +++ b/app/app/routes/application.js @@ -14,45 +14,45 @@ import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mi import netUtil from '../utils/net'; const { - inject: { service } + inject: { service } } = Ember; export default Ember.Route.extend(ApplicationRouteMixin, { - appMeta: service(), - session: service(), - beforeModel() { - return this.get('appMeta').boot().then(data => { - if (data.allowAnonymousAccess) { - return this.get('session').authenticate('authenticator:anonymous', data); - } - return; - }); - }, + appMeta: service(), + session: service(), + beforeModel() { + return this.get('appMeta').boot().then(data => { + if (data.allowAnonymousAccess) { + return this.get('session').authenticate('authenticator:anonymous', data); + } + return; + }); + }, - actions: { - willTransition: function ( /*transition*/ ) { - $("#zone-sidebar").css('height', 'auto'); - Mousetrap.reset(); - }, + actions: { + willTransition: function ( /*transition*/ ) { + $("#zone-sidebar").css('height', 'auto'); + Mousetrap.reset(); + }, - didTransition() { - Ember.run.schedule("afterRender", this, function () { - $("#zone-sidebar").css('height', $(document).height() - $("#zone-navigation").height() - $("#zone-header").height() - 35); - }); + didTransition() { + Ember.run.schedule("afterRender", this, function () { + $("#zone-sidebar").css('height', $(document).height() - $("#zone-navigation").height() - $("#zone-header").height() - 35); + }); - return true; - }, + return true; + }, - error(error, transition) { // jshint ignore: line - if (error) { - if (netUtil.isAjaxAccessError(error)) { - localStorage.clear(); - return this.transitionTo('auth.login'); - } - } + error(error, transition) { // jshint ignore: line + if (error) { + if (netUtil.isAjaxAccessError(error)) { + localStorage.clear(); + return this.transitionTo('auth.login'); + } + } - // Return true to bubble this event to any parent route. - return true; - } - }, -}); \ No newline at end of file + // Return true to bubble this event to any parent route. + return true; + } + }, +}); diff --git a/app/app/services/local-storage.js b/app/app/services/local-storage.js index 0939d28e..082b7e5e 100644 --- a/app/app/services/local-storage.js +++ b/app/app/services/local-storage.js @@ -2,15 +2,15 @@ import Ember from 'ember'; export default Ember.Service.extend({ - storeSessionItem: function(key, data) { - localStorage[key] = data; - }, + storeSessionItem: function (key, data) { + localStorage[key] = data; + }, - getSessionItem: function(key) { - return localStorage[key]; - }, + getSessionItem: function (key) { + return localStorage[key]; + }, - clearSessionItem: function(key) { - delete localStorage[key]; - } + clearSessionItem: function (key) { + delete localStorage[key]; + } }); diff --git a/app/app/templates/components/document/document-view.hbs b/app/app/templates/components/document/document-view.hbs index 2378d57e..649d4901 100644 --- a/app/app/templates/components/document/document-view.hbs +++ b/app/app/templates/components/document/document-view.hbs @@ -15,7 +15,7 @@ {{#each attachments key="id" as |a index|}}
  • - + {{ a.filename }} {{#if isEditor}} diff --git a/app/app/templates/components/layout/zone-navigation.hbs b/app/app/templates/components/layout/zone-navigation.hbs index bd36b350..90cb95f2 100644 --- a/app/app/templates/components/layout/zone-navigation.hbs +++ b/app/app/templates/components/layout/zone-navigation.hbs @@ -6,13 +6,13 @@ {{else}} {{#link-to 'application' class='title'}} -
    +
    apps
    {{/link-to}} {{/if}} {{#link-to 'application' class='title'}} - {{session.appMeta.title}} + {{appMeta.title}} {{/link-to}}
    From 9e8577b86c9a3b94fbd964d239efb91b3f9f89b2 Mon Sep 17 00:00:00 2001 From: zinyando Date: Thu, 7 Jul 2016 17:05:40 +0200 Subject: [PATCH 32/32] Fixes to folders route --- app/app/pods/folders/route.js | 25 +++++++++++--------- app/app/services/session.js | 44 +++++++++++++++++------------------ 2 files changed, 36 insertions(+), 33 deletions(-) diff --git a/app/app/pods/folders/route.js b/app/app/pods/folders/route.js index 03dbfb60..8d26ad33 100644 --- a/app/app/pods/folders/route.js +++ b/app/app/pods/folders/route.js @@ -1,6 +1,10 @@ import Ember from 'ember'; import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; +const { + isPresent +} = Ember; + export default Ember.Route.extend(AuthenticatedRouteMixin, { folderService: Ember.inject.service('folder'), localStorage: Ember.inject.service(), @@ -11,22 +15,21 @@ export default Ember.Route.extend(AuthenticatedRouteMixin, { }, afterModel: function (model) { - // TODO: replace with ES6 features (remove self this) - // TODO: replace is.* with Ember utilities - // TODO: flatten if/else - // TODO: make sure chain is maintained by returning promies - if (is.empty(this.paramsFor('folders.folder'))) { + let params = this.paramsFor('folders.folder'); + + if (is.empty(params)) { let lastFolder = this.get('localStorage').getSessionItem("folder"); //If folder lastFolder is defined - if (Ember.isPresent(lastFolder)) { + if (isPresent(lastFolder)) { return this.get('folderService').getFolder(lastFolder).then((folder) => { //if Response is null or undefined redirect to login else transitionTo dashboard if (Ember.isNone(folder)) { this.transitionTo('auth.login'); } - this.folder = folder; + + Ember.set(this, 'folder', folder); this.transitionTo('folders.folder', folder.get('id'), folder.get('slug')); }).catch(() => { //if there was an error redirect to login @@ -37,24 +40,24 @@ export default Ember.Route.extend(AuthenticatedRouteMixin, { // If model has any folders redirect to dashboard if (model.length > 0) { let folder = model[0]; - this.folder = folder; + Ember.set(this, 'folder', folder); this.transitionTo('folders.folder', folder.get('id'), folder.get('slug')); } // has no folders, create default folder return this.get('folderService').add({ name: "My Space" }).then((folder) => { - this.folder = folder; + Ember.set(this, 'folder', folder); this.transitionTo('folders.folder', folder.get('id'), folder.get('slug')); }); } //If folder route has params - if (Ember.isPresent(this.paramsFor('folders.folder'))) { + if (isPresent(params)) { let folderId = this.paramsFor('folders.folder').folder_id; return this.get('folderService').getFolder(folderId).then((folder) => { - this.folder = folder; + Ember.set(this, 'folder', folder); }); } diff --git a/app/app/services/session.js b/app/app/services/session.js index 5c6e2d04..7960cf02 100644 --- a/app/app/services/session.js +++ b/app/app/services/session.js @@ -14,34 +14,34 @@ import models from '../utils/model'; import SimpleAuthSession from 'ember-simple-auth/services/session'; const { - inject: { service }, - computed: { oneWay, or, notEmpty }, - computed + inject: { service }, + computed: { oneWay, or, notEmpty }, + computed } = Ember; export default SimpleAuthSession.extend({ - ajax: service(), - appMeta: service(), + ajax: service(), + appMeta: service(), - isMac: false, - isMobile: false, - authenticated: notEmpty('user.id'), - isAdmin: oneWay('user.admin'), - isEditor: or('user.admin', 'user.editor'), + isMac: false, + isMobile: false, + authenticated: notEmpty('user.id'), + isAdmin: oneWay('user.admin'), + isEditor: or('user.admin', 'user.editor'), - init: function() { - this.set('isMac', is.mac()); - this.set('isMobile', is.mobile()); - }, + init: function () { + this.set('isMac', is.mac()); + this.set('isMobile', is.mobile()); + }, - user: computed('isAuthenticated', 'session.content.authenticated.user', function(){ - if (this.get('isAuthenticated')) { - let user = this.get('session.content.authenticated.user') || { id: '' }; - return models.UserModel.create(user); - } + user: computed('isAuthenticated', 'session.content.authenticated.user', function () { + if (this.get('isAuthenticated')) { + let user = this.get('session.content.authenticated.user') || { id: '' }; + return models.UserModel.create(user); + } - }), + }), - folderPermissions: null, - currentFolder: null + folderPermissions: null, + currentFolder: null });