1

I am using Cancan to ensure only users with permissions can delete objects in my Rails app. I have a companion mobile application that submits delete requests with the auth_token of a user. This is what the request looks like:

Started DELETE "/projects/888?auth_token=ArpuyxbDyjtyn67r3JgF"
Processing by ProjectsController#destroy as */*
Parameters: {"auth_token"=>"ArpuyxbDyjtyn67r3JgF", "id"=>"888", "project"=>{}}

But I am getting that the user is unauthorized.

This is what I put in my controller:

class ProjectsController < ApplicationController
 def destroy
    @project = Project.find(params[:id])
    if params[:auth_token]
      current_user = User.where(:authentication_token => params[:auth_token]).first
    end

    authorize! :destroy, @project
    @project.destroy
    respond_to do |format|
      format.html{ redirect_to user_path(current_user.username) }
      format.json { head :no_content}
    end    
  end
end

And this is my ability.rb file:

class Ability
  include CanCan::Ability

  def initialize(user)

    user ||= User.new

    can :destroy, Project do |project|
        project.user == user || (user && user.admin?)
    end
end

Checking my database, the correct auth_token is being passed for the user.

How do I get the cancan user to match the user with the passed auth_token parameter so it can satisfy the ability permissions?

scientiffic
  • 9,045
  • 18
  • 76
  • 149

1 Answers1

0

I think the issue is that you are setting a local variable of current_user as opposed to having a controller method which finds and returns the current user. Cancan is looking for a controller method to find the current_user.

Levsero
  • 591
  • 1
  • 4
  • 14
  • I thought the app would be able to determine the current user automatically with the passed authentication token – is this an issue that I should be resolving with devise or with cancan? – scientiffic Aug 10 '15 at 18:23
  • Just make sure you're actually signing in the user with devise, should fix it if this is the issue. – Levsero Aug 10 '15 at 18:27