auth.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import Ember from 'ember';
  2. export default Ember.Service.extend({
  3. // State synchronization across tabs
  4. needsSync: false, // becomes true if auth state between tabs differs
  5. syncToUser: null, // becomes user obj to which we want to sync or null for anon
  6. syncSession: function() {
  7. this.session.setItem('auth-user', this.get('user'));
  8. this.session.setItem('auth-is-authenticated', this.get('isAuthenticated'));
  9. var self = this;
  10. this.session.watchItem('auth-is-authenticated', function(isAuthenticated) {
  11. self._handleAuthChange(isAuthenticated);
  12. });
  13. this.session.watchItem('auth-user', function(newUser) {
  14. self._handleUserChange(newUser);
  15. });
  16. }.on('init'),
  17. _handleAuthChange: function(isAuthenticated) {
  18. if (!this.get('needsSync')) {
  19. // display annoying "you were desynced" message
  20. this.set('needsSync', true);
  21. if (isAuthenticated) {
  22. this.set('syncToUser', Ember.Object.create(this.session.getItem('auth-user')));
  23. }
  24. }
  25. },
  26. _handleUserChange: function(newUser) {
  27. if (!this.get('needsSync')) {
  28. var userObj = Ember.Object.create(newUser);
  29. if (userObj.get('id') !== this.get('user.id')) {
  30. this.setProperties({
  31. 'needsSync': true,
  32. 'syncToUser': userObj,
  33. });
  34. } else {
  35. this.get('user').setProperties(newUser);
  36. }
  37. }
  38. },
  39. // Anon/auth state
  40. isAnonymous: Ember.computed.not('isAuthenticated'),
  41. logout: function() {
  42. this.session.setItem('auth-user', false);
  43. this.session.setItem('auth-is-authenticated', false);
  44. Ember.$('#hidden-logout-form').submit();
  45. },
  46. // Utils for triggering 403 error
  47. _throw: function(message) {
  48. throw {
  49. status: 403,
  50. responseJSON: {
  51. detail: message
  52. }
  53. };
  54. },
  55. denyAuthenticated: function(message) {
  56. if (this.get('isAuthenticated')) {
  57. this._throw(message || gettext('This page is not available to signed in users.'));
  58. }
  59. },
  60. denyAnonymous: function(message) {
  61. if (this.get('isAnonymous')) {
  62. this._throw(message || gettext('This page is not available to guests.'));
  63. }
  64. }
  65. });