Ruby on Rails: Form and Authentication 表以及用户登陆与退出

14 篇文章 0 订阅

Form

  • The 
destination 
url
  • Whether 
the
 data
 is 
associated 
with
 a 
model
  • The 
field
 names
  • The 
field 
input
 types
  • The
 display 
name
 of 
fields

With URL:

<%= form_with url: '/login' do |form| %>
	<%= form.label :email %>
	<%= form.text_field :email %>
	<%= form.submit %>
<% end %>

With model:

<%= form_with model: @user do |form| %>
	<%= form.label :email %>
	<%= form.text_field :email %>
	<%= form.submit %>
<% end %>

form_with models are database critical

Certain fields need to be explicitly whitelisting

params.require(:post).permit(:title, :content)

Designing forms

  1. Is the form associeated with DB insertion/update?
    • If yes, form_with model
    • If not, form_with url
  2. What end point does the form POST to?
    • define the route in route.rb
  3. What data need (field name, type, label)

Authentication

Session: on server, hash data structure

Cookie: on browser, pass session_ids to session

log in obtain a cookie and create a session

log out ask server to remove cookie-session pair

session[:last_search] = "Who am I?"
session[:user] = @user
reset_session

Implementing log in

Create SessionsController

  • new method: render a login form
  • create method
    • Check if valid login credentials were applied
    • assign session[:user_id] to user’s id
  • destroy method: call reset_session
class SessionController < ApplicationController
  def new
    @user = User.new
  end
  
  def create
    @user = User.find_by(email: params[:email])
    if @user.password == params[:password]
      session[:user_id] = @user.id
      redirect_to @user
    end
  end
  
  def destroy
    reset_session
    redirect_to @user
  end
end

<%= form_with url: '/login' do |form| %>
	<%= form.label :email %>
	<%= form.text_field :email %>

	<%= form.label :password %>
	<%= form.text_field :password %>

	<%= form.submit %>
<%= end %>

Helper methods

class ApplicationController < ActionController::Base
  helper_method :logged_in?, :current_user
  
  def logged_in?
    session[:user_id]
  end
  
  def current_user
    @current_user ||= User.find(session[:user_id]) if logged_in?
  end
  
  def authenticate_user
    redirect_to login_path unless logged_in?
  end
end

Personalizing view

<% if logged_in? %>
	<h1> Welcome <%= current_user.name %> </h1>
<% else %>
	<h1> Please Sign Up! </h1>
<% end %>
# in controller
before_action :authenticate_user

BCrypt

https://www.rubydoc.info/gems/bcrypt-ruby/3.1.5

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值