2014-03-05 07:52:20 -05:00
|
|
|
class UserBadgesController < ApplicationController
|
|
|
|
def index
|
2014-04-22 05:40:47 -04:00
|
|
|
params.permit(:username).permit(:granted_before)
|
|
|
|
|
2014-04-16 10:56:11 -04:00
|
|
|
if params[:username]
|
|
|
|
user = fetch_user_from_params
|
|
|
|
user_badges = user.user_badges
|
|
|
|
else
|
|
|
|
badge = fetch_badge_from_params
|
2014-05-19 01:02:59 -04:00
|
|
|
user_badges = badge.user_badges.order('granted_at DESC').limit(96)
|
2014-04-22 05:40:47 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
if params[:granted_before]
|
|
|
|
user_badges = user_badges.where('granted_at < ?', Time.at(params[:granted_before].to_f))
|
2014-04-16 10:56:11 -04:00
|
|
|
end
|
2014-04-22 05:40:47 -04:00
|
|
|
|
2014-04-17 12:27:42 -04:00
|
|
|
user_badges = user_badges.includes(:user, :granted_by, badge: :badge_type)
|
2014-04-22 05:40:47 -04:00
|
|
|
|
2014-05-21 03:22:42 -04:00
|
|
|
if params[:aggregated]
|
|
|
|
user_badges = user_badges.group(:badge_id).select(UserBadge.attribute_names.map {|x| "MAX(#{x}) as #{x}" }, 'COUNT(*) as count')
|
|
|
|
end
|
|
|
|
|
2014-04-16 10:56:11 -04:00
|
|
|
render_serialized(user_badges, UserBadgeSerializer, root: "user_badges")
|
2014-03-05 07:52:20 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def create
|
|
|
|
params.require(:username)
|
|
|
|
user = fetch_user_from_params
|
|
|
|
|
|
|
|
unless can_assign_badge_to_user?(user)
|
|
|
|
render json: failed_json, status: 403
|
|
|
|
return
|
|
|
|
end
|
|
|
|
|
|
|
|
badge = fetch_badge_from_params
|
|
|
|
user_badge = BadgeGranter.grant(badge, user, granted_by: current_user)
|
|
|
|
|
2014-03-19 05:16:16 -04:00
|
|
|
render_serialized(user_badge, UserBadgeSerializer, root: "user_badge")
|
2014-03-05 07:52:20 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def destroy
|
|
|
|
params.require(:id)
|
|
|
|
user_badge = UserBadge.find(params[:id])
|
|
|
|
|
|
|
|
unless can_assign_badge_to_user?(user_badge.user)
|
|
|
|
render json: failed_json, status: 403
|
|
|
|
return
|
|
|
|
end
|
|
|
|
|
2014-03-19 15:30:12 -04:00
|
|
|
BadgeGranter.revoke(user_badge, revoked_by: current_user)
|
2014-03-05 07:52:20 -05:00
|
|
|
render json: success_json
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
# Get the badge from either the badge name or id specified in the params.
|
|
|
|
def fetch_badge_from_params
|
|
|
|
badge = nil
|
|
|
|
|
|
|
|
params.permit(:badge_name)
|
|
|
|
if params[:badge_name].nil?
|
|
|
|
params.require(:badge_id)
|
2014-05-06 09:41:59 -04:00
|
|
|
badge = Badge.find_by(id: params[:badge_id])
|
2014-03-05 07:52:20 -05:00
|
|
|
else
|
2014-05-06 09:41:59 -04:00
|
|
|
badge = Badge.find_by(name: params[:badge_name])
|
2014-03-05 07:52:20 -05:00
|
|
|
end
|
|
|
|
raise Discourse::NotFound.new if badge.blank?
|
|
|
|
|
|
|
|
badge
|
|
|
|
end
|
|
|
|
|
|
|
|
def can_assign_badge_to_user?(user)
|
|
|
|
master_api_call = current_user.nil? && is_api?
|
|
|
|
master_api_call or guardian.can_grant_badges?(user)
|
|
|
|
end
|
|
|
|
end
|