auth.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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: false, // becomes user obj to which we want to sync or none 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. if (!self.get('needsSync')) {
  12. // display annoying "you were desynced" message
  13. self.set('needsSync', true);
  14. if (isAuthenticated) {
  15. self.set('syncToUser', Ember.Object.create(self.session.getItem('auth-user')));
  16. }
  17. }
  18. });
  19. }.on('init'),
  20. // Anon/auth state
  21. isAnonymous: Ember.computed.not('isAuthenticated'),
  22. logout: function() {
  23. this.session.setItem('auth-user', false);
  24. this.session.setItem('auth-is-authenticated', false);
  25. Ember.$('#hidden-logout-form').submit();
  26. },
  27. // Utils for triggering 403 error
  28. _throw: function(message) {
  29. throw {
  30. status: 403,
  31. responseJSON: {
  32. detail: message
  33. }
  34. };
  35. },
  36. denyAuthenticated: function(message) {
  37. if (this.get('isAuthenticated')) {
  38. this._throw(message || gettext('This page is not available to signed in users.'));
  39. }
  40. },
  41. denyAnonymous: function(message) {
  42. if (this.get('isAnonymous')) {
  43. this._throw(message || gettext('This page is not available to guests.'));
  44. }
  45. }
  46. });