Compare commits

...

76 Commits

Author SHA1 Message Date
Constantin Graf
a958f95b44 Load existing time entries per member and compare the type when deduplicating imports
Existing time entries are now loaded per member and month (backed by the
member_id/start index) and streamed with a cursor, so only the members an
import touches are loaded. The type is part of the fingerprint, so a break is
no longer matched against a work entry.
2026-12-04 15:48:45 +01:00
Constantin Graf
384853745e Skip time entries that already exist when importing
Re-importing the same data duplicated all time entries, because only
clients, projects, tasks, tags and users were matched with existing
records. Time entries are now matched by member, start, end, project,
task and description. Matches are counted, so identical time entries
within one import are still kept.

Fixes #894
2026-12-04 15:48:45 +01:00
Gregor Vostrak
7fd9f36d69 Request uncompressed imports response in running import e2e test 2026-12-04 15:48:42 +01:00
Gregor Vostrak
e2dc40a305 keep black solidtime logo in guided import 2026-12-04 15:48:42 +01:00
Gregor Vostrak
c448955838 fix hover colors in light mode for ghost and outline buttons 2026-12-04 15:48:42 +01:00
Gregor Vostrak
51f594d0a5 add importer wizard with guided steps for each type 2026-12-04 15:48:42 +01:00
Constantin Graf
bd851e4edf Run the project's pint version in the linting workflow
The laravel-pint-action builds on composer:latest, whose current image lacks
mbstring and crashes pint. Run vendor/bin/pint after setting up PHP instead,
which also uses the pint version from composer.lock. Remove an unused import
that the newer pint version reports.
2026-12-04 15:48:42 +01:00
Constantin Graf
1b6ca3e00f Reject import files that are not UTF-8 encoded
Invalid UTF-8 (for example CSV files saved as Windows-1252 by Excel) was only
rejected by the database on insert, which failed the import with a generic
unexpected error. The CSV importers and the CSV files in solidtime exports are
now checked up front and fail with a clear message.
2026-12-04 15:48:42 +01:00
Constantin Graf
463182666b Wait for background import in e2e helper and fix coverage metadata of import and export tests 2026-12-04 15:48:42 +01:00
Constantin Graf
cbc7261a12 Only report unexpected errors of imports 2026-12-04 15:48:42 +01:00
Constantin Graf
eb1e89a91d Mark stale imports and exports as failed before creating new ones and fix review findings
- Mark stale imports/exports of the organization as failed when a new one is created, so they do not block until the prune command runs
- Move the stale check into a stale() scope on the Import and Export models
- Remove orderBy(created_at) from chunkById queries in the prune commands, it skipped rows with random UUIDs
- Delete the export file if the export was deleted while it was running
- Extract the error details formatting into ErrorDetailsFormatter
- Add the exports() relation to Organization
2026-12-04 15:48:42 +01:00
Constantin Graf
b5aa2f7e1a Rename import controller methods to match the export controller 2026-12-04 15:48:42 +01:00
Constantin Graf
89d004f88c Detect project members of another organization in the database consistency check 2026-12-04 15:48:42 +01:00
Constantin Graf
50c028ee23 Reject solidtime imports with project members that reference missing records 2026-12-04 15:48:42 +01:00
Constantin Graf
e44a3733e1 Store error details of failed imports and show them in the admin panel
The importers keep the original exception as the previous exception, so the
exception chain and stack trace can be stored in the new error_details column.
The details are only visible in the admin panel, which now also links the
organization and user of an import.
2026-12-04 15:48:42 +01:00
Constantin Graf
4c8215a889 Store exports in the database and process them in a queued job 2026-12-04 15:48:42 +01:00
Constantin Graf
a440687a41 Mark timed out and stale imports as failed in the prune command
The job's failed() handler can not mark a timed out import as failed, since
the timeout handler runs while the import transaction is still open and the
change is rolled back when the worker is killed. It also must not mark the
import as failed when the queue hands out the job a second time after
retry_after, while the first attempt is still running.

Running imports are now considered stale shortly after the job timeout and
the prune command runs every five minutes.
2026-12-04 15:48:42 +01:00
Constantin Graf
cecaa429c9 Limit the number of records a single import can create 2026-12-04 15:48:42 +01:00
Constantin Graf
a83eeb0222 Store imports in the database and process them in a queued job 2026-12-04 15:48:42 +01:00
Constantin Graf
1a589a9552 Wait for minio before creating the bucket and update the playwright image 2026-12-04 15:48:42 +01:00
Gregor Vostrak
61865f699d Publish npm packages through trusted publishing only (#1433)
* publish packages through trusted publishing only

* drop verbose npm logging
2026-12-02 14:21:43 +01:00
Gregor Vostrak
fcc7e0fed1 Publish npm packages automatically on version bumps (#1431)
* publish npm packages automatically when their version changes

* run the publish job in a main-only npm environment

* drop release tags so the publish job only needs read access

* split the package check and publish into separate workflows
2026-12-02 13:19:58 +01:00
Gregor Vostrak
df71051feb Add @solidtime/composables package for logic shared with desktop and the extension (#1430)
* add @solidtime/composables package shared by web, desktop and extension

* bump api to 0.0.8 and require it in composables

* drop the manual composables publish workflow
2026-12-01 17:22:44 +01:00
Connor Cleveland
ec74a1d841 fix: update Supercronic to v0.2.51 (#1416) 2026-11-26 19:18:40 +01:00
Gregor Vostrak
d0f5e7452f Require PHP 8.3.37 for security fix 2026-11-19 18:14:40 +01:00
Constantin Graf
abb07fdfc8 Look up the member once in time_entries.destroyMultiple 2026-11-19 16:18:11 +01:00
Constantin Graf
01a5961961 Add postgres 18 support 2026-11-19 14:21:02 +01:00
Constantin Graf
34ab2aed32 Normalize email case in admin commands, Filament user form, imports and placeholder merging (#1398)
* Normalize email case in admin commands, Filament user form, imports and placeholder merging

* Add tests for email case normalization

* Lowercase existing invitation emails and match duplicates case-insensitively

Adds a migration that lowercases organization_invitations.email. Invitations of the
same organization whose emails only differ in case are deduplicated first (accepted
invitation preferred, otherwise the newest), so the unique index is not violated.
The duplicate check when inviting a user now ignores case.

* Lowercase placeholder emails in migration and use Str::lower for emails
2026-11-19 14:16:03 +01:00
Constantin Graf
065967ad02 Update services extension to v0.0.10 2026-11-19 13:08:56 +01:00
Constantin Graf
3605a971b4 Fix stale heartbeat lock, skip queue heartbeat on sync driver and enforce a heartbeat timeout 2026-11-19 13:07:06 +01:00
Constantin Graf
9b742372f0 Add heartbeat monitoring for the scheduler and the queue 2026-11-19 13:07:06 +01:00
Constantin Graf
84af013881 Add invoice logo and invoice settings support
Adds the invoice logo fields to the API client and a permission helper for
the invoice settings page. Points the Invoicing extension at the
feature/invoice-logo branch, which must be pinned to a release tag before
merging.
2026-11-19 12:13:18 +01:00
Constantin Graf
56973656d0 Update billing extension to v0.0.16 2026-11-19 12:13:02 +01:00
Constantin Graf
e3b031b426 Require view all permissions for creating and updating reports 2026-11-19 11:47:21 +01:00
Gregor Vostrak
aa464e5bfe Pin SSO extension to v0.0.1 2026-11-18 16:31:48 +01:00
Gregor Vostrak
ddcf15bc8f clarify email change locked text 2026-11-18 16:31:48 +01:00
Constantin Graf
321a50cd81 Add SSO extension to the extension manifest and build workflows 2026-11-18 16:31:48 +01:00
Constantin Graf
7912b0a237 Add exit impersonation to the user menu 2026-11-18 16:31:48 +01:00
Constantin Graf
cc23cdc76b Fix bcrypt cost at 12 so the absent-user hash matches login timing 2026-11-18 16:31:48 +01:00
Gregor Vostrak
f845c9001b Add core support for extendable authentication and passwordless user
creation
2026-11-18 16:31:48 +01:00
Constantin Graf
9c4e9f373a Updated billing extension to v0.0.15 2026-11-11 19:47:31 +01:00
Constantin Graf
eb8c0b0091 Remove unimplemented users/me/time-entries route 2026-11-11 19:42:39 +01:00
Gregor Vostrak
0ca240ac22 Fix calendar drag moving events by the start hour offset
Fixes #1361
2026-11-11 18:43:14 +01:00
Constantin Graf
7a570dc567 Recalculate project and task spent time after admin time entry changes
Creating, editing, deleting and bulk deleting time entries in the Filament
admin panel did not dispatch the spent time recalculation jobs, leaving
stale spent_time values on projects and tasks.

Fixes #1319
2026-11-11 18:26:57 +01:00
Constantin Graf
525ee8d426 Fail prod image build if PHP is below configurable minimum version 2026-11-09 14:25:42 +01:00
Gregor Vostrak
6e1e947dcf Unpin PHP patch version in prod Dockerfile 2026-11-09 14:25:42 +01:00
Constantin Graf
e4d337f42e Look up the e2e test member from the user's own memberships and order memberships by age 2026-11-09 14:17:12 +01:00
Constantin Graf
1743c281ac Sign Docker images built for same-repo pull requests 2026-11-09 14:17:03 +01:00
Constantin Graf
82db637963 Use Docker Hub image in SECURITY.md verification examples 2026-11-09 14:17:03 +01:00
Constantin Graf
bd1b04f34e Pin cosign-installer to v4.1.3 commit SHA 2026-11-09 14:17:03 +01:00
Constantin Graf
6e095a31ad Sign private cloud Docker image with cosign 2026-11-09 14:17:03 +01:00
Constantin Graf
c2ba36d94d Sign on-premise Docker images with cosign and attach SBOM and provenance 2026-11-09 14:17:03 +01:00
Constantin Graf
f68d98f9c0 Sign public Docker images with cosign and attach SBOM and provenance 2026-11-09 14:17:03 +01:00
Constantin Graf
1092fc76e3 Update billing extension to v0.0.14 and invoicing extension to v0.0.13 2026-11-09 12:41:22 +01:00
Constantin Graf
97bd942b9a Check organization membership in middleware and cache permission lookups 2026-11-09 12:41:22 +01:00
Constantin Graf
369b012cc0 Validate import emails with the app's RFC rule
Use email:rfc,strict instead of FILTER_VALIDATE_EMAIL so every address the
app accepts (including Unicode ones) can be re-imported, and add the rule to
the user import helper so generated Harvest emails are validated too. Stop
trimming emails so they match existing users exactly as stored, and fix the
misplaced docblocks.
2026-11-09 12:07:09 +01:00
Constantin Graf
063ce93fb7 Validate user emails in imports 2026-11-09 12:07:09 +01:00
Constantin Graf
15af6125b2 Dispatch Verified event after the transaction commits in UserService::createUser 2026-11-09 11:45:24 +01:00
Constantin Graf
4e6fe53b86 Test verified event dispatch in UserService::createUser 2026-11-09 11:45:24 +01:00
Constantin Graf
ff8d8a4c94 Update billing extension to v0.0.13 2026-11-09 11:45:24 +01:00
Constantin Graf
9996f7bc2b Fire verified event for users created with a verified email 2026-11-09 11:45:24 +01:00
Constantin Graf
9bc26bf181 Skip task-belongs-to-project rule when no organization is bound 2026-11-09 11:44:40 +01:00
Constantin Graf
48ca588b7d Keep task-belongs-to-project check for missing project_id and share it via helper
- Fix required_with key for changes.project_id in bulk time entry update
- Run task check when project_id is null, skip only for non-UUID values
- Move the duplicated task rule into BaseFormRequest::taskBelongsToProjectRule
2026-11-09 11:44:40 +01:00
Constantin Graf
60f91b8ea0 Skip project-dependent task rules when project_id is not a valid UUID 2026-11-09 11:44:40 +01:00
dependabot[bot]
57fd653df0 Bump docker/login-action from 4.7.0 to 4.8.0
Bumps [docker/login-action](https://github.com/docker/login-action) from 4.7.0 to 4.8.0.
- [Release notes](https://github.com/docker/login-action/releases)
- [Commits](https://github.com/docker/login-action/compare/v4.7.0...v4.8.0)

---
updated-dependencies:
- dependency-name: docker/login-action
  dependency-version: 4.8.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-09 11:38:16 +01:00
Constantin Graf
6debd4cb1e Add foreign key from oauth refresh tokens to access tokens and delete orphaned refresh tokens 2026-11-07 21:54:02 +01:00
Constantin Graf
dc1199962a Respect daylight saving time when grouping time entries by date
The date grouping in the time entry aggregation and the dashboard shifted
all entries by the current UTC offset of the user's timezone. Entries
tracked in the other DST period were assigned to the wrong day, week,
month or year, and with fill_gaps_in_time_groups entries at the edge of
the range were dropped ("Problem with filling gaps in time groups").

The conversion to local time is now done per row by PostgreSQL
(AT TIME ZONE) with the timezone passed as a binding.
2026-11-05 13:32:51 +01:00
Constantin Graf
2b371c4aed Disable unused Passport device grant 2026-11-05 13:11:48 +01:00
Constantin Graf
14bb884091 Update dependencies 2026-11-03 23:09:49 +01:00
Constantin Graf
27361b6233 Update services extension to v0.0.8 2026-11-03 23:09:10 +01:00
Constantin Graf
ea07027008 Update laravel/passport to v13.10.0 2026-11-03 17:42:53 +01:00
Constantin Graf
0e1ed2e114 Keep the client of time entries in sync with their project 2026-11-03 17:29:40 +01:00
Constantin Graf
eab05eb92e Return 404 for unused Filament import/export download routes 2026-11-03 17:09:41 +01:00
Constantin Graf
cc9d04ab5a Keep registration working when an accepted invitation can not be turned into a membership 2026-11-03 17:09:24 +01:00
Constantin Graf
b07235a63a Limit Composer and npm Dependabot PRs 2026-11-03 16:59:22 +01:00
AKolenda
b561179ba5 Redirect logged-out users to login from the OAuth authorization page
Passport's /oauth/authorize prompts guests to log in by throwing an
AuthenticationException without a redirect target. Laravel 13 renders
such an exception as an empty 401 instead of falling back to the login
route, so OAuth clients opened in a browser without a solidtime session
showed a blank "HTTP ERROR 401" page.

Register the login route as the fallback redirect for authentication
exceptions, which restores the redirect to /login and the return to the
authorization prompt after logging in.
2026-11-03 16:21:35 +01:00
272 changed files with 13944 additions and 1168 deletions

View File

@@ -38,6 +38,12 @@ CACHE_DRIVER=file
# Queue
QUEUE_CONNECTION=sync
# Heartbeat (optional push/heartbeat monitor URLs to check that the scheduler and queue are running)
# The queue URL may contain the placeholder {latency_ms}, which is replaced with the queue latency.
# The queue heartbeat is skipped if the queue connection uses the sync driver.
# HEARTBEAT_SCHEDULER_URL=
# HEARTBEAT_QUEUE_URL=
# Session
SESSION_DRIVER=database
SESSION_LIFETIME=120

View File

@@ -15,34 +15,10 @@ updates:
schedule:
interval: "weekly"
target-branch: "main"
groups:
major-updates:
update-types:
- "major"
minor-updates:
update-types:
- "minor"
- "patch"
security-updates:
applies-to: version-updates
update-types:
- "minor"
- "patch"
open-pull-requests-limit: 0
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
target-branch: "main"
groups:
major-updates:
update-types:
- "major"
minor-updates:
update-types:
- "minor"
- "patch"
security-updates:
applies-to: version-updates
update-types:
- "minor"
- "patch"
open-pull-requests-limit: 0

View File

@@ -105,6 +105,8 @@ jobs:
echo "invoicing_ref=$(jq -r '.Invoicing.ref' extensions/manifest.json)"
echo "auditing_repository=$(jq -r '.Auditing.repository' extensions/manifest.json)"
echo "auditing_ref=$(jq -r '.Auditing.ref' extensions/manifest.json)"
echo "sso_repository=$(jq -r '.SSO.repository' extensions/manifest.json)"
echo "sso_ref=$(jq -r '.SSO.ref' extensions/manifest.json)"
} >> "$GITHUB_OUTPUT"
- name: "Checkout invoicing extension"
@@ -135,12 +137,26 @@ jobs:
- name: "Install npm dependencies in auditing extension"
run: cd extensions/Auditing && npm ci
- name: "Checkout SSO extension"
uses: actions/checkout@v7
with:
repository: ${{ steps.extension-manifest.outputs.sso_repository }}
ref: ${{ steps.extension-manifest.outputs.sso_ref }}
path: extensions/SSO
ssh-key: ${{ secrets.SSH_PRIVATE_KEY_SSO_EXTENSION }}
- name: "Install composer dependencies in SSO extension"
run: cd extensions/SSO && composer install --no-dev --no-ansi --no-interaction --prefer-dist --ignore-platform-reqs --classmap-authoritative
- name: "Activate invoicing extension"
run: php artisan module:enable Invoicing
- name: "Activate auditing extension"
run: php artisan module:enable Auditing
- name: "Activate SSO extension"
run: php artisan module:enable SSO
- name: "Install npm dependencies"
run: npm ci
@@ -160,7 +176,7 @@ jobs:
${{ env.DOCKER_REPO }}
- name: "Login to solidtime OnPremise Registry"
uses: docker/login-action@v4.7.0
uses: docker/login-action@v4.8.0
with:
registry: registry.on-premise.solidtime.io
username: ${{ secrets.ONPREMISE_USERNAME }}
@@ -183,6 +199,8 @@ jobs:
platforms: ${{ matrix.platform }}
labels: ${{ steps.meta.outputs.labels }}
outputs: type=image,"name=${{ env.DOCKER_REPO }}",push-by-digest=true,name-canonical=true,push=true
provenance: mode=max
sbom: true
cache-from: type=gha
cache-to: type=gha,mode=max
@@ -214,7 +232,7 @@ jobs:
merge-multiple: true
- name: "Login to solidtime OnPremise Registry"
uses: docker/login-action@v4.7.0
uses: docker/login-action@v4.8.0
with:
registry: registry.on-premise.solidtime.io
username: ${{ secrets.ONPREMISE_USERNAME }}
@@ -244,3 +262,17 @@ jobs:
- name: "Inspect image"
run: |
docker buildx imagetools inspect ${{ env.DOCKER_REPO }}:${{ steps.meta.outputs.version }}
- name: "Install cosign"
if: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }}
uses: sigstore/cosign-installer@756fe2d284c7292c4e9b62c8a28f1e5629c59532 # v4.1.3
# Keyless signing via GitHub OIDC; the signature is recorded in the public Sigstore transparency log.
- name: "Sign image"
if: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }}
env:
VERSION: ${{ steps.meta.outputs.version }}
run: |
digest=$(docker buildx imagetools inspect "${{ env.DOCKER_REPO }}:${VERSION}" --format '{{json .Manifest}}' | jq -r '.digest')
echo "Signing ${{ env.DOCKER_REPO }}@${digest}"
cosign sign --yes "${{ env.DOCKER_REPO }}@${digest}"

View File

@@ -14,6 +14,7 @@ on:
workflow_dispatch:
permissions:
contents: read
id-token: write
name: Build - Private
jobs:
@@ -86,6 +87,8 @@ jobs:
echo "invoicing_ref=$(jq -r '.Invoicing.ref' extensions/manifest.json)"
echo "auditing_repository=$(jq -r '.Auditing.repository' extensions/manifest.json)"
echo "auditing_ref=$(jq -r '.Auditing.ref' extensions/manifest.json)"
echo "sso_repository=$(jq -r '.SSO.repository' extensions/manifest.json)"
echo "sso_ref=$(jq -r '.SSO.ref' extensions/manifest.json)"
} >> "$GITHUB_OUTPUT"
- name: "Checkout billing extension"
@@ -166,6 +169,22 @@ jobs:
- name: "Install npm dependencies in auditing extension"
run: cd extensions/Auditing && npm ci
- name: "Checkout SSO extension"
uses: actions/checkout@v7
with:
repository: ${{ steps.extension-manifest.outputs.sso_repository }}
ref: ${{ steps.extension-manifest.outputs.sso_ref }}
path: extensions/SSO
ssh-key: ${{ secrets.SSH_PRIVATE_KEY_SSO_EXTENSION }}
- name: "Install composer dependencies in SSO extension"
uses: php-actions/composer@v6
with:
working_dir: "extensions/SSO"
command: install
only_args: --no-dev --no-ansi --no-interaction --prefer-dist --ignore-platform-reqs --classmap-authoritative
php_version: 8.3
- name: "Setup PHP with PECL extension"
uses: shivammathur/setup-php@v2
with:
@@ -192,6 +211,9 @@ jobs:
- name: "Activate auditing extension"
run: php artisan module:enable Auditing
- name: "Activate SSO extension"
run: php artisan module:enable SSO
- name: "Install npm dependencies"
run: npm ci
@@ -201,7 +223,7 @@ jobs:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
- name: "Login to GitHub Container Registry"
uses: docker/login-action@v4.7.0
uses: docker/login-action@v4.8.0
with:
registry: rg.fr-par.scw.cloud/solidtime
username: nologin
@@ -226,6 +248,7 @@ jobs:
uses: docker/setup-buildx-action@v4
- name: "Build and push"
id: build-push
uses: docker/build-push-action@v7
with:
context: .
@@ -238,3 +261,14 @@ jobs:
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
- name: "Install cosign"
if: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }}
uses: sigstore/cosign-installer@756fe2d284c7292c4e9b62c8a28f1e5629c59532 # v4.1.3
# Keyless signing via GitHub OIDC; the deploy script verifies this signature before rollout.
- name: "Sign image"
if: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }}
env:
DIGEST: ${{ steps.build-push.outputs.digest }}
run: cosign sign --yes "rg.fr-par.scw.cloud/solidtime/solidtime@${DIGEST}"

View File

@@ -117,13 +117,13 @@ jobs:
${{ env.GHCR_REPO }}
- name: "Login to Docker Hub Container Registry"
uses: docker/login-action@v4.7.0
uses: docker/login-action@v4.8.0
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: "Login to GitHub Container Registry"
uses: docker/login-action@v4.7.0
uses: docker/login-action@v4.8.0
with:
registry: ghcr.io
username: ${{ github.actor }}
@@ -146,6 +146,8 @@ jobs:
platforms: ${{ matrix.platform }}
labels: ${{ steps.meta.outputs.labels }}
outputs: type=image,"name=${{ env.DOCKERHUB_REPO }},${{ env.GHCR_REPO }}",push-by-digest=true,name-canonical=true,push=true
provenance: mode=max
sbom: true
cache-from: type=gha
cache-to: type=gha,mode=max
@@ -177,13 +179,13 @@ jobs:
merge-multiple: true
- name: "Login to Docker Hub"
uses: docker/login-action@v4.7.0
uses: docker/login-action@v4.8.0
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: "Login to GHCR"
uses: docker/login-action@v4.7.0
uses: docker/login-action@v4.8.0
with:
registry: ghcr.io
username: ${{ github.actor }}
@@ -217,3 +219,19 @@ jobs:
run: |
docker buildx imagetools inspect ${{ env.DOCKERHUB_REPO }}:${{ steps.meta.outputs.version }}
docker buildx imagetools inspect ${{ env.GHCR_REPO }}:${{ steps.meta.outputs.version }}
- name: "Install cosign"
if: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }}
uses: sigstore/cosign-installer@756fe2d284c7292c4e9b62c8a28f1e5629c59532 # v4.1.3
# Keyless signing via GitHub OIDC; the signature is recorded in the public Sigstore transparency log.
- name: "Sign image"
if: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }}
env:
VERSION: ${{ steps.meta.outputs.version }}
run: |
for repo in "${{ env.DOCKERHUB_REPO }}" "${{ env.GHCR_REPO }}"; do
digest=$(docker buildx imagetools inspect "${repo}:${VERSION}" --format '{{json .Manifest}}' | jq -r '.digest')
echo "Signing ${repo}@${digest}"
cosign sign --yes "${repo}@${digest}"
done

View File

@@ -0,0 +1,37 @@
name: NPM Packages Check
# Type-checks and builds the shared packages on every PR that touches them.
on:
pull_request:
paths:
- 'resources/js/packages/**'
- 'package.json'
- 'package-lock.json'
- '.github/workflows/npm-packages-check.yml'
permissions:
contents: read
jobs:
check:
runs-on: ubuntu-latest
timeout-minutes: 15
env:
# Dependency order: ui and composables build against api
PACKAGES: api ui composables
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: '24.x'
- run: npm ci
- name: Type-check and build packages
run: |
for package in $PACKAGES; do
dir="resources/js/packages/$package"
[ -d "$dir" ] || continue
echo "::group::$package"
npm run type-check --if-present --prefix "$dir"
npm run build --prefix "$dir"
echo "::endgroup::"
done

63
.github/workflows/npm-packages.yml vendored Normal file
View File

@@ -0,0 +1,63 @@
name: NPM Packages
# Publishes each shared package whose version isn't on npm yet. npm's trusted
# publisher config points at this file, so keep unrelated changes out of it.
on:
push:
branches: [main]
paths:
- 'resources/js/packages/**'
- '.github/workflows/npm-packages.yml'
workflow_dispatch:
permissions:
contents: read
jobs:
publish:
runs-on: ubuntu-latest
timeout-minutes: 15
# Restricted to main in the repo settings, which a branch can't override
# by editing this file. npm's trusted publisher config requires it too.
environment: npm
concurrency:
group: npm-publish
cancel-in-progress: false
permissions:
contents: read
id-token: write # npm trusted publishing and provenance
env:
# Dependency order: ui and composables build against api
PACKAGES: api ui composables
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
# npm >= 11.5.1 is required for trusted publishing
node-version: '24.x'
registry-url: 'https://registry.npmjs.org'
- run: npm ci
- name: Publish new package versions
run: |
for package in $PACKAGES; do
dir="resources/js/packages/$package"
[ -d "$dir" ] || continue
name=$(node -p "require('./$dir/package.json').name")
version=$(node -p "require('./$dir/package.json').version")
# Build every package so later ones can build against it
npm run type-check --if-present --prefix "$dir"
npm run build --prefix "$dir"
if existing=$(npm view "$name@$version" version 2>&1); then
echo "$name@$version is already published"
continue
elif ! grep -q E404 <<< "$existing"; then
echo "$existing"
exit 1
fi
(cd "$dir" && npm publish --provenance --access public)
done

View File

@@ -1,32 +0,0 @@
name: Publish API package to NPM
on:
workflow_dispatch
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
steps:
- name: "Checkout code"
uses: actions/checkout@v7
# Setup .npmrc file to publish to npm
- name: Install root project dependencies
run: npm ci
- uses: actions/setup-node@v7
with:
node-version: '20.x'
registry-url: 'https://registry.npmjs.org'
- name: Install dependencies
run: npm ci
working-directory: ./resources/js/packages/api
- name: Build package
run: npm run build
working-directory: ./resources/js/packages/api
- name: Publish Package
run: npm publish --provenance --access public
working-directory: ./resources/js/packages/api
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

View File

@@ -1,32 +0,0 @@
name: Publish UI package to NPM
on:
workflow_dispatch
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
steps:
- name: "Checkout code"
uses: actions/checkout@v7
# Setup .npmrc file to publish to npm
- uses: actions/setup-node@v7
with:
node-version: '20.x'
registry-url: 'https://registry.npmjs.org'
- name: Install root project dependencies
run: npm ci
- name: Install package dependencies
run: npm ci
working-directory: ./resources/js/packages/ui
- name: Build package
run: npm run build
working-directory: ./resources/js/packages/ui
- name: Publish Package
run: npm publish --provenance --access public
working-directory: ./resources/js/packages/ui
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

View File

@@ -8,7 +8,7 @@ jobs:
timeout-minutes: 25
strategy:
matrix:
postgres_version: [ 15, 16, 17 ]
postgres_version: [ 15, 16, 17, 18 ]
services:
pgsql_test:

View File

@@ -8,7 +8,7 @@ jobs:
timeout-minutes: 10
strategy:
matrix:
postgres_version: [ 15, 16, 17 ]
postgres_version: [ 15, 16, 17, 18 ]
services:
pgsql_test:

View File

@@ -11,7 +11,15 @@ jobs:
- name: "Checkout code"
uses: actions/checkout@v7
- name: "Check code style"
uses: aglipanci/laravel-pint-action@2.6
- name: "Setup PHP"
uses: shivammathur/setup-php@v2
with:
configPath: "pint.json"
php-version: '8.3'
extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv
coverage: none
- name: "Run composer install"
run: composer install -n --prefer-dist
- name: "Check code style"
run: vendor/bin/pint --test --config pint.json

View File

@@ -2,7 +2,30 @@
## Reporting a Vulnerability
If you discover a security vulnerability regarding this project, please e-mail me to [security@solidtime.io](mailto:security@solidtime.io)!
If you discover a security vulnerability regarding this project, please e-mail me to [security@solidtime.io](mailto:security@solidtime.io) or use GitHub's [private vulnerability reporting](https://github.com/solidtime-io/solidtime/security/advisories/new)!
Published advisories are listed at [github.com/solidtime-io/solidtime/security/advisories](https://github.com/solidtime-io/solidtime/security/advisories).
## Verifying Docker images
The public images (`solidtime/solidtime` and `ghcr.io/solidtime-io/solidtime`) are signed with [Sigstore cosign](https://github.com/sigstore/cosign) (keyless, via GitHub Actions OIDC) and ship with an SBOM and SLSA provenance attestation.
Verify the signature:
```bash
cosign verify solidtime/solidtime:<version> \
--certificate-identity-regexp '^https://github.com/solidtime-io/solidtime/.github/workflows/build-public.yml@refs/(heads/main|tags/v.*)$' \
--certificate-oidc-issuer https://token.actions.githubusercontent.com
```
On-premise images (`registry.on-premise.solidtime.io/solidtime/solidtime`) are signed the same way; log in to the registry first and use `build-onpremise.yml` instead of `build-public.yml` in the identity regex.
Show the SBOM (SPDX) and build provenance:
```bash
docker buildx imagetools inspect solidtime/solidtime:<version> --format '{{ json .SBOM }}'
docker buildx imagetools inspect solidtime/solidtime:<version> --format '{{ json .Provenance }}'
```
## Out of scope

View File

@@ -8,6 +8,7 @@ use App\Enums\RegistrationMode;
use App\Enums\Weekday;
use App\Events\NewsletterRegistered;
use App\Models\User;
use App\Service\AuthenticationContract;
use App\Service\InvitationService;
use App\Service\IpLookup\IpLookupServiceContract;
use App\Service\TimezoneService;
@@ -40,6 +41,12 @@ class CreateNewUser implements CreatesNewUsers
]);
}
if (! app(AuthenticationContract::class)->isPasswordRegistrationAllowed()) {
throw ValidationException::withMessages([
'email' => [__(AuthenticationContract::PASSWORD_REGISTRATION_DISABLED_MESSAGE)],
]);
}
$validated = Validator::make($input, [
'name' => [
'required',
@@ -109,17 +116,17 @@ class CreateNewUser implements CreatesNewUsers
DB::transaction(function () use (&$user, $input, $timezone, $startOfWeek, $currency, $numberFormat, $currencyFormat, $dateFormat, $intervalFormat, $timeFormat): void {
$userService = app(UserService::class);
$user = $userService->createUser(
$input['name'],
$input['email'],
$input['password'],
$timezone ?? 'UTC',
$startOfWeek,
$currency,
$numberFormat,
$currencyFormat,
$dateFormat,
$intervalFormat,
$timeFormat
name: $input['name'],
email: $input['email'],
password: $input['password'],
timezone: $timezone ?? 'UTC',
weekStart: $startOfWeek,
currency: $currency,
numberFormat: $numberFormat,
currencyFormat: $currencyFormat,
dateFormat: $dateFormat,
intervalFormat: $intervalFormat,
timeFormat: $timeFormat,
);
});

View File

@@ -5,8 +5,12 @@ declare(strict_types=1);
namespace App\Actions\Fortify;
use App\Models\User;
use App\Service\AuthenticationContract;
use Illuminate\Auth\Passwords\PasswordBroker;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Laravel\Fortify\Contracts\ResetsUserPasswords;
class ResetUserPassword implements ResetsUserPasswords
@@ -20,6 +24,16 @@ class ResetUserPassword implements ResetsUserPasswords
*/
public function reset(User $user, array $input): void
{
if (! app(AuthenticationContract::class)->isPasswordLoginAllowed($user)) {
/** @var PasswordBroker $broker */
$broker = Password::broker(config('fortify.passwords'));
$broker->deleteToken($user);
throw ValidationException::withMessages([
'email' => [__('This password reset link is invalid.')],
]);
}
Validator::make($input, [
'password' => $this->passwordRules(),
])->validate();

View File

@@ -5,8 +5,10 @@ declare(strict_types=1);
namespace App\Actions\Fortify;
use App\Models\User;
use App\Service\IdentityConfirmationService;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Laravel\Fortify\Contracts\UpdatesUserPasswords;
class UpdateUserPassword implements UpdatesUserPasswords
@@ -20,6 +22,13 @@ class UpdateUserPassword implements UpdatesUserPasswords
*/
public function update(User $user, array $input): void
{
// Users who may not log in with their password (e.g. SSO) have no password to change
if (! app(IdentityConfirmationService::class)->confirmsWithPassword($user)) {
throw ValidationException::withMessages([
'current_password' => [__('Your account has no password to confirm this with. Contact your administrator.')],
])->errorBag('updatePassword');
}
Validator::make($input, [
'current_password' => ['required', 'string', 'current_password:web'],
'password' => $this->passwordRules(),

View File

@@ -10,6 +10,8 @@ use App\Models\User;
use App\Service\UserService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use LogicException;
class UserCreateCommand extends Command
@@ -38,10 +40,18 @@ class UserCreateCommand extends Command
public function handle(): int
{
$name = $this->argument('name');
$email = $this->argument('email');
// Lowercased like UserService::createUser() stores it, so the existence check below finds any casing.
$email = Str::lower((string) $this->argument('email'));
$askForPassword = (bool) $this->option('ask-for-password');
$verifyEmail = (bool) $this->option('verify-email');
// Same rule as registration
if (Validator::make(['email' => $email], ['email' => ['required', 'email:rfc,strict']])->fails()) {
$this->error('"'.$email.'" is not a valid email address.');
return self::FAILURE;
}
if (User::query()->where('email', $email)->where('is_placeholder', '=', false)->exists()) {
$this->error('User with email "'.$email.'" already exists.');
@@ -59,13 +69,13 @@ class UserCreateCommand extends Command
$user = null;
DB::transaction(function () use (&$user, $name, $email, $password, $verifyEmail): void {
$user = app(UserService::class)->createUser(
$name,
$email,
$password,
'UTC',
Weekday::Monday,
null,
verifyEmail: $verifyEmail
name: $name,
email: $email,
password: $password,
timezone: 'UTC',
weekStart: Weekday::Monday,
currency: null,
verifyEmail: $verifyEmail,
);
});
/** @var Organization|null $organization */

View File

@@ -7,6 +7,7 @@ namespace App\Console\Commands\Admin;
use App\Models\User;
use Illuminate\Auth\Events\Verified;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
class UserVerifyCommand extends Command
{
@@ -30,7 +31,8 @@ class UserVerifyCommand extends Command
*/
public function handle(): int
{
$email = $this->argument('email');
// Emails are stored lowercase (see UserService::createUser)
$email = Str::lower((string) $this->argument('email'));
$this->info('Start verifying user with email "'.$email.'"');

View File

@@ -0,0 +1,78 @@
<?php
declare(strict_types=1);
namespace App\Console\Commands\Export;
use App\Models\Export;
use App\Service\Export\ExportService;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;
class ExportPruneCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'export:prune '.
' { --dry-run : Do not actually save or delete anything, just output what would happen }';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Marks stale exports as failed and deletes export files after the retention period.';
/**
* Execute the console command.
*/
public function handle(ExportService $exportService): int
{
$dryRun = (bool) $this->option('dry-run');
if ($dryRun) {
$this->comment('Running in dry-run mode. Nothing will be saved or deleted.');
}
$staleExports = 0;
Export::query()
->stale()
->chunkById(500, function (Collection $exports) use ($dryRun, $exportService, &$staleExports): void {
/** @var Collection<int, Export> $exports */
foreach ($exports as $export) {
$this->info('Mark stale export '.$export->getKey().' ('.$export->status->value.') as failed');
$staleExports++;
if (! $dryRun) {
$exportService->markAsFailed($export, 'Export could not be finished');
}
}
});
$retentionBefore = Carbon::now()->subDays((int) config('export.file_retention_days'));
$prunedFiles = 0;
Export::query()
->whereNotNull('file_path')
->whereNotNull('finished_at')
->where('finished_at', '<', $retentionBefore)
->chunkById(500, function (Collection $exports) use ($dryRun, &$prunedFiles): void {
/** @var Collection<int, Export> $exports */
foreach ($exports as $export) {
$this->info('Delete file of export '.$export->getKey().' ('.$export->file_path.')');
$prunedFiles++;
if (! $dryRun) {
Storage::disk(config('filesystems.private'))->delete((string) $export->file_path);
$export->file_path = null;
$export->save();
}
}
});
$this->comment('Marked '.$staleExports.' stale exports as failed and deleted '.$prunedFiles.' export files.');
return self::SUCCESS;
}
}

View File

@@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
namespace App\Console\Commands\Heartbeat;
use App\Jobs\HeartbeatQueueJob;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Throwable;
class HeartbeatSendCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'heartbeat:send';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Sends the scheduler heartbeat and dispatches the queue heartbeat job to the configured monitoring URLs.';
/**
* Execute the console command.
*/
public function handle(): int
{
$schedulerUrl = config('heartbeat.scheduler_url');
$queueUrl = config('heartbeat.queue_url');
if (! is_string($schedulerUrl) || $schedulerUrl === '') {
$schedulerUrl = null;
}
if (! is_string($queueUrl) || $queueUrl === '') {
$queueUrl = null;
}
if ($schedulerUrl === null && $queueUrl === null) {
$this->info('No heartbeat URLs configured, nothing to do.');
return self::SUCCESS;
}
if ($schedulerUrl !== null) {
try {
Http::timeout((int) config('heartbeat.timeout'))
->connectTimeout(2)
->get($schedulerUrl)
->throw();
$this->info('Scheduler heartbeat sent.');
} catch (Throwable $exception) {
Log::warning('Failed to send scheduler heartbeat', [
'exception' => $exception->getMessage(),
]);
$this->warn('Failed to send scheduler heartbeat, check the logs for more information.');
}
}
if ($queueUrl !== null) {
$queueConnection = config('queue.default');
if (config('queue.connections.'.$queueConnection.'.driver') === 'sync') {
// With the sync driver the job would run inline in the scheduler, so the heartbeat would not prove that a queue worker is running.
Log::warning('Skipped queue heartbeat, because the queue connection uses the sync driver', [
'queue_connection' => $queueConnection,
]);
$this->warn('Skipped queue heartbeat, because the queue connection uses the sync driver.');
} else {
HeartbeatQueueJob::dispatch(Carbon::now()->getTimestampMs());
$this->info('Queue heartbeat job dispatched.');
}
}
return self::SUCCESS;
}
}

View File

@@ -0,0 +1,78 @@
<?php
declare(strict_types=1);
namespace App\Console\Commands\Import;
use App\Models\Import;
use App\Service\Import\ImportService;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;
class ImportPruneCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'import:prune '.
' { --dry-run : Do not actually save or delete anything, just output what would happen }';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Marks stale imports as failed and deletes import files after the retention period.';
/**
* Execute the console command.
*/
public function handle(ImportService $importService): int
{
$dryRun = (bool) $this->option('dry-run');
if ($dryRun) {
$this->comment('Running in dry-run mode. Nothing will be saved or deleted.');
}
$staleImports = 0;
Import::query()
->stale()
->chunkById(500, function (Collection $imports) use ($dryRun, $importService, &$staleImports): void {
/** @var Collection<int, Import> $imports */
foreach ($imports as $import) {
$this->info('Mark stale import '.$import->getKey().' ('.$import->status->value.') as failed');
$staleImports++;
if (! $dryRun) {
$importService->markAsFailed($import, 'Import could not be finished');
}
}
});
$retentionBefore = Carbon::now()->subDays((int) config('import.file_retention_days'));
$prunedFiles = 0;
Import::query()
->whereNotNull('file_path')
->whereNotNull('finished_at')
->where('finished_at', '<', $retentionBefore)
->chunkById(500, function (Collection $imports) use ($dryRun, &$prunedFiles): void {
/** @var Collection<int, Import> $imports */
foreach ($imports as $import) {
$this->info('Delete file of import '.$import->getKey().' ('.$import->file_path.')');
$prunedFiles++;
if (! $dryRun) {
Storage::disk(config('filesystems.private'))->delete((string) $import->file_path);
$import->file_path = null;
$import->save();
}
}
});
$this->comment('Marked '.$staleImports.' stale imports as failed and deleted '.$prunedFiles.' import files.');
return self::SUCCESS;
}
}

View File

@@ -106,6 +106,15 @@ class SelfHostDatabaseConsistency extends Command
})->get();
$this->logProblems($problems, 'Users have a current organization that they are not a member of', $hadAProblem);
// Project members need to be a member of the organization of the project
$problems = DB::table('project_members')
->select(['project_members.id as id'])
->join('projects', 'project_members.project_id', '=', 'projects.id')
->join('members', 'project_members.member_id', '=', 'members.id')
->whereColumn('members.organization_id', '!=', 'projects.organization_id')
->get();
$this->logProblems($problems, 'Project members have a member that does not belong to the organization of the project', $hadAProblem);
return $hadAProblem ? self::FAILURE : self::SUCCESS;
}

View File

@@ -44,9 +44,22 @@ class Kernel extends ConsoleKernel
}
}
$schedule->command('import:prune')
->when(fn (): bool => config('scheduling.tasks.import_prune'))
->everyFiveMinutes();
$schedule->command('export:prune')
->when(fn (): bool => config('scheduling.tasks.export_prune'))
->everyFiveMinutes();
$schedule->command('self-host:database-consistency')
->when(fn (): bool => config('scheduling.tasks.self_hosting_database_consistency'))
->everySixHours();
$schedule->command('heartbeat:send')
->when(fn (): bool => filled(config('heartbeat.scheduler_url')) || filled(config('heartbeat.queue_url')))
->everyMinute()
->onOneServer();
}
/**

View File

@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace App\Enums;
use Datomatic\LaravelEnumHelper\LaravelEnumHelper;
enum ExportStatus: string
{
use LaravelEnumHelper;
case Pending = 'pending';
case Running = 'running';
case Completed = 'completed';
case Failed = 'failed';
/**
* Statuses of exports that are not finished yet, only one export per organization can have one of these statuses.
*
* @return array<ExportStatus>
*/
public static function active(): array
{
return [self::Pending, self::Running];
}
public function isActive(): bool
{
return in_array($this, self::active(), true);
}
}

17
app/Enums/ExportType.php Normal file
View File

@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace App\Enums;
use Datomatic\LaravelEnumHelper\LaravelEnumHelper;
enum ExportType: string
{
use LaravelEnumHelper;
/**
* Full export of all data of an organization (ZIP with CSV files), can be imported with the solidtime importer
*/
case Organization = 'organization';
}

View File

@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Enums;
use Datomatic\LaravelEnumHelper\LaravelEnumHelper;
enum ImportSource: string
{
use LaravelEnumHelper;
/**
* Import of an uploaded file (CSV, JSON or ZIP)
*/
case File = 'file';
/**
* Import via the API of a third party service
*/
case Api = 'api';
}

View File

@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace App\Enums;
use Datomatic\LaravelEnumHelper\LaravelEnumHelper;
enum ImportStatus: string
{
use LaravelEnumHelper;
case Pending = 'pending';
case Running = 'running';
case Completed = 'completed';
case Failed = 'failed';
/**
* Statuses of imports that are not finished yet, only one import per organization can have one of these statuses.
*
* @return array<ImportStatus>
*/
public static function active(): array
{
return [self::Pending, self::Running];
}
public function isActive(): bool
{
return in_array($this, self::active(), true);
}
}

View File

@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Events;
use App\Models\User;
use Illuminate\Foundation\Events\Dispatchable;
class BeforeUserDeletion
{
use Dispatchable;
public User $user;
public function __construct(User $user)
{
$this->user = $user;
}
}

View File

@@ -8,14 +8,15 @@ use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use LogicException;
use Throwable;
abstract class ApiException extends Exception
{
public const string KEY = 'api_exception';
public function __construct()
public function __construct(?Throwable $previous = null)
{
parent::__construct(static::KEY);
parent::__construct(static::KEY, 0, $previous);
}
/**

View File

@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Exceptions\Api;
class ExportAlreadyInProgressApiException extends ApiException
{
public const string KEY = 'export_already_in_progress';
public function report(): bool
{
return true;
}
}

View File

@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Exceptions\Api;
class ExportFileNotAvailableApiException extends ApiException
{
public const string KEY = 'export_file_not_available';
public function report(): bool
{
return true;
}
}

View File

@@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace App\Exceptions;
use Exception;
/**
* Thrown by listeners of the MemberAdding event to prevent a member from being added to an organization.
*/
class MemberCanNotBeAddedException extends Exception {}

View File

@@ -0,0 +1,193 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources;
use App\Enums\ExportStatus;
use App\Enums\ExportType;
use App\Filament\Resources\ExportResource\Pages\ListExports;
use App\Filament\Resources\ExportResource\Pages\ViewExport;
use App\Models\Export;
use Carbon\CarbonInterface;
use Filament\Actions\Action;
use Filament\Actions\ViewAction;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;
class ExportResource extends Resource
{
protected static ?string $model = Export::class;
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-archive-box-arrow-down';
protected static string|\UnitEnum|null $navigationGroup = 'Timetracking';
protected static ?int $navigationSort = 10;
public static function form(Schema $schema): Schema
{
return $schema
->columns(2)
->components([
TextInput::make('id')
->label('ID')
->disabled(),
Select::make('organization_id')
->label('Organization')
->relationship(name: 'organization', titleAttribute: 'name')
->hintAction(
Action::make('open-organization')
->label('Open organization')
->icon('heroicon-o-arrow-top-right-on-square')
->url(fn (?Export $record): ?string => $record !== null
? OrganizationResource::getUrl('view', ['record' => $record->organization_id])
: null)
)
->disabled(),
Select::make('user_id')
->label('User')
->relationship(name: 'user', titleAttribute: 'email')
->hintAction(
Action::make('open-user')
->label('Open user')
->icon('heroicon-o-arrow-top-right-on-square')
->hidden(fn (?Export $record): bool => $record?->user_id === null)
->url(fn (?Export $record): ?string => $record?->user_id !== null
? UserResource::getUrl('view', ['record' => $record->user_id])
: null)
)
->disabled(),
Select::make('type')
->label('Type')
->options(ExportType::class)
->disabled(),
Select::make('status')
->label('Status')
->options(ExportStatus::class)
->disabled(),
TextInput::make('file_path')
->label('File path')
->disabled(),
Textarea::make('error_message')
->label('Error message')
->columnSpanFull()
->disabled(),
Textarea::make('error_details')
->label('Error details')
->helperText('Exception chain and stack trace, only visible in the admin panel')
// The attribute is hidden for serialization, so it is not filled into the form automatically
->formatStateUsing(fn (Export $record): ?string => $record->error_details)
->rows(15)
->extraInputAttributes(['style' => 'font-family: monospace; font-size: 80%;'])
->columnSpanFull()
->disabled(),
DateTimePicker::make('created_at')
->label('Created at')
->disabled(),
DateTimePicker::make('started_at')
->label('Started at')
->disabled(),
DateTimePicker::make('finished_at')
->label('Finished at')
->disabled(),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
TextColumn::make('organization.name')
->url(fn (Export $record): string => OrganizationResource::getUrl('view', ['record' => $record->organization_id]))
->searchable()
->sortable(),
TextColumn::make('user.email')
->label('User')
->url(fn (Export $record): ?string => $record->user_id !== null
? UserResource::getUrl('view', ['record' => $record->user_id])
: null)
->searchable()
->toggleable(),
TextColumn::make('type')
->sortable()
->toggleable(isToggledHiddenByDefault: true),
TextColumn::make('status')
->badge()
->color(fn (Export $record): string => match ($record->status) {
ExportStatus::Pending => 'gray',
ExportStatus::Running => 'info',
ExportStatus::Completed => 'success',
ExportStatus::Failed => 'danger',
})
->sortable(),
TextColumn::make('error_message')
->limit(80)
->toggleable(),
TextColumn::make('created_at')
->dateTime()
->sortable(),
TextColumn::make('duration')
->label('Duration')
->state(function (Export $record): ?string {
if ($record->started_at === null || $record->finished_at === null) {
return null;
}
return $record->started_at->diffForHumans($record->finished_at, [
'syntax' => CarbonInterface::DIFF_ABSOLUTE,
'parts' => 2,
]);
}),
])
->defaultSort('created_at', 'desc')
->filters([
SelectFilter::make('status')
->options(ExportStatus::class),
SelectFilter::make('type')
->options(ExportType::class),
SelectFilter::make('organization')
->label('Organization')
->relationship('organization', 'name')
->searchable(),
SelectFilter::make('organization_id')
->label('Organization ID')
->relationship('organization', 'id')
->searchable(),
])
->recordActions([
Action::make('download-file')
->label('File')
->icon('heroicon-o-arrow-down-tray')
->color('gray')
->hidden(fn (Export $record): bool => $record->file_path === null)
->action(fn (Export $record): StreamedResponse => Storage::disk(config('filesystems.private'))
->download((string) $record->file_path, $record->getDownloadFilename('UTC'))),
ViewAction::make(),
])
->toolbarActions([
]);
}
public static function canCreate(): bool
{
return false;
}
public static function getPages(): array
{
return [
'index' => ListExports::route('/'),
'view' => ViewExport::route('/{record}'),
];
}
}

View File

@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\ExportResource\Pages;
use App\Filament\Resources\ExportResource;
use Filament\Resources\Pages\ListRecords;
class ListExports extends ListRecords
{
protected static string $resource = ExportResource::class;
protected function getHeaderActions(): array
{
return [
];
}
}

View File

@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\ExportResource\Pages;
use App\Filament\Resources\ExportResource;
use Filament\Resources\Pages\ViewRecord;
class ViewExport extends ViewRecord
{
protected static string $resource = ExportResource::class;
protected function getHeaderActions(): array
{
return [
];
}
}

View File

@@ -0,0 +1,222 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources;
use App\Enums\ImportSource;
use App\Enums\ImportStatus;
use App\Filament\Resources\ImportResource\Pages\ListImports;
use App\Filament\Resources\ImportResource\Pages\ViewImport;
use App\Models\Import;
use App\Service\Import\Importers\ImporterProvider;
use Carbon\CarbonInterface;
use Filament\Actions\Action;
use Filament\Actions\ViewAction;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Support\Facades\Storage;
use Novadaemon\FilamentPrettyJson\Form\PrettyJsonField;
use Symfony\Component\HttpFoundation\StreamedResponse;
class ImportResource extends Resource
{
protected static ?string $model = Import::class;
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-inbox-arrow-down';
protected static string|\UnitEnum|null $navigationGroup = 'Timetracking';
protected static ?int $navigationSort = 9;
public static function form(Schema $schema): Schema
{
return $schema
->columns(2)
->components([
TextInput::make('id')
->label('ID')
->disabled(),
Select::make('organization_id')
->label('Organization')
->relationship(name: 'organization', titleAttribute: 'name')
->hintAction(
Action::make('open-organization')
->label('Open organization')
->icon('heroicon-o-arrow-top-right-on-square')
->url(fn (?Import $record): ?string => $record !== null
? OrganizationResource::getUrl('view', ['record' => $record->organization_id])
: null)
)
->disabled(),
Select::make('user_id')
->label('User')
->relationship(name: 'user', titleAttribute: 'email')
->hintAction(
Action::make('open-user')
->label('Open user')
->icon('heroicon-o-arrow-top-right-on-square')
->hidden(fn (?Import $record): bool => $record?->user_id === null)
->url(fn (?Import $record): ?string => $record?->user_id !== null
? UserResource::getUrl('view', ['record' => $record->user_id])
: null)
)
->disabled(),
TextInput::make('type')
->label('Type')
->disabled(),
Select::make('source')
->label('Source')
->options(ImportSource::class)
->disabled(),
Select::make('status')
->label('Status')
->options(ImportStatus::class)
->disabled(),
TextInput::make('timezone')
->label('Timezone')
->disabled(),
TextInput::make('file_path')
->label('File path')
->disabled(),
Toggle::make('ignore_limits')
->label('Ignore limits (admin import)')
->disabled(),
Textarea::make('error_message')
->label('Error message')
->columnSpanFull()
->disabled(),
Textarea::make('error_details')
->label('Error details')
->helperText('Exception chain and stack trace, only visible in the admin panel')
// The attribute is hidden for serialization, so it is not filled into the form automatically
->formatStateUsing(fn (Import $record): ?string => $record->error_details)
->rows(15)
->extraInputAttributes(['style' => 'font-family: monospace; font-size: 80%;'])
->columnSpanFull()
->disabled(),
PrettyJsonField::make('report')
->formatStateUsing(fn (Import $record): ?string => $record->getRawOriginal('report'))
->columnSpanFull()
->disabled(),
PrettyJsonField::make('options')
->formatStateUsing(fn (Import $record): ?string => $record->getRawOriginal('options'))
->columnSpanFull()
->disabled(),
DateTimePicker::make('created_at')
->label('Created at')
->disabled(),
DateTimePicker::make('started_at')
->label('Started at')
->disabled(),
DateTimePicker::make('finished_at')
->label('Finished at')
->disabled(),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
TextColumn::make('organization.name')
->url(fn (Import $record): string => OrganizationResource::getUrl('view', ['record' => $record->organization_id]))
->searchable()
->sortable(),
TextColumn::make('user.email')
->label('User')
->url(fn (Import $record): ?string => $record->user_id !== null
? UserResource::getUrl('view', ['record' => $record->user_id])
: null)
->searchable()
->toggleable(),
TextColumn::make('type')
->sortable(),
TextColumn::make('source')
->sortable()
->toggleable(isToggledHiddenByDefault: true),
TextColumn::make('status')
->badge()
->color(fn (Import $record): string => match ($record->status) {
ImportStatus::Pending => 'gray',
ImportStatus::Running => 'info',
ImportStatus::Completed => 'success',
ImportStatus::Failed => 'danger',
})
->sortable(),
TextColumn::make('error_message')
->limit(80)
->toggleable(),
TextColumn::make('created_at')
->dateTime()
->sortable(),
TextColumn::make('duration')
->label('Duration')
->state(function (Import $record): ?string {
if ($record->started_at === null || $record->finished_at === null) {
return null;
}
return $record->started_at->diffForHumans($record->finished_at, [
'syntax' => CarbonInterface::DIFF_ABSOLUTE,
'parts' => 2,
]);
}),
])
->defaultSort('created_at', 'desc')
->filters([
SelectFilter::make('status')
->options(ImportStatus::class),
SelectFilter::make('type')
->options(function (): array {
$options = [];
foreach (app(ImporterProvider::class)->getImporterKeys() as $key) {
$options[$key] = $key;
}
return $options;
}),
SelectFilter::make('organization')
->label('Organization')
->relationship('organization', 'name')
->searchable(),
SelectFilter::make('organization_id')
->label('Organization ID')
->relationship('organization', 'id')
->searchable(),
])
->recordActions([
Action::make('download-file')
->label('File')
->icon('heroicon-o-arrow-down-tray')
->color('gray')
->hidden(fn (Import $record): bool => $record->file_path === null)
->action(fn (Import $record): StreamedResponse => Storage::disk(config('filesystems.private'))
->download((string) $record->file_path, 'import-'.$record->getKey())),
ViewAction::make(),
])
->toolbarActions([
]);
}
public static function canCreate(): bool
{
return false;
}
public static function getPages(): array
{
return [
'index' => ListImports::route('/'),
'view' => ViewImport::route('/{record}'),
];
}
}

View File

@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\ImportResource\Pages;
use App\Filament\Resources\ImportResource;
use Filament\Resources\Pages\ListRecords;
class ListImports extends ListRecords
{
protected static string $resource = ImportResource::class;
protected function getHeaderActions(): array
{
return [
];
}
}

View File

@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\ImportResource\Pages;
use App\Filament\Resources\ImportResource;
use Filament\Resources\Pages\ViewRecord;
class ViewImport extends ViewRecord
{
protected static string $resource = ImportResource::class;
protected function getHeaderActions(): array
{
return [
];
}
}

View File

@@ -16,11 +16,11 @@ use App\Filament\Resources\OrganizationResource\Pages\ViewOrganization;
use App\Filament\Resources\OrganizationResource\RelationManagers\InvitationsRelationManager;
use App\Filament\Resources\OrganizationResource\RelationManagers\UsersRelationManager;
use App\Models\Organization;
use App\Models\User;
use App\Service\DeletionService;
use App\Service\Export\ExportService;
use App\Service\Import\Importers\ImporterProvider;
use App\Service\Import\Importers\ImportException;
use App\Service\Import\Importers\ReportDto;
use App\Service\Import\ImportService;
use App\Service\TimezoneService;
use Brick\Money\IsoCurrencyProvider;
@@ -39,6 +39,7 @@ use Filament\Schemas\Schema;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use League\Flysystem\UnableToReadFile;
@@ -192,30 +193,30 @@ class OrganizationResource extends Resource
}
/** @var string $timezone */
$timezone = $data['timezone'];
/** @var ReportDto $report */
$report = app(ImportService::class)->import(
/** @var User|null $user */
$user = Auth::user();
$import = app(ImportService::class)->createFileImport(
$record,
$user,
$data['type'],
$file,
$timezone
$timezone,
ignoreLimits: true
);
Notification::make()
->title('Import successful')
->title('Import queued')
->success()
->body(
'Imported time entries: '.$report->timeEntriesCreated.'<br>'.
'Imported clients: '.$report->clientsCreated.'<br>'.
'Imported projects: '.$report->projectsCreated.'<br>'.
'Imported tasks: '.$report->tasksCreated.'<br>'.
'Imported tags: '.$report->tagsCreated.'<br>'.
'Imported users: '.$report->usersCreated
)
->body('The import is processed in the background, see the imports for the result.')
->actions([
Action::make('view')
->label('View import')
->url(ImportResource::getUrl('view', ['record' => $import])),
])
->persistent()
->send();
} catch (ImportException $exception) {
report($exception);
Notification::make()
->title('Import failed, changes rolled back')
->title('Import failed')
->danger()
->body('Message: '.$exception->getMessage())
->persistent()

View File

@@ -7,7 +7,11 @@ namespace App\Filament\Resources;
use App\Filament\Resources\TimeEntryResource\Pages\CreateTimeEntry;
use App\Filament\Resources\TimeEntryResource\Pages\EditTimeEntry;
use App\Filament\Resources\TimeEntryResource\Pages\ListTimeEntries;
use App\Jobs\RecalculateSpentTimeForProject;
use App\Jobs\RecalculateSpentTimeForTask;
use App\Models\Member;
use App\Models\Project;
use App\Models\Task;
use App\Models\TimeEntry;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
@@ -22,6 +26,7 @@ use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
class TimeEntryResource extends Resource
{
@@ -120,7 +125,13 @@ class TimeEntryResource extends Resource
])
->toolbarActions([
BulkActionGroup::make([
DeleteBulkAction::make(),
DeleteBulkAction::make()
->after(function (Collection $records): void {
static::recalculateSpentTime(
$records->pluck('project_id')->all(),
$records->pluck('task_id')->all()
);
}),
]),
]);
}
@@ -132,6 +143,43 @@ class TimeEntryResource extends Resource
];
}
/**
* The client of a time entry is always the client of its project.
*/
public static function getClientIdForProject(mixed $projectId): ?string
{
if ($projectId === null || $projectId === '') {
return null;
}
/** @var Project|null $project */
$project = Project::query()->find($projectId);
return $project?->client_id;
}
/**
* Recalculate the stored spent time of the given projects and tasks.
*
* @param array<int, string|null> $projectIds
* @param array<int, string|null> $taskIds
*/
public static function recalculateSpentTime(array $projectIds, array $taskIds): void
{
$projectIds = array_values(array_unique(array_filter($projectIds)));
$taskIds = array_values(array_unique(array_filter($taskIds)));
if (count($projectIds) > 0) {
Project::query()->whereKey($projectIds)->each(function (Project $project): void {
RecalculateSpentTimeForProject::dispatch($project);
});
}
if (count($taskIds) > 0) {
Task::query()->whereKey($taskIds)->each(function (Task $task): void {
RecalculateSpentTimeForTask::dispatch($task);
});
}
}
public static function getPages(): array
{
return [

View File

@@ -6,6 +6,7 @@ namespace App\Filament\Resources\TimeEntryResource\Pages;
use App\Filament\Resources\TimeEntryResource;
use App\Models\Member;
use App\Models\TimeEntry;
use Filament\Resources\Pages\CreateRecord;
class CreateTimeEntry extends CreateRecord
@@ -26,7 +27,15 @@ class CreateTimeEntry extends CreateRecord
$data['organization_id'] = $member->organization_id;
}
}
$data['client_id'] = TimeEntryResource::getClientIdForProject($data['project_id'] ?? null);
return $data;
}
protected function afterCreate(): void
{
/** @var TimeEntry $timeEntry */
$timeEntry = $this->getRecord();
TimeEntryResource::recalculateSpentTime([$timeEntry->project_id], [$timeEntry->task_id]);
}
}

View File

@@ -6,6 +6,7 @@ namespace App\Filament\Resources\TimeEntryResource\Pages;
use App\Filament\Resources\TimeEntryResource;
use App\Models\Member;
use App\Models\TimeEntry;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
@@ -13,11 +14,18 @@ class EditTimeEntry extends EditRecord
{
protected static string $resource = TimeEntryResource::class;
private ?string $originalProjectId = null;
private ?string $originalTaskId = null;
protected function getHeaderActions(): array
{
return [
DeleteAction::make()
->icon('heroicon-m-trash'),
->icon('heroicon-m-trash')
->after(function (TimeEntry $record): void {
TimeEntryResource::recalculateSpentTime([$record->project_id], [$record->task_id]);
}),
];
}
@@ -35,7 +43,26 @@ class EditTimeEntry extends EditRecord
$data['organization_id'] = $member->organization_id;
}
}
$data['client_id'] = TimeEntryResource::getClientIdForProject($data['project_id'] ?? null);
return $data;
}
protected function beforeSave(): void
{
/** @var TimeEntry $timeEntry */
$timeEntry = $this->getRecord();
$this->originalProjectId = $timeEntry->project_id;
$this->originalTaskId = $timeEntry->task_id;
}
protected function afterSave(): void
{
/** @var TimeEntry $timeEntry */
$timeEntry = $this->getRecord();
TimeEntryResource::recalculateSpentTime(
[$this->originalProjectId, $timeEntry->project_id],
[$this->originalTaskId, $timeEntry->task_id]
);
}
}

View File

@@ -17,6 +17,7 @@ use App\Service\DeletionService;
use App\Service\TimezoneService;
use App\Service\UserService;
use Brick\Money\IsoCurrencyProvider;
use Closure;
use Exception;
use Filament\Actions\BulkAction;
use Filament\Actions\DeleteAction;
@@ -36,7 +37,7 @@ use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Korridor\LaravelModelValidationRules\Rules\UniqueEloquent;
use Illuminate\Support\Str;
use STS\FilamentImpersonate\Actions\Impersonate;
class UserResource extends Resource
@@ -71,12 +72,25 @@ class UserResource extends Resource
->label('Email')
->required()
->rules($record?->is_placeholder ? [] : [
UniqueEloquent::make(User::class, 'email')
->ignore($record?->getKey()),
// Compared lowercased, since that is how the email is stored (see dehydrateStateUsing).
// Wrapped, because Filament evaluates closures in rules() itself.
fn (): Closure => function (string $attribute, mixed $value, Closure $fail) use ($record): void {
$emailAlreadyInUse = is_string($value) && User::query()
->where('email', '=', Str::lower($value))
->where('is_placeholder', '=', false)
->when($record !== null, fn (Builder $query) => $query->whereKeyNot($record->getKey()))
->exists();
if ($emailAlreadyInUse) {
$fail(__('validation.unique', ['attribute' => $attribute]));
}
},
])
->rule([
'email:rfc,strict',
])
// Emails are stored lowercase, and login and invitations look them up lowercased.
->dehydrateStateUsing(fn (?string $state): ?string => $state !== null ? Str::lower($state) : null)
->maxLength(255),
Toggle::make('is_placeholder')
->label('Is Placeholder?')

View File

@@ -18,13 +18,13 @@ class CreateUser extends CreateRecord
{
$userService = app(UserService::class);
$user = $userService->createUser(
$data['name'],
$data['email'],
$data['password_create'],
$data['timezone'],
$data['week_start'] instanceof Weekday ? $data['week_start'] : Weekday::from($data['week_start']),
$data['currency'],
verifyEmail: (bool) $data['is_email_verified']
name: $data['name'],
email: $data['email'],
password: $data['password_create'],
timezone: $data['timezone'],
weekStart: $data['week_start'] instanceof Weekday ? $data['week_start'] : Weekday::from($data['week_start']),
currency: $data['currency'],
verifyEmail: (bool) $data['is_email_verified'],
);
return $user;

View File

@@ -4,8 +4,14 @@ declare(strict_types=1);
namespace App\Http\Controllers\Api\V1;
use App\Enums\ExportStatus;
use App\Exceptions\Api\ExportAlreadyInProgressApiException;
use App\Exceptions\Api\ExportFileNotAvailableApiException;
use App\Http\Requests\V1\Export\ExportIndexRequest;
use App\Http\Resources\V1\Export\ExportCollection;
use App\Http\Resources\V1\Export\ExportResource;
use App\Models\Export;
use App\Models\Organization;
use App\Service\Export\ExportException;
use App\Service\Export\ExportService;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\JsonResponse;
@@ -17,8 +23,11 @@ class ExportController extends Controller
/**
* Export data of an organization
*
* The export is processed in the background. Use the returned export ID to poll the status of the export and
* the download endpoint to get the download URL once the export is completed.
*
* @throws AuthorizationException
* @throws ExportException
* @throws ExportAlreadyInProgressApiException
*
* @operationId exportOrganization
*/
@@ -26,15 +35,85 @@ class ExportController extends Controller
{
$this->checkPermission($organization, 'export');
$filepath = $exportService->export($organization);
$export = $exportService->createOrganizationExport($organization, $this->user());
return (new ExportResource($export->refresh()))
->response()
->setStatusCode(202);
}
/**
* Get exports
*
* @throws AuthorizationException
*
* @operationId getExports
*/
public function index(Organization $organization, ExportIndexRequest $request): ExportCollection
{
$this->checkPermission($organization, 'export');
$exports = Export::query()
->whereBelongsTo($organization, 'organization')
->orderBy('created_at', 'desc')
->orderBy('id')
->paginate(config('app.pagination_per_page_default'));
return new ExportCollection($exports);
}
/**
* Get export
*
* @throws AuthorizationException
*
* @operationId getExport
*/
public function show(Organization $organization, Export $export): ExportResource
{
$this->checkPermission($organization, 'export');
$this->checkExportBelongsToOrganization($organization, $export);
return new ExportResource($export);
}
/**
* Get download URL of an export
*
* The download URL is only valid for a short time, request a new one for every download.
*
* @throws AuthorizationException
* @throws ExportFileNotAvailableApiException
*
* @operationId downloadExport
*/
public function download(Organization $organization, Export $export): JsonResponse
{
$this->checkPermission($organization, 'export');
$this->checkExportBelongsToOrganization($organization, $export);
if ($export->status !== ExportStatus::Completed || $export->file_path === null) {
throw new ExportFileNotAvailableApiException;
}
$downloadUrl = Storage::disk(config('filesystems.private'))
->temporaryUrl($filepath, Carbon::now()->addMinutes(10), [
'ResponseContentDisposition' => 'attachment; filename="'.basename($filepath).'"',
->temporaryUrl($export->file_path, Carbon::now()->addMinutes(10), [
'ResponseContentDisposition' => 'attachment; filename="'.$export->getDownloadFilename($this->user()->timezone).'"',
]);
return new JsonResponse([
'success' => true,
/** @var string $download_url Temporary download URL of the export file, valid for 10 minutes */
'download_url' => $downloadUrl,
], 200);
}
/**
* @throws AuthorizationException
*/
private function checkExportBelongsToOrganization(Organization $organization, Export $export): void
{
if ($export->organization_id !== $organization->getKey()) {
throw new AuthorizationException('Export does not belong to organization');
}
}
}

View File

@@ -4,7 +4,11 @@ declare(strict_types=1);
namespace App\Http\Controllers\Api\V1;
use App\Http\Requests\V1\Import\ImportIndexRequest;
use App\Http\Requests\V1\Import\ImportRequest;
use App\Http\Resources\V1\Import\ImportCollection;
use App\Http\Resources\V1\Import\ImportResource;
use App\Models\Import;
use App\Models\Organization;
use App\Service\Import\Importers\ImporterContract;
use App\Service\Import\Importers\ImporterProvider;
@@ -24,7 +28,7 @@ class ImportController extends Controller
*
* @response array{data: array<array{ key: string, name: string, description: string }>}
*/
public function index(Organization $organization, ImporterProvider $importerProvider): JsonResponse
public function importers(Organization $organization, ImporterProvider $importerProvider): JsonResponse
{
$this->checkPermission($organization, 'import');
@@ -51,11 +55,13 @@ class ImportController extends Controller
/**
* Import data into the organization
*
* The import is processed in the background. Use the returned import ID to poll the status of the import.
*
* @throws AuthorizationException
*
* @operationId importData
*/
public function import(Organization $organization, ImportRequest $request, ImportService $importService): JsonResponse
public function import(Organization $organization, ImportRequest $request, ImportService $importService): JsonResponse|ImportResource
{
$this->checkPermission($organization, 'import');
@@ -67,43 +73,59 @@ class ImportController extends Controller
], 400);
}
$timezone = $this->user()->timezone;
$report = $importService->import(
$user = $this->user();
$import = $importService->createFileImport(
$organization,
$user,
$request->input('type'),
$importData,
$timezone
$user->timezone
);
return new JsonResponse([
/** @var array{
* clients: array{
* created: int,
* },
* projects: array{
* created: int,
* },
* tasks: array{
* created: int,
* },
* time_entries: array{
* created: int,
* },
* tags: array{
* created: int,
* },
* users: array{
* created: int,
* }
* } $report Import report */
'report' => $report->toArray(),
], 200);
return (new ImportResource($import->refresh()))
->response()
->setStatusCode(202);
} catch (ImportException $exception) {
report($exception);
return new JsonResponse([
'message' => $exception->getMessage(),
], 400);
}
}
/**
* Get imports
*
* @throws AuthorizationException
*
* @operationId getImports
*/
public function index(Organization $organization, ImportIndexRequest $request): ImportCollection
{
$this->checkPermission($organization, 'import');
$imports = Import::query()
->whereBelongsTo($organization, 'organization')
->orderBy('created_at', 'desc')
->orderBy('id')
->paginate(config('app.pagination_per_page_default'));
return new ImportCollection($imports);
}
/**
* Get import
*
* @throws AuthorizationException
*
* @operationId getImport
*/
public function show(Organization $organization, Import $import): ImportResource
{
$this->checkPermission($organization, 'import');
if ($import->organization_id !== $organization->getKey()) {
throw new AuthorizationException('Import does not belong to organization');
}
return new ImportResource($import);
}
}

View File

@@ -31,6 +31,19 @@ class ReportController extends Controller
}
}
/**
* Public reports aggregate all time entries of the organization and are not scoped to the visibility of
* the user that created them, so only users that can see all projects and time entries may create or
* update (and thereby publish) reports.
*
* @throws AuthorizationException
*/
private function checkCanExposeOrganizationData(Organization $organization): void
{
$this->checkPermission($organization, 'projects:view:all');
$this->checkPermission($organization, 'time-entries:view:all');
}
/**
* Get reports
*
@@ -77,6 +90,7 @@ class ReportController extends Controller
public function store(Organization $organization, ReportStoreRequest $request, TimezoneService $timezoneService, ReportService $reportService): DetailedReportResource
{
$this->checkPermission($organization, 'reports:create');
$this->checkCanExposeOrganizationData($organization);
$user = $this->user();
$report = new Report;
@@ -136,6 +150,7 @@ class ReportController extends Controller
public function update(Organization $organization, Report $report, ReportUpdateRequest $request, ReportService $reportService): DetailedReportResource
{
$this->checkPermission($organization, 'reports:update', $report);
$this->checkCanExposeOrganizationData($organization);
if ($request->has('name')) {
$report->name = $request->getName();

View File

@@ -932,6 +932,7 @@ class TimeEntryController extends Controller
{
$this->checkAnyPermission($organization, ['time-entries:delete:all', 'time-entries:delete:own']);
$canDeleteAll = $this->hasPermission($organization, 'time-entries:delete:all');
$member = $canDeleteAll ? null : $this->member($organization);
$ids = $request->validated('ids');
$timeEntries = TimeEntry::query()
@@ -956,7 +957,7 @@ class TimeEntryController extends Controller
continue;
}
if (! $canDeleteAll && $timeEntry->member_id !== $this->member($organization)->getKey()) {
if ($member !== null && $timeEntry->member_id !== $member->getKey()) {
$error->push($id);
continue;

View File

@@ -13,6 +13,7 @@ use App\Http\Resources\V1\User\UserResource;
use App\Mail\VerifyUpdatedEmailMail;
use App\Models\Organization;
use App\Models\User;
use App\Service\AuthenticationContract;
use App\Service\DeletionService;
use App\Service\UserService;
use App\Support\Base64File;
@@ -21,6 +22,7 @@ use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class UserController extends Controller
{
@@ -167,8 +169,9 @@ class UserController extends Controller
*
* @throws AuthorizationException Thrown when the authenticated user does not match the user whose email is pending verification.
* @throws UserResendEmailVerificationNoPendingEmailApiException Thrown when the user does not have a pending email to verify.
* @throws ValidationException Thrown when the user's email is locked, e.g. managed by their organization's identity provider.
*/
public function resendEmailVerification(User $user): JsonResponse
public function resendEmailVerification(User $user, AuthenticationContract $authentication): JsonResponse
{
if ($user->getKey() !== $this->user()->getKey()) {
throw new AuthorizationException;
@@ -178,6 +181,11 @@ class UserController extends Controller
throw new UserResendEmailVerificationNoPendingEmailApiException;
}
// A change requested before the email was locked can no longer be confirmed.
if (! $authentication->canChangeEmail($user)) {
throw ValidationException::withMessages(['email' => AuthenticationContract::EMAIL_CHANGE_LOCKED_MESSAGE]);
}
Mail::to($user->pending_email)
->queue(new VerifyUpdatedEmailMail($user, $user->pending_email));

View File

@@ -29,6 +29,8 @@ class UserMembershipController extends Controller
$members = Member::query()
->whereBelongsTo($user, 'user')
->with(['organization'])
->orderBy('created_at')
->orderBy('id')
->get();
return new PersonalMembershipCollection($members);

View File

@@ -7,6 +7,7 @@ namespace App\Http\Controllers;
use App\Models\Member;
use App\Models\Organization;
use App\Models\User;
use App\Service\PermissionStore;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
@@ -40,8 +41,7 @@ class Controller extends BaseController
protected function member(Organization $organization): Member
{
$user = $this->user();
/** @var Member|null $member */
$member = Member::query()->whereBelongsTo($organization, 'organization')->whereBelongsTo($user, 'user')->first();
$member = app(PermissionStore::class)->getMember($organization, $user);
if ($member === null) {
Log::error('This function should only be called in authenticated context after checking the user is a member of the organization', [
'user' => $user->getKey(),

View File

@@ -10,13 +10,14 @@ use App\Models\User;
use App\Service\MemberService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use RuntimeException;
class OrganizationInvitationController extends Controller
{
public function accept(OrganizationInvitation $invitation, MemberService $memberService): RedirectResponse
{
$email = strtolower($invitation->email);
$email = Str::lower($invitation->email);
$role = Role::tryFrom($invitation->role);
if ($role === null || $role === Role::Owner || $role === Role::Placeholder) {
throw new RuntimeException('Invalid role');

View File

@@ -4,6 +4,8 @@ declare(strict_types=1);
namespace App\Http\Controllers\Web;
use App\Models\User;
use App\Service\IdentityConfirmationService;
use Illuminate\Contracts\Auth\StatefulGuard;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
@@ -17,8 +19,27 @@ class OtherBrowserSessionsController extends Controller
/**
* Log the user out of their other browser sessions across all devices.
*/
public function destroy(Request $request, StatefulGuard $guard): RedirectResponse
public function destroy(Request $request, StatefulGuard $guard, IdentityConfirmationService $identityConfirmationService): RedirectResponse
{
/** @var User $user */
$user = $request->user();
// Users who can't confirm with a password (e.g. SSO) may log out other sessions without confirming.
// Someone with a stolen session could only end the user's other sessions, while asking for a
// confirmation would keep the user from ending the stolen one.
if (! $identityConfirmationService->confirmsWithPassword($user)) {
// Without a password to rehash, other sessions can only be removed from the database
if (config('session.driver') !== 'database') {
throw ValidationException::withMessages([
'password' => __('Signing out other sessions is unavailable on this instance. Contact your administrator.'),
]);
}
$this->deleteOtherSessionRecords($request);
return back(303);
}
$password = (string) $request->string('password');
$confirmed = app(ConfirmPassword::class)($guard, $request->user(), $password);

View File

@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace App\Http\Controllers\Web;
use App\Models\User;
use App\Service\AuthenticationContract;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
@@ -12,7 +13,7 @@ use Illuminate\Support\Str;
class UserController extends Controller
{
public function verifyEmailChange(Request $request, User $user): RedirectResponse
public function verifyEmailChange(Request $request, User $user, AuthenticationContract $authentication): RedirectResponse
{
if ($request->user()?->getAuthIdentifier() !== $user->getKey()) {
abort(403);
@@ -29,6 +30,16 @@ class UserController extends Controller
abort(403);
}
// A change requested before the email was locked can no longer be confirmed.
if (! $authentication->canChangeEmail($user)) {
$user->pending_email = null;
$user->save();
return redirect(route('dashboard'))
->with('bannerStyle', 'danger')
->with('bannerText', AuthenticationContract::EMAIL_CHANGE_LOCKED_MESSAGE);
}
$emailAlreadyInUse = User::query()
->where('email', '=', $email)
->where('is_placeholder', '=', false)

View File

@@ -6,6 +6,7 @@ namespace App\Http;
use App\Http\Middleware\Authenticate;
use App\Http\Middleware\CheckOrganizationBlocked;
use App\Http\Middleware\CheckOrganizationMember;
use App\Http\Middleware\EncryptCookies;
use App\Http\Middleware\EnsureEmailIsVerified;
use App\Http\Middleware\ForceHttps;
@@ -106,5 +107,6 @@ class Kernel extends HttpKernel
'throttle' => ThrottleRequests::class,
'verified' => EnsureEmailIsVerified::class,
'check-organization-blocked' => CheckOrganizationBlocked::class,
'check-organization-member' => CheckOrganizationMember::class,
];
}

View File

@@ -5,7 +5,6 @@ declare(strict_types=1);
namespace App\Http\Middleware;
use Filament\Http\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;
class AuthenticateFilamentPanel extends Middleware
{

View File

@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use App\Models\Organization;
use App\Service\PermissionStore;
use Closure;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\Request;
use LogicException;
use Symfony\Component\HttpFoundation\Response;
/**
* Rejects requests to organization routes when the authenticated user is not a member of the organization.
* Routes without an organization parameter are passed through.
*/
class CheckOrganizationMember
{
public function __construct(private readonly PermissionStore $permissionStore) {}
/**
* @param Closure(Request): (Response) $next
*
* @throws AuthorizationException
*/
public function handle(Request $request, Closure $next): Response
{
$organization = $request->route('organization');
if ($organization === null) {
return $next($request);
}
if (! ($organization instanceof Organization)) {
throw new LogicException('The organization must be loaded before this middleware.');
}
if (! $this->permissionStore->isMember($organization)) {
throw new AuthorizationException;
}
return $next($request);
}
}

View File

@@ -8,6 +8,7 @@ use App\Service\BillingContract;
use Illuminate\Http\Request;
use Inertia\Middleware;
use Nwidart\Modules\Facades\Module;
use STS\FilamentImpersonate\ImpersonateManager;
class HandleInertiaRequests extends Middleware
{
@@ -62,6 +63,7 @@ class HandleInertiaRequests extends Middleware
'goal_limit' => $billing->getGoalLimit($currentOrganization),
'can_use_billable_rates' => $billing->canUseBillableRates($currentOrganization),
] : null,
'is_impersonating' => app(ImpersonateManager::class)->isImpersonating(),
'flash' => [
'message' => fn () => $request->session()->get('message'),
'bannerText' => fn () => $request->session()->get('bannerText'),

View File

@@ -4,7 +4,14 @@ declare(strict_types=1);
namespace App\Http\Requests\V1;
use App\Models\Organization;
use App\Models\Task;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Str;
use Illuminate\Validation\ConditionalRules;
use Illuminate\Validation\Rule;
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
class BaseFormRequest extends FormRequest
{
@@ -25,4 +32,27 @@ class BaseFormRequest extends FormRequest
return $rules;
}
/**
* Validates that the task belongs to the project given in the input field $projectKey.
* The check is skipped if the project ID is not a valid UUID, since the project ID rule already reports that error
* and the query would otherwise fail in the database.
*/
protected function taskBelongsToProjectRule(?Organization $organization, string $projectKey): ConditionalRules
{
if ($organization === null) {
// The rules are also evaluated without a bound route (e.g. during API docs generation), so there is no organization yet
return Rule::when(false, []);
}
$projectId = $this->input($projectKey);
return Rule::when($projectId === null || Str::isUuid($projectId), [
ExistsEloquent::make(Task::class, null, function (Builder $builder) use ($organization, $projectId): Builder {
/** @var Builder<Task> $builder */
return $builder->whereBelongsTo($organization, 'organization')
->where('project_id', $projectId);
})->uuid()->withMessage(__('validation.task_belongs_to_project')),
]);
}
}

View File

@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\V1\Concerns;
use App\Models\User;
use App\Service\IdentityConfirmationService;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Validator;
/**
* Requires the user's "password". Users who can't confirm with a password can't do the action themselves.
*/
trait ConfirmsIdentity
{
/**
* @return array<string, array<string>>
*/
protected function identityConfirmationRules(): array
{
$user = $this->user();
$requiresPassword = ! $user instanceof User
|| app(IdentityConfirmationService::class)->confirmsWithPassword($user);
return [
'password' => [
$requiresPassword ? 'required' : 'nullable',
'string',
],
];
}
protected function validateIdentityConfirmation(Validator $validator): void
{
if ($validator->errors()->has('password')) {
return;
}
$user = $this->user();
if (! $user instanceof User) {
$validator->errors()->add('password', __('The password is incorrect.'));
return;
}
if (! app(IdentityConfirmationService::class)->confirmsWithPassword($user)) {
$validator->errors()->add('password', __('Your account has no password to confirm this with. Contact your administrator.'));
return;
}
$password = $this->input('password');
if (! is_string($password) || ! Hash::check($password, (string) $user->password)) {
$validator->errors()->add('password', __('The password is incorrect.'));
}
}
}

View File

@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\V1\Export;
use App\Http\Requests\V1\BaseFormRequest;
use Illuminate\Contracts\Validation\ValidationRule;
class ExportIndexRequest extends BaseFormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array<string, array<string|ValidationRule>>
*/
public function rules(): array
{
return [
'page' => [
'integer',
'min:1',
'max:2147483647',
],
];
}
}

View File

@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\V1\Import;
use App\Http\Requests\V1\BaseFormRequest;
use Illuminate\Contracts\Validation\ValidationRule;
class ImportIndexRequest extends BaseFormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array<string, array<string|ValidationRule>>
*/
public function rules(): array
{
return [
'page' => [
'integer',
'min:1',
'max:2147483647',
],
];
}
}

View File

@@ -5,11 +5,13 @@ declare(strict_types=1);
namespace App\Http\Requests\V1\Organization;
use App\Http\Requests\V1\BaseFormRequest;
use Illuminate\Support\Facades\Hash;
use App\Http\Requests\V1\Concerns\ConfirmsIdentity;
use Illuminate\Validation\Validator;
class OrganizationDestroyRequest extends BaseFormRequest
{
use ConfirmsIdentity;
/**
* Get the validation rules that apply to the request.
*
@@ -17,12 +19,7 @@ class OrganizationDestroyRequest extends BaseFormRequest
*/
public function rules(): array
{
return [
'password' => [
'required',
'string',
],
];
return $this->identityConfirmationRules();
}
/**
@@ -31,18 +28,7 @@ class OrganizationDestroyRequest extends BaseFormRequest
public function after(): array
{
return [
function (Validator $validator): void {
if ($validator->errors()->has('password')) {
return;
}
$user = $this->user();
$password = $this->input('password');
if (! is_string($password) || $user === null || ! Hash::check($password, (string) $user->password)) {
$validator->errors()->add('password', __('The password is incorrect.'));
}
},
fn (Validator $validator) => $this->validateIdentityConfirmation($validator),
];
}
}

View File

@@ -10,6 +10,9 @@ use App\Models\Project;
use App\Models\Task;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Str;
use Illuminate\Validation\ConditionalRules;
use Illuminate\Validation\Rule;
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
use Korridor\LaravelModelValidationRules\Rules\UniqueEloquent;
@@ -21,7 +24,7 @@ class TaskStoreRequest extends BaseFormRequest
/**
* Get the validation rules that apply to the request.
*
* @return array<string, array<string|ValidationRule>>
* @return array<string, array<string|ValidationRule|ConditionalRules>>
*/
public function rules(): array
{
@@ -31,10 +34,12 @@ class TaskStoreRequest extends BaseFormRequest
'string',
'min:1',
'max:255',
UniqueEloquent::make(Task::class, 'name', function (Builder $builder): Builder {
/** @var Builder<Task> $builder */
return $builder->where('project_id', '=', $this->input('project_id'));
})->withCustomTranslation('validation.task_name_already_exists'),
Rule::when(Str::isUuid($this->input('project_id')), [
UniqueEloquent::make(Task::class, 'name', function (Builder $builder): Builder {
/** @var Builder<Task> $builder */
return $builder->where('project_id', '=', $this->input('project_id'));
})->withCustomTranslation('validation.task_name_already_exists'),
]),
],
'project_id' => [
'required',

View File

@@ -16,6 +16,7 @@ use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ConditionalRules;
use Illuminate\Validation\Rule;
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
@@ -27,7 +28,7 @@ class TimeEntryStoreRequest extends BaseFormRequest
/**
* Get the validation rules that apply to the request.
*
* @return array<string, array<string|Closure|ValidationRule|\Illuminate\Contracts\Validation\Rule>>
* @return array<string, array<string|Closure|ValidationRule|\Illuminate\Contracts\Validation\Rule|ConditionalRules>>
*/
public function rules(): array
{
@@ -69,11 +70,7 @@ class TimeEntryStoreRequest extends BaseFormRequest
/** @var Builder<Task> $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid(),
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
/** @var Builder<Task> $builder */
return $builder->whereBelongsTo($this->organization, 'organization')
->where('project_id', $this->input('project_id'));
})->uuid()->withMessage(__('validation.task_belongs_to_project')),
$this->taskBelongsToProjectRule($this->organization, 'project_id'),
],
// Start of time entry (Format: "Y-m-d\TH:i:s\Z", UTC timezone, Example: "2000-02-22T14:58:59Z")
'start' => [

View File

@@ -15,6 +15,7 @@ use App\Service\PermissionStore;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ConditionalRules;
use Illuminate\Validation\Rule;
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
@@ -26,7 +27,7 @@ class TimeEntryUpdateMultipleRequest extends BaseFormRequest
/**
* Get the validation rules that apply to the request.
*
* @return array<string, array<string|ValidationRule|\Illuminate\Contracts\Validation\Rule>>
* @return array<string, array<string|ValidationRule|\Illuminate\Contracts\Validation\Rule|ConditionalRules>>
*/
public function rules(): array
{
@@ -55,7 +56,7 @@ class TimeEntryUpdateMultipleRequest extends BaseFormRequest
'changes.project_id' => [
'nullable',
'string',
'required_with:task_id',
'required_with:changes.task_id',
'prohibited_if:changes.type,break',
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
/** @var Builder<Project> $builder */
@@ -80,11 +81,7 @@ class TimeEntryUpdateMultipleRequest extends BaseFormRequest
/** @var Builder<Task> $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid(),
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
/** @var Builder<Task> $builder */
return $builder->whereBelongsTo($this->organization, 'organization')
->where('project_id', $this->input('changes.project_id'));
})->uuid()->withMessage(__('validation.task_belongs_to_project')),
$this->taskBelongsToProjectRule($this->organization, 'changes.project_id'),
],
// Whether time entry is billable
'changes.billable' => [

View File

@@ -83,11 +83,7 @@ class TimeEntryUpdateRequest extends BaseFormRequest
/** @var Builder<Task> $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid(),
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
/** @var Builder<Task> $builder */
return $builder->whereBelongsTo($this->organization, 'organization')
->where('project_id', $this->input('project_id'));
})->uuid()->withMessage(__('validation.task_belongs_to_project')),
$this->taskBelongsToProjectRule($this->organization, 'project_id'),
],
// Start of time entry (Format: "Y-m-d\TH:i:s\Z", UTC timezone, Example: "2000-02-22T14:58:59Z")
'start' => [

View File

@@ -5,11 +5,13 @@ declare(strict_types=1);
namespace App\Http\Requests\V1\User;
use App\Http\Requests\V1\BaseFormRequest;
use Illuminate\Support\Facades\Hash;
use App\Http\Requests\V1\Concerns\ConfirmsIdentity;
use Illuminate\Validation\Validator;
class UserDestroyRequest extends BaseFormRequest
{
use ConfirmsIdentity;
/**
* Get the validation rules that apply to the request.
*
@@ -17,12 +19,7 @@ class UserDestroyRequest extends BaseFormRequest
*/
public function rules(): array
{
return [
'password' => [
'required',
'string',
],
];
return $this->identityConfirmationRules();
}
/**
@@ -31,18 +28,7 @@ class UserDestroyRequest extends BaseFormRequest
public function after(): array
{
return [
function (Validator $validator): void {
if ($validator->errors()->has('password')) {
return;
}
$user = $this->user();
$password = $this->input('password');
if (! is_string($password) || $user === null || ! Hash::check($password, (string) $user->password)) {
$validator->errors()->add('password', __('The password is incorrect.'));
}
},
fn (Validator $validator) => $this->validateIdentityConfirmation($validator),
];
}
}

View File

@@ -8,6 +8,8 @@ use App\Enums\Weekday;
use App\Http\Requests\V1\BaseFormRequest;
use App\Models\User;
use App\Rules\Base64ImageRule;
use App\Service\AuthenticationContract;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Str;
@@ -31,7 +33,7 @@ class UserUpdateRequest extends BaseFormRequest
/**
* Get the validation rules that apply to the request.
*
* @return array<string, array<string|\Illuminate\Contracts\Validation\Rule|ValidationRule>>
* @return array<string, array<string|\Illuminate\Contracts\Validation\Rule|ValidationRule|Closure>>
*/
public function rules(): array
{
@@ -48,6 +50,16 @@ class UserUpdateRequest extends BaseFormRequest
return $query->where('is_placeholder', '=', false)
->whereKeyNot($this->user->getKey());
}),
function (string $attribute, mixed $value, Closure $fail): void {
// Sending the current address back unchanged is not a change.
if (! is_string($value) || $value === Str::lower($this->user->email)) {
return;
}
if (! app(AuthenticationContract::class)->canChangeEmail($this->user)) {
$fail(AuthenticationContract::EMAIL_CHANGE_LOCKED_MESSAGE);
}
},
],
'photo' => [
'nullable',

View File

@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace App\Http\Resources\V1\Export;
use Illuminate\Http\Resources\Json\ResourceCollection;
class ExportCollection extends ResourceCollection
{
/**
* The resource that this resource collects.
*
* @var string
*/
public $collects = ExportResource::class;
}

View File

@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace App\Http\Resources\V1\Export;
use App\Enums\ExportStatus;
use App\Http\Resources\V1\BaseResource;
use App\Models\Export;
use Illuminate\Http\Request;
/**
* @property Export $resource
*/
class ExportResource extends BaseResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
/** ID of the export */
'id' => $this->resource->id,
/** Type of the export */
'type' => $this->resource->type,
/** Status of the export */
'status' => $this->resource->status,
/** @var bool $download_available Whether the export file can be downloaded, the file is deleted after the retention period */
'download_available' => $this->resource->status === ExportStatus::Completed && $this->resource->file_path !== null,
/** Error message, only set if the export failed */
'error_message' => $this->resource->error_message,
/** ID of the user that started the export */
'user_id' => $this->resource->user_id,
/** @var string|null $started_at Date when the export was started */
'started_at' => $this->formatDateTime($this->resource->started_at),
/** @var string|null $finished_at Date when the export was finished */
'finished_at' => $this->formatDateTime($this->resource->finished_at),
/** @var string|null $created_at Date when the export was created */
'created_at' => $this->formatDateTime($this->resource->created_at),
];
}
}

View File

@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace App\Http\Resources\V1\Import;
use Illuminate\Http\Resources\Json\ResourceCollection;
class ImportCollection extends ResourceCollection
{
/**
* The resource that this resource collects.
*
* @var string
*/
public $collects = ImportResource::class;
}

View File

@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace App\Http\Resources\V1\Import;
use App\Http\Resources\V1\BaseResource;
use App\Models\Import;
use Illuminate\Http\Request;
/**
* @property Import $resource
*/
class ImportResource extends BaseResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
/** ID of the import */
'id' => $this->resource->id,
/** Importer key, see the importers endpoint */
'type' => $this->resource->type,
/** Source of the import data */
'source' => $this->resource->source,
/** Status of the import */
'status' => $this->resource->status,
/** @var array{
* clients: array{
* created: int,
* },
* projects: array{
* created: int,
* },
* tasks: array{
* created: int,
* },
* time_entries: array{
* created: int,
* skipped: int,
* },
* tags: array{
* created: int,
* },
* users: array{
* created: int,
* }
* }|null $report Import report, only set if the import is completed */
'report' => $this->resource->report,
/** Error message, only set if the import failed */
'error_message' => $this->resource->error_message,
/** ID of the user that started the import */
'user_id' => $this->resource->user_id,
/** @var string|null $started_at Date when the import was started */
'started_at' => $this->formatDateTime($this->resource->started_at),
/** @var string|null $finished_at Date when the import was finished */
'finished_at' => $this->formatDateTime($this->resource->finished_at),
/** @var string|null $created_at Date when the import was created */
'created_at' => $this->formatDateTime($this->resource->created_at),
];
}
}

View File

@@ -7,6 +7,8 @@ namespace App\Http\Resources\V1\User;
use App\Enums\Weekday;
use App\Http\Resources\V1\BaseResource;
use App\Models\User;
use App\Service\AuthenticationContract;
use App\Service\IdentityConfirmationService;
use Illuminate\Http\Request;
/**
@@ -38,6 +40,10 @@ class UserResource extends BaseResource
'week_start' => $this->resource->week_start->value,
/** Whether to email the user when a time entry has been running for more than 8 hours */
'send_time_entry_still_running_email' => $this->resource->send_time_entry_still_running_email,
/** Whether the user confirms sensitive actions (like deleting their account) with their password. If not, an administrator has to do these actions for them. */
'confirms_with_password' => app(IdentityConfirmationService::class)->confirmsWithPassword($this->resource),
/** Whether the user may change their email address. If not, it is managed elsewhere (e.g. by the organization's identity provider). */
'can_change_email' => app(AuthenticationContract::class)->canChangeEmail($this->resource),
];
}
}

View File

@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Throwable;
class HeartbeatQueueJob implements ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
/**
* A heartbeat is not retried, since a retried heartbeat would be stale.
*/
public int $tries = 1;
/**
* @param int $dispatchedAtMs Unix timestamp in milliseconds of when the job was dispatched
*/
public function __construct(
public readonly int $dispatchedAtMs
) {}
/**
* Execute the job.
*/
public function handle(): void
{
$queueUrl = config('heartbeat.queue_url');
if (! is_string($queueUrl) || $queueUrl === '') {
return;
}
$latencyMs = max(0, Carbon::now()->getTimestampMs() - $this->dispatchedAtMs);
$url = str_replace('{latency_ms}', (string) $latencyMs, $queueUrl);
try {
Http::timeout((int) config('heartbeat.timeout'))
->connectTimeout(2)
->get($url)
->throw();
} catch (Throwable $exception) {
Log::warning('Failed to send queue heartbeat', [
'exception' => $exception->getMessage(),
]);
}
}
}

View File

@@ -0,0 +1,78 @@
<?php
declare(strict_types=1);
namespace App\Jobs;
use App\Models\Export;
use App\Service\Export\ExportService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\MaxAttemptsExceededException;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\TimeoutExceededException;
use Throwable;
class ProcessExport implements ShouldDispatchAfterCommit, ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/**
* Delete the job if its models no longer exist.
*/
public bool $deleteWhenMissingModels = true;
/**
* Exports are not retried, the user can start a new export.
*/
public int $tries = 1;
public int $timeout;
public Export $export;
/**
* Create a new job instance.
*/
public function __construct(Export $export)
{
$this->export = $export;
$this->timeout = (int) config('export.job_timeout');
$this->onQueue(config('export.queue'));
}
/**
* Execute the job.
*/
public function handle(ExportService $exportService): void
{
$exportService->process($this->export);
}
/**
* Handle a job failure.
*/
public function failed(?Throwable $exception): void
{
// A MaxAttemptsExceededException (that is not a timeout) is thrown if the export runs longer than the
// "retry_after" of the queue connection and the queue hands out the job a second time, while the first
// attempt is still running. The export must not be marked as failed in this case.
// The export:prune command marks the export as failed if it is really stale.
// Note: Unlike imports, exports do not run in a database transaction, so a timed out export can be marked
// as failed here.
if ($exception instanceof MaxAttemptsExceededException && ! $exception instanceof TimeoutExceededException) {
return;
}
$this->export->refresh();
if ($this->export->status->isActive()) {
app(ExportService::class)->markAsFailed($this->export, 'Export could not be finished');
}
}
}

View File

@@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
namespace App\Jobs;
use App\Models\Import;
use App\Service\Import\ImportService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\MaxAttemptsExceededException;
use Illuminate\Queue\SerializesModels;
use Throwable;
class ProcessImport implements ShouldDispatchAfterCommit, ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/**
* Delete the job if its models no longer exist.
*/
public bool $deleteWhenMissingModels = true;
/**
* Imports are not retried, since a failed import is rolled back and the user has to fix the import data.
*/
public int $tries = 1;
public int $timeout;
public Import $import;
/**
* Create a new job instance.
*/
public function __construct(Import $import)
{
$this->import = $import;
$this->timeout = (int) config('import.job_timeout');
$this->onQueue(config('import.queue'));
}
/**
* Execute the job.
*/
public function handle(ImportService $importService): void
{
$importService->process($this->import);
}
/**
* Handle a job failure.
*/
public function failed(?Throwable $exception): void
{
// A MaxAttemptsExceededException is thrown in two cases where the import must not be marked as failed here:
// - The import runs longer than the "retry_after" of the queue connection and the queue hands out the job
// a second time, while the first attempt is still running.
// - The import timed out (TimeoutExceededException). The timeout handler runs while the import transaction
// is still open, so the change would be rolled back when the worker is killed.
// In both cases the import:prune command marks the import as failed if it is really stale.
if ($exception instanceof MaxAttemptsExceededException) {
return;
}
$this->import->refresh();
if ($this->import->status->isActive()) {
app(ImportService::class)->markAsFailed($this->import, 'Import could not be finished');
}
}
}

145
app/Models/Export.php Normal file
View File

@@ -0,0 +1,145 @@
<?php
declare(strict_types=1);
namespace App\Models;
use App\Enums\ExportStatus;
use App\Enums\ExportType;
use App\Models\Concerns\HasUuids;
use Database\Factories\ExportFactory;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
/**
* @property string $id
* @property ExportType $type
* @property ExportStatus $status
* @property string|null $file_path
* @property string|null $error_message
* @property string|null $error_details
* @property Carbon|null $started_at
* @property Carbon|null $finished_at
* @property string $organization_id
* @property string|null $user_id
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property-read Organization $organization
* @property-read User|null $user
*
* @method static ExportFactory factory()
*/
class Export extends Model
{
/** @use HasFactory<ExportFactory> */
use HasFactory;
use HasUuids;
/**
* Time in seconds a running export can exceed the job timeout before it is considered stale.
*/
private const int RUNNING_STALE_BUFFER_SECONDS = 300;
/**
* Time in seconds a pending export can exceed the job timeout before it is considered stale.
*/
private const int PENDING_STALE_BUFFER_SECONDS = 3600;
private const int DOWNLOAD_FILENAME_SLUG_MAX_LENGTH = 40;
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'type' => ExportType::class,
'status' => ExportStatus::class,
'started_at' => 'datetime',
'finished_at' => 'datetime',
];
/**
* The attributes that should be hidden for serialization.
*
* @var list<string>
*/
protected $hidden = [
'error_details',
];
/**
* @return BelongsTo<Organization, $this>
*/
public function organization(): BelongsTo
{
return $this->belongsTo(Organization::class, 'organization_id');
}
/**
* The user that started the export, null if the user was deleted.
*
* @return BelongsTo<User, $this>
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id');
}
/**
* Filename that is used when the export file is downloaded, for example
* "solidtime-export_acme-gmbh_2026-11-18_10-20_1f2470b2.zip".
* The short export ID makes the filename unique, even for exports of organizations with the same name.
*
* @param string $timezone Timezone of the date in the filename
*/
public function getDownloadFilename(string $timezone): string
{
$organizationSlug = Str::limit(Str::slug($this->organization->name), self::DOWNLOAD_FILENAME_SLUG_MAX_LENGTH, '');
$organizationSlug = trim($organizationSlug, '-');
if ($organizationSlug === '') {
$organizationSlug = 'organization';
}
$createdAt = ($this->created_at ?? Carbon::now())->copy()->setTimezone($timezone);
return 'solidtime-export_'.$organizationSlug.'_'.$createdAt->format('Y-m-d_H-i').'_'.Str::substr($this->getKey(), 0, 8).'.zip';
}
/**
* @param Builder<Export> $builder
* @return Builder<Export>
*/
public function scopeActive(Builder $builder): Builder
{
return $builder->whereIn('status', ExportStatus::active());
}
/**
* Active exports that are not finished in time, for example because the worker crashed or the job timed out.
* The buffers cover small delays after the job timeout (running) and the time the job waits in the queue (pending).
*
* @param Builder<Export> $builder
* @return Builder<Export>
*/
public function scopeStale(Builder $builder): Builder
{
$jobTimeout = (int) config('export.job_timeout');
$runningStaleBefore = Carbon::now()->subSeconds($jobTimeout + self::RUNNING_STALE_BUFFER_SECONDS);
$pendingStaleBefore = Carbon::now()->subSeconds($jobTimeout + self::PENDING_STALE_BUFFER_SECONDS);
return $builder->where(function (Builder $query) use ($runningStaleBefore, $pendingStaleBefore): void {
$query->where(function (Builder $query) use ($runningStaleBefore): void {
$query->where('status', ExportStatus::Running)
->where('started_at', '<', $runningStaleBefore);
})->orWhere(function (Builder $query) use ($pendingStaleBefore): void {
$query->where('status', ExportStatus::Pending)
->where('created_at', '<', $pendingStaleBefore);
});
});
}
}

136
app/Models/Import.php Normal file
View File

@@ -0,0 +1,136 @@
<?php
declare(strict_types=1);
namespace App\Models;
use App\Enums\ImportSource;
use App\Enums\ImportStatus;
use App\Models\Concerns\HasUuids;
use Database\Factories\ImportFactory;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Carbon;
/**
* @property string $id
* @property string $type
* @property ImportSource $source
* @property ImportStatus $status
* @property string $timezone
* @property string|null $file_path
* @property array<string, mixed>|null $credentials
* @property array<string, mixed>|null $options
* @property bool $ignore_limits
* @property array<string, mixed>|null $report
* @property string|null $error_message
* @property string|null $error_details
* @property Carbon|null $started_at
* @property Carbon|null $finished_at
* @property string $organization_id
* @property string|null $user_id
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property-read Organization $organization
* @property-read User|null $user
*
* @method static ImportFactory factory()
*/
class Import extends Model
{
/** @use HasFactory<ImportFactory> */
use HasFactory;
use HasUuids;
/**
* Time in seconds a running import can exceed the job timeout before it is considered stale.
* Note: The job itself can not mark a timed out import as failed, since the timeout handler runs while the
* import transaction is still open and the change is rolled back when the worker is killed.
*/
private const int RUNNING_STALE_BUFFER_SECONDS = 300;
/**
* Time in seconds a pending import can exceed the job timeout before it is considered stale.
*/
private const int PENDING_STALE_BUFFER_SECONDS = 3600;
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'source' => ImportSource::class,
'status' => ImportStatus::class,
'credentials' => 'encrypted:array',
'options' => 'array',
'ignore_limits' => 'bool',
'report' => 'array',
'started_at' => 'datetime',
'finished_at' => 'datetime',
];
/**
* The attributes that should be hidden for serialization.
*
* @var list<string>
*/
protected $hidden = [
'credentials',
'error_details',
];
/**
* @return BelongsTo<Organization, $this>
*/
public function organization(): BelongsTo
{
return $this->belongsTo(Organization::class, 'organization_id');
}
/**
* The user that started the import, null if the user was deleted.
*
* @return BelongsTo<User, $this>
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id');
}
/**
* @param Builder<Import> $builder
* @return Builder<Import>
*/
public function scopeActive(Builder $builder): Builder
{
return $builder->whereIn('status', ImportStatus::active());
}
/**
* Active imports that are not finished in time, for example because the worker crashed or the job timed out.
* The buffers cover small delays after the job timeout (running) and the time the job waits in the queue (pending).
*
* @param Builder<Import> $builder
* @return Builder<Import>
*/
public function scopeStale(Builder $builder): Builder
{
$jobTimeout = (int) config('import.job_timeout');
$runningStaleBefore = Carbon::now()->subSeconds($jobTimeout + self::RUNNING_STALE_BUFFER_SECONDS);
$pendingStaleBefore = Carbon::now()->subSeconds($jobTimeout + self::PENDING_STALE_BUFFER_SECONDS);
return $builder->where(function (Builder $query) use ($runningStaleBefore, $pendingStaleBefore): void {
$query->where(function (Builder $query) use ($runningStaleBefore): void {
$query->where('status', ImportStatus::Running)
->where('started_at', '<', $runningStaleBefore);
})->orWhere(function (Builder $query) use ($pendingStaleBefore): void {
$query->where('status', ImportStatus::Pending)
->where('created_at', '<', $pendingStaleBefore);
});
});
}
}

View File

@@ -40,6 +40,8 @@ use OwenIt\Auditing\Contracts\Auditable as AuditableContract;
* @property Collection<int, User> $users
* @property Collection<int, User> $realUsers
* @property-read Collection<int, OrganizationInvitation> $organizationInvitations
* @property-read Collection<int, Import> $imports
* @property-read Collection<int, Export> $exports
* @property Member $membership
* @property NumberFormat $number_format
* @property CurrencyFormat $currency_format
@@ -158,6 +160,22 @@ class Organization extends Model implements AuditableContract
return $this->hasMany(OrganizationInvitation::class, 'organization_id');
}
/**
* @return HasMany<Import, $this>
*/
public function imports(): HasMany
{
return $this->hasMany(Import::class, 'organization_id');
}
/**
* @return HasMany<Export, $this>
*/
public function exports(): HasMany
{
return $this->hasMany(Export::class, 'organization_id');
}
/**
* Find a model by its primary key or throw an exception.
*

View File

@@ -140,6 +140,10 @@ class TimeEntry extends Model implements AuditableContract
$timeEntry->client_id = null;
$timeEntry->tags = [];
}
// The client of a time entry is always the client of its project.
if ($timeEntry->project_id === null) {
$timeEntry->client_id = null;
}
});
}

View File

@@ -9,9 +9,11 @@ use App\Enums\Weekday;
use App\Models\Concerns\CustomAuditable;
use App\Models\Concerns\HasUuids;
use App\Models\Passport\Token;
use App\Service\AuthenticationContract;
use Database\Factories\UserFactory;
use Filament\Models\Contracts\FilamentUser;
use Filament\Panel;
use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
@@ -24,6 +26,7 @@ use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Passport\AuthCode;
use Laravel\Passport\Contracts\OAuthenticatable;
@@ -160,13 +163,36 @@ class User extends Authenticatable implements AuditableContract, FilamentUser, M
return 'https://ui-avatars.com/api/?name='.urlencode($name).'&color=7F9CF5&background=EBF4FF';
}
public function canAccessPanel(Panel $panel): bool
public function isSuperAdmin(): bool
{
return $this->is_placeholder === false
&& in_array($this->email, config('auth.super_admins', []), true)
&& in_array(Str::lower($this->email), config()->array('auth.super_admins'), true)
&& $this->hasVerifiedEmail();
}
/**
* Sends the reset link, unless the user may not use a password. The unsent token stays, so Fortify throttles
* them like everyone else and doesn't reveal SSO-only accounts; ResetUserPassword refuses it anyway.
*/
public function sendPasswordResetNotification(#[\SensitiveParameter] $token): void
{
if (! app(AuthenticationContract::class)->isPasswordLoginAllowed($this)) {
return;
}
$this->notify(new ResetPassword($token));
}
public function hasLocalPassword(): bool
{
return is_string($this->password) && $this->password !== '';
}
public function canAccessPanel(Panel $panel): bool
{
return $this->isSuperAdmin();
}
public function isMemberOfOrganization(Organization $organization): bool
{
if ($this->relationLoaded('organizations')) {

View File

@@ -16,6 +16,7 @@ use App\Models\Tag;
use App\Models\Task;
use App\Models\TimeEntry;
use App\Models\User;
use App\Service\AuthenticationContract;
use App\Service\BillingContract;
use App\Service\GoalsContract;
use App\Service\IpLookup\IpLookupServiceContract;
@@ -109,6 +110,7 @@ class AppServiceProvider extends ServiceProvider
$this->app->bind(IpLookupServiceContract::class, NoIpLookupService::class);
$this->app->bind(BillingContract::class);
$this->app->bind(GoalsContract::class);
$this->app->bind(AuthenticationContract::class);
// Storage
// The local driver ignores the ResponseContentDisposition option of temporaryUrl,

View File

@@ -9,6 +9,7 @@ use App\Models\Passport\AuthCode;
use App\Models\Passport\Client;
use App\Models\Passport\RefreshToken;
use App\Models\Passport\Token;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Auth;
@@ -24,6 +25,15 @@ class AuthServiceProvider extends ServiceProvider
protected $policies = [
];
public function register(): void
{
parent::register();
// The device authorization grant is not used and has no views. Passport registers its routes
// while booting, so the grant has to be disabled before that, during registration.
Passport::$deviceCodeGrantEnabled = false;
}
/**
* Register any authentication / authorization services.
*/
@@ -36,6 +46,11 @@ class AuthServiceProvider extends ServiceProvider
return new ActiveUserProvider($app->make('hash'), $config['model']);
});
// Passport's authorization endpoint prompts guests to log in by throwing an
// AuthenticationException without a redirect target. Since Laravel 13 such an
// exception renders as an empty 401 instead of falling back to the login route.
AuthenticationException::redirectUsing(fn (): string => route('login'));
// define scopes for passport tokens
Passport::tokensCan([
'create' => 'Create resources',

View File

@@ -11,6 +11,8 @@ use App\Actions\Fortify\UpdateUserProfileInformation;
use App\Extensions\Fortify\CustomLoginResponse;
use App\Extensions\Fortify\CustomTwoFactorLoginResponse;
use App\Models\User;
use App\Service\AuthenticationContract;
use App\Service\IdentityConfirmationService;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
@@ -25,6 +27,12 @@ use Laravel\Fortify\Fortify;
class FortifyServiceProvider extends ServiceProvider
{
/**
* Hash of a random value that is checked when no user exists for the email,
* so login takes the same time whether the email is registered or not.
*/
private const string ABSENT_USER_PASSWORD_HASH = '$2y$12$PtSQLk/QWOJJpg42pGEkt.TTR7NwCq0.g/0EOWb2B6eDww4zR92.2';
/**
* Register any application services.
*/
@@ -44,6 +52,13 @@ class FortifyServiceProvider extends ServiceProvider
Fortify::resetUserPasswordsUsing(ResetUserPassword::class);
Fortify::registerView(function () {
if (! app(AuthenticationContract::class)->isPasswordRegistrationAllowed()) {
// Keeps flashed banners, like an invitation's "finish joining {org}", across the redirect.
session()->reflash();
return redirect()->route('login')->with('status', __(AuthenticationContract::PASSWORD_REGISTRATION_DISABLED_MESSAGE));
}
return Inertia::render('Auth/Register', [
'email' => session('registration_email', ''),
'terms_url' => config('auth.terms_url'),
@@ -93,13 +108,24 @@ class FortifyServiceProvider extends ServiceProvider
->where('is_placeholder', '=', false)
->first();
if ($user !== null && Hash::check($request->password, $user->password)) {
// Always check a hash so the response time doesn't reveal whether the user exists
$hasLocalPassword = $user !== null && $user->hasLocalPassword();
$existingPasswordHash = $hasLocalPassword ? $user->password : self::ABSENT_USER_PASSWORD_HASH;
$passwordIsValid = Hash::check((string) $request->password, $existingPasswordHash);
if ($hasLocalPassword && $passwordIsValid && app(AuthenticationContract::class)->isPasswordLoginAllowed($user)) {
return $user;
}
return null;
});
// Used by the password confirmation screen (e.g. before enabling 2FA) and OtherBrowserSessionsController
Fortify::confirmPasswordsUsing(function (mixed $user, ?string $password): bool {
return $user instanceof User && app(IdentityConfirmationService::class)->confirmPassword($user, $password);
});
RateLimiter::for('login', function (Request $request) {
$throttleKey = Str::transliterate(Str::lower($request->input(Fortify::username())).'|'.$request->ip());

View File

@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\Models\User;
/**
* Decides how users authenticate. Core only has password login.
* The SSO extension rebinds this to add single sign-on.
*/
class AuthenticationContract
{
public const string PASSWORD_REGISTRATION_DISABLED_MESSAGE = 'Create your account by signing in with single sign-on.';
public const string EMAIL_CHANGE_LOCKED_MESSAGE = 'Your email address comes from the identity provider you sign in with. Changes there are taken over on your next sign-in.';
/**
* Whether the user may use their local password: to log in, to reset it and to confirm their identity.
* Returning false for a user without a password also keeps "forgot password" from creating their first one.
*/
public function isPasswordLoginAllowed(User $user): bool
{
return true;
}
/**
* Whether people may create an account with a password on the register page. It is separate from
* the registration mode (app.enable_registration), which the register action checks first.
*/
public function isPasswordRegistrationAllowed(): bool
{
return true;
}
/**
* Whether the user may change their own email address. It is false when something else manages it,
* e.g. their organization's identity provider.
*/
public function canChangeEmail(User $user): bool
{
return true;
}
}

View File

@@ -140,25 +140,17 @@ class DashboardService
public function getDailyTrackedHours(User $user, Organization $organization, int $days): array
{
$timezone = $this->timezoneService->getTimezoneFromUser($user);
$timezoneShift = $this->timezoneService->getShiftFromUtc($timezone);
if ($timezoneShift > 0) {
$dateWithTimeZone = 'start + INTERVAL \''.$timezoneShift.' second\'';
} elseif ($timezoneShift < 0) {
$dateWithTimeZone = 'start - INTERVAL \''.abs($timezoneShift).' second\'';
} else {
$dateWithTimeZone = 'start';
}
$dateWithTimeZone = $this->timezoneService->getLocalDateTimeSqlExpression('start', $timezone);
$possibleDays = $this->lastDays($days, $timezone);
// The SQL fragment contains only a timezone offset calculated as an integer.
// Note: GROUP BY must use the alias, since the bound expressions would not be recognized as identical by PostgreSQL.
$query = TimeEntry::query()
->select(DB::raw('DATE('.$dateWithTimeZone.') as date, round(sum(extract(epoch from (coalesce("end", now()) - start)))) as aggregate')) // @phpstan-ignore argument.type
->selectRaw('DATE('.$dateWithTimeZone['sql'].') as date, round(sum(extract(epoch from (coalesce("end", now()) - start)))) as aggregate', $dateWithTimeZone['bindings'])
->where('user_id', '=', $user->getKey())
->where('organization_id', '=', $organization->getKey())
->workTime()
->groupBy(DB::raw('DATE('.$dateWithTimeZone.')')) // @phpstan-ignore argument.type
->groupBy('date')
->orderBy('date');
$query = $this->constrainDateByPossibleDates($query, $possibleDays, $timezone);
@@ -185,23 +177,16 @@ class DashboardService
public function getWeeklyHistory(User $user, Organization $organization): array
{
$timezone = $this->timezoneService->getTimezoneFromUser($user);
$timezoneShift = $this->timezoneService->getShiftFromUtc($timezone);
if ($timezoneShift > 0) {
$dateWithTimeZone = 'start + INTERVAL \''.$timezoneShift.' second\'';
} elseif ($timezoneShift < 0) {
$dateWithTimeZone = 'start - INTERVAL \''.abs($timezoneShift).' second\'';
} else {
$dateWithTimeZone = 'start';
}
$dateWithTimeZone = $this->timezoneService->getLocalDateTimeSqlExpression('start', $timezone);
$possibleDays = $this->daysOfThisWeek($timezone, $user->week_start);
// The SQL fragment contains only a timezone offset calculated as an integer.
// Note: GROUP BY must use the alias, since the bound expressions would not be recognized as identical by PostgreSQL.
$query = TimeEntry::query()
->select(DB::raw('DATE('.$dateWithTimeZone.') as date, round(sum(extract(epoch from (coalesce("end", now()) - start)))) as aggregate')) // @phpstan-ignore argument.type
->selectRaw('DATE('.$dateWithTimeZone['sql'].') as date, round(sum(extract(epoch from (coalesce("end", now()) - start)))) as aggregate', $dateWithTimeZone['bindings'])
->where('user_id', '=', $user->getKey())
->where('organization_id', '=', $organization->getKey())
->workTime()
->groupBy(DB::raw('DATE('.$dateWithTimeZone.')')) // @phpstan-ignore argument.type
->groupBy('date')
->orderBy('date');
$query = $this->constrainDateByPossibleDates($query, $possibleDays, $timezone);

View File

@@ -6,13 +6,15 @@ namespace App\Service;
use App\Enums\Role;
use App\Events\BeforeOrganizationDeletion;
use App\Events\BeforeUserDeletion;
use App\Exceptions\Api\CanNotDeleteUserWhoIsOwnerOfOrganizationWithMultipleMembers;
use App\Models\Client;
use App\Models\Export;
use App\Models\Goal;
use App\Models\Import;
use App\Models\Member;
use App\Models\Organization;
use App\Models\OrganizationInvitation;
use App\Models\Passport\RefreshToken;
use App\Models\Project;
use App\Models\ProjectMember;
use App\Models\Report;
@@ -22,6 +24,7 @@ use App\Models\TimeEntry;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
class DeletionService
{
@@ -80,6 +83,34 @@ class DeletionService
// Delete all goals
Goal::query()->whereBelongsTo($organization, 'organization')->delete();
// Delete all imports, the stored import files are deleted after the transaction is committed,
// since the deletion of files is not reversible via a database rollback
$importFilePaths = Import::query()
->whereBelongsTo($organization, 'organization')
->whereNotNull('file_path')
->pluck('file_path')
->all();
Import::query()->whereBelongsTo($organization, 'organization')->delete();
if (count($importFilePaths) > 0) {
DB::afterCommit(function () use ($importFilePaths): void {
Storage::disk(config('filesystems.private'))->delete($importFilePaths);
});
}
// Delete all exports, the stored export files are deleted after the transaction is committed,
// since the deletion of files is not reversible via a database rollback
$exportFilePaths = Export::query()
->whereBelongsTo($organization, 'organization')
->whereNotNull('file_path')
->pluck('file_path')
->all();
Export::query()->whereBelongsTo($organization, 'organization')->delete();
if (count($exportFilePaths) > 0) {
DB::afterCommit(function () use ($exportFilePaths): void {
Storage::disk(config('filesystems.private'))->delete($exportFilePaths);
});
}
// Reset the current organization
$organization->owner()
->where('current_team_id', $organization->getKey())
@@ -165,6 +196,8 @@ class DeletionService
}
}
BeforeUserDeletion::dispatch($user);
/** @var Member $member */
foreach ($members as $member) {
if ($member->role === Role::Owner->value) {
@@ -174,10 +207,7 @@ class DeletionService
}
}
// Refresh tokens are not linked to the user directly, so they need to be deleted via their access tokens.
// Otherwise a still-valid refresh token could be used to issue a new access token for a deleted user,
// which fails with a foreign key violation on oauth_access_tokens.user_id.
RefreshToken::query()->whereIn('access_token_id', $user->accessTokens()->pluck('id'))->delete();
// Note: Refresh tokens are deleted via the cascading foreign key on oauth_refresh_tokens.access_token_id
$user->accessTokens()->delete();
$user->authCodes()->delete();

View File

@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace App\Service;
use Illuminate\Support\Str;
use Throwable;
class ErrorDetailsFormatter
{
private const int MAX_LENGTH = 50000;
/**
* Technical details of the exception and all previous exceptions for debugging in the admin panel.
*/
public static function format(Throwable $exception): string
{
$parts = [];
$current = $exception;
while ($current !== null) {
$parts[] = $current::class.': '.$current->getMessage()."\n".
'at '.$current->getFile().':'.$current->getLine()."\n".
$current->getTraceAsString();
$current = $current->getPrevious();
}
return Str::limit(implode("\n\nCaused by: ", $parts), self::MAX_LENGTH);
}
}

View File

@@ -4,7 +4,12 @@ declare(strict_types=1);
namespace App\Service\Export;
use App\Enums\ExportStatus;
use App\Enums\ExportType;
use App\Exceptions\Api\ExportAlreadyInProgressApiException;
use App\Jobs\ProcessExport;
use App\Models\Client;
use App\Models\Export;
use App\Models\Member;
use App\Models\Organization;
use App\Models\OrganizationInvitation;
@@ -13,8 +18,11 @@ use App\Models\ProjectMember;
use App\Models\Tag;
use App\Models\Task;
use App\Models\TimeEntry;
use App\Models\User;
use App\Service\ErrorDetailsFormatter;
use Exception;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Http\File;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;
@@ -25,6 +33,7 @@ use League\Csv\Exception as LeagueCsvException;
use League\Csv\UnavailableStream;
use League\Csv\Writer;
use Spatie\TemporaryDirectory\TemporaryDirectory;
use Throwable;
use ZipArchive;
class ExportService
@@ -32,11 +41,102 @@ class ExportService
public const string VERSION = '1.0';
/**
* Creates an export of all data of the organization and queues it.
*
* @throws ExportAlreadyInProgressApiException
*/
public function createOrganizationExport(Organization $organization, ?User $user): Export
{
// Stale exports would block new exports until the export:prune command runs
Export::query()->whereBelongsTo($organization, 'organization')->stale()->get()
->each(fn (Export $staleExport) => $this->markAsFailed($staleExport, 'Export could not be finished'));
if (Export::query()->whereBelongsTo($organization, 'organization')->active()->exists()) {
throw new ExportAlreadyInProgressApiException;
}
$export = new Export;
$export->type = ExportType::Organization;
$export->status = ExportStatus::Pending;
$export->organization()->associate($organization);
$export->user()->associate($user);
try {
$export->save();
} catch (UniqueConstraintViolationException) {
// Another export of the organization was created in the meantime
throw new ExportAlreadyInProgressApiException;
}
ProcessExport::dispatch($export);
return $export;
}
/**
* Runs the export, the result (file path or error message) is stored on the export.
*/
public function process(Export $export): void
{
if ($export->status !== ExportStatus::Pending) {
Log::warning('Skipping export that is not pending', [
'export_id' => $export->getKey(),
'status' => $export->status->value,
]);
return;
}
$export->status = ExportStatus::Running;
$export->started_at = Carbon::now();
$export->save();
try {
$export->file_path = $this->export($export->organization, $export->getKey());
$export->status = ExportStatus::Completed;
} catch (Throwable $exception) {
// Export exceptions are already reported in the export method
if (! $exception instanceof ExportException) {
report($exception);
}
$export->status = ExportStatus::Failed;
$export->error_message = 'Export failed, please try again later or contact support';
$export->error_details = ErrorDetailsFormatter::format($exception->getPrevious() ?? $exception);
} finally {
$export->finished_at = Carbon::now();
$export->save();
}
// The export (and its organization) can be deleted while the export is running, the file would be orphaned
if ($export->file_path !== null && ! Export::query()->whereKey($export->getKey())->exists()) {
Log::warning('Deleting file of export that was deleted while it was running', [
'export_id' => $export->getKey(),
]);
Storage::disk(config('filesystems.private'))->delete($export->file_path);
}
}
/**
* Marks an export as failed that could not be finished, for example because the job timed out or the worker crashed.
*/
public function markAsFailed(Export $export, string $errorMessage): void
{
$export->status = ExportStatus::Failed;
$export->error_message = $errorMessage;
$export->finished_at = Carbon::now();
$export->save();
}
/**
* Creates the export ZIP file and stores it on the private disk.
*
* @return string Path of the ZIP file on the private disk
*
* @throws ExportException
*/
public function export(Organization $organization): string
public function export(Organization $organization, ?string $exportId = null): string
{
$exportId = Str::uuid();
$exportId ??= (string) Str::uuid();
$timeStamp = Carbon::now();
$temporaryDirectory = TemporaryDirectory::make();
Log::debug('Start exporting organization', [
@@ -365,9 +465,10 @@ class ExportService
$zip->close();
// Upload ZIP file to private storage
$filename = 'export_'.$organization->getKey().'_'.$timeStamp->format('Y-m-d_H-i-s').'_'.$exportId.'.zip';
$folder = 'exports/'.$organization->getKey();
$filename = $exportId.'.zip';
Storage::disk(config('filesystems.private'))->putFileAs(
'exports',
$folder,
new File($temporaryDirectoryZip->path('export.zip')),
$filename
);
@@ -381,11 +482,11 @@ class ExportService
'export_id' => $exportId,
]);
return 'exports/'.$filename;
return $folder.'/'.$filename;
} catch (UnavailableStream|CannotInsertRecord|Exception|LeagueCsvException $exception) {
report($exception);
throw new ExportException;
throw new ExportException(previous: $exception);
}
}
}

View File

@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
/**
* Confirms the account owner before sensitive actions like deleting an account or organization.
* Users confirm by re-entering their password. Users without one (or with one they may not log in with)
* can't confirm, so an administrator has to do these actions for them.
*/
class IdentityConfirmationService
{
/**
* Whether the user may confirm with their local password: they need one, and it must be one
* they may log in with. A password should not be an easier proof of identity than logging in.
*/
public function confirmsWithPassword(User $user): bool
{
return $user->hasLocalPassword() && app(AuthenticationContract::class)->isPasswordLoginAllowed($user);
}
/**
* Whether the given password confirms the user's identity.
*/
public function confirmPassword(User $user, ?string $password): bool
{
return $password !== null
&& $this->confirmsWithPassword($user)
&& Hash::check($password, (string) $user->password);
}
}

View File

@@ -4,44 +4,168 @@ declare(strict_types=1);
namespace App\Service\Import;
use App\Enums\ImportSource;
use App\Enums\ImportStatus;
use App\Jobs\ProcessImport;
use App\Models\Import;
use App\Models\Organization;
use App\Models\User;
use App\Service\ErrorDetailsFormatter;
use App\Service\Import\Importers\ImporterContract;
use App\Service\Import\Importers\ImporterProvider;
use App\Service\Import\Importers\ImportException;
use App\Service\Import\Importers\ReportDto;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use LogicException;
use Throwable;
class ImportService
{
/**
* Stores the import file and queues the import.
*
* @param bool $ignoreLimits Skip the import limits, only for imports started by a super admin (admin panel)
*
* @throws ImportException
*/
public function import(Organization $organization, string $importerType, string $data, string $timezone): ReportDto
public function createFileImport(Organization $organization, ?User $user, string $importerType, string $data, string $timezone, bool $ignoreLimits = false): Import
{
/** @var ImporterContract $importer */
$importer = app(ImporterProvider::class)->getImporter($importerType);
$importer->init($organization);
Storage::disk(config('filesystems.private'))
->put('import/'.Carbon::now()->toDateString().'-'.$organization->getKey().'-'.Str::uuid(), $data);
// Throws an InvalidArgumentException if the importer type is unknown
app(ImporterProvider::class)->getImporter($importerType);
$lock = Cache::lock('import:'.$organization->getKey(), config('octane.max_execution_time', 60) + 1);
// Stale imports would block new imports until the import:prune command runs
Import::query()->whereBelongsTo($organization, 'organization')->stale()->get()
->each(fn (Import $staleImport) => $this->markAsFailed($staleImport, 'Import could not be finished'));
if ($lock->get()) {
try {
DB::transaction(function () use (&$importer, &$data, &$timezone): void {
$importer->importData($data, $timezone);
});
} finally {
$lock->release();
}
} else {
if (Import::query()->whereBelongsTo($organization, 'organization')->active()->exists()) {
throw new ImportException('Import is already in progress');
}
return $importer->getReport();
$import = new Import;
$import->type = $importerType;
$import->source = ImportSource::File;
$import->status = ImportStatus::Pending;
$import->timezone = $timezone;
$import->ignore_limits = $ignoreLimits;
$import->organization()->associate($organization);
$import->user()->associate($user);
$import->id = $import->newUniqueId();
$import->file_path = 'import/'.$organization->getKey().'/'.$import->getKey();
Storage::disk(config('filesystems.private'))->put($import->file_path, $data);
try {
$import->save();
} catch (UniqueConstraintViolationException) {
// Another import of the organization was created in the meantime
Storage::disk(config('filesystems.private'))->delete($import->file_path);
throw new ImportException('Import is already in progress');
}
ProcessImport::dispatch($import);
return $import;
}
/**
* Runs the import, the result (report or error message) is stored on the import.
*/
public function process(Import $import): void
{
if ($import->status !== ImportStatus::Pending) {
Log::warning('Skipping import that is not pending', [
'import_id' => $import->getKey(),
'status' => $import->status->value,
]);
return;
}
$import->status = ImportStatus::Running;
$import->started_at = Carbon::now();
$import->save();
try {
/** @var ImporterContract $importer */
$importer = app(ImporterProvider::class)->getImporter($import->type);
$importer->init($import->organization);
$data = $this->getImportData($import);
DB::transaction(function () use (&$importer, &$data, $import): void {
$importer->importData($data, $import->timezone);
// Note: The limit is checked after the import, the exception rolls back all created records
$this->checkLimits($import, $importer->getReport());
});
$import->status = ImportStatus::Completed;
$import->report = $importer->getReport()->toArray();
} catch (ImportException $exception) {
// Import exceptions are not reported, they are caused by invalid import data or the importers already
// reported the underlying unexpected error
$import->status = ImportStatus::Failed;
$import->error_message = $exception->getMessage();
$import->error_details = ErrorDetailsFormatter::format($exception);
} catch (Throwable $exception) {
report($exception);
$import->status = ImportStatus::Failed;
$import->error_message = 'Unexpected error during import';
$import->error_details = ErrorDetailsFormatter::format($exception);
} finally {
$import->credentials = null;
$import->finished_at = Carbon::now();
$import->save();
}
}
/**
* Marks an import as failed that could not be finished, for example because the job timed out or the worker crashed.
*/
public function markAsFailed(Import $import, string $errorMessage): void
{
$import->status = ImportStatus::Failed;
$import->error_message = $errorMessage;
$import->credentials = null;
$import->finished_at = Carbon::now();
$import->save();
}
/**
* @throws ImportException
*/
private function checkLimits(Import $import, ReportDto $report): void
{
$maxRecords = config('import.max_records');
if ($import->ignore_limits || $maxRecords === null) {
return;
}
$totalCreated = $report->getTotalCreated();
if ($totalCreated > $maxRecords) {
throw new ImportException('The import would create '.$totalCreated.' records, but imports are limited to '.
$maxRecords.' records. Bigger imports are possible, please contact the support.');
}
}
/**
* @throws ImportException
*/
private function getImportData(Import $import): string
{
if ($import->source !== ImportSource::File) {
throw new LogicException('Import source "'.$import->source->value.'" is not supported yet');
}
$disk = Storage::disk(config('filesystems.private'));
if ($import->file_path === null || ! $disk->exists($import->file_path)) {
throw new ImportException('Import file does not exist anymore');
}
$data = $disk->get($import->file_path);
if ($data === null) {
throw new ImportException('Import file does not exist anymore');
}
return $data;
}
}

View File

@@ -20,6 +20,7 @@ class ClockifyProjectsImporter extends DefaultImporter
public function importData(string $data, string $timezone): void
{
try {
$this->checkUtf8($data);
$reader = Reader::createFromString($data);
$reader->setHeaderOffset(0);
$reader->setDelimiter(',');
@@ -67,10 +68,10 @@ class ClockifyProjectsImporter extends DefaultImporter
} catch (ImportException $exception) {
throw $exception;
} catch (CsvException $exception) {
throw new ImportException('Invalid CSV data');
throw new ImportException('Invalid CSV data', previous: $exception);
} catch (Exception $exception) {
report($exception);
throw new ImportException('Unknown error');
throw new ImportException('Unknown error', previous: $exception);
}
}

View File

@@ -49,6 +49,7 @@ class ClockifyTimeEntriesImporter extends DefaultImporter
public function importData(string $data, string $timezone): void
{
try {
$this->checkUtf8($data);
$reader = Reader::createFromString($data);
$reader->setHeaderOffset(0);
$reader->setDelimiter(',');
@@ -60,7 +61,7 @@ class ClockifyTimeEntriesImporter extends DefaultImporter
$records = $reader->getRecords();
foreach ($records as $record) {
$userId = $this->userImportHelper->getKey([
'email' => $record['Email'],
'email' => $this->validateEmail($record['Email'], 'Email'),
], [
'name' => $record['User'],
'timezone' => 'UTC',
@@ -118,7 +119,7 @@ class ClockifyTimeEntriesImporter extends DefaultImporter
$timeEntry->member_id = $memberId;
$timeEntry->task_id = $taskId;
$timeEntry->project_id = $projectId;
$timeEntry->client_id = $clientId;
$timeEntry->client_id = $project?->client_id;
$timeEntry->organization_id = $this->organization->id;
if (strlen($record['Description']) > 5000) {
throw new ImportException('Time entry description is too long');
@@ -202,6 +203,9 @@ class ClockifyTimeEntriesImporter extends DefaultImporter
$member,
$this->organization
);
if ($this->skipIfAlreadyExists($timeEntry)) {
continue;
}
$timeEntry->save();
$this->timeEntriesCreated++;
}
@@ -214,10 +218,10 @@ class ClockifyTimeEntriesImporter extends DefaultImporter
} catch (ImportException $exception) {
throw $exception;
} catch (CsvException $exception) {
throw new ImportException('Invalid CSV data');
throw new ImportException('Invalid CSV data', previous: $exception);
} catch (Exception $exception) {
report($exception);
throw new ImportException('Unknown error');
throw new ImportException('Unknown error', previous: $exception);
}
}

View File

@@ -12,12 +12,16 @@ use App\Models\Project;
use App\Models\ProjectMember;
use App\Models\Tag;
use App\Models\Task;
use App\Models\TimeEntry;
use App\Models\User;
use App\Service\BillableRateService;
use App\Service\ColorService;
use App\Service\Import\ImportDatabaseHelper;
use App\Service\Import\TimeEntryDeduplicator;
use App\Service\TimezoneService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Override;
abstract class DefaultImporter implements ImporterContract
@@ -58,6 +62,10 @@ abstract class DefaultImporter implements ImporterContract
protected int $timeEntriesCreated;
protected int $timeEntriesSkipped;
protected TimeEntryDeduplicator $timeEntryDeduplicator;
protected ColorService $colorService;
protected TimezoneService $timezoneService;
@@ -88,6 +96,12 @@ abstract class DefaultImporter implements ImporterContract
/** @var Builder<User> $builder */
return $builder->belongsToOrganization($this->organization);
}, null, validate: [
'email' => [
'required',
'string',
'max:255',
'email:rfc,strict',
],
'name' => [
'required',
'max:255',
@@ -197,10 +211,28 @@ abstract class DefaultImporter implements ImporterContract
],
]);
$this->timeEntriesCreated = 0;
$this->timeEntriesSkipped = 0;
$this->timeEntryDeduplicator = new TimeEntryDeduplicator($organization->getKey());
$this->colorService = app(ColorService::class);
$this->timezoneService = app(TimezoneService::class);
}
/**
* Uses the same rule as registration and invitations, so every email the app accepts can be re-imported.
* The value is lowercased (not trimmed), so it matches existing users exactly as stored.
*
* @throws ImportException
*/
protected function validateEmail(mixed $email, string $field): string
{
$email = is_string($email) ? Str::lower($email) : '';
if (Validator::make(['email' => $email], ['email' => ['required', 'email:rfc,strict']])->fails()) {
throw new ImportException('Value of '.$field.' ("'.$email.'") is not a valid email address');
}
return $email;
}
/**
* @throws ImportException
*/
@@ -211,6 +243,52 @@ abstract class DefaultImporter implements ImporterContract
}
}
/**
* @throws ImportException
*/
protected function checkUtf8(string $data, string $fileName = 'The file'): void
{
if (! mb_check_encoding($data, 'UTF-8')) {
throw new ImportException($fileName.' is not UTF-8 encoded, please export or save it as UTF-8 and try again');
}
}
/**
* Checks the file line by line, so large files are not loaded into memory at once. A line break is a single byte
* that never occurs inside a multibyte UTF-8 character, so splitting at line breaks is safe.
*
* @throws ImportException
*/
protected function checkFileUtf8(string $path, string $fileName): void
{
$handle = fopen($path, 'rb');
if ($handle === false) {
throw new ImportException('File "'.$fileName.'" can not be opened');
}
try {
while (($line = fgets($handle)) !== false) {
$this->checkUtf8($line, 'File "'.$fileName.'"');
}
} finally {
fclose($handle);
}
}
/**
* Returns true if an equal time entry already exists in the organization, for example because the same data was
* imported before. The time entry is counted as skipped and should not be saved.
*/
protected function skipIfAlreadyExists(TimeEntry $timeEntry): bool
{
if ($this->timeEntryDeduplicator->claimExisting($timeEntry)) {
$this->timeEntriesSkipped++;
return true;
}
return false;
}
#[Override]
public function getReport(): ReportDto
{
@@ -219,6 +297,7 @@ abstract class DefaultImporter implements ImporterContract
projectsCreated: $this->projectImportHelper->getCreatedCount(),
tasksCreated: $this->taskImportHelper->getCreatedCount(),
timeEntriesCreated: $this->timeEntriesCreated,
timeEntriesSkipped: $this->timeEntriesSkipped,
tagsCreated: $this->tagImportHelper->getCreatedCount(),
usersCreated: $this->userImportHelper->getCreatedCount(),
);

View File

@@ -28,6 +28,7 @@ class GenericProjectsImporter extends DefaultImporter
public function importData(string $data, string $timezone): void
{
try {
$this->checkUtf8($data);
$reader = Reader::createFromString($data);
$reader->setHeaderOffset(0);
$reader->setDelimiter(',');
@@ -70,10 +71,10 @@ class GenericProjectsImporter extends DefaultImporter
} catch (ImportException $exception) {
throw $exception;
} catch (CsvException $exception) {
throw new ImportException('Invalid CSV data');
throw new ImportException('Invalid CSV data', previous: $exception);
} catch (Exception $exception) {
report($exception);
throw new ImportException('Unknown error');
throw new ImportException('Unknown error', previous: $exception);
}
}

View File

@@ -64,6 +64,7 @@ class GenericTimeEntriesImporter extends DefaultImporter
public function importData(string $data, string $timezone): void
{
try {
$this->checkUtf8($data);
$reader = Reader::createFromString($data);
$reader->setHeaderOffset(0);
$reader->setDelimiter(',');
@@ -74,7 +75,7 @@ class GenericTimeEntriesImporter extends DefaultImporter
$records = $reader->getRecords();
foreach ($records as $record) {
$userId = $this->userImportHelper->getKey([
'email' => $record['user_email'],
'email' => $this->validateEmail($record['user_email'], 'user_email'),
], [
'name' => $record['user_name'],
'timezone' => 'UTC',
@@ -128,7 +129,7 @@ class GenericTimeEntriesImporter extends DefaultImporter
$timeEntry->member_id = $memberId;
$timeEntry->task_id = $taskId;
$timeEntry->project_id = $projectId;
$timeEntry->client_id = $clientId;
$timeEntry->client_id = $project?->client_id;
$timeEntry->organization_id = $this->organization->id;
$timeEntry->description = $record['description'];
if (! in_array($record['billable'], ['true', 'false'], true)) {
@@ -166,6 +167,9 @@ class GenericTimeEntriesImporter extends DefaultImporter
$member,
$this->organization
);
if ($this->skipIfAlreadyExists($timeEntry)) {
continue;
}
$timeEntry->save();
$this->timeEntriesCreated++;
}
@@ -178,10 +182,10 @@ class GenericTimeEntriesImporter extends DefaultImporter
} catch (ImportException $exception) {
throw $exception;
} catch (CsvException $exception) {
throw new ImportException('Invalid CSV data');
throw new ImportException('Invalid CSV data', previous: $exception);
} catch (Exception $exception) {
report($exception);
throw new ImportException('Unknown error');
throw new ImportException('Unknown error', previous: $exception);
}
}

View File

@@ -25,6 +25,7 @@ class HarvestClientsImporter extends DefaultImporter
public function importData(string $data, string $timezone): void
{
try {
$this->checkUtf8($data);
$reader = Reader::createFromString($data);
$reader->setHeaderOffset(0);
$reader->setDelimiter(',');
@@ -42,10 +43,10 @@ class HarvestClientsImporter extends DefaultImporter
} catch (ImportException $exception) {
throw $exception;
} catch (CsvException $exception) {
throw new ImportException('Invalid CSV data');
throw new ImportException('Invalid CSV data', previous: $exception);
} catch (Exception $exception) {
report($exception);
throw new ImportException('Unknown error');
throw new ImportException('Unknown error', previous: $exception);
}
}

View File

@@ -29,6 +29,7 @@ class HarvestProjectsImporter extends DefaultImporter
public function importData(string $data, string $timezone): void
{
try {
$this->checkUtf8($data);
$reader = Reader::createFromString($data);
$reader->setHeaderOffset(0);
$reader->setDelimiter(',');
@@ -73,10 +74,10 @@ class HarvestProjectsImporter extends DefaultImporter
} catch (ImportException $exception) {
throw $exception;
} catch (CsvException $exception) {
throw new ImportException('Invalid CSV data');
throw new ImportException('Invalid CSV data', previous: $exception);
} catch (Exception $exception) {
report($exception);
throw new ImportException('Unknown error');
throw new ImportException('Unknown error', previous: $exception);
}
}

View File

@@ -40,6 +40,7 @@ class HarvestTimeEntriesImporter extends DefaultImporter
public function importData(string $data, string $timezone): void
{
try {
$this->checkUtf8($data);
$reader = Reader::createFromString($data);
$reader->setHeaderOffset(0);
$reader->setDelimiter(',');
@@ -106,7 +107,7 @@ class HarvestTimeEntriesImporter extends DefaultImporter
$timeEntry->member_id = $memberId;
$timeEntry->task_id = $taskId;
$timeEntry->project_id = $projectId;
$timeEntry->client_id = $clientId;
$timeEntry->client_id = $project?->client_id;
$timeEntry->organization_id = $this->organization->id;
if (strlen($record['Notes']) > 5000) {
throw new ImportException('Time entry note is too long');
@@ -148,6 +149,9 @@ class HarvestTimeEntriesImporter extends DefaultImporter
$member,
$this->organization
);
if ($this->skipIfAlreadyExists($timeEntry)) {
continue;
}
$timeEntry->save();
$this->timeEntriesCreated++;
}
@@ -160,10 +164,10 @@ class HarvestTimeEntriesImporter extends DefaultImporter
} catch (ImportException $exception) {
throw $exception;
} catch (CsvException $exception) {
throw new ImportException('Invalid CSV data');
throw new ImportException('Invalid CSV data', previous: $exception);
} catch (Exception $exception) {
report($exception);
throw new ImportException('Unknown error');
throw new ImportException('Unknown error', previous: $exception);
}
}

Some files were not shown because too many files have changed in this diff Show More