I'm trying to set up something that allows users to go to certain urls only under certain circumstances. Right now I have a
setEvent/:id url that sets a property on users to an
event_id, then redirects the user to the
event url. The user can access a url like
1 needs to equal the
event_id, and if it doesn't it redirects the user.
However, this doesn't stop someone from just typing
.../whatever/setEvent/:id into their address bar to get access to the page.
The proper way to do this is with a before action in your controllers. Here is an example from one of my apps where a user who is not logged in will always be redirected to the new_session URL.
class ApplicationController < ActionController::Base helper_method :current_user, :logged_in?, :herd_user def herd_user redirect_to new_session_url unless logged_in? end ... other medthods... end
class StaticPagesController < ApplicationController before_action :herd_user def index end end
without bringing in more gems you can just do a before_action
before_action :enforce_tenancy, except: [:index] before_action :allow_only_admin, only: [:index] private def enforce_tenancy render unauthorized unless event.user_id == current_user.id end def allow_only_admin render no_way_sucka_path unless current_user.admin? end
I had a similar problem and this might not be the best way to handle it but in the action for that page you can check the current url and check the property then redirect to the one they can access if they go to an incorrect url.
Something kind of like:
url_id = request.fullpath.sub('/whatever/event/', '') redirect_to user_page_path(user.id) unless (current_user.event_id.to_s == url_id)
Sorry if the code isn't great I tried to write it based off of the info you gave.
Edit* Make sure to do this before getting any info for the page from your database or it will be less efficient.