Invitation codes: a link that gives an account and roles

Ported from the original (InvitationCode), adapted to configurable roles.

- Admin → Invitations: a label, optionally one email address (only it can
  use the link, and it's emailed) and a name, how many uses (or
  unlimited), an expiry (or never), and a role on any aircraft (or none,
  for an account only).
- An aircraft's Access page: whoever manages its people invites to that
  aircraft, with only the roles they can give; they see and revoke its
  invitations.
- /join/<code>: shows what it gives; create an account (when password
  sign-in is on) or sign in, then accept. Existing accounts and SSO users
  accept too. A role someone already has on an aircraft stays.
- Roles are given as the invitation's creator (AircraftAccess), and only
  while they can still manage that aircraft's people. Codes are kept as
  digests and shown once; uses are counted under a lock; account creation
  and accepting are rate-limited; any invalid link gets the same answer.
- Docs: guide (Administration, Access & sharing), README, and why /join
  isn't on the Authentik bypass list. The README's not-yet-ported list
  now names Prometheus metrics, and no longer claims oil analysis import
  as new.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-15 18:50:58 -05:00
1 parent a645778f26
commit b4c7aaa3ff
34 files changed
+822 -7

No files matched your search

+4 -4
View File
@@ -160,7 +160,7 @@ To back up or move a single aircraft with all its files, use **More → Download
| Reminders | A Monday email to those whose role gets reminders (Owners and Mechanics by default) when something is overdue or coming due, plus push alerts when something becomes overdue, and to anyone whose certificate (e.g. an IA) is about to expire; admins also get the records audit due date (needs SMTP; users can turn it off). |
| Oil and fuel | Records, trend charts, and averages (last 20 intervals, IQR outlier filtering, manual exclusion). |
| Activity log | Every write is recorded as an `AircraftEvent`; the Activity tab loads them as you scroll. |
| Access | Configurable roles per aircraft (see [Roles](#roles)), plus share links (Current Status or Maintenance Detail, optional expiry, at most 10 per aircraft). Admins can disable accounts; a disabled account can't sign in or sign entries, and its past signatures stay. |
| Access | Configurable roles per aircraft (see [Roles](#roles)), invitation links (from Admin → Invitations or an aircraft's Access page; limited uses, expiry, optionally one email address) that give an account and roles, plus share links (Current Status or Maintenance Detail, optional expiry, at most 10 per aircraft). Admins can disable accounts; a disabled account can't sign in or sign entries, and its past signatures stay. |
| Sign-in security | Passwords of at least 12 characters, checked against known breaches (Have I Been Pwned, k-anonymity). 10 failed sign-ins in a row lock an account for 15 minutes from any address, and the user is emailed; admins can unlock. Optional authenticator-app (TOTP) codes with recovery codes for password and emailed-link sign-in and for signing entries; admins can reset them. Rate limits per address on every sign-in form. |
| Phones and offline | Installable (PWA). Flights and squawks logged without signal, or with one too weak to answer within 10 seconds, are kept on the device and sent later, never twice. The Fleet, Overview, W&B, Log Flight and Report Squawk pages are saved ahead of time; any other page falls back to an offline page. The top bar turns red when the server can't be reached, and a ring shows saving and sending progress. |
| REST API | Personal and integration tokens with scopes, read endpoints, squawks, draft logbook entries for signing in the app, and signed webhooks ([docs](docs/guide/api.md)). Follows the person's role. |
@@ -202,15 +202,15 @@ Users who aren't on an aircraft get a 404 for it, identical to a missing record.
Differences from the original:
- Integer primary keys instead of UUIDs. Share tokens are 32-character random strings.
- Logbook entries and inspection records don't keep many-to-many links to components. An inspection record or AD compliance can reference one component.
- Accounts are created by an admin, by the first-run setup, at first SSO sign-in (if `OIDC_AUTO_CREATE_USERS` is on), or by an outside mechanic accepting a signing invitation. The original's invitation codes aren't implemented yet.
- Accounts are created by an admin, by the first-run setup, at first SSO sign-in (if `OIDC_AUTO_CREATE_USERS` is on), by an outside mechanic accepting a signing invitation, or by someone opening an invitation link (Admin → Invitations, or an aircraft's Access page).
### Not yet ported
The MCP server for AI agents, invitation codes, per-aircraft feature switches, the plugin system, and the desktop builds.
The MCP server for AI agents, Prometheus metrics, per-aircraft feature switches (only airworthiness enforcement is here, as an aircraft setting), the plugin system, and the desktop builds.
### Added in this port
AirTrail sync and export, an airport database, FAA DRS AD import, spreadsheet flight import, engine monitor data (CGR-30P/C) with interactive charts, AvLab and Blackstone oil analysis import with trends, multiple squawk attachments with a photo viewer, AI logbook transcription with Claude (images and PDFs), printable logbook entries, electronic signatures and recordkeeping along the lines of AC 120-78B (record history, nightly integrity checks, records package, procedures and audits), off-site backup to Google Drive, a user guide, and an installable app (PWA) that logs flights and squawks offline, keeps pre-flight pages for use without signal, and sends push notifications.
AirTrail sync and export, an airport database, FAA DRS AD import, spreadsheet flight import, engine monitor data (CGR-30P/C) with interactive charts, multiple squawk attachments with a photo viewer, AI logbook transcription with Claude (images and PDFs), printable logbook entries, electronic signatures and recordkeeping along the lines of AC 120-78B (record history, nightly integrity checks, records package, procedures and audits), off-site backup to Google Drive, a user guide, and an installable app (PWA) that logs flights and squawks offline, keeps pre-flight pages for use without signal, and sends push notifications.
## Translating
@@ -0,0 +1,32 @@
# Invitation codes for any aircraft, or none (an account only), by
# administrators (AccessInvitation).
class Admin::InvitationsController < ApplicationController
before_action :require_admin!
def index
@invitations = AccessInvitation.recent_first.includes(:created_by, grants: %i[aircraft role]).limit(200)
end
def new
@invitation = AccessInvitation.new(max_uses: 1, expires_at: AccessInvitation::VALID_FOR.from_now.change(sec: 0))
end
def create
roles = Role.all.index_by(&:id)
grants = Aircraft.where(id: params.fetch(:roles, {}).keys).filter_map do |aircraft|
role = roles[params[:roles][aircraft.id.to_s].to_i]
[ aircraft, role ] if role
end
@invitation = AccessInvitation.create_for(current_user, params.require(:access_invitation).permit(:label, :email, :name, :max_uses, :expires_at), grants)
if @invitation.persisted?
render :created
else
render :new, status: :unprocessable_entity
end
end
def destroy
AccessInvitation.find(params[:id]).update!(revoked_at: Time.current)
redirect_to admin_invitations_path, notice: t("flash.admin_invitations.revoked")
end
end
@@ -0,0 +1,34 @@
# Invitation codes for one aircraft (AccessInvitation), from its Access page,
# by whoever manages its people: only the roles they can give (AircraftAccess).
class AircraftInvitationsController < ApplicationController
include AircraftScoped
requires_permission :manage_people
def create
role = AircraftAccess.new(@aircraft, actor: current_user).assignable_roles.find { _1.id == params[:role_id].to_i }
return back(alert: t("services.aircraft_access.owner_only")) unless role
attributes = params.permit(:label, :email, :name, :max_uses, :expires_at).to_h.symbolize_keys
attributes[:label] = t("flash.aircraft_invitations.default_label", tail_number: @aircraft.tail_number) if attributes[:label].blank?
@invitation = AccessInvitation.create_for(current_user, attributes, [ [ @aircraft, role ] ])
return back(alert: @invitation.errors.full_messages.to_sentence) unless @invitation.persisted?
log_event("role", t("flash.aircraft_invitations.created_event", role: role.name), notes: @invitation.label)
render :created
end
# Only invitations for this aircraft alone; others are managed in Admin → Invitations.
def destroy
invitation = AccessInvitation.where(id: self.class.only_for(@aircraft)).find(params[:id])
invitation.update!(revoked_at: Time.current)
log_event("role", t("flash.aircraft_invitations.revoked_event"), notes: invitation.label)
back(notice: t("flash.aircraft_invitations.revoked"))
end
# Ids of the invitations that give a role on this aircraft and no other.
def self.only_for(aircraft)
AccessInvitationRole.group(:access_invitation_id).having("COUNT(*) = 1 AND MAX(aircraft_id) = ?", aircraft.id).select(:access_invitation_id)
end
private
def back(flash) = redirect_to(aircraft_aircraft_roles_path(@aircraft, anchor: "invitations"), flash)
end
@@ -11,6 +11,8 @@ class AircraftRolesController < ApplicationController
@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)
@invitations = AccessInvitation.where(id: AircraftInvitationsController.only_for(@aircraft), revoked_at: nil)
.recent_first.includes(:created_by, grants: :role).limit(20)
end
def create
+71
View File
@@ -0,0 +1,71 @@
# Opening an invitation link (AccessInvitation): see what it gives, then
# create an account (when sign-in by password is on) or sign in, and accept.
# An invitation for one email address only works for that address. An
# invalid link (unknown, expired, used up, revoked) gets one answer for all.
class JoinsController < ApplicationController
allow_unauthenticated_access only: %i[show account]
before_action :set_invitation
rate_limit to: 10, within: 15.minutes, only: %i[account accept],
with: -> { redirect_to join_path(params[:token]), alert: t("flash.joins.try_again_later") }
def show
unless current_user
session[:return_to_after_authenticating] = request.url
return render(:welcome)
end
return redirect_to(root_path, notice: t("flash.joins.already_accepted")) if @invitation.redeemed_by?(current_user)
return render(:wrong_account) unless @invitation.for?(current_user)
render :accept
end
# A new account, then the invitation accepted with it.
def account
return redirect_to(join_path(params[:token])) if current_user
return redirect_to(join_path(params[:token]), alert: t("flash.joins.sign_in_to_continue")) unless Sso.password_login?
email = @invitation.email || params[:email_address].to_s.strip.downcase
if User.exists?(email_address: email)
return redirect_to join_path(params[:token]), alert: t("flash.joins.account_exists")
end
user = User.new(params.permit(:name, :password, :password_confirmation).merge(email_address: email))
results = nil
User.transaction do
raise ActiveRecord::Rollback unless user.save
results = @invitation.redeem!(user)
end
if results
reset_session
start_new_session_for user
redirect_to root_path, notice: summary(results, t("flash.joins.welcome"))
else
@account_errors = user.errors.full_messages
render :welcome, status: :unprocessable_entity
end
rescue ActiveRecord::RecordInvalid
render :invalid, layout: "public", status: :not_found
end
def accept
return redirect_to(root_path, notice: t("flash.joins.already_accepted")) if @invitation.redeemed_by?(current_user)
return render(:wrong_account) unless @invitation.for?(current_user)
redirect_to root_path, notice: summary(@invitation.redeem!(current_user), t("flash.joins.accepted"))
rescue ActiveRecord::RecordInvalid
render :invalid, layout: "public", status: :not_found
end
private
def set_invitation
@invitation = AccessInvitation.find_by_token(params[:token])
render :invalid, layout: "public", status: :not_found unless @invitation&.usable?
end
# "Invitation accepted. N12345: Mechanic. N54321: already Owner, unchanged."
def summary(results, lead)
parts = results.map do |aircraft, role, message|
"#{aircraft.tail_number}: #{[ role&.name, message ].compact.join(', ')}"
end
[ lead, *parts ].join(" ")
end
def current_user = Current.user || (resume_session && Current.user)
end
+9
View File
@@ -0,0 +1,9 @@
# The link of an invitation made for one email address (AccessInvitation).
class AccessInvitationMailer < ApplicationMailer
def invite(invitation, token)
@invitation = invitation
@grants = invitation.grants.includes(:aircraft, :role).sort_by { _1.aircraft.tail_number }
@url = join_url(token)
mail subject: t(".subject", who: invitation.created_by&.display_name || t(".an_administrator")), to: invitation.email
end
end
+74
View File
@@ -0,0 +1,74 @@
# An invitation code: a link someone opens to create an account (or accept
# with the one they have) and get roles on aircraft. Made by administrators
# (Admin → Invitations, any aircraft) or by whoever manages an aircraft's
# people (its Access page, that aircraft). Limited by number of uses, an
# expiry, and optionally to one email address; it can be revoked. Only a
# digest of the code is kept, so the link is shown once, when it's made.
class AccessInvitation < ApplicationRecord
VALID_FOR = 14.days
belongs_to :created_by, class_name: "User", optional: true
has_many :grants, class_name: "AccessInvitationRole", dependent: :delete_all
has_many :redemptions, class_name: "AccessInvitationRedemption", dependent: :delete_all
has_many :aircraft, through: :grants
attr_reader :token
normalizes :email, with: ->(email) { email.strip.downcase.presence }
normalizes :label, :name, with: ->(text) { text.squish.presence }
validates :label, presence: true, length: { maximum: 100 }
validates :email, format: { with: URI::MailTo::EMAIL_REGEXP }, allow_nil: true
validates :max_uses, numericality: { only_integer: true, greater_than: 0, less_than_or_equal_to: 1000 }, allow_nil: true
before_validation(on: :create) do
@token = SecureRandom.urlsafe_base64(24)
self.token_digest = self.class.digest(@token)
end
scope :recent_first, -> { order(created_at: :desc) }
scope :usable, -> {
where(revoked_at: nil).where("expires_at IS NULL OR expires_at > ?", Time.current).where("max_uses IS NULL OR uses_count < max_uses")
}
# A new invitation by creator giving roles ([[aircraft, role], …]); its
# link is emailed when it's for one address and email is set up.
def self.create_for(creator, attributes, grants)
invitation = new(attributes.merge(created_by: creator))
grants.each { |aircraft, role| invitation.grants.build(aircraft: aircraft, role: role) }
if invitation.save && invitation.email && MailSettings.configured?
AccessInvitationMailer.invite(invitation, invitation.token).deliver_later
end
invitation
end
def self.digest(token) = OpenSSL::Digest::SHA256.hexdigest(token.to_s)
def self.find_by_token(token) = token.present? ? find_by(token_digest: digest(token)) : nil
def usable? = !revoked? && !expired? && !used_up?
def revoked? = revoked_at.present?
def expired? = expires_at.present? && expires_at <= Time.current
def used_up? = max_uses.present? && uses_count >= max_uses
def for?(user) = email.nil? || email == user.email_address
def redeemed_by?(user) = redemptions.exists?(user: user)
# Gives the person the invitation's roles, as if its creator added them
# (AircraftAccess: so it can't give more than they could, then or now).
# A role they already have on an aircraft stays as it is. Returns
# [[aircraft, role or nil, message or nil], …].
def redeem!(user)
with_lock do
raise ActiveRecord::RecordInvalid, self unless usable? && for?(user)
redemptions.create!(user: user)
increment!(:uses_count)
grants.includes(:aircraft, :role).map do |grant|
if (existing = grant.aircraft.roles.find_by(user: user))
[ grant.aircraft, nil, I18n.t("models.access_invitation.already_has", role: existing.role.name) ]
elsif created_by.nil? || created_by.disabled? || !created_by.can?(:manage_people, grant.aircraft)
[ grant.aircraft, nil, I18n.t("models.access_invitation.creator_gone") ]
else
error = AircraftAccess.new(grant.aircraft, actor: created_by).add(user, grant.role)
[ grant.aircraft, (grant.role unless error), error ]
end
end
end
end
end
@@ -0,0 +1,7 @@
# Who used an invitation, and when (once per person).
class AccessInvitationRedemption < ApplicationRecord
belongs_to :access_invitation
belongs_to :user
validates :user_id, uniqueness: { scope: :access_invitation_id }
end
+8
View File
@@ -0,0 +1,8 @@
# A role an invitation gives on one aircraft.
class AccessInvitationRole < ApplicationRecord
belongs_to :access_invitation
belongs_to :aircraft
belongs_to :role
validates :aircraft_id, uniqueness: { scope: :access_invitation_id }
end
+1
View File
@@ -9,6 +9,7 @@ class Aircraft < ApplicationRecord
end
has_many :roles, class_name: "AircraftRole", dependent: :destroy
has_many :invitation_grants, class_name: "AccessInvitationRole", dependent: :delete_all
has_many :users, through: :roles
has_many :notes, class_name: "AircraftNote", dependent: :destroy
has_many :events, class_name: "AircraftEvent", dependent: :delete_all
+1
View File
@@ -7,6 +7,7 @@ class Role < ApplicationRecord
BUILT_IN = %w[owner mechanic pilot viewer].freeze
has_many :aircraft_roles, dependent: :restrict_with_error
has_many :invitation_grants, class_name: "AccessInvitationRole", dependent: :delete_all
normalizes :name, with: ->(name) { name.squish }
validates :name, presence: true, uniqueness: { case_sensitive: false }, length: { maximum: 40 }
+2
View File
@@ -2,6 +2,8 @@ class User < ApplicationRecord
has_secure_password
has_many :sessions, dependent: :destroy
has_many :aircraft_roles, dependent: :destroy
has_many :access_invitations, foreign_key: :created_by_id, dependent: :nullify, inverse_of: :created_by
has_many :access_invitation_redemptions, dependent: :delete_all
has_many :push_subscriptions, dependent: :delete_all
has_many :api_tokens, dependent: :destroy
@@ -0,0 +1,4 @@
<p><%= t(".invites_you_html", who: (@invitation.created_by&.display_name || t(".an_administrator"))) %></p>
<% if @grants.any? %><ul><% @grants.each do |g| %><li><strong><%= g.aircraft.tail_number %></strong>: <%= g.role.name %></li><% end %></ul><% end %>
<p><%= link_to t(".accept_the_invitation"), @url %></p>
<% if @invitation.expires_at %><p style="color:#64748b;font-size:12px"><%= t(".expires_html", date: fmt_date(@invitation.expires_at.to_date)) %></p><% end %>
@@ -0,0 +1,11 @@
<%= raw t(".invites_you_text", who: (@invitation.created_by&.display_name || t(".an_administrator"))) %>
<% @grants.each do |g| %>
- <%= g.aircraft.tail_number %>: <%= g.role.name %>
<% end %>
<%= raw t(".open_the_link_text") %>
<%= @url %>
<% if @invitation.expires_at %>
<%= raw t(".expires_text", date: fmt_date(@invitation.expires_at.to_date)) %>
<% end %>
@@ -0,0 +1,2 @@
<% content_for :title, t("shared.invitation_created.title") %>
<%= render "shared/invitation_created", invitation: @invitation, back_path: admin_invitations_path %>
@@ -0,0 +1,28 @@
<% content_for :title, t(".invitations") %>
<div class="mb-2 flex items-center justify-between"><h1 class="text-2xl font-bold"><%= t(".invitations") %></h1><%= link_to t(".new_invitation"), new_admin_invitation_path, class: "btn-primary" %></div>
<p class="mb-4 text-sm text-slate-600"><%= t(".intro") %></p>
<section class="card">
<% if @invitations.any? %>
<table class="table">
<thead><tr><th><%= t(".label") %></th><th><%= t(".gives") %></th><th><%= t(".uses") %></th><th><%= t(".status") %></th><th></th></tr></thead>
<tbody>
<% @invitations.each do |inv| %>
<tr class="invitation-row">
<td><span class="font-medium"><%= inv.label %></span><div class="text-xs text-slate-500"><%= [ inv.email, inv.created_by&.display_name, fmt_date(inv.created_at) ].compact.join(" · ") %></div></td>
<td class="text-xs" data-label="<%= t(".gives") %>"><%= inv.grants.map { "#{_1.aircraft.tail_number} (#{_1.role.name})" }.join(", ").presence || t(".account_only") %></td>
<td class="tabular-nums" data-label="<%= t(".uses") %>"><%= inv.uses_count %> / <%= inv.max_uses || "∞" %></td>
<td data-label="<%= t(".status") %>">
<% if inv.revoked? %><span class="badge-gray"><%= t(".revoked") %></span>
<% elsif inv.expired? %><span class="badge-red"><%= t(".expired") %></span>
<% elsif inv.used_up? %><span class="badge-gray"><%= t(".used") %></span>
<% else %><span class="badge-green"><%= t(".active") %></span><span class="block text-xs text-slate-500"><%= inv.expires_at ? t(".until", time: l(inv.expires_at, format: :app)) : t(".never_expires") %></span><% end %>
</td>
<td class="text-right"><% if inv.usable? %><%= delete_button t(".revoke"), admin_invitation_path(inv), confirm: t(".revoke_invitation") %><% end %></td>
</tr>
<% end %>
</tbody>
</table>
<% else %>
<%= empty_state t(".no_invitations") %>
<% end %>
</section>
+29
View File
@@ -0,0 +1,29 @@
<% content_for :title, t(".new_invitation") %>
<h1 class="mb-4 text-2xl font-bold"><%= t(".new_invitation") %></h1>
<%= form_with model: @invitation, url: admin_invitations_path, method: :post, class: "card card-body max-w-3xl space-y-5" do |f| %>
<%= f.errors_summary %>
<div class="grid gap-4 sm:grid-cols-2">
<%= f.field :label, required: true, hint: t(".label_hint") %>
<%= f.field :email, as: :email, label: t(".email"), hint: t(".email_hint") %>
<%= f.field :name, label: t(".name"), hint: t(".name_hint") %>
<%= f.field :max_uses, as: :number, label: t(".max_uses"), hint: t(".max_uses_hint"), min: 1, max: 1000 %>
<%= f.field :expires_at, as: :datetime, label: t(".expires"), hint: t(".expires_hint") %>
</div>
<fieldset>
<legend class="mb-2 text-sm font-semibold"><%= t(".roles") %></legend>
<% aircraft = Aircraft.ordered.to_a %>
<% if aircraft.any? %>
<div class="grid gap-2 sm:grid-cols-2">
<% roles = Role.ordered.map { [ _1.name, _1.id ] } %>
<% aircraft.each do |a| %>
<label class="flex items-center justify-between gap-3 text-sm">
<span><span class="font-medium"><%= a.tail_number %></span> <span class="text-xs text-slate-500"><%= [ a.make, a.model ].compact_blank.join(" ") %></span></span>
<%= select_tag "roles[#{a.id}]", options_for_select([ [ t(".no_access"), "" ] ] + roles, params.dig(:roles, a.id.to_s)), class: "input w-36" %>
</label>
<% end %>
</div>
<% end %>
<p class="hint mt-2"><%= t(".roles_hint") %></p>
</fieldset>
<div class="flex flex-wrap gap-2"><%= f.submit t(".create") %><%= link_to t(".cancel"), admin_invitations_path, class: "btn-secondary" %></div>
<% end %>
@@ -0,0 +1,3 @@
<% content_for :title, t("shared.invitation_created.title") %>
<%= render "shared/aircraft_header", aircraft: @aircraft %>
<%= render "shared/invitation_created", invitation: @invitation, back_path: aircraft_aircraft_roles_path(@aircraft, anchor: "invitations") %>
+32
View File
@@ -38,6 +38,38 @@
<p class="hint mt-2"><%= t(".roles_are_set_by_an_administrator") %></p>
</details>
</section>
<%# Invitation codes for this aircraft (AircraftInvitationsController). %>
<section class="card" id="invitations">
<div class="card-header"><h2 class="card-title"><%= t(".invitations") %></h2></div>
<% if @invitations.any? %>
<ul class="divide-y divide-slate-100">
<% @invitations.each do |inv| %>
<li class="flex flex-wrap items-center justify-between gap-2 px-4 py-3 text-sm">
<div>
<span class="font-medium"><%= inv.label %></span>
<span class="badge-blue"><%= inv.grants.first&.role&.name %></span>
<% if inv.expired? %><span class="badge-red"><%= t(".expired") %></span><% elsif inv.used_up? %><span class="badge-gray"><%= t(".used") %></span><% end %>
<div class="text-xs text-slate-500"><%= [ inv.email, t(".uses_html", used: inv.uses_count, max: inv.max_uses || "∞"), (inv.expires_at ? t(".until", time: l(inv.expires_at, format: :app)) : t(".never_expires")), inv.created_by&.display_name ].compact.join(" · ") %></div>
</div>
<% if inv.usable? %><%= delete_button t(".revoke"), aircraft_invitation_path(@aircraft, inv), confirm: t(".revoke_invitation") %><% end %>
</li>
<% end %>
</ul>
<% else %>
<%= empty_state t(".no_invitations") %>
<% end %>
<%= form_with url: aircraft_invitations_path(@aircraft), class: "space-y-3 border-t border-slate-100 p-4" do |f| %>
<div class="grid gap-3 sm:grid-cols-2">
<div><%= f.label :email, t(".invite_email"), class: "label" %><%= f.email_field :email, class: "input", placeholder: t(".optional") %></div>
<div><%= 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" %></div>
<div><%= f.label :max_uses, t(".max_uses"), class: "label" %><%= f.number_field :max_uses, value: 1, min: 1, max: 1000, class: "input" %></div>
<div><%= f.label :expires_at, t(".expires"), class: "label" %><%= f.datetime_field :expires_at, value: AccessInvitation::VALID_FOR.from_now.strftime("%Y-%m-%dT%H:%M"), class: "input" %></div>
</div>
<p class="hint"><%= t(".invitation_hint") %></p>
<%= f.submit t(".create_invitation"), class: "btn-primary" %>
<% end %>
</section>
<% end %>
<% if can?(:manage_sharing) %>
+11
View File
@@ -0,0 +1,11 @@
<%# What the invitation gives: a role on each of its aircraft (or just an account). %>
<% grants = invitation.grants.includes(:aircraft, :role).sort_by { _1.aircraft.tail_number } %>
<% if grants.any? %>
<ul class="space-y-1 text-sm">
<% grants.each do |g| %>
<li class="flex items-baseline gap-2"><span class="font-semibold"><%= g.aircraft.tail_number %></span> <span class="text-slate-500"><%= [ g.aircraft.make, g.aircraft.model ].compact_blank.join(" ") %></span> <span class="badge-blue" title="<%= g.role.description %>"><%= g.role.name %></span></li>
<% end %>
</ul>
<% else %>
<p class="text-sm text-slate-600"><%= t("joins.grants.account_only") %></p>
<% end %>
+11
View File
@@ -0,0 +1,11 @@
<% content_for :title, t(".invitation") %>
<div class="mx-auto max-w-md space-y-4">
<h1 class="text-2xl font-bold"><%= t(".youre_invited") %></h1>
<div class="card card-body space-y-3">
<p class="text-sm text-slate-600"><%= t(".invited_by_html", who: (@invitation.created_by&.display_name || t(".an_administrator")), label: @invitation.label) %></p>
<%= render "joins/grants", invitation: @invitation %>
<p class="hint"><%= t(".existing_roles_stay") %></p>
<%= button_to t(".accept"), accept_join_path(params[:token]), class: "btn-primary w-full justify-center", form: { class: "pt-1" } %>
</div>
<p class="text-center text-sm text-slate-500"><%= t(".signed_in_as", email: current_user.email_address) %></p>
</div>
+5
View File
@@ -0,0 +1,5 @@
<% content_for :title, t(".invitation") %>
<div class="mx-auto max-w-md card card-body">
<h1 class="card-title"><%= t(".not_valid") %></h1>
<p class="mt-1 text-sm text-slate-600"><%= t(".ask_for_a_new_one") %></p>
</div>
+27
View File
@@ -0,0 +1,27 @@
<% content_for :title, t(".invitation") %>
<div class="mx-auto max-w-md space-y-4">
<h1 class="text-2xl font-bold"><%= t(".youre_invited") %></h1>
<div class="card card-body space-y-3">
<p class="text-sm text-slate-600"><%= t(".invited_by_html", who: (@invitation.created_by&.display_name || t(".an_administrator")), label: @invitation.label) %></p>
<%= render "joins/grants", invitation: @invitation %>
</div>
<div class="card card-body space-y-3">
<%= link_to t(".i_have_an_account"), new_session_path, class: "btn-primary w-full justify-center" %>
<% if @invitation.email %><p class="hint"><%= t(".for_email", email: @invitation.email) %></p><% end %>
</div>
<% if Sso.password_login? && !(@invitation.email && User.exists?(email_address: @invitation.email)) %>
<%= form_with url: account_join_path(params[:token]), class: "card card-body space-y-3" do %>
<h2 class="card-title"><%= t(".or_create_an_account") %></h2>
<% if @account_errors.present? %><div class="rounded-md bg-red-50 p-2 text-sm text-red-700" role="alert"><%= @account_errors.to_sentence %></div><% end %>
<% if @invitation.email %>
<div><label class="label" for="invited_email"><%= t(".email") %></label><input id="invited_email" class="input" value="<%= @invitation.email %>" disabled></div>
<% else %>
<div><%= label_tag :email_address, t(".email"), class: "label" %><%= email_field_tag :email_address, params[:email_address], class: "input", required: true, autocomplete: "username" %></div>
<% end %>
<div><%= label_tag :name, t(".your_name"), class: "label" %><%= text_field_tag :name, params[:name] || @invitation.name, class: "input", required: true, autocomplete: "name" %></div>
<div><%= label_tag :password, t(".password"), class: "label" %><%= password_field_tag :password, nil, class: "input", required: true, autocomplete: "new-password", minlength: User::PASSWORD_MIN, maxlength: 72 %><p class="hint"><%= t(".password_hint", min: User::PASSWORD_MIN) %></p></div>
<div><%= label_tag :password_confirmation, t(".confirm_password"), class: "label" %><%= password_field_tag :password_confirmation, nil, class: "input", required: true, autocomplete: "new-password" %></div>
<%= submit_tag t(".create_account"), class: "btn-secondary", data: { turbo_submits_with: t(".creating") } %>
<% end %>
<% end %>
</div>
+6
View File
@@ -0,0 +1,6 @@
<% content_for :title, t(".invitation") %>
<div class="mx-auto max-w-md card card-body space-y-3">
<h1 class="card-title"><%= t(".wrong_account") %></h1>
<p class="text-sm text-slate-600"><%= t(".for_another_email_html", email: @invitation.email, email_address: current_user.email_address) %></p>
<%= button_to t(".sign_out"), session_path, method: :delete, class: "btn-secondary" %>
</div>
+2 -2
View File
@@ -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? %>
<p class="border-t border-slate-100 px-4 pt-2 pb-1 text-xs font-semibold text-slate-500"><%= t(".admin") %></p>
<% [ [ 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| %>
<% [ [ t(".users"), admin_users_path ], [ t(".roles"), admin_roles_path ], [ t(".invitations"), admin_invitations_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") %> <span aria-hidden="true" class="text-xs">▾</span>
</summary>
<div class="absolute right-0 z-30 mt-2 w-48 rounded-md bg-surface py-1 text-slate-700 shadow-lg ring-1 ring-slate-200">
<% [ [ 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| %>
<% [ [ t(".users"), admin_users_path ], [ t(".roles"), admin_roles_path ], [ t(".invitations"), admin_invitations_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 %>
</div>
@@ -0,0 +1,14 @@
<%# A just-made invitation's link: shown this once (only a digest is kept). %>
<section class="card card-body max-w-xl space-y-3">
<h1 class="card-title"><%= t("shared.invitation_created.title") %></h1>
<p class="text-sm text-slate-600"><%= t("shared.invitation_created.copy_now") %></p>
<input type="text" class="input font-mono text-xs" value="<%= join_url(invitation.token) %>" readonly data-select-on-click aria-label="<%= t("shared.invitation_created.link") %>">
<%= render "joins/grants", invitation: invitation %>
<p class="hint">
<%= [ (t("shared.invitation_created.emailed", email: invitation.email) if invitation.email && MailSettings.configured?),
(t("shared.invitation_created.only_for", email: invitation.email) if invitation.email),
(invitation.max_uses ? t("shared.invitation_created.uses", count: invitation.max_uses) : t("shared.invitation_created.unlimited")),
(invitation.expires_at ? t("shared.invitation_created.expires", time: l(invitation.expires_at, format: :app)) : t("shared.invitation_created.never_expires")) ].compact.join(" ") %>
</p>
<p><%= link_to t("shared.invitation_created.done"), back_path, class: "btn-primary" %></p>
</section>
+126
View File
@@ -562,6 +562,9 @@ en:
notes: Notes
reason: Reason
models:
access_invitation:
already_has: already %{role}, unchanged
creator_gone: not given (whoever made the invitation can't give roles any more)
logbook_entry:
inspection_blank: a ______________
inspection_a: a %{name}
@@ -875,6 +878,20 @@ en:
one: Imported %{count} flight.
other: Imported %{count} flights.
flights_imported_but_aircraft: 'Flights imported, but aircraft hours weren''t updated: the aircraft is grounded and enforcement is on.'
joins:
try_again_later: Too many tries; wait a few minutes.
already_accepted: You've already accepted this invitation.
sign_in_to_continue: Sign in to accept the invitation.
account_exists: There's already an account for that email address. Sign in, then open the link again.
welcome: Welcome! Your account is ready.
accepted: Invitation accepted.
aircraft_invitations:
default_label: Invitation to %{tail_number}
created_event: Invitation made (%{role})
revoked_event: Invitation revoked
revoked: Invitation revoked.
admin_invitations:
revoked: Invitation revoked.
aircraft_roles:
no_user_with_that: No user with that email. Ask an administrator to create their account first.
added: "%{display_name} added."
@@ -1224,6 +1241,41 @@ en:
matches: Matches
update: Update
admin:
invitations:
index:
invitations: Invitations
new_invitation: New invitation
intro: An invitation is a link someone opens to create an account, or accept with the one they have, and get roles on aircraft. An aircraft's Owner can also invite people to that aircraft from its Access page.
label: Invitation
gives: Gives
uses: Used
status: Status
account_only: An account only
revoked: Revoked
expired: Expired
used: Used up
active: Active
until: until %{time}
never_expires: never expires
revoke: Revoke
revoke_invitation: Revoke this invitation? Its link stops working; people who already used it keep their access.
no_invitations: No invitations yet.
new:
new_invitation: New Invitation
label_hint: For you, e.g. "Flying club pilots, spring 2027".
email: Email (optional)
email_hint: Only that address can use it; the link is emailed to it when email is set up.
name: Name (optional)
name_hint: Filled in when they create their account.
max_uses: Uses
max_uses_hint: Empty for unlimited.
expires: Expires
expires_hint: Empty for never.
roles: Roles on aircraft
no_access: No access
roles_hint: Where they already have a role, it stays as it is.
create: Create invitation
cancel: Cancel
roles:
index:
roles: Roles
@@ -1901,6 +1953,21 @@ en:
role_for: Role for %{display_name}
role: Role
what_each_role_can_do: What each role can do
invitations: Invitations
expired: Expired
used: Used
uses_html: "%{used} of %{max} used"
until: until %{time}
never_expires: never expires
revoke: Revoke
revoke_invitation: Revoke this invitation? Its link stops working; people who already used it keep their access.
no_invitations: No open invitations.
invite_email: Email
optional: Optional
max_uses: Uses
expires: Expires
invitation_hint: A link that gives the role on this aircraft to whoever opens it, with a new or existing account. With an email, it only works for that address (and is emailed to it when email is set up). Leave the expiry empty for never, or the uses empty for unlimited.
create_invitation: Create invitation
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
@@ -2649,6 +2716,7 @@ en:
layouts:
application:
roles: Roles
invitations: Invitations
integrations: Integrations
skip_to_content_html: <a href="#main" class="skip-link">Skip to content</a>
simple_aircraft_manager: Simple Aircraft Manager
@@ -3315,6 +3383,19 @@ en:
simple_aircraft_manager_is_provided: Simple Aircraft Manager is provided as is, without warranty, and is not approved by the FAA or any other aviation authority. It is up to you to verify that using it for your aircraft and operation is legal and suitable. The full disclaimer is under Help once you're signed in.
create_admin_account: Create Admin Account
shared:
invitation_created:
title: Invitation created
copy_now: Copy the link now and send it to the person; it isn't shown again (only a fingerprint of it is kept).
link: Invitation link
emailed: Emailed to %{email}.
only_for: Only works for %{email}.
uses:
one: Works once.
other: Works %{count} times.
unlimited: Works any number of times.
expires: Until %{time}.
never_expires: Never expires.
done: Done
aircraft_header:
admin: Admin
tach_hobbs_html: Tach %{tach_time} · Hobbs %{hobbs_time}
@@ -3397,6 +3478,51 @@ en:
statement_2_text: 'Statement: %{statement}'
fingerprint_text: 'Fingerprint: %{content_digest}'
subject: You signed a logbook entry for %{tail_number}
access_invitation_mailer:
invite:
subject: "%{who} invites you to Simple Aircraft Manager"
an_administrator: An administrator
invites_you_text: "%{who} invites you to Simple Aircraft Manager:"
invites_you_html: "%{who} invites you to Simple Aircraft Manager:"
open_the_link_text: 'Open this link to create your account, or accept with the one you have:'
accept_the_invitation: Accept the invitation
expires_text: The link works until %{date}.
expires_html: The link works until %{date}.
joins:
grants:
account_only: An account (no aircraft yet).
welcome:
invitation: Invitation
youre_invited: You're invited
invited_by_html: "<strong>%{who}</strong> invites you (%{label}):"
an_administrator: An administrator
i_have_an_account: I have an account – sign in
for_email: This invitation is for %{email}.
or_create_an_account: Or create an account
email: Email
your_name: Your name
password: Password
password_hint: At least %{min} characters.
confirm_password: Confirm password
create_account: Create account and accept
creating: Creating…
accept:
invitation: Invitation
youre_invited: You're invited
invited_by_html: "<strong>%{who}</strong> invites you (%{label}):"
an_administrator: An administrator
existing_roles_stay: Where you already have a role, it stays as it is.
accept: Accept invitation
signed_in_as: Signed in as %{email}
wrong_account:
invitation: Invitation
wrong_account: This invitation is for someone else
for_another_email_html: It's for <strong>%{email}</strong>, but you're signed in as %{email_address}. Sign out and sign in (or create an account) with that address.
sign_out: Sign out
invalid:
invitation: Invitation
not_valid: This invitation isn't valid
ask_for_a_new_one: It may have expired, been used up or revoked. Ask whoever sent it for a new one.
signing_invitation_mailer:
invite:
asks_you_to_sign_a_html: "%{owner} asks you to sign a logbook entry for <strong>%{tail_number}</strong> (%{date}, %{log_type} log)."
+6
View File
@@ -112,6 +112,7 @@ Rails.application.routes.draw do
resource :loading_setup, path: "weight_balance/loading", only: %i[edit update] # before the records' :id routes
resources :weight_balance_records, path: "weight_balance", except: :show
resources :aircraft_roles, path: "access", only: %i[index create update destroy]
resources :invitations, controller: "aircraft_invitations", only: %i[create destroy]
resources :share_tokens, only: %i[create destroy]
resource :export, controller: "aircraft_exports", only: :show
resource :report, controller: "maintenance_reports", only: :show
@@ -131,6 +132,10 @@ Rails.application.routes.draw do
# Public read-only share links (no login).
# Invited signers (outside mechanics) sign one entry.
get "sign/:token", to: "invited_signings#show", as: :invited_signing
# Invitation codes (AccessInvitation): an account and roles on aircraft.
get "join/:token", to: "joins#show", as: :join
post "join/:token/accept", to: "joins#accept", as: :accept_join
post "join/:token/account", to: "joins#account", as: :account_join
post "sign/:token", to: "invited_signings#create"
post "sign/:token/account", to: "invited_signings#account", as: :account_invited_signing
@@ -175,6 +180,7 @@ Rails.application.routes.draw do
resources :aircraft_roles, controller: "user_aircraft_roles", only: %i[create update destroy]
end
resources :roles, except: :show
resources :invitations, only: %i[index new create destroy]
resources :integrations do
post :new_secret, on: :member
end
@@ -0,0 +1,34 @@
# Invitation codes (AccessInvitation): a link someone opens to create an
# account, or accept with the one they have, and get roles on aircraft.
class CreateAccessInvitations < ActiveRecord::Migration[8.1]
def change
create_table :access_invitations do |t|
t.string :label, null: false
t.string :email
t.string :name
t.string :token_digest, null: false
t.integer :max_uses
t.integer :uses_count, null: false, default: 0
t.datetime :expires_at
t.datetime :revoked_at
t.references :created_by, foreign_key: { to_table: :users }
t.timestamps
end
add_index :access_invitations, :token_digest, unique: true
create_table :access_invitation_roles do |t|
t.references :access_invitation, null: false, foreign_key: true
t.references :aircraft, null: false, foreign_key: true
t.references :role, null: false, foreign_key: true
t.timestamps
end
add_index :access_invitation_roles, %i[access_invitation_id aircraft_id], unique: true, name: "index_access_invitation_roles_unique"
create_table :access_invitation_redemptions do |t|
t.references :access_invitation, null: false, foreign_key: true
t.references :user, null: false, foreign_key: true
t.timestamps
end
add_index :access_invitation_redemptions, %i[access_invitation_id user_id], unique: true, name: "index_access_invitation_redemptions_unique"
end
end
Generated
+45 -1
View File
@@ -10,7 +10,45 @@
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[8.1].define(version: 2026_11_16_010000) do
ActiveRecord::Schema[8.1].define(version: 2026_11_16_020000) do
create_table "access_invitation_redemptions", force: :cascade do |t|
t.integer "access_invitation_id", null: false
t.integer "user_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["access_invitation_id", "user_id"], name: "index_access_invitation_redemptions_unique", unique: true
t.index ["access_invitation_id"], name: "index_access_invitation_redemptions_on_access_invitation_id"
t.index ["user_id"], name: "index_access_invitation_redemptions_on_user_id"
end
create_table "access_invitation_roles", force: :cascade do |t|
t.integer "access_invitation_id", null: false
t.integer "aircraft_id", null: false
t.integer "role_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["access_invitation_id", "aircraft_id"], name: "index_access_invitation_roles_unique", unique: true
t.index ["access_invitation_id"], name: "index_access_invitation_roles_on_access_invitation_id"
t.index ["aircraft_id"], name: "index_access_invitation_roles_on_aircraft_id"
t.index ["role_id"], name: "index_access_invitation_roles_on_role_id"
end
create_table "access_invitations", force: :cascade do |t|
t.string "label", null: false
t.string "email"
t.string "name"
t.string "token_digest", null: false
t.integer "max_uses"
t.integer "uses_count", default: 0, null: false
t.datetime "expires_at"
t.datetime "revoked_at"
t.integer "created_by_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["created_by_id"], name: "index_access_invitations_on_created_by_id"
t.index ["token_digest"], name: "index_access_invitations_on_token_digest", unique: true
end
create_table "active_storage_attachments", force: :cascade do |t|
t.string "name", null: false
t.string "record_type", null: false
@@ -950,6 +988,12 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_16_010000) do
t.index ["major_record_id"], name: "index_weight_balance_records_on_major_record_id"
end
add_foreign_key "access_invitation_redemptions", "access_invitations"
add_foreign_key "access_invitation_redemptions", "users"
add_foreign_key "access_invitation_roles", "access_invitations"
add_foreign_key "access_invitation_roles", "aircraft"
add_foreign_key "access_invitation_roles", "roles"
add_foreign_key "access_invitations", "users", column: "created_by_id"
add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id"
add_foreign_key "active_storage_variant_records", "active_storage_blobs", column: "blob_id"
add_foreign_key "ad_alerts", "aircraft"
+2
View File
@@ -100,6 +100,8 @@ What each group is for:
| `/help/records` | The "How signing works" link on the signing form | The signing instructions, for signed-in accounts |
| `/calendar/<token>.ics` | Calendar apps fetching the due-items feed (Profile → Calendar feed) | The due list of that user's aircraft, only with their secret 32-character token; making a new link retires the old one |
Invitation links (`/join/…`) are deliberately not on the list: behind forward auth, someone with only an app account still couldn't get past the proxy to use the app, so invited people need an Authentik account anyway. They sign in to Authentik, then open the link and accept it.
Leave out lines for features you don't use: without share links drop `/shared` and Active Storage; without calendar feeds drop `/calendar`; if mechanics never sign through invitations drop `/sign`, `/session`, `/profile/…` and `/help/records`.
Everything else stays behind Authentik: the fleet, records, admin pages, the emailed sign-in links and password resets (an invited mechanic who forgets their password asks the administrator, who resets it under Admin → Users or sends a new invitation), and the Google Drive callback (`/admin/offsite_backup/callback`), which comes back to the administrator's own signed-in browser.
+6
View File
@@ -26,6 +26,12 @@ Signing a logbook entry needs the **Sign logbook entries** permission *and* a cu
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.
## Invitations
**Admin → Invitations → New invitation** makes a link someone opens to create their own account (or accept with the one they have) and get roles on aircraft: a label for you, optionally an email address (then only that address can use it, and the link is emailed to it when email is set up) and a name, how many times it works (empty for unlimited, e.g. for a flying club), when it expires (empty for never), and a role on any of the aircraft (none at all gives just an account). The link is shown once, when it's made; copy it then.
Where someone already has a role on an aircraft, an invitation leaves it as it is. An invitation never gives more than whoever made it can give when it's used. **Revoke** stops a link working; people who already used it keep their access. With sign-in by single sign-on only, people accept invitations after signing in with it.
## 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.
+4
View File
@@ -8,6 +8,10 @@ Add people by email with a role: **Owner**, **Mechanic**, **Pilot**, **Viewer**,
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**.
## Invitations
To add someone who has no account yet, or without knowing their email, use **Invitations** on the same page: choose the role, optionally their email (then only they can use it, and it's emailed to them when email is set up), how many times it works and when it expires, then **Create invitation**. Copy the link shown and send it; it isn't shown again. Whoever opens it creates an account, or signs in, and gets the role on this aircraft. **Revoke** stops a link that hasn't been used. Administrators can also make invitations for several aircraft at once (Admin → Invitations).
## Share links
**Create Share Link** gives a read-only link that needs no account, for a mechanic, partner, buyer or insurer:
+169
View File
@@ -0,0 +1,169 @@
require "test_helper"
# Invitation codes (AccessInvitation): a link that gives an account and roles
# on aircraft, made by administrators or by whoever manages an aircraft's
# people, used by new people (creating an account) or existing ones.
class InvitationsTest < ActionDispatch::IntegrationTest
PASSWORD = "a-long-unique-test-passphrase-42".freeze
setup do
@owner = create_user("owner@example.com")
@admin = create_user("admin@example.com", admin: true)
@a = create_aircraft(owner: @owner, tail_number: "N12345")
@b = create_aircraft(owner: @owner, tail_number: "N54321")
end
def invitation(creator: @admin, grants: [ [ @a, "mechanic" ] ], **attrs)
AccessInvitation.create_for(creator, { label: "Test", max_uses: 1 }.merge(attrs), grants.map { |a, key| [ a, Role.for_key(key) ] })
end
def join_link_in(body) = body[%r{/join/[\w-]+}]
test "an administrator invites to several aircraft; the link is shown once and the code kept only as a digest" do
sign_in @admin
get new_admin_invitation_path
assert_select "select[name='roles[#{@a.id}]']"
post admin_invitations_path, params: { access_invitation: { label: "Club pilots", max_uses: 5, expires_at: "" },
roles: { @a.id => Role.for_key("pilot").id, @b.id => Role.for_key("viewer").id } }
assert_response :success
link = join_link_in(response.body)
assert link
inv = AccessInvitation.last
assert_equal({ "N12345" => "Pilot", "N54321" => "Viewer" }, inv.grants.to_h { [ _1.aircraft.tail_number, _1.role.name ] })
assert_nil inv.expires_at
assert_not_includes inv.attributes.values.map(&:to_s), link.split("/").last
get admin_invitations_path
assert_select "tr.invitation-row", 1
assert_not_includes response.body, link
end
test "someone new opens the link, creates an account and gets the roles; a single-use link then stops working" do
inv = invitation(grants: [ [ @a, "mechanic" ], [ @b, "viewer" ] ])
get join_path(inv.token)
assert_response :success
assert_select ".badge-blue", text: "Mechanic"
post account_join_path(inv.token), params: { email_address: "New@Example.com", name: "New Mechanic", password: PASSWORD, password_confirmation: PASSWORD }
assert_redirected_to root_path
assert_match "Welcome! Your account is ready. N12345: Mechanic N54321: Viewer", flash[:notice]
user = User.find_by!(email_address: "new@example.com")
assert_equal "mechanic", user.role_for(@a).key
assert_equal 1, inv.reload.uses_count
assert inv.redeemed_by?(user)
delete session_path
get join_path(inv.token)
assert_response :not_found
assert_select "h1", text: "This invitation isn't valid"
end
test "someone with an account signs in and accepts; a role they already have stays" do
pilot = create_user("pilot@example.com")
@b.roles.create!(user: pilot, role: "owner")
inv = invitation(grants: [ [ @a, "pilot" ], [ @b, "viewer" ] ], max_uses: nil)
get join_path(inv.token)
assert_select "a[href=?]", new_session_path
sign_in pilot # returns to the invitation
assert_equal join_path(inv.token), path
assert_select "form[action=?]", accept_join_path(inv.token)
post accept_join_path(inv.token)
assert_match "N12345: Pilot N54321: already Owner, unchanged", flash[:notice]
assert_equal "owner", pilot.role_for(@b).key
assert_equal "pilot", pilot.role_for(@a).key
post accept_join_path(inv.token)
assert_equal "You've already accepted this invitation.", flash[:notice]
assert_equal 1, inv.reload.uses_count
end
test "an invitation for one address only works for it, and its account uses that address" do
inv = invitation(email: "Invited@Example.com", name: "Invited Person")
get join_path(inv.token)
assert_select "input[disabled][value='invited@example.com']"
assert_select "input[name=name][value='Invited Person']"
sign_in create_user("someone@example.com")
get join_path(inv.token)
assert_select "h1", text: "This invitation is for someone else"
post accept_join_path(inv.token)
assert_equal 0, inv.reload.uses_count
delete session_path
post account_join_path(inv.token), params: { email_address: "other@example.com", name: "X", password: PASSWORD, password_confirmation: PASSWORD }
assert User.exists?(email_address: "invited@example.com")
assert_not User.exists?(email_address: "other@example.com")
end
test "unknown, expired and revoked links get the same answer, and an existing address is sent to sign in" do
get join_path("nope")
assert_response :not_found
expired = invitation
expired.update!(expires_at: 1.minute.ago)
get join_path(expired.token)
assert_response :not_found
revoked = invitation
revoked.update!(revoked_at: Time.current)
post account_join_path(revoked.token), params: { email_address: "x@example.com", name: "X", password: PASSWORD, password_confirmation: PASSWORD }
assert_response :not_found
assert_not User.exists?(email_address: "x@example.com")
inv = invitation
post account_join_path(inv.token), params: { email_address: "owner@example.com", name: "X", password: PASSWORD, password_confirmation: PASSWORD }
assert_redirected_to join_path(inv.token)
assert_match "already an account", flash[:alert]
assert_equal 0, inv.reload.uses_count
end
test "an aircraft's manager invites to it from its Access page, emailed, with only roles they can give" do
sign_in @owner
assert_emails 1 do
perform_enqueued_jobs do
post aircraft_invitations_path(@a), params: { email: "Mech@Example.com", role_id: Role.for_key("mechanic").id, max_uses: 1, expires_at: "" }
end
end
assert_response :success
link = join_link_in(response.body)
assert_includes ActionMailer::Base.deliveries.last.text_part.body.to_s, link
assert_equal [ "mech@example.com" ], ActionMailer::Base.deliveries.last.to
inv = AccessInvitation.last
assert_equal "Invitation to N12345", inv.label
get aircraft_aircraft_roles_path(@a)
assert_select "#invitations li", 1
assert_select "#invitations select[name=role_id] option", text: "Owner"
partner_role = Role.create!(name: "Partner", permissions: %w[manage_people])
partner = create_user("partner@example.com")
@a.roles.create!(user: partner, role: partner_role)
sign_in partner
post aircraft_invitations_path(@a), params: { role_id: Role.owner.id, max_uses: 1 }
assert_equal 1, AccessInvitation.count
delete aircraft_invitation_path(@a, inv)
assert inv.reload.revoked?
viewer = create_user("viewer@example.com")
@a.roles.create!(user: viewer, role: "viewer")
sign_in viewer
post aircraft_invitations_path(@a), params: { role_id: Role.for_key("viewer").id, max_uses: 1 }
assert_equal 1, AccessInvitation.count
end
test "an invitation can't give more than its creator can when it's used" do
partner_role = Role.create!(name: "Partner", permissions: %w[manage_people])
partner = create_user("partner@example.com")
@a.roles.create!(user: partner, role: partner_role)
inv = invitation(creator: partner, grants: [ [ @a, "pilot" ] ])
@a.roles.find_by(user: partner).update!(role: "viewer") # no longer manages people
newbie = create_user("newbie@example.com")
sign_in newbie
post accept_join_path(inv.token)
assert_nil newbie.role_for(@a)
assert_match "N12345:", flash[:notice]
end
test "an invitation of someone else's aircraft can't be revoked from another aircraft's page" do
inv = invitation(grants: [ [ @b, "pilot" ] ])
sign_in @owner
delete aircraft_invitation_path(@a, inv)
assert_response :not_found
assert_not inv.reload.revoked?
end
end