Use Devise For Authentication
Devise is great gem for authentication, check out here.
Add Gem
First thing you need to do is to add devise gem to you Gemfile. Just add gem 'devise', '~> 3.5'
to your Gemfile and run bundle install
and restart your server.
Set Up
Run generator rails generate devise:install
to install an initializer. Devise will generate lots of file, git status
to checkout. Also there will be some guides for what to do next in the terminal, just do as indicated! Something like make sure there is homepage, rails g devise:views
and configuration stuff.
Generate User
Say you want to generate a user model. Just run rails g devise User
and rake db:migrate
. Then you can go to users/sign_up
to create a new account.
Devise It
Authenticate Users
Now you can authenticate users! Say you want that only users that have signed in can edit or delete posts, otherwise, they can only go for index and show pages. It’s pretty easy, just add this code to your posts_controller.rb
file.
before_action: authenticate_user!, except: [:index, :show]
Then unauthenticated users will be redirected to sign up page if they want to edit or delete posts.
Show Edit and Delete Link for Users Signed In
If you want the Edit and Delete button shown for users signed in. Add this code to your view.
<% if user_signed_in? %>
<div id="admin_links">
<%= link_to "Edit Article", edit_post_path(@post) %>
<%= link_to "Delete Article", post_path(@post), method: :delete, data: {confirm: "Are you sure?"} %>
</div>
<% end %>
Show Sign Out Link for Users Singed In
You may also want add a sign out link for users who have signed in. To do this, add this code to your _header.html.erb
partial.
<% if user_signed_in? %>
<%= link_to "Sign Out", destroy_user_session_path, method: :delete %>
<% end %>