Update users in Gears API

pull/11839/head
Javier Torres 8 years ago
parent 71ac440c82
commit 62d663e2c1

@ -0,0 +1,21 @@
module CartoGearsApi
module Errors
# Thrown when an object could not be found in the database
class RecordNotFound < StandardError
def initialize(object)
super("Could not find #{object.class.name.split('::').last} with id #{object.id}")
end
end
# Thrown when trying to set invalid values for an object
class ValidationFailed < StandardError
# @return [Hash<String, Array<String>>] A hash with incorrect attributes as keys and array of messages as values
attr_reader :errors
def initialize(errors)
super(errors)
@errors = errors
end
end
end
end

@ -8,8 +8,11 @@ module CartoGearsApi
# @attr_reader [String] id User id
# @attr_reader [String] username User name
# @attr_reader [String] email Email
# @attr_reader [Integer] quota_in_bytes Disk quota in bytes
# @attr_reader [Boolean] viewer The user is a viewer (cannot create maps, datasets, etc.)
# @attr_reader [CartoGearsApi::Organizations::Organization] organization Organization
class User < Value.new(:id, :username, :email, :organization, :feature_flags, :can_change_email)
class User < Value.new(:id, :username, :email, :organization, :feature_flags, :can_change_email, :quota_in_bytes,
:viewer)
extend ActiveModel::Naming
include ActiveRecord::AttributeMethods::PrimaryKey

@ -1,5 +1,6 @@
require_dependency 'carto_gears_api/users/user'
require_dependency 'carto_gears_api/organizations/organization'
require_dependency 'carto_gears_api/errors'
module CartoGearsApi
module Users
@ -12,6 +13,30 @@ module CartoGearsApi
user(request.env['warden'].user(CartoDB.extract_subdomain(request)))
end
# Updates the values of a user.
#
# Only the following values can be updated: +quota_in_bytes+, +viewer+
# @note Setting +viewer = true+ resets all quotas to 0
#
# @param user [User] the user with updated values
# @return [User] the modified user
# @raise [Errors::RecordNotFound] if the user could not be found in the database
# @raise [Errors::ValidationFailed] if the validation failed
#
# @example Change the quota of the logged user
# user_service = CartoGearsApi::Users::UsersService.new
# user_service.update(user_service.logged_user(request).with(quota_in_bytes: 10000000))
def update(updated_user)
db_user = ::User.find(id: updated_user.id)
raise CartoGearsApi::Errors::RecordNotFound.new(updated_user) unless db_user
db_user.viewer = updated_user.viewer
db_user.quota_in_bytes = updated_user.quota_in_bytes
raise CartoGearsApi::Errors::ValidationFailed.new(db_user.errors) unless db_user.save
user(db_user)
end
private
def user(user)
@ -21,7 +46,9 @@ module CartoGearsApi
email: user.email,
organization: user.organization ? organization(user.organization) : nil,
feature_flags: user.feature_flags,
can_change_email: user.can_change_email?
can_change_email: user.can_change_email?,
quota_in_bytes: user.quota_in_bytes,
viewer: user.viewer
)
end

Loading…
Cancel
Save