auth.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. var userObj = Ember.Object.create(newUser);
  28. if (userObj.get('id') !== this.get('user.id')) {
  29. this.setProperties({
  30. 'needsSync': true,
  31. 'syncToUser': userObj,
  32. });
  33. } else {
  34. this.get('user').setProperties(newUser);
  35. }
  36. },
  37. // Anon/auth state
  38. isAnonymous: Ember.computed.not('isAuthenticated'),
  39. logout: function() {
  40. this.session.setItem('auth-user', false);
  41. this.session.setItem('auth-is-authenticated', false);
  42. Ember.$('#hidden-logout-form').submit();
  43. },
  44. // Utils for triggering 403 error
  45. _throw: function(message) {
  46. throw {
  47. status: 403,
  48. responseJSON: {
  49. detail: message
  50. }
  51. };
  52. },
  53. denyAuthenticated: function(message) {
  54. if (this.get('isAuthenticated')) {
  55. this._throw(message || gettext('This page is not available to signed in users.'));
  56. }
  57. },
  58. denyAnonymous: function(message) {
  59. if (this.get('isAnonymous')) {
  60. this._throw(message || gettext('This page is not available to guests.'));
  61. }
  62. }
  63. });