undefined method `attributes' for nil:NilClass - Wicked/Devise gems - ruby-on-rails

I'm trying to implement Wicked gem with Devise as I want users to go through different steps in order to complete their profiles. I'm a complete newbie so I would appreciate if you can give me a suggestion on what could be the problem.
The error I'm getting is this one and it shows when I try to continue from "Personal" to "Style" step. I guess it's a problem with saving the data:
NoMethodError in OnboardingController#update
undefined method `attributes' for nil:NilClass
**#user.attributes(user_params)**
These are my registration and onboarding controllers:
class RegistrationsController < Devise::RegistrationsController
protected
def after_sign_up_path_for(resource)
'/onboarding/personal'
end
def after_update_path_for(resource)
registration_steps_path
end
def new
super
end
def create
super
end
def update
super
end
def update_resource(resource, params)
if resource.encrypted_password.blank? # || params[:password].blank?
resource.email = params[:email] if params[:email]
if !params[:password].blank? && params[:password] == params[:password_confirmation]
logger.info "Updating password"
resource.password = params[:password]
resource.save
end
if resource.valid?
resource.update_without_password(params)
end
else
resource.update_with_password(params)
end
end
end
and
class OnboardingController < ApplicationController
include Wicked::Wizard
steps :personal, :stylefirst
def show
#user = current_user
render_wizard
end
def update
#user = current_user
#user.attributes(user_params)
render_wizard #user
end
end

With Devise, current_user is nil if no user is logged in. So your problem is that you're assigning #user = current_user on your update action without verifying a user is signed in.
If you want to ensure the update action is only available to signed in users then use the authenticate_user! helper action provided by Devise:
class OnboardingController < ApplicationController
before_filter :authenticate_user!, only: [:edit, :update]
# ...
end
The authenticate_user! helper method will redirect the user to the sign in page if they're not logged in. If the user successfully signs in, current_user will be set and they will be redirected back to the page the originally tried to access.

Related

Authorize Users to perform various CRUD actions for each controller without using Pundit; Ruby on Rails

I am currently building a simple web app with Ruby on Rails that allows logged in users to perform CRUD actions to the User model. I would like to add a function where:
Users can select which actions they can perform per controller;
Ex: User A can perform actions a&b in controller A, whereas User B can only perform action B in controller A. These will be editable via the view.
Only authorized users will have access to editing authorization rights of other users. For example, if User A is authorized, then it can change what User B will be able to do, but User B, who is unauthorized, will not be able to change its own, or anyone's performable actions.
I already have my users controller set up with views and a model
class UsersController < ApplicationController
skip_before_action :already_logged_in?
skip_before_action :not_authorized, only: [:index, :show]
def index
#users = User.all
end
def new
#user = User.new
end
def create
#user = User.new(user_params)
if #user.save
redirect_to users_path
else
render :new
end
end
def show
set_user
end
def edit
set_user
end
def update
if set_user.update(user_params)
redirect_to user_path(set_user)
else
render :edit
end
end
def destroy
if current_user.id == set_user.id
set_user.destroy
session[:user_id] = nil
redirect_to root_path
else
set_user.destroy
redirect_to users_path
end
end
private
def user_params
params.require(:user).permit(:email, :password)
end
def set_user
#user = User.find(params[:id])
end
end
My sessions controller:
class SessionsController < ApplicationController
skip_before_action :login?, except: [:destroy]
skip_before_action :already_logged_in?, only: [:destroy]
skip_before_action :not_authorized
def new
end
def create
user = User.find_by(email: params[:email])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
redirect_to user_path(user.id), notice: 'You are now successfully logged in.'
else
flash.now[:alert] = 'Email or Password is Invalid'
render :new
end
end
def destroy
session[:user_id] = nil
redirect_to root_path, notice: 'You have successfully logged out'
end
end
The login/logout function works, no problem there.
I started off by implementing a not_authorized method in the main application controller which by default prevents users from accessing the respective actions if the user role is not equal to 1.
def not_authorized
return if current_user.nil?
redirect_to users_path, notice: 'Not Authorized' unless current_user.role == 1
end
the problem is that I would like to make this editable. So users with role = 1 are able to edit each user's access authorization, if that makes sense.
How would I go about developing this further? I also do not want to use gems, as the sole purpose of this is for me to learn.
Any insights are appreciated. Thank you!
The basics of an authorization system is an exception class:
# app/errors/authorization_error.rb
class AuthorizationError < StandardError; end
And a rescue which will catch when your application raises the error:
class ApplicationController < ActionController::Base
rescue_from 'AuthorizationError', with: :deny_access
private
def deny_access
# see https://stackoverflow.com/questions/3297048/403-forbidden-vs-401-unauthorized-http-responses
redirect_to '/somewhere', status: :forbidden
end
end
This avoids repeating the logic all over your controllers while you can still override the deny_access method in subclasses to customize it.
You would then perform authorization checks in your controllers:
class ThingsController
before_action :authorize!, only: [:update, :edit, :destroy]
def create
#thing = current_user.things.new(thing_params)
if #thing.save
redirect_to :thing
else
render :new
end
end
# ...
private
def authorize!
#thing.find(params[:id])
raise AuthorizationError unless #thing.user == current_user || current_user.admin?
end
end
In this pretty typical scenario anybody can create a Thing, but the users can only edit things they have created unless they are admins. "Inlining" everything like this into your controllers can quickly become an unwieldy mess through as the level of complexity grows - which is why gems such as Pundit and CanCanCan extract this out into a separate layer.
Creating a system where the permissions are editable by users of the application is several degrees of magnitude harder to both conceptualize and implement and is really beyond what you should be attempting if you are new to authorization (or Rails). You would need to create a separate table to hold the permissions:
class User < ApplicationRecord
has_many :privileges
end
class Privilege < ApplicationRecord
belongs_to :thing
belongs_to :user
end
class ThingsController
before_action :authorize!, only: [:update, :edit, :destroy]
# ...
private
def authorize!
#thing.find(params[:id])
raise AuthorizationError unless owner? || admin? || privileged?
end
def owner?
#thing.user == current_user
end
def admin?
current_user.admin?
end
def privileged?
current_user.privileges.where(
thing: #thing,
name: params[:action]
)
end
end
This is really a rudimentary Role-based access control system (RBAC).

Authenticate user in controller and then redirect

I have the following code under projects_controller.rb
class Admin::ProjectsController < ApplicationController
before_filter :require_login
def require_login
while (adminLogin != 'username')
redirect_to admin_login_path and return
end
end
And this under application_controller.rb
class ApplicationController < ActionController::Base
# Return the admin user
def adminLogin
#email = params[:email]
#password = params[:password]
return #email
end
end
I am trying to get the email in that form and pass it to the projects controller so when the email is defined, the admin can log in. When I press the submit button on the form I can see the right email being sent to the projects controller by using <%= debug #email %> in the form, but the page redirects to login again. How can I then go to /projects?
[UPDATE]:
application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
# Return the admin user
def redirect_unless_admin
#email = params[:email]
password = params[:password]
if (#email == 'username')
redirect_to admin_projects_path
else
redirect_to admin_login_path
end
end
end
and I require this method in my projects_controller.rb. This is just breaking it, redirecting too many times
You should be able to get by with this in application_controller:
class ApplicationController < ActionController::Base
def redirect_unless_admin
email = params[:email]
password = params[:password]
if params[:email].present? && email == 'username'
redirect_to admin_projects_path
else
redirect_to root_path
end
end
end
and this in admin/projects_controller:
class Admin::ProjectsController < ApplicationController
before_filter :redirect_unless_admin
end
That way the redirect_unless_admin method is available to any controller that inherits application_controller. You can customize the logic any way you need to figure out which redirect to use, but this should be a good starting point.
If you need to call adminLogin from ProjectsController, it should be defined either in ApplicationController or in a common parent class which derives from ApplicationController.

Restrict access in Rails app only for users logged in

I'm learning Rails and I'm trying to restrict access to pages if a user hasn't logged in and to only allow them to view the login and sign up pages.
Currently, my code creates a session when a user logs in and clears it when the user logs out. I've got a Sessions helper so that I can check whether a user is logged in but I'm unsure how to redirect the user throughout the app if he/she's not logged in.
UPDATE:
As I posted the question, I managed to get something to work with a before_filter. Should I use a before_action or before_filter?
Do I need to copy the same method in all my controllers where I want to restrict access?
CODE:
/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
include SessionsHelper
end
/controllers/sessions_controller.rb
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
log_in user
redirect_to user
else
flash.now[:danger] = 'Invalid email/password combination'
render 'new'
end
end
def destroy
log_out
redirect_to root_url
end
end
/helpers/sessions_helper.rb
module SessionsHelper
# Logs in the given user.
def log_in(user)
session[:user_id] = user.id
end
# Returns the current logged-in user (if any).
def current_user
#current_user ||= User.find_by(id: session[:user_id])
end
# Returns true if the user is logged in, false otherwise.
def logged_in?
!current_user.nil?
end
# Logs out the current user.
def log_out
session.delete(:user_id)
#current_user = nil
end
end
You can use a before_action. The rails guide has a nice section with an example on that:
class ApplicationController < ActionController::Base
before_action :require_login
private
def require_login
unless logged_in?
flash[:error] = "You must be logged in to access this section"
redirect_to new_login_url # halts request cycle
end
end
end

pundit_user: undefined method `current_user' for #<User:0x007fcefbc2b150>

I have two layouts Admin and Domain. And I don't need any extra configuration in Admin layout. but if user tries to access Domain layout they must be in their valid domain.
This means that, I need to customize all of my Domain policy to include both current_user as well as current_domain. I found this can be done with UserContext and pundit_user... so here is what I have done:
application_controller.rb
class ApplicationController < ActionController::Base
include Pundit
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
def pundit_user
UserContext.new(current_user, current_domain)
end
def after_sign_out_path_for(resource)
root_path
end
def current_domain
#current_domain ||= Domain.where(name: requested_domain).first
end
helper_method :current_domain
private
def requested_domain
return request.env["SERVER_NAME"]
end
def user_not_authorized
# reset_session
flash[:alert] = "You are not authorized to perform this action"
redirect_to(request.referrer || root_path)
end
end
Note that, when I access Admin layout, current_domain will be nil and if I visit any routes of Domain layout, then current_domain will set to currently accessing domain.
user_context.rb
class UserContext
attr_reader :current_user, :current_domain
def initialize(current_user, current_domain)
#current_user = current_user
#current_domain = current_domain
end
end
PROBLEM
Suppose I have this policy:
user_policy.rb
class UserPolicy < ApplicationPolicy
attr_reader :user, :scope
def initialize(user, scope)
#user = user
#scope = scope
end
def index?
binding.pry # debugging
current_user.admin? ||
current_user.domain == current_domain
end
private
def current_user
# return user.is_a?(User) ? user : user.current_user
user.current_user
end
def current_domain
# return user.is_a?(User) ? nil : user.current_domain
user.current_domain
end
end
when application runs current_user and current_domain must available in UserPolicy as per documentation(https://github.com/elabs/pundit#additional-context).
But I am getting
undefined method `current_user' for #<User:0x007fcefbc2b150>
That means, still I have user object in it, not user.current_user and user.current_domain
Please let me know, if you need further description. What am I missing here?
It was my own dumb mistake.
PROBLEM
I had a before_filter call in domain/base_controller.rb something like:
class Domain::BaseController < ApplicationController
before_action :authenticate_user!
before_action :domain_exists?
before_action :verify_domain!
private
def verify_domain!
# PROBLEM: this line was updating pundit_user again to user object
raise Pundit::NotAuthorizedError unless DomainConsolePolicy.new(current_user, current_domain).authorized?
end
def domain_exists?
if current_domain.blank?
redirect_to root_path, alert: 'Domain that you provided is not valid or is permanently removed!'
end
end
end
SOLUTION:
I have used headless policy for this because now I have both current_user and current_domain set with pundit_user in application_controller
domain/base_controller.rb
class Domain::BaseController < ApplicationController
before_action :authenticate_user!
before_action :domain_exists?
before_action :verify_domain!
private
def verify_domain!
# SOLUTION
authorize :domain_console, :has_access?
end
def domain_exists?
if current_domain.blank?
redirect_to root_path, alert: 'Domain that you provided is not valid or is permanently removed!'
end
end
end
policy/domain_console_policy.rb
class DomainConsolePolicy < Struct.new(:user, :domain_console)
def has_access?
user.current_user.admin? ||
user.current_user.domain_id == user.current_domain.id
end
end
Thanks

Couldn't find User with 'id'=true Omniauth - rails 4

I am implementing omniauth for twitter and I have run into an error "Couldn't find User with 'id'=true" the error is pointing to the application controller current_user metho. Heere is my current_user method:
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
helper_method :current_user
private
def current_user
#current_user ||= User.find(session[:user_id]) if session[:user_id]
end
end
and here is my User model:
class User < ActiveRecord::Base
def self.find_or_create_by_auth(auth_data)
user = where(provider: auth_data[:provider], uid: auth_data[:uid]).first_or_create
user.update(name: auth_data[:info][:name])
end
end
and finally the SessionController is below:
class SessionsController < ApplicationController
def create
#user = User.find_or_create_by_auth(request.env["omniauth.auth"])
session[:user_id] = #user
redirect_to products_path, notice: "logged in as "
end
def destroy
session[:user_id] = nil
redirect_to root_path, notice: "Goodbye!!"
end
end
When I trying to log in the error pops and i can't get past login to load my index page.
I think your problem should be solved with following modification in User.find_or_create_by_auth method:
def self.find_or_create_by_auth(auth_data)
# all previous code
# you should return user from here
# your current code returned true of false
user
end
Also you should save #user.id in session, not full #user object:
session[:user_id] = #user.id
I finally solved this, the issue was that i had deleted the previous authenticated twitter user in the db and i was trying to authenticate with the same credentials again on the app.
so what i did is create a new twitter app and use different keys to authenticate into my rails App... hoep this explains it thanks

Resources