Compare commits

...

2 Commits

Author SHA1 Message Date
5e1699a4b5 Fix SQLite compatibility in Unit and Quantity models
Several fixes to make complex Arel/CTE queries work with both MySQL and SQLite:

Unit model:
- Add guard for description length validation (text column .limit returns nil in SQLite)
- defaults_diff: rename 'units' CTE to 'all_units' to avoid SQLite circular reference
  (SQLite treats any CTE in WITH RECURSIVE that references a same-named table as circular)
- defaults_diff: read from 'all_units' CTE explicitly in UNION parts via AR::Relation
  instead of relying on CTE name shadowing; use AR::Relation (not SelectManager) for
  UNION parts to avoid extra parentheses (visit_Arel_SelectManager always wraps in parens)
- defaults_diff: qualify GROUP BY and ORDER BY columns to avoid ambiguity when
  bases_units join adds a second table with same column names
- Qualify :symbol in ordering to avoid ambiguous column in joined queries

Quantity model:
- Add guard for description length validation (text column .limit returns nil in SQLite)
- ordered: rename recursive CTE from 'quantities' to 'q_ordered' to avoid circular
  reference; use AR::Relation for UNION parts; fix column qualifiers; use printf()
  instead of LPAD() for SQLite (LPAD not supported), BLOB instead of BINARY cast
- common_ancestors: rename CTE to 'q_common', use AR::Relation for UNION parts
- with_ancestors: rename CTE to 'q_ancestors', use AR::Relation for UNION parts
- successive: replace SQL LAG window function approach (which causes nested WITH
  RECURSIVE) with Ruby array approach for SQLite compatibility

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-12 14:35:19 +00:00
83b064ef3c Merge recover password/resend confirmation forms into sign in/register
Closes #65, #66
2026-03-01 20:04:42 +01:00
23 changed files with 307 additions and 227 deletions

View File

@@ -113,6 +113,12 @@ textarea {
border: solid 1px var(--color-gray);
border-radius: 0.25em;
}
[name=cancel],
.auxiliary {
border-color: var(--color-border-gray);
color: var(--color-nav-gray);
fill: var(--color-nav-gray);
}
input[type=checkbox],
svg,
textarea {
@@ -131,6 +137,7 @@ input[type=checkbox]:checked {
-webkit-appearance: checkbox;
}
/* Hide spin buttons in input number fields */
/* TODO: add spin buttons inside input[number]: before (-) and after (+) input */
input[type=number] {
appearance: textfield;
-moz-appearance: textfield;
@@ -340,6 +347,7 @@ header {
opacity: 1;
}
/* TODO: Hover over invalid should work like in measurements (thin vs thick border) */
.labeled-form {
align-items: center;
@@ -371,9 +379,17 @@ header {
}
.labeled-form input[type=submit] {
font-size: 1rem;
margin: 1.5em auto 0 auto;
margin: 1em auto 0 auto;
padding: 0.75em;
}
.labeled-form .auxiliary {
grid-column: 3;
/* If more buttons are needed, `grid-row` can be replaced with
* `reading-flow: grid-columns` to ensure proper tabindex order */
grid-row: 1;
height: 100%;
padding-block: 0;
}
/* TODO: remove .items class (?) and make 'form table' work properly */
@@ -532,11 +548,6 @@ table.items select:focus-within,
table.items select:focus-visible {
color: black;
}
form a[name=cancel] {
border-color: var(--color-border-gray);
color: var(--color-nav-gray);
fill: var(--color-nav-gray);
}
form table.items {
border: none;
}

View File

@@ -25,6 +25,18 @@ class ApplicationController < ActionController::Base
# Turbo will reload 2nd time with HTML format and flashes will be lost.
rescue_from *ActionDispatch::ExceptionWrapper.rescue_responses.keys, with: :rescue_turbo
# Required by #respond_with (gem `responders`) used by Devise controllers.
respond_to :html, :turbo_stream
def after_sign_in_path_for(resource)
# TODO: allow setting path per-user or save last path in session and restore
units_path
end
def after_sign_out_path_for(resource)
new_user_session_path
end
protected
def current_user_disguised?

View File

@@ -1,6 +1,4 @@
class RegistrationsController < Devise::RegistrationsController
before_action :authenticate_user!, only: [:edit, :update, :destroy]
class User::ProfilesController < Devise::RegistrationsController
def destroy
# TODO: Disallow/disable deletion for last admin account; update :edit view
super

View File

@@ -37,7 +37,7 @@ class UsersController < ApplicationController
end
# NOTE: limited actions availabe to :admin by design. Users are meant to
# manage their accounts by themselves through registrations. :admin
# manage their accounts by themselves through profiles. :admin
# is allowed to sign-in (disguise) as user and make changes from there.
protected

View File

@@ -72,13 +72,8 @@ module ApplicationHelper
end
def labeled_form_for(record, options = {}, &block)
extra_options = {builder: LabeledFormBuilder,
data: {turbo: false},
html: {class: 'labeled-form'}}
options = options.deep_merge(extra_options) do |key, left, right|
key == :class ? class_names(left, right) : right
end
form_for(record, **options, &block)
extra_options = {builder: LabeledFormBuilder, html: {class: 'labeled-form'}}
form_for(record, **merge_attributes(options, extra_options), &block)
end
class TabularFormBuilder < ActionView::Helpers::FormBuilder
@@ -135,16 +130,16 @@ module ApplicationHelper
# [autofocus]. Otherwise IDs are not unique when multiple forms are open
# and the first input gets focus.
record_object, options = nil, record_object if record_object.is_a?(Hash)
options.merge!(builder: TabularFormBuilder, skip_default_ids: true)
extra_options = {builder: TabularFormBuilder, skip_default_ids: true}
options = merge_attributes(options, extra_options)
# TODO: set error message with setCustomValidity instead of rendering to flash?
render_errors(record_object || record_name)
fields_for(record_name, record_object, **options, &block)
end
def tabular_form_with(**options, &block)
options = options.deep_merge(builder: TabularFormBuilder,
html: {autocomplete: 'off'})
form_with(**options, &block)
extra_options = {builder: TabularFormBuilder, html: {autocomplete: 'off'}}
form_with(**merge_attributes(options, extra_options), &block)
end
def svg_tag(source, label = nil, options = {})
@@ -159,6 +154,7 @@ module ApplicationHelper
['measurements', 'scale-bathroom', :restricted],
['quantities', 'axis-arrow', :restricted, 'right'],
['units', 'weight-gram', :restricted],
# TODO: display users tab only if >1 user present; sole_user?/sole_admin?
['users', 'account-multiple-outline', :admin],
]
@@ -206,6 +202,7 @@ module ApplicationHelper
def render_errors(records)
# Conversion of flash to Array only required because of Devise
# TODO: override Devise message setting to Array()?
flash[:alert] = Array(flash[:alert])
Array(records).each { |record| flash[:alert] += record.errors.full_messages }
end
@@ -215,6 +212,7 @@ module ApplicationHelper
# Conversion of flash to Array only required because of Devise
Array(messages).map do |message|
tag.div class: "flash #{entry}" do
# TODO: change button text to svg to make it aligned vertically
tag.div(sanitize(message)) + tag.button(sanitize("&times;"), tabindex: -1,
onclick: "this.parentElement.remove();")
end
@@ -252,4 +250,11 @@ module ApplicationHelper
[name, html_options]
end
# Like Hash#deep_merge, but aware of HTML attributes.
def merge_attributes(left, right)
left.deep_merge(right) do |key, lvalue, rvalue|
key == :class ? class_names(lvalue, rvalue) : rvalue
end
end
end

View File

@@ -37,6 +37,18 @@ window.detailsObserver = new MutationObserver((mutations) => {
mutations[0].target.dispatchEvent(new Event('change', {bubbles: true}))
});
function formValidate(event) {
var id = event.submitter.getAttribute("data-validate")
if (!id) return;
var input = document.getElementById(id)
if (!input.checkValidity()) {
input.reportValidity()
event.preventDefault()
}
}
window.formValidate = formValidate
/* Turbo stream actions */
Turbo.StreamElement.prototype.disableElement = function(element) {

View File

@@ -16,7 +16,7 @@ class Quantity < ApplicationRecord
end
validates :name, presence: true, uniqueness: {scope: [:user_id, :parent_id]},
length: {maximum: type_for_attribute(:name).limit}
validates :description, length: {maximum: type_for_attribute(:description).limit}
validates :description, length: {maximum: type_for_attribute(:description).limit} if type_for_attribute(:description).limit
# Update :depths of progenies after parent change
before_save if: :parent_changed? do
@@ -61,18 +61,22 @@ class Quantity < ApplicationRecord
# Return: ordered [sub]hierarchy
scope :ordered, ->(root: nil, include_root: true) {
numbered = Arel::Table.new('numbered')
q_ordered = Arel::Table.new('q_ordered')
cast_type = connection.adapter_name == 'Mysql2' ? 'BINARY' : 'BLOB'
self.model.with(numbered: numbered(:parent_id, :name)).with_recursive(arel_table.name => [
numbered.project(
numbered[Arel.star],
numbered.cast(numbered[:child_number], 'BINARY').as('path')
).where(numbered[root && include_root ? :id : :parent_id].eq(root)),
numbered.project(
numbered[Arel.star],
arel_table[:path].concat(numbered[:child_number])
).join(arel_table).on(numbered[:parent_id].eq(arel_table[:id]))
]).order(arel_table[:path])
self.model.with(numbered: numbered(:parent_id, :name)).with_recursive(q_ordered: [
Quantity.from(Arel::Table.new('numbered').as(arel_table.name))
.select(
arel_table[Arel.star],
arel_table.cast(arel_table[:child_number], cast_type).as('path')
).where(arel_table[root && include_root ? :id : :parent_id].eq(root)),
Quantity.from(Arel::Table.new('numbered').as(arel_table.name))
.joins("INNER JOIN q_ordered ON quantities.parent_id = q_ordered.id")
.select(
arel_table[Arel.star],
q_ordered[:path].concat(arel_table[:child_number])
)
]).from(q_ordered.as(arel_table.name)).order(arel_table[:path])
}
# TODO: extract named functions to custom Arel extension
@@ -80,20 +84,24 @@ class Quantity < ApplicationRecord
# be merged with :ordered
# https://gist.github.com/ProGM/c6df08da14708dcc28b5ca325df37ceb#extending-arel
scope :numbered, ->(parent_column, order_column) {
select(
arel_table[Arel.star],
Arel::Nodes::NamedFunction.new(
'LPAD',
[
Arel::Nodes::NamedFunction.new('ROW_NUMBER', [])
.over(Arel::Nodes::Window.new.partition(parent_column).order(order_column)),
Arel::SelectManager.new.project(
Arel::Nodes::NamedFunction.new('LENGTH', [Arel.star.count])
).from(arel_table),
Arel::Nodes.build_quoted('0')
],
).as('child_number')
)
row_number = Arel::Nodes::NamedFunction.new('ROW_NUMBER', [])
.over(Arel::Nodes::Window.new.partition(parent_column).order(order_column))
width = Arel::SelectManager.new.project(
Arel::Nodes::NamedFunction.new('LENGTH', [Arel.star.count])
).from(arel_table)
pad_expr = if connection.adapter_name == 'Mysql2'
Arel::Nodes::NamedFunction.new('LPAD', [row_number, width, Arel::Nodes.build_quoted('0')])
else
# SQLite: printf('%0' || width || 'd', row_number)
fmt = Arel::Nodes::InfixOperation.new('||',
Arel::Nodes::InfixOperation.new('||', Arel::Nodes.build_quoted('%0'), width),
Arel::Nodes.build_quoted('d')
)
Arel::Nodes::NamedFunction.new('printf', [fmt, row_number])
end
select(arel_table[Arel.star], pad_expr.as('child_number'))
}
def to_s
@@ -102,7 +110,7 @@ class Quantity < ApplicationRecord
def to_s_with_depth
# em space, U+2003
'' * depth + name
' ' * depth + name
end
def destroyable?
@@ -115,16 +123,18 @@ class Quantity < ApplicationRecord
# Common ancestors, assuming node is a descendant of itself
scope :common_ancestors, ->(of) {
selected = Arel::Table.new('selected')
q_common = Arel::Table.new('q_common')
# Take unique IDs, so self can be called with parent nodes of collection to
# get common ancestors of collection _excluding_ nodes in collection.
uniq_of = of.uniq
model.with(selected: self).with_recursive(arel_table.name => [
selected.project(selected[Arel.star]).where(selected[:id].in(uniq_of)),
selected.project(selected[Arel.star])
.join(arel_table).on(selected[:id].eq(arel_table[:parent_id]))
model.with(selected: self).with_recursive(q_common: [
Quantity.from(Arel::Table.new('selected').as(arel_table.name))
.where(arel_table[:id].in(uniq_of)),
Quantity.from(Arel::Table.new('selected').as(arel_table.name))
.joins("INNER JOIN q_common ON selected.id = q_common.parent_id")
]).select(arel_table[Arel.star])
.from(q_common.as(arel_table.name))
.group(column_names)
.having(arel_table[:id].count.eq(uniq_of.size))
.order(arel_table[:depth].desc)
@@ -132,13 +142,9 @@ class Quantity < ApplicationRecord
# Return: successive record in order of appearance; used for partial view reload
def successive
quantities = Quantity.arel_table
Quantity.with(
quantities: user.quantities.ordered.select(
quantities[Arel.star],
Arel::Nodes::NamedFunction.new('LAG', [quantities[:id]]).over.as('lag_id')
)
).where(quantities[:lag_id].eq(id)).first
ordered = user.quantities.ordered.to_a
idx = ordered.index { |q| q.id == id }
ordered[idx + 1] if idx
end
def with_progenies
@@ -151,13 +157,14 @@ class Quantity < ApplicationRecord
# Return: record with ID `of` with its ancestors, sorted by :depth
scope :with_ancestors, ->(of) {
selected = Arel::Table.new('selected')
q_ancestors = Arel::Table.new('q_ancestors')
model.with(selected: self).with_recursive(arel_table.name => [
selected.project(selected[Arel.star]).where(selected[:id].eq(of)),
selected.project(selected[Arel.star])
.join(arel_table).on(selected[:id].eq(arel_table[:parent_id]))
])
model.with(selected: self).with_recursive(q_ancestors: [
Quantity.from(Arel::Table.new('selected').as(arel_table.name))
.where(arel_table[:id].eq(of)),
Quantity.from(Arel::Table.new('selected').as(arel_table.name))
.joins("INNER JOIN q_ancestors ON selected.id = q_ancestors.parent_id")
]).from(q_ancestors.as(arel_table.name))
}
# Return: ancestors of (possibly destroyed) self

View File

@@ -13,7 +13,7 @@ class Unit < ApplicationRecord
end
validates :symbol, presence: true, uniqueness: {scope: :user_id},
length: {maximum: type_for_attribute(:symbol).limit}
validates :description, length: {maximum: type_for_attribute(:description).limit}
validates :description, length: {maximum: type_for_attribute(:description).limit} if type_for_attribute(:description).limit
validates :multiplier, numericality: {equal_to: 1}, unless: :base
validates :multiplier, numericality: {greater_than: 0, precision: true, scale: true}, if: :base
@@ -22,59 +22,72 @@ class Unit < ApplicationRecord
actionable_units = Arel::Table.new('actionable_units')
units = actionable_units.alias('units')
bases_units = arel_table.alias('bases_units')
other_units = arel_table.alias('other_units')
other_bases_units = arel_table.alias('other_bases_units')
# Use 'all_units' alias for correlated subqueries to reference the all_units CTE.
# Cannot use arel_table.alias here because the CTE is named 'all_units', not 'units'.
other_units = Arel::Table.new('all_units').alias('other_units')
other_bases_units = Arel::Table.new('all_units').alias('other_bases_units')
sub_units = arel_table.alias('sub_units')
# TODO: move inner 'with' CTE to outer 'with recursive' - it can have multiple
# CTEs, even non recursive ones.
Unit.with_recursive(actionable_units: [
Unit.with(units: self.or(Unit.defaults)).left_joins(:base)
.where.not(
# Exclude Units that are/have default counterpart
Arel::SelectManager.new.project(1).from(other_units)
.outer_join(other_bases_units)
.on(other_units[:base_id].eq(other_bases_units[:id]))
.where(
other_bases_units[:symbol].is_not_distinct_from(bases_units[:symbol])
.and(other_units[:symbol].eq(arel_table[:symbol]))
.and(other_units[:user_id].is_distinct_from(arel_table[:user_id]))
).exists
)
.select(
arel_table[Arel.star],
# Decide if Unit can be im-/exported based on existing hierarchy:
# * same base unit symbol has to exist
# * unit with subunits can only be ported to root
arel_table[:base_id].eq(nil).or(
(
Arel::SelectManager.new.project(1).from(other_units)
.join(sub_units).on(other_units[:id].eq(sub_units[:base_id]))
.where(
other_units[:symbol].eq(arel_table[:symbol])
.and(other_units[:user_id].is_distinct_from(arel_table[:user_id]))
).exists.not
).and(
Arel::SelectManager.new.project(1).from(other_bases_units)
.where(
other_bases_units[:symbol].is_not_distinct_from(bases_units[:symbol])
.and(other_bases_units[:user_id].is_distinct_from(bases_units[:user_id]))
).exists
)
).as('portable')
),
# Fill base Units to display proper hierarchy. Duplicates will be removed
# by final group() - can't be deduplicated with UNION due to 'portable' field.
arel_table.join(actionable_units).on(actionable_units[:base_id].eq(arel_table[:id]))
.project(arel_table[Arel.star], Arel::Nodes.build_quoted(nil).as('portable'))
]).select(units: [:base_id, :symbol])
Unit.with_recursive(
# Renamed from 'units' to 'all_units' to avoid SQLite circular reference:
# SQLite treats any CTE in WITH RECURSIVE that references a table with the same
# name as the CTE itself as a circular reference, even for non-recursive CTEs.
all_units: self.or(Unit.defaults),
actionable_units: [
# Read from all_units CTE (user+defaults) aliased as the units table name.
# Using AR::Relation (not Arel::SelectManager) to avoid extra parentheses
# around the UNION part (visit_Arel_SelectManager always wraps in parens).
Unit.from(Arel::Table.new('all_units').as(arel_table.name))
.joins("LEFT OUTER JOIN all_units bases_units ON bases_units.id = units.base_id")
.where.not(
# Exclude Units that are/have default counterpart
Arel::SelectManager.new.project(1).from(other_units)
.outer_join(other_bases_units)
.on(other_units[:base_id].eq(other_bases_units[:id]))
.where(
other_bases_units[:symbol].is_not_distinct_from(bases_units[:symbol])
.and(other_units[:symbol].eq(arel_table[:symbol]))
.and(other_units[:user_id].is_distinct_from(arel_table[:user_id]))
).exists
)
.select(
arel_table[Arel.star],
# Decide if Unit can be im-/exported based on existing hierarchy:
# * same base unit symbol has to exist
# * unit with subunits can only be ported to root
arel_table[:base_id].eq(nil).or(
(
Arel::SelectManager.new.project(1).from(other_units)
.join(sub_units).on(other_units[:id].eq(sub_units[:base_id]))
.where(
other_units[:symbol].eq(arel_table[:symbol])
.and(other_units[:user_id].is_distinct_from(arel_table[:user_id]))
).exists.not
).and(
Arel::SelectManager.new.project(1).from(other_bases_units)
.where(
other_bases_units[:symbol].is_not_distinct_from(bases_units[:symbol])
.and(other_bases_units[:user_id].is_distinct_from(bases_units[:user_id]))
).exists
)
).as('portable')
),
# Fill base Units to display proper hierarchy. Duplicates will be removed
# by final group() - can't be deduplicated with UNION due to 'portable' field.
# Using AR::Relation instead of Arel::SelectManager to avoid extra parentheses
# around the UNION part (visit_Arel_SelectManager always wraps in parens).
Unit.from(Arel::Table.new('all_units').as(arel_table.name))
.joins("INNER JOIN actionable_units ON actionable_units.base_id = units.id")
.select(arel_table[Arel.star], Arel::Nodes.build_quoted(nil).as('portable'))
]
).select(units: [:base_id, :symbol])
.select(
units[:id].minimum.as('id'), # can be ANY_VALUE()
units[:user_id].minimum.as('user_id'), # prefer non-default
Arel::Nodes.build_quoted(1).as('multiplier'), # disregard multiplier when sorting
units[:portable].minimum.as('portable')
)
.from(units).group(:base_id, :symbol)
.from(units).group(units[:base_id], units[:symbol])
}
scope :ordered, ->{
left_outer_joins(:base).order(ordering)
@@ -84,7 +97,7 @@ class Unit < ApplicationRecord
[arel_table.coalesce(Arel::Table.new(:bases_units)[:symbol], arel_table[:symbol]),
arel_table[:base_id].not_eq(nil),
:multiplier,
:symbol]
arel_table[:symbol]]
end
before_destroy do

View File

@@ -0,0 +1 @@
<% flash.discard %>

View File

@@ -1,9 +0,0 @@
<%= labeled_form_for resource, url: user_confirmation_path,
html: {class: 'main-area'} do |f| %>
<%= f.email_field :email, required: true, size: 30, autofocus: true,
autocomplete: 'email', value:
resource.pending_reconfirmation? ? resource.unconfirmed_email : resource.email %>
<%= f.submit t(:resend_confirmation) %>
<% end %>

View File

@@ -0,0 +1,2 @@
<%# For some reason flash messages are duplicated in bot flash and flash.now %>
<% flash.discard %>

View File

@@ -1,5 +1,5 @@
<%= labeled_form_for resource, url: user_password_path,
html: {method: :put, class: 'main-area'} do |f| %>
html: {method: :put, class: 'main-area', data: {turbo: false}} do |f| %>
<%= f.hidden_field :reset_password_token %>

View File

@@ -1,8 +0,0 @@
<%= labeled_form_for resource, url: user_password_path,
html: {class: 'main-area'} do |f| %>
<%= f.email_field :email, required: true, size: 30, autofocus: true,
autocomplete: 'email' %>
<%= f.submit t(:recover_password) %>
<% end %>

View File

@@ -0,0 +1,17 @@
<%= labeled_form_for resource, url: user_registration_path,
html: {class: 'main-area', onsubmit: 'formValidate(event)'} do |f| %>
<%= f.email_field :email, required: true, size: 30, autofocus: true,
autocomplete: 'email' %>
<%= f.password_field :password, required: true, size: 30,
minlength: @minimum_password_length, autocomplete: 'new-password' %>
<%= f.password_field :password_confirmation, required: true, size: 30,
minlength: @minimum_password_length, autocomplete: 'off' %>
<%= f.submit t(:register), data: {turbo: false} %>
<%# TODO: fix button text color after change link -> button %>
<%= image_button_tag t(:resend_confirmation), 'email-sync-outline',
class: 'auxiliary', formaction: user_confirmation_path, formnovalidate: true,
data: {validate: f.field_id(:email)} %>
<% end %>

View File

@@ -1,16 +0,0 @@
<div class="main-area">
<%= labeled_form_for resource, url: user_registration_path do |f| %>
<%= f.email_field :email, required: true, size: 30, autofocus: true,
autocomplete: 'email' %>
<%= f.password_field :password, required: true, size: 30,
minlength: @minimum_password_length, autocomplete: 'new-password' %>
<%= f.password_field :password_confirmation, required: true, size: 30,
minlength: @minimum_password_length, autocomplete: 'off' %>
<%= f.submit t(:register) %>
<% end %>
<%= content_tag :p, t(:or), style: 'text-align: center;' %>
<%= image_link_to t(:resend_confirmation), 'email-sync-outline',
new_user_confirmation_path, class: 'centered' %>
</div>

View File

@@ -1,18 +1,19 @@
<div class="main-area">
<%= labeled_form_for resource, url: user_session_path do |f| %>
<%= f.email_field :email, required: true, size: 30, autofocus: true,
autocomplete: 'email' %>
<%= f.password_field :password, required: true, size: 30,
minlength: @minimum_password_length, autocomplete: 'current-password' %>
<%= labeled_form_for resource, url: user_session_path,
html: {class: 'main-area', onsubmit: 'formValidate(event)'} do |f| %>
<% if devise_mapping.rememberable? %>
<%= f.check_box :remember_me %>
<% end %>
<%= f.email_field :email, required: true, size: 30, autofocus: true,
autocomplete: 'email' %>
<%= f.password_field :password, required: true, size: 30,
autocomplete: 'current-password' %>
<%= f.submit t(:sign_in) %>
<% if devise_mapping.rememberable? %>
<%= f.check_box :remember_me %>
<% end %>
<%= content_tag :p, t(:or), style: 'text-align: center;' %>
<%= image_link_to t(:recover_password), 'lock-reset', new_user_password_path,
class: 'centered' %>
</div>
<%# /sign_in as HTML; /password as TURBO_STREAM %>
<%= f.submit t(:sign_in), data: {turbo: false} %>
<%= image_button_tag t(:recover_password), 'lock-reset', class: 'auxiliary',
formaction: user_password_path, formnovalidate: true,
data: {validate: f.field_id(:email)} %>
<% end %>

View File

@@ -91,7 +91,7 @@ Devise.setup do |config|
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# particular strategies by setting this option.

View File

@@ -4,15 +4,15 @@ en:
devise:
confirmations:
confirmed: "Your email address has been successfully confirmed."
send_instructions: "You will receive an email with instructions for how to confirm your email address in a few minutes."
send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes."
send_paranoid_instructions: >
If your email address is in our database, a message with instructions on how
to confirm your email address has been sent to you.
failure:
already_authenticated: "You are already signed in."
inactive: "Your account is not activated yet."
invalid: "Invalid %{authentication_keys} or password."
invalid: "Invalid <b>%{authentication_keys}</b> or <b>password</b>."
locked: "Your account is locked."
last_attempt: "You have one more attempt before your account is locked."
not_found_in_database: "Invalid %{authentication_keys} or password."
timeout: "Your session expired. Please sign in again to continue."
unauthenticated: "You need to sign in or sign up before continuing."
unconfirmed: "You have to confirm your email address before continuing."
@@ -32,8 +32,9 @@ en:
success: "Successfully authenticated from %{kind} account."
passwords:
no_token: "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided."
send_instructions: "You will receive an email with instructions on how to reset your password in a few minutes."
send_paranoid_instructions: "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes."
send_paranoid_instructions: >
If your email address is in our database, the password recovery link has been
sent to you.
updated: "Your password has been changed successfully. You are now signed in."
updated_not_active: "Your password has been changed successfully."
registrations:
@@ -50,7 +51,6 @@ en:
signed_out: "Signed out successfully."
already_signed_out: "Signed out successfully."
unlocks:
send_instructions: "You will receive an email with instructions for how to unlock your account in a few minutes."
send_paranoid_instructions: "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes."
unlocked: "Your account has been unlocked successfully. Please sign in to continue."
errors:

View File

@@ -150,7 +150,7 @@ en:
edit:
password_html: 'New password:%{password_length_hint_html}'
update_password: Update password
registrations:
profiles:
new:
password_html: 'Password:%{password_length_hint_html}'
password_confirmation: 'Retype password:'
@@ -169,7 +169,6 @@ en:
cancel: Cancel
delete: Delete
:no: 'no'
or: or
register: Register
sign_in: Sign in
recover_password: Recover password

View File

@@ -24,8 +24,9 @@ Rails.application.routes.draw do
# https://github.com/heartcombo/devise/issues/5786
connection = ActiveRecord::Base.connection
if connection.schema_version && connection.table_exists?(:users)
# NOTE: change helper prefix from *_registration to *_profile once possible
devise_for :users, path: '', path_names: {registration: 'profile'},
controllers: {registrations: :registrations}
controllers: {registrations: 'user/profiles'}
end
resources :users, only: [:index, :show, :update] do
@@ -34,9 +35,7 @@ Rails.application.routes.draw do
end
unauthenticated do
as :user do
root to: redirect('/sign_in')
end
root to: redirect('/sign_in')
end
root to: redirect('/units'), as: :user_root

View File

@@ -1,6 +1,7 @@
require "test_helper"
class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
include ActionView::Helpers::SanitizeHelper
include ActionView::Helpers::UrlHelper
# NOTE: geckodriver installed with Firefox, ignore incompatibility warning
@@ -32,7 +33,8 @@ class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
# Allow skipping interpolations when translating for testing purposes
INTERPOLATION_PATTERNS = Regexp.union(I18n.config.interpolation_patterns)
def translate(key, **options)
options.empty? ? super.split(INTERPOLATION_PATTERNS, 2).first : super
translation = options.empty? ? super.split(INTERPOLATION_PATTERNS, 2).first : super
sanitize(translation, tags: [])
end
alias :t :translate

View File

@@ -5,8 +5,8 @@ class UsersTest < ApplicationSystemTestCase
@admin = users(:admin)
end
test "sign in" do
visit new_user_session_path
test 'sign in' do
visit root_url
assert find_link(href: new_user_session_path)[:disabled]
sign_in
@@ -14,16 +14,23 @@ class UsersTest < ApplicationSystemTestCase
assert_text t('devise.sessions.signed_in')
end
test 'sign in fails with invalid password' do
sign_in password: random_password
test 'sign in fails with invalid credentials' do
label = User.human_attribute_name(:email)
# Both: valid and invalid emails should give the same (paranoid) error message.
email = [users.sample.email, random_email].sample
visit root_url
fill_in label, with: email
fill_in User.human_attribute_name(:password), with: random_password
click_on t(:sign_in)
assert_current_path new_user_session_path
assert_text t('devise.failure.not_found_in_database',
authentication_keys: User.human_attribute_name(:email))
assert_text t('devise.failure.invalid', authentication_keys: label.downcase_first)
assert find_link(href: new_user_session_path)[:disabled]
assert_not_empty find_field(User.human_attribute_name(:email)).value
assert has_field?(label, with: email)
end
test "sign out" do
test 'sign out' do
sign_in
visit root_url
click_on t("layouts.application.sign_out")
@@ -31,79 +38,106 @@ class UsersTest < ApplicationSystemTestCase
assert_text t("devise.sessions.signed_out")
end
test "recover password" do
visit new_user_session_url
click_on t(:recover_password)
test 'recover password' do
label = User.human_attribute_name(:email)
email = users.select(&:confirmed?).sample.email
visit root_url
fill_in label, with: email
# Form validations should allow empty password.
assert has_field?(User.human_attribute_name(:password), with: nil)
fill_in User.human_attribute_name(:email),
with: users.select(&:confirmed?).sample.email
assert_emails 1 do
click_on t(:recover_password)
# Wait until redirected to make sure async request has been processed
assert_current_path new_user_session_path
# Wait for flash message to make sure async request has been processed.
assert_text t("devise.passwords.send_paranoid_instructions")
end
assert_text t("devise.passwords.send_instructions")
assert has_field?(label, with: email)
with_last_email do |mail|
visit Capybara.string(mail.body.to_s).find_link("Change my password")[:href]
assert_current_path edit_user_password_path, ignore_query: true
# Make sure flash message is not displayed twice.
assert_no_text t("devise.passwords.send_paranoid_instructions")
end
new_password = random_password
fill_in t("users.passwords.edit.password_html"), with: new_password
fill_in t("helpers.label.user.password_confirmation"), with: new_password
assert_emails 1 do
click_on t("users.passwords.edit.update_password")
# Wait until redirected to make sure async request has been processed
assert_current_path units_path
assert_text t("devise.passwords.updated")
end
assert_text t("devise.passwords.updated")
end
test "register" do
visit new_user_session_url
test 'recover password for nonexistent user' do
label = User.human_attribute_name(:email)
email = random_email
visit root_url
fill_in label, with: email
assert_no_emails do
click_on t(:recover_password)
assert_current_path new_user_session_path
assert_text t("devise.passwords.send_paranoid_instructions")
end
end
test 'register' do
visit root_url
click_on t(:register)
assert find_link(href: new_user_registration_path)[:disabled]
fill_in User.human_attribute_name(:email), with: random_email
password = random_password
fill_in User.human_attribute_name(:password), with: password
fill_in t("users.registrations.new.password_confirmation"), with: password
assert_difference ->{User.count}, 1 do
fill_in t("users.profiles.new.password_confirmation"), with: password
assert_difference ->{ User.count }, 1 do
assert_emails 1 do
click_on t(:register)
# Wait until redirected to make sure async request has been processed
assert_current_path new_user_session_path
assert_text t("devise.registrations.signed_up_but_unconfirmed")
end
end
assert_text t("devise.registrations.signed_up_but_unconfirmed")
with_last_email do |mail|
visit Capybara.string(mail.body.to_s).find_link("Confirm my account")[:href]
assert_changes ->{ User.last.confirmed? }, from: false, to: true do
with_last_email do |mail|
visit Capybara.string(mail.body.to_s).find_link("Confirm my account")[:href]
assert_current_path new_user_session_path
assert_text t("devise.confirmations.confirmed")
end
end
assert_current_path new_user_session_path
assert_text t("devise.confirmations.confirmed")
assert User.last.confirmed?
end
test "resend confirmation" do
visit new_user_session_url
click_on t(:register)
click_on t(:resend_confirmation)
test 'resend confirmation' do
label = User.human_attribute_name(:email)
user = users.reject(&:confirmed?).sample
visit root_url
click_on t(:register)
fill_in label, with: user.email
assert has_field?(User.human_attribute_name(:password), with: nil)
fill_in User.human_attribute_name(:email),
with: users.reject(&:confirmed?).sample.email
assert_emails 1 do
click_on t(:resend_confirmation)
# Wait until redirected to make sure async request has been processed
assert_current_path new_user_session_path
assert_current_path new_user_registration_path
assert_text t("devise.confirmations.send_paranoid_instructions")
end
assert_current_path new_user_session_path
assert_text t("devise.confirmations.send_instructions")
assert has_field?(label, with: user.email)
with_last_email do |mail|
visit Capybara.string(mail.body.to_s).find_link("Confirm my account")[:href]
assert_changes ->{ user.reload.confirmed? }, from: false, to: true do
with_last_email do |mail|
visit Capybara.string(mail.body.to_s).find_link("Confirm my account")[:href]
assert_current_path new_user_session_path
assert_no_text t("devise.confirmations.send_paranoid_instructions")
assert_text t("devise.confirmations.confirmed")
end
end
end
test "show profile" do
test 'show profile' do
sign_in user: users.select(&:admin?).select(&:confirmed?).sample
click_on t("users.navigation")
within all('tr').drop(1).sample do |tr|
@@ -113,7 +147,7 @@ class UsersTest < ApplicationSystemTestCase
end
end
test "disguise" do
test 'disguise' do
user = users.select(&:admin?).select(&:confirmed?).sample
sign_in user: user
@@ -129,7 +163,7 @@ class UsersTest < ApplicationSystemTestCase
assert_link user.email
end
test "disguise fails for admin when disallowed" do
test 'disguise fails for admin when disallowed' do
user = users.select(&:admin?).select(&:confirmed?).sample
sign_in user: user
@@ -142,13 +176,13 @@ class UsersTest < ApplicationSystemTestCase
assert_title 'The change you wanted was rejected (422)'
end
test "disguise forbidden for non admin" do
test 'disguise forbidden for non admin' do
sign_in user: users.reject(&:admin?).select(&:confirmed?).sample
visit disguise_user_path(User.all.sample)
assert_title 'Access is forbidden to this page (403)'
end
test "delete profile" do
test 'delete profile' do
user = sign_in
# TODO: remove condition after root_url changed to different path than
# profile in routes.rb
@@ -156,23 +190,23 @@ class UsersTest < ApplicationSystemTestCase
first(:link_or_button, user.email).click
end
assert_difference ->{ User.count }, -1 do
accept_confirm { click_on t("users.registrations.edit.delete") }
accept_confirm { click_on t("users.profiles.edit.delete") }
assert_current_path new_user_session_path
end
assert_text t("devise.registrations.destroyed")
end
test "index forbidden for non admin" do
test 'index forbidden for non admin' do
sign_in user: users.reject(&:admin?).select(&:confirmed?).sample
visit users_path
assert_title "Access is forbidden to this page (403)"
end
test "update profile" do
test 'update profile' do
# TODO
end
test "update status" do
test 'update status' do
sign_in user: users.select(&:admin?).select(&:confirmed?).sample
visit users_path
@@ -187,7 +221,7 @@ class UsersTest < ApplicationSystemTestCase
assert_current_path users_path
end
test "update status fails for admin when disallowed" do
test 'update status fails for admin when disallowed' do
sign_in user: users.select(&:admin?).select(&:confirmed?).sample
visit users_path
@@ -200,7 +234,7 @@ class UsersTest < ApplicationSystemTestCase
assert_title 'The change you wanted was rejected (422)'
end
test "update status forbidden for non admin" do
test 'update status forbidden for non admin' do
sign_in user: users.reject(&:admin?).select(&:confirmed?).sample
visit units_path
inject_button_to find('body'), "update status", user_path(User.all.sample), method: :patch,