authtoken_view.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. /* global Handlebars, moment */
  2. /**
  3. * @author Christoph Wurst <christoph@owncloud.com>
  4. *
  5. * @copyright Copyright (c) 2016, ownCloud, Inc.
  6. * @license AGPL-3.0
  7. *
  8. * This code is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU Affero General Public License, version 3,
  10. * as published by the Free Software Foundation.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU Affero General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Affero General Public License, version 3,
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>
  19. *
  20. */
  21. (function (OC, _, $, Handlebars, moment) {
  22. 'use strict';
  23. OC.Settings = OC.Settings || {};
  24. var TEMPLATE_TOKEN =
  25. '<tr data-id="{{id}}">'
  26. + '<td class="client">'
  27. + '<div class="{{icon}}" />'
  28. + '</td>'
  29. + '<td class="has-tooltip" title="{{title}}">'
  30. + '<span class="token-name">{{name}}</span>'
  31. + '</td>'
  32. + '<td><span class="last-activity has-tooltip" title="{{lastActivityTime}}">{{lastActivity}}</span></td>'
  33. + '<td class="more">'
  34. + '{{#if showMore}}<a class="icon icon-more"/>{{/if}}'
  35. + '<div class="popovermenu bubble open menu configure">'
  36. + '{{#if canScope}}'
  37. + '<input class="filesystem checkbox" type="checkbox" id="{{id}}_filesystem" {{#if scope.filesystem}}checked{{/if}}/>'
  38. + '<label for="{{id}}_filesystem">' + t('settings', 'Allow filesystem access') + '</label><br/>'
  39. + '{{/if}}'
  40. + '{{#if canDelete}}'
  41. + '<a class="icon icon-delete has-tooltip" title="' + t('settings', 'Disconnect') + '">' + t('settings', 'Revoke') +'</a>'
  42. + '{{/if}}'
  43. + '</div>'
  44. + '</td>'
  45. + '<tr>';
  46. var SubView = OC.Backbone.View.extend({
  47. collection: null,
  48. _template: undefined,
  49. template: function (data) {
  50. if (_.isUndefined(this._template)) {
  51. this._template = Handlebars.compile(TEMPLATE_TOKEN);
  52. }
  53. return this._template(data);
  54. },
  55. initialize: function (options) {
  56. this.collection = options.collection;
  57. this.on(this.collection, 'change', this.render);
  58. },
  59. render: function () {
  60. var _this = this;
  61. var list = this.$('.token-list');
  62. var tokens = this.collection.filter(function (token) {
  63. return true;
  64. });
  65. list.html('');
  66. // Show header only if there are tokens to show
  67. this._toggleHeader(tokens.length > 0);
  68. tokens.forEach(function (token) {
  69. var viewData = this._formatViewData(token);
  70. var html = _this.template(viewData);
  71. var $html = $(html);
  72. $html.find('.has-tooltip').tooltip({container: 'body'});
  73. list.append($html);
  74. }.bind(this));
  75. },
  76. toggleLoading: function (state) {
  77. this.$('table').toggleClass('icon-loading', state);
  78. },
  79. _toggleHeader: function (show) {
  80. this.$('.hidden-when-empty').toggleClass('hidden', !show);
  81. },
  82. _formatViewData: function (token) {
  83. var viewData = token.toJSON();
  84. var ts = viewData.lastActivity * 1000;
  85. viewData.lastActivity = OC.Util.relativeModifiedDate(ts);
  86. viewData.lastActivityTime = OC.Util.formatDate(ts, 'LLL');
  87. viewData.canScope = token.get('type') === 1;
  88. viewData.showMore = viewData.canScope || viewData.canDelete;
  89. // preserve title for cases where we format it further
  90. viewData.title = viewData.name;
  91. // pretty format sync client user agent
  92. var matches = viewData.name.match(/Mozilla\/5\.0 \((\w+)\) (?:mirall|csyncoC)\/(\d+\.\d+\.\d+)/);
  93. var userAgentMap = {
  94. ie: /(?:MSIE|Trident|Trident\/7.0; rv)[ :](\d+)/,
  95. // Microsoft Edge User Agent from https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx
  96. edge: /^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Chrome\/[0-9.]+ (?:Mobile Safari|Safari)\/[0-9.]+ Edge\/[0-9.]+$/,
  97. // Firefox User Agent from https://developer.mozilla.org/en-US/docs/Web/HTTP/Gecko_user_agent_string_reference
  98. firefox: /^Mozilla\/5\.0 \([^)]*(Windows|OS X|Linux)[^)]+\) Gecko\/[0-9.]+ Firefox\/(\d+)(?:\.\d)?$/,
  99. // Chrome User Agent from https://developer.chrome.com/multidevice/user-agent
  100. chrome: /^Mozilla\/5\.0 \([^)]*(Windows|OS X|Linux)[^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Chrome\/(\d+)[0-9.]+ (?:Mobile Safari|Safari)\/[0-9.]+$/,
  101. // Safari User Agent from http://www.useragentstring.com/pages/Safari/
  102. safari: /^Mozilla\/5\.0 \([^)]*(Windows|OS X)[^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\)(?: Version\/([0-9]+)[0-9.]+)? Safari\/[0-9.A-Z]+$/,
  103. // Android Chrome user agent: https://developers.google.com/chrome/mobile/docs/user-agent
  104. androidChrome: /Android.*(?:; (.*) Build\/).*Chrome\/(\d+)[0-9.]+/,
  105. iphone: / *CPU +iPhone +OS +([0-9]+)_(?:[0-9_])+ +like +Mac +OS +X */,
  106. ipad: /\(iPad\; *CPU +OS +([0-9]+)_(?:[0-9_])+ +like +Mac +OS +X */,
  107. iosClient: /^Mozilla\/5\.0 \(iOS\) (ownCloud|Nextcloud)\-iOS.*$/,
  108. androidClient:/^Mozilla\/5\.0 \(Android\) ownCloud\-android.*$/,
  109. // DAVdroid/1.2 (2016/07/03; dav4android; okhttp3) Android/6.0.1
  110. davDroid: /DAVdroid\/([0-9.]+)/,
  111. // Mozilla/5.0 (U; Linux; Maemo; Jolla; Sailfish; like Android 4.3) AppleWebKit/538.1 (KHTML, like Gecko) WebPirate/2.0 like Mobile Safari/538.1 (compatible)
  112. webPirate: /(Sailfish).*WebPirate\/(\d+)/,
  113. // Mozilla/5.0 (Maemo; Linux; U; Jolla; Sailfish; Mobile; rv:31.0) Gecko/31.0 Firefox/31.0 SailfishBrowser/1.0
  114. sailfishBrowser: /(Sailfish).*SailfishBrowser\/(\d+)/
  115. };
  116. var nameMap = {
  117. ie: t('setting', 'Internet Explorer'),
  118. edge: t('setting', 'Edge'),
  119. firefox: t('setting', 'Firefox'),
  120. chrome: t('setting', 'Google Chrome'),
  121. safari: t('setting', 'Safari'),
  122. androidChrome: t('setting', 'Google Chrome for Android'),
  123. iphone: t('setting', 'iPhone iOS'),
  124. ipad: t('setting', 'iPad iOS'),
  125. iosClient: t('setting', 'iOS Client'),
  126. androidClient: t('setting', 'Android Client'),
  127. davDroid: 'DAVdroid',
  128. webPirate: 'WebPirate',
  129. sailfishBrowser: 'SailfishBrowser'
  130. };
  131. var iconMap = {
  132. ie: 'icon-desktop',
  133. edge: 'icon-desktop',
  134. firefox: 'icon-desktop',
  135. chrome: 'icon-desktop',
  136. safari: 'icon-desktop',
  137. androidChrome: 'icon-phone',
  138. iphone: 'icon-phone',
  139. ipad: 'icon-tablet',
  140. iosClient: 'icon-phone',
  141. androidClient: 'icon-phone',
  142. davDroid: 'icon-phone',
  143. webPirate: 'icon-link',
  144. sailfishBrowser: 'icon-link'
  145. };
  146. if (matches) {
  147. viewData.name = t('settings', 'Sync client - {os}', {
  148. os: matches[1],
  149. version: matches[2]
  150. });
  151. viewData.icon = 'icon-desktop';
  152. }
  153. for (var client in userAgentMap) {
  154. if (matches = viewData.title.match(userAgentMap[client])) {
  155. if (matches[2] && matches[1]) { // version number and os
  156. viewData.name = nameMap[client] + ' ' + matches[2] + ' - ' + matches[1];
  157. }else if (matches[1]) { // only version number
  158. viewData.name = nameMap[client] + ' ' + matches[1];
  159. } else {
  160. viewData.name = nameMap[client];
  161. }
  162. // update title - for easier view
  163. viewData.title = viewData.name;
  164. viewData.icon = iconMap[client];
  165. }
  166. }
  167. if (viewData.current) {
  168. viewData.name = t('settings', 'This session');
  169. }
  170. return viewData;
  171. }
  172. });
  173. var AuthTokenView = OC.Backbone.View.extend({
  174. collection: null,
  175. _view: [],
  176. _form: undefined,
  177. _tokenName: undefined,
  178. _addAppPasswordBtn: undefined,
  179. _result: undefined,
  180. _newAppLoginName: undefined,
  181. _newAppPassword: undefined,
  182. _newAppId: undefined,
  183. _hideAppPasswordBtn: undefined,
  184. _addingToken: false,
  185. initialize: function (options) {
  186. this.collection = options.collection;
  187. var el = '#security';
  188. this._view = new SubView({
  189. el: el,
  190. collection: this.collection
  191. });
  192. var $el = $(el);
  193. $('body').on('click', _.bind(this._hideConfigureToken, this));
  194. $el.on('click', '.popovermenu', function(event) {
  195. event.stopPropagation();
  196. });
  197. $el.on('click', 'a.icon-delete', _.bind(this._onDeleteToken, this));
  198. $el.on('click', '.icon-more', _.bind(this._onConfigureToken, this));
  199. $el.on('change', 'input.filesystem', _.bind(this._onSetTokenScope, this));
  200. this._form = $('#app-password-form');
  201. this._tokenName = $('#app-password-name');
  202. this._addAppPasswordBtn = $('#add-app-password');
  203. this._addAppPasswordBtn.click(_.bind(this._addAppPassword, this));
  204. this._appPasswordName = $('#app-password-name');
  205. this._appPasswordName.on('keypress', function(event) {
  206. if (event.which === 13) {
  207. this._addAppPassword();
  208. }
  209. });
  210. this._result = $('#app-password-result');
  211. this._newAppLoginName = $('#new-app-login-name');
  212. this._newAppLoginName.on('focus', _.bind(this._onNewTokenLoginNameFocus, this));
  213. this._newAppPassword = $('#new-app-password');
  214. this._newAppPassword.on('focus', _.bind(this._onNewTokenFocus, this));
  215. this._hideAppPasswordBtn = $('#app-password-hide');
  216. this._hideAppPasswordBtn.click(_.bind(this._hideToken, this));
  217. this._result.find('.clipboardButton').tooltip({placement: 'bottom', title: t('core', 'Copy'), trigger: 'hover'});
  218. // Clipboard!
  219. var clipboard = new Clipboard('.clipboardButton');
  220. clipboard.on('success', function(e) {
  221. var $input = $(e.trigger);
  222. $input.tooltip('hide')
  223. .attr('data-original-title', t('core', 'Copied!'))
  224. .tooltip('fixTitle')
  225. .tooltip({placement: 'bottom', trigger: 'manual'})
  226. .tooltip('show');
  227. _.delay(function() {
  228. $input.tooltip('hide')
  229. .attr('data-original-title', t('core', 'Copy'))
  230. .tooltip('fixTitle');
  231. }, 3000);
  232. });
  233. clipboard.on('error', function (e) {
  234. var $input = $(e.trigger);
  235. var actionMsg = '';
  236. if (/iPhone|iPad/i.test(navigator.userAgent)) {
  237. actionMsg = t('core', 'Not supported!');
  238. } else if (/Mac/i.test(navigator.userAgent)) {
  239. actionMsg = t('core', 'Press ⌘-C to copy.');
  240. } else {
  241. actionMsg = t('core', 'Press Ctrl-C to copy.');
  242. }
  243. $input.tooltip('hide')
  244. .attr('data-original-title', actionMsg)
  245. .tooltip('fixTitle')
  246. .tooltip({placement: 'bottom', trigger: 'manual'})
  247. .tooltip('show');
  248. _.delay(function () {
  249. $input.tooltip('hide')
  250. .attr('data-original-title', t('core', 'Copy'))
  251. .tooltip('fixTitle');
  252. }, 3000);
  253. });
  254. },
  255. render: function () {
  256. this._view.render();
  257. this._view.toggleLoading(false);
  258. },
  259. reload: function () {
  260. var _this = this;
  261. this._view.toggleLoading(true);
  262. var loadingTokens = this.collection.fetch();
  263. $.when(loadingTokens).done(function () {
  264. _this.render();
  265. });
  266. $.when(loadingTokens).fail(function () {
  267. OC.Notification.showTemporary(t('core', 'Error while loading browser sessions and device tokens'));
  268. });
  269. },
  270. _addAppPassword: function () {
  271. if (OC.PasswordConfirmation.requiresPasswordConfirmation()) {
  272. OC.PasswordConfirmation.requirePasswordConfirmation(_.bind(this._addAppPassword, this));
  273. return;
  274. }
  275. var _this = this;
  276. this._toggleAddingToken(true);
  277. var deviceName = this._tokenName.val() !== '' ? this._tokenName.val() : new Date();
  278. var creatingToken = $.ajax(OC.generateUrl('/settings/personal/authtokens'), {
  279. method: 'POST',
  280. data: {
  281. name: deviceName
  282. }
  283. });
  284. $.when(creatingToken).done(function (resp) {
  285. // We can delete token we add
  286. resp.deviceToken.canDelete = true;
  287. _this.collection.add(resp.deviceToken);
  288. _this.render();
  289. _this._newAppLoginName.val(resp.loginName);
  290. _this._newAppPassword.val(resp.token);
  291. _this._newAppId = resp.deviceToken.id;
  292. _this._toggleFormResult(false);
  293. _this._newAppPassword.select();
  294. _this._tokenName.val('');
  295. });
  296. $.when(creatingToken).fail(function () {
  297. OC.Notification.showTemporary(t('core', 'Error while creating device token'));
  298. });
  299. $.when(creatingToken).always(function () {
  300. _this._toggleAddingToken(false);
  301. });
  302. },
  303. _onNewTokenLoginNameFocus: function () {
  304. this._newAppLoginName.select();
  305. },
  306. _onNewTokenFocus: function () {
  307. this._newAppPassword.select();
  308. },
  309. _hideToken: function () {
  310. this._toggleFormResult(true);
  311. },
  312. _toggleAddingToken: function (state) {
  313. this._addingToken = state;
  314. this._addAppPasswordBtn.toggleClass('icon-loading-small', state);
  315. },
  316. _onConfigureToken: function (event) {
  317. event.stopPropagation();
  318. this._hideConfigureToken();
  319. var $target = $(event.target);
  320. var $row = $target.closest('tr');
  321. $row.toggleClass('active');
  322. var id = $row.data('id');
  323. },
  324. _hideConfigureToken: function() {
  325. $('.token-list tr').removeClass('active');
  326. },
  327. _onDeleteToken: function (event) {
  328. var $target = $(event.target);
  329. var $row = $target.closest('tr');
  330. var id = $row.data('id');
  331. if (id === this._newAppId) {
  332. this._toggleFormResult(true);
  333. }
  334. var token = this.collection.get(id);
  335. if (_.isUndefined(token)) {
  336. // Ignore event
  337. return;
  338. }
  339. var destroyingToken = token.destroy();
  340. $row.find('.icon-delete').tooltip('hide');
  341. var _this = this;
  342. $.when(destroyingToken).fail(function () {
  343. OC.Notification.showTemporary(t('core', 'Error while deleting the token'));
  344. });
  345. $.when(destroyingToken).always(function () {
  346. _this.render();
  347. });
  348. },
  349. _onSetTokenScope: function (event) {
  350. var $target = $(event.target);
  351. var $row = $target.closest('tr');
  352. var id = $row.data('id');
  353. var token = this.collection.get(id);
  354. if (_.isUndefined(token)) {
  355. // Ignore event
  356. return;
  357. }
  358. var scope = token.get('scope');
  359. scope.filesystem = $target.is(":checked");
  360. token.set('scope', scope);
  361. token.save();
  362. },
  363. _toggleFormResult: function (showForm) {
  364. if (showForm) {
  365. this._result.slideUp();
  366. this._form.slideDown();
  367. } else {
  368. this._form.slideUp();
  369. this._result.slideDown();
  370. }
  371. }
  372. });
  373. OC.Settings.AuthTokenView = AuthTokenView;
  374. })(OC, _, $, Handlebars, moment);