mirror of
https://github.com/rickbarrette/simple-aircraft-manager-rails.git
synced 2026-11-17 15:50:36 -05:00
Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a5ca534fd1 | ||
|
|
d956cfbe83 | ||
|
|
34e3232350 | ||
|
|
3ad6b9493a | ||
|
|
9adbc3d0a8 | ||
|
|
c360edfce0 | ||
|
|
9a20c91f5e | ||
|
|
19bc3efa19 | ||
|
|
b4c7aaa3ff | ||
|
|
a645778f26 | ||
|
|
3e5d896662 | ||
|
|
d8cd462194 | ||
|
|
d2cd60c6a7 | ||
|
|
34879e7310 | ||
|
|
e8b0cd030e | ||
|
|
e4bc3a5b7b | ||
|
|
d9de1be562 | ||
|
|
66fa5f4423 | ||
|
|
2e8d789975 | ||
|
|
e4c27c6ff7 | ||
|
|
bffdea937c | ||
|
|
ec0f43019f |
No files matched your search
+9
-1
@@ -46,7 +46,7 @@ FORCE_SSL=true
|
||||
# OIDC_CLIENT_ID=
|
||||
# OIDC_CLIENT_SECRET=
|
||||
# OIDC_PROVIDER_NAME=Authentik
|
||||
# OIDC_AUTO_CREATE_USERS=false # true: create an account at first sign-in
|
||||
# OIDC_AUTO_CREATE_USERS=false # true: an account at first sign-in for anyone the provider lets in, without an invitation
|
||||
# OIDC_TRUST_EMAIL=false # true: link accounts by unverified email
|
||||
# OIDC_ADMIN_GROUP= # members become admins (synced at sign-in)
|
||||
|
||||
@@ -64,6 +64,14 @@ FORCE_SSL=true
|
||||
# LOGBOOK_AI_MODEL=claude-opus-5-5
|
||||
# LOGBOOK_AI_EFFORT=high
|
||||
|
||||
# --- Push notifications --------------------------------------------------
|
||||
# Optional: without them the app makes a pair once and keeps it in storage/vapid_keys.json.
|
||||
# Changing the pair turns notifications off on every device until turned on again.
|
||||
# VAPID_PUBLIC_KEY=
|
||||
# VAPID_PRIVATE_KEY= # bin/rails runner 'k = WebPush.generate_key; puts k.public_key, k.private_key'
|
||||
|
||||
# --- Other ---------------------------------------------------------------
|
||||
# APP_LOCALE=en # language, e.g. es for config/locales/es.yml
|
||||
# APP_REPOSITORY_URL= # source link on Admin → About (for a fork)
|
||||
# APP_IMAGE= # image for the records package's viewer, used as is (for a fork); default: the published one at this release
|
||||
# RAILS_LOG_LEVEL=info
|
||||
@@ -2,6 +2,47 @@
|
||||
|
||||
Each release has a **version** (year.month.release, e.g. 2026.11.0) and a **build** (the exact source commit, shown on Admin → About). The newest release is first.
|
||||
|
||||
## 2026.11.7
|
||||
|
||||
### Changes
|
||||
|
||||
- **Correct a flight.** Open it and choose **Edit**: the date, airports, route, notes, oil and fuel (its oil and fuel records follow) and its files can always be fixed. The meter readings only on the latest flight, while nothing else has changed the hours; the aircraft and its components then move by the difference. On earlier flights the readings are shown locked. Owners can correct any flight; pilots, the ones they logged.
|
||||
- **Roles you can set up.** Each person has a role on each aircraft: **Owner**, **Mechanic** (maintenance records, signing, components, inspections, ADs, squawks, reminders), **Pilot** (as before) or **Viewer** (sees everything, changes nothing). Owners and pilots keep exactly what they could do. Buttons for what your role doesn't allow aren't shown.
|
||||
- **Reminders and overdue alerts** go to the roles that get them: Owners and Mechanics, as roles come.
|
||||
- **Records package viewer, with no account.** The package's `viewer/docker-compose.yml` now runs a read-only copy on the recipient's computer: `docker compose up`, open http://localhost:3000, and the records are there (imported by itself, nothing can be changed, reachable only from that computer). It runs the release that made the package.
|
||||
|
||||
### For administrators
|
||||
|
||||
- **Admin → Roles**: change what Mechanic, Pilot and Viewer can do (31 permissions, grouped), or add your own roles (a partner, an instructor). Owner always has everything. **Admin → Users → Edit** lists each person's role on every aircraft, to add, change or remove. Only an Owner (or an administrator) can give the Owner role, nobody changes their own, and every aircraft keeps an Owner.
|
||||
- **Admin → Invitations**: a link that makes an account (or is accepted with one) and gives roles on aircraft; limited uses, an expiry, optionally one email address (and then emailed). With single sign-on, **Continue with** on the invitation makes the account.
|
||||
- **New accounts come only from an administrator**, an administrator's invitation, or an Owner's signing invitation to an outside mechanic (for that address). Signing invitations from others need an existing account.
|
||||
- **Who can add aircraft** (Admin → Settings) is **administrators only** by default: adding or importing an aircraft makes you its Owner, who can bring in mechanics. **After this update, other users can't add aircraft** until you choose *Everyone* there.
|
||||
- `OIDC_AUTO_CREATE_USERS=true` still gives an account to anyone the identity provider lets in, without an invitation; leave it off to keep accounts to administrators and their invitations.
|
||||
- The REST API follows the person's role; its `owners_only` error is now `not_permitted`.
|
||||
- The update adds the roles and invitations tables, filled in automatically when the new version starts.
|
||||
- The compose files and `.env.example` mention the first-run setup code and the push notification, language and image settings.
|
||||
|
||||
### Fixes
|
||||
|
||||
- Disabled fields look disabled (they looked like any other).
|
||||
- The records package's viewer said to just create an account (it needs the setup code since 2026.11.5) and named the wrong menu.
|
||||
|
||||
## 2026.11.6
|
||||
|
||||
### Changes
|
||||
|
||||
- **PDFs show on phones.** Android showed nothing for a PDF document and iPhones only its first page. On phones and tablets every page is now drawn in the app, as it scrolls into view, downloading only the parts of the file those pages need (a long manual opens quickly and doesn't use up mobile data). Computers keep the browser's own PDF viewer.
|
||||
- **Connection status in the top bar.** It turns red when the server can't be reached, and back on its own when it can. A ring fills while pages are saved for offline use or what was logged offline is sent; it's amber with a count while flights or squawks wait to send.
|
||||
- **A weak signal counts as no signal.** Log Flight and Report Squawk say "Sending…" and, if the server doesn't answer within 10 seconds (a minute with photos), keep the entry on the phone and send it when the connection's back. If it got through after all, it isn't logged twice. Every page falls back to its offline copy or the offline page instead of loading forever.
|
||||
- **The activity log loads as you scroll** (it stopped at 200 events).
|
||||
- **What's new** shows the running version's notes on Admin → About; older releases fold to one line each.
|
||||
- **REST API** for other programs, such as a script that pulls what's coming due or a work-order system: read aircraft, parts, due items, inspections, ADs, squawks and logbook entries; report and update squawks; send draft logbook entries to be signed in the app. Webhooks announce squawks reported, updated and resolved, entries signed, and drafts completed. Personal tokens are made in Profile. The API never signs an entry; see Help → REST API.
|
||||
|
||||
### For administrators
|
||||
|
||||
- **Admin → Integrations** makes tokens for other systems, acting for the person each request names, limited to the aircraft chosen, plus webhook endpoints.
|
||||
- The update adds the API's tables; they're created automatically when the new version starts.
|
||||
|
||||
## 2026.11.5
|
||||
|
||||
### Changes
|
||||
|
||||
@@ -88,12 +88,14 @@ The app is a standard Rails app. Run `bin/rails db:prepare && bin/thrust bin/rai
|
||||
| `APP_URL` | Optional public base URL, e.g. `https://aircraft.example.com` (default `https://APP_HOST`). Used for the SSO and Google Drive redirect URIs. |
|
||||
| `OIDC_ISSUER`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET` | Optional. Turn on single sign-on with an OpenID Connect provider (see below). |
|
||||
| `OIDC_PROVIDER_NAME` | Button label, e.g. `Authentik` (default `SSO`). |
|
||||
| `OIDC_AUTO_CREATE_USERS` | `true` creates an account for anyone the provider lets in. New accounts start with no aircraft. Default off: an admin adds users first. |
|
||||
| `OIDC_AUTO_CREATE_USERS` | `true` creates an account for anyone the provider lets in, without an invitation. New accounts start with no aircraft. Default off: accounts come only from an admin, an admin's invitation, or an Owner's signing invitation (signing in with SSO from the link makes the account). |
|
||||
| `OIDC_TRUST_EMAIL` | `true` links existing accounts by email even if the provider doesn't mark it verified. Only use it if users can't edit their own email at the provider. |
|
||||
| `OIDC_ADMIN_GROUP` | Optional. Members of this provider group become admins and others lose admin, synced at each sign-in. |
|
||||
| `PWNED_PASSWORDS_CHECK` | `false` turns off the check of new passwords against Have I Been Pwned (only the first 5 characters of the password's SHA-1 are sent). Use it if the server has no outbound internet access; the check also allows the password if the service can't be reached. |
|
||||
| `PASSWORD_LOGIN` | `false` hides email/password sign-in, emailed sign-in links and password resets once SSO works. It's ignored while SSO isn't configured, so you can't lock yourself out. |
|
||||
| `APP_REPOSITORY_URL` | Optional. The source code link on Admin → About, for a fork. |
|
||||
| `APP_IMAGE` | Optional. The image the records package's viewer runs, used as is (for a fork). Default: the published image at the release that made the package. |
|
||||
| `SAM_VIEWER`, `SAM_VIEWER_ARCHIVE` | **Only for the records package's viewer** (its `viewer/docker-compose.yml` sets them). `SAM_VIEWER=true` makes the app a read-only copy with no sign-in: it imports the `.sam.zip` at `SAM_VIEWER_ARCHIVE` at start, everyone browses as a built-in account, and nothing can be changed. It refuses to start on a database with any user account, so turning it on for a real installation stops the app instead of exposing its records. |
|
||||
| `APP_REVISION`, `APP_BUILT_AT` | Set as Docker build arguments (see the `Dockerfile`) so Admin → About shows the version and the records keep a software version history. |
|
||||
|
||||
### Single sign-on (Authentik example)
|
||||
@@ -138,9 +140,9 @@ To back up or move a single aircraft with all its files, use **More → Download
|
||||
| Fleet dashboard | Every aircraft you can access, with airworthiness status and its top issues. |
|
||||
| Airworthiness | Grounded / limited (e.g. "VFR only" for an overdue 91.411 check) / due soon / current, from AD compliance, grounding squawks, inspections, replacement-critical and expiring parts, and expiring documents (an expired registration grounds). Warnings start 10 hours or 30 days ahead. The pilot in command still decides airworthiness (91.7). Logic: `app/services/airworthiness.rb`, `app/services/compliance.rb`. |
|
||||
| Hours | Absolute tach/hobbs updates or per-flight logs. Both apply the delta to every in-service component. Downward corrections are clamped at 0. Each aircraft picks tach or Hobbs as its maintenance clock (time in service). |
|
||||
| Flight import | Owners can import historical flights from `.xlsx` or `.csv` (Date, From, To, Tach, Hobbs, Oil Added, Fuel Added). Each flight's time is derived from the previous row's reading. A preview flags typos such as a tach going backwards, and rows already imported are skipped. History only: component hours aren't changed unless you choose to advance the aircraft's meters. |
|
||||
| Flight import | Import historical flights from `.xlsx` or `.csv` (Date, From, To, Tach, Hobbs, Oil Added, Fuel Added). Each flight's time is derived from the previous row's reading. A preview flags typos such as a tach going backwards, and rows already imported are skipped. History only: component hours aren't changed unless you choose to advance the aircraft's meters. |
|
||||
| Airworthiness enforcement | Optional per aircraft. It blocks flight logs and hours updates while the aircraft is grounded (not for limitations). |
|
||||
| Components | Tree of parent and child parts, TBO and replacement limits, and service/replace reset. Owners can create new component types inline. |
|
||||
| Components | Tree of parent and child parts, TBO and replacement limits, and service/replace reset. New component types can be created inline. |
|
||||
| Squawks | Four priorities. "Ground Aircraft" grounds the aircraft. Inoperative items can be deferred under 91.213(d) after confirming each condition; resolving can record the fix as a logbook entry. Attachments, reopen. |
|
||||
| Notes | Per-aircraft notes in Markdown, with a preview; shown on share links. |
|
||||
| ADs and bulletins | Shared across aircraft and applicable to the airframe or to specific components. Hour- and month-based recurrence (due at end of month), conditional and non-mandatory types, per-aircraft "not applicable" determinations, and compliance history with method of compliance and the revision complied with. |
|
||||
@@ -148,35 +150,40 @@ To back up or move a single aircraft with all its files, use **More → Download
|
||||
| AD import | Import ADs from an FAA DRS export (`.xlsx` recommended: its AD numbers link to each AD's DRS page, which the import keeps; `.csv` works without links). ADs are matched by number, so nothing is duplicated. The preview suggests Track, Not applicable or Skip for each AD, and flags superseded or non-current ADs, model mismatches, appliance or STC-only ADs, and repetitive actions. |
|
||||
| Inspections | Shared inspection types with hour, month, and day recurrence, plus history. Each says what overdue means (grounded, no IFR, no transponder, advisory); an annual can also count as the 100-hour, and the 100-hour's 10-hour overrun is credited (91.409(b)). One click adds the standard Part 91 set. |
|
||||
| Logbook | Maintenance entries with search and a link to a scanned document page. Records the signer's certificate kind and number and an inspection's result, and flags what 43.9 / 43.11 needs that's missing. Entries transcribed by Claude stay "unverified" until someone checks them against the scan. Entry templates (built-in pilot preventive maintenance per 43.3(g) and Part 43 Appendix A(c); admins add and edit their own under Admin → Logbook templates). Engine and propeller entries link the component and record its total time and time since overhaul (SMOH/SFOH/SNEW) at the entry, worked out from the entry's airframe total time; sub-components (an oil filter on the engine…) can be included with their own times. Print entries as a PDF on Avery 5163/8163 or 5164/8164 labels or half-letter/letter pages (boxed) to sign and put in the paper logbook. |
|
||||
| Documents | Collections, multi-file documents with a page viewer, per-document share visibility, bulk upload, and expiration dates (registration, insurance…). Their text is read for search: PDF text layers directly, scans by Tesseract OCR (in the image) or optionally Claude. |
|
||||
| Documents | Collections, multi-file documents with a page viewer (PDFs drawn page by page with PDF.js on phones, fetching only the pages viewed), per-document share visibility, bulk upload, and expiration dates (registration, insurance…). Their text is read for search: PDF text layers directly, scans by Tesseract OCR (in the image) or optionally Claude. |
|
||||
| Electronic signatures | Logbook entries can be signed electronically along the lines of AC 120-78B chapter 2: the signer reviews the entry, picks their certificate, re-enters their password (or signs in again with SSO) and confirms a "Certified by" statement. The signature records who, which certificate, the statement, the time and a SHA-256 fingerprint of the entry, sealed by the server; the signer gets an email. Signed entries are locked: a correction is a new signed entry that supersedes the original. Owners can invite an outside mechanic to sign one entry with their own account. Disabled accounts can't sign; their past signatures stay. |
|
||||
| Records integrity | Every change to maintenance records is kept (who, when, field by field) in a hash chain per aircraft (Activity → Record history). Nightly: a verified SQLite backup in `storage/backups` (how many are kept: Admin → Settings), then a check of the history chains and every signature; admins are emailed on a problem (Admin → About). Software versions are recorded. A records package (Access & Sharing) bundles every entry as a PDF with signatures, a signature register, the history, the status report and the `.sam.zip` for the FAA or a buyer, with a README (and a ready-to-run `viewer/docker-compose.yml`) so the recipient can browse the data in their own local copy of the app. Scans of paper logbooks can be marked as legacy records, with an "electronic records since" date per aircraft. |
|
||||
| Records integrity | Every change to maintenance records is kept (who, when, field by field) in a hash chain per aircraft (Activity → Record history). Nightly: a verified SQLite backup in `storage/backups` (how many are kept: Admin → Settings), then a check of the history chains and every signature; admins are emailed on a problem (Admin → About). Software versions are recorded. A records package (Access & Sharing) bundles every entry as a PDF with signatures, a signature register, the history, the status report and the `.sam.zip` for the FAA or a buyer, with a README and a ready-to-run `viewer/docker-compose.yml`: `docker compose up` gives the recipient a read-only copy of the app on their own computer, with the archive imported and no sign-in (`SAM_VIEWER`). Scans of paper logbooks can be marked as legacy records, with an "electronic records since" date per aircraft. |
|
||||
| Off-site backup | Nightly copy of the verified database snapshot (newest 30 kept) and every new uploaded file to Google Drive, using your own Google OAuth client and the `drive.file` scope (the app sees only its own files). Restore test from the admin page; failures emailed to admins; `bin/rails offsite:restore_files` brings files back after a restore. |
|
||||
| Recordkeeping procedures and audits | Admin → Recordkeeping Procedures generates the procedures document AC 120-78B asks for (who is responsible, who may sign, signing, corrections, backups, access, audits, transfer, legacy records) from the system setup plus a few details you fill in (with suggested text built from the installation's settings; a revision can't be adopted while a [bracketed] blank is left); adopt it as numbered, unchangeable revisions, included in the records package. Admin → Records Audits is a periodic QC checklist (app checks plus a restore test, a sample of entries against source documents and a user review); admins get the due date in the weekly reminder. The users' instructions are the guide's [Electronic records and signing](docs/guide/records.md) page. |
|
||||
| Major repairs and alterations | Form 337, STC, and ICA tracking; an STC's ICA can become a tracked recurring inspection. |
|
||||
| Weight & balance | History of empty weight and CG (linked to the alteration that changed them) and a loading calculator: takeoff and landing weight and CG against max gross and the CG envelope. The envelope can be entered as CG (inches) or as moment (lb-in/1000, as in POH moment charts and Garmin Pilot). |
|
||||
| Status report | A printable maintenance status (91.417(a)(2)): total times, life-limited parts, time since overhaul, inspections, ADs with method and revision, major alterations, open discrepancies. Also on maintenance share links. |
|
||||
| Calendar feed | A private iCalendar link (Profile) with everything coming due on your aircraft as all-day events; hour-based items get a date projected from the past year's flying. |
|
||||
| Reminders | A Monday email to owners when something is overdue or coming due, 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). |
|
||||
| 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`. |
|
||||
| Access | Admin, owner, and pilot 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. |
|
||||
| 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)), admins' invitation links (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. |
|
||||
| Help | The [user guide](docs/guide/README.md), shown in the app under **Help**. |
|
||||
|
||||
### Roles
|
||||
|
||||
| Action | Admin | Owner | Pilot |
|
||||
|---|:-:|:-:|:-:|
|
||||
| View everything on the aircraft | ✓ | ✓ | ✓ |
|
||||
| Update hours, log flights, add squawks/notes/oil/fuel | ✓ | ✓ | ✓ |
|
||||
| Defer squawks (91.213(d)) | ✓ | ✓ | ✓ |
|
||||
| Sign logbook entries with their own certificate | ✓ | ✓ | ✓ |
|
||||
| Edit or delete squawks and notes, resolve squawks | ✓ | ✓ | |
|
||||
| Components, logbook, ADs, inspections, documents, major records | ✓ | ✓ | |
|
||||
| Edit or delete aircraft, manage people and share links | ✓ | ✓ | |
|
||||
| Create aircraft (creator becomes owner) | ✓ | ✓ | ✓ |
|
||||
| Users, component types, airports, templates, settings, off-site backup, procedures and audits | ✓ | | |
|
||||
Each person has a role on each aircraft, and a role is a set of permissions (`app/models/permission.rb`) that administrators change under **Admin → Roles**, where they can also add their own. The built-in roles as they come:
|
||||
|
||||
| Action | Viewer | Pilot | Mechanic | Owner |
|
||||
|---|:-:|:-:|:-:|:-:|
|
||||
| View everything on the aircraft | ✓ | ✓ | ✓ | ✓ |
|
||||
| Log flights, correct own flights | | ✓ | | ✓ |
|
||||
| Update hours, report and defer squawks (91.213(d)), add notes/oil/fuel | | ✓ | ✓ | ✓ |
|
||||
| Sign logbook entries with their own certificate | | ✓ | ✓ | ✓ |
|
||||
| Logbook, components, ADs, inspections, documents, major records, W&B; edit squawks, notes, oil/fuel | | | ✓ | ✓ |
|
||||
| Reminders and overdue alerts | | | ✓ | ✓ |
|
||||
| Correct or delete any flight, imports, exports, restore from history | | | | ✓ |
|
||||
| Edit or delete the aircraft, manage people and share links | | | | ✓ |
|
||||
|
||||
Owner always has every permission. Only an Owner can give the Owner role, nobody changes their own, and every aircraft keeps an Owner. Administrators can do everything on every aircraft and manage users, roles, component types, airports, templates, settings, off-site backup, procedures and audits. Whoever adds an aircraft becomes its Owner (who can add aircraft is an admin setting: administrators only by default). Controllers declare the permission each action needs (`requires_permission`); a write with none declared is refused.
|
||||
|
||||
Users who aren't on an aircraft get a 404 for it, identical to a missing record.
|
||||
|
||||
@@ -197,15 +204,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 only by an admin, by the first-run setup, by someone opening an admin's invitation link (with a password, or SSO), by an outside mechanic from an Owner's signing invitation (for its address), or at first SSO sign-in when `OIDC_AUTO_CREATE_USERS` is on. Who can add aircraft, and so become an Owner, is an admin setting (administrators only by default).
|
||||
|
||||
### 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
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
--color-page: oklch(96.8% 0.007 247.896); /* slate-100 */
|
||||
--color-surface: oklch(100% 0 0); /* white: cards, inputs, menus */
|
||||
--color-header: oklch(20.8% 0.042 265.755); /* slate-900: top bar, dark in both themes */
|
||||
--color-header-offline: oklch(50.5% 0.213 27.518); /* red-700: top bar when the server can't be reached */
|
||||
--color-accent: oklch(50% 0.134 242.749); /* sky-700: primary buttons */
|
||||
--color-accent-hover: oklch(44.3% 0.11 240.79); /* sky-800 */
|
||||
}
|
||||
@@ -25,7 +26,7 @@
|
||||
@utility card-body { @apply p-4; }
|
||||
|
||||
@utility label { @apply block text-sm font-medium text-slate-700 mb-1; }
|
||||
@utility input { @apply block w-full rounded-md border-0 px-2.5 py-1.5 text-sm text-slate-900 shadow-sm ring-1 ring-slate-300 ring-inset placeholder:text-slate-400 focus:ring-2 focus:ring-sky-600 focus:outline-none bg-surface; }
|
||||
@utility input { @apply block w-full rounded-md border-0 px-2.5 py-1.5 text-sm text-slate-900 shadow-sm ring-1 ring-slate-300 ring-inset placeholder:text-slate-400 focus:ring-2 focus:ring-sky-600 focus:outline-none bg-surface disabled:cursor-not-allowed disabled:bg-slate-100 disabled:text-slate-500 disabled:shadow-none disabled:ring-slate-200; }
|
||||
@utility hint { @apply mt-1 text-xs text-slate-500; }
|
||||
@utility field-error { @apply mt-1 text-xs text-red-600; }
|
||||
|
||||
@@ -62,6 +63,7 @@
|
||||
--color-page: oklch(15.5% 0.035 264);
|
||||
--color-surface: oklch(20.8% 0.042 265.755);
|
||||
--color-header: oklch(12.9% 0.042 264.695);
|
||||
--color-header-offline: oklch(44.4% 0.177 26.899); /* red-800 */
|
||||
--color-accent: oklch(50% 0.134 242.749); /* same blue: white text stays ≥ 4.5:1 */
|
||||
--color-accent-hover: oklch(54% 0.15 242);
|
||||
|
||||
@@ -190,3 +192,32 @@
|
||||
@apply grid grid-cols-[6.5rem_minmax(0,1fr)] items-baseline gap-x-3;
|
||||
& > dt { @apply text-slate-500; }
|
||||
}
|
||||
|
||||
/* The top bar's connection status (connection_controller.js, after
|
||||
SilverBullet): red when the server can't be reached, and a ring that fills
|
||||
with the percentage in its hole while saving for offline or sending. Amber
|
||||
and full while flights or squawks wait to send, with how many. */
|
||||
header.is-offline { --color-header: var(--color-header-offline); }
|
||||
.sync-ring {
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
flex: none;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 9999px;
|
||||
background: conic-gradient(var(--ring-color, white) var(--progress, 0%), rgb(255 255 255 / 0.25) 0);
|
||||
}
|
||||
.sync-ring[hidden] { display: none; }
|
||||
.sync-ring.is-waiting { --ring-color: oklch(87.9% 0.169 91.605); } /* amber-300 */
|
||||
.sync-ring > span {
|
||||
position: absolute;
|
||||
inset: 2.5px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 9999px;
|
||||
background-color: var(--color-header);
|
||||
font-size: 9px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
line-height: 1;
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
# search terms used.
|
||||
class AdAlertsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!
|
||||
requires_permission :manage_ads
|
||||
before_action :set_alert, only: %i[track dismiss]
|
||||
rate_limit to: 5, within: 1.minute, only: :check, with: -> { redirect_to aircraft_airworthiness_directives_path(@aircraft), alert: t("flash.ad_alerts.try_again_in_a") }
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
class AdCompliancesController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!
|
||||
requires_permission :manage_ads
|
||||
before_action :set_compliance, only: %i[edit update destroy]
|
||||
|
||||
def new
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
class AdImportsController < ApplicationController
|
||||
include AircraftScoped
|
||||
include StoredUpload
|
||||
before_action :require_owner!
|
||||
requires_permission :manage_ads
|
||||
|
||||
def new; end
|
||||
|
||||
|
||||
@@ -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,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,57 @@
|
||||
# The roles people can have on an aircraft and what each allows (Role,
|
||||
# Permission). Owner always has every permission; the other built-in roles
|
||||
# can be changed but not deleted; administrators can add their own.
|
||||
class Admin::RolesController < ApplicationController
|
||||
before_action :require_admin!
|
||||
before_action :set_role, only: %i[edit update destroy]
|
||||
|
||||
def index
|
||||
Role.ensure_built_in!
|
||||
@roles = Role.ordered
|
||||
@counts = AircraftRole.group(:role_id).count
|
||||
end
|
||||
|
||||
def new
|
||||
@role = Role.new(permissions: Permission::DEFAULTS["viewer"])
|
||||
end
|
||||
|
||||
def create
|
||||
@role = Role.new(role_params)
|
||||
if @role.save
|
||||
redirect_to admin_roles_path, notice: t("flash.admin_roles.created", name: @role.name)
|
||||
else
|
||||
render :new, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
def edit; end
|
||||
|
||||
def update
|
||||
attributes = @role.owner? ? role_params.except(:permissions) : role_params
|
||||
if @role.update(attributes)
|
||||
redirect_to admin_roles_path, notice: t("flash.admin_roles.updated", name: @role.name)
|
||||
else
|
||||
render :edit, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
def destroy
|
||||
if @role.built_in?
|
||||
redirect_to admin_roles_path, alert: t("flash.admin_roles.built_in")
|
||||
elsif @role.aircraft_roles.exists?
|
||||
redirect_to admin_roles_path, alert: t("flash.admin_roles.in_use", name: @role.name, count: @role.aircraft_roles.count)
|
||||
else
|
||||
@role.destroy!
|
||||
redirect_to admin_roles_path, notice: t("flash.admin_roles.deleted", name: @role.name)
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_role = @role = Role.find(params[:id])
|
||||
|
||||
# Unticking every box sends none, so an empty list is always sent too.
|
||||
def role_params
|
||||
params.require(:role).permit(:name, :description, permissions: []).tap { _1[:permissions] = Array(_1[:permissions]).compact_blank }
|
||||
end
|
||||
end
|
||||
@@ -2,18 +2,18 @@ class Admin::SettingsController < ApplicationController
|
||||
before_action :require_admin!
|
||||
|
||||
def edit
|
||||
@values = %w[max_upload_mb backups_kept offsite_backups_kept documents_claude_text].index_with { Setting.integer(_1) }
|
||||
@values = %w[max_upload_mb backups_kept offsite_backups_kept documents_claude_text anyone_adds_aircraft].index_with { Setting.integer(_1) }
|
||||
end
|
||||
|
||||
def update
|
||||
submitted = params.fetch(:settings, {}).permit(:max_upload_mb, :backups_kept, :offsite_backups_kept, :documents_claude_text).to_h
|
||||
submitted = params.fetch(:settings, {}).permit(:max_upload_mb, :backups_kept, :offsite_backups_kept, :documents_claude_text, :anyone_adds_aircraft).to_h
|
||||
records = Setting.update_integers(submitted)
|
||||
@errors = records.flat_map { _1.errors.full_messages }
|
||||
if @errors.empty?
|
||||
Rails.logger.info("[settings] #{current_user.email_address} changed #{submitted.inspect}")
|
||||
redirect_to edit_admin_settings_path, notice: t("flash.admin_settings.settings_saved")
|
||||
else
|
||||
@values = %w[max_upload_mb backups_kept offsite_backups_kept documents_claude_text].index_with { Setting.integer(_1) }.merge(submitted)
|
||||
@values = %w[max_upload_mb backups_kept offsite_backups_kept documents_claude_text anyone_adds_aircraft].index_with { Setting.integer(_1) }.merge(submitted)
|
||||
render :edit, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# Administrators give people roles on any aircraft (from Admin → Users),
|
||||
# under the same rules as the aircraft's Access page (AircraftAccess).
|
||||
class Admin::UserAircraftRolesController < ApplicationController
|
||||
before_action :require_admin!
|
||||
before_action :set_user
|
||||
|
||||
def create
|
||||
aircraft = Aircraft.find_by(id: params[:aircraft_id])
|
||||
return back(alert: t("services.aircraft_access.not_found")) unless aircraft
|
||||
back_with AircraftAccess.new(aircraft, actor: current_user).add(@user, Role.find_by(id: params[:role_id])),
|
||||
t("flash.admin_users.access_added", tail_number: aircraft.tail_number)
|
||||
end
|
||||
|
||||
def update
|
||||
membership = @user.aircraft_roles.find(params[:id])
|
||||
back_with AircraftAccess.new(membership.aircraft, actor: current_user).change(membership, Role.find_by(id: params[:role_id])),
|
||||
t("flash.admin_users.access_changed", tail_number: membership.aircraft.tail_number)
|
||||
end
|
||||
|
||||
def destroy
|
||||
membership = @user.aircraft_roles.find(params[:id])
|
||||
back_with AircraftAccess.new(membership.aircraft, actor: current_user).remove(membership),
|
||||
t("flash.admin_users.access_removed", tail_number: membership.aircraft.tail_number)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_user = @user = User.find(params[:user_id])
|
||||
def back(flash) = redirect_to(edit_admin_user_path(@user, anchor: "access"), flash)
|
||||
def back_with(error, notice) = back(error ? { alert: error } : { notice: notice })
|
||||
end
|
||||
@@ -3,7 +3,7 @@ class Admin::UsersController < ApplicationController
|
||||
before_action :set_user, only: %i[edit update destroy disable enable unlock reset_two_factor]
|
||||
|
||||
def index
|
||||
@users = User.order(:email_address).includes(:certificates, aircraft_roles: :aircraft)
|
||||
@users = User.order(:email_address).includes(:certificates, aircraft_roles: %i[aircraft role])
|
||||
end
|
||||
|
||||
def new
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# Download the aircraft's flights as an AirTrail import file.
|
||||
class AirTrailExportsController < ApplicationController
|
||||
include AircraftScoped
|
||||
requires_permission :log_flights
|
||||
|
||||
def new
|
||||
@export = build_export
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
class AircraftController < ApplicationController
|
||||
include AircraftScoped
|
||||
skip_before_action :set_aircraft, only: %i[index new create]
|
||||
before_action :require_owner!, only: %i[edit update destroy]
|
||||
skip_before_action :set_aircraft, :authorize_permission!, only: %i[index new create]
|
||||
before_action :require_aircraft_adder!, only: %i[new create]
|
||||
requires_permission :edit_aircraft, only: %i[edit update]
|
||||
requires_permission :delete_aircraft, only: :destroy
|
||||
requires_permission :update_hours, only: :update_hours
|
||||
|
||||
def index
|
||||
@aircraft_list = current_user.accessible_aircraft.ordered.with_attached_picture
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Download an aircraft as a .sam.zip archive (owners and admins).
|
||||
class AircraftExportsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!
|
||||
requires_permission :export_data
|
||||
|
||||
EXPORT_DIR = Rails.root.join("tmp/exports")
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
# create an aircraft with all its records. The archive is checked right away;
|
||||
# the import itself runs in the background (AircraftImportJob).
|
||||
class AircraftImportsController < ApplicationController
|
||||
before_action :require_aircraft_adder!, only: %i[new create]
|
||||
before_action :set_import, only: :show
|
||||
|
||||
def new; end
|
||||
|
||||
@@ -1,54 +1,37 @@
|
||||
# Owner-only: manage who can access the aircraft, and its public share links.
|
||||
# Who can access the aircraft, with which role ("manage people"), and its
|
||||
# public share links ("manage sharing", see ShareTokensController). The rules
|
||||
# for changing roles are in AircraftAccess.
|
||||
class AircraftRolesController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!
|
||||
checks_permission_itself only: :index
|
||||
requires_permission :manage_people, only: %i[create update destroy]
|
||||
|
||||
def index
|
||||
@roles = @aircraft.roles.includes(:user).order(:role, :created_at)
|
||||
return permission_denied unless can?(:manage_people) || can?(:manage_sharing) || can?(:export_data)
|
||||
@access = AircraftAccess.new(@aircraft, actor: current_user)
|
||||
@roles = @aircraft.roles.includes(:user, :role).joins(:role).order("roles.position", :created_at)
|
||||
@share_tokens = @aircraft.share_tokens.order(created_at: :desc).includes(:created_by)
|
||||
end
|
||||
|
||||
def create
|
||||
user = User.find_by(email_address: params[:email_address].to_s.strip.downcase)
|
||||
unless user
|
||||
return redirect_to aircraft_aircraft_roles_path(@aircraft),
|
||||
alert: t("flash.aircraft_roles.no_user_with_that")
|
||||
end
|
||||
role = @aircraft.roles.new(user: user, role: params[:role])
|
||||
if role.save
|
||||
log_event("role", t("flash.aircraft_roles.added_as", display_name: user.display_name, role: role.role))
|
||||
redirect_to aircraft_aircraft_roles_path(@aircraft), notice: t("flash.aircraft_roles.added", display_name: user.display_name)
|
||||
else
|
||||
redirect_to aircraft_aircraft_roles_path(@aircraft), alert: role.errors.full_messages.to_sentence
|
||||
end
|
||||
return back(alert: t("flash.aircraft_roles.no_user_with_that")) unless user
|
||||
error = access.add(user, Role.find_by(id: params[:role_id]))
|
||||
back(error ? { alert: error } : { notice: t("flash.aircraft_roles.added", display_name: user.display_name) })
|
||||
end
|
||||
|
||||
def update
|
||||
role = @aircraft.roles.find(params[:id])
|
||||
if demoting_last_owner?(role, params[:role])
|
||||
return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: t("flash.aircraft_roles.an_aircraft_must_keep")
|
||||
end
|
||||
role.update!(role: params[:role])
|
||||
log_event("role", t("flash.aircraft_roles.changed_to", display_name: role.user.display_name, role: role.role))
|
||||
redirect_to aircraft_aircraft_roles_path(@aircraft), notice: t("flash.aircraft_roles.role_updated")
|
||||
error = access.change(@aircraft.roles.find(params[:id]), Role.find_by(id: params[:role_id]))
|
||||
back(error ? { alert: error } : { notice: t("flash.aircraft_roles.role_updated") })
|
||||
end
|
||||
|
||||
def destroy
|
||||
role = @aircraft.roles.find(params[:id])
|
||||
if role.user == current_user
|
||||
return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: t("flash.aircraft_roles.you_can_t_remove")
|
||||
end
|
||||
if demoting_last_owner?(role, nil)
|
||||
return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: t("flash.aircraft_roles.an_aircraft_must_keep_2")
|
||||
end
|
||||
role.destroy!
|
||||
log_event("role", t("flash.aircraft_roles.removed", display_name: role.user.display_name))
|
||||
redirect_to aircraft_aircraft_roles_path(@aircraft), notice: t("flash.aircraft_roles.access_removed")
|
||||
error = access.remove(@aircraft.roles.find(params[:id]))
|
||||
back(error ? { alert: error } : { notice: t("flash.aircraft_roles.access_removed") })
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def demoting_last_owner?(role, new_role)
|
||||
role.role == "owner" && new_role != "owner" && @aircraft.roles.owners.count <= 1
|
||||
end
|
||||
def access = AircraftAccess.new(@aircraft, actor: current_user)
|
||||
def back(flash) = redirect_to(aircraft_aircraft_roles_path(@aircraft), flash)
|
||||
end
|
||||
@@ -1,7 +1,7 @@
|
||||
# Flights → Standardize airport codes (owners).
|
||||
class AirportCodesController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!
|
||||
requires_permission :edit_any_flight
|
||||
|
||||
def show
|
||||
@standardizer = AirportCodeStandardizer.new(@aircraft)
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
class AirworthinessDirectivesController < ApplicationController
|
||||
include AircraftScoped
|
||||
include Applicability
|
||||
before_action :require_owner!, except: :index
|
||||
requires_permission :manage_ads, except: :index
|
||||
before_action :set_ad, only: %i[edit update destroy]
|
||||
|
||||
def index
|
||||
@rows = Compliance.ad_rows(@aircraft)
|
||||
@history = AdCompliance.for_aircraft(@aircraft).recent_first
|
||||
.includes(:component, :logbook_entry, airworthiness_directive: :document, inspection_record: :inspection_type)
|
||||
@attachable = AirworthinessDirective.where.not(id: @aircraft.applicable_ads.select(:id)).ordered if owner?
|
||||
@attachable = AirworthinessDirective.where.not(id: @aircraft.applicable_ads.select(:id)).ordered if can?(:manage_ads)
|
||||
@alerts = @aircraft.ad_alerts.pending
|
||||
end
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,127 @@
|
||||
# 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)
|
||||
|
||||
# What the person it's acting for can do on the aircraft, as in the app (Role).
|
||||
def can?(permission, aircraft) = acting_user&.can?(permission, aircraft) || false
|
||||
|
||||
def not_permitted(permission)
|
||||
render_error(:forbidden, "not_permitted", "This needs the \"#{Permission.label(permission)}\" permission on the aircraft.")
|
||||
end
|
||||
|
||||
# ?limit= (1–200, default 50), ?after=<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
|
||||
@@ -0,0 +1,129 @@
|
||||
module Api
|
||||
module V1
|
||||
# Draft logbook entries for one visit (docs/api.md, "Draft entries"). The
|
||||
# work items become one unsigned entry per logbook, signed in the app; the
|
||||
# squawks they resolve and inspections they complete are held until every
|
||||
# entry is signed. Like writing entries in the app, it's for the
|
||||
# aircraft's owners.
|
||||
class DraftBatchesController < BaseController
|
||||
before_action -> { require_scope!(:read) }, only: %i[index show lookup]
|
||||
before_action -> { require_scope!("drafts:write") }, :require_person!, only: %i[create destroy]
|
||||
|
||||
def index
|
||||
scope = find_aircraft.draft_batches.includes(entries: :signature)
|
||||
scope = scope.where(status: params[:status]) if params[:status].present?
|
||||
render_page(scope) { ApiPresenter.draft_batch(_1) }
|
||||
end
|
||||
|
||||
def lookup
|
||||
scope = DraftBatch.where(aircraft: aircraft_scope, external_ref: params.require(:external_ref)).includes(entries: :signature)
|
||||
render json: { data: scope.map { ApiPresenter.draft_batch(_1) } }
|
||||
end
|
||||
|
||||
def show
|
||||
render json: { data: ApiPresenter.draft_batch(find_batch) }
|
||||
end
|
||||
|
||||
# POST /aircraft/:aircraft_id/draft_batches
|
||||
def create
|
||||
@aircraft = find_aircraft
|
||||
return not_permitted(:write_logbook) unless can?(:write_logbook, @aircraft)
|
||||
|
||||
input = params.require(:draft_batch)
|
||||
items = Array(input[:items]).map { _1.permit(:log, :text, :external_ref, resolves_squawks: []) }
|
||||
errors = check(input, items)
|
||||
return render_error(:unprocessable_entity, "invalid", errors.values.flatten.to_sentence, fields: errors) if errors.any?
|
||||
|
||||
invitations = {}
|
||||
batch = DraftBatch.transaction do
|
||||
b = @aircraft.draft_batches.create!(api_token: api_token, created_by: acting_user, external_ref: input[:external_ref],
|
||||
signer_email: signer_email(input), held: held(input, items))
|
||||
items.group_by { _1[:log] }.each do |log, group|
|
||||
entry = b.entries.create!(aircraft: @aircraft, log_type: log, date: input[:date], text: group.map { _1[:text].to_s.strip }.join("\n\n"),
|
||||
entry_type: inspection_logs(input, items).include?(log) ? "INSPECTION" : "MAINTENANCE",
|
||||
inspection_result: inspection_result_for(input, items, log),
|
||||
aircraft_hours_at_entry: input[:aircraft_hours].presence, external_ref: group.filter_map { _1[:external_ref] }.join(",").presence)
|
||||
invitations[entry.id] = invite(entry, b.signer_email, send: input.dig(:signer, :send_email).to_s == "true") if b.signer_email
|
||||
end
|
||||
b
|
||||
end
|
||||
@aircraft.log_event!("logbook", I18n.t("api.draft_batches.sent", count: batch.entries.size, name: api_token.name), notes: batch.external_ref)
|
||||
render json: { data: ApiPresenter.draft_batch(batch.reload, invitations: invitations) }, status: :created
|
||||
end
|
||||
|
||||
# DELETE /draft_batches/:id: withdraw it while nothing in it is signed.
|
||||
def destroy
|
||||
batch = find_batch
|
||||
return not_permitted(:write_logbook) unless can?(:write_logbook, batch.aircraft)
|
||||
unless batch.awaiting? && batch.entries.none?(&:signed?)
|
||||
return render_error(:conflict, "signed", "Part of this draft is signed (or it's no longer awaiting signature); correct it in the app instead.")
|
||||
end
|
||||
batch.withdraw!
|
||||
render json: { data: ApiPresenter.draft_batch(batch.reload) }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def find_batch = DraftBatch.where(aircraft: aircraft_scope).includes(entries: :signature).find(params[:id])
|
||||
|
||||
def check(input, items)
|
||||
errors = Hash.new { |h, k| h[k] = [] }
|
||||
errors[:items] << "at least one item is needed" if items.empty?
|
||||
items.each_with_index do |item, i|
|
||||
errors[:"items.#{i}.log"] << "must be one of #{LogbookEntry::LOG_TYPES.keys.join(', ')}" unless LogbookEntry::LOG_TYPES.key?(item[:log])
|
||||
errors[:"items.#{i}.text"] << "can't be blank" if item[:text].blank?
|
||||
end
|
||||
errors[:date] << "must be a date (YYYY-MM-DD)" unless (Date.iso8601(input[:date].to_s) rescue nil)
|
||||
errors[:aircraft_hours] << "must be a number" if input[:aircraft_hours].present? && !input[:aircraft_hours].to_s.match?(/\A\d+(\.\d+)?\z/)
|
||||
squawk_ids = items.flat_map { Array(_1[:resolves_squawks]) }.map(&:to_i)
|
||||
missing = squawk_ids - @aircraft.squawks.active.where(id: squawk_ids).ids
|
||||
errors[:resolves_squawks] << "no open squawk #{missing.join(', ')} on this aircraft" if missing.any?
|
||||
Array(input[:completes_inspections]).each_with_index do |c, i|
|
||||
id = c.respond_to?(:[]) ? c[:inspection_type_id].to_i : 0
|
||||
errors[:"completes_inspections.#{i}"] << "no inspection #{id} applies to this aircraft" unless @aircraft.applicable_inspection_types.exists?(id: id)
|
||||
log = inspection_log(c, items)
|
||||
errors[:"completes_inspections.#{i}.log"] << "must be the log of one of the items" unless items.any? { _1[:log] == log }
|
||||
unless LogbookEntry::INSPECTION_RESULTS.key?(c.respond_to?(:[]) ? c[:result].to_s : "")
|
||||
errors[:"completes_inspections.#{i}.result"] << "must be #{LogbookEntry::INSPECTION_RESULTS.keys.join(' or ')}"
|
||||
end
|
||||
end
|
||||
Array(input[:completes_inspections]).group_by { inspection_log(_1, items) }.each do |log, group|
|
||||
errors[:completes_inspections] << "inspections in the #{log} log need the same result (one entry)" if group.map { _1[:result].to_s }.uniq.size > 1
|
||||
end
|
||||
errors[:aircraft_hours] << "is needed to record an inspection" if Array(input[:completes_inspections]).any? && input[:aircraft_hours].blank?
|
||||
email = input.dig(:signer, :email).to_s.strip
|
||||
errors[:"signer.email"] << "isn't an email address" if email.present? && !email.match?(URI::MailTo::EMAIL_REGEXP)
|
||||
errors[:"signer.send_email"] << "needs email set up on the server" if input.dig(:signer, :send_email).to_s == "true" && !MailSettings.configured?
|
||||
errors
|
||||
end
|
||||
|
||||
# The inspection goes in the logbook named for it, else the airframe
|
||||
# log if there's an item for it, else the first item's.
|
||||
def inspection_log(c, items)
|
||||
c[:log].presence || (items.any? { _1[:log] == "AC" } ? "AC" : items.first&.dig(:log))
|
||||
end
|
||||
|
||||
def inspection_logs(input, items) = Array(input[:completes_inspections]).map { inspection_log(_1, items) }
|
||||
|
||||
# approved | discrepancies, for the entry in that log that records inspections.
|
||||
def inspection_result_for(input, items, log)
|
||||
Array(input[:completes_inspections]).find { inspection_log(_1, items) == log }&.dig(:result)
|
||||
end
|
||||
|
||||
def held(input, items)
|
||||
{ "squawks" => items.flat_map { |it| Array(it[:resolves_squawks]).map { |id| { "id" => id.to_i, "log" => it[:log] } } }.uniq { _1["id"] },
|
||||
"inspections" => Array(input[:completes_inspections]).map { { "id" => _1[:inspection_type_id].to_i, "log" => inspection_log(_1, items) } } }
|
||||
end
|
||||
|
||||
def signer_email(input) = input.dig(:signer, :email).to_s.strip.downcase.presence
|
||||
|
||||
# A link for the signer to sign this entry with their own account,
|
||||
# returned to the caller to pass on; emailed too when asked.
|
||||
def invite(entry, email, send: false)
|
||||
invitation = entry.signing_invitations.create!(email: email, invited_by: acting_user)
|
||||
SigningInvitationMailer.invite(invitation, invitation.token).deliver_later if send
|
||||
invitation.token
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -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,67 @@
|
||||
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
|
||||
return not_permitted(:report_squawks) unless can?(:report_squawks, aircraft)
|
||||
squawk = aircraft.squawks.new(create_params.merge(reported_by: acting_user, resolved: false))
|
||||
squawk.component_id = nil unless aircraft.components.exists?(id: squawk.component_id)
|
||||
squawk.save!
|
||||
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) with "manage squawks", as in the app.
|
||||
def update
|
||||
squawk = find_squawk
|
||||
return render_error(:unprocessable_entity, "resolved", "A resolved squawk can't be changed.") if squawk.resolved?
|
||||
attrs = params.require(:squawk).permit(:external_ref, :issue_reported, :priority, :component_id, :notes)
|
||||
if (attrs.keys - %w[external_ref]).any? && !can?(:manage_squawks, squawk.aircraft)
|
||||
return not_permitted(:manage_squawks)
|
||||
end
|
||||
attrs[:component_id] = nil if attrs.key?(:component_id) && !squawk.aircraft.components.exists?(id: attrs[:component_id])
|
||||
squawk.update!(attrs)
|
||||
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
|
||||
@@ -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
|
||||
@@ -4,8 +4,9 @@ class ApplicationController < ActionController::Base
|
||||
include TimeZones
|
||||
allow_browser versions: :modern
|
||||
|
||||
include RejectsNullBytes
|
||||
prepend_before_action :redirect_to_setup
|
||||
prepend_before_action :reject_null_bytes
|
||||
prepend_before_action :viewer_guard # first (see Viewer)
|
||||
before_action { Current.ip_address = request.remote_ip } # for record history
|
||||
helper_method :current_user
|
||||
|
||||
@@ -36,28 +37,31 @@ 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
|
||||
|
||||
# First run: no users yet → create the initial admin.
|
||||
# Viewer mode: never with real accounts, and nothing can be changed.
|
||||
def viewer_guard
|
||||
return unless Viewer.enabled?
|
||||
return render(plain: Viewer::RealAccounts.new.message, status: :service_unavailable) if Viewer.real_accounts?
|
||||
Viewer.user
|
||||
return if request.get? || request.head?
|
||||
respond_to do |format|
|
||||
format.html { redirect_back fallback_location: root_path, alert: t("viewer.read_only") }
|
||||
format.any { head :forbidden }
|
||||
end
|
||||
end
|
||||
|
||||
def redirect_to_setup
|
||||
redirect_to new_setup_path if !User.exists? && !is_a?(SetupController)
|
||||
end
|
||||
|
||||
# Adding or importing an aircraft (User#can_add_aircraft?).
|
||||
def require_aircraft_adder!
|
||||
redirect_to root_path, alert: t("flash.aircraft.ask_an_administrator") unless current_user.can_add_aircraft?
|
||||
end
|
||||
|
||||
def require_admin!
|
||||
redirect_to root_path, alert: t("flash.application.admins_only") unless current_user&.admin?
|
||||
end
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
class ComponentsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!, except: %i[index show]
|
||||
requires_permission :manage_components, except: %i[index show]
|
||||
before_action :set_component, only: %i[show edit update destroy reset_service]
|
||||
|
||||
def index
|
||||
|
||||
@@ -1,16 +1,38 @@
|
||||
# Scopes a controller to one aircraft the current user can access and exposes
|
||||
# role helpers. Unknown and inaccessible aircraft both 404 (enumeration-safe).
|
||||
# Scopes a controller to one aircraft the current user can access, and checks
|
||||
# what their role there allows (Role, Permission). Unknown and inaccessible
|
||||
# aircraft both 404 (enumeration-safe). Administrators can do everything.
|
||||
#
|
||||
# Access matrix (mirrors the original):
|
||||
# admin – everything
|
||||
# owner – everything on their aircraft
|
||||
# pilot – view all; update hours; create squawks, notes, oil/fuel, flight logs
|
||||
# Each controller says which permission its actions need:
|
||||
#
|
||||
# requires_permission :manage_components, except: %i[index show]
|
||||
# requires_permission :report_squawks, only: %i[new create]
|
||||
# checks_permission_itself only: %i[edit update] # decided in the controller
|
||||
#
|
||||
# Looking needs no permission. A request that changes something (anything but
|
||||
# GET/HEAD) with no permission declared for its action is refused, so nothing
|
||||
# is left open by mistake; in development and tests it raises instead.
|
||||
module AircraftScoped
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
SELF_CHECKED = "(checked by the controller)".freeze
|
||||
|
||||
class MissingPermission < StandardError; end
|
||||
|
||||
included do
|
||||
class_attribute :permission_rules, instance_accessor: false, default: []
|
||||
before_action :set_aircraft
|
||||
helper_method :current_role, :owner?, :can_write?
|
||||
before_action :authorize_permission!
|
||||
helper_method :current_role, :can?, :owner?
|
||||
end
|
||||
|
||||
class_methods do
|
||||
def requires_permission(permission, only: nil, except: nil)
|
||||
self.permission_rules += [ [ permission.to_s, only && Array(only).map(&:to_s), except && Array(except).map(&:to_s) ] ]
|
||||
end
|
||||
|
||||
def checks_permission_itself(only:)
|
||||
requires_permission(SELF_CHECKED, only: only)
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
@@ -21,18 +43,35 @@ module AircraftScoped
|
||||
@aircraft = current_user.accessible_aircraft.find(aircraft_param)
|
||||
end
|
||||
|
||||
# Their Role here (nil for an administrator without one).
|
||||
def current_role
|
||||
@current_role ||= current_user.role_for(@aircraft)
|
||||
return @current_role if defined?(@current_role)
|
||||
@current_role = current_user.role_for(@aircraft)
|
||||
end
|
||||
|
||||
# Owner-level write access (admins included).
|
||||
def owner? = current_role.in?(%w[admin owner])
|
||||
alias_method :can_write?, :owner?
|
||||
# Nothing in viewer mode (a read-only copy, see Viewer).
|
||||
def can?(permission) = !Viewer.enabled? && (current_user.admin? || current_role&.can?(permission) || false)
|
||||
|
||||
def require_owner!
|
||||
return if owner?
|
||||
redirect_back fallback_location: aircraft_path(@aircraft),
|
||||
alert: t("flash.common.only_owners_can_do")
|
||||
# The Owner role (or an administrator): everything.
|
||||
def owner? = !Viewer.enabled? && (current_user.admin? || current_role&.owner? || false)
|
||||
|
||||
def authorize_permission!
|
||||
rules = self.class.permission_rules.select do |_, only, except|
|
||||
(only.nil? || only.include?(action_name)) && (except.nil? || except.exclude?(action_name))
|
||||
end
|
||||
if rules.empty?
|
||||
return if request.get? || request.head?
|
||||
raise MissingPermission, "#{self.class.name}##{action_name} changes data without declaring a permission" if Rails.env.local?
|
||||
return permission_denied
|
||||
end
|
||||
permission_denied unless rules.all? { |permission, *| permission == SELF_CHECKED || can?(permission) }
|
||||
end
|
||||
|
||||
def permission_denied
|
||||
respond_to do |format|
|
||||
format.html { redirect_back fallback_location: aircraft_path(@aircraft), alert: t("flash.common.not_allowed") }
|
||||
format.any { head :forbidden }
|
||||
end
|
||||
end
|
||||
|
||||
# Returns id only if it belongs to the given (aircraft-scoped) relation; else nil.
|
||||
|
||||
@@ -21,7 +21,12 @@ module Authentication
|
||||
end
|
||||
|
||||
def require_authentication
|
||||
resume_session || request_authentication
|
||||
resume_session || start_viewer_session || request_authentication
|
||||
end
|
||||
|
||||
# Viewer mode: everyone is its built-in account, without signing in.
|
||||
def start_viewer_session
|
||||
start_new_session_for(Viewer.user) if Viewer.enabled? && !Viewer.real_accounts?
|
||||
end
|
||||
|
||||
def resume_session
|
||||
|
||||
@@ -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,6 +1,7 @@
|
||||
class ConsumableRecordsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!, only: %i[edit update destroy]
|
||||
requires_permission :record_consumables, only: %i[new create]
|
||||
requires_permission :manage_consumables, only: %i[edit update destroy]
|
||||
before_action :set_record, only: %i[edit update destroy]
|
||||
|
||||
RECORDS_PER_PAGE = 50
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
class DocumentCollectionsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!
|
||||
requires_permission :manage_documents
|
||||
before_action :set_collection, only: %i[edit update destroy]
|
||||
|
||||
def new
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
class DocumentsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!, except: %i[index show]
|
||||
requires_permission :manage_documents, except: %i[index show]
|
||||
before_action :set_document, only: %i[show edit update destroy]
|
||||
|
||||
def index
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
# who they are again (password, or single sign-on just now), and confirms.
|
||||
class EntrySignaturesController < ApplicationController
|
||||
include AircraftScoped
|
||||
requires_permission :sign_logbook
|
||||
include EntrySigning
|
||||
before_action :set_entry
|
||||
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
class EventsController < ApplicationController
|
||||
include AircraftScoped
|
||||
|
||||
EVENTS_PER_PAGE = 50
|
||||
|
||||
# A page at a time; the rest load as you scroll (each page ends in a lazy
|
||||
# frame that fetches the next).
|
||||
def index
|
||||
@category = params[:category].presence_in(AircraftEvent::CATEGORIES.keys)
|
||||
scope = @aircraft.events.includes(:user)
|
||||
@page = [ params[:page].to_i, 1 ].max
|
||||
scope = @aircraft.events.includes(:user).reorder(created_at: :desc, id: :desc)
|
||||
scope = scope.where(category: @category) if @category
|
||||
@events = scope.limit(200)
|
||||
rows = scope.offset((@page - 1) * EVENTS_PER_PAGE).limit(EVENTS_PER_PAGE + 1).to_a
|
||||
@more = rows.size > EVENTS_PER_PAGE
|
||||
@events = rows.first(EVENTS_PER_PAGE)
|
||||
render(partial: "events/page", locals: { events: @events, page: @page, more: @more, category: @category }) if turbo_frame_request?
|
||||
end
|
||||
end
|
||||
@@ -2,7 +2,7 @@
|
||||
class FlightImportsController < ApplicationController
|
||||
include AircraftScoped
|
||||
include StoredUpload
|
||||
before_action :require_owner!
|
||||
requires_permission :import_flights
|
||||
|
||||
def new; end
|
||||
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
class FlightLogsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!, only: :destroy
|
||||
before_action :set_flight_log, only: %i[show engine_data_series attach_engine_data remove_engine_data]
|
||||
requires_permission :log_flights, only: %i[new create]
|
||||
requires_permission :delete_flights, only: :destroy
|
||||
checks_permission_itself only: %i[edit update attach_engine_data remove_engine_data]
|
||||
before_action :set_flight_log, only: %i[show edit update engine_data_series attach_engine_data remove_engine_data]
|
||||
before_action :require_flight_editor!, only: %i[edit update]
|
||||
helper_method :can_edit_flight?
|
||||
before_action :require_engine_data_access!, only: %i[attach_engine_data remove_engine_data]
|
||||
helper_method :manage_engine_data?
|
||||
|
||||
@@ -99,6 +103,22 @@ class FlightLogsController < ApplicationController
|
||||
redirect_to aircraft_flight_log_path(@aircraft, @flight_log), notice: t("flash.flight_logs.engine_data_removed")
|
||||
end
|
||||
|
||||
def edit
|
||||
@meters_editable = @flight_log.meters_editable?
|
||||
end
|
||||
|
||||
# A correction. The readings only change on the latest flight (see
|
||||
# FlightLog#meters_editable?); on earlier ones they're left as they are.
|
||||
def update
|
||||
@meters_editable = @flight_log.meters_editable?
|
||||
attributes = flight_log_params.except(:client_key)
|
||||
attributes = attributes.except(*FlightLog::METERS) unless @meters_editable
|
||||
HoursService.new(@aircraft).update_flight!(@flight_log, attributes)
|
||||
redirect_to aircraft_flight_log_path(@aircraft, @flight_log), notice: t("flash.flight_logs.flight_corrected")
|
||||
rescue ActiveRecord::RecordInvalid
|
||||
render :edit, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
# Deleting a flight does not roll back hours; correct those with an hours update.
|
||||
def destroy
|
||||
@aircraft.flight_logs.find(params[:id]).destroy!
|
||||
@@ -108,14 +128,22 @@ class FlightLogsController < ApplicationController
|
||||
|
||||
private
|
||||
|
||||
# Any flight with "correct any flight"; the ones they logged with "correct own flights".
|
||||
def can_edit_flight?(flight)
|
||||
can?(:edit_any_flight) || (can?(:edit_own_flights) && flight.user_id.present? && flight.user_id == current_user.id)
|
||||
end
|
||||
|
||||
def require_flight_editor!
|
||||
return if can_edit_flight?(@flight_log)
|
||||
redirect_to aircraft_flight_log_path(@aircraft, @flight_log), alert: t("flash.flight_logs.only_owners_or_the")
|
||||
end
|
||||
|
||||
def set_flight_log
|
||||
@flight_log = @aircraft.flight_logs.find(params[:id])
|
||||
end
|
||||
|
||||
# Owners, or the pilot who logged the flight.
|
||||
def manage_engine_data?
|
||||
owner? || (@flight_log.user_id.present? && @flight_log.user_id == current_user.id)
|
||||
end
|
||||
def manage_engine_data? = can_edit_flight?(@flight_log)
|
||||
|
||||
def require_engine_data_access!
|
||||
return if manage_engine_data?
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
class InspectionRecordsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!
|
||||
requires_permission :manage_inspections
|
||||
before_action :set_record, only: %i[edit update destroy]
|
||||
|
||||
def new
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
class InspectionTypesController < ApplicationController
|
||||
include AircraftScoped
|
||||
include Applicability
|
||||
before_action :require_owner!
|
||||
requires_permission :manage_inspections
|
||||
before_action :set_type, only: %i[edit update destroy]
|
||||
|
||||
def new
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# The invited signer's side: sign in (or create an account for the invited
|
||||
# address), add a certificate if needed, review the entry and sign it. The
|
||||
# invitation gives access to that one entry only.
|
||||
# The invited signer's side: sign in (or, from an Owner's invitation, create an
|
||||
# account for the invited address: SigningInvitation#creates_account?), add a
|
||||
# certificate if needed, review the entry and sign it. The invitation gives
|
||||
# access to that one entry only.
|
||||
class InvitedSigningsController < ApplicationController
|
||||
include EntrySigning
|
||||
allow_unauthenticated_access only: %i[show account]
|
||||
@@ -12,6 +13,7 @@ class InvitedSigningsController < ApplicationController
|
||||
@aircraft = @entry.aircraft
|
||||
unless authenticated?
|
||||
session[:return_to_after_authenticating] = request.url
|
||||
session[:signing_token] = params[:token] # for an account made by signing in with SSO
|
||||
return render(:welcome)
|
||||
end
|
||||
return render(:wrong_account) unless current_user.email_address == @invitation.email
|
||||
@@ -20,10 +22,10 @@ class InvitedSigningsController < ApplicationController
|
||||
render :new
|
||||
end
|
||||
|
||||
# Creating an account for the invited email address.
|
||||
# Creating an account for the invited email address (an Owner's invitation).
|
||||
def account
|
||||
return redirect_to(invited_signing_path(params[:token])) if authenticated?
|
||||
if User.exists?(email_address: @invitation.email) || !Sso.password_login?
|
||||
if User.exists?(email_address: @invitation.email) || !Sso.password_login? || !@invitation.creates_account?
|
||||
return redirect_to invited_signing_path(params[:token]), alert: t("flash.invited_signings.sign_in_to_continue")
|
||||
end
|
||||
user = User.new(params.permit(:name, :password, :password_confirmation).merge(email_address: @invitation.email))
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
# Opening an invitation link (AccessInvitation): see what it gives, then sign
|
||||
# in and accept. Only an administrator's invitation can make a new account
|
||||
# (with a password here, or by signing in with SSO: SsoController); others
|
||||
# need an existing one. An invitation for one email address only works for
|
||||
# that address. Any invalid link (unknown, expired, used up, revoked) gets
|
||||
# one answer.
|
||||
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
|
||||
session[:join_token] = params[:token] # for an account made by signing in with SSO
|
||||
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
|
||||
unless Sso.password_login? && @invitation.creates_accounts?
|
||||
return redirect_to(join_path(params[:token]), alert: t("flash.joins.sign_in_to_continue"))
|
||||
end
|
||||
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: [ t("flash.joins.welcome"), AccessInvitation.describe(results) ].join(" ").strip
|
||||
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: [ t("flash.joins.accepted"), AccessInvitation.describe(@invitation.redeem!(current_user)) ].join(" ").strip
|
||||
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
|
||||
|
||||
def current_user = Current.user || (resume_session && Current.user)
|
||||
end
|
||||
@@ -2,7 +2,7 @@
|
||||
# the loading calculator.
|
||||
class LoadingSetupsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!
|
||||
requires_permission :manage_weight_balance
|
||||
|
||||
def edit
|
||||
@setup = @aircraft.loading_setup
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
class LogbookEntriesController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!, except: %i[index show]
|
||||
requires_permission :write_logbook, except: %i[index show]
|
||||
before_action :set_entry, only: %i[show edit update destroy verify]
|
||||
before_action :require_unsigned, only: %i[edit update destroy]
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
# entries in the background (LogbookTranscriptionJob).
|
||||
class LogbookImportsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!
|
||||
requires_permission :import_records
|
||||
|
||||
def new
|
||||
@collections = @aircraft.document_collections.ordered
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
class MajorRecordsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!, except: %i[index show]
|
||||
requires_permission :manage_major_records, except: %i[index show]
|
||||
before_action :set_record, only: %i[show edit update destroy]
|
||||
|
||||
def index
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
class NotesController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!, only: %i[edit update destroy]
|
||||
requires_permission :write_notes, only: %i[new create preview]
|
||||
requires_permission :manage_notes, only: %i[edit update destroy]
|
||||
before_action :set_note, only: %i[edit update destroy]
|
||||
|
||||
def index
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
class OilAnalysesController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!, only: %i[edit update destroy]
|
||||
requires_permission :record_oil_analyses, only: %i[new create import]
|
||||
requires_permission :manage_oil_analyses, only: %i[edit update destroy]
|
||||
before_action :set_analysis, only: %i[show edit update destroy]
|
||||
|
||||
COMPARE_SAMPLES = 6 # columns in the trend table, like the lab report's history
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Every change to the aircraft's maintenance records (AC 120-78B 3.2.2).
|
||||
class RecordVersionsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!, only: :restore
|
||||
requires_permission :restore_history, only: :restore
|
||||
|
||||
SHARED = { "AirworthinessDirective" => AirworthinessDirective, "InspectionType" => InspectionType }.freeze
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Download every record of an aircraft in one ZIP (owners).
|
||||
class RecordsPackagesController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!
|
||||
requires_permission :export_data
|
||||
|
||||
def show
|
||||
package = RecordsPackage.new(@aircraft, source: request.host)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
class ShareTokensController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!
|
||||
requires_permission :manage_sharing
|
||||
|
||||
def create
|
||||
token = @aircraft.share_tokens.new(params.require(:share_token).permit(:label, :privilege, :expires_at))
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# An owner asks someone outside the aircraft (a mechanic) to sign an entry.
|
||||
class SigningInvitationsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!
|
||||
requires_permission :write_logbook
|
||||
before_action :set_entry
|
||||
rate_limit to: 10, within: 1.hour, only: :create, with: -> { redirect_back fallback_location: root_path, alert: t("flash.signing_invitations.too_many_invitations_try") }
|
||||
|
||||
@@ -22,7 +22,9 @@ class SigningInvitationsController < ApplicationController
|
||||
tail: @aircraft.tail_number, name: current_user.display_name)
|
||||
end
|
||||
log_event("logbook", t("flash.signing_invitations.signature_requested_from_entry", email: @invitation.email, date: l(@entry.date, format: :app)))
|
||||
redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: t("flash.signing_invitations.invitation_sent_to_the", email: @invitation.email, days: SigningInvitation::VALID_FOR.in_days.to_i)
|
||||
notice = t("flash.signing_invitations.invitation_sent_to_the", email: @invitation.email, days: SigningInvitation::VALID_FOR.in_days.to_i)
|
||||
notice = "#{notice} #{t('flash.signing_invitations.no_account_yet')}" unless invitee || @invitation.creates_account?
|
||||
redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: notice
|
||||
else
|
||||
render :new, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
@@ -2,7 +2,9 @@ class SquawksController < ApplicationController
|
||||
include AircraftScoped
|
||||
# Pilots may create squawks and defer inoperative items (91.213(d) lets the
|
||||
# pilot decide); editing and resolving need an owner.
|
||||
before_action :require_owner!, except: %i[index new create deferral defer]
|
||||
requires_permission :report_squawks, only: %i[new create]
|
||||
requires_permission :defer_squawks, only: %i[deferral defer]
|
||||
requires_permission :manage_squawks, except: %i[index new create deferral defer]
|
||||
before_action :set_squawk, only: %i[edit update destroy resolution resolve reopen deferral defer undefer]
|
||||
|
||||
def index
|
||||
@@ -21,11 +23,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
|
||||
|
||||
@@ -6,6 +6,11 @@
|
||||
# email is verified (or OIDC_TRUST_EMAIL is on), since some providers let
|
||||
# users edit their email. Otherwise, sign in with a password once and link
|
||||
# from the profile page.
|
||||
#
|
||||
# Someone without an account gets one only from an invitation they opened
|
||||
# first that can make one (an administrator's AccessInvitation, accepted at
|
||||
# once; an Owner's SigningInvitation, for its address), or for anyone the
|
||||
# provider lets in when OIDC_AUTO_CREATE_USERS is on.
|
||||
class SsoController < ApplicationController
|
||||
allow_unauthenticated_access only: %i[callback failure]
|
||||
before_action :require_sso
|
||||
@@ -29,6 +34,7 @@ class SsoController < ApplicationController
|
||||
return_to = session[:return_to_after_authenticating]
|
||||
reset_session # fresh session id after signing in
|
||||
start_new_session_for user
|
||||
return redirect_to(root_url, notice: [ t("flash.joins.welcome"), AccessInvitation.describe(@joined) ].join(" ").strip) if @joined
|
||||
redirect_to return_to || root_url
|
||||
end
|
||||
|
||||
@@ -81,15 +87,34 @@ class SsoController < ApplicationController
|
||||
end
|
||||
|
||||
def create_user(auth)
|
||||
return unless Sso.auto_create_users?
|
||||
email = auth.info&.email.to_s.strip.downcase
|
||||
return if email.blank? || User.exists?(email_address: email)
|
||||
# The random password is never shown; a password reset can set a real one.
|
||||
User.create!(email_address: email, name: auth.info&.name.presence, sso_uid: auth.uid, password: SecureRandom.base58(40))
|
||||
invitation = invitation_making_account(email)
|
||||
return unless invitation || signing_invitation_making_account?(email) || Sso.auto_create_users?
|
||||
User.transaction do
|
||||
# The random password is never shown; a password reset can set a real one.
|
||||
user = User.create!(email_address: email, name: auth.info&.name.presence, sso_uid: auth.uid, password: SecureRandom.base58(40))
|
||||
@joined = invitation&.redeem!(user)
|
||||
user
|
||||
end
|
||||
rescue ActiveRecord::RecordInvalid
|
||||
nil
|
||||
end
|
||||
|
||||
# A signing invitation opened in this browser before signing in, from an
|
||||
# Owner, for this email address.
|
||||
def signing_invitation_making_account?(email)
|
||||
invitation = SigningInvitation.find_usable(session[:signing_token])
|
||||
invitation.present? && invitation.creates_account? && invitation.email == email
|
||||
end
|
||||
|
||||
# The invitation opened in this browser before signing in, when it can
|
||||
# make an account (an administrator's) for this email address.
|
||||
def invitation_making_account(email)
|
||||
invitation = AccessInvitation.find_by_token(session[:join_token])
|
||||
invitation if invitation&.usable? && invitation.creates_accounts? && invitation.for_email?(email)
|
||||
end
|
||||
|
||||
def email_verified?(auth)
|
||||
[ true, "true" ].include?(raw_info(auth)["email_verified"])
|
||||
end
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
class StandardInspectionsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!
|
||||
requires_permission :manage_inspections
|
||||
|
||||
def new; end
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
# keep the records and the loading setup).
|
||||
class WeightBalanceRecordsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!, except: :index
|
||||
requires_permission :manage_weight_balance, except: :index
|
||||
before_action :set_record, only: %i[edit update destroy]
|
||||
|
||||
def index
|
||||
|
||||
@@ -3,11 +3,14 @@ module AircraftHelper
|
||||
|
||||
# What the app saves ahead of time for use without signal (see
|
||||
# offline_prep_controller.js): for each of your aircraft, the Overview, W&B,
|
||||
# Log Flight and Report Squawk pages, and its photo (at both page sizes).
|
||||
# Log Flight and Report Squawk pages (when their role allows them), and its
|
||||
# photo (at both page sizes).
|
||||
def offline_pages
|
||||
current_user.accessible_aircraft.ordered.limit(OFFLINE_AIRCRAFT).map do |a|
|
||||
role = current_user.role_for(a)
|
||||
can = ->(permission) { current_user.admin? || role&.can?(permission) }
|
||||
{ tail: a.tail_number, pages: [ aircraft_path(a), aircraft_weight_balance_records_path(a) ],
|
||||
flight: new_aircraft_flight_log_path(a), squawk: new_aircraft_squawk_path(a),
|
||||
flight: (new_aircraft_flight_log_path(a) if can.(:log_flights)), squawk: (new_aircraft_squawk_path(a) if can.(:report_squawks)),
|
||||
pictures: (%i[thumb card].map { url_for(a.picture_for(_1)) }.uniq if a.picture_shown?) }.compact
|
||||
end
|
||||
end
|
||||
|
||||
@@ -7,4 +7,15 @@ module HelpHelper
|
||||
html = HelpGuide.html(page, title: title, link: (links ? method(:help_page_url_for) : nil))
|
||||
tag.div(html.html_safe, class: "markdown guide") # rubocop:disable Rails/OutputSafety -- sanitized in HelpGuide
|
||||
end
|
||||
|
||||
# A piece of the guide's Markdown (an intro, one release's notes).
|
||||
def guide_markdown(markdown, class: nil)
|
||||
html = HelpGuide.render(markdown, link: method(:help_page_url_for))
|
||||
tag.div(html.html_safe, class: [ "markdown guide", binding.local_variable_get(:class) ]) # rubocop:disable Rails/OutputSafety -- sanitized in HelpGuide
|
||||
end
|
||||
|
||||
# "4 changes · 3 fixes · 2 for administrators"
|
||||
def release_summary(release)
|
||||
release.counts.map { |key, count| t("help.changelog.counts.#{key}", count: count) }.join(" · ")
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,118 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
import { t } from "i18n"
|
||||
|
||||
// The top bar shows the connection at a glance (as SilverBullet does):
|
||||
// - it turns red when the server can't be reached: the device is offline, or
|
||||
// a request failed (signal but no internet, or the proxy answering for the
|
||||
// app). While red it checks /up every so often and turns back on its own;
|
||||
// - a ring fills while pages are being saved for offline use or flights and
|
||||
// squawks logged offline are being sent, with the percentage in its middle;
|
||||
// - while some are waiting to send, the ring is amber with how many.
|
||||
// Others report with events on document:
|
||||
// sam:progress { source, done, total } (done >= total when finished)
|
||||
// sam:waiting { count }
|
||||
// sam:unreachable / sam:reachable
|
||||
// and it says when the server answers again with sam:back-online (what was
|
||||
// logged offline is sent then).
|
||||
// The header is replaced on every page, so the state and the listeners live
|
||||
// in this module and the header on the page just shows them.
|
||||
const RETRY_EVERY = 15 * 1000
|
||||
const UNREACHABLE = [ 502, 503, 504 ]
|
||||
const OFFLINE_COLOR = "#b91c1c" // red-700, for the phone's status bar
|
||||
const state = { online: navigator.onLine, progress: {}, waiting: 0 }
|
||||
let header = null // the controller on the page
|
||||
let checking = null
|
||||
let timer = null
|
||||
let normalColor = null
|
||||
|
||||
// Any answer from the app (even a sign-in redirect) means it's reachable.
|
||||
async function check() {
|
||||
checking ||= fetch("/up", { cache: "no-store", redirect: "manual", credentials: "same-origin" })
|
||||
.then((response) => !UNREACHABLE.includes(response.status), () => false)
|
||||
.finally(() => { checking = null })
|
||||
setOnline(await checking)
|
||||
}
|
||||
|
||||
function setOnline(online) {
|
||||
clearTimeout(timer)
|
||||
if (!online) timer = setTimeout(check, RETRY_EVERY)
|
||||
if (state.online === online) return
|
||||
state.online = online
|
||||
header?.announce(online ? t("connection.back_online") : t("connection.offline"))
|
||||
update()
|
||||
if (online) document.dispatchEvent(new CustomEvent("sam:back-online"))
|
||||
}
|
||||
|
||||
// Several reports often arrive together (done sending, then none waiting):
|
||||
// show them once, on the next frame, so the ring doesn't flicker between.
|
||||
let frame = null
|
||||
function update() {
|
||||
frame ||= requestAnimationFrame(() => { frame = null; header?.render() })
|
||||
}
|
||||
|
||||
window.addEventListener("online", check)
|
||||
window.addEventListener("offline", () => setOnline(false))
|
||||
document.addEventListener("visibilitychange", () => { if (document.visibilityState === "visible" && !state.online) check() })
|
||||
document.addEventListener("sam:unreachable", () => setOnline(false))
|
||||
document.addEventListener("turbo:fetch-request-error", () => setOnline(false))
|
||||
document.addEventListener("sam:reachable", () => setOnline(true))
|
||||
document.addEventListener("sam:progress", ({ detail }) => { state.progress[detail.source] = detail; update() })
|
||||
document.addEventListener("sam:waiting", ({ detail }) => { state.waiting = detail.count; update() })
|
||||
|
||||
// Whether the server answered last time (false while the top bar is red).
|
||||
export const serverReachable = () => state.online
|
||||
|
||||
export default class extends Controller {
|
||||
static targets = [ "ring", "label", "announce" ]
|
||||
|
||||
connect() {
|
||||
header = this
|
||||
this.themeColor = document.querySelector("meta[name=theme-color]")
|
||||
normalColor ||= this.themeColor?.content
|
||||
if (!navigator.onLine) setOnline(false)
|
||||
else if (!state.online || this.fromSavedCopy()) check() // a fresh page, or maybe the offline copy
|
||||
this.render()
|
||||
}
|
||||
|
||||
disconnect() {
|
||||
if (header === this) header = null
|
||||
}
|
||||
|
||||
fromSavedCopy() {
|
||||
const rendered = Date.parse(document.querySelector("meta[name=rendered-at]")?.content || "")
|
||||
return rendered && Date.now() - rendered > 60 * 1000
|
||||
}
|
||||
|
||||
announce(text) {
|
||||
if (this.hasAnnounceTarget) this.announceTarget.textContent = text
|
||||
}
|
||||
|
||||
render() {
|
||||
this.element.classList.toggle("is-offline", !state.online)
|
||||
this.element.title = state.online ? "" : t("connection.offline")
|
||||
if (this.themeColor && normalColor) this.themeColor.content = state.online ? normalColor : OFFLINE_COLOR
|
||||
|
||||
const busy = Object.values(state.progress).filter((p) => p.total && p.done < p.total)
|
||||
if (busy.length) {
|
||||
const done = busy.reduce((sum, p) => sum + p.done, 0)
|
||||
const total = busy.reduce((sum, p) => sum + p.total, 0)
|
||||
const percent = Math.floor((done / total) * 100)
|
||||
const what = busy.some((p) => p.source === "send") ? "sending" : "saving"
|
||||
this.showRing({ percent, number: percent, waiting: false, text: t(`connection.${what}`, { percent }) })
|
||||
} else if (state.waiting) {
|
||||
this.showRing({ percent: 100, number: state.waiting, waiting: true, text: t("connection.waiting", { count: state.waiting }) })
|
||||
} else {
|
||||
this.ringTarget.hidden = true
|
||||
}
|
||||
}
|
||||
|
||||
showRing({ percent, number, waiting, text }) {
|
||||
const ring = this.ringTarget
|
||||
ring.hidden = false
|
||||
ring.classList.toggle("is-waiting", waiting)
|
||||
ring.style.setProperty("--progress", `${percent}%`)
|
||||
ring.title = text
|
||||
ring.setAttribute("aria-label", text)
|
||||
this.labelTarget.textContent = number
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,18 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
import { t } from "i18n"
|
||||
import { queue, formFields, newKey, currentUser } from "controllers/offline_queue"
|
||||
import { serverReachable } from "controllers/connection_controller"
|
||||
|
||||
// How long to wait for the server before keeping it here instead. Photos
|
||||
// on a squawk take longer to send.
|
||||
const WAIT = 10 * 1000
|
||||
const WAIT_WITH_FILES = 60 * 1000
|
||||
|
||||
// Log Flight and Report Squawk: with no connection, the form is kept on this
|
||||
// device and sent later (see offline_sync_controller). For flights, the next
|
||||
// leg starts where the last saved one ended.
|
||||
// leg starts where the last saved one ended. A signal so weak the server
|
||||
// doesn't answer counts as none: it's kept here too, and if it got through
|
||||
// after all, the server drops the copy sent later (same client_key).
|
||||
export default class extends Controller {
|
||||
static targets = [ "key", "notice" ]
|
||||
static values = { kind: { type: String, default: "flight" }, tail: String }
|
||||
@@ -23,14 +31,21 @@ export default class extends Controller {
|
||||
|
||||
get flight() { return this.kindValue === "flight" }
|
||||
|
||||
// No connection: keep it here instead of submitting.
|
||||
// No connection (or the top bar is red): keep it here instead of submitting.
|
||||
async submit(event) {
|
||||
if (navigator.onLine) return
|
||||
if (navigator.onLine && serverReachable()) return
|
||||
event.preventDefault()
|
||||
event.stopImmediatePropagation()
|
||||
await this.save(formFields(this.element))
|
||||
}
|
||||
|
||||
// Give up waiting after a while; the request then fails (networkFailed).
|
||||
limit(event) {
|
||||
const options = event.detail.fetchOptions
|
||||
const files = [ ...this.element.querySelectorAll("input[type=file]") ].some((input) => input.files?.length)
|
||||
options.signal = AbortSignal.any([ options.signal, AbortSignal.timeout(files ? WAIT_WITH_FILES : WAIT) ].filter(Boolean))
|
||||
}
|
||||
|
||||
// Kept in case the request fails on the way (no signal but the browser thinks it's online).
|
||||
remember() { this.pending = formFields(this.element) }
|
||||
|
||||
|
||||
@@ -8,6 +8,9 @@ import { currentUser } from "controllers/offline_queue"
|
||||
// your aircraft change. Signing out clears it.
|
||||
const EVERY = 60 * 60 * 1000
|
||||
|
||||
// How far along it is, for the ring in the top bar (connection_controller.js).
|
||||
const progress = (done, total) => document.dispatchEvent(new CustomEvent("sam:progress", { detail: { source: "prep", done, total } }))
|
||||
|
||||
export default class extends Controller {
|
||||
static values = { aircraft: Array }
|
||||
|
||||
@@ -26,17 +29,26 @@ export default class extends Controller {
|
||||
const forms = {}
|
||||
const paths = [ "/" ]
|
||||
for (const a of this.aircraftValue) {
|
||||
paths.push(...a.pages, a.flight, a.squawk)
|
||||
forms[a.flight] = { tail: a.tail, kind: "flight" }
|
||||
forms[a.squawk] = { tail: a.tail, kind: "squawk" }
|
||||
paths.push(...a.pages)
|
||||
if (a.flight) { paths.push(a.flight); forms[a.flight] = { tail: a.tail, kind: "flight" } }
|
||||
if (a.squawk) { paths.push(a.squawk); forms[a.squawk] = { tail: a.tail, kind: "squawk" } }
|
||||
}
|
||||
for (const path of paths) {
|
||||
if (!navigator.onLine) return
|
||||
// One at a time, after the page has settled, so it never competes with what you're doing.
|
||||
await new Promise((resolve) => (window.requestIdleCallback || setTimeout)(resolve, { timeout: 2000 }))
|
||||
try { await fetch(path, { credentials: "same-origin", headers: { Accept: "text/html" } }) } catch (_) { return }
|
||||
}
|
||||
await this.savePictures(this.aircraftValue.flatMap((a) => a.pictures || []))
|
||||
const pictures = this.aircraftValue.flatMap((a) => a.pictures || [])
|
||||
const total = paths.length + 1
|
||||
try {
|
||||
for (const [ index, path ] of paths.entries()) {
|
||||
progress(index, total)
|
||||
if (!navigator.onLine) return
|
||||
// One at a time, after the page has settled, so it never competes with what you're doing.
|
||||
await new Promise((resolve) => (window.requestIdleCallback || setTimeout)(resolve, { timeout: 2000 }))
|
||||
try { await fetch(path, { credentials: "same-origin", headers: { Accept: "text/html" } }) } catch (_) {
|
||||
document.dispatchEvent(new CustomEvent("sam:unreachable"))
|
||||
return
|
||||
}
|
||||
}
|
||||
progress(paths.length, total)
|
||||
await this.savePictures(pictures)
|
||||
} finally { progress(total, total) }
|
||||
try {
|
||||
localStorage.setItem("sam-offline-forms", JSON.stringify({ ...JSON.parse(localStorage.getItem("sam-offline-forms") || "{}"), ...forms }))
|
||||
localStorage.setItem("sam-offline-prep", JSON.stringify({ signature, at: Date.now() }))
|
||||
|
||||
@@ -1,10 +1,20 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
import { t } from "i18n"
|
||||
import { queue } from "controllers/offline_queue"
|
||||
import { serverReachable } from "controllers/connection_controller"
|
||||
|
||||
// How long to wait for the server to take one before trying again later
|
||||
// (a weak signal can leave a request hanging for minutes). Photos take longer.
|
||||
const WAIT = 15 * 1000
|
||||
const WAIT_WITH_FILES = 60 * 1000
|
||||
|
||||
const report = (name, detail) => document.dispatchEvent(new CustomEvent(name, { detail }))
|
||||
|
||||
// On every page: sends the flights and squawks this user saved offline once
|
||||
// there's a connection, says what happened, and shows the count on the app
|
||||
// icon. A rejected item stays until it's discarded.
|
||||
// icon. A rejected item stays until it's discarded. Nothing is tried while
|
||||
// the top bar is red; it goes again as soon as it turns back
|
||||
// (connection_controller.js), signal or not.
|
||||
export default class extends Controller {
|
||||
static targets = [ "banner" ]
|
||||
|
||||
@@ -12,30 +22,37 @@ export default class extends Controller {
|
||||
this.sync = this.sync.bind(this)
|
||||
window.addEventListener("online", this.sync)
|
||||
document.addEventListener("offline-queue:changed", this.sync)
|
||||
document.addEventListener("sam:back-online", this.sync)
|
||||
this.sync()
|
||||
}
|
||||
|
||||
disconnect() {
|
||||
window.removeEventListener("online", this.sync)
|
||||
document.removeEventListener("offline-queue:changed", this.sync)
|
||||
document.removeEventListener("sam:back-online", this.sync)
|
||||
}
|
||||
|
||||
async sync() {
|
||||
let items
|
||||
try { items = await queue.mine() } catch (_) { return }
|
||||
if (!items.length) { this.badge(0); return this.show("") }
|
||||
if (!navigator.onLine || this.running) return this.status(items)
|
||||
if (!items.length) { this.badge(0); report("sam:waiting", { count: 0 }); return this.show("") }
|
||||
if (!navigator.onLine || !serverReachable() || this.running) return this.status(items)
|
||||
this.running = true
|
||||
const sent = []
|
||||
const sending = items.filter((i) => !i.error)
|
||||
try {
|
||||
for (const item of items.filter((i) => !i.error)) {
|
||||
for (const [ index, item ] of sending.entries()) {
|
||||
report("sam:progress", { source: "send", done: index, total: sending.length })
|
||||
const result = await this.send(item)
|
||||
if (result === "sent") { await queue.remove(item.id); sent.push(item) }
|
||||
if (result === "sent") { await queue.remove(item.id); sent.push(item); report("sam:reachable") }
|
||||
else if (result === "signin") { this.show(t("offline.sign_in")); return }
|
||||
else if (result === "offline") break
|
||||
else if (result === "offline") { report("sam:unreachable"); break }
|
||||
else { item.error = result; await queue.put(item) }
|
||||
}
|
||||
} finally { this.running = false }
|
||||
} finally {
|
||||
this.running = false
|
||||
report("sam:progress", { source: "send", done: 0, total: 0 })
|
||||
}
|
||||
this.status(await queue.mine(), sent)
|
||||
}
|
||||
|
||||
@@ -46,7 +63,9 @@ export default class extends Controller {
|
||||
if (token) body.append("authenticity_token", token)
|
||||
let response
|
||||
try {
|
||||
response = await fetch(item.url, { method: "POST", body, credentials: "same-origin", headers: { Accept: "text/html" } })
|
||||
const files = item.fields.some(([ , value ]) => value instanceof Blob)
|
||||
response = await fetch(item.url, { method: "POST", body, credentials: "same-origin", headers: { Accept: "text/html" },
|
||||
signal: AbortSignal.timeout(files ? WAIT_WITH_FILES : WAIT) })
|
||||
} catch (_) { return "offline" }
|
||||
if ([ 502, 503, 504 ].includes(response.status)) return "offline"
|
||||
if (response.url.includes("/session/new")) return "signin"
|
||||
@@ -68,6 +87,7 @@ export default class extends Controller {
|
||||
}
|
||||
this.show(parts.join(" "), failed)
|
||||
this.badge(items.length)
|
||||
report("sam:waiting", { count: waiting.length })
|
||||
}
|
||||
|
||||
// The number of unsent items on the installed app's icon.
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
import { t } from "i18n"
|
||||
|
||||
// A PDF in the document viewer. Desktop browsers show it in their own viewer,
|
||||
// in a frame. Phones don't: Android shows nothing in a frame and iPhones only
|
||||
// the first page, so there every page is drawn with PDF.js (public/pdfjs,
|
||||
// loaded only here), each one as it scrolls into view, fetching only the
|
||||
// parts of the file those pages need.
|
||||
export default class extends Controller {
|
||||
static targets = [ "frame", "status", "pages" ]
|
||||
static values = { url: String, pdfjs: String }
|
||||
|
||||
// Starts over each time, as a page restored from Turbo's cache comes back
|
||||
// with blank pages.
|
||||
connect() {
|
||||
this.pagesTarget.replaceChildren()
|
||||
this.statusTarget.replaceChildren(t("pdf.loading"))
|
||||
this.statusTarget.hidden = false
|
||||
if (navigator.pdfViewerEnabled && !matchMedia("(pointer: coarse)").matches) return this.showFrame()
|
||||
this.draw().catch((error) => this.failed(error))
|
||||
}
|
||||
|
||||
disconnect() {
|
||||
this.observer?.disconnect()
|
||||
this.loading?.destroy()
|
||||
}
|
||||
|
||||
showFrame() {
|
||||
this.statusTarget.hidden = true
|
||||
this.pagesTarget.append(this.frameTarget.content.cloneNode(true))
|
||||
}
|
||||
|
||||
async draw() {
|
||||
const base = this.pdfjsValue
|
||||
const pdfjs = await import(`${base}pdf.min.mjs`)
|
||||
pdfjs.GlobalWorkerOptions.workerSrc = `${base}pdf.worker.min.mjs`
|
||||
this.loading = pdfjs.getDocument({
|
||||
url: this.urlValue,
|
||||
withCredentials: true,
|
||||
// Only the parts needed for the pages being drawn, not the whole file
|
||||
// in the background (a long manual on a phone's data plan).
|
||||
disableAutoFetch: true,
|
||||
disableStream: true,
|
||||
wasmUrl: `${base}wasm/`,
|
||||
standardFontDataUrl: `${base}standard_fonts/`,
|
||||
iccUrl: `${base}iccs/`
|
||||
})
|
||||
const pdf = await this.loading.promise
|
||||
if (!this.element.isConnected) return
|
||||
|
||||
// Placeholders the size of the first page keep the scroll position steady
|
||||
// while pages are drawn; each takes its own shape once it's drawn.
|
||||
const first = (await pdf.getPage(1)).getViewport({ scale: 1 })
|
||||
// Pages are drawn as they come near the screen and let go once they're
|
||||
// far from it, so a long manual doesn't use up a phone's memory.
|
||||
this.observer = new IntersectionObserver((entries) => {
|
||||
for (const { target, isIntersecting } of entries) {
|
||||
target.dataset.near = isIntersecting
|
||||
if (isIntersecting && !target.dataset.drawn) this.drawPage(pdf, target)
|
||||
else if (!isIntersecting && target.dataset.drawn) { delete target.dataset.drawn; target.replaceChildren() }
|
||||
}
|
||||
}, { rootMargin: "200% 0px" })
|
||||
|
||||
for (let number = 1; number <= pdf.numPages; number++) {
|
||||
const page = document.createElement("div")
|
||||
page.className = "relative w-full bg-white shadow-sm ring-1 ring-slate-200"
|
||||
page.style.aspectRatio = `${first.width} / ${first.height}`
|
||||
page.dataset.page = number
|
||||
page.setAttribute("role", "img")
|
||||
page.setAttribute("aria-label", t("pdf.page", { page: number, pages: pdf.numPages }))
|
||||
this.pagesTarget.append(page)
|
||||
this.observer.observe(page)
|
||||
}
|
||||
this.statusTarget.hidden = true
|
||||
}
|
||||
|
||||
async drawPage(pdf, holder) {
|
||||
holder.dataset.drawn = "drawing"
|
||||
try {
|
||||
const page = await pdf.getPage(Number(holder.dataset.page))
|
||||
const natural = page.getViewport({ scale: 1 })
|
||||
holder.style.aspectRatio = `${natural.width} / ${natural.height}`
|
||||
// Sharp on the screen and when pinched in a little.
|
||||
const density = Math.min((window.devicePixelRatio || 1) * 1.25, 2.5)
|
||||
const viewport = page.getViewport({ scale: (holder.clientWidth * density) / natural.width })
|
||||
const canvas = document.createElement("canvas")
|
||||
canvas.width = Math.floor(viewport.width)
|
||||
canvas.height = Math.floor(viewport.height)
|
||||
canvas.className = "block h-auto w-full"
|
||||
await page.render({ canvas, canvasContext: canvas.getContext("2d"), viewport }).promise
|
||||
page.cleanup()
|
||||
if (holder.dataset.near !== "true") { canvas.width = canvas.height = 0; delete holder.dataset.drawn; return } // scrolled away meanwhile
|
||||
holder.dataset.drawn = "drawn"
|
||||
holder.replaceChildren(canvas)
|
||||
} catch (_) {
|
||||
holder.dataset.drawn = "failed"
|
||||
holder.replaceChildren(Object.assign(document.createElement("p"), { className: "p-6 text-center text-sm text-slate-500", textContent: t("pdf.page_failed") }))
|
||||
}
|
||||
}
|
||||
|
||||
// Can't draw it here (an old browser, or not a readable PDF): the browser's own viewer is one tap away.
|
||||
failed(error) {
|
||||
if (!this.element.isConnected) return
|
||||
console.warn("PDF viewer:", error)
|
||||
this.statusTarget.hidden = false
|
||||
this.statusTarget.replaceChildren(t("pdf.failed"), " ")
|
||||
this.statusTarget.append(Object.assign(document.createElement("a"), { href: this.urlValue, target: "_blank", rel: "noopener", className: "link", textContent: t("pdf.open") }))
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,17 @@
|
||||
# Daily: tells owners about items that have newly become overdue or limit
|
||||
# Daily: tells those who get its reminders (Role "gets reminders") about items that have newly become overdue or limit
|
||||
# the aircraft (grounded, VFR only…). Each is sent once; one that's fixed and
|
||||
# becomes overdue again is sent again.
|
||||
class OverdueNotificationJob < ApplicationJob
|
||||
queue_as :default
|
||||
|
||||
def perform
|
||||
Aircraft.includes(roles: :user).find_each do |aircraft|
|
||||
Aircraft.includes(roles: %i[user role]).find_each do |aircraft|
|
||||
issues = aircraft.airworthiness.issues.select { _1.severity.in?([ Airworthiness::RED, Airworthiness::LIMITED ]) }
|
||||
keys = issues.map { |i| "#{i.category}:#{i.item.class.name}:#{i.item.id}" }
|
||||
fresh = issues.reject.with_index { |_, n| aircraft.notified_issue_keys.include?(keys[n]) }
|
||||
owners = aircraft.roles.select { _1.role == "owner" }.map(&:user).reject(&:disabled?)
|
||||
recipients = aircraft.roles.select { _1.role.can?(:receive_reminders) }.map(&:user).reject(&:disabled?)
|
||||
if fresh.any?
|
||||
PushNotifier.notify(owners, :overdue, path: Rails.application.routes.url_helpers.aircraft_path(aircraft), tag: "overdue-#{aircraft.id}",
|
||||
PushNotifier.notify(recipients, :overdue, path: Rails.application.routes.url_helpers.aircraft_path(aircraft), tag: "overdue-#{aircraft.id}",
|
||||
tail: aircraft.tail_number, items: fresh.map(&:title).to_sentence, count: fresh.size)
|
||||
end
|
||||
aircraft.update_column(:notified_issue_keys, keys) if keys.sort != aircraft.notified_issue_keys.sort
|
||||
|
||||
@@ -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
|
||||
@@ -1,4 +1,4 @@
|
||||
# Weekly email to aircraft owners listing what's overdue or coming due
|
||||
# Weekly email to those who get an aircraft's reminders (Role "gets reminders") listing what's overdue or coming due
|
||||
# (inspections, ADs, components, expiring documents), deferred items, new
|
||||
# ADs, and the user's own certificates that are about to expire.
|
||||
# Nothing is sent when nothing needs attention, or when email isn't set up.
|
||||
|
||||
@@ -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
|
||||
@@ -1,8 +1,13 @@
|
||||
class ReminderMailer < ApplicationMailer
|
||||
# [[aircraft, issues, new AD alerts], …] for the aircraft the user owns
|
||||
# that need attention.
|
||||
# Aircraft where the user's role includes the permission.
|
||||
def self.aircraft_where(user, permission)
|
||||
Aircraft.where(id: AircraftRole.with_permission(permission).where(user_id: user.id).select(:aircraft_id)).ordered
|
||||
end
|
||||
|
||||
# [[aircraft, issues, new AD alerts], …] for the aircraft the user gets
|
||||
# reminders for (their role's "gets reminders") that need attention.
|
||||
def self.items_for(user)
|
||||
Aircraft.joins(:roles).where(aircraft_roles: { user_id: user.id, role: "owner" }).ordered
|
||||
aircraft_where(user, :receive_reminders)
|
||||
.map { [ _1, _1.airworthiness.issues, _1.ad_alerts.pending.to_a ] }.reject { _2.empty? && _3.empty? }
|
||||
end
|
||||
|
||||
@@ -10,10 +15,11 @@ class ReminderMailer < ApplicationMailer
|
||||
|
||||
def self.audit_due_for?(user) = user.admin? && AuditRun.due_soon?
|
||||
|
||||
# Owned aircraft whose AD baseline needs a (new) DRS import: none yet, a
|
||||
# year old, or a model never covered.
|
||||
# Aircraft they get reminders for and manage the ADs of, whose AD baseline
|
||||
# needs a (new) DRS import: none yet, a year old, or a model never covered.
|
||||
def self.drs_due_for(user)
|
||||
Aircraft.joins(:roles).where(aircraft_roles: { user_id: user.id, role: "owner" }).ordered
|
||||
aircraft_where(user, :receive_reminders)
|
||||
.where(id: AircraftRole.with_permission(:manage_ads).where(user_id: user.id).select(:aircraft_id))
|
||||
.select { DrsImport.renewal_due?(_1) || DrsImport.missing_models(_1).any? }
|
||||
end
|
||||
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
# 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.
|
||||
#
|
||||
# New accounts are only ever made by an administrator or from an
|
||||
# administrator's invitation: anyone can add an aircraft and so manage its
|
||||
# people, so other invitations are for people who already have an account.
|
||||
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
|
||||
|
||||
# "N12345: Mechanic. N54321: already Owner, unchanged" (from #redeem!).
|
||||
def self.describe(results)
|
||||
results.map { |aircraft, role, message| "#{aircraft.tail_number}: #{[ role&.name, message ].compact.join(', ')}" }.join(" ")
|
||||
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?
|
||||
# Whether someone without an account can make one with it (see above),
|
||||
# decided when it's used: its creator must still be an administrator.
|
||||
def creates_accounts? = created_by.present? && created_by.admin? && !created_by.disabled?
|
||||
def for_email?(email) = self.email.nil? || self.email == email.to_s.strip.downcase
|
||||
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) = for_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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -16,6 +17,7 @@ class Aircraft < ApplicationRecord
|
||||
has_many :components, dependent: :destroy
|
||||
has_many :squawks, dependent: :destroy
|
||||
has_many :logbook_entries, dependent: :destroy
|
||||
has_many :draft_batches, dependent: :destroy
|
||||
has_many :logbook_imports, dependent: :destroy
|
||||
has_many :document_collections, dependent: :destroy
|
||||
has_many :documents, dependent: :destroy
|
||||
|
||||
@@ -1,11 +1,21 @@
|
||||
# Someone's role on an aircraft (Role), which decides what they can do there.
|
||||
class AircraftRole < ApplicationRecord
|
||||
ROLES = LabelSet.new("aircraft_role.roles", %w[owner pilot])
|
||||
|
||||
belongs_to :aircraft
|
||||
belongs_to :user
|
||||
belongs_to :role
|
||||
|
||||
validates :role, inclusion: { in: ROLES.keys }
|
||||
validates :user_id, uniqueness: { scope: :aircraft_id, message: "already has a role on this aircraft" }
|
||||
|
||||
scope :owners, -> { where(role: "owner") }
|
||||
scope :owners, -> { joins(:role).where(roles: { key: "owner" }) }
|
||||
# Whose role includes a permission (Owner always does).
|
||||
scope :with_permission, ->(permission) {
|
||||
joins(:role).where("roles.key = 'owner' OR EXISTS (SELECT 1 FROM json_each(roles.permissions) WHERE json_each.value = ?)", permission.to_s)
|
||||
}
|
||||
|
||||
# A Role, or a built-in role's key ("owner", "pilot").
|
||||
def role=(value)
|
||||
super(value.is_a?(Role) || value.nil? ? value : Role.for_key(value))
|
||||
end
|
||||
|
||||
def owner? = role&.owner?
|
||||
end
|
||||
@@ -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
|
||||
@@ -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 drafts: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
|
||||
@@ -0,0 +1,57 @@
|
||||
# The release notes (CHANGELOG.md) split into releases, so the app can show
|
||||
# the running version's notes on their own and fold away older ones. The
|
||||
# file stays one plain Markdown document (it reads the same on GitHub):
|
||||
#
|
||||
# # What's new
|
||||
# intro...
|
||||
# ## 2026.11.5
|
||||
# ### Changes
|
||||
# - ...
|
||||
# ### Fixes
|
||||
# - ...
|
||||
class Changelog
|
||||
PATH = Rails.root.join("CHANGELOG.md")
|
||||
# The section headings counted in a release's one-line summary; items
|
||||
# under any other heading (the first release's highlights) count as notes.
|
||||
SECTIONS = { "Changes" => :changes, "Fixes" => :fixes, "For administrators" => :administrators }.freeze
|
||||
|
||||
Release = Data.define(:version, :markdown) do
|
||||
def year = version.split(".")[0].to_i
|
||||
def month = version.split(".")[1].to_i
|
||||
def month_start = Date.new(year, month, 1)
|
||||
def anchor = "v#{version.tr('.', '-')}"
|
||||
|
||||
# { changes: 4, fixes: 3 }: the top-level items under each heading.
|
||||
def counts
|
||||
counts = markdown.split(/^### /).drop(1).each_with_object(Hash.new(0)) do |section, tally|
|
||||
heading, body = section.split("\n", 2)
|
||||
tally[SECTIONS.fetch(heading.strip, :notes)] += body.to_s.scan(/^- /).size
|
||||
end
|
||||
(SECTIONS.values + [ :notes ]).filter_map { |key| [ key, counts[key] ] if counts[key].positive? }.to_h
|
||||
end
|
||||
end
|
||||
|
||||
def self.load = new(PATH.file? ? PATH.read : "")
|
||||
|
||||
attr_reader :title, :intro, :releases
|
||||
|
||||
def initialize(markdown)
|
||||
head, *parts = markdown.split(/^## /)
|
||||
@title = head[/\A# (.+)$/, 1] || "What's new"
|
||||
@intro = head.sub(/\A# .+\n+/, "").strip
|
||||
@releases = parts.filter_map do |part|
|
||||
version, body = part.split("\n", 2)
|
||||
version = version.strip
|
||||
Release.new(version: version, markdown: body.to_s.strip) if version.match?(/\A\d{4}\.\d{1,2}\.\d+\z/)
|
||||
end
|
||||
end
|
||||
|
||||
def release(version) = releases.find { _1.version == version }
|
||||
|
||||
# Shown open: the running version and any newer (or the newest, when the
|
||||
# running version has no notes, such as in development).
|
||||
def open?(release, running:)
|
||||
index = releases.index { _1.version == running } || 0
|
||||
releases.index(release) <= index
|
||||
end
|
||||
end
|
||||
@@ -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
|
||||
@@ -0,0 +1,63 @@
|
||||
# One visit's work sent through the API as draft logbook entries: an
|
||||
# unsigned entry for each logbook it touches, signed in the app like any
|
||||
# other entry (by an aircraft user, or a mechanic invited to sign).
|
||||
#
|
||||
# What the work resolves (squawks, inspections) is held until every entry in
|
||||
# the batch is signed: a draft never clears a squawk or completes an
|
||||
# inspection on its own.
|
||||
class DraftBatch < ApplicationRecord
|
||||
include Versioned
|
||||
|
||||
STATUSES = %w[awaiting_signature completed withdrawn].freeze
|
||||
|
||||
belongs_to :aircraft
|
||||
belongs_to :api_token, optional: true
|
||||
belongs_to :created_by, class_name: "User", optional: true
|
||||
has_many :entries, class_name: "LogbookEntry", dependent: :nullify
|
||||
|
||||
validates :status, inclusion: { in: STATUSES }
|
||||
|
||||
def awaiting? = status == "awaiting_signature"
|
||||
|
||||
def held_squawks = Array(held["squawks"])
|
||||
def held_inspections = Array(held["inspections"])
|
||||
|
||||
# What signing will do, for the signer to see before they sign.
|
||||
def held_effects_for(entry)
|
||||
squawks = aircraft.squawks.where(id: held_squawks.select { _1["log"] == entry.log_type }.map { _1["id"] })
|
||||
types = aircraft.applicable_inspection_types.where(id: held_inspections.select { _1["log"] == entry.log_type }.map { _1["id"] })
|
||||
{ squawks: squawks.to_a, inspections: types.to_a }
|
||||
end
|
||||
|
||||
# Called when one of its entries is signed: once they all are, the held
|
||||
# changes are made, attributed to the person who signed last.
|
||||
def entry_signed!
|
||||
return unless awaiting?
|
||||
with_lock do
|
||||
return unless awaiting? && entries.reload.all?(&:signed?)
|
||||
by_log = entries.index_by(&:log_type)
|
||||
aircraft.squawks.active.where(id: held_squawks.map { _1["id"] }).find_each do |squawk|
|
||||
entry = by_log[held_squawks.find { _1["id"] == squawk.id }["log"]]
|
||||
squawk.resolve!(logbook_entry: entry)
|
||||
aircraft.log_event!("squawk", I18n.t("flash.squawks.squawk_resolved_2"), notes: squawk.issue_reported.truncate(200))
|
||||
end
|
||||
aircraft.applicable_inspection_types.where(id: held_inspections.map { _1["id"] }).find_each do |type|
|
||||
entry = by_log[held_inspections.find { _1["id"] == type.id }["log"]]
|
||||
aircraft.inspection_records.create!(inspection_type: type, logbook_entry: entry, date: entry.date, aircraft_hours: entry.aircraft_hours_at_entry)
|
||||
aircraft.log_event!("inspection", I18n.t("flash.logbook_entries.inspection_completed_logbook_entry",
|
||||
name: type.name, date: I18n.l(entry.date, format: :app)))
|
||||
end
|
||||
update!(status: "completed", completed_at: Time.current)
|
||||
end
|
||||
Webhooks.publish("draft_batch.completed", aircraft: aircraft, data: ApiPresenter.draft_batch(self))
|
||||
end
|
||||
|
||||
# Withdraws an unsigned batch: its entries are removed (kept in the record history).
|
||||
def withdraw!
|
||||
transaction do
|
||||
raise ActiveRecord::RecordInvalid, self if entries.any?(&:signed?)
|
||||
entries.each(&:destroy!)
|
||||
update!(status: "withdrawn")
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -18,6 +18,13 @@ 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))
|
||||
entry.draft_batch&.entry_signed! # a draft from the API: its held changes once all its entries are signed
|
||||
end
|
||||
before_update { throw :abort } # signatures are permanent (2.1.2.7)
|
||||
before_destroy { throw :abort unless destroyed_by_association }
|
||||
|
||||
|
||||
@@ -26,6 +26,16 @@ class FlightLog < ApplicationRecord
|
||||
[ departure_location, destination_location ].compact_blank.join(" → ")
|
||||
end
|
||||
|
||||
# The meter readings that move the aircraft's and components' hours.
|
||||
METERS = %w[tach_out tach_in tach_time hobbs_out hobbs_in hobbs_time].freeze
|
||||
|
||||
# Its readings can be corrected only while it's the last flight logged and
|
||||
# nothing has changed the hours since (an hours update, an import): only
|
||||
# then is the aircraft's time just this flight's on top of the one before.
|
||||
def meters_editable?
|
||||
aircraft.flight_logs.maximum(:id) == id && (tach_in.nil? || tach_in == aircraft.tach_time)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Reject files the engine data parser can't read, before they're stored.
|
||||
|
||||
@@ -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 },
|
||||
@@ -27,7 +27,11 @@ class HelpGuide
|
||||
# Sanitized HTML. Links to other guide pages ("records.md#mistakes") go
|
||||
# through `link` (slug, anchor) -> URL, or become plain text when nil.
|
||||
def self.html(page, link:, title: true)
|
||||
source = title ? page.markdown : page.markdown.sub(/\A# .+\n+/, "")
|
||||
render(title ? page.markdown : page.markdown.sub(/\A# .+\n+/, ""), link: link)
|
||||
end
|
||||
|
||||
# Any Markdown from the guide (or a part of it, such as one release of the changelog).
|
||||
def self.render(source, link:)
|
||||
html = Commonmarker.to_html(source, options: OPTIONS, plugins: { syntax_highlighter: nil })
|
||||
html = Rails::HTML5::SafeListSanitizer.new.sanitize(html, tags: TAGS, attributes: ATTRIBUTES)
|
||||
html.gsub(%r{<a href="([a-z-]+|README)\.md(?:#([a-z0-9-]+))?">(.*?)</a>}m) do
|
||||
|
||||
@@ -14,6 +14,7 @@ class LogbookEntry < ApplicationRecord
|
||||
belongs_to :document, optional: true
|
||||
# For engine / propeller logs: which one, and its times at this entry.
|
||||
belongs_to :component, optional: true
|
||||
belongs_to :draft_batch, optional: true # made through the API, see DraftBatch
|
||||
# Sub-components it also covers (the oil filter on the engine…).
|
||||
has_many :parts, -> { includes(component: :component_type).order(:id) }, class_name: "LogbookEntryPart",
|
||||
dependent: :destroy, autosave: true
|
||||
@@ -33,6 +34,7 @@ class LogbookEntry < ApplicationRecord
|
||||
validates :signoff_certificate_type, inclusion: { in: CERTIFICATE_TYPES.keys }, allow_blank: true
|
||||
validates :inspection_result, inclusion: { in: INSPECTION_RESULTS.keys }, allow_blank: true
|
||||
validates :component_hours_at_entry, :component_since_overhaul_at_entry, numericality: { greater_than_or_equal_to: 0 }, allow_nil: true
|
||||
normalizes :external_ref, with: ->(r) { r.to_s.strip.first(200).presence }
|
||||
normalizes :signoff_certificate_type, :inspection_result, :signoff_certificate_number, with: ->(v) { v.strip.presence }
|
||||
|
||||
# Fields that may still change on a signed entry: its link to a scanned
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# What a role on an aircraft can do (Role#permissions). Grouped the way the
|
||||
# app is laid out; labels and descriptions are in config/locales
|
||||
# (permissions.<key>.label / .description). Seeing an aircraft's records
|
||||
# needs no permission: every role can view everything on its aircraft.
|
||||
module Permission
|
||||
GROUPS = {
|
||||
flying: %w[log_flights update_hours import_flights edit_own_flights edit_any_flight delete_flights],
|
||||
squawks_and_notes: %w[report_squawks defer_squawks manage_squawks write_notes manage_notes record_consumables manage_consumables],
|
||||
maintenance: %w[write_logbook sign_logbook manage_components manage_inspections manage_ads manage_major_records
|
||||
manage_weight_balance manage_documents record_oil_analyses manage_oil_analyses],
|
||||
data: %w[import_records export_data restore_history],
|
||||
aircraft: %w[edit_aircraft delete_aircraft manage_people manage_sharing],
|
||||
notifications: %w[receive_reminders]
|
||||
}.freeze
|
||||
|
||||
ALL = GROUPS.values.flatten.freeze
|
||||
|
||||
# The built-in roles' permissions when first created (admins can change all
|
||||
# but Owner's, which always has every permission). Pilot is what pilots
|
||||
# could do before roles were configurable.
|
||||
DEFAULTS = {
|
||||
"pilot" => %w[log_flights update_hours edit_own_flights report_squawks defer_squawks write_notes record_consumables
|
||||
record_oil_analyses sign_logbook],
|
||||
"mechanic" => %w[update_hours report_squawks defer_squawks manage_squawks write_notes manage_notes record_consumables
|
||||
manage_consumables write_logbook sign_logbook manage_components manage_inspections manage_ads
|
||||
manage_major_records manage_weight_balance manage_documents record_oil_analyses manage_oil_analyses
|
||||
receive_reminders],
|
||||
"viewer" => []
|
||||
}.freeze
|
||||
|
||||
def self.label(key) = I18n.t("permissions.#{key}.label")
|
||||
def self.description(key) = I18n.t("permissions.#{key}.description")
|
||||
def self.group_label(group) = I18n.t("permissions.groups.#{group}")
|
||||
end
|
||||
@@ -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"]
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
# A role someone can have on an aircraft: a name and a set of permissions
|
||||
# (Permission). Installation-wide; administrators manage them (Admin → Roles).
|
||||
# Four are built in (key set): Owner, which always has every permission so an
|
||||
# aircraft can always be managed, and Mechanic, Pilot and Viewer, whose
|
||||
# permissions can be changed. Administrators can add their own.
|
||||
class Role < ApplicationRecord
|
||||
BUILT_IN = %w[owner mechanic pilot viewer].freeze
|
||||
|
||||
has_many :aircraft_roles, dependent: :restrict_with_error
|
||||
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 }
|
||||
validates :description, length: { maximum: 200 }
|
||||
validates :key, inclusion: { in: BUILT_IN }, uniqueness: true, allow_nil: true
|
||||
before_validation { self.permissions = Array(permissions).map(&:to_s) & Permission::ALL }
|
||||
before_destroy { throw :abort if built_in? }
|
||||
|
||||
scope :ordered, -> { order(Arel.sql("CASE WHEN key IS NULL THEN 1 ELSE 0 END"), :position, :name) }
|
||||
|
||||
# The built-in roles, created when first needed (a new installation, tests).
|
||||
def self.ensure_built_in!
|
||||
BUILT_IN.each_with_index do |key, i|
|
||||
find_or_create_by!(key: key) do |role|
|
||||
role.name = I18n.t("roles.#{key}.name")
|
||||
role.description = I18n.t("roles.#{key}.description")
|
||||
role.permissions = Permission::DEFAULTS.fetch(key, [])
|
||||
role.position = i
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def self.for_key(key) = find_by(key: key.to_s) || (ensure_built_in! && find_by!(key: key.to_s))
|
||||
def self.owner = for_key("owner")
|
||||
|
||||
def built_in? = key.present?
|
||||
def owner? = key == "owner"
|
||||
|
||||
def permissions = owner? ? Permission::ALL : super
|
||||
def can?(permission) = permissions.include?(permission.to_s)
|
||||
end
|
||||
@@ -10,6 +10,9 @@ class Setting < ApplicationRecord
|
||||
"backups_kept" => { default: 14, in: 1..365 },
|
||||
"offsite_backups_kept" => { default: 30, in: 1..365 },
|
||||
"documents_claude_text" => { default: 0, in: 0..1 },
|
||||
# Who can add aircraft (and so become an Owner, who invites people): 0
|
||||
# administrators only, 1 everyone.
|
||||
"anyone_adds_aircraft" => { default: 0, in: 0..1 },
|
||||
"logbook_templates_seeded" => { default: 0, in: 0..1 } # internal flag
|
||||
}.freeze
|
||||
LABELS = LabelSet.new("setting.keys", INTEGERS.keys)
|
||||
@@ -20,6 +23,7 @@ class Setting < ApplicationRecord
|
||||
class << self
|
||||
def max_upload_mb = integer("max_upload_mb")
|
||||
def max_upload_bytes = max_upload_mb.megabytes
|
||||
def anyone_adds_aircraft? = integer("anyone_adds_aircraft") == 1
|
||||
|
||||
def integer(key)
|
||||
definition = INTEGERS.fetch(key)
|
||||
|
||||
@@ -22,4 +22,12 @@ class SigningInvitation < ApplicationRecord
|
||||
def self.find_usable(token) = where(token_digest: digest(token), used_at: nil).where("expires_at > ?", Time.current).first
|
||||
|
||||
def aircraft = logbook_entry.aircraft
|
||||
|
||||
# Whether the mechanic can make an account for the invited address with it:
|
||||
# when it's from an Owner of the aircraft or an administrator (still, when
|
||||
# it's used). Who can become an Owner is up to the administrator (Admin →
|
||||
# Settings, who can add aircraft); others' invitations need an account.
|
||||
def creates_account?
|
||||
invited_by.present? && !invited_by.disabled? && (invited_by.admin? || invited_by.role_for(aircraft)&.owner?) || false
|
||||
end
|
||||
end
|
||||
@@ -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
|
||||
|
||||
+15
-3
@@ -2,7 +2,10 @@ 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
|
||||
|
||||
normalizes :time_zone, with: ->(z) { z.strip.presence }
|
||||
validates :time_zone, inclusion: { in: ->(_) { ActiveSupport::TimeZone.all.map(&:name) } }, allow_nil: true
|
||||
@@ -113,10 +116,19 @@ class User < ApplicationRecord
|
||||
admin? ? Aircraft.all : aircraft
|
||||
end
|
||||
|
||||
# 'admin' | 'owner' | 'pilot' | nil
|
||||
# Their Role on the aircraft (nil for none; administrators may have none).
|
||||
def role_for(aircraft)
|
||||
return "admin" if admin?
|
||||
aircraft_roles.find_by(aircraft: aircraft)&.role
|
||||
aircraft_roles.includes(:role).find_by(aircraft: aircraft)&.role
|
||||
end
|
||||
|
||||
# Adding an aircraft (or importing one) makes you its Owner: administrators,
|
||||
# or everyone when Admin → Settings allows it.
|
||||
def can_add_aircraft? = !Viewer.enabled? && (admin? || Setting.anyone_adds_aircraft?)
|
||||
|
||||
# Administrators can do everything on every aircraft.
|
||||
def can?(permission, aircraft)
|
||||
return false if Viewer.enabled?
|
||||
admin? || role_for(aircraft)&.can?(permission) || false
|
||||
end
|
||||
|
||||
def display_name
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
# Viewer mode (SAM_VIEWER=true): a read-only copy of an aircraft archive for
|
||||
# whoever receives a records package (the FAA, a buyer), with no sign-in. It's
|
||||
# what the package's viewer/docker-compose.yml runs, on that person's own
|
||||
# computer.
|
||||
#
|
||||
# - At start (bin/rails sam:viewer:prepare, from bin/docker-entrypoint), the
|
||||
# archive at SAM_VIEWER_ARCHIVE is imported, owned by a built-in account.
|
||||
# - Everyone is that account (Authentication): no sign-in.
|
||||
# - Nothing can be changed: requests other than GET/HEAD are refused
|
||||
# (ApplicationController), and no role permission applies (AircraftScoped).
|
||||
#
|
||||
# So that it can never open a real installation, it refuses to run when the
|
||||
# database has any account other than the built-in one: setting SAM_VIEWER on
|
||||
# a real server stops it rather than exposing its records.
|
||||
module Viewer
|
||||
EMAIL = "viewer@sam-viewer.invalid".freeze
|
||||
|
||||
class RealAccounts < StandardError
|
||||
def message = "SAM_VIEWER is on, but this database has user accounts: viewer mode is only for an empty " \
|
||||
"copy made to look at an archive. Turn SAM_VIEWER off for a real installation."
|
||||
end
|
||||
|
||||
def self.enabled? = ENV["SAM_VIEWER"] == "true"
|
||||
def self.archive = ENV["SAM_VIEWER_ARCHIVE"].presence
|
||||
# What was imported, for the banner (kept with the data).
|
||||
def self.info_path = Pathname(ENV["SAM_VIEWER_INFO"].presence || Rails.root.join("storage/viewer.json"))
|
||||
def self.real_accounts? = User.where.not(email_address: EMAIL).exists?
|
||||
|
||||
# The built-in account everyone browses as (made when first needed). It
|
||||
# can't sign in by password: nobody knows it.
|
||||
def self.user
|
||||
User.find_or_create_by!(email_address: EMAIL) do |u|
|
||||
u.name = I18n.t("viewer.account_name")
|
||||
u.password = SecureRandom.base58(40)
|
||||
end
|
||||
end
|
||||
|
||||
# Checks the database, then imports the archive the first time.
|
||||
def self.prepare!(output: $stdout)
|
||||
raise RealAccounts if real_accounts?
|
||||
owner = user
|
||||
if Aircraft.exists?
|
||||
output.puts "Viewer: already imported (#{Aircraft.ordered.pluck(:tail_number).join(', ')})."
|
||||
elsif archive.nil? || !File.file?(archive)
|
||||
output.puts "Viewer: no archive at SAM_VIEWER_ARCHIVE (#{archive.inspect}); nothing to show."
|
||||
else
|
||||
output.puts "Viewer: importing #{File.basename(archive)}…"
|
||||
preview = AircraftArchive::Importer.check(archive)
|
||||
result = AircraftArchive::Importer.new(archive, owner: owner).run
|
||||
File.write(info_path, { file: File.basename(archive), tail_number: result[:aircraft].tail_number,
|
||||
exported_at: preview.exported_at&.iso8601 }.to_json)
|
||||
output.puts "Viewer: imported #{result[:aircraft].tail_number}: #{result[:counts].map { |k, n| "#{n} #{k.tr('_', ' ')}" }.join(', ')}"
|
||||
end
|
||||
output.puts "Viewer ready: open http://localhost:3000"
|
||||
end
|
||||
|
||||
# What the banner says: the archive's file and when it was exported.
|
||||
def self.info
|
||||
JSON.parse(info_path.read) if info_path.file?
|
||||
rescue JSON::ParserError
|
||||
nil
|
||||
end
|
||||
end
|
||||
@@ -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
|
||||
@@ -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 draft_batch.completed])
|
||||
|
||||
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
|
||||
@@ -0,0 +1,80 @@
|
||||
# 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), draft_batch_id: e.draft_batch_id, external_ref: e.external_ref,
|
||||
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 draft_batch(b, invitations: {})
|
||||
urls = Rails.application.routes.url_helpers
|
||||
{ id: b.id, aircraft_id: b.aircraft_id, status: b.status, external_ref: b.external_ref, signer_email: b.signer_email,
|
||||
held: { resolves_squawks: b.held_squawks.map { _1["id"] }, completes_inspections: b.held_inspections.map { _1["id"] } },
|
||||
entries: b.entries.sort_by(&:log_type).map do |e|
|
||||
logbook_entry(e).merge(sign_url: "#{Sso.app_url}#{urls.new_aircraft_logbook_entry_signature_path(b.aircraft_id, e)}",
|
||||
invitation_url: invitations[e.id] && "#{Sso.app_url}#{urls.invited_signing_path(invitations[e.id])}")
|
||||
end,
|
||||
completed_at: time(b.completed_at), created_at: time(b.created_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
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
# Giving, changing and taking away people's roles on an aircraft, by someone
|
||||
# allowed to (the aircraft's "manage people", or an administrator). The rules,
|
||||
# the same from the aircraft's Access page and Admin → Users:
|
||||
# - only an Owner or an administrator can give or take away the Owner role
|
||||
# (otherwise anyone who manages people could make themselves Owner);
|
||||
# - only an administrator can change or remove their own role;
|
||||
# - an aircraft always keeps at least one Owner.
|
||||
# Each method returns nil when done, or a message saying why not.
|
||||
class AircraftAccess
|
||||
def initialize(aircraft, actor:)
|
||||
@aircraft = aircraft
|
||||
@actor = actor
|
||||
end
|
||||
|
||||
def add(user, role)
|
||||
return t("not_found") unless user && role
|
||||
return t("owner_only") if role.owner? && !actor_owner?
|
||||
membership = @aircraft.roles.new(user: user, role: role)
|
||||
return membership.errors.full_messages.to_sentence unless membership.save
|
||||
@aircraft.log_event!("role", I18n.t("flash.aircraft_roles.added_as", display_name: user.display_name, role: role.name), user: @actor)
|
||||
nil
|
||||
end
|
||||
|
||||
def change(membership, role)
|
||||
return t("not_found") unless role
|
||||
return if membership.role == role
|
||||
return t("own_role") if membership.user == @actor && !@actor.admin?
|
||||
return t("owner_only") if (role.owner? || membership.owner?) && !actor_owner?
|
||||
return t("last_owner") if membership.owner? && !role.owner? && last_owner?
|
||||
membership.update!(role: role)
|
||||
@aircraft.log_event!("role", I18n.t("flash.aircraft_roles.changed_to", display_name: membership.user.display_name, role: role.name), user: @actor)
|
||||
nil
|
||||
end
|
||||
|
||||
def remove(membership)
|
||||
return t("own_role") if membership.user == @actor && !@actor.admin?
|
||||
return t("owner_only") if membership.owner? && !actor_owner?
|
||||
return t("last_owner") if membership.owner? && last_owner?
|
||||
membership.destroy!
|
||||
@aircraft.log_event!("role", I18n.t("flash.aircraft_roles.removed", display_name: membership.user.display_name), user: @actor)
|
||||
nil
|
||||
end
|
||||
|
||||
# The roles this person can hand out here (Owner only by an Owner).
|
||||
def assignable_roles = Role.ordered.select { |role| !role.owner? || actor_owner? }
|
||||
|
||||
private
|
||||
|
||||
def actor_owner? = @actor.admin? || @actor.role_for(@aircraft)&.owner?
|
||||
def last_owner? = @aircraft.roles.owners.count <= 1
|
||||
def t(key) = I18n.t("services.aircraft_access.#{key}")
|
||||
end
|
||||
@@ -149,7 +149,7 @@ module AircraftArchive
|
||||
import_notes
|
||||
import_oil_analyses
|
||||
import_flight_logs
|
||||
@aircraft.roles.find_or_create_by!(user: @owner, role: "owner") if @owner
|
||||
@aircraft.roles.find_or_create_by!(user: @owner) { _1.role = Role.owner } if @owner
|
||||
@aircraft.log_event!("aircraft", "Aircraft imported from a .sam.zip archive",
|
||||
notes: [ @manifest["source_instance"].presence && "Source: #{@manifest['source_instance']}", summary ].compact.join(". "),
|
||||
user: @owner)
|
||||
|
||||
@@ -67,8 +67,53 @@ class HoursService
|
||||
flight
|
||||
end
|
||||
|
||||
# Correct a saved flight. Its readings change only when it's the latest
|
||||
# (FlightLog#meters_editable?); the aircraft and its components then move by
|
||||
# the difference. Its oil and fuel records follow. With both readings given,
|
||||
# the duration is worked out from them.
|
||||
def update_flight!(flight, attributes)
|
||||
Aircraft.transaction do
|
||||
before = flight.attributes.slice(*FlightLog::METERS, "date", "departure_location", "destination_location",
|
||||
"oil_added", "fuel_added", "route", "notes")
|
||||
flight.assign_attributes(attributes)
|
||||
flight.tach_time = flight.tach_in - flight.tach_out if flight.tach_in && flight.tach_out
|
||||
flight.hobbs_time = flight.hobbs_in - flight.hobbs_out if flight.hobbs_in && flight.hobbs_out
|
||||
flight.save!
|
||||
|
||||
tach_delta = flight.tach_time - before["tach_time"].to_d
|
||||
hobbs_delta = flight.hobbs_time.to_d - before["hobbs_time"].to_d
|
||||
if tach_delta.nonzero? || hobbs_delta.nonzero?
|
||||
@aircraft.tach_time += tach_delta
|
||||
@aircraft.hobbs_time += hobbs_delta if @aircraft.hobbs_time
|
||||
@aircraft.save!
|
||||
cascade_to_components(@aircraft.hobbs? && flight.hobbs_time ? hobbs_delta : tach_delta, clamp: true)
|
||||
end
|
||||
sync_consumables(flight)
|
||||
|
||||
changed = before.keys.reject { |key| before[key] == flight[key] }
|
||||
@aircraft.log_event!("flight", I18n.t("#{H}.flight_corrected", date: I18n.l(flight.date, format: :app)), user: @user,
|
||||
notes: changed.map { |key| FlightLog.human_attribute_name(key) }.join(", ").presence)
|
||||
end
|
||||
flight
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# The flight's oil and fuel records match what it says was added.
|
||||
def sync_consumables(flight)
|
||||
{ "oil" => [ flight.oil_added, flight.oil_level_after, flight.oil_added_type ],
|
||||
"fuel" => [ flight.fuel_added, flight.fuel_level_after, flight.fuel_added_type ] }.each do |type, (qty, level, kind)|
|
||||
record = flight.consumable_records.find_by(record_type: type)
|
||||
if qty.to_f.positive?
|
||||
record ||= @aircraft.consumable_records.new(record_type: type, flight_log: flight, flight_hours: @aircraft.tach_time,
|
||||
notes: I18n.t("#{H}.auto_created_from_flight_log"))
|
||||
record.update!(date: flight.date, quantity_added: qty, level_after: level, consumable_type: kind)
|
||||
else
|
||||
record&.destroy!
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def cascade_to_components(delta, clamp: false)
|
||||
@aircraft.components.in_use.find_each do |c|
|
||||
his = c.hours_in_service + delta
|
||||
|
||||
@@ -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
|
||||
@@ -12,9 +12,10 @@ module ProceduresTemplates
|
||||
t(:sign_in, sentence: sign_in_sentence, min: User::PASSWORD_MIN, minutes: User::LOCK_FOR.in_minutes.to_i,
|
||||
tries: User::LOCK_AFTER, days: Authentication::SESSION_IDLE_TIMEOUT.in_days.to_i),
|
||||
t(Sso.enabled? ? :signing_sso : :signing),
|
||||
api_sentence,
|
||||
t(:updates),
|
||||
t(:secret_key)
|
||||
].join("\n\n")
|
||||
].compact.join("\n\n")
|
||||
end
|
||||
|
||||
def additional
|
||||
@@ -37,6 +38,13 @@ module ProceduresTemplates
|
||||
end
|
||||
end
|
||||
|
||||
# Only when the API is in use: who can reach the records through it, and that signing stays in the app.
|
||||
def api_sentence
|
||||
integrations = ApiToken.integration.active.order(:name).pluck(:name)
|
||||
return if integrations.empty? && !ApiToken.personal.active.exists?
|
||||
t(:api, integrations: integrations.any? ? t(:api_integrations, names: integrations.to_sentence) : t(:api_no_integrations))
|
||||
end
|
||||
|
||||
def docker? = File.exist?("/.dockerenv")
|
||||
|
||||
def t(key, **opts) = I18n.t(key, scope: "services.procedures_templates", **opts)
|
||||
|
||||
Loaded 100 of 269 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user