简体   繁体   中英

Rails authenticate admin for pages — but allow jquery calls

I want to add a private method to LanguagesController :authenticate_admin

Is there a way to only have it run on the pages themselves, but if a jQuery call is made to that controller, it is allowed?

right now I have

before_action :authenticate_admin


private
def authenticate_admin
      if current_user.role_id != 1
        redirect_to home_path
      end
end

But there is a dropdown of languages on the sign up and user's dashboard. So, in profile,js there is:

var getLanguages = $.get('/languages.json', function(languages){
        lang = languages
        var langConfirmSource = $('#language-confirmation-template').html();
        var langConfirmCompiled = Handlebars.compile(langConfirmSource);
        var langConfirmTemplate = langConfirmCompiled(languages)
        $('body').append(langConfirmTemplate)
     });

What is the right way to set it to protect admin only on pages, but let jQuery do it's thing when called?

I assume you have a page, rendered by a rails application and have your JavaScript code on that page. This page is authenticated and you want to allow an ajax request to be public accessible.

If that is correct, you might want to skip your authentication when a specific request comes in.

So you can create a new route, mapping to your controller method and having a skip_authenticate_admin for that method:

class LanguagesController < ApplicationController
  skip_before_action : authenticate_admin, only: [:languages_whatever]

   def languages_whatever
     render json: data
   end
end

does it help?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM