Refactor: Instead of getting currentUser from the Discourse namespace, use

`Discourse.User.current()`
This commit is contained in:
Robin Ward
2013-05-28 11:08:32 -04:00
parent 55526e24d6
commit 57f97880e6
26 changed files with 101 additions and 124 deletions

View File

@ -4,7 +4,7 @@
@class AdminDashboardController @class AdminDashboardController
@extends Ember.Controller @extends Ember.Controller
@namespace Discourse @namespace Discourse
@module Discourse @module Discourse
**/ **/
Discourse.AdminDashboardController = Ember.Controller.extend({ Discourse.AdminDashboardController = Ember.Controller.extend({
loading: true, loading: true,
@ -12,11 +12,11 @@ Discourse.AdminDashboardController = Ember.Controller.extend({
problemsCheckInterval: '1 minute ago', problemsCheckInterval: '1 minute ago',
foundProblems: function() { foundProblems: function() {
return(Discourse.currentUser.admin && this.get('problems') && this.get('problems').length > 0); return(Discourse.User.current('admin') && this.get('problems') && this.get('problems').length > 0);
}.property('problems'), }.property('problems'),
thereWereProblems: function() { thereWereProblems: function() {
if(!Discourse.currentUser.admin) { return false } if(!Discourse.User.current('admin')) { return false }
if( this.get('foundProblems') ) { if( this.get('foundProblems') ) {
this.set('hadProblems', true); this.set('hadProblems', true);
return true; return true;

View File

@ -54,7 +54,7 @@ Discourse.AdminUser = Discourse.User.extend({
approve: function() { approve: function() {
this.set('can_approve', false); this.set('can_approve', false);
this.set('approved', true); this.set('approved', true);
this.set('approved_by', Discourse.get('currentUser')); this.set('approved_by', Discourse.User.current());
Discourse.ajax("/admin/users/" + (this.get('id')) + "/approve", {type: 'PUT'}); Discourse.ajax("/admin/users/" + (this.get('id')) + "/approve", {type: 'PUT'});
}, },

View File

@ -52,38 +52,6 @@ Discourse = Ember.Application.createWithMixins({
}, 200); }, 200);
}.observes('title', 'hasFocus', 'notify'), }.observes('title', 'hasFocus', 'notify'),
currentUserChanged: function() {
// We don't want to receive any previous user notifications
var bus = Discourse.MessageBus;
bus.unsubscribe("/notification/*");
bus.callbackInterval = Discourse.SiteSettings.anon_polling_interval;
bus.enableLongPolling = false;
var user = this.get('currentUser');
if (user) {
bus.callbackInterval = Discourse.SiteSettings.polling_interval;
bus.enableLongPolling = true;
if (user.admin || user.moderator) {
bus.subscribe("/flagged_counts", function(data) {
user.set('site_flagged_posts_count', data.total);
});
}
bus.subscribe("/notification/" + user.id, (function(data) {
user.set('unread_notifications', data.unread_notifications);
user.set('unread_private_messages', data.unread_private_messages);
}), user.notification_channel_position);
bus.subscribe("/categories", function(data){
var site = Discourse.Site.instance();
data.categories.each(function(c){
site.updateCategory(c)
});
});
}
}.observes('currentUser'),
// The classes of buttons to show on a post // The classes of buttons to show on a post
postButtons: function() { postButtons: function() {
return Discourse.SiteSettings.post_menu.split("|").map(function(i) { return Discourse.SiteSettings.post_menu.split("|").map(function(i) {
@ -179,13 +147,11 @@ Discourse = Ember.Application.createWithMixins({
@method logout @method logout
**/ **/
logout: function() { logout: function() {
Discourse.KeyValueStore.abandonLocal(); Discourse.User.logout().then(function() {
Discourse.ajax("/session/" + this.get('currentUser.username'), {
type: 'DELETE'
}).then(function() {
// Reloading will refresh unbound properties // Reloading will refresh unbound properties
Discourse.KeyValueStore.abandonLocal();
window.location.reload(); window.location.reload();
}); })
}, },
authenticationComplete: function(options) { authenticationComplete: function(options) {

View File

@ -38,7 +38,7 @@ Discourse.ClickTrack = {
userId = $link.data('user-id'); userId = $link.data('user-id');
if (!userId) userId = $article.data('user-id'); if (!userId) userId = $article.data('user-id');
var ownLink = userId && (userId === Discourse.get('currentUser.id')); var ownLink = userId && (userId === Discourse.User.current('id'));
// Build a Redirect URL // Build a Redirect URL
var trackingUrl = Discourse.getURL("/clicks/track?url=" + encodeURIComponent(href)); var trackingUrl = Discourse.getURL("/clicks/track?url=" + encodeURIComponent(href));
@ -99,7 +99,7 @@ Discourse.ClickTrack = {
} }
// Otherwise, use a custom URL with a redirect // Otherwise, use a custom URL with a redirect
if (Discourse.get('currentUser.external_links_in_new_tab')) { if (Discourse.User.current('external_links_in_new_tab')) {
var win = window.open(trackingUrl, '_blank'); var win = window.open(trackingUrl, '_blank');
win.focus(); win.focus();
} else { } else {

View File

@ -72,9 +72,8 @@ Discourse.ScreenTrack = Ember.Object.extend({
return; return;
} }
// We don't log anything unless we're logged in // We don't log anything unless we're logged in
if (!Discourse.get('currentUser')) { if (!Discourse.User.current()) return;
return;
}
newTimings = {}; newTimings = {};
Object.values(this.timings, function(timing) { Object.values(this.timings, function(timing) {
if (!_this.totalTimings[timing.postNumber]) if (!_this.totalTimings[timing.postNumber])

View File

@ -12,8 +12,10 @@ Discourse.ApplicationController = Discourse.Controller.extend({
needs: ['modal'], needs: ['modal'],
showLogin: function() { showLogin: function() {
var _ref; var modalController = this.get('controllers.modal');
return (_ref = this.get('controllers.modal')) ? _ref.show(Discourse.LoginView.create()) : void 0; if (modalController) {
modalController.show(Discourse.LoginView.create())
}
}, },
routeChanged: function(){ routeChanged: function(){

View File

@ -94,9 +94,9 @@ Discourse.ComposerController = Discourse.Controller.extend({
opts = opts || {}; opts = opts || {};
_this.close(); _this.close();
if (composer.get('creatingTopic')) { if (composer.get('creatingTopic')) {
Discourse.set('currentUser.topic_count', Discourse.get('currentUser.topic_count') + 1); Discourse.set('currentUser.topic_count', Discourse.User.current('topic_count') + 1);
} else { } else {
Discourse.set('currentUser.reply_count', Discourse.get('currentUser.reply_count') + 1); Discourse.set('currentUser.reply_count', Discourse.User.current('reply_count') + 1);
} }
Discourse.URL.routeTo(opts.post.get('url')); Discourse.URL.routeTo(opts.post.get('url'));
}, function(error) { }, function(error) {
@ -133,7 +133,7 @@ Discourse.ComposerController = Discourse.Controller.extend({
if (this.get('content.editingPost')) return; if (this.get('content.editingPost')) return;
// If creating a topic, use topic_count, otherwise post_count // If creating a topic, use topic_count, otherwise post_count
var count = this.get('content.creatingTopic') ? Discourse.get('currentUser.topic_count') : Discourse.get('currentUser.reply_count'); var count = this.get('content.creatingTopic') ? Discourse.User.current('topic_count') : Discourse.User.current('reply_count');
if (count >= Discourse.SiteSettings.educate_until_posts) { if (count >= Discourse.SiteSettings.educate_until_posts) {
this.set('educationClosed', true); this.set('educationClosed', true);
this.set('educationContents', ''); this.set('educationContents', '');

View File

@ -1,7 +1,7 @@
/** /**
This controller supports actions when listing categories This controller supports actions when listing categories
@class ListCategoriesController @class ListCategoriesController
@extends Discourse.ObjectController @extends Discourse.ObjectController
@namespace Discourse @namespace Discourse
@module Discourse @module Discourse
@ -9,34 +9,30 @@
Discourse.ListCategoriesController = Discourse.ObjectController.extend({ Discourse.ListCategoriesController = Discourse.ObjectController.extend({
needs: ['modal'], needs: ['modal'],
categoriesEven: (function() { categoriesEven: function() {
if (this.blank('categories')) { if (this.blank('categories')) return Em.A();
return Em.A();
}
return this.get('categories').filter(function(item, index) { return this.get('categories').filter(function(item, index) {
return (index % 2) === 0; return (index % 2) === 0;
}); });
}).property('categories.@each'), }.property('categories.@each'),
categoriesOdd: (function() { categoriesOdd: function() {
if (this.blank('categories')) { if (this.blank('categories')) return Em.A();
return Em.A();
}
return this.get('categories').filter(function(item, index) { return this.get('categories').filter(function(item, index) {
return (index % 2) === 1; return (index % 2) === 1;
}); });
}).property('categories.@each'), }.property('categories.@each'),
editCategory: function(category) { editCategory: function(category) {
this.get('controllers.modal').show(Discourse.EditCategoryView.create({ category: category })); this.get('controllers.modal').show(Discourse.EditCategoryView.create({ category: category }));
return false; return false;
}, },
canEdit: (function() { canEdit: function() {
var u; var u = Discourse.User.current();
u = Discourse.get('currentUser');
return u && u.admin; return u && u.admin;
}).property() }.property()
}); });

View File

@ -15,7 +15,7 @@ Discourse.ListController = Discourse.Controller.extend({
availableNavItems: function() { availableNavItems: function() {
var summary = this.get('filterSummary'); var summary = this.get('filterSummary');
var loggedOn = !!Discourse.get('currentUser'); var loggedOn = !!Discourse.User.current();
return Discourse.SiteSettings.top_menu.split("|").map(function(i) { return Discourse.SiteSettings.top_menu.split("|").map(function(i) {
return Discourse.NavItem.fromText(i, { return Discourse.NavItem.fromText(i, {
loggedOn: loggedOn, loggedOn: loggedOn,
@ -90,7 +90,7 @@ Discourse.ListController = Discourse.Controller.extend({
canEditCategory: function() { canEditCategory: function() {
if( this.present('category') ) { if( this.present('category') ) {
var u = Discourse.get('currentUser'); var u = Discourse.User.current();
return u && u.admin; return u && u.admin;
} else { } else {
return false; return false;

View File

@ -62,8 +62,8 @@ Discourse.PreferencesController = Discourse.ObjectController.extend({
return model.save().then(function() { return model.save().then(function() {
// model was saved // model was saved
preferencesController.set('saving', false); preferencesController.set('saving', false);
if (Discourse.currentUser.id === model.get('id')) { if (Discourse.User.current('id') === model.get('id')) {
Discourse.currentUser.set('name', model.get('name')); Discourse.User.current().set('name', model.get('name'));
} }
preferencesController.set('content.bio_cooked', preferencesController.set('content.bio_cooked',

View File

@ -31,7 +31,8 @@ Discourse.QuoteButtonController = Discourse.Controller.extend({
**/ **/
selectText: function(postId) { selectText: function(postId) {
// anonymous users cannot "quote-reply" // anonymous users cannot "quote-reply"
if (!Discourse.get('currentUser')) return; if (!Discourse.User.current()) return;
// don't display the "quote-reply" button if we can't create a post // don't display the "quote-reply" button if we can't create a post
if (!this.get('controllers.topic.content.can_create_post')) return; if (!this.get('controllers.topic.content.can_create_post')) return;

View File

@ -415,7 +415,7 @@ Discourse.TopicController = Discourse.ObjectController.extend(Discourse.Selected
}, },
toggleBookmark: function(post) { toggleBookmark: function(post) {
if (!Discourse.get('currentUser')) { if (!Discourse.User.current()) {
alert(Em.String.i18n("bookmarks.not_bookmarked")); alert(Em.String.i18n("bookmarks.not_bookmarked"));
return; return;
} }
@ -480,7 +480,7 @@ Discourse.TopicController = Discourse.ObjectController.extend(Discourse.Selected
deletePost: function(post) { deletePost: function(post) {
// Moderators can delete posts. Regular users can only create a deleted at message. // Moderators can delete posts. Regular users can only create a deleted at message.
if (Discourse.get('currentUser.staff')) { if (Discourse.User.current('staff')) {
post.set('deleted_at', new Date()); post.set('deleted_at', new Date());
} else { } else {
post.set('cooked', Discourse.Markdown.cook(Em.String.i18n("post.deleted_by_author"))); post.set('cooked', Discourse.Markdown.cook(Em.String.i18n("post.deleted_by_author")));

View File

@ -8,13 +8,13 @@
**/ **/
Discourse.UserController = Discourse.ObjectController.extend({ Discourse.UserController = Discourse.ObjectController.extend({
viewingSelf: (function() { viewingSelf: function() {
return this.get('content.username') === Discourse.get('currentUser.username'); return this.get('content.username') === Discourse.User.current('username');
}).property('content.username', 'Discourse.currentUser.username'), }.property('content.username'),
canSeePrivateMessages: (function() { canSeePrivateMessages: function() {
return this.get('viewingSelf') || Discourse.get('currentUser.staff'); return this.get('viewingSelf') || Discourse.User.current('staff');
}).property('viewingSelf', 'Discourse.currentUser') }.property('viewingSelf')
}); });

View File

@ -348,20 +348,3 @@ Handlebars.registerHelper('date', function(property, options) {
return new Handlebars.SafeString("<span class='date' title='" + fullReadable + "'>" + displayDate + "</span>"); return new Handlebars.SafeString("<span class='date' title='" + fullReadable + "'>" + displayDate + "</span>");
}); });
/**
A personalized name for display
@method personalizedName
@for Handlebars
**/
Handlebars.registerHelper('personalizedName', function(property, options) {
var name, username;
name = Ember.Handlebars.get(this, property, options);
if (options.hash.usernamePath) {
username = Ember.Handlebars.get(this, options.hash.usernamePath, options);
}
if (username !== Discourse.get('currentUser.username')) {
return name;
}
return Em.String.i18n('you');
});

View File

@ -52,7 +52,7 @@ Discourse.ActionSummary = Discourse.Model.extend({
// Add ourselves to the users who liked it if present // Add ourselves to the users who liked it if present
if (this.present('users')) { if (this.present('users')) {
this.users.pushObject(Discourse.get('currentUser')); this.users.pushObject(Discourse.User.current());
} }
// Create our post action // Create our post action

View File

@ -69,7 +69,7 @@ Discourse.Composer = Discourse.Model.extend({
}.property('editingPost', 'creatingTopic', 'post.post_number'), }.property('editingPost', 'creatingTopic', 'post.post_number'),
showAdminOptions: function() { showAdminOptions: function() {
if (this.get('creatingTopic') && Discourse.get('currentUser.staff')) return true; if (this.get('creatingTopic') && Discourse.User.current('staff')) return true;
return false; return false;
}.property('editTitle'), }.property('editTitle'),
@ -340,7 +340,7 @@ Discourse.Composer = Discourse.Model.extend({
createPost: function(opts) { createPost: function(opts) {
var post = this.get('post'), var post = this.get('post'),
topic = this.get('topic'), topic = this.get('topic'),
currentUser = Discourse.get('currentUser'), currentUser = Discourse.User.current(),
addedToStream = false; addedToStream = false;
// The post number we'll probably get from the server // The post number we'll probably get from the server
@ -384,7 +384,7 @@ Discourse.Composer = Discourse.Model.extend({
// Update last post // Update last post
topic.set('last_posted_at', new Date()); topic.set('last_posted_at', new Date());
topic.set('highest_post_number', createdPost.get('post_number')); topic.set('highest_post_number', createdPost.get('post_number'));
topic.set('last_poster', Discourse.get('currentUser')); topic.set('last_poster', Discourse.User.current());
topic.set('filtered_posts_count', topic.get('filtered_posts_count') + 1); topic.set('filtered_posts_count', topic.get('filtered_posts_count') + 1);
// Set the topic view for the new post // Set the topic view for the new post
@ -479,7 +479,7 @@ Discourse.Composer = Discourse.Model.extend({
flashDraftStatusForNewUser: function() { flashDraftStatusForNewUser: function() {
var $draftStatus = $('#draft-status'); var $draftStatus = $('#draft-status');
if (Discourse.get('currentUser.trust_level') === 0) { if (Discourse.User.current('trust_level') === 0) {
$draftStatus.toggleClass('flash', true); $draftStatus.toggleClass('flash', true);
setTimeout(function() { $draftStatus.removeClass('flash'); }, 250); setTimeout(function() { $draftStatus.removeClass('flash'); }, 250);
} }

View File

@ -9,12 +9,10 @@
Discourse.Post = Discourse.Model.extend({ Discourse.Post = Discourse.Model.extend({
shareUrl: function() { shareUrl: function() {
var user = Discourse.get('currentUser'); if (this.get('postnumber') === 1) return this.get('topic.url');
if (this.get('postnumber') === 1){
return this.get('topic.url'); var user = Discourse.User.current();
} else { return this.get('url') + (user ? '?u=' + user.get('username_lower') : '');
return this.get('url') + (user ? '?u=' + user.get('username_lower') : '');
}
}.property('url'), }.property('url'),
new_user: function() { new_user: function() {

View File

@ -38,7 +38,7 @@ Discourse.Topic = Discourse.Model.extend({
}.property('categoryName'), }.property('categoryName'),
shareUrl: function(){ shareUrl: function(){
var user = Discourse.get('currentUser'); var user = Discourse.User.current();
return this.get('url') + (user ? '?u=' + user.get('username_lower') : ''); return this.get('url') + (user ? '?u=' + user.get('username_lower') : '');
}.property('url'), }.property('url'),
@ -310,7 +310,7 @@ Discourse.Topic = Discourse.Model.extend({
if (typeof this.get('notifications_reason_id') === 'number') { if (typeof this.get('notifications_reason_id') === 'number') {
locale_string += "_" + this.get('notifications_reason_id'); locale_string += "_" + this.get('notifications_reason_id');
} }
return Em.String.i18n(locale_string, { username: Discourse.currentUser.username.toLowerCase() }); return Em.String.i18n(locale_string, { username: Discourse.User.current('username_lower') });
}.property('notification_level', 'notifications_reason_id'), }.property('notification_level', 'notifications_reason_id'),
updateNotifications: function(v) { updateNotifications: function(v) {

View File

@ -275,6 +275,45 @@ Discourse.User = Discourse.Model.extend({
}); });
Discourse.User.reopenClass({ Discourse.User.reopenClass({
/**
Returns the currently logged in user
@method current
@param {String} optional property to return from the user if the user exists
@returns {Discourse.User} the logged in user
**/
current: function(property) {
if (!this.currentUser) {
var userJson = PreloadStore.get('currentUser');
if (userJson) {
this.currentUser = Discourse.User.create(userJson);
}
}
// If we found the current user
if (this.currentUser && property) {
return this.currentUser.get(property);
}
return this.currentUser;
},
/**
Logs out the currently logged in user
@method logout
@returns {Promise} resolved when the logout finishes
**/
logout: function() {
var discourseUserClass = this;
return Discourse.ajax("/session/" + Discourse.User.current('username'), {
type: 'DELETE'
}).then(function () {
discourseUserClass.currentUser = null;
});
},
/** /**
Checks if given username is valid for this email address Checks if given username is valid for this email address

View File

@ -14,7 +14,7 @@ Discourse.UserAction = Discourse.Model.extend({
var actions = [ua.LIKE, ua.WAS_LIKED, ua.STAR, ua.EDIT, ua.BOOKMARK, ua.GOT_PRIVATE_MESSAGE, ua.NEW_PRIVATE_MESSAGE]; var actions = [ua.LIKE, ua.WAS_LIKED, ua.STAR, ua.EDIT, ua.BOOKMARK, ua.GOT_PRIVATE_MESSAGE, ua.NEW_PRIVATE_MESSAGE];
var icon = ""; var icon = "";
var sentence = ""; var sentence = "";
var sameUser = (this.get('username') === Discourse.get('currentUser.username')); var sameUser = (this.get('username') === Discourse.User.current('username'));
if (action === null || actions.indexOf(action) >= 0) { if (action === null || actions.indexOf(action) >= 0) {
if (this.get('isPM')) { if (this.get('isPM')) {
@ -60,7 +60,7 @@ Discourse.UserAction = Discourse.Model.extend({
sentence = Em.String.i18n('user_action.you_mentioned_user', { user: this.get('target_name'), sentence = Em.String.i18n('user_action.you_mentioned_user', { user: this.get('target_name'),
user1Url: this.get('userUrl'), user2Url: this.get('targetUserUrl') }); user1Url: this.get('userUrl'), user2Url: this.get('targetUserUrl') });
} else { } else {
if (this.get('target_username') === Discourse.get('currentUser.username')) { if (this.get('target_username') === Discourse.User.current('username')) {
sentence = Em.String.i18n('user_action.user_mentioned_you', { user: this.get('name'), sentence = Em.String.i18n('user_action.user_mentioned_you', { user: this.get('name'),
user1Url: this.get('userUrl'), user2Url: this.get('targetUserUrl') }); user1Url: this.get('userUrl'), user2Url: this.get('targetUserUrl') });
} else { } else {

View File

@ -27,7 +27,6 @@ Discourse.UserStream = Discourse.Model.extend({
if (result && result.user_actions && result.user_actions.each) { if (result && result.user_actions && result.user_actions.each) {
var copy = Em.A(); var copy = Em.A();
result.user_actions.each(function(i) { result.user_actions.each(function(i) {
console.log(i);
return copy.pushObject(Discourse.UserAction.create(i)); return copy.pushObject(Discourse.UserAction.create(i));
}); });
copy = Discourse.UserAction.collapseStream(copy); copy = Discourse.UserAction.collapseStream(copy);

View File

@ -8,12 +8,6 @@
**/ **/
Discourse.ApplicationRoute = Discourse.Route.extend({ Discourse.ApplicationRoute = Discourse.Route.extend({
setupController: function(controller) { setupController: function(controller) {
//Discourse.set('site', Discourse.Site.instance()); Discourse.set('currentUser', Discourse.User.current());
var currentUser = PreloadStore.get('currentUser');
if (currentUser) {
Discourse.set('currentUser', Discourse.User.create(currentUser));
}
// make sure we delete preloaded data
PreloadStore.remove('currentUser');
} }
}); });

View File

@ -150,7 +150,7 @@ Discourse.PostMenuView = Discourse.View.extend({
// Bookmark button // Bookmark button
renderBookmark: function(post, buffer) { renderBookmark: function(post, buffer) {
if (!Discourse.get('currentUser')) return; if (!Discourse.User.current()) return;
var icon = 'bookmark'; var icon = 'bookmark';
if (!this.get('post.bookmarked')) { if (!this.get('post.bookmarked')) {

View File

@ -72,7 +72,7 @@ Discourse.QuoteButtonView = Discourse.View.extend({
selectText: function(target, controller) { selectText: function(target, controller) {
var $target = $(target); var $target = $(target);
// quoting as been disabled by the user // quoting as been disabled by the user
if (!Discourse.get('currentUser.enable_quoting')) return; if (!Discourse.User.current('enable_quoting')) return;
// retrieve the post id from the DOM // retrieve the post id from the DOM
var postId = $target.closest('.boxed').data('post-id'); var postId = $target.closest('.boxed').data('post-id');
// select the text // select the text

View File

@ -19,7 +19,7 @@ Discourse.TopicFooterButtonsView = Ember.ContainerView.extend({
createButtons: function() { createButtons: function() {
var topic; var topic;
topic = this.get('topic'); topic = this.get('topic');
if (Discourse.get('currentUser')) { if (Discourse.User.current()) {
if (!topic.get('isPrivateMessage')) { if (!topic.get('isPrivateMessage')) {
// We hide some controls from private messages // We hide some controls from private messages
@ -83,7 +83,7 @@ Discourse.TopicFooterButtonsView = Ember.ContainerView.extend({
// Hide the button if it becomes unpinned // Hide the button if it becomes unpinned
unpinned: function() { unpinned: function() {
// When not logged in don't show the button // When not logged in don't show the button
if (!Discourse.get('currentUser')) return 'hidden' if (!Discourse.User.current()) return 'hidden'
return this.get('controller.pinned') ? null : 'hidden'; return this.get('controller.pinned') ? null : 'hidden';
}.property('controller.pinned'), }.property('controller.pinned'),

View File

@ -12,7 +12,7 @@ Discourse.UserSelector = Discourse.TextField.extend({
dataSource: function(term) { dataSource: function(term) {
var exclude = selected; var exclude = selected;
if (_this.get('excludeCurrentUser')){ if (_this.get('excludeCurrentUser')){
exclude = exclude.concat([Discourse.get('currentUser.username')]); exclude = exclude.concat([Discourse.User.current('username')]);
} }
return Discourse.UserSearch.search({ return Discourse.UserSearch.search({
term: term, term: term,