diff --git a/app/models/user.rb b/app/models/user.rb index 0edf48210cc..bd1c6635c8a 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -131,11 +131,12 @@ class User < ActiveRecord::Base end def change_username(new_username) + current_username = self.username self.username = new_username if SiteSetting.call_mothership? and self.valid? begin - Mothership.register_nickname( self.username, self.email ) + Mothership.change_nickname( current_username, new_username ) rescue Mothership::NicknameUnavailable return false rescue => e diff --git a/lib/mothership.rb b/lib/mothership.rb index e5e78edccf0..26a126fdc01 100644 --- a/lib/mothership.rb +++ b/lib/mothership.rb @@ -19,10 +19,20 @@ module Mothership if json.has_key?('success') true else - raise NicknameUnavailable # json['failed'] == -200 + raise NicknameUnavailable # TODO: report ALL the errors end end + def self.change_nickname(current_nickname, new_nickname) + json = put("/users/#{current_nickname}/nickname", {nickname: new_nickname}) + if json.has_key?('success') + true + else + raise NicknameUnavailable # TODO: report ALL the errors + end + end + + def self.current_discourse_version get('/current_version')['version'] end @@ -40,6 +50,11 @@ module Mothership JSON.parse(response) end + def self.put(rel_url, params={}) + response = RestClient.put( "#{mothership_base_url}#{rel_url}", {access_token: access_token}.merge(params), content_type: :json, accept: accepts ) + JSON.parse(response) + end + def self.mothership_base_url if Rails.env == 'production' 'http://api.discourse.org/api' diff --git a/spec/components/mothership_spec.rb b/spec/components/mothership_spec.rb index cd8575e8b6a..9b2a2ec3bd6 100644 --- a/spec/components/mothership_spec.rb +++ b/spec/components/mothership_spec.rb @@ -61,4 +61,34 @@ describe Mothership do Mothership.current_discourse_version().should == 1.0 end end + + describe '#change_nickname' do + it 'should return true when nickname is changed successfully' do + RestClient.stubs(:put).returns( {success: 'OK'}.to_json ) + Mothership.change_nickname('MacGyver', 'MacG').should be_true + end + + it 'should return raise NicknameUnavailable when nickname is not available' do + RestClient.stubs(:put).returns( {failed: -200}.to_json ) + expect { + Mothership.change_nickname('MacGyver', 'MacG') + }.to raise_error(Mothership::NicknameUnavailable) + end + + # TODO: General error handling in mothership.rb + + # it 'should return raise NicknameUnavailable when nickname does not belong to this forum' do + # RestClient.stubs(:put).returns( {failed: -13}.to_json ) + # expect { + # Mothership.change_nickname('MacGyver', 'MacG') + # }.to raise_error(Mothership::ActionForbidden) + # end + + # it 'should return raise NicknameUnavailable when nickname does not belong to this forum' do + # RestClient.stubs(:put).returns( {failed: -13}.to_json ) + # expect { + # Mothership.change_nickname('MacGyver', 'MacG') + # }.to raise_error(Mothership::ActionForbidden) + # end + end end