From d8cd4621943b49e605ba497e679373973569ec98 Mon Sep 17 00:00:00 2001 From: Rick Barrette Date: Sun, 15 Nov 2026 17:43:38 -0500 Subject: [PATCH] Configurable roles: Owner, Mechanic, Pilot, Viewer and custom roles MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit What people can do on an aircraft now comes from their role there, and administrators set what each role allows (Admin → Roles). - Roles are installation-wide sets of permissions (31, grouped as flying, squawks and notes, maintenance records, imports and exports, the aircraft, notifications). Seeing an aircraft's records needs none. - Built in: Owner (always every permission, so an aircraft can always be managed), Mechanic (shop maintenance: logbook, signing, components, inspections, ADs, squawks, reminders), Pilot (what pilots could do before) and Viewer (view only). Administrators can change all but Owner's, and add their own; a role can be deleted once nobody has it. - Existing owners and pilots keep exactly what they could do. - Admin → Users → a user lists their role on every aircraft, to change, remove or add. On the aircraft's Access page, anyone who manages people hands out roles, but only an Owner can give or take away Owner, nobody changes their own (except administrators), and an aircraft always keeps an Owner (AircraftAccess). - Controllers declare the permission each action needs; a request that changes something with none declared is refused (and raises in development and tests), and a test walks every route to check. - Weekly reminders and overdue alerts go to roles that get reminders; the DRS reminder also needs Manage ADs. The API follows the person's role; its owners_only error is now not_permitted. Co-Authored-By: Claude Opus 5.5 --- app/controllers/ad_alerts_controller.rb | 2 +- app/controllers/ad_compliances_controller.rb | 2 +- app/controllers/ad_imports_controller.rb | 2 +- app/controllers/admin/roles_controller.rb | 57 ++++++ .../admin/user_aircraft_roles_controller.rb | 31 +++ app/controllers/admin/users_controller.rb | 2 +- .../air_trail_exports_controller.rb | 1 + app/controllers/aircraft_controller.rb | 6 +- .../aircraft_exports_controller.rb | 2 +- app/controllers/aircraft_roles_controller.rb | 51 ++--- app/controllers/airport_codes_controller.rb | 2 +- .../airworthiness_directives_controller.rb | 4 +- app/controllers/api/v1/base_controller.rb | 8 +- .../api/v1/draft_batches_controller.rb | 4 +- app/controllers/api/v1/squawks_controller.rb | 7 +- app/controllers/components_controller.rb | 2 +- app/controllers/concerns/aircraft_scoped.rb | 68 +++++-- .../consumable_records_controller.rb | 3 +- .../document_collections_controller.rb | 2 +- app/controllers/documents_controller.rb | 2 +- .../entry_signatures_controller.rb | 1 + app/controllers/flight_imports_controller.rb | 2 +- app/controllers/flight_logs_controller.rb | 9 +- .../inspection_records_controller.rb | 2 +- .../inspection_types_controller.rb | 2 +- app/controllers/loading_setups_controller.rb | 2 +- app/controllers/logbook_entries_controller.rb | 2 +- app/controllers/logbook_imports_controller.rb | 2 +- app/controllers/major_records_controller.rb | 2 +- app/controllers/notes_controller.rb | 3 +- app/controllers/oil_analyses_controller.rb | 3 +- app/controllers/record_versions_controller.rb | 2 +- .../records_packages_controller.rb | 2 +- app/controllers/share_tokens_controller.rb | 2 +- .../signing_invitations_controller.rb | 2 +- app/controllers/squawks_controller.rb | 4 +- .../standard_inspections_controller.rb | 2 +- .../weight_balance_records_controller.rb | 2 +- app/helpers/aircraft_helper.rb | 7 +- .../controllers/offline_prep_controller.js | 6 +- app/jobs/overdue_notification_job.rb | 8 +- app/jobs/weekly_reminder_job.rb | 2 +- app/mailers/reminder_mailer.rb | 18 +- app/models/aircraft_role.rb | 18 +- app/models/flight_log.rb | 5 - app/models/permission.rb | 34 ++++ app/models/role.rb | 40 ++++ app/models/user.rb | 10 +- app/services/aircraft_access.rb | 52 +++++ app/services/aircraft_archive/importer.rb | 2 +- app/services/records_audit.rb | 2 +- app/views/admin/audits/new.html.erb | 2 +- app/views/admin/procedures/_document.html.erb | 4 +- app/views/admin/roles/_form.html.erb | 27 +++ app/views/admin/roles/edit.html.erb | 3 + app/views/admin/roles/index.html.erb | 15 ++ app/views/admin/roles/new.html.erb | 3 + app/views/admin/users/edit.html.erb | 33 ++++ app/views/admin/users/index.html.erb | 2 +- app/views/aircraft/show.html.erb | 10 +- app/views/aircraft_roles/index.html.erb | 29 ++- .../airworthiness_directives/index.html.erb | 14 +- app/views/components/index.html.erb | 4 +- app/views/components/show.html.erb | 8 +- .../consumable_records/_records.html.erb | 2 +- app/views/consumable_records/index.html.erb | 2 +- app/views/documents/_doc_row.html.erb | 2 +- app/views/documents/index.html.erb | 4 +- app/views/documents/show.html.erb | 2 +- app/views/flight_logs/index.html.erb | 6 +- app/views/flight_logs/show.html.erb | 2 +- app/views/inspections/index.html.erb | 6 +- app/views/layouts/application.html.erb | 4 +- app/views/logbook_entries/index.html.erb | 6 +- app/views/logbook_entries/show.html.erb | 12 +- app/views/major_records/index.html.erb | 2 +- app/views/major_records/show.html.erb | 6 +- app/views/notes/index.html.erb | 4 +- app/views/oil_analyses/index.html.erb | 4 +- app/views/oil_analyses/show.html.erb | 2 +- app/views/record_versions/index.html.erb | 2 +- app/views/shared/_aircraft_header.html.erb | 12 +- app/views/squawks/_form.html.erb | 2 +- app/views/squawks/_table.html.erb | 8 +- app/views/squawks/index.html.erb | 2 +- .../weight_balance_records/index.html.erb | 8 +- config/locales/en.yml | 180 +++++++++++++++++- config/routes.rb | 5 +- db/migrate/20261116010000_create_roles.rb | 56 ++++++ db/schema.rb | 18 +- docs/guide/administration.md | 12 ++ docs/guide/api.md | 8 +- docs/guide/flights.md | 2 +- docs/guide/getting-started.md | 25 +-- docs/guide/sharing.md | 6 +- .../integration/aircraft_archive_flow_test.rb | 2 +- test/integration/api_drafts_test.rb | 2 +- test/integration/permissions_test.rb | 13 +- test/integration/roles_test.rb | 169 ++++++++++++++++ test/integration/setup_test.rb | 2 +- test/services/aircraft_archive_test.rb | 2 +- 101 files changed, 1032 insertions(+), 232 deletions(-) create mode 100644 app/controllers/admin/roles_controller.rb create mode 100644 app/controllers/admin/user_aircraft_roles_controller.rb create mode 100644 app/models/permission.rb create mode 100644 app/models/role.rb create mode 100644 app/services/aircraft_access.rb create mode 100644 app/views/admin/roles/_form.html.erb create mode 100644 app/views/admin/roles/edit.html.erb create mode 100644 app/views/admin/roles/index.html.erb create mode 100644 app/views/admin/roles/new.html.erb create mode 100644 db/migrate/20261116010000_create_roles.rb create mode 100644 test/integration/roles_test.rb diff --git a/app/controllers/ad_alerts_controller.rb b/app/controllers/ad_alerts_controller.rb index 94c9da3..063fb20 100644 --- a/app/controllers/ad_alerts_controller.rb +++ b/app/controllers/ad_alerts_controller.rb @@ -2,7 +2,7 @@ # search terms used. class AdAlertsController < ApplicationController include AircraftScoped - before_action :require_owner! + requires_permission :manage_ads before_action :set_alert, only: %i[track dismiss] rate_limit to: 5, within: 1.minute, only: :check, with: -> { redirect_to aircraft_airworthiness_directives_path(@aircraft), alert: t("flash.ad_alerts.try_again_in_a") } diff --git a/app/controllers/ad_compliances_controller.rb b/app/controllers/ad_compliances_controller.rb index 52df3df..7a49009 100644 --- a/app/controllers/ad_compliances_controller.rb +++ b/app/controllers/ad_compliances_controller.rb @@ -1,6 +1,6 @@ class AdCompliancesController < ApplicationController include AircraftScoped - before_action :require_owner! + requires_permission :manage_ads before_action :set_compliance, only: %i[edit update destroy] def new diff --git a/app/controllers/ad_imports_controller.rb b/app/controllers/ad_imports_controller.rb index aa70adb..73049d6 100644 --- a/app/controllers/ad_imports_controller.rb +++ b/app/controllers/ad_imports_controller.rb @@ -2,7 +2,7 @@ class AdImportsController < ApplicationController include AircraftScoped include StoredUpload - before_action :require_owner! + requires_permission :manage_ads def new; end diff --git a/app/controllers/admin/roles_controller.rb b/app/controllers/admin/roles_controller.rb new file mode 100644 index 0000000..496cb99 --- /dev/null +++ b/app/controllers/admin/roles_controller.rb @@ -0,0 +1,57 @@ +# The roles people can have on an aircraft and what each allows (Role, +# Permission). Owner always has every permission; the other built-in roles +# can be changed but not deleted; administrators can add their own. +class Admin::RolesController < ApplicationController + before_action :require_admin! + before_action :set_role, only: %i[edit update destroy] + + def index + Role.ensure_built_in! + @roles = Role.ordered + @counts = AircraftRole.group(:role_id).count + end + + def new + @role = Role.new(permissions: Permission::DEFAULTS["viewer"]) + end + + def create + @role = Role.new(role_params) + if @role.save + redirect_to admin_roles_path, notice: t("flash.admin_roles.created", name: @role.name) + else + render :new, status: :unprocessable_entity + end + end + + def edit; end + + def update + attributes = @role.owner? ? role_params.except(:permissions) : role_params + if @role.update(attributes) + redirect_to admin_roles_path, notice: t("flash.admin_roles.updated", name: @role.name) + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + if @role.built_in? + redirect_to admin_roles_path, alert: t("flash.admin_roles.built_in") + elsif @role.aircraft_roles.exists? + redirect_to admin_roles_path, alert: t("flash.admin_roles.in_use", name: @role.name, count: @role.aircraft_roles.count) + else + @role.destroy! + redirect_to admin_roles_path, notice: t("flash.admin_roles.deleted", name: @role.name) + end + end + + private + + def set_role = @role = Role.find(params[:id]) + + # Unticking every box sends none, so an empty list is always sent too. + def role_params + params.require(:role).permit(:name, :description, permissions: []).tap { _1[:permissions] = Array(_1[:permissions]).compact_blank } + end +end diff --git a/app/controllers/admin/user_aircraft_roles_controller.rb b/app/controllers/admin/user_aircraft_roles_controller.rb new file mode 100644 index 0000000..1b42ed3 --- /dev/null +++ b/app/controllers/admin/user_aircraft_roles_controller.rb @@ -0,0 +1,31 @@ +# Administrators give people roles on any aircraft (from Admin → Users), +# under the same rules as the aircraft's Access page (AircraftAccess). +class Admin::UserAircraftRolesController < ApplicationController + before_action :require_admin! + before_action :set_user + + def create + aircraft = Aircraft.find_by(id: params[:aircraft_id]) + return back(alert: t("services.aircraft_access.not_found")) unless aircraft + back_with AircraftAccess.new(aircraft, actor: current_user).add(@user, Role.find_by(id: params[:role_id])), + t("flash.admin_users.access_added", tail_number: aircraft.tail_number) + end + + def update + membership = @user.aircraft_roles.find(params[:id]) + back_with AircraftAccess.new(membership.aircraft, actor: current_user).change(membership, Role.find_by(id: params[:role_id])), + t("flash.admin_users.access_changed", tail_number: membership.aircraft.tail_number) + end + + def destroy + membership = @user.aircraft_roles.find(params[:id]) + back_with AircraftAccess.new(membership.aircraft, actor: current_user).remove(membership), + t("flash.admin_users.access_removed", tail_number: membership.aircraft.tail_number) + end + + private + + def set_user = @user = User.find(params[:user_id]) + def back(flash) = redirect_to(edit_admin_user_path(@user, anchor: "access"), flash) + def back_with(error, notice) = back(error ? { alert: error } : { notice: notice }) +end diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rb index 0953bfb..ac9eeec 100644 --- a/app/controllers/admin/users_controller.rb +++ b/app/controllers/admin/users_controller.rb @@ -3,7 +3,7 @@ class Admin::UsersController < ApplicationController before_action :set_user, only: %i[edit update destroy disable enable unlock reset_two_factor] def index - @users = User.order(:email_address).includes(:certificates, aircraft_roles: :aircraft) + @users = User.order(:email_address).includes(:certificates, aircraft_roles: %i[aircraft role]) end def new diff --git a/app/controllers/air_trail_exports_controller.rb b/app/controllers/air_trail_exports_controller.rb index f765de6..ab8c92b 100644 --- a/app/controllers/air_trail_exports_controller.rb +++ b/app/controllers/air_trail_exports_controller.rb @@ -1,6 +1,7 @@ # Download the aircraft's flights as an AirTrail import file. class AirTrailExportsController < ApplicationController include AircraftScoped + requires_permission :log_flights def new @export = build_export diff --git a/app/controllers/aircraft_controller.rb b/app/controllers/aircraft_controller.rb index 6092d0d..6851a55 100644 --- a/app/controllers/aircraft_controller.rb +++ b/app/controllers/aircraft_controller.rb @@ -1,7 +1,9 @@ class AircraftController < ApplicationController include AircraftScoped - skip_before_action :set_aircraft, only: %i[index new create] - before_action :require_owner!, only: %i[edit update destroy] + skip_before_action :set_aircraft, :authorize_permission!, only: %i[index new create] + requires_permission :edit_aircraft, only: %i[edit update] + requires_permission :delete_aircraft, only: :destroy + requires_permission :update_hours, only: :update_hours def index @aircraft_list = current_user.accessible_aircraft.ordered.with_attached_picture diff --git a/app/controllers/aircraft_exports_controller.rb b/app/controllers/aircraft_exports_controller.rb index fd3d4f3..92a4142 100644 --- a/app/controllers/aircraft_exports_controller.rb +++ b/app/controllers/aircraft_exports_controller.rb @@ -1,7 +1,7 @@ # Download an aircraft as a .sam.zip archive (owners and admins). class AircraftExportsController < ApplicationController include AircraftScoped - before_action :require_owner! + requires_permission :export_data EXPORT_DIR = Rails.root.join("tmp/exports") diff --git a/app/controllers/aircraft_roles_controller.rb b/app/controllers/aircraft_roles_controller.rb index 9d62166..1eabc3b 100644 --- a/app/controllers/aircraft_roles_controller.rb +++ b/app/controllers/aircraft_roles_controller.rb @@ -1,54 +1,37 @@ -# Owner-only: manage who can access the aircraft, and its public share links. +# Who can access the aircraft, with which role ("manage people"), and its +# public share links ("manage sharing", see ShareTokensController). The rules +# for changing roles are in AircraftAccess. class AircraftRolesController < ApplicationController include AircraftScoped - before_action :require_owner! + checks_permission_itself only: :index + requires_permission :manage_people, only: %i[create update destroy] def index - @roles = @aircraft.roles.includes(:user).order(:role, :created_at) + return permission_denied unless can?(:manage_people) || can?(:manage_sharing) || can?(:export_data) + @access = AircraftAccess.new(@aircraft, actor: current_user) + @roles = @aircraft.roles.includes(:user, :role).joins(:role).order("roles.position", :created_at) @share_tokens = @aircraft.share_tokens.order(created_at: :desc).includes(:created_by) end def create user = User.find_by(email_address: params[:email_address].to_s.strip.downcase) - unless user - return redirect_to aircraft_aircraft_roles_path(@aircraft), - alert: t("flash.aircraft_roles.no_user_with_that") - end - role = @aircraft.roles.new(user: user, role: params[:role]) - if role.save - log_event("role", t("flash.aircraft_roles.added_as", display_name: user.display_name, role: role.role)) - redirect_to aircraft_aircraft_roles_path(@aircraft), notice: t("flash.aircraft_roles.added", display_name: user.display_name) - else - redirect_to aircraft_aircraft_roles_path(@aircraft), alert: role.errors.full_messages.to_sentence - end + return back(alert: t("flash.aircraft_roles.no_user_with_that")) unless user + error = access.add(user, Role.find_by(id: params[:role_id])) + back(error ? { alert: error } : { notice: t("flash.aircraft_roles.added", display_name: user.display_name) }) end def update - role = @aircraft.roles.find(params[:id]) - if demoting_last_owner?(role, params[:role]) - return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: t("flash.aircraft_roles.an_aircraft_must_keep") - end - role.update!(role: params[:role]) - log_event("role", t("flash.aircraft_roles.changed_to", display_name: role.user.display_name, role: role.role)) - redirect_to aircraft_aircraft_roles_path(@aircraft), notice: t("flash.aircraft_roles.role_updated") + error = access.change(@aircraft.roles.find(params[:id]), Role.find_by(id: params[:role_id])) + back(error ? { alert: error } : { notice: t("flash.aircraft_roles.role_updated") }) end def destroy - role = @aircraft.roles.find(params[:id]) - if role.user == current_user - return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: t("flash.aircraft_roles.you_can_t_remove") - end - if demoting_last_owner?(role, nil) - return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: t("flash.aircraft_roles.an_aircraft_must_keep_2") - end - role.destroy! - log_event("role", t("flash.aircraft_roles.removed", display_name: role.user.display_name)) - redirect_to aircraft_aircraft_roles_path(@aircraft), notice: t("flash.aircraft_roles.access_removed") + error = access.remove(@aircraft.roles.find(params[:id])) + back(error ? { alert: error } : { notice: t("flash.aircraft_roles.access_removed") }) end private - def demoting_last_owner?(role, new_role) - role.role == "owner" && new_role != "owner" && @aircraft.roles.owners.count <= 1 - end + def access = AircraftAccess.new(@aircraft, actor: current_user) + def back(flash) = redirect_to(aircraft_aircraft_roles_path(@aircraft), flash) end diff --git a/app/controllers/airport_codes_controller.rb b/app/controllers/airport_codes_controller.rb index 77eb74f..abf674d 100644 --- a/app/controllers/airport_codes_controller.rb +++ b/app/controllers/airport_codes_controller.rb @@ -1,7 +1,7 @@ # Flights → Standardize airport codes (owners). class AirportCodesController < ApplicationController include AircraftScoped - before_action :require_owner! + requires_permission :edit_any_flight def show @standardizer = AirportCodeStandardizer.new(@aircraft) diff --git a/app/controllers/airworthiness_directives_controller.rb b/app/controllers/airworthiness_directives_controller.rb index 25f32ad..f57b8b3 100644 --- a/app/controllers/airworthiness_directives_controller.rb +++ b/app/controllers/airworthiness_directives_controller.rb @@ -1,14 +1,14 @@ class AirworthinessDirectivesController < ApplicationController include AircraftScoped include Applicability - before_action :require_owner!, except: :index + requires_permission :manage_ads, except: :index before_action :set_ad, only: %i[edit update destroy] def index @rows = Compliance.ad_rows(@aircraft) @history = AdCompliance.for_aircraft(@aircraft).recent_first .includes(:component, :logbook_entry, airworthiness_directive: :document, inspection_record: :inspection_type) - @attachable = AirworthinessDirective.where.not(id: @aircraft.applicable_ads.select(:id)).ordered if owner? + @attachable = AirworthinessDirective.where.not(id: @aircraft.applicable_ads.select(:id)).ordered if can?(:manage_ads) @alerts = @aircraft.ad_alerts.pending end diff --git a/app/controllers/api/v1/base_controller.rb b/app/controllers/api/v1/base_controller.rb index 9e191dd..8aa8571 100644 --- a/app/controllers/api/v1/base_controller.rb +++ b/app/controllers/api/v1/base_controller.rb @@ -70,8 +70,12 @@ module Api def find_aircraft(id = params[:aircraft_id]) = aircraft_scope.find(id) - def role_on(aircraft) = acting_user&.role_for(aircraft) - def owner_of?(aircraft) = role_on(aircraft).in?(%w[admin owner]) + # What the person it's acting for can do on the aircraft, as in the app (Role). + def can?(permission, aircraft) = acting_user&.can?(permission, aircraft) || false + + def not_permitted(permission) + render_error(:forbidden, "not_permitted", "This needs the \"#{Permission.label(permission)}\" permission on the aircraft.") + end # ?limit= (1–200, default 50), ?after= to continue, ?updated_since=. def paginate(scope) diff --git a/app/controllers/api/v1/draft_batches_controller.rb b/app/controllers/api/v1/draft_batches_controller.rb index 21ab6e7..f440f2e 100644 --- a/app/controllers/api/v1/draft_batches_controller.rb +++ b/app/controllers/api/v1/draft_batches_controller.rb @@ -27,7 +27,7 @@ module Api # POST /aircraft/:aircraft_id/draft_batches def create @aircraft = find_aircraft - return render_error(:forbidden, "owners_only", "Draft entries are for the aircraft's owners (act for an owner).") unless owner_of?(@aircraft) + return not_permitted(:write_logbook) unless can?(:write_logbook, @aircraft) input = params.require(:draft_batch) items = Array(input[:items]).map { _1.permit(:log, :text, :external_ref, resolves_squawks: []) } @@ -54,7 +54,7 @@ module Api # DELETE /draft_batches/:id: withdraw it while nothing in it is signed. def destroy batch = find_batch - return render_error(:forbidden, "owners_only", "Only the aircraft's owners can withdraw a draft.") unless owner_of?(batch.aircraft) + return not_permitted(:write_logbook) unless can?(:write_logbook, batch.aircraft) unless batch.awaiting? && batch.entries.none?(&:signed?) return render_error(:conflict, "signed", "Part of this draft is signed (or it's no longer awaiting signature); correct it in the app instead.") end diff --git a/app/controllers/api/v1/squawks_controller.rb b/app/controllers/api/v1/squawks_controller.rb index 4270e6c..149c9af 100644 --- a/app/controllers/api/v1/squawks_controller.rb +++ b/app/controllers/api/v1/squawks_controller.rb @@ -31,6 +31,7 @@ module Api # POST /aircraft/:aircraft_id/squawks def create aircraft = find_aircraft + return not_permitted(:report_squawks) unless can?(:report_squawks, aircraft) squawk = aircraft.squawks.new(create_params.merge(reported_by: acting_user, resolved: false)) squawk.component_id = nil unless aircraft.components.exists?(id: squawk.component_id) squawk.save! @@ -39,13 +40,13 @@ module Api end # PATCH /squawks/:id: external_ref by anyone who may write; the rest - # (issue, priority, component, notes) by the aircraft's owners, as in the app. + # (issue, priority, component, notes) with "manage squawks", as in the app. def update squawk = find_squawk return render_error(:unprocessable_entity, "resolved", "A resolved squawk can't be changed.") if squawk.resolved? attrs = params.require(:squawk).permit(:external_ref, :issue_reported, :priority, :component_id, :notes) - if (attrs.keys - %w[external_ref]).any? && !owner_of?(squawk.aircraft) - return render_error(:forbidden, "owners_only", "Only the aircraft's owners can change a squawk's details.") + if (attrs.keys - %w[external_ref]).any? && !can?(:manage_squawks, squawk.aircraft) + return not_permitted(:manage_squawks) end attrs[:component_id] = nil if attrs.key?(:component_id) && !squawk.aircraft.components.exists?(id: attrs[:component_id]) squawk.update!(attrs) diff --git a/app/controllers/components_controller.rb b/app/controllers/components_controller.rb index b09ca6e..21e8922 100644 --- a/app/controllers/components_controller.rb +++ b/app/controllers/components_controller.rb @@ -1,6 +1,6 @@ class ComponentsController < ApplicationController include AircraftScoped - before_action :require_owner!, except: %i[index show] + requires_permission :manage_components, except: %i[index show] before_action :set_component, only: %i[show edit update destroy reset_service] def index diff --git a/app/controllers/concerns/aircraft_scoped.rb b/app/controllers/concerns/aircraft_scoped.rb index 8da841b..00970fc 100644 --- a/app/controllers/concerns/aircraft_scoped.rb +++ b/app/controllers/concerns/aircraft_scoped.rb @@ -1,16 +1,38 @@ -# Scopes a controller to one aircraft the current user can access and exposes -# role helpers. Unknown and inaccessible aircraft both 404 (enumeration-safe). +# Scopes a controller to one aircraft the current user can access, and checks +# what their role there allows (Role, Permission). Unknown and inaccessible +# aircraft both 404 (enumeration-safe). Administrators can do everything. # -# Access matrix (mirrors the original): -# admin – everything -# owner – everything on their aircraft -# pilot – view all; update hours; create squawks, notes, oil/fuel, flight logs +# Each controller says which permission its actions need: +# +# requires_permission :manage_components, except: %i[index show] +# requires_permission :report_squawks, only: %i[new create] +# checks_permission_itself only: %i[edit update] # decided in the controller +# +# Looking needs no permission. A request that changes something (anything but +# GET/HEAD) with no permission declared for its action is refused, so nothing +# is left open by mistake; in development and tests it raises instead. module AircraftScoped extend ActiveSupport::Concern + SELF_CHECKED = "(checked by the controller)".freeze + + class MissingPermission < StandardError; end + included do + class_attribute :permission_rules, instance_accessor: false, default: [] before_action :set_aircraft - helper_method :current_role, :owner?, :can_write? + before_action :authorize_permission! + helper_method :current_role, :can?, :owner? + end + + class_methods do + def requires_permission(permission, only: nil, except: nil) + self.permission_rules += [ [ permission.to_s, only && Array(only).map(&:to_s), except && Array(except).map(&:to_s) ] ] + end + + def checks_permission_itself(only:) + requires_permission(SELF_CHECKED, only: only) + end end private @@ -21,18 +43,34 @@ module AircraftScoped @aircraft = current_user.accessible_aircraft.find(aircraft_param) end + # Their Role here (nil for an administrator without one). def current_role - @current_role ||= current_user.role_for(@aircraft) + return @current_role if defined?(@current_role) + @current_role = current_user.role_for(@aircraft) end - # Owner-level write access (admins included). - def owner? = current_role.in?(%w[admin owner]) - alias_method :can_write?, :owner? + def can?(permission) = current_user.admin? || current_role&.can?(permission) || false - def require_owner! - return if owner? - redirect_back fallback_location: aircraft_path(@aircraft), - alert: t("flash.common.only_owners_can_do") + # The Owner role (or an administrator): everything. + def owner? = current_user.admin? || current_role&.owner? || false + + def authorize_permission! + rules = self.class.permission_rules.select do |_, only, except| + (only.nil? || only.include?(action_name)) && (except.nil? || except.exclude?(action_name)) + end + if rules.empty? + return if request.get? || request.head? + raise MissingPermission, "#{self.class.name}##{action_name} changes data without declaring a permission" if Rails.env.local? + return permission_denied + end + permission_denied unless rules.all? { |permission, *| permission == SELF_CHECKED || can?(permission) } + end + + def permission_denied + respond_to do |format| + format.html { redirect_back fallback_location: aircraft_path(@aircraft), alert: t("flash.common.not_allowed") } + format.any { head :forbidden } + end end # Returns id only if it belongs to the given (aircraft-scoped) relation; else nil. diff --git a/app/controllers/consumable_records_controller.rb b/app/controllers/consumable_records_controller.rb index 96b495a..cf22f09 100644 --- a/app/controllers/consumable_records_controller.rb +++ b/app/controllers/consumable_records_controller.rb @@ -1,6 +1,7 @@ class ConsumableRecordsController < ApplicationController include AircraftScoped - before_action :require_owner!, only: %i[edit update destroy] + requires_permission :record_consumables, only: %i[new create] + requires_permission :manage_consumables, only: %i[edit update destroy] before_action :set_record, only: %i[edit update destroy] RECORDS_PER_PAGE = 50 diff --git a/app/controllers/document_collections_controller.rb b/app/controllers/document_collections_controller.rb index 0db4244..3c2b681 100644 --- a/app/controllers/document_collections_controller.rb +++ b/app/controllers/document_collections_controller.rb @@ -1,6 +1,6 @@ class DocumentCollectionsController < ApplicationController include AircraftScoped - before_action :require_owner! + requires_permission :manage_documents before_action :set_collection, only: %i[edit update destroy] def new diff --git a/app/controllers/documents_controller.rb b/app/controllers/documents_controller.rb index 6d70f8f..eeac08e 100644 --- a/app/controllers/documents_controller.rb +++ b/app/controllers/documents_controller.rb @@ -1,6 +1,6 @@ class DocumentsController < ApplicationController include AircraftScoped - before_action :require_owner!, except: %i[index show] + requires_permission :manage_documents, except: %i[index show] before_action :set_document, only: %i[show edit update destroy] def index diff --git a/app/controllers/entry_signatures_controller.rb b/app/controllers/entry_signatures_controller.rb index b17e594..a623b83 100644 --- a/app/controllers/entry_signatures_controller.rb +++ b/app/controllers/entry_signatures_controller.rb @@ -3,6 +3,7 @@ # who they are again (password, or single sign-on just now), and confirms. class EntrySignaturesController < ApplicationController include AircraftScoped + requires_permission :sign_logbook include EntrySigning before_action :set_entry diff --git a/app/controllers/flight_imports_controller.rb b/app/controllers/flight_imports_controller.rb index 4ff3db9..a3d14f1 100644 --- a/app/controllers/flight_imports_controller.rb +++ b/app/controllers/flight_imports_controller.rb @@ -2,7 +2,7 @@ class FlightImportsController < ApplicationController include AircraftScoped include StoredUpload - before_action :require_owner! + requires_permission :import_flights def new; end diff --git a/app/controllers/flight_logs_controller.rb b/app/controllers/flight_logs_controller.rb index 55a89eb..9311db5 100644 --- a/app/controllers/flight_logs_controller.rb +++ b/app/controllers/flight_logs_controller.rb @@ -1,6 +1,8 @@ class FlightLogsController < ApplicationController include AircraftScoped - before_action :require_owner!, only: :destroy + requires_permission :log_flights, only: %i[new create] + requires_permission :delete_flights, only: :destroy + checks_permission_itself only: %i[edit update attach_engine_data remove_engine_data] before_action :set_flight_log, only: %i[show edit update engine_data_series attach_engine_data remove_engine_data] before_action :require_flight_editor!, only: %i[edit update] helper_method :can_edit_flight? @@ -126,7 +128,10 @@ class FlightLogsController < ApplicationController private - def can_edit_flight?(flight) = flight.editable_by?(current_user, role: current_role) + # Any flight with "correct any flight"; the ones they logged with "correct own flights". + def can_edit_flight?(flight) + can?(:edit_any_flight) || (can?(:edit_own_flights) && flight.user_id.present? && flight.user_id == current_user.id) + end def require_flight_editor! return if can_edit_flight?(@flight_log) diff --git a/app/controllers/inspection_records_controller.rb b/app/controllers/inspection_records_controller.rb index 305cabc..7b16add 100644 --- a/app/controllers/inspection_records_controller.rb +++ b/app/controllers/inspection_records_controller.rb @@ -1,6 +1,6 @@ class InspectionRecordsController < ApplicationController include AircraftScoped - before_action :require_owner! + requires_permission :manage_inspections before_action :set_record, only: %i[edit update destroy] def new diff --git a/app/controllers/inspection_types_controller.rb b/app/controllers/inspection_types_controller.rb index f6c3993..91df92a 100644 --- a/app/controllers/inspection_types_controller.rb +++ b/app/controllers/inspection_types_controller.rb @@ -1,7 +1,7 @@ class InspectionTypesController < ApplicationController include AircraftScoped include Applicability - before_action :require_owner! + requires_permission :manage_inspections before_action :set_type, only: %i[edit update destroy] def new diff --git a/app/controllers/loading_setups_controller.rb b/app/controllers/loading_setups_controller.rb index bbcaf9f..098e425 100644 --- a/app/controllers/loading_setups_controller.rb +++ b/app/controllers/loading_setups_controller.rb @@ -2,7 +2,7 @@ # the loading calculator. class LoadingSetupsController < ApplicationController include AircraftScoped - before_action :require_owner! + requires_permission :manage_weight_balance def edit @setup = @aircraft.loading_setup diff --git a/app/controllers/logbook_entries_controller.rb b/app/controllers/logbook_entries_controller.rb index 1b49bad..b535615 100644 --- a/app/controllers/logbook_entries_controller.rb +++ b/app/controllers/logbook_entries_controller.rb @@ -1,6 +1,6 @@ class LogbookEntriesController < ApplicationController include AircraftScoped - before_action :require_owner!, except: %i[index show] + requires_permission :write_logbook, except: %i[index show] before_action :set_entry, only: %i[show edit update destroy verify] before_action :require_unsigned, only: %i[edit update destroy] diff --git a/app/controllers/logbook_imports_controller.rb b/app/controllers/logbook_imports_controller.rb index f3e359b..568689e 100644 --- a/app/controllers/logbook_imports_controller.rb +++ b/app/controllers/logbook_imports_controller.rb @@ -3,7 +3,7 @@ # entries in the background (LogbookTranscriptionJob). class LogbookImportsController < ApplicationController include AircraftScoped - before_action :require_owner! + requires_permission :import_records def new @collections = @aircraft.document_collections.ordered diff --git a/app/controllers/major_records_controller.rb b/app/controllers/major_records_controller.rb index 3798abb..08092f8 100644 --- a/app/controllers/major_records_controller.rb +++ b/app/controllers/major_records_controller.rb @@ -1,6 +1,6 @@ class MajorRecordsController < ApplicationController include AircraftScoped - before_action :require_owner!, except: %i[index show] + requires_permission :manage_major_records, except: %i[index show] before_action :set_record, only: %i[show edit update destroy] def index diff --git a/app/controllers/notes_controller.rb b/app/controllers/notes_controller.rb index 6279e29..dde7403 100644 --- a/app/controllers/notes_controller.rb +++ b/app/controllers/notes_controller.rb @@ -1,6 +1,7 @@ class NotesController < ApplicationController include AircraftScoped - before_action :require_owner!, only: %i[edit update destroy] + requires_permission :write_notes, only: %i[new create preview] + requires_permission :manage_notes, only: %i[edit update destroy] before_action :set_note, only: %i[edit update destroy] def index diff --git a/app/controllers/oil_analyses_controller.rb b/app/controllers/oil_analyses_controller.rb index b6c9996..bd51dd2 100644 --- a/app/controllers/oil_analyses_controller.rb +++ b/app/controllers/oil_analyses_controller.rb @@ -1,6 +1,7 @@ class OilAnalysesController < ApplicationController include AircraftScoped - before_action :require_owner!, only: %i[edit update destroy] + requires_permission :record_oil_analyses, only: %i[new create import] + requires_permission :manage_oil_analyses, only: %i[edit update destroy] before_action :set_analysis, only: %i[show edit update destroy] COMPARE_SAMPLES = 6 # columns in the trend table, like the lab report's history diff --git a/app/controllers/record_versions_controller.rb b/app/controllers/record_versions_controller.rb index 15ef972..fef714e 100644 --- a/app/controllers/record_versions_controller.rb +++ b/app/controllers/record_versions_controller.rb @@ -1,7 +1,7 @@ # Every change to the aircraft's maintenance records (AC 120-78B 3.2.2). class RecordVersionsController < ApplicationController include AircraftScoped - before_action :require_owner!, only: :restore + requires_permission :restore_history, only: :restore SHARED = { "AirworthinessDirective" => AirworthinessDirective, "InspectionType" => InspectionType }.freeze diff --git a/app/controllers/records_packages_controller.rb b/app/controllers/records_packages_controller.rb index e331ba7..38e9d04 100644 --- a/app/controllers/records_packages_controller.rb +++ b/app/controllers/records_packages_controller.rb @@ -1,7 +1,7 @@ # Download every record of an aircraft in one ZIP (owners). class RecordsPackagesController < ApplicationController include AircraftScoped - before_action :require_owner! + requires_permission :export_data def show package = RecordsPackage.new(@aircraft, source: request.host) diff --git a/app/controllers/share_tokens_controller.rb b/app/controllers/share_tokens_controller.rb index 1cacdb7..a7592a7 100644 --- a/app/controllers/share_tokens_controller.rb +++ b/app/controllers/share_tokens_controller.rb @@ -1,6 +1,6 @@ class ShareTokensController < ApplicationController include AircraftScoped - before_action :require_owner! + requires_permission :manage_sharing def create token = @aircraft.share_tokens.new(params.require(:share_token).permit(:label, :privilege, :expires_at)) diff --git a/app/controllers/signing_invitations_controller.rb b/app/controllers/signing_invitations_controller.rb index af662d5..14d2bad 100644 --- a/app/controllers/signing_invitations_controller.rb +++ b/app/controllers/signing_invitations_controller.rb @@ -1,7 +1,7 @@ # An owner asks someone outside the aircraft (a mechanic) to sign an entry. class SigningInvitationsController < ApplicationController include AircraftScoped - before_action :require_owner! + requires_permission :write_logbook before_action :set_entry rate_limit to: 10, within: 1.hour, only: :create, with: -> { redirect_back fallback_location: root_path, alert: t("flash.signing_invitations.too_many_invitations_try") } diff --git a/app/controllers/squawks_controller.rb b/app/controllers/squawks_controller.rb index 07d2b32..21a83a5 100644 --- a/app/controllers/squawks_controller.rb +++ b/app/controllers/squawks_controller.rb @@ -2,7 +2,9 @@ class SquawksController < ApplicationController include AircraftScoped # Pilots may create squawks and defer inoperative items (91.213(d) lets the # pilot decide); editing and resolving need an owner. - before_action :require_owner!, except: %i[index new create deferral defer] + requires_permission :report_squawks, only: %i[new create] + requires_permission :defer_squawks, only: %i[deferral defer] + requires_permission :manage_squawks, except: %i[index new create deferral defer] before_action :set_squawk, only: %i[edit update destroy resolution resolve reopen deferral defer undefer] def index diff --git a/app/controllers/standard_inspections_controller.rb b/app/controllers/standard_inspections_controller.rb index b784af7..7877655 100644 --- a/app/controllers/standard_inspections_controller.rb +++ b/app/controllers/standard_inspections_controller.rb @@ -1,6 +1,6 @@ class StandardInspectionsController < ApplicationController include AircraftScoped - before_action :require_owner! + requires_permission :manage_inspections def new; end diff --git a/app/controllers/weight_balance_records_controller.rb b/app/controllers/weight_balance_records_controller.rb index 3f19d91..1120ae9 100644 --- a/app/controllers/weight_balance_records_controller.rb +++ b/app/controllers/weight_balance_records_controller.rb @@ -2,7 +2,7 @@ # keep the records and the loading setup). class WeightBalanceRecordsController < ApplicationController include AircraftScoped - before_action :require_owner!, except: :index + requires_permission :manage_weight_balance, except: :index before_action :set_record, only: %i[edit update destroy] def index diff --git a/app/helpers/aircraft_helper.rb b/app/helpers/aircraft_helper.rb index ac68611..3fe3c8b 100644 --- a/app/helpers/aircraft_helper.rb +++ b/app/helpers/aircraft_helper.rb @@ -3,11 +3,14 @@ module AircraftHelper # What the app saves ahead of time for use without signal (see # offline_prep_controller.js): for each of your aircraft, the Overview, W&B, - # Log Flight and Report Squawk pages, and its photo (at both page sizes). + # Log Flight and Report Squawk pages (when their role allows them), and its + # photo (at both page sizes). def offline_pages current_user.accessible_aircraft.ordered.limit(OFFLINE_AIRCRAFT).map do |a| + role = current_user.role_for(a) + can = ->(permission) { current_user.admin? || role&.can?(permission) } { tail: a.tail_number, pages: [ aircraft_path(a), aircraft_weight_balance_records_path(a) ], - flight: new_aircraft_flight_log_path(a), squawk: new_aircraft_squawk_path(a), + flight: (new_aircraft_flight_log_path(a) if can.(:log_flights)), squawk: (new_aircraft_squawk_path(a) if can.(:report_squawks)), pictures: (%i[thumb card].map { url_for(a.picture_for(_1)) }.uniq if a.picture_shown?) }.compact end end diff --git a/app/javascript/controllers/offline_prep_controller.js b/app/javascript/controllers/offline_prep_controller.js index 5c889ba..ecec806 100644 --- a/app/javascript/controllers/offline_prep_controller.js +++ b/app/javascript/controllers/offline_prep_controller.js @@ -29,9 +29,9 @@ export default class extends Controller { const forms = {} const paths = [ "/" ] for (const a of this.aircraftValue) { - paths.push(...a.pages, a.flight, a.squawk) - forms[a.flight] = { tail: a.tail, kind: "flight" } - forms[a.squawk] = { tail: a.tail, kind: "squawk" } + paths.push(...a.pages) + if (a.flight) { paths.push(a.flight); forms[a.flight] = { tail: a.tail, kind: "flight" } } + if (a.squawk) { paths.push(a.squawk); forms[a.squawk] = { tail: a.tail, kind: "squawk" } } } const pictures = this.aircraftValue.flatMap((a) => a.pictures || []) const total = paths.length + 1 diff --git a/app/jobs/overdue_notification_job.rb b/app/jobs/overdue_notification_job.rb index daa07da..85a11fb 100644 --- a/app/jobs/overdue_notification_job.rb +++ b/app/jobs/overdue_notification_job.rb @@ -1,17 +1,17 @@ -# Daily: tells owners about items that have newly become overdue or limit +# Daily: tells those who get its reminders (Role "gets reminders") about items that have newly become overdue or limit # the aircraft (grounded, VFR only…). Each is sent once; one that's fixed and # becomes overdue again is sent again. class OverdueNotificationJob < ApplicationJob queue_as :default def perform - Aircraft.includes(roles: :user).find_each do |aircraft| + Aircraft.includes(roles: %i[user role]).find_each do |aircraft| issues = aircraft.airworthiness.issues.select { _1.severity.in?([ Airworthiness::RED, Airworthiness::LIMITED ]) } keys = issues.map { |i| "#{i.category}:#{i.item.class.name}:#{i.item.id}" } fresh = issues.reject.with_index { |_, n| aircraft.notified_issue_keys.include?(keys[n]) } - owners = aircraft.roles.select { _1.role == "owner" }.map(&:user).reject(&:disabled?) + recipients = aircraft.roles.select { _1.role.can?(:receive_reminders) }.map(&:user).reject(&:disabled?) if fresh.any? - PushNotifier.notify(owners, :overdue, path: Rails.application.routes.url_helpers.aircraft_path(aircraft), tag: "overdue-#{aircraft.id}", + PushNotifier.notify(recipients, :overdue, path: Rails.application.routes.url_helpers.aircraft_path(aircraft), tag: "overdue-#{aircraft.id}", tail: aircraft.tail_number, items: fresh.map(&:title).to_sentence, count: fresh.size) end aircraft.update_column(:notified_issue_keys, keys) if keys.sort != aircraft.notified_issue_keys.sort diff --git a/app/jobs/weekly_reminder_job.rb b/app/jobs/weekly_reminder_job.rb index 1111949..8d302d6 100644 --- a/app/jobs/weekly_reminder_job.rb +++ b/app/jobs/weekly_reminder_job.rb @@ -1,4 +1,4 @@ -# Weekly email to aircraft owners listing what's overdue or coming due +# Weekly email to those who get an aircraft's reminders (Role "gets reminders") listing what's overdue or coming due # (inspections, ADs, components, expiring documents), deferred items, new # ADs, and the user's own certificates that are about to expire. # Nothing is sent when nothing needs attention, or when email isn't set up. diff --git a/app/mailers/reminder_mailer.rb b/app/mailers/reminder_mailer.rb index 0839031..758f882 100644 --- a/app/mailers/reminder_mailer.rb +++ b/app/mailers/reminder_mailer.rb @@ -1,8 +1,13 @@ class ReminderMailer < ApplicationMailer - # [[aircraft, issues, new AD alerts], …] for the aircraft the user owns - # that need attention. + # Aircraft where the user's role includes the permission. + def self.aircraft_where(user, permission) + Aircraft.where(id: AircraftRole.with_permission(permission).where(user_id: user.id).select(:aircraft_id)).ordered + end + + # [[aircraft, issues, new AD alerts], …] for the aircraft the user gets + # reminders for (their role's "gets reminders") that need attention. def self.items_for(user) - Aircraft.joins(:roles).where(aircraft_roles: { user_id: user.id, role: "owner" }).ordered + aircraft_where(user, :receive_reminders) .map { [ _1, _1.airworthiness.issues, _1.ad_alerts.pending.to_a ] }.reject { _2.empty? && _3.empty? } end @@ -10,10 +15,11 @@ class ReminderMailer < ApplicationMailer def self.audit_due_for?(user) = user.admin? && AuditRun.due_soon? - # Owned aircraft whose AD baseline needs a (new) DRS import: none yet, a - # year old, or a model never covered. + # Aircraft they get reminders for and manage the ADs of, whose AD baseline + # needs a (new) DRS import: none yet, a year old, or a model never covered. def self.drs_due_for(user) - Aircraft.joins(:roles).where(aircraft_roles: { user_id: user.id, role: "owner" }).ordered + aircraft_where(user, :receive_reminders) + .where(id: AircraftRole.with_permission(:manage_ads).where(user_id: user.id).select(:aircraft_id)) .select { DrsImport.renewal_due?(_1) || DrsImport.missing_models(_1).any? } end diff --git a/app/models/aircraft_role.rb b/app/models/aircraft_role.rb index eb44113..d3362f8 100644 --- a/app/models/aircraft_role.rb +++ b/app/models/aircraft_role.rb @@ -1,11 +1,21 @@ +# Someone's role on an aircraft (Role), which decides what they can do there. class AircraftRole < ApplicationRecord - ROLES = LabelSet.new("aircraft_role.roles", %w[owner pilot]) - belongs_to :aircraft belongs_to :user + belongs_to :role - validates :role, inclusion: { in: ROLES.keys } validates :user_id, uniqueness: { scope: :aircraft_id, message: "already has a role on this aircraft" } - scope :owners, -> { where(role: "owner") } + scope :owners, -> { joins(:role).where(roles: { key: "owner" }) } + # Whose role includes a permission (Owner always does). + scope :with_permission, ->(permission) { + joins(:role).where("roles.key = 'owner' OR EXISTS (SELECT 1 FROM json_each(roles.permissions) WHERE json_each.value = ?)", permission.to_s) + } + + # A Role, or a built-in role's key ("owner", "pilot"). + def role=(value) + super(value.is_a?(Role) || value.nil? ? value : Role.for_key(value)) + end + + def owner? = role&.owner? end diff --git a/app/models/flight_log.rb b/app/models/flight_log.rb index 8162f76..609ee88 100644 --- a/app/models/flight_log.rb +++ b/app/models/flight_log.rb @@ -36,11 +36,6 @@ class FlightLog < ApplicationRecord aircraft.flight_logs.maximum(:id) == id && (tach_in.nil? || tach_in == aircraft.tach_time) end - # Owners can correct any flight; a pilot, the flights they logged. - def editable_by?(user, role:) - role.in?(%w[admin owner]) || (user_id.present? && user_id == user.id) - end - private # Reject files the engine data parser can't read, before they're stored. diff --git a/app/models/permission.rb b/app/models/permission.rb new file mode 100644 index 0000000..03c9363 --- /dev/null +++ b/app/models/permission.rb @@ -0,0 +1,34 @@ +# What a role on an aircraft can do (Role#permissions). Grouped the way the +# app is laid out; labels and descriptions are in config/locales +# (permissions..label / .description). Seeing an aircraft's records +# needs no permission: every role can view everything on its aircraft. +module Permission + GROUPS = { + flying: %w[log_flights update_hours import_flights edit_own_flights edit_any_flight delete_flights], + squawks_and_notes: %w[report_squawks defer_squawks manage_squawks write_notes manage_notes record_consumables manage_consumables], + maintenance: %w[write_logbook sign_logbook manage_components manage_inspections manage_ads manage_major_records + manage_weight_balance manage_documents record_oil_analyses manage_oil_analyses], + data: %w[import_records export_data restore_history], + aircraft: %w[edit_aircraft delete_aircraft manage_people manage_sharing], + notifications: %w[receive_reminders] + }.freeze + + ALL = GROUPS.values.flatten.freeze + + # The built-in roles' permissions when first created (admins can change all + # but Owner's, which always has every permission). Pilot is what pilots + # could do before roles were configurable. + DEFAULTS = { + "pilot" => %w[log_flights update_hours edit_own_flights report_squawks defer_squawks write_notes record_consumables + record_oil_analyses sign_logbook], + "mechanic" => %w[update_hours report_squawks defer_squawks manage_squawks write_notes manage_notes record_consumables + manage_consumables write_logbook sign_logbook manage_components manage_inspections manage_ads + manage_major_records manage_weight_balance manage_documents record_oil_analyses manage_oil_analyses + receive_reminders], + "viewer" => [] + }.freeze + + def self.label(key) = I18n.t("permissions.#{key}.label") + def self.description(key) = I18n.t("permissions.#{key}.description") + def self.group_label(group) = I18n.t("permissions.groups.#{group}") +end diff --git a/app/models/role.rb b/app/models/role.rb new file mode 100644 index 0000000..bd9cfbd --- /dev/null +++ b/app/models/role.rb @@ -0,0 +1,40 @@ +# A role someone can have on an aircraft: a name and a set of permissions +# (Permission). Installation-wide; administrators manage them (Admin → Roles). +# Four are built in (key set): Owner, which always has every permission so an +# aircraft can always be managed, and Mechanic, Pilot and Viewer, whose +# permissions can be changed. Administrators can add their own. +class Role < ApplicationRecord + BUILT_IN = %w[owner mechanic pilot viewer].freeze + + has_many :aircraft_roles, dependent: :restrict_with_error + + normalizes :name, with: ->(name) { name.squish } + validates :name, presence: true, uniqueness: { case_sensitive: false }, length: { maximum: 40 } + validates :description, length: { maximum: 200 } + validates :key, inclusion: { in: BUILT_IN }, uniqueness: true, allow_nil: true + before_validation { self.permissions = Array(permissions).map(&:to_s) & Permission::ALL } + before_destroy { throw :abort if built_in? } + + scope :ordered, -> { order(Arel.sql("CASE WHEN key IS NULL THEN 1 ELSE 0 END"), :position, :name) } + + # The built-in roles, created when first needed (a new installation, tests). + def self.ensure_built_in! + BUILT_IN.each_with_index do |key, i| + find_or_create_by!(key: key) do |role| + role.name = I18n.t("roles.#{key}.name") + role.description = I18n.t("roles.#{key}.description") + role.permissions = Permission::DEFAULTS.fetch(key, []) + role.position = i + end + end + end + + def self.for_key(key) = find_by(key: key.to_s) || (ensure_built_in! && find_by!(key: key.to_s)) + def self.owner = for_key("owner") + + def built_in? = key.present? + def owner? = key == "owner" + + def permissions = owner? ? Permission::ALL : super + def can?(permission) = permissions.include?(permission.to_s) +end diff --git a/app/models/user.rb b/app/models/user.rb index 184a3a9..2fe5e38 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -114,10 +114,14 @@ class User < ApplicationRecord admin? ? Aircraft.all : aircraft end - # 'admin' | 'owner' | 'pilot' | nil + # Their Role on the aircraft (nil for none; administrators may have none). def role_for(aircraft) - return "admin" if admin? - aircraft_roles.find_by(aircraft: aircraft)&.role + aircraft_roles.includes(:role).find_by(aircraft: aircraft)&.role + end + + # Administrators can do everything on every aircraft. + def can?(permission, aircraft) + admin? || role_for(aircraft)&.can?(permission) || false end def display_name diff --git a/app/services/aircraft_access.rb b/app/services/aircraft_access.rb new file mode 100644 index 0000000..3ecefa9 --- /dev/null +++ b/app/services/aircraft_access.rb @@ -0,0 +1,52 @@ +# Giving, changing and taking away people's roles on an aircraft, by someone +# allowed to (the aircraft's "manage people", or an administrator). The rules, +# the same from the aircraft's Access page and Admin → Users: +# - only an Owner or an administrator can give or take away the Owner role +# (otherwise anyone who manages people could make themselves Owner); +# - only an administrator can change or remove their own role; +# - an aircraft always keeps at least one Owner. +# Each method returns nil when done, or a message saying why not. +class AircraftAccess + def initialize(aircraft, actor:) + @aircraft = aircraft + @actor = actor + end + + def add(user, role) + return t("not_found") unless user && role + return t("owner_only") if role.owner? && !actor_owner? + membership = @aircraft.roles.new(user: user, role: role) + return membership.errors.full_messages.to_sentence unless membership.save + @aircraft.log_event!("role", I18n.t("flash.aircraft_roles.added_as", display_name: user.display_name, role: role.name), user: @actor) + nil + end + + def change(membership, role) + return t("not_found") unless role + return if membership.role == role + return t("own_role") if membership.user == @actor && !@actor.admin? + return t("owner_only") if (role.owner? || membership.owner?) && !actor_owner? + return t("last_owner") if membership.owner? && !role.owner? && last_owner? + membership.update!(role: role) + @aircraft.log_event!("role", I18n.t("flash.aircraft_roles.changed_to", display_name: membership.user.display_name, role: role.name), user: @actor) + nil + end + + def remove(membership) + return t("own_role") if membership.user == @actor && !@actor.admin? + return t("owner_only") if membership.owner? && !actor_owner? + return t("last_owner") if membership.owner? && last_owner? + membership.destroy! + @aircraft.log_event!("role", I18n.t("flash.aircraft_roles.removed", display_name: membership.user.display_name), user: @actor) + nil + end + + # The roles this person can hand out here (Owner only by an Owner). + def assignable_roles = Role.ordered.select { |role| !role.owner? || actor_owner? } + + private + + def actor_owner? = @actor.admin? || @actor.role_for(@aircraft)&.owner? + def last_owner? = @aircraft.roles.owners.count <= 1 + def t(key) = I18n.t("services.aircraft_access.#{key}") +end diff --git a/app/services/aircraft_archive/importer.rb b/app/services/aircraft_archive/importer.rb index d9f2444..7c3fc70 100644 --- a/app/services/aircraft_archive/importer.rb +++ b/app/services/aircraft_archive/importer.rb @@ -149,7 +149,7 @@ module AircraftArchive import_notes import_oil_analyses import_flight_logs - @aircraft.roles.find_or_create_by!(user: @owner, role: "owner") if @owner + @aircraft.roles.find_or_create_by!(user: @owner) { _1.role = Role.owner } if @owner @aircraft.log_event!("aircraft", "Aircraft imported from a .sam.zip archive", notes: [ @manifest["source_instance"].presence && "Source: #{@manifest['source_instance']}", summary ].compact.join(". "), user: @owner) diff --git a/app/services/records_audit.rb b/app/services/records_audit.rb index d60a3f4..6ba957c 100644 --- a/app/services/records_audit.rb +++ b/app/services/records_audit.rb @@ -44,7 +44,7 @@ class RecordsAudit (signed + pool.where.not(id: signed.map(&:id)).order(Arel.sql("RANDOM()")).limit(@policy.audit_sample_size - signed.size).to_a).first(@policy.audit_sample_size) end - def users = User.order(:email_address).includes(:certificates, aircraft_roles: :aircraft) + def users = User.order(:email_address).includes(:certificates, aircraft_roles: %i[aircraft role]) # Saves the audit from the auditor's answers: { key => { "passed" => "1", "note" => … } }. def record!(user:, answers:, notes:, sample_ids:) diff --git a/app/views/admin/audits/new.html.erb b/app/views/admin/audits/new.html.erb index 1876374..9924807 100644 --- a/app/views/admin/audits/new.html.erb +++ b/app/views/admin/audits/new.html.erb @@ -32,7 +32,7 @@ <% elsif key == "users" %>
    - <% @audit.users.each do |u| %>
  • <%= t(".last_sign_in_html", display_name: u.display_name, email_address: u.email_address, admin: (t(".admin") if u.admin?), any: (" · #{u.aircraft_roles.map { "#{AircraftRole::ROLES[_1.role]} #{_1.aircraft.tail_number}" }.join(', ')}" if u.aircraft_roles.any?), never: (u.last_signed_in_at ? t(".ago", time: time_ago_in_words(u.last_signed_in_at)) : t(".never")), disabled: (t(".disabled") if u.disabled?)) %>
  • <% end %> + <% @audit.users.each do |u| %>
  • <%= t(".last_sign_in_html", display_name: u.display_name, email_address: u.email_address, admin: (t(".admin") if u.admin?), any: (" · #{u.aircraft_roles.map { "#{_1.role.name} #{_1.aircraft.tail_number}" }.join(', ')}" if u.aircraft_roles.any?), never: (u.last_signed_in_at ? t(".ago", time: time_ago_in_words(u.last_signed_in_at)) : t(".never")), disabled: (t(".disabled") if u.disabled?)) %>
  • <% end %>
<% end %> <%= text_field_tag "answers[#{key}][note]", nil, class: "input", placeholder: t(".note_what_was_checked_or") %> diff --git a/app/views/admin/procedures/_document.html.erb b/app/views/admin/procedures/_document.html.erb index a246d9c..bc4bdc5 100644 --- a/app/views/admin/procedures/_document.html.erb +++ b/app/views/admin/procedures/_document.html.erb @@ -2,7 +2,7 @@ Locals: policy, number, adopted_at, adopted_by, revisions, summary. %> <% info = SystemInfo.new %> <% aircraft = Aircraft.ordered.includes(:roles) %> -<% users = User.order(:email_address).includes(:certificates, aircraft_roles: :aircraft) %> +<% users = User.order(:email_address).includes(:certificates, aircraft_roles: %i[aircraft role]) %> <% h2 = "mt-6 text-base font-semibold" %> <% p_ = "mt-1 text-sm leading-relaxed" %>
@@ -50,7 +50,7 @@ <% users.each do |u| %> <% current = u.certificates.reject(&:expired?) %> <%= u.display_name %>
<%= u.email_address %>
- <%= [ (t(".administrator") if u.admin?), *u.aircraft_roles.map { "#{_1.role.capitalize}, #{_1.aircraft.tail_number}" } ].compact.join("; ").presence || "—" %><%= t(".disabled") if u.disabled? %> + <%= [ (t(".administrator") if u.admin?), *u.aircraft_roles.map { "#{_1.role.name}, #{_1.aircraft.tail_number}" } ].compact.join("; ").presence || "—" %><%= t(".disabled") if u.disabled? %> <%= u.certificates.map { "#{_1.short_label} #{_1.number}#{" #{t('.expires_short', date: _1.expires_on)}" if _1.expires_on}" }.join("; ").presence || "—" %> <%= if u.disabled? || current.empty? then t(".no") elsif current.any?(&:mechanic?) then t(".maintenance_and_inspection_entries") diff --git a/app/views/admin/roles/_form.html.erb b/app/views/admin/roles/_form.html.erb new file mode 100644 index 0000000..0abc5de --- /dev/null +++ b/app/views/admin/roles/_form.html.erb @@ -0,0 +1,27 @@ +<%# A role's name, description and permissions, grouped as in Permission. + Owner's permissions are shown but can't be changed: it always has all. %> +<%= form_with model: [:admin, role], class: "card card-body max-w-3xl space-y-5" do |f| %> + <%= f.errors_summary %> +
+ <%= f.field :name, required: true %> + <%= f.field :description, hint: t(".description_hint") %> +
+ <% if role.owner? %>

<%= t(".owner_has_everything") %>

<% end %> + <%= hidden_field_tag "role[permissions][]", "", id: nil %> +
+ <% Permission::GROUPS.each do |group, keys| %> +
> + <%= Permission.group_label(group) %> + <% keys.each do |key| %> + + <% end %> +
+ <% end %> +
+

<%= t(".viewing_needs_nothing") %>

+
<%= f.submit t(".save") %><%= link_to t(".cancel"), admin_roles_path, class: "btn-secondary" %>
+<% end %> +<% if role.persisted? && !role.built_in? %>
<%= delete_button t(".delete_role"), admin_role_path(role), confirm: t(".delete_role_confirm", name: role.name) %>
<% end %> diff --git a/app/views/admin/roles/edit.html.erb b/app/views/admin/roles/edit.html.erb new file mode 100644 index 0000000..74c8d03 --- /dev/null +++ b/app/views/admin/roles/edit.html.erb @@ -0,0 +1,3 @@ +<% content_for :title, t(".edit_role", name: @role.name_was) %> +

<%= t(".edit_role", name: @role.name_was) %>

+<%= render "form", role: @role %> diff --git a/app/views/admin/roles/index.html.erb b/app/views/admin/roles/index.html.erb new file mode 100644 index 0000000..976d24f --- /dev/null +++ b/app/views/admin/roles/index.html.erb @@ -0,0 +1,15 @@ +<% content_for :title, t(".roles") %> +

<%= t(".roles") %>

<%= link_to t(".new_role"), new_admin_role_path, class: "btn-primary" %>
+

<%= t(".intro") %>

+
+ + <% @roles.each do |role| %> + + + + + <% end %> +
<%= t(".name") %><%= t(".can") %><%= t(".people") %>
<%= role.name %> <% if role.built_in? %><%= t(".built_in") %><% end %> + <% if role.description.present? %>
<%= role.description %>
<% end %>
"> + <%= role.owner? ? t(".everything") : (role.permissions.map { Permission.label(_1) }.to_sentence.presence || t(".view_only")) %> + "><%= @counts.fetch(role.id, 0) %><%= link_to t(".edit"), edit_admin_role_path(role), class: "btn-secondary btn-sm" %>
diff --git a/app/views/admin/roles/new.html.erb b/app/views/admin/roles/new.html.erb new file mode 100644 index 0000000..a184fd6 --- /dev/null +++ b/app/views/admin/roles/new.html.erb @@ -0,0 +1,3 @@ +<% content_for :title, t(".new_role") %> +

<%= t(".new_role") %>

+<%= render "form", role: @role %> diff --git a/app/views/admin/users/edit.html.erb b/app/views/admin/users/edit.html.erb index f9a7d8c..16f4bf3 100644 --- a/app/views/admin/users/edit.html.erb +++ b/app/views/admin/users/edit.html.erb @@ -1,2 +1,35 @@

<%= t(".edit_user") %>

<%= render "form", user: @user %> + +<%# Their role on each aircraft (same rules as each aircraft's Access page, AircraftAccess). %> +
+

<%= t(".aircraft_access") %>

+ <% roles = Role.ordered.to_a %> + <% memberships = @user.aircraft_roles.includes(:aircraft, :role).sort_by { _1.aircraft.tail_number } %> + <% if memberships.any? %> + + + <% memberships.each do |m| %> + + + + + + <% end %> + +
<%= link_to m.aircraft.tail_number, aircraft_path(m.aircraft), class: "link font-medium" %> <%= [ m.aircraft.make, m.aircraft.model ].compact_blank.join(" ") %><%= form_with url: admin_user_aircraft_role_path(@user, m), method: :patch do |f| %> + <%= f.select :role_id, roles.map { [ _1.name, _1.id ] }, { selected: m.role_id }, class: "input w-36", "aria-label": t(".role_on", tail_number: m.aircraft.tail_number), data: { submit_on_change: true } %> + <% end %><%= delete_button t(".remove"), admin_user_aircraft_role_path(@user, m), confirm: t(".remove_access", tail_number: m.aircraft.tail_number) %>
+ <% else %> + <%= empty_state t(".no_aircraft") %> + <% end %> + <% others = Aircraft.where.not(id: memberships.map(&:aircraft_id)).ordered %> + <% if others.any? %> + <%= form_with url: admin_user_aircraft_roles_path(@user), class: "flex flex-wrap items-end gap-2 border-t border-slate-100 p-4" do |f| %> +
<%= f.label :aircraft_id, t(".aircraft"), class: "label" %><%= f.select :aircraft_id, others.map { [ _1.tail_number, _1.id ] }, {}, class: "input" %>
+
<%= f.label :role_id, t(".role"), class: "label" %><%= f.select :role_id, roles.map { [ _1.name, _1.id ] }, { selected: Role.for_key("pilot").id }, class: "input w-36" %>
+ <%= f.submit t(".add"), class: "btn-primary" %> + <% end %> + <% end %> +

<%= t(".roles_hint_html", link: link_to(t(".roles"), admin_roles_path, class: "link")) %>

+
diff --git a/app/views/admin/users/index.html.erb b/app/views/admin/users/index.html.erb index 8db02ea..d094fb3 100644 --- a/app/views/admin/users/index.html.erb +++ b/app/views/admin/users/index.html.erb @@ -5,7 +5,7 @@ <% @users.each do |u| %> <%= u.name %> <% if u.admin? %><%= t(".admin") %><% end %><% if u.sso_uid? %> <%= Sso.label %><% end %><% if u.otp_enabled? %> "><%= t(".n2fa") %><% end %><% if u.locked? %> "><%= t(".locked") %><% end %> <%= u.email_address %><% if u.certificates.any? %>
<%= u.certificates.map { "#{_1.short_label} #{_1.number}" }.join(", ") %>
<% end %> - <%= u.aircraft_roles.map { "#{_1.aircraft.tail_number} (#{_1.role})" }.join(", ").presence || "—" %> + <%= u.aircraft_roles.map { "#{_1.aircraft.tail_number} (#{_1.role.name})" }.join(", ").presence || "—" %> <%= u.last_signed_in_at ? "#{time_ago_in_words(u.last_signed_in_at)} ago" : "never" %> <% if u.disabled? %><%= t(".disabled") %><%= button_to t(".enable"), enable_admin_user_path(u), method: :patch, class: "btn-secondary btn-sm", form: { class: "inline" } %> diff --git a/app/views/aircraft/show.html.erb b/app/views/aircraft/show.html.erb index f7bd00e..27f6061 100644 --- a/app/views/aircraft/show.html.erb +++ b/app/views/aircraft/show.html.erb @@ -4,7 +4,7 @@
- <% if owner? %><%= render "aircraft/setup", aircraft: @aircraft %><% end %> + <% if can?(:edit_aircraft) %><%= render "aircraft/setup", aircraft: @aircraft %><% end %>

<%= t(".airworthiness") %>

@@ -58,6 +58,7 @@
+ <% if can?(:update_hours) %>

<%= t(".update_hours") %>

<%= form_with url: hours_aircraft_path(@aircraft), method: :patch, class: "card-body space-y-3", @@ -69,17 +70,18 @@
<%= f.label :hobbs_time, t(".hobbs"), class: "label" %> <%= f.number_field :hobbs_time, value: @aircraft.hobbs_time, step: 0.1, class: "input", data: { hours_confirm_target: "hobbs" } %>
-

<%= t(".enter_the_current_meter_readings_html", link: (link_to t(".log_flight"), new_aircraft_flight_log_path(@aircraft), class: "link")) %>

+

<%= can?(:log_flights) ? t(".enter_the_current_meter_readings_html", link: (link_to t(".log_flight"), new_aircraft_flight_log_path(@aircraft), class: "link")) : t(".enter_the_current_meter_readings") %>

<%= f.submit t(".update_hours"), class: "btn-primary" %> <% end %>
+ <% end %> <%= render "aircraft/last_flight", aircraft: @aircraft, last_day: @last_day %>

<%= t(".details") %>

- <% if owner? %><%= link_to t(".edit"), edit_aircraft_path(@aircraft), class: "btn-secondary btn-sm" %><% end %> + <% if can?(:edit_aircraft) %><%= link_to t(".edit"), edit_aircraft_path(@aircraft), class: "btn-secondary btn-sm" %><% end %>
<%= t(".serial") %>
<%= @aircraft.serial_number.presence || "—" %>
@@ -94,7 +96,7 @@

<%= t(".notes") %>

- <%= link_to t(".add"), new_aircraft_note_path(@aircraft), class: "btn-secondary btn-sm" %>
+ <% if can?(:write_notes) %><%= link_to t(".add"), new_aircraft_note_path(@aircraft), class: "btn-secondary btn-sm" %><% end %>
<% if @notes.any? %>
    <% @notes.each do |note| %> diff --git a/app/views/aircraft_roles/index.html.erb b/app/views/aircraft_roles/index.html.erb index bf5bf54..3268c13 100644 --- a/app/views/aircraft_roles/index.html.erb +++ b/app/views/aircraft_roles/index.html.erb @@ -2,31 +2,45 @@ <%= render "shared/aircraft_header", aircraft: @aircraft %>

    <%= t(".access_sharing_html") %>

    + <% if can?(:manage_people) %>

    <%= t(".people") %>

    + <% roles = @access.assignable_roles %> <% @roles.each do |r| %> - + <% end %>
    <%= r.user.display_name %>
    <%= r.user.email_address %>
    - <%= form_with url: aircraft_aircraft_role_path(@aircraft, r), method: :patch do |f| %> - <%= f.select :role, AircraftRole::ROLES.invert, { selected: r.role }, class: "input w-28", data: { submit_on_change: true } %> + <% if roles.include?(r.role) && (r.user != current_user || current_user.admin?) %> + <%= form_with url: aircraft_aircraft_role_path(@aircraft, r), method: :patch do |f| %> + <%= f.select :role_id, roles.map { [ _1.name, _1.id ] }, { selected: r.role_id }, class: "input w-36", "aria-label": t(".role_for", display_name: r.user.display_name), data: { submit_on_change: true } %> + <% end %> + <% else %> + <%= r.role.name %> <% end %> <% unless r.user == current_user %><%= delete_button t(".remove"), aircraft_aircraft_role_path(@aircraft, r), confirm: t(".remove_s_access", display_name: r.user.display_name) %><% end %><% if r.user != current_user && roles.include?(r.role) %><%= delete_button t(".remove"), aircraft_aircraft_role_path(@aircraft, r), confirm: t(".remove_s_access", display_name: r.user.display_name) %><% end %>
    <%= form_with url: aircraft_aircraft_roles_path(@aircraft), class: "flex flex-wrap items-end gap-2 border-t border-slate-100 p-4" do |f| %> -
    <%= f.label :email_address, t(".add_by_email"), class: "label" %><%= f.email_field :email_address, class: "input", required: true %>
    - <%= f.select :role, AircraftRole::ROLES.invert, { selected: "pilot" }, class: "input w-28" %> +
    <%= f.label :email_address, t(".add_by_email"), class: "label" %><%= f.email_field :email_address, class: "input", required: true %>
    + <%= f.select :role_id, roles.map { [ _1.name, _1.id ] }, { selected: Role.for_key("pilot").id }, class: "input w-36", "aria-label": t(".role") %> <%= f.submit t(".add"), class: "btn-primary" %> <% end %> -

    <%= t(".owners_can_edit_everything_pilots_html") %>

    +
    + <%= t(".what_each_role_can_do") %> +
    + <% Role.ordered.each do |role| %>
    <%= role.name %>:
    <%= role.description.presence || role.permissions.map { Permission.label(_1) }.to_sentence %>
    <% end %> +
    +

    <%= t(".roles_are_set_by_an_administrator") %>

    +
    + <% end %> + <% if can?(:manage_sharing) %>

    <%= t(".share_links") %>

    <% if @share_tokens.any? %> @@ -59,7 +73,9 @@ <%= f.submit t(".create_share_link") %> <% end %>
    + <% end %> + <% if can?(:export_data) %>
    @@ -76,4 +92,5 @@ <%= link_to t(".download_records_package"), aircraft_records_package_path(@aircraft), class: "btn-secondary", data: { turbo: false } %>
    + <% end %>
    diff --git a/app/views/airworthiness_directives/index.html.erb b/app/views/airworthiness_directives/index.html.erb index 7148564..3f59782 100644 --- a/app/views/airworthiness_directives/index.html.erb +++ b/app/views/airworthiness_directives/index.html.erb @@ -3,7 +3,7 @@

    <%= t(".airworthiness_directives_bulletins") %>

    - <% if owner? %> + <% if can?(:manage_ads) %>
    <% if @attachable.any? %> <%= form_with url: attach_aircraft_airworthiness_directives_path(@aircraft), class: "flex gap-2" do |f| %> @@ -34,7 +34,7 @@ <%= [row.next_due_date && l(row.next_due_date, format: :month_year), row.next_due_hours && t(".due_hours", hours: hours(row.next_due_hours), meter: Aircraft::TIME_BASES[@aircraft.time_basis].downcase, left: hours(row.next_due_hours - @aircraft.current_hours))].compact.join(" / ").presence || "—" %> <%= compliance_badge(row.status) %> - <% if owner? %> + <% if can?(:manage_ads) %> <%= link_to t(".comply"), new_aircraft_ad_compliance_path(@aircraft, ad_id: ad.id), class: "btn-secondary btn-sm" %> <% if row.status.in?(%w[no_compliance overdue due_soon conditional]) %><%= link_to "N/A", new_aircraft_ad_compliance_path(@aircraft, ad_id: ad.id, not_applicable: 1), class: "btn-secondary btn-sm", title: t(".record_that_this_ad_doesn") %><% end %> <%= link_to t(".edit"), edit_aircraft_airworthiness_directive_path(@aircraft, ad), class: "btn-secondary btn-sm" %> @@ -58,7 +58,7 @@

    <%= t(".ad_baseline_from_faa_drs") %>

    <%= t(".the_full_list_comes_from") %>

    - <% if owner? %><%= link_to t(".import_from_faa_drs"), new_aircraft_ad_import_path(@aircraft), class: "btn-secondary btn-sm" %><% end %> + <% if can?(:manage_ads) %><%= link_to t(".import_from_faa_drs"), new_aircraft_ad_import_path(@aircraft), class: "btn-secondary btn-sm" %><% end %>
    <% if last_drs %> @@ -77,7 +77,7 @@

    <%= t(".newly_published_ads_that_may") %>

    <%= t(".searched_weekly_in_the_federal_html", components: (AdWatch.new(@aircraft).terms.map(&:label).uniq.to_sentence.presence || t(".the_aircraft_and_its_installed")), ad_watch_checked_at: (t(".last_checked_ago", ad_watch_checked_at: (time_ago_in_words(@aircraft.ad_watch_checked_at))) if @aircraft.ad_watch_checked_at)) %>

    - <% if owner? %><%= button_to t(".check_now"), check_aircraft_ad_alerts_path(@aircraft), class: "btn-secondary btn-sm", data: { turbo_submits_with: t(".checking") } %><% end %> + <% if can?(:manage_ads) %><%= button_to t(".check_now"), check_aircraft_ad_alerts_path(@aircraft), class: "btn-secondary btn-sm", data: { turbo_submits_with: t(".checking") } %><% end %>
<% if @alerts.any? %>
    @@ -89,7 +89,7 @@

    <%= alert.abstract.to_s.truncate(400) %>

    <%= link_to t(".read_it_in_the_federal"), alert.html_url, class: "link text-xs", target: "_blank", rel: "noopener" %> - <% if owner? %> + <% if can?(:manage_ads) %>
    <%= button_to t(".track"), track_aircraft_ad_alert_path(@aircraft, alert), class: "btn-primary btn-sm", title: t(".add_it_to_this_aircraft") %> <%= button_to t(".dismiss"), dismiss_aircraft_ad_alert_path(@aircraft, alert), class: "btn-secondary btn-sm", title: t(".doesn_t_apply") %> @@ -101,7 +101,7 @@ <% else %> <%= empty_state t(".nothing_new_to_review") %> <% end %> - <% if owner? %> + <% if can?(:manage_ads) %> <%= form_with url: terms_aircraft_ad_alerts_path(@aircraft), method: :patch, class: "flex flex-wrap items-end gap-2 border-t border-slate-100 px-4 py-3" do %>
    <%= label_tag :ad_watch_terms, t(".additional_search_terms"), class: "label" %> @@ -140,7 +140,7 @@
    <% end %> - <% if owner? %><%= link_to t(".edit"), edit_aircraft_ad_compliance_path(@aircraft, c), class: "btn-secondary btn-sm" %><% end %> + <% if can?(:manage_ads) %><%= link_to t(".edit"), edit_aircraft_ad_compliance_path(@aircraft, c), class: "btn-secondary btn-sm" %><% end %> <% end %> diff --git a/app/views/components/index.html.erb b/app/views/components/index.html.erb index 1608d26..ebb4841 100644 --- a/app/views/components/index.html.erb +++ b/app/views/components/index.html.erb @@ -6,7 +6,7 @@
    <%= link_to (@show_disposed ? t(".hide_disposed") : t(".show_disposed")), aircraft_components_path(@aircraft, disposed: (@show_disposed ? nil : 1)), class: "link text-sm" %> - <% if owner? %><%= link_to t(".add_component"), new_aircraft_component_path(@aircraft), class: "btn-primary" %><% end %> + <% if can?(:manage_components) %><%= link_to t(".add_component"), new_aircraft_component_path(@aircraft), class: "btn-primary" %><% end %>
    <% if @rows.empty? %> @@ -39,7 +39,7 @@ <%= life_badge(c.life_status) %> - <% if owner? %> + <% if can?(:manage_components) %> <%= link_to t(".edit"), edit_aircraft_component_path(@aircraft, c), class: "btn-secondary btn-sm" %> <%= link_to t(".service"), aircraft_component_path(@aircraft, c, anchor: "service"), class: "btn-secondary btn-sm" %> <% end %> diff --git a/app/views/components/show.html.erb b/app/views/components/show.html.erb index a927753..29344d9 100644 --- a/app/views/components/show.html.erb +++ b/app/views/components/show.html.erb @@ -4,7 +4,7 @@

    <%= @component %> <%= life_badge(@component.life_status) %>

    - <% if owner? %> + <% if can?(:manage_components) %>
    <%= link_to t(".sub_component"), new_aircraft_component_path(@aircraft, parent_id: @component.id), class: "btn-secondary btn-sm" %> <%= link_to t(".edit"), edit_aircraft_component_path(@aircraft, @component), class: "btn-secondary btn-sm" %> @@ -37,7 +37,7 @@ <% if @component.notes.present? %>
    <%= simple_format @component.notes %>
    <% end %>
    - <% if owner? %> + <% if can?(:manage_components) %>

    <%= t(".service_replace") %>

    <%= form_with url: reset_service_aircraft_component_path(@aircraft, @component), method: :post, class: "card-body space-y-3", @@ -53,11 +53,11 @@ <% end %> -<% if @inspection_rows.any? || owner? %> +<% if @inspection_rows.any? || can?(:manage_inspections) %>

    <%= t(".inspections_of_this_component") %>

    - <% if owner? %><%= link_to t(".inspection"), new_aircraft_inspection_type_path(@aircraft, component_id: @component.id), class: "btn-secondary btn-sm" %><% end %> + <% if can?(:manage_inspections) %><%= link_to t(".inspection"), new_aircraft_inspection_type_path(@aircraft, component_id: @component.id), class: "btn-secondary btn-sm" %><% end %>
    <% if @inspection_rows.any? %> diff --git a/app/views/consumable_records/_records.html.erb b/app/views/consumable_records/_records.html.erb index a0a8c69..166dadd 100644 --- a/app/views/consumable_records/_records.html.erb +++ b/app/views/consumable_records/_records.html.erb @@ -20,7 +20,7 @@ - + <% end %> diff --git a/app/views/consumable_records/index.html.erb b/app/views/consumable_records/index.html.erb index 5d71f44..6249abe 100644 --- a/app/views/consumable_records/index.html.erb +++ b/app/views/consumable_records/index.html.erb @@ -6,7 +6,7 @@

    <%= stats.oil? ? t(".oil_consumption") : t(".fuel_burn") %>

    - <%= link_to t(stats.oil? ? ".add_oil" : ".add_fuel"), new_aircraft_consumable_record_path(@aircraft, type: stats.record_type), class: "btn-secondary btn-sm" %> + <% if can?(:record_consumables) %><%= link_to t(stats.oil? ? ".add_oil" : ".add_fuel"), new_aircraft_consumable_record_path(@aircraft, type: stats.record_type), class: "btn-secondary btn-sm" %><% end %>
    diff --git a/app/views/documents/_doc_row.html.erb b/app/views/documents/_doc_row.html.erb index 8655c49..f3056a5 100644 --- a/app/views/documents/_doc_row.html.erb +++ b/app/views/documents/_doc_row.html.erb @@ -8,6 +8,6 @@
    <%= visibility_badge(doc.effective_visibility) %> - <% if owner? %><%= link_to t(".edit"), edit_aircraft_document_path(aircraft, doc), class: "btn-secondary btn-sm" %><% end %> + <% if can?(:manage_documents) %><%= link_to t(".edit"), edit_aircraft_document_path(aircraft, doc), class: "btn-secondary btn-sm" %><% end %>
    diff --git a/app/views/documents/index.html.erb b/app/views/documents/index.html.erb index 37c99f0..23fe111 100644 --- a/app/views/documents/index.html.erb +++ b/app/views/documents/index.html.erb @@ -1,7 +1,7 @@ <% content_for :title, t(".documents", tail_number: @aircraft.tail_number) %> <%= render "shared/aircraft_header", aircraft: @aircraft %>
    - <% if owner? %> + <% if can?(:manage_documents) %> <%= more_menu do %> <%= link_to t(".upload_several_files"), new_bulk_aircraft_documents_path(@aircraft), class: "menu-item" %> <%= link_to t(".new_collection"), new_aircraft_document_collection_path(@aircraft), class: "menu-item" %> @@ -25,7 +25,7 @@
    <%= visibility_badge(col.visibility) %> - <% if owner? %> + <% if can?(:manage_documents) %> <%= link_to t(".document"), new_aircraft_document_path(@aircraft, collection_id: col.id), class: "btn-secondary btn-sm" %> <%= link_to t(".edit"), edit_aircraft_document_collection_path(@aircraft, col), class: "btn-secondary btn-sm" %> <% end %> diff --git a/app/views/documents/show.html.erb b/app/views/documents/show.html.erb index 282e317..d477c6b 100644 --- a/app/views/documents/show.html.erb +++ b/app/views/documents/show.html.erb @@ -8,7 +8,7 @@
    <%= visibility_badge(@document.effective_visibility) %> - <% if owner? %><%= link_to t(".edit"), edit_aircraft_document_path(@aircraft, @document), class: "btn-secondary btn-sm" %><% end %> + <% if can?(:manage_documents) %><%= link_to t(".edit"), edit_aircraft_document_path(@aircraft, @document), class: "btn-secondary btn-sm" %><% end %>
    diff --git a/app/views/flight_logs/index.html.erb b/app/views/flight_logs/index.html.erb index e77dcc0..91b92c0 100644 --- a/app/views/flight_logs/index.html.erb +++ b/app/views/flight_logs/index.html.erb @@ -5,9 +5,9 @@

    <%= t(".flight_log") %>

    <%= more_menu do %> - <% if owner? %><%= link_to t(".import_from_spreadsheet"), new_aircraft_flight_import_path(@aircraft), class: "menu-item" %><% end %> - <%= link_to t(".export_for_airtrail"), new_aircraft_air_trail_export_path(@aircraft), class: "menu-item" %> - <% if owner? %><%= link_to t(".standardize_airport_codes"), aircraft_airport_codes_path(@aircraft), class: "menu-item" %><% end %> + <% if can?(:import_flights) %><%= link_to t(".import_from_spreadsheet"), new_aircraft_flight_import_path(@aircraft), class: "menu-item" %><% end %> + <% if can?(:log_flights) %><%= link_to t(".export_for_airtrail"), new_aircraft_air_trail_export_path(@aircraft), class: "menu-item" %><% end %> + <% if can?(:edit_any_flight) %><%= link_to t(".standardize_airport_codes"), aircraft_airport_codes_path(@aircraft), class: "menu-item" %><% end %> <% end %>
    <% if @days.any? %> diff --git a/app/views/flight_logs/show.html.erb b/app/views/flight_logs/show.html.erb index 54bf4ed..0152e96 100644 --- a/app/views/flight_logs/show.html.erb +++ b/app/views/flight_logs/show.html.erb @@ -4,7 +4,7 @@

    <%= t(".flight_on_html", date: (fmt_date(@flight_log.date))) %>

    <% if can_edit_flight?(@flight_log) %><%= link_to t(".edit"), edit_aircraft_flight_log_path(@aircraft, @flight_log), class: "btn-secondary btn-sm" %><% end %> - <% if owner? %><%= delete_button t(".delete"), aircraft_flight_log_path(@aircraft, @flight_log), confirm: t(".delete_this_flight_log_aircraft") %><% end %> + <% if can?(:delete_flights) %><%= delete_button t(".delete"), aircraft_flight_log_path(@aircraft, @flight_log), confirm: t(".delete_this_flight_log_aircraft") %><% end %>
    <%# One item per row on a phone (label, then value); two columns on wider screens. %>
    diff --git a/app/views/inspections/index.html.erb b/app/views/inspections/index.html.erb index cb23864..ed75030 100644 --- a/app/views/inspections/index.html.erb +++ b/app/views/inspections/index.html.erb @@ -2,7 +2,7 @@ <%= render "shared/aircraft_header", aircraft: @aircraft %>

    <%= t(".inspection_status") %>

    - <% if owner? %>
    <%= more_menu do %><%= link_to t(".add_standard_inspections"), new_aircraft_standard_inspections_path(@aircraft), class: "menu-item" %><% end %><%= link_to t(".inspection_type"), new_aircraft_inspection_type_path(@aircraft), class: "btn-primary" %>
    <% end %>
    + <% if can?(:manage_inspections) %>
    <%= more_menu do %><%= link_to t(".add_standard_inspections"), new_aircraft_standard_inspections_path(@aircraft), class: "menu-item" %><% end %><%= link_to t(".inspection_type"), new_aircraft_inspection_type_path(@aircraft), class: "btn-primary" %>
    <% end %>
    <% if @rows.any? %>
    <%= r.consumable_type %> <%= hours(r.flight_hours) %> <%= r.notes %><%= t(".excluded_from_average") if r.excluded_from_averages? %><% if owner? %><%= link_to t(".edit"), edit_aircraft_consumable_record_path(@aircraft, r), class: "btn-secondary btn-sm" %><% end %><% if can?(:manage_consumables) %><%= link_to t(".edit"), edit_aircraft_consumable_record_path(@aircraft, r), class: "btn-secondary btn-sm" %><% end %>
    @@ -17,7 +17,7 @@ - + <% end %> diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index 9adbef2..6b9d8d8 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -50,7 +50,7 @@ <%= link_to t(".help"), help_path, class: "block px-4 py-2.5 hover:bg-slate-100" %> <% if current_user.admin? %>

    <%= t(".admin") %>

    - <% [ [ t(".users"), admin_users_path ], [ t(".integrations"), admin_integrations_path ], [ t(".component_types"), admin_component_types_path ], [ t(".airports"), admin_airports_path ], [ t(".logbook_templates"), admin_logbook_templates_path ], [ t(".settings"), edit_admin_settings_path ], [ t(".off_site_backup"), admin_offsite_backup_path ], [ t(".recordkeeping_procedures"), admin_procedures_path ], [ t(".records_audits"), admin_audits_path ], [ t(".about"), admin_about_path ] ].each do |label, path| %> + <% [ [ t(".users"), admin_users_path ], [ t(".roles"), admin_roles_path ], [ t(".integrations"), admin_integrations_path ], [ t(".component_types"), admin_component_types_path ], [ t(".airports"), admin_airports_path ], [ t(".logbook_templates"), admin_logbook_templates_path ], [ t(".settings"), edit_admin_settings_path ], [ t(".off_site_backup"), admin_offsite_backup_path ], [ t(".recordkeeping_procedures"), admin_procedures_path ], [ t(".records_audits"), admin_audits_path ], [ t(".about"), admin_about_path ] ].each do |label, path| %> <%= link_to label, path, class: "block px-4 py-2.5 hover:bg-slate-100" %> <% end %> <% end %> @@ -71,7 +71,7 @@ <%= t(".admin") %>
    - <% [ [ t(".users"), admin_users_path ], [ t(".integrations"), admin_integrations_path ], [ t(".component_types"), admin_component_types_path ], [ t(".airports"), admin_airports_path ], [ t(".logbook_templates"), admin_logbook_templates_path ], [ t(".settings"), edit_admin_settings_path ], [ t(".off_site_backup"), admin_offsite_backup_path ], [ t(".recordkeeping_procedures"), admin_procedures_path ], [ t(".records_audits"), admin_audits_path ], [ t(".about"), admin_about_path ] ].each do |label, path| %> + <% [ [ t(".users"), admin_users_path ], [ t(".roles"), admin_roles_path ], [ t(".integrations"), admin_integrations_path ], [ t(".component_types"), admin_component_types_path ], [ t(".airports"), admin_airports_path ], [ t(".logbook_templates"), admin_logbook_templates_path ], [ t(".settings"), edit_admin_settings_path ], [ t(".off_site_backup"), admin_offsite_backup_path ], [ t(".recordkeeping_procedures"), admin_procedures_path ], [ t(".records_audits"), admin_audits_path ], [ t(".about"), admin_about_path ] ].each do |label, path| %> <%= link_to label, path, class: [ "block px-4 py-2 text-sm hover:bg-slate-100", ("font-semibold text-sky-700" if current_page?(path)) ] %> <% end %>
    diff --git a/app/views/logbook_entries/index.html.erb b/app/views/logbook_entries/index.html.erb index 5c4e260..2f487c4 100644 --- a/app/views/logbook_entries/index.html.erb +++ b/app/views/logbook_entries/index.html.erb @@ -13,10 +13,8 @@ <%= f.submit t(".filter"), class: "sr-only" %> <% end %> <% if @entries.any? %><% end %> - <% if owner? %> - <%= more_menu do %><%= link_to t(".import_scans"), new_aircraft_logbook_import_path(@aircraft), class: "menu-item" %><% end %> - <%= link_to t(".new_entry"), new_aircraft_logbook_entry_path(@aircraft), class: "btn-primary" %> - <% end %> + <% if can?(:import_records) %><%= more_menu do %><%= link_to t(".import_scans"), new_aircraft_logbook_import_path(@aircraft), class: "menu-item" %><% end %><% end %> + <% if can?(:write_logbook) %><%= link_to t(".new_entry"), new_aircraft_logbook_entry_path(@aircraft), class: "btn-primary" %><% end %> <% if @entries.any? %> diff --git a/app/views/logbook_entries/show.html.erb b/app/views/logbook_entries/show.html.erb index c32ac5b..74ef203 100644 --- a/app/views/logbook_entries/show.html.erb +++ b/app/views/logbook_entries/show.html.erb @@ -5,14 +5,14 @@
    <% if @entry.signed? %> <%= link_to t(".print_for_logbook"), new_aircraft_logbook_print_path(@aircraft, ids: [ @entry.id ]), class: "btn-secondary btn-sm" %> - <% if owner? && !@entry.superseded? && !@entry.superseded_by %> + <% if can?(:write_logbook) && !@entry.superseded? && !@entry.superseded_by %> <%= more_menu(small: true) do %><%= link_to t(".correct_this_entry"), new_aircraft_logbook_entry_path(@aircraft, supersedes: @entry.id), class: "menu-item" %><% end %> <% end %> <% else %> - <%= link_to t(".sign"), new_aircraft_logbook_entry_signature_path(@aircraft, @entry), class: "btn-primary btn-sm" %> - <% if owner? %><%= link_to t(".edit"), edit_aircraft_logbook_entry_path(@aircraft, @entry), class: "btn-secondary btn-sm" %><% end %> + <% if can?(:sign_logbook) %><%= link_to t(".sign"), new_aircraft_logbook_entry_signature_path(@aircraft, @entry), class: "btn-primary btn-sm" %><% end %> + <% if can?(:write_logbook) %><%= link_to t(".edit"), edit_aircraft_logbook_entry_path(@aircraft, @entry), class: "btn-secondary btn-sm" %><% end %> <%= more_menu(small: true) do %> - <% if owner? %><%= link_to t(".ask_someone_to_sign"), new_aircraft_logbook_entry_signing_invitation_path(@aircraft, @entry), class: "menu-item" %><% end %> + <% if can?(:write_logbook) %><%= link_to t(".ask_someone_to_sign"), new_aircraft_logbook_entry_signing_invitation_path(@aircraft, @entry), class: "menu-item" %><% end %> <%= link_to t(".print_for_logbook"), new_aircraft_logbook_print_path(@aircraft, ids: [ @entry.id ]), class: "menu-item" %> <% end %> <% end %> @@ -27,7 +27,7 @@ <% unless @entry.verified? %>
    <%= t(".transcribed_by_claude_and_not_html", transcription_confidence: (t(".confidence", transcription_confidence: @entry.transcription_confidence) if @entry.transcription_confidence), logbook: (@entry.document ? "" : t(".or_the_paper_logbook"))) %> - <% if owner? %><%= button_to t(".matches_the_scan_mark_verified"), verify_aircraft_logbook_entry_path(@aircraft, @entry), method: :patch, class: "btn-secondary btn-sm" %><% end %> + <% if can?(:write_logbook) %><%= button_to t(".matches_the_scan_mark_verified"), verify_aircraft_logbook_entry_path(@aircraft, @entry), method: :patch, class: "btn-secondary btn-sm" %><% end %>
    <% end %>
    @@ -53,7 +53,7 @@ <% if (missing = @entry.missing_record_items).any? %>

    <%= t(".missing_for_html", entry_type: (@entry.entry_type == "INSPECTION" ? "43.11" : "43.9"), items: missing.to_sentence) %> - <%= link_to(t(".fill_in"), edit_aircraft_logbook_entry_path(@aircraft, @entry), class: "link") if owner? %> + <%= link_to(t(".fill_in"), edit_aircraft_logbook_entry_path(@aircraft, @entry), class: "link") if can?(:write_logbook) %> <%= t(".check_against_the_signed_logbook") %>

    <% end %> diff --git a/app/views/major_records/index.html.erb b/app/views/major_records/index.html.erb index 451a1ed..79f08db 100644 --- a/app/views/major_records/index.html.erb +++ b/app/views/major_records/index.html.erb @@ -2,7 +2,7 @@ <%= render "shared/aircraft_header", aircraft: @aircraft %>

    <%= t(".major_repairs_alterations") %>

    - <% if owner? %>
    + <% if can?(:manage_major_records) %>
    <%= link_to t(".repair"), new_aircraft_major_record_path(@aircraft, type: "repair"), class: "btn-secondary" %> <%= link_to t(".alteration"), new_aircraft_major_record_path(@aircraft, type: "alteration"), class: "btn-primary" %>
    <% end %>
    <% if @records.any? %> diff --git a/app/views/major_records/show.html.erb b/app/views/major_records/show.html.erb index 4ab3ff3..b376f11 100644 --- a/app/views/major_records/show.html.erb +++ b/app/views/major_records/show.html.erb @@ -1,7 +1,7 @@ <%= render "shared/aircraft_header", aircraft: @aircraft %>

    <%= @record.type_label %>: <%= @record.title %>

    - <% if owner? %><%= link_to t(".edit"), edit_aircraft_major_record_path(@aircraft, @record), class: "btn-secondary btn-sm" %><% end %>
    + <% if can?(:manage_major_records) %><%= link_to t(".edit"), edit_aircraft_major_record_path(@aircraft, @record), class: "btn-secondary btn-sm" %><% end %>
    <%= t(".date") %>
    <%= fmt_date(@record.date_performed) %>
    <%= t(".aircraft_hours") %>
    <%= hours(@record.aircraft_hours) %>
    @@ -15,7 +15,7 @@
    <% if (wb = @aircraft.weight_balance_records.where(major_record: @record).recent_first.first) %> <%= link_to t(".lb_in", date: fmt_date(wb.date), weight: number_with_precision(wb.empty_weight, precision: 1), arm: number_with_precision(wb.empty_arm, precision: 2)), aircraft_weight_balance_records_path(@aircraft), class: "link" %> - <% elsif owner? %> + <% elsif can?(:manage_major_records) %> <%= link_to t(".record_the_new_w_b"), new_aircraft_weight_balance_record_path(@aircraft, major_record_id: @record.id), class: "link" %> <% else %>—<% end %>
    @@ -25,7 +25,7 @@ <% if (ica = @record.ica_inspection_type) %> <% row = Compliance.inspection_rows(@aircraft).find { _1.type == ica } %> <%= t(".inspection_html", link: (link_to ica.name, aircraft_inspections_path(@aircraft), class: "link"), row: (compliance_badge(row.status) if row)) %> - <% elsif @record.has_ica? && owner? %> + <% elsif @record.has_ica? && can?(:manage_major_records) %> · <%= link_to t(".add_the_ica_s_recurring"), new_aircraft_inspection_type_path(@aircraft, major_record_id: @record.id), class: "link" %> <% end %>
    diff --git a/app/views/notes/index.html.erb b/app/views/notes/index.html.erb index 8dc51af..0e20009 100644 --- a/app/views/notes/index.html.erb +++ b/app/views/notes/index.html.erb @@ -1,7 +1,7 @@ <% content_for :title, t(".notes", tail_number: @aircraft.tail_number) %> <%= render "shared/aircraft_header", aircraft: @aircraft %>
    -

    <%= t(".notes_2") %>

    <%= link_to t(".add_note"), new_aircraft_note_path(@aircraft), class: "btn-primary" %>
    +

    <%= t(".notes_2") %>

    <% if can?(:write_notes) %><%= link_to t(".add_note"), new_aircraft_note_path(@aircraft), class: "btn-primary" %><% end %>
    <% if @notes.any? %>
      <% @notes.each do |note| %> @@ -14,7 +14,7 @@ <% if note.public? %><%= t(".visible_on_share_links") %><% end %> - <% if owner? %><%= link_to t(".edit"), edit_aircraft_note_path(@aircraft, note), class: "btn-secondary btn-sm" %><% end %> + <% if can?(:manage_notes) %><%= link_to t(".edit"), edit_aircraft_note_path(@aircraft, note), class: "btn-secondary btn-sm" %><% end %> <% end %>
    diff --git a/app/views/oil_analyses/index.html.erb b/app/views/oil_analyses/index.html.erb index 947d5d3..0a162b4 100644 --- a/app/views/oil_analyses/index.html.erb +++ b/app/views/oil_analyses/index.html.erb @@ -3,6 +3,7 @@ <%= render "shared/oil_subnav", aircraft: @aircraft %> <% recent = @analyses.first(OilAnalysesController::COMPARE_SAMPLES) %>
    + <% if can?(:record_oil_analyses) %>
    @@ -12,11 +13,12 @@ <%= render "import", aircraft: @aircraft %>
    + <% end %>

    <%= t(".wear_metal_trends") %>

    - <%= link_to t(".add_oil_analysis"), new_aircraft_oil_analysis_path(@aircraft), class: "btn-secondary btn-sm" %> + <% if can?(:record_oil_analyses) %><%= link_to t(".add_oil_analysis"), new_aircraft_oil_analysis_path(@aircraft), class: "btn-secondary btn-sm" %><% end %>
    <% series = oil_trend_series(@analyses) %> diff --git a/app/views/oil_analyses/show.html.erb b/app/views/oil_analyses/show.html.erb index 451cbc8..c6ac539 100644 --- a/app/views/oil_analyses/show.html.erb +++ b/app/views/oil_analyses/show.html.erb @@ -38,7 +38,7 @@ <% if @analysis.notes.present? %>
    <%= t(".notes") %>
    <%= simple_format @analysis.notes %>
    <% end %> - <% if owner? %> + <% if can?(:manage_oil_analyses) %>
    <%= link_to t(".edit"), edit_aircraft_oil_analysis_path(@aircraft, @analysis), class: "btn-secondary btn-sm" %> <%= delete_button t(".delete"), aircraft_oil_analysis_path(@aircraft, @analysis), confirm: t(".delete_this_oil_analysis") %> diff --git a/app/views/record_versions/index.html.erb b/app/views/record_versions/index.html.erb index 669106e..5b1cc5b 100644 --- a/app/views/record_versions/index.html.erb +++ b/app/views/record_versions/index.html.erb @@ -10,5 +10,5 @@ <%= select_tag :type, options_for_select([ [ t(".all_records"), "" ] ] + @types.map { [ _1.underscore.humanize, _1 ] }, @type), class: "input w-48", data: { submit_on_change: true } %> <% end %>
    - <% if @versions.any? %><%= render "record_versions/list", versions: @versions, aircraft: @aircraft, can_restore: owner? %><% else %><%= empty_state t(".no_changes_recorded_yet") %><% end %> + <% if @versions.any? %><%= render "record_versions/list", versions: @versions, aircraft: @aircraft, can_restore: can?(:restore_history) %><% else %><%= empty_state t(".no_changes_recorded_yet") %><% end %>
    diff --git a/app/views/shared/_aircraft_header.html.erb b/app/views/shared/_aircraft_header.html.erb index e7fd303..4b52840 100644 --- a/app/views/shared/_aircraft_header.html.erb +++ b/app/views/shared/_aircraft_header.html.erb @@ -14,18 +14,18 @@ <%= airworthiness_badge(aw) %> <%= aircraft_status_badge(aircraft) unless aircraft.status == "AVAILABLE" %> <%= t(".tach_hobbs_html", tach_time: (hours(aircraft.tach_time)), hobbs_time: (hours(aircraft.hobbs_time))) %> - "><%= (current_user.aircraft_roles.find_by(aircraft: aircraft)&.role || current_role).capitalize %> + "><%= current_role&.name || t(".admin") %>
    - <%= link_to t(".log_flight"), new_aircraft_flight_log_path(aircraft), class: "btn-primary" %> - <%= link_to t(".report_squawk"), new_aircraft_squawk_path(aircraft), class: "btn-secondary" %> + <% if can?(:log_flights) %><%= link_to t(".log_flight"), new_aircraft_flight_log_path(aircraft), class: "btn-primary" %><% end %> + <% if can?(:report_squawks) %><%= link_to t(".report_squawk"), new_aircraft_squawk_path(aircraft), class: "btn-secondary" %><% end %> <%= more_menu do %> <%= link_to t(".status_report"), aircraft_report_path(aircraft), class: "menu-item" %> - <% if owner? %> - <%= link_to t(".access_sharing"), aircraft_aircraft_roles_path(aircraft), class: "menu-item" %> - <%= link_to t(".edit_aircraft"), edit_aircraft_path(aircraft), class: "menu-item" %> + <% if can?(:manage_people) || can?(:manage_sharing) || can?(:export_data) %><%= link_to t(".access_sharing"), aircraft_aircraft_roles_path(aircraft), class: "menu-item" %><% end %> + <% if can?(:edit_aircraft) %><%= link_to t(".edit_aircraft"), edit_aircraft_path(aircraft), class: "menu-item" %><% end %> + <% if can?(:export_data) %> <%= link_to t(".download_sam_zip"), aircraft_export_path(aircraft), class: "menu-item", data: { turbo: false } %> <%= link_to t(".download_records_package"), aircraft_records_package_path(aircraft), class: "menu-item", data: { turbo: false } %> <% end %> diff --git a/app/views/squawks/_form.html.erb b/app/views/squawks/_form.html.erb index 83a6526..82dc68c 100644 --- a/app/views/squawks/_form.html.erb +++ b/app/views/squawks/_form.html.erb @@ -29,6 +29,6 @@ <%= link_to t(".cancel"), aircraft_squawks_path(aircraft), class: "btn-secondary" %>
    <% end %> -<% if squawk.persisted? && owner? %> +<% if squawk.persisted? && can?(:manage_squawks) %>
    <%= delete_button t(".delete_squawk"), aircraft_squawk_path(aircraft, squawk) %>
    <% end %> diff --git a/app/views/squawks/_table.html.erb b/app/views/squawks/_table.html.erb index 530226e..d84fdc0 100644 --- a/app/views/squawks/_table.html.erb +++ b/app/views/squawks/_table.html.erb @@ -14,13 +14,13 @@
    <% end %> diff --git a/app/views/squawks/index.html.erb b/app/views/squawks/index.html.erb index 744cb73..ab9af11 100644 --- a/app/views/squawks/index.html.erb +++ b/app/views/squawks/index.html.erb @@ -19,7 +19,7 @@ - + <% end %> diff --git a/app/views/weight_balance_records/index.html.erb b/app/views/weight_balance_records/index.html.erb index c1ac6f7..5c5e2ed 100644 --- a/app/views/weight_balance_records/index.html.erb +++ b/app/views/weight_balance_records/index.html.erb @@ -5,7 +5,7 @@

    <%= t(".current_weight_balance") %>

    - <% if owner? %><%= link_to t(".new_w_b"), new_aircraft_weight_balance_record_path(@aircraft), class: "btn-primary btn-sm" %><% end %> + <% if can?(:manage_weight_balance) %><%= link_to t(".new_w_b"), new_aircraft_weight_balance_record_path(@aircraft), class: "btn-primary btn-sm" %><% end %>
    <% if @current %>
    @@ -24,14 +24,14 @@

    <%= t(".loading_calculator") %>

    - <% if owner? %><%= link_to t(".loading_setup"), edit_aircraft_loading_setup_path(@aircraft), class: "btn-secondary btn-sm" %><% end %> + <% if can?(:manage_weight_balance) %><%= link_to t(".loading_setup"), edit_aircraft_loading_setup_path(@aircraft), class: "btn-secondary btn-sm" %><% end %>
    <% if @current && setup.configured? %> <%= render "weight_balance_records/calculator", record: @current, setup: setup %> <% elsif !@current %> <%= empty_state t(".record_the_current_weight_balance") %> <% else %> - <%= empty_state(owner? ? t(".set_up_the_loading_stations") : t(".an_owner_needs_to_set")) %> + <%= empty_state(can?(:manage_weight_balance) ? t(".set_up_the_loading_stations") : t(".an_owner_needs_to_set")) %> <% end %>
    @@ -52,7 +52,7 @@
    - + <% end %> diff --git a/config/locales/en.yml b/config/locales/en.yml index 6119a84..7176584 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -165,10 +165,6 @@ en: privileges: status: Current Status maintenance: Maintenance Detail - aircraft_role: - roles: - owner: Owner - pilot: Pilot airport: kinds: seaplane_base: seaplane base @@ -826,7 +822,7 @@ en: engine_data_attached: Engine data attached. engine_data_removed: Engine data removed. flight_log_deleted_aircraft: Flight log deleted. Aircraft hours were not changed. - only_owners_or_the: Only owners or the flight's pilot can do that. + only_owners_or_the: Your role on this aircraft doesn't allow changing this flight. flight_log_deleted: Flight log deleted track_unreadable: 'Couldn''t read track: %{message}' engine_data_unreadable: 'Couldn''t read engine data: %{message}' @@ -1110,7 +1106,18 @@ en: one: Restored %{count} built-in template. other: Restored %{count} built-in templates. all_present: All the built-in templates are already here. + admin_roles: + created: Role “%{name}” created. + updated: Role “%{name}” saved. + deleted: Role “%{name}” deleted. + built_in: Built-in roles can't be deleted. + in_use: + one: "“%{name}” is still given to 1 person; give them another role first." + other: "“%{name}” is still given to %{count} people; give them another role first." admin_users: + access_added: Added to %{tail_number}. + access_changed: Role on %{tail_number} changed. + access_removed: Removed from %{tail_number}. user_created: User %{email_address} created. you_can_t_remove: You can't remove your own admin rights. user_updated: User updated. @@ -1137,7 +1144,7 @@ en: component_type_updated: Component type updated. component_type_deleted: Component type deleted. common: - only_owners_can_do: Only owners can do that. + not_allowed: Your role on this aircraft doesn't allow that. calendar_feeds: name: Aircraft maintenance projected: projected from recent flying @@ -1217,6 +1224,30 @@ en: matches: Matches update: Update admin: + roles: + index: + roles: Roles + new_role: New role + intro: What people can do on an aircraft depends on their role there. Change what a role allows, or add your own (a partner, an instructor, an insurer). Everyone can see the records of the aircraft they have a role on. + name: Role + can: Can + people: People + built_in: Built in + everything: Everything, including people and sharing + view_only: View only + edit: Edit + new: + new_role: New Role + edit: + edit_role: 'Edit Role: %{name}' + form: + description_hint: Shown when choosing a role. + owner_has_everything: Owner always has every permission, so every aircraft can always be managed. Its name and description can be changed. + viewing_needs_nothing: Seeing the aircraft's records needs no permission. Signing a logbook entry also needs a current certificate on the person's profile. + save: Save + cancel: Cancel + delete_role: Delete role + delete_role_confirm: Delete the role “%{name}”? integrations: show: revoked: Revoked @@ -1658,6 +1689,16 @@ en: users: edit: edit_user: Edit User + aircraft_access: Aircraft access + role_on: Role on %{tail_number} + remove: Remove + remove_access: Remove their access to %{tail_number}? + no_aircraft: No access to any aircraft yet. + aircraft: Aircraft + role: Role + add: Add + roles: Roles + roles_hint_html: What each role can do is set under %{link}. As an administrator they can see and change every aircraft whatever their roles. form: email: Email administrator: Administrator @@ -1787,6 +1828,7 @@ en: hobbs: Hobbs log_flight: Log Flight enter_the_current_meter_readings_html: Enter the current meter readings. The difference is applied to every in-service component. For a single flight, use %{link}. + enter_the_current_meter_readings: Enter the current meter readings. The difference is applied to every in-service component. details: Details edit: Edit serial: Serial @@ -1856,7 +1898,10 @@ en: remove: Remove add_by_email: Add by email add: Add - owners_can_edit_everything_pilots_html: "Owners can edit everything. Pilots can view all records, log flights, update hours, and add squawks, notes and oil/fuel." + role_for: Role for %{display_name} + role: Role + what_each_role_can_do: What each role can do + roles_are_set_by_an_administrator: An administrator sets what each role can do, and can add roles (Admin → Roles). Only an Owner can give or take away the Owner role. share_links: Share Links expired: Expired revoke_this_link_anyone_using: Revoke this link? Anyone using it will lose access. @@ -2602,6 +2647,7 @@ en: sign_out: Sign out layouts: application: + roles: Roles integrations: Integrations skip_to_content_html: simple_aircraft_manager: Simple Aircraft Manager @@ -3269,6 +3315,7 @@ en: create_admin_account: Create Admin Account shared: aircraft_header: + admin: Admin tach_hobbs_html: Tach %{tach_time} · Hobbs %{hobbs_time} your_access_to_this_aircraft: Your access to this aircraft log_flight: Log Flight @@ -3546,6 +3593,120 @@ en: an_owner_needs_to_set: An owner needs to set up the loading stations first. new: weight_balance: "%{tail_number} Weight & Balance" + roles: + owner: + name: Owner + description: Everything on the aircraft, including its people and sharing. + mechanic: + name: Mechanic + description: 'Maintenance records: logbook entries, components, inspections, ADs and squawks.' + pilot: + name: Pilot + description: 'Flying: logs flights and hours, reports squawks, adds notes and oil and fuel.' + viewer: + name: Viewer + description: Sees everything on the aircraft and changes nothing. + permissions: + groups: + flying: Flying + squawks_and_notes: Squawks, notes, oil and fuel + maintenance: Maintenance records + data: Imports and exports + aircraft: The aircraft + notifications: Notifications + log_flights: + label: Log flights + description: Log Flight (also offline) and the AirTrail export. + update_hours: + label: Update hours + description: Set the tach and Hobbs readings without logging a flight. + import_flights: + label: Import flights + description: From a spreadsheet. + edit_own_flights: + label: Correct own flights + description: The flights they logged, and their engine data. + edit_any_flight: + label: Correct any flight + description: Any flight and its engine data, and standardizing airport codes. + delete_flights: + label: Delete flights + description: Deleting doesn't take the hours back off. + report_squawks: + label: Report squawks + description: Also offline, and through the API. + defer_squawks: + label: Defer squawks + description: As inoperative equipment (14 CFR 91.213). + manage_squawks: + label: Manage squawks + description: Edit, resolve, reopen and delete squawks, and undo deferrals. + write_notes: + label: Write notes + description: Add notes to the aircraft. + manage_notes: + label: Manage notes + description: Edit and delete anyone's notes. + record_consumables: + label: Record oil and fuel + description: Add oil and fuel records. + manage_consumables: + label: Manage oil and fuel + description: Edit and delete oil and fuel records. + write_logbook: + label: Write logbook entries + description: Create and edit unsigned entries, correct signed ones, ask someone to sign, and send drafts through the API. + sign_logbook: + label: Sign logbook entries + description: Also needs a current certificate on their profile. + manage_components: + label: Manage components + description: Add, edit and remove components, and record service. + manage_inspections: + label: Manage inspections + description: Inspection types and records. + manage_ads: + label: Manage ADs + description: ADs, compliance, the DRS import and new-AD alerts. + manage_major_records: + label: Manage major repairs and alterations + description: Form 337s and their ICAs. + manage_weight_balance: + label: Manage weight and balance + description: Records and the loading setup. + manage_documents: + label: Manage documents + description: Upload, edit and delete documents and collections. + record_oil_analyses: + label: Add oil analyses + description: Enter or import lab reports. + manage_oil_analyses: + label: Manage oil analyses + description: Edit and delete oil analyses. + import_records: + label: Import logbook scans + description: Turn photos or PDFs of paper logbooks into entries. + export_data: + label: Export + description: The .sam.zip backup and the records package. + restore_history: + label: Restore from history + description: Put a record back as it was in the record history. + edit_aircraft: + label: Edit the aircraft + description: Its details, photo and settings, and the setup checklist. + delete_aircraft: + label: Delete the aircraft + description: With all its records. + manage_people: + label: Manage people + description: Give people roles on the aircraft. + manage_sharing: + label: Share links + description: Create and revoke read-only links. + receive_reminders: + label: Get reminders + description: The weekly email of what's coming due, and alerts when something becomes overdue. helpers: aircraft: overview: Overview @@ -3590,6 +3751,11 @@ en: form: interval_unit: "%{label} unit" services: + aircraft_access: + not_found: Choose a person and a role. + owner_only: Only an Owner can give or take away the Owner role. + own_role: You can't change your own role; ask another Owner or an administrator. + last_owner: An aircraft must keep at least one Owner. airworthiness: disclaimer: Based on the records in this app. Before each flight the pilot in command decides whether the aircraft is airworthy (14 CFR 91.7). categories: diff --git a/config/routes.rb b/config/routes.rb index 5f3e8bd..57dd42b 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -171,7 +171,10 @@ Rails.application.routes.draw do post "about/test_email", to: "about#test_email", as: :test_email post "about/test_reminder", to: "about#test_reminder", as: :test_reminder post "about/check_records", to: "about#check_records", as: :check_records - resources :users, except: :show + resources :users, except: :show do + resources :aircraft_roles, controller: "user_aircraft_roles", only: %i[create update destroy] + end + resources :roles, except: :show resources :integrations do post :new_secret, on: :member end diff --git a/db/migrate/20261116010000_create_roles.rb b/db/migrate/20261116010000_create_roles.rb new file mode 100644 index 0000000..cddc301 --- /dev/null +++ b/db/migrate/20261116010000_create_roles.rb @@ -0,0 +1,56 @@ +# Configurable roles (Role, Permission): the owner/pilot text on each +# aircraft role becomes a link to a role. Owners and pilots keep exactly what +# they could do (Owner has everything; Pilot gets what pilots could do), and +# Mechanic and Viewer are added. The permissions are spelled out here so this +# migration doesn't change if the defaults in code do. +class CreateRoles < ActiveRecord::Migration[8.1] + BUILT_IN = [ + [ "owner", "Owner", "Everything on the aircraft, including its people and sharing.", [] ], + [ "mechanic", "Mechanic", "Maintenance records: logbook entries, components, inspections, ADs and squawks.", + %w[update_hours report_squawks defer_squawks manage_squawks write_notes manage_notes record_consumables + manage_consumables write_logbook sign_logbook manage_components manage_inspections manage_ads + manage_major_records manage_weight_balance manage_documents record_oil_analyses manage_oil_analyses + receive_reminders] ], + [ "pilot", "Pilot", "Flying: logs flights and hours, reports squawks, adds notes and oil and fuel.", + %w[log_flights update_hours edit_own_flights report_squawks defer_squawks write_notes record_consumables + record_oil_analyses sign_logbook] ], + [ "viewer", "Viewer", "Sees everything on the aircraft and changes nothing.", [] ] + ].freeze + + def up + create_table :roles do |t| + t.string :name, null: false + t.string :key + t.string :description + t.json :permissions, null: false, default: [] + t.integer :position, null: false, default: 0 + t.timestamps + end + add_index :roles, :key, unique: true + add_index :roles, :name, unique: true + + now = Time.current + BUILT_IN.each_with_index do |(key, name, description, permissions), i| + execute sanitize_sql([ "INSERT INTO roles (name, key, description, permissions, position, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)", + name, key, description, permissions.to_json, i, now, now ]) + end + + add_reference :aircraft_roles, :role, foreign_key: true + execute "UPDATE aircraft_roles SET role_id = (SELECT id FROM roles WHERE roles.key = aircraft_roles.role)" + execute "UPDATE aircraft_roles SET role_id = (SELECT id FROM roles WHERE key = 'pilot') WHERE role_id IS NULL" + change_column_null :aircraft_roles, :role_id, false + remove_column :aircraft_roles, :role + end + + def down + add_column :aircraft_roles, :role, :string + execute "UPDATE aircraft_roles SET role = CASE (SELECT key FROM roles WHERE roles.id = aircraft_roles.role_id) WHEN 'owner' THEN 'owner' ELSE 'pilot' END" + change_column_null :aircraft_roles, :role, false + remove_reference :aircraft_roles, :role, foreign_key: true + drop_table :roles + end + + private + + def sanitize_sql(args) = ActiveRecord::Base.sanitize_sql_array(args) +end diff --git a/db/schema.rb b/db/schema.rb index 385a7cb..3265948 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema[8.1].define(version: 2026_11_15_020000) do +ActiveRecord::Schema[8.1].define(version: 2026_11_16_010000) do create_table "active_storage_attachments", force: :cascade do |t| t.string "name", null: false t.string "record_type", null: false @@ -210,11 +210,12 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_15_020000) do create_table "aircraft_roles", force: :cascade do |t| t.integer "aircraft_id", null: false t.integer "user_id", null: false - t.string "role", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false + t.integer "role_id", null: false t.index ["aircraft_id", "user_id"], name: "index_aircraft_roles_on_aircraft_id_and_user_id", unique: true t.index ["aircraft_id"], name: "index_aircraft_roles_on_aircraft_id" + t.index ["role_id"], name: "index_aircraft_roles_on_role_id" t.index ["user_id"], name: "index_aircraft_roles_on_user_id" end @@ -785,6 +786,18 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_15_020000) do t.datetime "updated_at", null: false end + create_table "roles", force: :cascade do |t| + t.string "name", null: false + t.string "key" + t.string "description" + t.json "permissions", default: [], null: false + t.integer "position", default: 0, null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["key"], name: "index_roles_on_key", unique: true + t.index ["name"], name: "index_roles_on_name", unique: true + end + create_table "sessions", force: :cascade do |t| t.integer "user_id", null: false t.string "ip_address" @@ -958,6 +971,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_15_020000) do add_foreign_key "aircraft_notes", "aircraft" add_foreign_key "aircraft_notes", "users", on_delete: :nullify add_foreign_key "aircraft_roles", "aircraft" + add_foreign_key "aircraft_roles", "roles" add_foreign_key "aircraft_roles", "users" add_foreign_key "airport_updates", "users", column: "requested_by_id", on_delete: :nullify add_foreign_key "airworthiness_directives", "documents", on_delete: :nullify diff --git a/docs/guide/administration.md b/docs/guide/administration.md index afb9e15..b651717 100644 --- a/docs/guide/administration.md +++ b/docs/guide/administration.md @@ -14,6 +14,18 @@ Admins see the **Admin** menu (on a phone, under ☰). Admins can see and edit e With single sign-on, accounts can be created automatically at first sign-in, and admin rights can follow a group at the provider (see the main README). +## Roles + +**Admin → Roles** sets what people can do on an aircraft. Each person has one role per aircraft; a role is a set of permissions, grouped as flying, squawks and notes, maintenance records, imports and exports, the aircraft itself, and notifications. Everyone can see the records of the aircraft they have a role on; the permissions are for changing things. + +- **Owner** always has every permission, so every aircraft can always be managed. Its name and description can be changed. +- **Mechanic**, **Pilot** and **Viewer** come with sensible permissions (the table in [Getting started](getting-started.md#roles)) that you can change. +- **New role** adds your own, such as a partner, an instructor or an insurer. A role can be deleted once nobody has it. + +Signing a logbook entry needs the **Sign logbook entries** permission *and* a current certificate on the person's profile. **Get reminders** decides who receives the weekly email of what's coming due and the alerts when something becomes overdue. + +To give someone a role on any aircraft, open them in **Admin → Users**: **Aircraft access** lists their role on each aircraft, to change, remove or add. + ## Account recovery from the command line If nobody can sign in to fix an account in the app (a forgotten admin password, a lockout, a lost phone with no recovery codes, the only admin disabled), run these on the server. With Docker Compose, put `docker compose exec web` in front; in Portainer, open the container's **Console** and run them there. Anyone who can run commands on the server already has the data, so they ask for nothing else. Each one is written to the log. diff --git a/docs/guide/api.md b/docs/guide/api.md index b3c034f..8f6e7c5 100644 --- a/docs/guide/api.md +++ b/docs/guide/api.md @@ -35,14 +35,14 @@ Reading works without it (limited to the integration's aircraft). Every write ne |---|---| | `read` | Aircraft, parts, due items, inspections, ADs, squawks and logbook entries | | `squawks:write` | Reporting squawks and updating them | -| `drafts:write` | Sending draft logbook entries for signing, and withdrawing them (acting for an owner of the aircraft) | +| `drafts:write` | Sending draft logbook entries for signing, and withdrawing them (acting for someone who can write logbook entries on the aircraft) | ## Requests and answers - Base address: `https:///api/v1` - JSON in and out. Times are ISO 8601 in UTC, hours are decimals, and values are codes (`ENG`, `IN-USE`) rather than translated labels. - Lists answer `{ "data": [ … ], "next_after": 123 }`. Ask for more with `?after=123`; `?limit=` sets the page size (up to 200, default 50); `?updated_since=2026-11-01T00:00:00Z` lists only what changed since then. -- Errors answer `{ "error": { "code": "invalid", "message": "…", "fields": { "issue_reported": ["can't be blank"] } } }` with the matching HTTP status: 400 bad request, 401 no or wrong token, 403 not allowed (`missing_scope`, `owners_only`), 404 not found or not reachable with this token, 409 `idempotency_conflict`, 422 invalid, 429 too many requests (600 a minute per token). +- Errors answer `{ "error": { "code": "invalid", "message": "…", "fields": { "issue_reported": ["can't be blank"] } } }` with the matching HTTP status: 400 bad request, 401 no or wrong token, 403 not allowed (`missing_scope`; `not_permitted` when the person's role on the aircraft doesn't allow it), 404 not found or not reachable with this token, 409 `idempotency_conflict`, 422 invalid, 429 too many requests (600 a minute per token). ### Safe retries @@ -98,11 +98,11 @@ The answer is `201` with the squawk: ### Updating a squawk -`PATCH /squawks/:id` with `{ "squawk": { … } }`. Anyone who may write can set `external_ref`; changing `issue_reported`, `priority`, `component_id` or `notes` needs an owner of the aircraft, as in the app. A resolved squawk can't be changed. Squawks are resolved by a signed logbook entry, in the app. +`PATCH /squawks/:id` with `{ "squawk": { … } }`. Anyone who may write can set `external_ref`; changing `issue_reported`, `priority`, `component_id` or `notes` needs the **Manage squawks** permission on the aircraft, as in the app. Reporting one needs **Report squawks**. A resolved squawk can't be changed. Squawks are resolved by a signed logbook entry, in the app. ## Draft entries -Another system that tracks the work, such as Redmine's issues, can send a finished visit to SAM as **draft logbook entries**: the person certifying the work then reviews and signs them in the app. Like writing entries in the app, sending drafts is for the aircraft's owners: an integration acts for an owner (`SAM-On-Behalf-Of`), such as the director of maintenance. +Another system that tracks the work, such as Redmine's issues, can send a finished visit to SAM as **draft logbook entries**: the person certifying the work then reviews and signs them in the app. Like writing entries in the app, sending drafts needs the **Write logbook entries** permission (Owners and Mechanics have it): an integration acts for such a person (`SAM-On-Behalf-Of`), such as the director of maintenance. ``` POST /api/v1/aircraft/12/draft_batches diff --git a/docs/guide/flights.md b/docs/guide/flights.md index 0b1d4d2..7484381 100644 --- a/docs/guide/flights.md +++ b/docs/guide/flights.md @@ -19,7 +19,7 @@ Track and engine data files attached offline are kept and sent too. ## Correct a flight -Open the flight and choose **Edit**. Owners can correct any flight; a pilot, the flights they logged. The date, airports, route, notes, oil and fuel (its oil and fuel records follow), and the track and engine data files can always be changed. +Open the flight and choose **Edit**. Owners can correct any flight; pilots, the flights they logged (the **Correct any flight** and **Correct own flights** permissions). The date, airports, route, notes, oil and fuel (its oil and fuel records follow), and the track and engine data files can always be changed. The meter readings can be changed only on the latest flight, and only until the hours change again (another flight, an hours update or an import). The aircraft and its installed components then move by the difference: fixing a tach in of 1001.4 to 1001.6 adds 0.2 hours. On earlier flights the readings are locked, since the flights after them started from those readings; correct the aircraft's hours with **Update Hours** instead. diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.md index 0a4a951..36a611a 100644 --- a/docs/guide/getting-started.md +++ b/docs/guide/getting-started.md @@ -16,20 +16,21 @@ The very first visit to a new installation asks for the administrator account in ## Roles -What you can do depends on your role on each aircraft: +What you can do depends on your role on each aircraft. These are the built-in roles as they come; the administrator can change what each allows and add others (see [Administration](administration.md#roles)). -| | Pilot | Owner | Admin | -|---|:-:|:-:|:-:| -| See everything on the aircraft | ✓ | ✓ | ✓ | -| Log flights, update hours, report squawks, add notes, oil and fuel | ✓ | ✓ | ✓ | -| Defer a squawk as inoperative | ✓ | ✓ | ✓ | -| Sign logbook entries (with your own certificate) | ✓ | ✓ | ✓ | -| Edit squawks and notes, resolve squawks | | ✓ | ✓ | -| Components, logbook, inspections, ADs, documents, major records, W&B | | ✓ | ✓ | -| Edit the aircraft, manage people and share links | | ✓ | ✓ | -| Users, settings, procedures and audits for the whole app | | | ✓ | +| | Viewer | Pilot | Mechanic | Owner | +|---|:-:|:-:|:-:|:-:| +| See everything on the aircraft | ✓ | ✓ | ✓ | ✓ | +| Log flights, correct the ones you logged | | ✓ | | ✓ | +| Update hours, report and defer squawks, add notes, oil and fuel | | ✓ | ✓ | ✓ | +| Sign logbook entries (with your own certificate) | | ✓ | ✓ | ✓ | +| Write logbook entries; components, inspections, ADs, major records, W&B, documents | | | ✓ | ✓ | +| Edit squawks and notes, resolve squawks; edit oil and fuel records | | | ✓ | ✓ | +| Weekly reminders and overdue alerts | | | ✓ | ✓ | +| Correct or delete any flight, imports, exports, restore from history | | | | ✓ | +| Edit the aircraft, manage people and share links | | | | ✓ | -Anyone can add an aircraft and becomes its owner. You only see aircraft you have a role on; admins see all of them. +Administrators can do everything on every aircraft, and manage users, roles, settings, procedures and audits for the whole app. Anyone can add an aircraft and becomes its Owner. You only see aircraft you have a role on; administrators see all of them. ## Finding your way around diff --git a/docs/guide/sharing.md b/docs/guide/sharing.md index e5ab970..41f28f7 100644 --- a/docs/guide/sharing.md +++ b/docs/guide/sharing.md @@ -1,10 +1,12 @@ # Access, sharing and transfer -**Access & sharing** is for the aircraft's owners: open it from **More** at the top of the aircraft's pages. +**Access & sharing** is for people whose role lets them manage the aircraft's people, share links or exports (Owners): open it from **More** at the top of the aircraft's pages. ## People -Add people by email as **owner** or **pilot** (they need an account; ask the administrator). Change or remove their role at any time. See the roles table in [Getting started](getting-started.md). +Add people by email with a role: **Owner**, **Mechanic**, **Pilot**, **Viewer**, or one the administrator added (they need an account; ask the administrator). Change or remove their role at any time; **What each role can do** on the page lists them. See the roles table in [Getting started](getting-started.md). + +Only an Owner can give or take away the Owner role, nobody can change their own, and an aircraft always keeps at least one Owner. An administrator can also give people roles on any aircraft from **Admin → Users**. ## Share links diff --git a/test/integration/aircraft_archive_flow_test.rb b/test/integration/aircraft_archive_flow_test.rb index a53d9e1..0c34f3b 100644 --- a/test/integration/aircraft_archive_flow_test.rb +++ b/test/integration/aircraft_archive_flow_test.rb @@ -98,7 +98,7 @@ class AircraftArchiveFlowTest < ActionDispatch::IntegrationTest assert_equal "done", import.status, import.error copy = import.aircraft assert_equal [ "N54321", "Cessna" ], [ copy.tail_number, copy.make ] - assert_equal [ "owner" ], copy.roles.where(user: @pilot).pluck(:role) # the importer owns the copy + assert_equal [ "owner" ], copy.roles.where(user: @pilot).map { _1.role.key } # the importer owns the copy assert_equal "notes.txt", copy.squawks.sole.attachments.sole.filename.to_s assert_equal 1, import.counts["logbook_entries"] diff --git a/test/integration/api_drafts_test.rb b/test/integration/api_drafts_test.rb index be19269..aacb032 100644 --- a/test/integration/api_drafts_test.rb +++ b/test/integration/api_drafts_test.rb @@ -70,7 +70,7 @@ class ApiDraftsTest < ActionDispatch::IntegrationTest test "drafts are for owners: an integration must act for one, with the drafts scope" do post "/api/v1/aircraft/#{@a.id}/draft_batches", params: batch_params, headers: headers(as: @mech), as: :json assert_response :forbidden - assert_equal "owners_only", JSON.parse(response.body).dig("error", "code") + assert_equal "not_permitted", JSON.parse(response.body).dig("error", "code") @token.update!(scopes: %w[read]) post "/api/v1/aircraft/#{@a.id}/draft_batches", params: batch_params, headers: headers(as: @owner), as: :json assert_equal "missing_scope", JSON.parse(response.body).dig("error", "code") diff --git a/test/integration/permissions_test.rb b/test/integration/permissions_test.rb index 9169097..08b6828 100644 --- a/test/integration/permissions_test.rb +++ b/test/integration/permissions_test.rb @@ -79,15 +79,20 @@ class PermissionsTest < ActionDispatch::IntegrationTest test "owner manages roles with last-owner protection" do sign_in @owner owner_role = @a.roles.find_by(user: @owner) - patch aircraft_aircraft_role_path(@a, owner_role), params: { role: "pilot" } - assert_equal "owner", owner_role.reload.role + patch aircraft_aircraft_role_path(@a, owner_role), params: { role_id: Role.for_key("pilot").id } + assert_equal "owner", owner_role.reload.role.key # not their own role newbie = create_user("newbie@example.com") - post aircraft_aircraft_roles_path(@a), params: { email_address: "NewBie@example.com ", role: "owner" } - assert_equal "owner", @a.roles.find_by(user: newbie).role + post aircraft_aircraft_roles_path(@a), params: { email_address: "NewBie@example.com ", role_id: Role.owner.id } + assert_equal "owner", @a.roles.find_by(user: newbie).role.key delete aircraft_aircraft_role_path(@a, owner_role) assert AircraftRole.exists?(owner_role.id), "can't remove self" + + newbie_role = @a.roles.find_by(user: newbie) + patch aircraft_aircraft_role_path(@a, newbie_role), params: { role_id: Role.for_key("mechanic").id } + assert_equal "mechanic", newbie_role.reload.role.key + assert_equal 1, @a.roles.owners.count end test "owner full workflow: component service, AD compliance, inspection" do diff --git a/test/integration/roles_test.rb b/test/integration/roles_test.rb new file mode 100644 index 0000000..3da1773 --- /dev/null +++ b/test/integration/roles_test.rb @@ -0,0 +1,169 @@ +require "test_helper" + +# Configurable roles (Role, Permission): what each built-in role can do, a +# custom role, who can hand out roles, administrators managing them, and +# that every action that changes something declares the permission it needs. +class RolesTest < ActionDispatch::IntegrationTest + setup do + @owner = create_user("owner@example.com") + @admin = create_user("admin@example.com", admin: true) + @a = create_aircraft(owner: @owner, tail_number: "N12345", tach_time: 1000) + end + + def member(email, role) + create_user(email).tap { @a.roles.create!(user: _1, role: role) } + end + + test "every action that changes something declares the permission it needs" do + missing = Rails.application.routes.routes.filter_map do |route| + verb, controller, action = route.verb, route.defaults[:controller], route.defaults[:action] + next if controller.blank? || verb.blank? || verb.match?(/\A(GET|HEAD)?\z/) + klass = "#{controller.camelize}Controller".safe_constantize + next unless klass && klass < ApplicationController && klass.include?(AircraftScoped) + next if klass._process_action_callbacks.none? { _1.filter == :authorize_permission! && _1.kind == :before } || + (klass == AircraftController && action == "create") # adding an aircraft makes you its Owner + rules = klass.permission_rules.select { |_, only, except| (only.nil? || only.include?(action)) && (except.nil? || except.exclude?(action)) } + "#{verb} #{controller}##{action}" if rules.empty? + end + assert_empty missing.uniq, "actions without a permission" + end + + test "the built-in roles: Owner has everything, the others their defaults, and none can be deleted" do + Role.ensure_built_in! + assert_equal Permission::ALL, Role.owner.permissions + assert_equal Permission::DEFAULTS["pilot"].sort, Role.for_key("pilot").permissions.sort + assert_empty Role.for_key("viewer").permissions + assert_not Role.for_key("pilot").destroy + Role.owner.update!(permissions: []) + assert_equal Permission::ALL, Role.owner.reload.permissions + end + + test "a viewer sees the records and can change nothing" do + viewer = member("viewer@example.com", "viewer") + sign_in viewer + get aircraft_path(@a) + assert_response :success + assert_select "a[href=?]", new_aircraft_flight_log_path(@a), 0 + assert_select "a[href=?]", new_aircraft_squawk_path(@a), 0 + assert_select "form[action=?]", hours_aircraft_path(@a), 0 + assert_select ".badge-gray", text: "Viewer" + + post aircraft_flight_logs_path(@a), params: { flight_log: { date: Date.current, tach_out: 1000, tach_in: 1001 } } + assert_redirected_to aircraft_path(@a) + assert_equal "Your role on this aircraft doesn't allow that.", flash[:alert] + post aircraft_squawks_path(@a), params: { squawk: { priority: 1, issue_reported: "x" } } + patch hours_aircraft_path(@a), params: { tach_time: 1010 } + post aircraft_notes_path(@a), params: { aircraft_note: { text: "hi" } } + assert_equal 0, @a.flight_logs.count + assert_equal 0, @a.squawks.count + assert_equal 0, @a.notes.count + assert_equal 1000, @a.reload.tach_time + end + + test "a mechanic maintains the aircraft but doesn't fly it or manage its people" do + mechanic = member("mech@example.com", "mechanic") + squawk = @a.squawks.create!(priority: 1, issue_reported: "Loose cowl") + sign_in mechanic + post aircraft_components_path(@a), params: { component: { component_type_id: component_type.id, manufacturer: "Lycoming", model: "O-320", date_in_service: Date.current } } + assert_equal 1, @a.components.count + patch aircraft_squawk_path(@a, squawk), params: { squawk: { issue_reported: "Loose cowl fastener" } } + assert_equal "Loose cowl fastener", squawk.reload.issue_reported + + post aircraft_flight_logs_path(@a), params: { flight_log: { date: Date.current, tach_out: 1000, tach_in: 1001 } } + assert_equal 0, @a.flight_logs.count + post aircraft_aircraft_roles_path(@a), params: { email_address: "owner@example.com", role_id: Role.for_key("viewer").id } + assert_equal "owner", @a.roles.find_by(user: @owner).role.key + get aircraft_aircraft_roles_path(@a) + assert_redirected_to aircraft_path(@a) + end + + test "a custom role gets exactly what's ticked, and managing people doesn't make you an Owner" do + role = Role.create!(name: "Partner", permissions: %w[log_flights manage_people]) + partner = member("partner@example.com", role) + sign_in partner + post aircraft_flight_logs_path(@a), params: { flight_log: { date: Date.current, tach_out: 1000, tach_in: 1001 } } + assert_equal 1, @a.flight_logs.count + post aircraft_squawks_path(@a), params: { squawk: { priority: 1, issue_reported: "x" } } + assert_equal 0, @a.squawks.count + + get aircraft_aircraft_roles_path(@a) + assert_response :success + assert_select "select[name=role_id] option", text: "Owner", count: 0 + newbie = create_user("newbie@example.com") + post aircraft_aircraft_roles_path(@a), params: { email_address: newbie.email_address, role_id: Role.owner.id } + assert_nil @a.roles.find_by(user: newbie) + post aircraft_aircraft_roles_path(@a), params: { email_address: newbie.email_address, role_id: Role.for_key("viewer").id } + assert_equal "viewer", @a.roles.find_by(user: newbie).role.key + + mine = @a.roles.find_by(user: partner) + patch aircraft_aircraft_role_path(@a, mine), params: { role_id: Role.owner.id } + assert_equal role, mine.reload.role + owners = @a.roles.find_by(user: @owner) + patch aircraft_aircraft_role_path(@a, owners), params: { role_id: Role.for_key("viewer").id } + delete aircraft_aircraft_role_path(@a, owners) + assert_equal "owner", owners.reload.role.key + end + + test "administrators manage roles: create, change, and delete only unused custom ones" do + sign_in @admin + get admin_roles_path + assert_select "tr.role-row", 4 + post admin_roles_path, params: { role: { name: "Instructor", description: "Teaches in it", permissions: [ "", "log_flights", "bogus" ] } } + role = Role.find_by!(name: "Instructor") + assert_equal %w[log_flights], role.permissions + + patch admin_role_path(role), params: { role: { name: "Instructor", permissions: [ "" ] } } + assert_empty role.reload.permissions + patch admin_role_path(Role.owner), params: { role: { name: "Owner", permissions: [ "" ] } } + assert_equal Permission::ALL, Role.owner.reload.permissions + + @a.roles.create!(user: create_user, role: role) + delete admin_role_path(role) + assert Role.exists?(role.id) + delete admin_role_path(Role.for_key("viewer")) + assert Role.for_key("viewer") + @a.roles.where(role: role).destroy_all + delete admin_role_path(role) + assert_not Role.exists?(role.id) + end + + test "administrators give people roles on any aircraft, keeping an Owner" do + person = create_user("person@example.com") + sign_in @admin + get edit_admin_user_path(person) + assert_select "#access select[name=aircraft_id] option", text: "N12345" + post admin_user_aircraft_roles_path(person), params: { aircraft_id: @a.id, role_id: Role.for_key("mechanic").id } + membership = @a.roles.find_by!(user: person) + assert_equal "mechanic", membership.role.key + + patch admin_user_aircraft_role_path(person, membership), params: { role_id: Role.owner.id } + assert_equal "owner", membership.reload.role.key + owner_membership = @a.roles.find_by(user: @owner) + delete admin_user_aircraft_role_path(@owner, owner_membership) + assert_not AircraftRole.exists?(owner_membership.id) + delete admin_user_aircraft_role_path(person, membership) + assert AircraftRole.exists?(membership.id), "the last Owner stays" + + sign_in create_user("nobody@example.com") + post admin_user_aircraft_roles_path(person), params: { aircraft_id: @a.id, role_id: Role.owner.id } + assert_equal 1, @a.roles.count + end + + test "reminders go to roles that get them" do + mechanic = member("mech@example.com", "mechanic") + pilot = member("pilot@example.com", "pilot") + @a.squawks.create!(priority: 0, issue_reported: "Grounding") + assert_equal [ @a ], ReminderMailer.items_for(@owner).map(&:first) + assert_equal [ @a ], ReminderMailer.items_for(mechanic).map(&:first) + assert_empty ReminderMailer.items_for(pilot) + end + + test "the API follows the person's role" do + viewer = member("viewer@example.com", "viewer") + token = ApiToken.create!(name: "script", kind: "personal", user: viewer, scopes: %w[read squawks:write]) + post "/api/v1/aircraft/#{@a.id}/squawks", params: { squawk: { issue_reported: "x", priority: 1 } }, + headers: { "Authorization" => "Bearer #{token.token}" }, as: :json + assert_response :forbidden + assert_equal "not_permitted", JSON.parse(response.body).dig("error", "code") + end +end diff --git a/test/integration/setup_test.rb b/test/integration/setup_test.rb index 70fc3f1..096b116 100644 --- a/test/integration/setup_test.rb +++ b/test/integration/setup_test.rb @@ -26,6 +26,6 @@ class SetupTest < ActionDispatch::IntegrationTest post aircraft_index_path, params: { aircraft: { tail_number: "N1", tach_time: 50 } } a = Aircraft.find_by!(tail_number: "N1") assert_redirected_to aircraft_path(a) - assert_equal "owner", user.role_for(a) + assert_equal "owner", user.role_for(a).key end end diff --git a/test/services/aircraft_archive_test.rb b/test/services/aircraft_archive_test.rb index 982705b..42b537f 100644 --- a/test/services/aircraft_archive_test.rb +++ b/test/services/aircraft_archive_test.rb @@ -83,7 +83,7 @@ class AircraftArchiveTest < ActiveSupport::TestCase assert_equal [ "N54321", "Cessna", "150", "C150", 2000 ], [ a.tail_number, a.make, a.model, a.icao_type, a.tach_time.to_i ] refute_equal original.id, a.id assert a.picture.attached? - assert_equal [ "owner" ], a.roles.where(user: other).pluck(:role) + assert_equal [ "owner" ], a.roles.where(user: other).map { _1.role.key } assert_equal 2, a.components.count oil = a.components.find_by(component_type: component_type("Oil")) assert_equal a.components.find_by(serial_number: "900001"), oil.parent_component
    <%= [row.next_due_date&.to_s, row.next_due_hours && "#{hours(row.next_due_hours)} h"].compact.join(" / ").presence || "—" %> <%= compliance_badge(row.status) %> - <% if owner? %> + <% if can?(:manage_inspections) %> <%= link_to t(".record"), new_aircraft_inspection_record_path(@aircraft, inspection_type_id: row.type.id), class: "btn-secondary btn-sm" %> <%= link_to t(".edit"), edit_aircraft_inspection_type_path(@aircraft, row.type), class: "btn-secondary btn-sm" %> <% end %> @@ -44,7 +44,7 @@ <%= r.inspection_type.name %><%= " (#{r.component})" if r.component %> <%= hours(r.hours_at_inspection) %> <%= r.notes %><% if r.logbook_entry %> <%= link_to "logbook", aircraft_logbook_entry_path(@aircraft, r.logbook_entry), class: "link" %><% end %><% if owner? %><%= link_to t(".edit"), edit_aircraft_inspection_record_path(@aircraft, r), class: "btn-secondary btn-sm" %><% end %><% if can?(:manage_inspections) %><%= link_to t(".edit"), edit_aircraft_inspection_record_path(@aircraft, r), class: "btn-secondary btn-sm" %><% end %>
    <%= s.component&.to_s || "—" %> <%= fmt_date(s.created_at.to_date) %>
    <%= s.reported_by&.display_name %>
    - <% if owner? %><%= link_to t(".resolve"), resolution_aircraft_squawk_path(aircraft, s), class: "btn-secondary btn-sm" %><% end %> + <% if can?(:manage_squawks) %><%= link_to t(".resolve"), resolution_aircraft_squawk_path(aircraft, s), class: "btn-secondary btn-sm" %><% end %> <% if s.deferred? %> - <% if owner? %><%= button_to t(".undo_deferral"), undefer_aircraft_squawk_path(aircraft, s), method: :patch, class: "btn-secondary btn-sm", form: { class: "inline" } %><% end %> + <% if can?(:manage_squawks) %><%= button_to t(".undo_deferral"), undefer_aircraft_squawk_path(aircraft, s), method: :patch, class: "btn-secondary btn-sm", form: { class: "inline" } %><% end %> <% else %> - <%= link_to t(".defer"), deferral_aircraft_squawk_path(aircraft, s), class: "btn-secondary btn-sm", title: t(".defer_as_inoperative_91_213") %> + <% if can?(:defer_squawks) %><%= link_to t(".defer"), deferral_aircraft_squawk_path(aircraft, s), class: "btn-secondary btn-sm", title: t(".defer_as_inoperative_91_213") %><% end %> <% end %> - <% if owner? %><%= link_to t(".edit"), edit_aircraft_squawk_path(aircraft, s), class: "btn-secondary btn-sm" %><% end %> + <% if can?(:manage_squawks) %><%= link_to t(".edit"), edit_aircraft_squawk_path(aircraft, s), class: "btn-secondary btn-sm" %><% end %>
    <%= s.issue_reported %><%= render "squawks/attachments", squawk: s %> <%= s.notes %><% if s.logbook_entry %>
    <%= link_to t(".logbook", date: fmt_date(s.logbook_entry.date)), aircraft_logbook_entry_path(@aircraft, s.logbook_entry), class: "link" %>
    <% end %>
    <%= fmt_date(s.resolved_at&.to_date) %><% if owner? %><%= button_to t(".reopen"), reopen_aircraft_squawk_path(@aircraft, s), method: :patch, class: "btn-secondary btn-sm" %><% end %><% if can?(:manage_squawks) %><%= button_to t(".reopen"), reopen_aircraft_squawk_path(@aircraft, s), method: :patch, class: "btn-secondary btn-sm" %><% end %>
    <%= r.reason %> <% if r.major_record %>
    <%= link_to r.major_record.title, aircraft_major_record_path(@aircraft, r.major_record), class: "link" %>
    <% end %> <% if r.document %>
    <%= link_to "📄 #{r.document.name}", aircraft_document_path(@aircraft, r.document), class: "link" %>
    <% end %>
    <% if owner? %><%= link_to t(".edit"), edit_aircraft_weight_balance_record_path(@aircraft, r), class: "btn-secondary btn-sm" %><% end %><% if can?(:manage_weight_balance) %><%= link_to t(".edit"), edit_aircraft_weight_balance_record_path(@aircraft, r), class: "btn-secondary btn-sm" %><% end %>