rails在账号注册时,通过邮件形式,发送验证码, 进行注册验证。
项目中本计划用短信进行注册验证。但开发阶段想想还是先用邮箱验证代替吧。第一次做这样的验证,记录一下。
基本思路: 前端请求验证码 --> 生成随机验证码,k=>v 形式保存在redis 。
注册时,在redis中查找请求邮箱地址对应的验证码 ---> 和参数值中的验证码进行比较。
注意点: 验证码请求需要使用 post 。
redis: 安装配置
https://www.cnblogs.com/yungg/p/8004046.html
rails: 邮件服务器配置
https://blog.csdn.net/code_for_free/article/details/51311340
第一步:生成验证码
# POST security_code
def genetate_security_code
security_code = rand(1000..9999)
$redis.set(params[:base_authentication][:email], security_code)
UserMailer.send_security_code(params[:email], security_code).deliver_later
render json: {security_code: security_code}, status: 200
end
第二步: 注册时比对验证码
# POST /api/v1/users.json
def create
unless params[:user][:security_code].to_s == $redis.get(params[:user][:email])
render json: {message: "验证码错误"}, status: :unprocessable_entity
return
end
@user = User.new(user_params)
if @user.save
render :show, status: :created
else
render json: @user.errors, status: :unprocessable_entity
end
end
希望对大家有用, 有不对的地方请留言指教, 谢谢