Rails subscription limitations
-
28-09-2019 - |
Question
I have an application with set limits on subscription attributes i/e a user can have five projects for subscription A but have ten for subscription B
At present I run a check on there current usage when linking to the create action and if they are over there limit I do not display the link to create a new project. On the view (for the new project ) I again run the check (in a helper) to see if they can create a new project and if they are not I display a message stating so and a little upgrade link.
Is this a secure method of stopping a user bypassing there subscription attribute limitations ?
What about direct PUT requests etc ?
Solution
You can also validate that the user's subscription allows starting a new project when a new project is created. This guarantee that even if they posted directly to the new_project_path they would get an error.
class Project
belongs_to :user
validate_on_create :subscription_allows_new_project
def subscription_allows_new_project
unless self.user.subscription.max_projects > self.user.projects.count
errors.add_to_base("Project limit reached, please upgrade today!")
end
end
end
OTHER TIPS
If you're really cautious about the put requests, you could simply create a helper method that you call in all of the pages.
<% if has_user_hit_project_limits %>
Upgrade Now!
<% else %>
Add project
<% end %>
def has_user_hit_project_limits
if #logic
true
else
false
end
end