Fast Auth in a Rails API

gem install bcrypt
rails g model User email password_digest
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :email
t.string :password_digest
t.timestamps
end
end
end
class User < ApplicationRecord 
has_secure_password
validates_presence_of :email
validates_uniqueness_of :email
end
Rails.application.routes.draw do
resources :sessions, only: [:create]
root to: "main#home"
end
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

--

--

--

Full Stack Software Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

What if our fingers have numbers?

A Data Scientist’s Intro to the Web

My experience with JavaFX to write Desktop Applications

Flutter asynchronous method — (1)Future

Need More SEO Data? Consider the SEMRush API in your Workflow (Updated!)

Version Control with Git

How to start with Binemon NFT Game?

Design Patterns Introduction

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kenneth Kebaara

Kenneth Kebaara

Full Stack Software Developer

More from Medium

Create REST API with Ruby On Rails (Part 2)

Ruby on Rails — Phase 4 Project

CURD actions with Ruby Sinatra

Creating Multiple User Types with a One-To-Many Relationship in Rails

Close-up of a needle with 2 threads coming in one side and coming out the other side intertwined.