Adding Login/Signup to Gym Management App

Chrisbradycode
2 min readJan 26, 2021

Adding Login and Signup functionality fall into the CRUD framework specifically the C (create).

Normally in a standard rails app, since it comes equipped with session functionality, the way you would create a user and log them in would look something like this :

In the sessions controller:

def create        
user = User.find_by(username: params[:user][:username])
if user && user.authenticate(params[:user][:password])
session[:user_id] = user.id
redirect_to user_path(user)
else
flash[:message] = "invalid credentials, please try again"
redirect_to login_path
end
end

And in the users controller :

def new        
@user = User.new
end

def create
@user = User.new(user_params)
if @user.save
session[:user_id] = @user.id
redirect_to user_path(@user)
else
render :new
end
end

and thats that, you would be able to create a user and log them in upon creation, and if a user existed in the database you could log them in with that code.

However, when you put Rails in API mode, a few more lines of code are needed outside of the App folder in order to allow sessions.

Your application.rb file will look like this when you create your rails app:

module GymManagementSystemclass Application < Rails::Applicationconfig.load_defaults 6.0#commented informationendend

you need to make add these lines of code with in the application class after the config.load, and before the first end:

config.api_only = trueconfig.middleware.use ActionDispatch::Cookiesconfig.middleware.use ActionDispatch::Session::CookieStore, key: '_cookie_name'

Also, in your cors.rb file which should look something like this :

Rails.application.config.middleware.insert_before 0, Rack::Cors doallow doorigins 'http://localhost:3000'resource '*',headers: :any,methods: [:get, :post, :put, :patch, :delete, :options, :head],endend

you’ll need to add the credentials: true key/value pair underneath your methods key like so:

Rails.application.config.middleware.insert_before 0, Rack::Cors doallow doorigins 'http://localhost:3000'resource '*',headers: :any,methods: [:get, :post, :put, :patch, :delete, :options, :head],credentials: trueendend

Hope this helps!

--

--