]> git.openstreetmap.org Git - rails.git/blob - app/controllers/friendships_controller.rb
Merge pull request #4197 from AntonKhorev/user-resources
[rails.git] / app / controllers / friendships_controller.rb
1 class FriendshipsController < ApplicationController
2   include UserMethods
3
4   layout "site"
5
6   before_action :authorize_web
7   before_action :set_locale
8   before_action :check_database_readable
9
10   authorize_resource
11
12   before_action :check_database_writable, :only => [:make_friend, :remove_friend]
13
14   def make_friend
15     @new_friend = User.find_by(:display_name => params[:display_name])
16
17     if @new_friend
18       if request.post?
19         friendship = Friendship.new
20         friendship.befriender = current_user
21         friendship.befriendee = @new_friend
22         if current_user.friends_with?(@new_friend)
23           flash[:warning] = t ".already_a_friend", :name => @new_friend.display_name
24         elsif current_user.friendships.where("created_at >= ?", Time.now.utc - 1.hour).count >= current_user.max_friends_per_hour
25           flash.now[:error] = t ".limit_exceeded"
26         elsif friendship.save
27           flash[:notice] = t ".success", :name => @new_friend.display_name
28           UserMailer.friendship_notification(friendship).deliver_later
29         else
30           friendship.add_error(t(".failed", :name => @new_friend.display_name))
31         end
32
33         referer = safe_referer(params[:referer]) if params[:referer]
34
35         redirect_to referer || user_path
36       end
37     else
38       render_unknown_user params[:display_name]
39     end
40   end
41
42   def remove_friend
43     @friend = User.find_by(:display_name => params[:display_name])
44
45     if @friend
46       if request.post?
47         if current_user.friends_with?(@friend)
48           Friendship.where(:befriender => current_user, :befriendee => @friend).delete_all
49           flash[:notice] = t ".success", :name => @friend.display_name
50         else
51           flash[:error] = t ".not_a_friend", :name => @friend.display_name
52         end
53
54         referer = safe_referer(params[:referer]) if params[:referer]
55
56         redirect_to referer || user_path
57       end
58     else
59       render_unknown_user params[:display_name]
60     end
61   end
62 end