auth.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. userObserver: function() {
  40. this.session.setItem('auth-user', this.get('user'));
  41. }.observes('user.avatar_hash'),
  42. // Anon/auth state
  43. isAnonymous: Ember.computed.not('isAuthenticated'),
  44. logout: function() {
  45. this.session.setItem('auth-user', false);
  46. this.session.setItem('auth-is-authenticated', false);
  47. Ember.$('#hidden-logout-form').submit();
  48. },
  49. // Utils for triggering 403 error
  50. _throw: function(message) {
  51. throw {
  52. status: 403,
  53. responseJSON: {
  54. detail: message
  55. }
  56. };
  57. },
  58. denyAuthenticated: function(message) {
  59. if (this.get('isAuthenticated')) {
  60. this._throw(message || gettext('This page is not available to signed in users.'));
  61. }
  62. },
  63. denyAnonymous: function(message) {
  64. if (this.get('isAnonymous')) {
  65. this._throw(message || gettext('This page is not available to guests.'));
  66. }
  67. }
  68. });