I am trying to make a note application in rails 4 and I really do not want to use devise or any any other user authentication system because I would really just like to code it my self. The only problem I have found is that there aren't any good tutorials out there. The tutorials that I have found do not teach you how to really do user authentication because you just stay on the so called home page the whole time. So I was wondering if anybody had any ideas or examples of user authentication methods from scratch?
Thanks I really appreciate it.
Don't do it.
You have no idea of the number of ways that you can accidentally leave yourself open to serious compromise.
You are not as smart as the hundreds of developers that have been working for years on devise (none of us are).
Have a look at the Rails Security Guide for a short list of the ways that people can use your app that you probably never even considered.
If you want to play around and have a go to see how it's done, then sure play... but when you come to actually securing a real app... Just Use Devise.
If this is a personal learning exercise for then there is no better way than to google for information. Plenty of tutorials available. These tutorials don't need to be about Ruby (or Rails). Basic principles are identical regardless of implementation language.
Learn by example via examining existing code. You can find a number of existing auth systems here. Look at their code.
https://www.ruby-toolbox.com/categories/rails_authentication
If you are planning to use your own authentication I would discourage you from doing so. The auth problem may seem simple at first, but there are a number of challenges and landmines that await you: sessions, sensitive data storage/transmission, cookie-handling, etc, etc. These are just a scratch at the surface.
The link @miler350 is a great place to start however with Rails 4, ActionModel now has has_secure_password
that takes care of managing the password hash, you just need password_digest
field in your table and enable the bcrypt
gem in your gemfile (don't forget to run bundle install
). Check out the APIDoc http://apidock.com/rails/ActiveModel/SecurePassword/ClassMethods/has_secure_password.
As for authenticating a user I use the before_action
helper methods in the controllers that I want to protect. For example on my UserController
I have before_action :require_login
that references
def require_login
unless current_user
flash[:error] = MessageBox.alert("You must be logged in to view this")
redirect_to root_url
end
end
http://guides.rubyonrails.org/action_controller_overview.html#filters
This assumes that you have a helper method in your ApplicationController
def current_user
begin
@current_user ||= User.find(session[:user_id]) if session[:user_id]
rescue
session[:user_id] = nil
end
end
helper_method :current_user