In general, we can use authentication gems like Devise and OmniAuth to build up the login and logout process. But here, we will start from scratch and implement it in our postit.
First we will add has_secure_password to the user model. In the user.rb file,
classSessionsController<ApplicationControllerdefnewenddefcreateuser=User.find_by(username:params[username])ifuser&&user.authenticate(params[:password])session[:user_id]=user.idflash[:notice]="You've logged in!"redirect_toroot_pathelseflash[:error]="There were something wrong with your username or password."render:newendenddefdestroysession[:user_id]=nilflash[:notice]="You've logged out!"redirect_toroot_pathendend
Following the actions in sessions#controller, we will need new.html.erb.
Now the login and logout structure is ready to use and in order to make the life easier to modify the view templates, we need several helper methods.
1234567891011121314
defcurrent_user@current_user||=User.find_by(sessions[:user_id])ifsession[:user_id]enddeflogged_in?!!current_userenddefrequire_userunlesslogged_in?flash[:error]="This action is not allowed."redirect_toroot_pathendend
VoilĂ ! Next step will be to customize the view templates to logged_in user and not.