Allow users to be uniquely identified by login

pull/5122/head
Oliver Günther 8 years ago
parent fc911b2e0d
commit 350de7c482
No known key found for this signature in database
GPG Key ID: 88872239EB414F99
  1. 17
      app/models/user.rb
  2. 2
      lib/api/v3/users/users_api.rb
  3. 15
      spec/models/user_spec.rb
  4. 16
      spec/requests/api/v3/user/user_resource_spec.rb

@ -481,6 +481,23 @@ class User < Principal
end end
end end
##
# Returns the first user that matches (in this order), either:
# 1. The given ID
# 2. The given login
def self.find_by_unique(login_or_id)
matches = where(id: login_or_id).or(where(login: login_or_id)).to_a
case matches.length
when 0
raise ActiveRecord::RecordNotFound
when 1
return matches.first
else
return matches.find { |user| user.id.to_s == login_or_id.to_s }
end
end
# Find a user account by matching the exact login and then a case-insensitive # Find a user account by matching the exact login and then a case-insensitive
# version. Exact matches will be given priority. # version. Exact matches will be given priority.
def self.find_by_login(login) def self.find_by_login(login)

@ -89,7 +89,7 @@ module API
helpers ::API::V3::Users::UpdateUser helpers ::API::V3::Users::UpdateUser
before do before do
@user = User.find(params[:id]) @user = User.find_by_unique(params[:id])
end end
get do get do

@ -46,21 +46,18 @@ describe User, type: :model do
} }
describe 'a user with a long login (<= 256 chars)' do describe 'a user with a long login (<= 256 chars)' do
let(:login) { 'a' * 256 }
it 'is valid' do it 'is valid' do
user.login = 'a' * 256 user.login = login
expect(user).to be_valid expect(user).to be_valid
end end
it 'may be stored in the database' do
user.login = 'a' * 256
expect(user.save).to be_truthy
end
it 'may be loaded from the database' do it 'may be loaded from the database' do
user.login = 'a' * 256 user.login = login
user.save expect(user.save).to be_truthy
expect(User.find_by_login('a' * 256)).to eq(user) expect(User.find_by_login(login)).to eq(user)
expect(User.find_by_unique(login)).to eq(user)
end end
end end

@ -182,6 +182,22 @@ describe 'API v3 User resource', type: :request do
end end
end end
context 'get with login' do
let(:get_path) { api_v3_paths.user user.login }
before do
allow(User).to receive(:current).and_return current_user
get get_path
end
it 'should respond with 200' do
expect(subject.status).to eq(200)
end
it 'should respond with correct body' do
expect(subject.body).to be_json_eql(user.name.to_json).at_path('name')
end
end
it_behaves_like 'handling anonymous user' do it_behaves_like 'handling anonymous user' do
let(:path) { api_v3_paths.user user.id } let(:path) { api_v3_paths.user user.id }
end end

Loading…
Cancel
Save