User Auth and Password Protection: Rails
Let’s create a login system!
After setting up your login/signup form on the frontend, it’s time to set up the backend! (assuming you did it a little backwards like me!)
sessions_controller.rb
The SessionsController handles the login action — our Create method.
We need to make it so that Create looks up a user in our db, confirms that the information we passed in is correct, and then stores the authenticated user id in the session.
It will look something like this:
def create
user = User.find_by(username: params[:username])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
render json: user, status: :ok
else
render json: {error: “User cannot be found”}, status: :unauthorized
end
end
Note the error handling close to the bottom. If the username and password can’t be authenticated, we’ll get the error “User cannot be found” and a 401 status code (unauthorized)
users_controller.rb
Next, in our users_controller we have to create a method that saves a created user and password.
def create
user = User.create(username: params[:username], password: params[:password])
if user.save
session[:user_id] = user.id
render json: user, status: :created
else
render json: {error: user.errors.full_messages}
end
end
Next, we’ll have to work with our routes to POST our login and signup requests.
routes.rb
post “/login”, to: “sessions#create”
post “signup”, to: “users#create”
user.rb
Don’t forget your user model!
Within it, you need to include:
has_secure_password
validates :username, presence: true
and within your users table include :password_digest & :username
make sure to update your gem.file to include: gem ‘bcrypt’
Now, you just have to set up the frontend!