REST API v1: tokens, read endpoints, squawks, webhooks

- Personal tokens (Profile → API tokens) act as their owner; integration
  tokens (Admin → Integrations) reach chosen aircraft and scopes, and their
  writes name the person they're for (SAM-On-Behalf-Of). Tokens are stored
  hashed, shown once, revocable, with last use recorded.
- GET aircraft, components, due list, inspections, ADs, logbook entries and
  squawks; POST/PATCH squawks with external_ref links to the other system.
- Idempotency-Key for safe retries, paging, JSON errors, rate limits.
- Record history keeps the token with each change (in the hashed payload).
- Webhooks (squawk created/updated/resolved, entry signed), HMAC-signed,
  retried, never sent to the server itself; deliveries listed for admins.
- The outbound address check is shared by AirTrail and webhooks; reporting a
  squawk is announced the same way from the form and the API.
- docs/guide/api.md: the API reference.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-14 19:05:10 -05:00
1 parent ec0f43019f
commit bffdea937c
45 files changed
+1577 -51

No files matched your search

@@ -0,0 +1,93 @@
# Admin → Integrations: tokens for other systems (e.g. Redmine), limited to
# chosen aircraft and scopes, each with an optional webhook (docs/api.md).
# The token and webhook secret are shown once, right after they're made.
class Admin::IntegrationsController < ApplicationController
before_action :require_admin!
before_action :set_integration, only: %i[show edit update destroy new_secret]
def index
@integrations = ApiToken.integration.order(revoked_at: :desc, name: :asc).includes(:webhook_endpoints)
end
def new
@integration = ApiToken.new(kind: "integration", scopes: %w[read])
@endpoint = WebhookEndpoint.new(events: [])
end
def create
@integration = ApiToken.new(integration_params.merge(kind: "integration", user: current_user))
@endpoint = build_endpoint(@integration)
ApiToken.transaction do
@integration.save!
@endpoint&.save!
end
@secret = @endpoint&.secret
render :created
rescue ActiveRecord::RecordInvalid
@endpoint ||= WebhookEndpoint.new(events: [])
render :new, status: :unprocessable_entity
end
def show
@endpoint = @integration.webhook_endpoints.first
@deliveries = @endpoint ? @endpoint.deliveries.recent.limit(25) : []
end
def edit
@endpoint = @integration.webhook_endpoints.first || WebhookEndpoint.new(events: [])
end
def update
@endpoint = @integration.webhook_endpoints.first
ApiToken.transaction do
@integration.update!(integration_params)
if webhook_params[:url].present?
@endpoint ||= @integration.webhook_endpoints.new(secret: WebhookEndpoint.new_secret)
@endpoint.update!(webhook_params)
else
@endpoint&.destroy!
end
end
redirect_to admin_integration_path(@integration), notice: t("flash.admin_integrations.saved")
rescue ActiveRecord::RecordInvalid
@endpoint ||= WebhookEndpoint.new(events: [])
render :edit, status: :unprocessable_entity
end
# A new webhook secret, shown once.
def new_secret
@endpoint = @integration.webhook_endpoints.first or return redirect_to(admin_integration_path(@integration))
@endpoint.update!(secret: WebhookEndpoint.new_secret)
@secret = @endpoint.secret
render :created
end
def destroy
@integration.revoke!
@integration.webhook_endpoints.update_all(enabled: false)
redirect_to admin_integrations_path, notice: t("flash.admin_integrations.revoked", name: @integration.name)
end
private
def set_integration = @integration = ApiToken.integration.find(params[:id])
def integration_params
p = params.require(:api_token).permit(:name, scopes: [], aircraft_ids: [])
p[:scopes] = Array(p[:scopes]) & ApiToken::SCOPES.keys
p[:aircraft_ids] = Aircraft.where(id: Array(p[:aircraft_ids])).ids
p
end
def webhook_params
p = params.fetch(:webhook, {}).permit(:url, :enabled, events: [])
p[:events] = Array(p[:events]) & WebhookEndpoint::EVENTS.keys
p[:enabled] = p[:enabled] != "0"
p
end
def build_endpoint(integration)
return if webhook_params[:url].blank?
integration.webhook_endpoints.new(webhook_params.merge(secret: WebhookEndpoint.new_secret))
end
end
@@ -0,0 +1,49 @@
module Api
module V1
# The fleet this token reaches, and each aircraft's own lists.
class AircraftController < BaseController
before_action -> { require_scope!(:read) }
def index
render_page(aircraft_scope) { ApiPresenter.aircraft(_1) }
end
def show
render json: { data: ApiPresenter.aircraft(find_aircraft(params[:id])) }
end
# The parts tree (?all=1 includes disposed parts).
def components
aircraft = find_aircraft(params[:id])
scope = aircraft.components.includes(:component_type)
scope = scope.where.not(status: "DISPOSED") unless params[:all].present?
render_page(scope) { ApiPresenter.component(_1) }
end
# Everything coming due, soonest first (hours projected to dates).
def due
aircraft = find_aircraft(params[:id])
render json: { data: DueList.new(aircraft).items.map { ApiPresenter.due_item(_1) } }
end
def inspections
aircraft = find_aircraft(params[:id])
render json: { data: Compliance.inspection_rows(aircraft).map { ApiPresenter.inspection(_1) } }
end
def ads
aircraft = find_aircraft(params[:id])
render json: { data: Compliance.ad_rows(aircraft).map { ApiPresenter.ad(_1) } }
end
# Logbook entries, oldest first (paged); ?log=AC|ENG|PROP|OTHER, ?signed=true|false.
def logbook_entries
aircraft = find_aircraft(params[:id])
scope = aircraft.logbook_entries.includes(:signature)
scope = scope.where(log_type: params[:log]) if params[:log].present?
scope = params[:signed] == "true" ? scope.where.associated(:signature) : scope.where.missing(:signature) if params[:signed].present?
render_page(scope) { ApiPresenter.logbook_entry(_1) }
end
end
end
end
+123
View File
@@ -0,0 +1,123 @@
# The REST API, version 1 (docs/api.md). JSON in and out; a token in
# "Authorization: Bearer sam_…" instead of a browser session, so no cookies
# and no CSRF tokens.
#
# A personal token acts as its owner. An integration token acts for the
# person named in "SAM-On-Behalf-Of: <email>" (required for writes), and
# reaches only its aircraft that person can also see.
module Api
module V1
class BaseController < ActionController::API
include RejectsNullBytes
MAX_PAGE = 200
before_action :authenticate
rate_limit to: 600, within: 1.minute, by: -> { @api_token&.id || request.remote_ip },
with: -> { render_error(:too_many_requests, "rate_limited", "Too many requests; slow down.") }
around_action :idempotent, if: -> { request.post? || request.patch? || request.delete? }
rescue_from ActiveRecord::RecordNotFound do
render_error(:not_found, "not_found", "Not found, or not available to this token.")
end
rescue_from ActionController::ParameterMissing, ActionDispatch::Http::Parameters::ParseError do |e|
render_error(:bad_request, "bad_request", e.message.truncate(200))
end
rescue_from ActiveRecord::RecordInvalid do |e|
render_invalid(e.record)
end
rescue_from ActiveSupport::MessageVerifier::InvalidSignature, ActiveModel::RangeError,
ActiveRecord::NotNullViolation, ActiveRecord::InvalidForeignKey do
render_error(:unprocessable_entity, "invalid", "Some values couldn't be saved.")
end
private
attr_reader :api_token
def acting_user = Current.api_user
def authenticate
token = request.authorization.to_s[/\ABearer\s+(\S+)\z/i, 1]
@api_token = ApiToken.authenticate(token)
return render_error(:unauthorized, "unauthorized", "A valid API token is required.") unless @api_token
Current.api_token = @api_token
Current.ip_address = request.remote_ip
Current.api_user = @api_token.personal? ? @api_token.user : on_behalf_of
@api_token.used!(request.remote_ip)
end
# The person an integration is acting for, if it named one.
def on_behalf_of
email = request.headers["SAM-On-Behalf-Of"].to_s.strip.downcase.presence or return
User.active.find_by(email_address: email) ||
render_error(:unprocessable_entity, "unknown_user", "SAM-On-Behalf-Of doesn't match an active user.")
end
def require_scope!(scope)
return if api_token.allows?(scope)
render_error(:forbidden, "missing_scope", "This token doesn't have the #{scope} scope.")
end
# Writes always name a person, so the record history shows who.
def require_person!
return if acting_user
render_error(:unprocessable_entity, "on_behalf_of_required", "Writes with an integration token need SAM-On-Behalf-Of.")
end
def aircraft_scope = api_token.aircraft_scope(acting_user)
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])
# ?limit= (1–200, default 50), ?after=<id> to continue, ?updated_since=<ISO time>.
def paginate(scope)
limit = params.fetch(:limit, 50).to_i.clamp(1, MAX_PAGE)
scope = scope.where(scope.arel_table[:id].gt(params[:after].to_i)) if params[:after].present?
if params[:updated_since].present?
since = Time.iso8601(params[:updated_since].to_s) rescue (raise ActionController::BadRequest, "updated_since must be an ISO 8601 time")
scope = scope.where(scope.arel_table[:updated_at].gteq(since))
end
records = scope.reorder(:id).limit(limit + 1).to_a
more = records.size > limit
records = records.first(limit)
[ records, (records.last.id if more) ]
end
def render_page(scope, &present)
records, next_after = paginate(scope)
render json: { data: records.map(&present), next_after: next_after }
end
def render_error(status, code, message, fields: nil)
render json: { error: { code: code, message: message, fields: fields }.compact }, status: status
end
def render_invalid(record)
render_error(:unprocessable_entity, "invalid", record.errors.full_messages.to_sentence, fields: record.errors.to_hash)
end
# The same Idempotency-Key again (a retry) gets the first answer; the
# same key with a different request is a conflict.
def idempotent
key = request.headers["Idempotency-Key"].to_s.strip
return yield if key.empty? || api_token.nil?
return render_error(:bad_request, "bad_request", "Idempotency-Key is too long.") if key.length > 100
digest = OpenSSL::Digest::SHA256.hexdigest([ request.method, request.path, request.raw_post ].join("\n"))
if (seen = api_token.idempotency_keys.find_by(key: key))
return render_error(:conflict, "idempotency_conflict", "This Idempotency-Key was used for a different request.") if seen.request_digest != digest
response.headers["Idempotent-Replay"] = "true"
return render(json: seen.response_body, status: seen.response_status)
end
yield
return if response.status >= 500
api_token.idempotency_keys.create(key: key, request_digest: digest, response_status: response.status,
response_body: response.body, created_at: Time.current)
end
end
end
end
+16
View File
@@ -0,0 +1,16 @@
module Api
module V1
# What this token is and who it's acting as: a quick check for a new integration.
class MeController < BaseController
def show
render json: { data: {
token: { name: api_token.name, kind: api_token.kind, hint: api_token.token_hint, scopes: api_token.scopes,
aircraft_ids: (api_token.aircraft_ids if api_token.integration?) }.compact,
acting_as: acting_user && { id: acting_user.id, name: acting_user.display_name, email: acting_user.email_address },
aircraft_ids: aircraft_scope.ids,
api_version: "v1", app_version: Rails.root.join("VERSION").read.strip
} }
end
end
end
end
@@ -0,0 +1,66 @@
module Api
module V1
# Squawks: list and report on an aircraft; find by external_ref; update.
# Resolving happens through a signed logbook entry, not here.
class SquawksController < BaseController
before_action -> { require_scope!(:read) }, only: %i[index show lookup]
before_action -> { require_scope!("squawks:write") }, :require_person!, only: %i[create update]
# GET /aircraft/:aircraft_id/squawks?status=open|resolved|all (default open)
def index
scope = find_aircraft.squawks.includes(:reported_by).with_attached_attachments
scope = case params.fetch(:status, "open")
when "open" then scope.active
when "resolved" then scope.resolved
else scope
end
render_page(scope) { ApiPresenter.squawk(_1) }
end
# GET /squawks?external_ref=redmine:issue:4512
def lookup
ref = params.require(:external_ref)
scope = Squawk.where(aircraft: aircraft_scope, external_ref: ref).includes(:reported_by).with_attached_attachments
render json: { data: scope.map { ApiPresenter.squawk(_1) } }
end
def show
render json: { data: ApiPresenter.squawk(find_squawk) }
end
# POST /aircraft/:aircraft_id/squawks
def create
aircraft = find_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!
SquawkReported.call(squawk, by: acting_user)
render json: { data: ApiPresenter.squawk(squawk) }, status: :created
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.
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.")
end
attrs[:component_id] = nil if attrs.key?(:component_id) && !squawk.aircraft.components.exists?(id: attrs[:component_id])
squawk.update!(attrs)
render json: { data: ApiPresenter.squawk(squawk) }
end
private
def find_squawk = Squawk.where(aircraft: aircraft_scope).find(params[:id])
def create_params
params.require(:squawk).permit(:issue_reported, :priority, :component_id, :external_ref).tap do |p|
p[:priority] = p.fetch(:priority, 2).to_i
end
end
end
end
end
+19
View File
@@ -0,0 +1,19 @@
# Profile → API tokens: personal tokens for the REST API (docs/api.md). The
# token is shown once, on the page right after it's made (not kept in the
# flash or anywhere else).
class ApiTokensController < ApplicationController
def create
@token = current_user.api_tokens.new(name: params.dig(:api_token, :name), kind: "personal",
scopes: Array(params.dig(:api_token, :scopes)) & ApiToken::SCOPES.keys)
if @token.save
render :created
else
redirect_to edit_profile_path(anchor: "api"), alert: @token.errors.full_messages.to_sentence
end
end
def destroy
current_user.api_tokens.personal.active.find(params[:id]).revoke!
redirect_to edit_profile_path(anchor: "api"), notice: t("flash.api_tokens.revoked")
end
end
+1 -15
View File
@@ -4,8 +4,8 @@ class ApplicationController < ActionController::Base
include TimeZones
allow_browser versions: :modern
include RejectsNullBytes
prepend_before_action :redirect_to_setup
prepend_before_action :reject_null_bytes
before_action { Current.ip_address = request.remote_ip } # for record history
helper_method :current_user
@@ -36,20 +36,6 @@ class ApplicationController < ActionController::Base
private
# No form sends a null byte; some libraries (password hashing, file paths)
# raise on one, so refuse the request up front.
def reject_null_bytes
head :bad_request if contains_null_byte?(request.params)
end
def contains_null_byte?(value)
case value
when String then value.include?("\0")
when Hash then value.any? { |k, v| contains_null_byte?(k) || contains_null_byte?(v) }
when Array then value.any? { contains_null_byte?(_1) }
else false
end
end
def current_user = Current.user
@@ -0,0 +1,22 @@
# No form or API client sends a null byte; some libraries (password hashing,
# file paths) raise on one, so such requests are refused up front.
module RejectsNullBytes
extend ActiveSupport::Concern
included { prepend_before_action :reject_null_bytes }
private
def reject_null_bytes
head :bad_request if contains_null_byte?(request.params)
end
def contains_null_byte?(value)
case value
when String then value.include?("\0")
when Hash then value.any? { |k, v| contains_null_byte?(k) || contains_null_byte?(v) }
when Array then value.any? { contains_null_byte?(_1) }
else false
end
end
end
+1 -5
View File
@@ -21,11 +21,7 @@ class SquawksController < ApplicationController
end
@squawk = @aircraft.squawks.new(squawk_params.merge(reported_by: current_user))
if @squawk.save
log_event("squawk", t("flash.squawks.squawk_reported_2", priority_label: @squawk.priority_label), notes: @squawk.issue_reported.truncate(200))
if @squawk.grounding?
PushNotifier.notify(@aircraft.users.merge(User.active).where.not(id: current_user.id), :grounding_squawk, path: aircraft_squawks_path(@aircraft),
tag: "squawk-#{@squawk.id}", tail: @aircraft.tail_number, issue: @squawk.issue_reported.truncate(120))
end
SquawkReported.call(@squawk, by: current_user)
redirect_to aircraft_squawks_path(@aircraft), notice: t("flash.squawks.squawk_reported")
else
render :new, status: :unprocessable_entity
+57
View File
@@ -0,0 +1,57 @@
require "net/http"
# Posts one webhook delivery. The body is signed so the receiver can check
# it came from here and wasn't replayed:
# SAM-Signature: t=<unix time>,v1=<hex HMAC-SHA256 of "<t>.<body>" with the endpoint's secret>
# Anything but a 2xx answer is retried with growing waits, then marked failed.
class WebhookDeliveryJob < ApplicationJob
queue_as :default
ATTEMPTS = 8
class Failed < StandardError; end
retry_on Failed, wait: :polynomially_longer, attempts: ATTEMPTS do |job, error|
WebhookDelivery.find_by(id: job.arguments.first)&.update!(status: "failed", last_error: error.message.truncate(250))
end
def perform(delivery_id)
delivery = WebhookDelivery.includes(:webhook_endpoint).find_by(id: delivery_id) or return
return if delivery.status == "delivered"
endpoint = delivery.webhook_endpoint
delivery.increment!(:attempts)
response = post(endpoint, delivery)
if response.code.to_i.between?(200, 299)
delivery.update!(status: "delivered", response_status: response.code.to_i, delivered_at: Time.current, last_error: nil)
else
delivery.update!(response_status: response.code.to_i, last_error: "HTTP #{response.code}")
raise Failed, "HTTP #{response.code}"
end
rescue OutboundAddress::Blocked => e
# Pointed at an address the server won't send to: retrying won't help.
delivery.update!(status: "failed", last_error: "blocked address (#{e.reason})")
rescue Timeout::Error, SocketError, SystemCallError, OpenSSL::SSL::SSLError, EOFError, IOError => e
delivery.update!(last_error: "#{e.class.name.demodulize}: #{e.message}".truncate(250))
raise Failed, e.message
end
private
def post(endpoint, delivery)
uri = URI.parse(endpoint.url)
timestamp = Time.current.to_i
signature = OpenSSL::HMAC.hexdigest("SHA256", endpoint.secret, "#{timestamp}.#{delivery.payload}")
req = Net::HTTP::Post.new(uri)
req["Content-Type"] = "application/json"
req["User-Agent"] = "SimpleAircraftManager-Webhooks"
req["SAM-Event"] = delivery.event
req["SAM-Delivery"] = delivery.id.to_s
req["SAM-Signature"] = "t=#{timestamp},v1=#{signature}"
req.body = delivery.payload
http = Net::HTTP.new(uri.host, uri.port)
http.ipaddr = OutboundAddress.resolve!(uri.host, allow_private: true) # set up by an admin: the private network is fine
http.use_ssl = uri.scheme == "https"
http.open_timeout = 5
http.read_timeout = 10
http.start { _1.request(req) }
end
end
+9
View File
@@ -0,0 +1,9 @@
# A write sent with an Idempotency-Key header, and the answer it got: the
# same key again (a retry) gets the same answer instead of a second record.
class ApiIdempotencyKey < ApplicationRecord
KEEP_FOR = 24.hours
belongs_to :api_token
def self.purge_old = where(created_at: ...KEEP_FOR.ago).delete_all
end
+80
View File
@@ -0,0 +1,80 @@
# A key for the REST API (docs/api.md). Only its SHA-256 digest is kept; the
# token itself is shown once, when it's made.
#
# personal: acts as its owner, with exactly their aircraft and role.
# integration: made by an admin for another system (e.g. Redmine), limited to
# chosen aircraft and scopes. Its writes name the person they're
# for (SAM-On-Behalf-Of), so the record history always shows who.
class ApiToken < ApplicationRecord
KINDS = %w[personal integration].freeze
SCOPES = LabelSet.new("api_token.scopes", %w[read squawks:write])
PREFIX = "sam_"
belongs_to :user
has_many :webhook_endpoints, dependent: :destroy
has_many :idempotency_keys, class_name: "ApiIdempotencyKey", dependent: :delete_all
attr_reader :token # the plain token, only right after create
normalizes :name, with: ->(n) { n.to_s.strip }
validates :name, presence: true, length: { maximum: 80 }
validates :kind, inclusion: { in: KINDS }
validate :scopes_known
validate :integration_made_by_admin, on: :create
before_validation :generate, on: :create
scope :active, -> { where(revoked_at: nil) }
scope :personal, -> { where(kind: "personal") }
scope :integration, -> { where(kind: "integration") }
def self.digest(token) = OpenSSL::Digest::SHA256.hexdigest(token.to_s)
# The token for this string, if it's in use (and its owner is too).
def self.authenticate(token)
return unless token.to_s.start_with?(PREFIX)
found = active.includes(:user).find_by(token_digest: digest(token))
found if found && (found.integration? || !found.user.disabled?)
end
def personal? = kind == "personal"
def integration? = kind == "integration"
def revoked? = revoked_at.present?
def revoke! = update!(revoked_at: Time.current)
def allows?(scope) = scopes.include?(scope.to_s)
# The aircraft this token reaches, acting for `user` (who must also have
# access, for an integration acting on someone's behalf).
def aircraft_scope(acting_user)
if personal?
user.accessible_aircraft
else
reachable = Aircraft.where(id: Array(aircraft_ids))
acting_user ? reachable.where(id: acting_user.accessible_aircraft.select(:id)) : reachable
end
end
# Last use, at most once a minute (no write per request).
def used!(ip)
return if last_used_at && last_used_at > 1.minute.ago && last_used_ip == ip
update_columns(last_used_at: Time.current, last_used_ip: ip)
end
private
def generate
@token = "#{PREFIX}#{SecureRandom.base58(40)}"
self.token_digest = self.class.digest(@token)
self.token_hint = @token.first(PREFIX.length + 6)
self.scopes = Array(scopes).map(&:to_s).compact_blank.uniq
end
def scopes_known
errors.add(:scopes, :blank) if scopes.blank?
errors.add(:scopes, :inclusion) if (Array(scopes) - SCOPES.keys).any?
end
def integration_made_by_admin
errors.add(:kind, :admins_only) if integration? && !user&.admin?
end
end
+5 -2
View File
@@ -1,4 +1,7 @@
class Current < ActiveSupport::CurrentAttributes
attribute :session, :ip_address
delegate :user, to: :session, allow_nil: true
# api_token / api_user: an API request (see Api::V1::BaseController), which
# acts as a person without a browser session.
attribute :session, :ip_address, :api_token, :api_user
def user = api_user || session&.user
end
+6
View File
@@ -18,6 +18,12 @@ class EntrySignature < ApplicationRecord
validates :auth_method, inclusion: { in: AUTH_METHODS.keys + [ "imported" ] }
validates :logbook_entry_id, uniqueness: true
before_create { self.seal ||= compute_seal unless imported? }
# Integrations hear about it (webhooks); not for signatures carried over by an import.
after_create_commit do
next if imported?
entry = logbook_entry
Webhooks.publish("entry.signed", aircraft: entry.aircraft, data: ApiPresenter.logbook_entry(entry))
end
before_update { throw :abort } # signatures are permanent (2.1.2.7)
before_destroy { throw :abort unless destroyed_by_association }
+1 -1
View File
@@ -3,7 +3,7 @@
class HelpGuide
DIR = Rails.root.join("docs/guide")
ORDER = %w[README getting-started profile aircraft flights squawks oil-and-fuel components logbook records
inspections ads documents major-records sharing administration disclaimer changelog].freeze
inspections ads documents major-records sharing administration api disclaimer changelog].freeze
OPTIONS = {
parse: { smart: true },
render: { hardbreaks: false, unsafe: false },
+5 -2
View File
@@ -4,6 +4,7 @@
# editing a version breaks the chain and the nightly check reports it.
class RecordVersion < ApplicationRecord
belongs_to :user, optional: true
belongs_to :api_token, optional: true
scope :chronological, -> { order(:id) }
@@ -15,10 +16,12 @@ class RecordVersion < ApplicationRecord
def self.append!(item:, aircraft_id:, event:, changes:)
now = Time.current
payload = { "item_type" => item.class.name, "item_id" => item.id, "event" => event, "changes" => changes,
"user_id" => Current.user&.id, "at" => now.utc.iso8601(6) }.to_json
"user_id" => Current.user&.id, "at" => now.utc.iso8601(6) }
payload["api_token_id"] = Current.api_token.id if Current.api_token # made through the API (part of the hashed payload)
payload = payload.to_json
prev = where(aircraft_id: aircraft_id).order(:id).last&.chain_hash
create!(aircraft_id: aircraft_id, item_type: item.class.name, item_id: item.id, event: event, user_id: Current.user&.id,
ip_address: Current.ip_address, payload: payload, prev_hash: prev, chain_hash: digest(prev, payload), created_at: now)
ip_address: Current.ip_address, api_token_id: Current.api_token&.id, payload: payload, prev_hash: prev, chain_hash: digest(prev, payload), created_at: now)
end
def changes_hash = JSON.parse(payload)["changes"]
+9
View File
@@ -11,6 +11,15 @@ class Squawk < ApplicationRecord
belongs_to :logbook_entry, optional: true
has_many_attached :attachments
# Integrations hear about squawks (webhooks), once the change is saved.
after_create_commit { Webhooks.publish("squawk.created", aircraft: aircraft, data: ApiPresenter.squawk(self)) }
after_update_commit do
next if (saved_changes.keys - %w[updated_at]).empty?
event = saved_change_to_resolved? && resolved? ? "squawk.resolved" : "squawk.updated"
Webhooks.publish(event, aircraft: aircraft, data: ApiPresenter.squawk(self))
end
normalizes :external_ref, with: ->(r) { r.to_s.strip.first(200).presence }
validates :priority, inclusion: { in: PRIORITIES.keys }
validates :issue_reported, presence: true
validates_uploads :attachments
+1
View File
@@ -3,6 +3,7 @@ class User < ApplicationRecord
has_many :sessions, dependent: :destroy
has_many :aircraft_roles, dependent: :destroy
has_many :push_subscriptions, dependent: :delete_all
has_many :api_tokens, dependent: :destroy
normalizes :time_zone, with: ->(z) { z.strip.presence }
validates :time_zone, inclusion: { in: ->(_) { ActiveSupport::TimeZone.all.map(&:name) } }, allow_nil: true
+11
View File
@@ -0,0 +1,11 @@
# One event sent (or being sent) to a webhook endpoint; the recent ones are
# listed for the admin, with the answer the other system gave.
class WebhookDelivery < ApplicationRecord
KEEP_FOR = 30.days
belongs_to :webhook_endpoint
scope :recent, -> { order(created_at: :desc) }
def self.purge_old = where(created_at: ...KEEP_FOR.ago).delete_all
end
+28
View File
@@ -0,0 +1,28 @@
# Where an integration wants to hear about changes (squawks, signed entries):
# SAM posts JSON there, signed with the shared secret (see WebhookDeliveryJob).
class WebhookEndpoint < ApplicationRecord
EVENTS = LabelSet.new("webhook_endpoint.events", %w[squawk.created squawk.updated squawk.resolved entry.signed])
belongs_to :api_token
has_many :deliveries, class_name: "WebhookDelivery", dependent: :delete_all
encrypts :secret
normalizes :url, with: ->(u) { u.to_s.strip }
validates :url, presence: true, format: { with: %r{\Ahttps?://[^\s/]+(:\d+)?(/\S*)?\z}i }
validates :secret, presence: true, length: { minimum: 16 }
validate :events_known
scope :enabled, -> { where(enabled: true) }
def self.new_secret = SecureRandom.hex(32)
def subscribed?(event) = events.include?(event.to_s)
private
def events_known
errors.add(:events, :blank) if events.blank?
errors.add(:events, :inclusion) if (Array(events) - EVENTS.keys).any?
end
end
+69
View File
@@ -0,0 +1,69 @@
# What the API and webhooks send for each kind of record (docs/api.md).
# Times are ISO 8601 UTC, hours decimals, codes rather than translated labels.
module ApiPresenter
module_function
def aircraft(a)
aw = a.airworthiness
{ id: a.id, tail_number: a.tail_number, make: a.make, model: a.model, serial_number: a.serial_number,
icao_type: a.icao_type, status: a.status,
airworthiness: { status: aw.status, issues: aw.issues.map { { category: _1.category, severity: _1.severity, title: _1.title } } },
time_basis: a.time_basis, hours: dec(a.current_hours), tach: dec(a.tach_time), hobbs: dec(a.hobbs_time),
updated_at: time(a.updated_at) }
end
def component(c)
{ id: c.id, aircraft_id: c.aircraft_id, parent_id: c.parent_component_id, type: c.component_type&.name,
manufacturer: c.manufacturer, model: c.model, serial_number: c.serial_number.presence,
location: c.install_location.presence, status: c.status, date_in_service: c.date_in_service&.iso8601,
hours_in_service: dec(c.hours_in_service), hours_since_overhaul: dec(c.hours_since_overhaul),
overhaul_date: c.overhaul_date&.iso8601, overhaul_kind: c.overhaul_kind.presence,
tbo: { hours: c.tbo_hours, days: c.tbo_days, months: c.tbo_months, on_condition: c.on_condition, critical: c.tbo_critical }.compact,
replacement: { hours: c.replacement_hours, days: c.replacement_days, months: c.replacement_months, critical: c.replacement_critical }.compact,
expires_on: c.expires_on&.iso8601, updated_at: time(c.updated_at) }
end
def due_item(i)
{ key: i.key, title: i.title, kind: i.kind, due_date: i.date.iso8601, projected: i.projected,
due_hours: dec(i.due_hours), overdue: i.overdue? }
end
def squawk(s)
{ id: s.id, aircraft_id: s.aircraft_id, component_id: s.component_id, issue_reported: s.issue_reported,
priority: s.priority, grounding: s.grounding?, deferred: s.deferred?, resolved: !!s.resolved,
resolved_at: time(s.resolved_at), notes: s.notes.presence, logbook_entry_id: s.logbook_entry_id,
reported_by: s.reported_by&.display_name, external_ref: s.external_ref,
attachments: s.attachments.map { _1.filename.to_s },
created_at: time(s.created_at), updated_at: time(s.updated_at) }
end
def logbook_entry(e)
sig = e.signature
{ id: e.id, aircraft_id: e.aircraft_id, component_id: e.component_id, log: e.log_type, entry_type: e.entry_type,
date: e.date.iso8601, text: e.text, aircraft_hours: dec(e.aircraft_hours_at_entry),
inspection_result: e.inspection_result.presence, verified: e.verified, superseded: e.superseded_at.present?,
signed: sig.present?, signature: sig && signature(sig),
signoff: sig ? nil : { person: e.signoff_person.presence, certificate_type: e.signoff_certificate_type.presence,
certificate_number: e.signoff_certificate_number.presence }.compact.presence,
created_at: time(e.created_at), updated_at: time(e.updated_at) }
end
def signature(sig)
{ signer_name: sig.signer_name, certificate_kind: sig.certificate_kind, certificate_number: sig.certificate_number,
signed_at: time(sig.signed_at) }
end
def inspection(row)
{ inspection_type_id: row.type.id, name: row.type.name, status: row.status, next_due_date: row.next_due_date&.iso8601,
next_due_hours: dec(row.next_due_hours), last_done: row.latest&.date&.iso8601 }
end
def ad(row)
{ airworthiness_directive_id: row.ad.id, name: row.ad.name, description: row.ad.short_description.presence,
status: row.status, next_due_date: row.next_due_date&.iso8601, next_due_hours: dec(row.next_due_hours),
last_complied: row.latest&.date_complied&.iso8601 }
end
def dec(value) = value&.to_d&.round(1)&.to_f
def time(value) = value&.utc&.iso8601
end
+4 -18
View File
@@ -30,9 +30,6 @@ class AirTrailClient
@allow_private = allow_private || self.class.allowed_hosts.include?(@base.host.to_s.downcase)
end
# Host name → IP addresses (replaceable in tests, which have no DNS).
class_attribute :resolver, default: ->(host) { Addrinfo.getaddrinfo(host, nil, nil, :STREAM).map(&:ip_address) }
def self.allowed_hosts = ENV.fetch("AIRTRAIL_ALLOWED_HOSTS", "").split(",").map { _1.strip.downcase }.compact_blank
def me = request(:get, "/api/v1/me").fetch("data")
@@ -85,24 +82,13 @@ class AirTrailClient
raise NetworkError, I18n.t("services.air_trail.can_t_reach_airtrail_at", host: @base.host, message: e.message)
end
# The address to connect to: the host's first, once all of its addresses are
# ones this connection may reach.
# The address to connect to (see OutboundAddress).
def address(host)
ips = resolver.call(host).map { IPAddr.new(_1.sub(/%.*/, "")) }.uniq
raise SocketError, "no address" if ips.empty?
ips.each do |ip|
ip = ip.native # ::ffff:10.0.0.1 → 10.0.0.1
reason = if ip.loopback? || ip.link_local? || UNREACHABLE.any? { _1.include?(ip) } then :never
elsif (ip.private? || CGNAT.include?(ip)) && !@allow_private then :private
end
raise BlockedAddress, I18n.t("services.air_trail.blocked_#{reason}", host: host) if reason
end
ips.first.to_s
OutboundAddress.resolve!(host, allow_private: @allow_private)
rescue OutboundAddress::Blocked => e
raise BlockedAddress, I18n.t("services.air_trail.blocked_#{e.reason}", host: host)
end
UNREACHABLE = [ IPAddr.new("0.0.0.0/8"), IPAddr.new("::/128"), IPAddr.new("224.0.0.0/4"), IPAddr.new("ff00::/8") ].freeze
CGNAT = IPAddr.new("100.64.0.0/10") # shared address space, e.g. Tailscale
def handle(response)
status = response.code.to_i
json = begin
+34
View File
@@ -0,0 +1,34 @@
# Checks where the server is about to send a request (AirTrail, webhooks):
# resolves the host and returns the address to connect to, so the name can't
# be pointed elsewhere in between. Never the server itself, link-local
# addresses (cloud metadata) or multicast; the private network only when
# allowed (admins, or hosts the admin listed).
module OutboundAddress
class Blocked < StandardError
attr_reader :reason # :never | :private
def initialize(reason, host)
@reason = reason
super("#{host}: #{reason}")
end
end
UNREACHABLE = [ IPAddr.new("0.0.0.0/8"), IPAddr.new("::/128"), IPAddr.new("224.0.0.0/4"), IPAddr.new("ff00::/8") ].freeze
CGNAT = IPAddr.new("100.64.0.0/10") # shared address space, e.g. Tailscale
# Host name → IP addresses (replaceable in tests, which have no DNS).
mattr_accessor :resolver, default: ->(host) { Addrinfo.getaddrinfo(host, nil, nil, :STREAM).map(&:ip_address) }
module_function
def resolve!(host, allow_private:)
ips = resolver.call(host).map { IPAddr.new(_1.sub(/%.*/, "")) }.uniq
raise SocketError, "no address for #{host}" if ips.empty?
ips.each do |ip|
ip = ip.native # ::ffff:10.0.0.1 → 10.0.0.1
raise Blocked.new(:never, host) if ip.loopback? || ip.link_local? || UNREACHABLE.any? { _1.include?(ip) }
raise Blocked.new(:private, host) if (ip.private? || CGNAT.include?(ip)) && !allow_private
end
ips.first.to_s
end
end
+16
View File
@@ -0,0 +1,16 @@
# What happens when a squawk is reported, from the form or the API: the
# aircraft's activity log, and a push notification to its other people when
# it grounds the aircraft.
module SquawkReported
module_function
def call(squawk, by:)
aircraft = squawk.aircraft
aircraft.log_event!("squawk", I18n.t("flash.squawks.squawk_reported_2", priority_label: squawk.priority_label),
user: by, notes: squawk.issue_reported.truncate(200))
return unless squawk.grounding?
PushNotifier.notify(aircraft.users.merge(User.active).where.not(id: by&.id), :grounding_squawk,
path: Rails.application.routes.url_helpers.aircraft_squawks_path(aircraft),
tag: "squawk-#{squawk.id}", tail: aircraft.tail_number, issue: squawk.issue_reported.truncate(120))
end
end
+18
View File
@@ -0,0 +1,18 @@
# Tells integrations about changes (docs/api.md, "Webhooks"): each enabled
# endpoint subscribed to the event, whose token is active and reaches the
# aircraft, gets a delivery, sent by WebhookDeliveryJob after the change is
# saved.
module Webhooks
module_function
def publish(event, aircraft:, data:)
endpoints = WebhookEndpoint.enabled.joins(:api_token).merge(ApiToken.active).includes(:api_token)
.select { _1.subscribed?(event) && Array(_1.api_token.aircraft_ids).include?(aircraft.id) }
return if endpoints.empty?
body = { event: event, id: SecureRandom.uuid, created_at: Time.current.utc.iso8601, aircraft_id: aircraft.id, data: data }.to_json
endpoints.each do |endpoint|
delivery = endpoint.deliveries.create!(event: event, payload: body)
WebhookDeliveryJob.perform_later(delivery.id)
end
end
end
@@ -0,0 +1,32 @@
<%= form_with model: integration, url: (integration.persisted? ? admin_integration_path(integration) : admin_integrations_path), scope: :api_token,
class: "card card-body max-w-2xl space-y-5", data: { turbo: false } do |f| %>
<%= f.errors_summary %>
<% if endpoint&.errors&.any? %><div class="rounded-md bg-red-50 p-3 text-sm text-red-700"><%= endpoint.errors.full_messages.to_sentence %></div><% end %>
<%= f.field :name, hint: t(".name_hint") %>
<fieldset>
<legend class="label"><%= t(".scopes") %></legend>
<% ApiToken::SCOPES.each do |key, label| %>
<label class="flex items-start gap-2 text-sm"><%= check_box_tag "api_token[scopes][]", key, integration.scopes.include?(key), id: "scope_#{key.parameterize}", class: "mt-1" %> <span><%= label %></span></label>
<% end %>
</fieldset>
<fieldset>
<legend class="label"><%= t(".aircraft") %></legend>
<p class="hint mb-1"><%= t(".aircraft_hint") %></p>
<% Aircraft.ordered.each do |a| %>
<label class="mr-4 inline-flex items-center gap-2 text-sm"><%= check_box_tag "api_token[aircraft_ids][]", a.id, Array(integration.aircraft_ids).include?(a.id), id: "aircraft_#{a.id}" %> <%= a.tail_number %></label>
<% end %>
</fieldset>
<fieldset class="space-y-2 border-t border-slate-200 pt-4">
<legend class="label"><%= t(".webhook") %></legend>
<p class="hint"><%= t(".webhook_hint") %></p>
<%= url_field_tag "webhook[url]", endpoint&.url, class: "input", placeholder: "https://redmine.example.com/sam/webhook", "aria-label": t(".webhook_url") %>
<% WebhookEndpoint::EVENTS.each do |key, label| %>
<label class="flex items-start gap-2 text-sm"><%= check_box_tag "webhook[events][]", key, Array(endpoint&.events).include?(key), id: "event_#{key.parameterize}", class: "mt-1" %> <span><%= label %> <code class="text-xs text-slate-500"><%= key %></code></span></label>
<% end %>
<% if endpoint&.persisted? %>
<%= hidden_field_tag "webhook[enabled]", "0", id: nil %>
<label class="flex items-center gap-2 text-sm"><%= check_box_tag "webhook[enabled]", "1", endpoint.enabled %> <%= t(".webhook_enabled") %></label>
<% end %>
</fieldset>
<%= f.submit integration.persisted? ? t(".save") : t(".create"), class: "btn-primary" %>
<% end %>
@@ -0,0 +1,15 @@
<% content_for :title, @integration.name %>
<section class="card card-body max-w-xl space-y-3">
<h1 class="card-title"><%= @integration.name %></h1>
<p class="text-sm text-slate-600"><%= t(".copy_now") %></p>
<% if @integration.token %>
<label class="label" for="integration_token"><%= t(".token") %></label>
<input id="integration_token" class="input font-mono text-sm" value="<%= @integration.token %>" readonly>
<% end %>
<% if @secret %>
<label class="label" for="webhook_secret"><%= t(".webhook_secret") %></label>
<input id="webhook_secret" class="input font-mono text-sm" value="<%= @secret %>" readonly>
<p class="hint"><%= t(".secret_hint") %></p>
<% end %>
<p><%= link_to t(".done"), admin_integration_path(@integration), class: "btn-primary" %></p>
</section>
@@ -0,0 +1,3 @@
<% content_for :title, @integration.name %>
<h1 class="mb-4 text-2xl font-bold"><%= @integration.name %></h1>
<%= render "form", integration: @integration, endpoint: @endpoint %>
@@ -0,0 +1,17 @@
<% content_for :title, t(".integrations") %>
<div class="mb-4 flex items-center justify-between"><h1 class="text-2xl font-bold"><%= t(".integrations") %></h1><%= link_to t(".new_integration"), new_admin_integration_path, class: "btn-primary" %></div>
<p class="mb-4 max-w-3xl text-sm text-slate-600"><%= t(".what_html", docs: link_to(t(".api_docs"), help_page_path("api"), class: "link")) %></p>
<% if @integrations.any? %>
<section class="card"><table class="table">
<thead><tr><th><%= t(".name") %></th><th><%= t(".aircraft") %></th><th><%= t(".webhook") %></th><th><%= t(".last_used") %></th></tr></thead>
<tbody><% @integrations.each do |i| %><tr>
<td><%= link_to i.name, admin_integration_path(i), class: "link font-medium" %> <% if i.revoked? %><span class="badge-red"><%= t(".revoked") %></span><% end %>
<div class="text-xs text-slate-500"><code><%= i.token_hint %>…</code></div></td>
<td class="text-xs"><%= Aircraft.where(id: Array(i.aircraft_ids)).order(:tail_number).pluck(:tail_number).join(", ").presence || "—" %></td>
<td class="text-xs"><%= (e = i.webhook_endpoints.first) ? e.url : "—" %></td>
<td class="text-xs text-slate-500"><%= i.last_used_at ? t(".ago", ago: time_ago_in_words(i.last_used_at)) : t(".never") %></td>
</tr><% end %></tbody>
</table></section>
<% else %>
<%= empty_state t(".none_yet") %>
<% end %>
@@ -0,0 +1,3 @@
<% content_for :title, t(".new_integration") %>
<h1 class="mb-4 text-2xl font-bold"><%= t(".new_integration") %></h1>
<%= render "form", integration: @integration, endpoint: @endpoint %>
@@ -0,0 +1,49 @@
<% content_for :title, @integration.name %>
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
<h1 class="text-2xl font-bold"><%= @integration.name %> <% if @integration.revoked? %><span class="badge-red align-middle text-sm"><%= t(".revoked") %></span><% end %></h1>
<% unless @integration.revoked? %>
<div class="flex gap-2">
<%= link_to t(".edit"), edit_admin_integration_path(@integration), class: "btn-secondary" %>
<%= button_to t(".revoke"), admin_integration_path(@integration), method: :delete, class: "btn-danger",
form: { data: { turbo_confirm: t(".revoke_confirm", name: @integration.name) } } %>
</div>
<% end %>
</div>
<div class="grid max-w-5xl items-start gap-5 lg:grid-cols-2">
<section class="card card-body">
<h2 class="card-title"><%= t(".token") %></h2>
<dl class="mt-2 grid gap-y-2 text-sm">
<div class="detail-row"><dt><%= t(".hint") %></dt><dd><code><%= @integration.token_hint %>…</code></dd></div>
<div class="detail-row"><dt><%= t(".scopes") %></dt><dd><%= @integration.scopes.map { ApiToken::SCOPES[_1] }.to_sentence %></dd></div>
<div class="detail-row"><dt><%= t(".aircraft") %></dt><dd><%= Aircraft.where(id: Array(@integration.aircraft_ids)).order(:tail_number).pluck(:tail_number).join(", ").presence || "—" %></dd></div>
<div class="detail-row"><dt><%= t(".created") %></dt><dd><%= fmt_time(@integration.created_at) %> · <%= @integration.user.display_name %></dd></div>
<div class="detail-row"><dt><%= t(".last_used") %></dt><dd><%= @integration.last_used_at ? "#{fmt_time(@integration.last_used_at)} · #{@integration.last_used_ip}" : t(".never") %></dd></div>
</dl>
</section>
<section class="card card-body">
<h2 class="card-title"><%= t(".webhook") %></h2>
<% if @endpoint %>
<dl class="mt-2 grid gap-y-2 text-sm">
<div class="detail-row"><dt><%= t(".url") %></dt><dd class="break-all"><%= @endpoint.url %> <% unless @endpoint.enabled %><span class="badge-gray"><%= t(".paused") %></span><% end %></dd></div>
<div class="detail-row"><dt><%= t(".events") %></dt><dd><%= @endpoint.events.map { WebhookEndpoint::EVENTS[_1] }.to_sentence %></dd></div>
</dl>
<% unless @integration.revoked? %>
<div class="mt-3"><%= button_to t(".new_secret"), new_secret_admin_integration_path(@integration), class: "btn-secondary btn-sm",
form: { data: { turbo: false, turbo_confirm: t(".new_secret_confirm") } } %></div>
<% end %>
<% else %>
<p class="mt-1 text-sm text-slate-600"><%= t(".no_webhook") %></p>
<% end %>
</section>
</div>
<% if @deliveries.any? %>
<section class="card mt-5 max-w-5xl">
<div class="card-header"><h2 class="card-title"><%= t(".recent_deliveries") %></h2></div>
<table class="table"><thead><tr><th><%= t(".when") %></th><th><%= t(".event") %></th><th><%= t(".result") %></th></tr></thead>
<tbody><% @deliveries.each do |d| %><tr>
<td class="text-xs"><%= fmt_time(d.created_at) %></td><td><code class="text-xs"><%= d.event %></code></td>
<td class="text-xs"><span class="<%= { "delivered" => "badge-green", "failed" => "badge-red" }.fetch(d.status, "badge-gray") %>"><%= t(".status.#{d.status}") %></span>
<%= d.response_status %> <%= d.last_error %> <% if d.attempts > 1 %>· <%= t(".attempts", count: d.attempts) %><% end %></td>
</tr><% end %></tbody></table>
</section>
<% end %>
+8
View File
@@ -0,0 +1,8 @@
<% content_for :title, t(".title") %>
<section class="card card-body max-w-xl space-y-3">
<h1 class="card-title"><%= t(".title") %></h1>
<p class="text-sm text-slate-600"><%= t(".copy_now", name: @token.name) %></p>
<input class="input font-mono text-sm" value="<%= @token.token %>" readonly aria-label="<%= t(".token") %>">
<p class="hint"><%= t(".how_to_use_html") %></p>
<p><%= link_to t(".done"), edit_profile_path(anchor: "api"), class: "btn-primary" %></p>
</section>
+2 -2
View File
@@ -46,7 +46,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(".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(".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 %>
@@ -67,7 +67,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(".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(".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>
+28
View File
@@ -136,6 +136,34 @@
</div>
</section>
<section class="card card-body" id="api">
<h2 class="card-title"><%= t(".api_tokens") %></h2>
<p class="mt-1 text-sm text-slate-600"><%= t(".api_tokens_what_html", docs: link_to(t(".api_docs"), help_page_path("api"), class: "link")) %></p>
<% tokens = @user.api_tokens.personal.active.order(:created_at) %>
<% if tokens.any? %>
<ul class="mt-3 divide-y divide-slate-100 rounded-md ring-1 ring-slate-200">
<% tokens.each do |token| %>
<li class="flex flex-wrap items-center justify-between gap-2 px-3 py-2 text-sm">
<span><span class="font-medium"><%= token.name %></span> <code class="text-xs text-slate-500"><%= token.token_hint %>…</code>
<span class="block text-xs text-slate-500"><%= token.scopes.map { ApiToken::SCOPES[_1] }.to_sentence %> ·
<%= token.last_used_at ? t(".api_token_used", ago: time_ago_in_words(token.last_used_at)) : t(".api_token_unused") %></span></span>
<%= button_to t(".revoke"), api_token_path(token), method: :delete, class: "btn-secondary btn-sm",
form: { data: { turbo_confirm: t(".revoke_token", name: token.name) } } %>
</li>
<% end %>
</ul>
<% end %>
<%= form_with model: ApiToken.new, url: api_tokens_path, class: "mt-3 space-y-2", data: { turbo: false } do |f| %>
<%= f.text_field :name, class: "input", placeholder: t(".api_token_name"), required: true, maxlength: 80, "aria-label": t(".api_token_name") %>
<fieldset class="space-y-1 text-sm">
<% ApiToken::SCOPES.each do |key, label| %>
<label class="flex items-start gap-2"><%= check_box_tag "api_token[scopes][]", key, key == "read", id: "api_token_scope_#{key.parameterize}", class: "mt-1" %> <span><%= label %></span></label>
<% end %>
</fieldset>
<%= f.submit t(".create_api_token"), class: "btn-secondary" %>
<% end %>
</section>
<section class="card card-body">
<h2 class="card-title"><%= t(".integrations") %></h2>
<p class="mt-1 text-sm text-slate-600">