Fast Auth in a Rails API
Here is how you can set up Authentication quickly in a Rails API
Before we start we will need the bycpt gem
gem install bcrypt
Then we start by building the User model with email and password attributes
rails g model User email password_digest
After this we can check our table it should look like
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :email
t.string :password_digestt.timestamps
end
end
end
This is the magic of the password digest and has secured digest. When we describe the password digest rails automatically knows that we want a password and a password confirmation set of attributes in our user model.
Then we can go to the User model and update it to make sure that it has all attributes we want set up how we want.
class User < ApplicationRecord
has_secure_passwordvalidates_presence_of :email
validates_uniqueness_of :email
end
After this we can go to our routes file and set up the session routes and configure it.
Rails.application.routes.draw do
resources :sessions, only: [:create]
root to: "main#home"
end
Then last and definitely not least. We head over to the Sessions controller . This is the part that will be communication with the Front End ie the post. We set up the info that it is giving back in JSON.
class SessionsController < ApplicationController
def create
user = User
.find_by(email: params["user"]["email"])
.try(:authenticate, params["user"]["password"])if user
session[:user_id] = user.id
render json: {
status: created,
logged_in: true,
user:user
}
else
render json: { status: 401}
end
end
end
I hope this has helped you understand more about authentication and be able to get your sessions up and running fast.