From 4faa4fd5556ab2311d01fa9fe2149c0447d903bf Mon Sep 17 00:00:00 2001 From: ricola Date: Sun, 6 Apr 2025 17:04:31 -0600 Subject: [PATCH] Validate email and password --- views/login.erb | 2 ++ views/signup.erb | 23 +++++++++++++++++++++-- vote.rb | 22 ++++++++++++++++++---- 3 files changed, 41 insertions(+), 6 deletions(-) diff --git a/views/login.erb b/views/login.erb index fd64e04..ada5979 100644 --- a/views/login.erb +++ b/views/login.erb @@ -1,7 +1,9 @@

<%= _("Login") %>

+ <% if @error %>

<%= @error %>

<% end %> +

diff --git a/views/signup.erb b/views/signup.erb index 3ee2e58..7eb7ff3 100644 --- a/views/signup.erb +++ b/views/signup.erb @@ -1,13 +1,32 @@

<%= _("Create account") %>

+<% if @errors %> +<% @errors.each do |error| %> + <% if error.attribute == :password and error.type == :blank %> +

<%= _("Specify a password.") %>

+ <% end %> +<% end %> +<% end %> + +<% if @user and @user.errors.any? %> +<% @user.errors.each do |error| %> + <% if error.attribute == :email and error.type == :invalid %> +

<%= _("Email is not a valid email address.") %>

+ <% end %> + <% if error.attribute == :email and error.type == :taken %> +

<%= _("An account already exists for %{email}.") % { email: @user.email } %>

+ <% end %> +<% end %> +<% end %> +

- +

- +

diff --git a/vote.rb b/vote.rb index c70ec7f..71f7f01 100644 --- a/vote.rb +++ b/vote.rb @@ -28,6 +28,8 @@ class User < ActiveRecord::Base has_many :ratings has_many :organizers has_many :votes, through: :organizers + validates :email, uniqueness: true + validates :email, format: URI::MailTo::EMAIL_REGEXP end class Organizer < ActiveRecord::Base @@ -81,9 +83,21 @@ get '/signup' do end post '/signup' do - @user = User.create(email: params[:email], - password: hash_password(params[:password])) - redirect '/' + @user = User.create(email: params[:email]) + @errors = [] + if params[:password].empty? + @errors << OpenStruct.new(:attribute => :password, :type => :blank) + else + @user.password = hash_password(params[:password]) + end + if @errors.empty? and @user.valid? + @user.save + session.clear + session[:user_id] = @user.id + redirect '/' + else + erb :signup + end end get '/login' do @@ -97,7 +111,7 @@ post '/login' do session[:user_id] = user.id redirect '/' else - @error = 'Username or password was incorrect' + @error = _("Incorrect email or password.") erb :login end end