Compare commits

..

4 Commits

Author SHA1 Message Date
Gregor Vostrak
595132ec2c fix diagnostics smoke test 2026-05-12 15:15:40 +02:00
Gregor Vostrak
0659cb3993 fix smoke test permissions 2026-05-11 20:15:21 +02:00
Gregor Vostrak
e8fc6fd77e removed SOLIDTIME_DROP_PRIVILEGES always option 2026-05-11 20:10:37 +02:00
Gregor Vostrak
a04185921d improve self-hosting permission handling 2026-05-11 19:08:55 +02:00
98 changed files with 1481 additions and 2558 deletions

View File

@@ -91,7 +91,7 @@ jobs:
if: steps.cache-vendor.outputs.cache-hit != 'true' # Skip if cache hit if: steps.cache-vendor.outputs.cache-hit != 'true' # Skip if cache hit
- name: "Use Node.js" - name: "Use Node.js"
uses: actions/setup-node@v6 uses: actions/setup-node@v4
with: with:
node-version: '20.x' node-version: '20.x'
@@ -177,7 +177,7 @@ jobs:
- build - build
steps: steps:
- name: "Download digests" - name: "Download digests"
uses: actions/download-artifact@v6 uses: actions/download-artifact@v4
with: with:
path: ${{ runner.temp }}/digests path: ${{ runner.temp }}/digests
pattern: digests-* pattern: digests-*

View File

@@ -22,7 +22,7 @@ jobs:
steps: steps:
- name: "Check out code" - name: "Check out code"
uses: actions/checkout@v5 uses: actions/checkout@v4
with: with:
fetch-depth: 0 # Required for WyriHaximus/github-action-get-previous-tag fetch-depth: 0 # Required for WyriHaximus/github-action-get-previous-tag
@@ -68,12 +68,12 @@ jobs:
run: cat .env run: cat .env
- name: "Use Node.js" - name: "Use Node.js"
uses: actions/setup-node@v6 uses: actions/setup-node@v4
with: with:
node-version: '20.x' node-version: '20.x'
- name: "Checkout billing extension" - name: "Checkout billing extension"
uses: actions/checkout@v5 uses: actions/checkout@v4
with: with:
repository: solidtime-io/extension-billing repository: solidtime-io/extension-billing
path: extensions/Billing path: extensions/Billing
@@ -93,7 +93,7 @@ jobs:
run: cd extensions/Billing && npm ci run: cd extensions/Billing && npm ci
- name: "Checkout services extension" - name: "Checkout services extension"
uses: actions/checkout@v5 uses: actions/checkout@v4
with: with:
repository: solidtime-io/extension-services repository: solidtime-io/extension-services
path: extensions/Services path: extensions/Services
@@ -111,7 +111,7 @@ jobs:
run: cd extensions/Services && npm ci run: cd extensions/Services && npm ci
- name: "Checkout invoicing extension" - name: "Checkout invoicing extension"
uses: actions/checkout@v5 uses: actions/checkout@v4
with: with:
repository: solidtime-io/extension-invoicing repository: solidtime-io/extension-invoicing
path: extensions/Invoicing path: extensions/Invoicing

View File

@@ -36,7 +36,7 @@ jobs:
steps: steps:
- name: "Check out code" - name: "Check out code"
uses: actions/checkout@v5 uses: actions/checkout@v4
with: with:
fetch-depth: 0 # Required for WyriHaximus/github-action-get-previous-tag fetch-depth: 0 # Required for WyriHaximus/github-action-get-previous-tag
@@ -92,7 +92,7 @@ jobs:
if: steps.cache-vendor.outputs.cache-hit != 'true' # Skip if cache hit if: steps.cache-vendor.outputs.cache-hit != 'true' # Skip if cache hit
- name: "Use Node.js" - name: "Use Node.js"
uses: actions/setup-node@v6 uses: actions/setup-node@v4
with: with:
node-version: '20.x' node-version: '20.x'
@@ -169,7 +169,7 @@ jobs:
- build - build
steps: steps:
- name: "Download digests" - name: "Download digests"
uses: actions/download-artifact@v6 uses: actions/download-artifact@v4
with: with:
path: ${{ runner.temp }}/digests path: ${{ runner.temp }}/digests
pattern: digests-* pattern: digests-*

View File

@@ -29,7 +29,7 @@ jobs:
steps: steps:
- name: "Checkout code" - name: "Checkout code"
uses: actions/checkout@v5 uses: actions/checkout@v4
- name: "Setup PHP" - name: "Setup PHP"
uses: shivammathur/setup-php@v2 uses: shivammathur/setup-php@v2

258
.github/workflows/image-smoke-test.yml vendored Normal file
View File

@@ -0,0 +1,258 @@
name: Image Smoke Tests
on:
pull_request:
paths:
- 'docker/prod/**'
- '.github/workflows/image-smoke-test.yml'
workflow_dispatch:
permissions:
contents: read
jobs:
smoke:
name: Smoke (${{ matrix.mode }})
runs-on: ubuntu-24.04
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
mode:
- default
- puid-pgid
- openshift
- drop-never
- diagnostic
- puid-mismatch-warning
steps:
- name: Check out code
uses: actions/checkout@v4
- name: Copy .env template
run: |
cp .env.production .env
rm .env.production .env.ci .env.example
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.3'
extensions: mbstring, dom, fileinfo, pgsql
- name: Composer install
run: composer install --no-dev --no-ansi --no-interaction --prefer-dist --ignore-platform-reqs --classmap-authoritative
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: '20.x'
- name: NPM ci
run: npm ci
- name: NPM build
run: npm run build
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Build smoke image
uses: docker/build-push-action@v6
with:
context: .
file: docker/prod/Dockerfile
build-args: |
DOCKER_FILES_BASE_PATH=docker/prod/
load: true
tags: solidtime-smoke:test
cache-from: type=gha
cache-to: type=gha,mode=max
- name: "Smoke: default (image config + fresh deploy with empty bind mounts)"
if: matrix.mode == 'default'
run: |
echo "[smoke] image's default USER is root (entrypoint needs root to drop privs)"
user=$(docker inspect --format '{{.Config.User}}' solidtime-smoke:test)
if [ "$user" != "root" ]; then
echo "Expected 'root', got '$user'. The Dockerfile must end with USER root so the entrypoint can chown/usermod and drop privileges."
exit 1
fi
echo "[smoke] storage tree is group-0 owned (OpenShift / arbitrary-UID compat)"
group=$(docker run --rm --entrypoint stat solidtime-smoke:test -c '%g' /var/www/html/storage)
if [ "$group" != "0" ]; then
echo "Expected group 0, got '$group'. The Dockerfile must chgrp -R 0 storage bootstrap/cache so arbitrary-UID containers can write."
exit 1
fi
mkdir -p test-storage test-cache
docker run --rm \
-v "$(pwd)/test-storage:/var/www/html/storage" \
-v "$(pwd)/test-cache:/var/www/html/bootstrap/cache" \
solidtime-smoke:test \
sh -c '
set -e
echo "[smoke] framework subdirs exist"
test -d /var/www/html/storage/framework/cache/data
test -d /var/www/html/storage/framework/sessions
test -d /var/www/html/storage/framework/views
test -d /var/www/html/storage/framework/testing
test -d /var/www/html/storage/logs
test -d /var/www/html/storage/app/public
test -d /var/www/html/storage/app/private
test -d /var/www/html/bootstrap/cache
echo "[smoke] storage is writable"
touch /var/www/html/storage/framework/cache/data/test-file
echo "[smoke] running as octane (UID 1000)"
[ "$(id -u)" = "1000" ]
echo "[smoke] PASS"
'
- name: "Smoke: PUID/PGID remap"
if: matrix.mode == 'puid-pgid'
run: |
mkdir -p test-storage test-cache
sudo chown -R 1501:1501 test-storage test-cache
docker run --rm \
-e PUID=1501 -e PGID=1501 \
-v "$(pwd)/test-storage:/var/www/html/storage" \
-v "$(pwd)/test-cache:/var/www/html/bootstrap/cache" \
solidtime-smoke:test \
sh -c '
set -e
echo "[smoke] running as remapped UID/GID 1501"
[ "$(id -u)" = "1501" ]
[ "$(id -g)" = "1501" ]
echo "[smoke] storage is writable as 1501"
touch /var/www/html/storage/framework/cache/data/test-file
echo "[smoke] PASS"
'
- name: "Smoke: OpenShift / arbitrary UID + group 0"
if: matrix.mode == 'openshift'
run: |
mkdir -p test-storage test-cache
sudo chown -R 2000:0 test-storage test-cache
sudo chmod -R g+rwX test-storage test-cache
docker run --rm --user 2000:0 \
-v "$(pwd)/test-storage:/var/www/html/storage" \
-v "$(pwd)/test-cache:/var/www/html/bootstrap/cache" \
solidtime-smoke:test \
sh -c '
set -e
echo "[smoke] running as arbitrary UID 2000, group 0"
[ "$(id -u)" = "2000" ]
[ "$(id -g)" = "0" ]
echo "[smoke] storage is writable via group 0"
touch /var/www/html/storage/framework/cache/data/test-file
echo "[smoke] PASS"
'
- name: "Smoke: SOLIDTIME_DROP_PRIVILEGES=never (run as root)"
if: matrix.mode == 'drop-never'
run: |
mkdir -p test-storage test-cache
docker run --rm \
-e SOLIDTIME_DROP_PRIVILEGES=never \
-v "$(pwd)/test-storage:/var/www/html/storage" \
-v "$(pwd)/test-cache:/var/www/html/bootstrap/cache" \
solidtime-smoke:test \
sh -c '
set -e
echo "[smoke] running as root (privilege drop disabled)"
[ "$(id -u)" = "0" ]
echo "[smoke] bootstrap still ran"
test -d /var/www/html/storage/framework/cache/data
echo "[smoke] storage writable as root"
touch /var/www/html/storage/framework/cache/data/test-file
echo "[smoke] PASS"
'
- name: "Smoke: PUID set + started non-root prints a warning but continues"
if: matrix.mode == 'puid-mismatch-warning'
run: |
mkdir -p test-storage test-cache
sudo chown -R 1500:1500 test-storage test-cache
set +e
docker run --rm \
--user 1500:1500 \
-e PUID=1500 -e PGID=1500 \
-v "$(pwd)/test-storage:/var/www/html/storage" \
-v "$(pwd)/test-cache:/var/www/html/bootstrap/cache" \
solidtime-smoke:test \
sh -c '
set -e
echo "[smoke] running as 1500 (user: directive wins)"
[ "$(id -u)" = "1500" ]
echo "[smoke] storage is writable as 1500"
touch /var/www/html/storage/framework/cache/data/test-file
echo "[smoke] container completed successfully"
' \
>stdout.log 2>stderr.log
exit_code=$?
set -e
echo "[smoke] exit code: $exit_code"
echo "--- stderr ---"
cat stderr.log
echo "--- end stderr ---"
if [ "$exit_code" -ne 0 ]; then
echo "Expected the entrypoint to continue (warning is non-fatal)."
exit 1
fi
for needle in "PUID/PGID is set but the container started as UID" "remove any 'user:' directive" "Continuing as UID"; do
if ! grep -q "$needle" stderr.log; then
echo "Missing warning fragment: $needle"
exit 1
fi
done
echo "[smoke] PASS"
- name: "Smoke: diagnostic error path (read-only storage mount)"
if: matrix.mode == 'diagnostic'
run: |
# Pre-create the full storage tree on the host so the entrypoint's
# bootstrap_storage_tree() is a no-op (mkdir -p on existing dirs
# returns 0 even on a read-only mount). The write test then fires
# against the RO mount and triggers our diagnostic.
mkdir -p test-storage/framework/cache/data \
test-storage/framework/sessions \
test-storage/framework/views \
test-storage/framework/testing \
test-storage/logs \
test-storage/app/public \
test-storage/app/private \
test-cache
set +e
docker run --rm \
-v "$(pwd)/test-storage:/var/www/html/storage:ro" \
-v "$(pwd)/test-cache:/var/www/html/bootstrap/cache:ro" \
solidtime-smoke:test \
true \
>stdout.log 2>stderr.log
exit_code=$?
set -e
echo "[smoke] exit code: $exit_code"
echo "--- stderr ---"
cat stderr.log
echo "--- end stderr ---"
if [ "$exit_code" -eq 0 ]; then
echo "Expected the entrypoint to exit non-zero on an unwritable storage mount."
exit 1
fi
for needle in "not writable" "PUID=" "permissions"; do
if ! grep -q "$needle" stderr.log; then
echo "Missing diagnostic fragment: $needle"
exit 1
fi
done
echo "[smoke] PASS"

View File

@@ -11,7 +11,7 @@ jobs:
steps: steps:
- name: "Checkout code" - name: "Checkout code"
uses: actions/checkout@v5 uses: actions/checkout@v4
- name: "Setup PHP (for Ziggy)" - name: "Setup PHP (for Ziggy)"
uses: shivammathur/setup-php@v2 uses: shivammathur/setup-php@v2
@@ -24,7 +24,7 @@ jobs:
run: composer install -n --prefer-dist run: composer install -n --prefer-dist
- name: "Use Node.js" - name: "Use Node.js"
uses: actions/setup-node@v6 uses: actions/setup-node@v4
with: with:
node-version: '20.x' node-version: '20.x'

View File

@@ -9,10 +9,10 @@ jobs:
steps: steps:
- name: "Checkout code" - name: "Checkout code"
uses: actions/checkout@v5 uses: actions/checkout@v4
- name: "Use Node.js" - name: "Use Node.js"
uses: actions/setup-node@v6 uses: actions/setup-node@v4
with: with:
node-version: '20.x' node-version: '20.x'

View File

@@ -11,10 +11,10 @@ jobs:
steps: steps:
- name: "Checkout code" - name: "Checkout code"
uses: actions/checkout@v5 uses: actions/checkout@v4
- name: "Use Node.js" - name: "Use Node.js"
uses: actions/setup-node@v6 uses: actions/setup-node@v4
with: with:
node-version: '20.x' node-version: '20.x'

View File

@@ -11,11 +11,11 @@ jobs:
id-token: write id-token: write
steps: steps:
- name: "Checkout code" - name: "Checkout code"
uses: actions/checkout@v5 uses: actions/checkout@v4
# Setup .npmrc file to publish to npm # Setup .npmrc file to publish to npm
- name: Install root project dependencies - name: Install root project dependencies
run: npm ci run: npm ci
- uses: actions/setup-node@v6 - uses: actions/setup-node@v4
with: with:
node-version: '20.x' node-version: '20.x'
registry-url: 'https://registry.npmjs.org' registry-url: 'https://registry.npmjs.org'

View File

@@ -11,9 +11,9 @@ jobs:
id-token: write id-token: write
steps: steps:
- name: "Checkout code" - name: "Checkout code"
uses: actions/checkout@v5 uses: actions/checkout@v4
# Setup .npmrc file to publish to npm # Setup .npmrc file to publish to npm
- uses: actions/setup-node@v6 - uses: actions/setup-node@v4
with: with:
node-version: '20.x' node-version: '20.x'
registry-url: 'https://registry.npmjs.org' registry-url: 'https://registry.npmjs.org'

View File

@@ -10,7 +10,7 @@ jobs:
steps: steps:
- name: "Checkout code" - name: "Checkout code"
uses: actions/checkout@v5 uses: actions/checkout@v4
- name: "Setup PHP (for Ziggy)" - name: "Setup PHP (for Ziggy)"
uses: shivammathur/setup-php@v2 uses: shivammathur/setup-php@v2
@@ -23,7 +23,7 @@ jobs:
run: composer install -n --prefer-dist run: composer install -n --prefer-dist
- name: "Use Node.js" - name: "Use Node.js"
uses: actions/setup-node@v6 uses: actions/setup-node@v4
with: with:
node-version: '20.x' node-version: '20.x'

View File

@@ -9,7 +9,7 @@ jobs:
steps: steps:
- name: "Checkout code" - name: "Checkout code"
uses: actions/checkout@v5 uses: actions/checkout@v4
- name: "Setup PHP" - name: "Setup PHP"
uses: shivammathur/setup-php@v2 uses: shivammathur/setup-php@v2

View File

@@ -36,7 +36,7 @@ jobs:
--health-retries 5 --health-retries 5
steps: steps:
- name: "Checkout code" - name: "Checkout code"
uses: actions/checkout@v5 uses: actions/checkout@v4
- name: "Setup PHP" - name: "Setup PHP"
uses: shivammathur/setup-php@v2 uses: shivammathur/setup-php@v2
@@ -48,7 +48,7 @@ jobs:
- name: "Run composer install" - name: "Run composer install"
run: composer install -n --prefer-dist run: composer install -n --prefer-dist
- uses: actions/setup-node@v6 - uses: actions/setup-node@v4
with: with:
node-version: '20.x' node-version: '20.x'
@@ -68,7 +68,7 @@ jobs:
run: php artisan test --stop-on-failure --coverage-text --coverage-clover=coverage.xml run: php artisan test --stop-on-failure --coverage-text --coverage-clover=coverage.xml
- name: "Upload coverage reports to Codecov" - name: "Upload coverage reports to Codecov"
uses: codecov/codecov-action@v5.5.1 uses: codecov/codecov-action@v5.4.3
with: with:
token: ${{ secrets.CODECOV_TOKEN }} token: ${{ secrets.CODECOV_TOKEN }}
slug: solidtime-io/solidtime slug: solidtime-io/solidtime

View File

@@ -9,9 +9,9 @@ jobs:
steps: steps:
- name: "Checkout code" - name: "Checkout code"
uses: actions/checkout@v5 uses: actions/checkout@v4
- name: "Check code style" - name: "Check code style"
uses: aglipanci/laravel-pint-action@2.6 uses: aglipanci/laravel-pint-action@2.5
with: with:
configPath: "pint.json" configPath: "pint.json"

View File

@@ -35,10 +35,10 @@ jobs:
steps: steps:
- name: "Checkout code" - name: "Checkout code"
uses: actions/checkout@v5 uses: actions/checkout@v4
- name: "Setup node" - name: "Setup node"
uses: actions/setup-node@v6 uses: actions/setup-node@v4
with: with:
node-version: '20.x' node-version: '20.x'

1
.gitignore vendored
View File

@@ -42,4 +42,3 @@ yarn-error.log
/data /data
/config/caddy /config/caddy
/config/composer /config/composer
/AGENTS.md

View File

@@ -3,18 +3,3 @@
## Reporting a Vulnerability ## 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)!
## Out of scope
Reports we typically won't issue an advisory for:
* Theoretical findings without a working PoC
* Raw scanner output without manual validation
* Missing/weak security headers in isolation (CSP, X-Frame-Options, HSTS, etc.)
* SPF/DKIM/DMARC on non-mail-sending domains; missing DNSSEC/CAA; TLS cipher preferences
* Self-XSS; CSRF on non-state-changing endpoints (logout, theme)
* CSV / spreadsheet formula injection in exports — treated as a spreadsheet-application issue
* Org owners or admins acting destructively within their own organization
* Anything requiring direct DB, shell, or filesystem access on a self-hosted instance
* Missing OAuth Scope enforcement (this is not implemented yet, but AI scanners flag it which is why it is included in this list until we actually support it)

View File

@@ -5,12 +5,9 @@ declare(strict_types=1);
namespace App\Actions\Fortify; namespace App\Actions\Fortify;
use App\Enums\Weekday; use App\Enums\Weekday;
use App\Mail\VerifyUpdatedEmailMail;
use App\Models\User; use App\Models\User;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule; use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException; use Illuminate\Validation\ValidationException;
use Korridor\LaravelModelValidationRules\Rules\UniqueEloquent; use Korridor\LaravelModelValidationRules\Rules\UniqueEloquent;
@@ -27,10 +24,6 @@ class UpdateUserProfileInformation implements UpdatesUserProfileInformation
*/ */
public function update(User $user, array $input): void public function update(User $user, array $input): void
{ {
if (isset($input['email']) && is_string($input['email'])) {
$input['email'] = Str::lower($input['email']);
}
Validator::make($input, [ Validator::make($input, [
'name' => [ 'name' => [
'required', 'required',
@@ -65,17 +58,16 @@ class UpdateUserProfileInformation implements UpdatesUserProfileInformation
$user->updateProfilePhoto($input['photo']); $user->updateProfilePhoto($input['photo']);
} }
$email = Str::lower((string) $input['email']); if ($input['email'] !== $user->email) {
if ($email !== Str::lower($user->email)) {
$user->forceFill([ $user->forceFill([
'name' => $input['name'], 'name' => $input['name'],
'pending_email' => $email, 'email' => $input['email'],
'email_verified_at' => null,
'timezone' => $input['timezone'], 'timezone' => $input['timezone'],
'week_start' => $input['week_start'], 'week_start' => $input['week_start'],
])->save(); ])->save();
Mail::to($email)->send(new VerifyUpdatedEmailMail($user, $email)); $user->sendEmailVerificationNotification();
} else { } else {
$user->forceFill([ $user->forceFill([
'name' => $input['name'], 'name' => $input['name'],

View File

@@ -4,9 +4,18 @@ declare(strict_types=1);
namespace App\Actions\Jetstream; namespace App\Actions\Jetstream;
use App\Exceptions\MovedToApiException; use App\Enums\Role;
use App\Models\Organization; use App\Models\Organization;
use App\Models\User; use App\Models\User;
use App\Service\MemberService;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\In;
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
use Laravel\Jetstream\Contracts\AddsTeamMembers; use Laravel\Jetstream\Contracts\AddsTeamMembers;
class AddOrganizationMember implements AddsTeamMembers class AddOrganizationMember implements AddsTeamMembers
@@ -16,6 +25,70 @@ class AddOrganizationMember implements AddsTeamMembers
*/ */
public function add(User $owner, Organization $organization, string $email, ?string $role = null): void public function add(User $owner, Organization $organization, string $email, ?string $role = null): void
{ {
throw new MovedToApiException; Gate::forUser($owner)->authorize('addTeamMember', $organization); // TODO: refactor after owner refactoring
$this->validate($organization, $email, $role);
$newOrganizationMember = User::query()
->where('email', $email)
->where('is_placeholder', '=', false)
->firstOrFail();
app(MemberService::class)->addMember($newOrganizationMember, $organization, Role::from($role));
}
/**
* Validate the add member operation.
*/
protected function validate(Organization $organization, string $email, ?string $role): void
{
Validator::make([
'email' => $email,
'role' => $role,
], $this->rules())->after(
$this->ensureUserIsNotAlreadyOnTeam($organization, $email)
)->validateWithBag('addTeamMember');
}
/**
* Get the validation rules for adding a team member.
*
* @return array<string, array<ValidationRule|Rule|string|In>>
*/
protected function rules(): array
{
return [
'email' => [
'required',
'email',
ExistsEloquent::make(User::class, 'email', function (Builder $builder) {
/** @var Builder<User> $builder */
return $builder->where('is_placeholder', '=', false);
})->withMessage(__('We were unable to find a registered user with this email address.')),
],
'role' => [
'required',
'string',
Rule::in([
Role::Admin->value,
Role::Manager->value,
Role::Employee->value,
]),
],
];
}
/**
* Ensure that the user is not already on the team.
*/
protected function ensureUserIsNotAlreadyOnTeam(Organization $team, string $email): Closure
{
return function ($validator) use ($team, $email): void {
$validator->errors()->addIf(
$team->hasRealUserWithEmail($email),
'email',
__('This user already belongs to the team.')
);
};
} }
} }

View File

@@ -25,8 +25,6 @@ class CreateOrganization implements CreatesTeams
* *
* @throws AuthorizationException * @throws AuthorizationException
* @throws ValidationException * @throws ValidationException
*
* @deprecated Use REST endpoint instead
*/ */
public function create(User $user, array $input): Organization public function create(User $user, array $input): Organization
{ {

View File

@@ -12,8 +12,6 @@ class DeleteOrganization implements DeletesTeams
{ {
/** /**
* Delete the given team. * Delete the given team.
*
* @deprecated Use REST endpoint instead
*/ */
public function delete(Organization $organization): void public function delete(Organization $organization): void
{ {

View File

@@ -16,8 +16,6 @@ class DeleteUser implements DeletesUsers
* Delete the given user. * Delete the given user.
* *
* @throws ValidationException * @throws ValidationException
*
* @deprecated Use REST endpoint instead
*/ */
public function delete(User $user): void public function delete(User $user): void
{ {

View File

@@ -18,8 +18,6 @@ class ValidateOrganizationDeletion
* @param Organization $organization Organization to be deleted * @param Organization $organization Organization to be deleted
* *
* @throws AuthorizationException * @throws AuthorizationException
*
* @deprecated Use REST endpoint instead
*/ */
public function validate(User $user, Organization $organization): void public function validate(User $user, Organization $organization): void
{ {

View File

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

View File

@@ -1,28 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Events;
use App\Enums\Role;
use App\Models\Organization;
use App\Models\User;
use Illuminate\Foundation\Events\Dispatchable;
class MemberAdding
{
use Dispatchable;
public User $user;
public Organization $organization;
public Role $role;
public function __construct(User $user, Organization $organization, Role $role)
{
$this->user = $user;
$this->organization = $organization;
$this->role = $role;
}
}

View File

@@ -1,10 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Exceptions\Api;
class UserResendEmailVerificationNoPendingEmailApiException extends ApiException
{
public const string KEY = 'user_resend_email_verification_no_pending_email';
}

View File

@@ -20,7 +20,7 @@ class ApiTokenController extends Controller
/** /**
* List all api token of the currently authenticated user * List all api token of the currently authenticated user
* *
* This endpoint is independent of the organization. * This endpoint is independent of organization.
* *
* @operationId getApiTokens * @operationId getApiTokens
* *

View File

@@ -5,17 +5,11 @@ declare(strict_types=1);
namespace App\Http\Controllers\Api\V1; namespace App\Http\Controllers\Api\V1;
use App\Enums\Role; use App\Enums\Role;
use App\Events\AfterCreateOrganization;
use App\Http\Requests\V1\Organization\OrganizationStoreRequest;
use App\Http\Requests\V1\Organization\OrganizationUpdateRequest; use App\Http\Requests\V1\Organization\OrganizationUpdateRequest;
use App\Http\Resources\V1\Organization\OrganizationResource; use App\Http\Resources\V1\Organization\OrganizationResource;
use App\Models\Organization; use App\Models\Organization;
use App\Service\BillableRateService; use App\Service\BillableRateService;
use App\Service\DeletionService;
use App\Service\IpLookup\IpLookupServiceContract;
use App\Service\OrganizationService;
use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\JsonResponse;
class OrganizationController extends Controller class OrganizationController extends Controller
{ {
@@ -86,48 +80,4 @@ class OrganizationController extends Controller
return new OrganizationResource($organization, true); return new OrganizationResource($organization, true);
} }
/**
* Create organization
*
* @operationId createOrganization
*/
public function store(OrganizationStoreRequest $request, OrganizationService $organizationService): OrganizationResource
{
$user = $this->user();
$ipLookupResponse = app(IpLookupServiceContract::class)->lookup($request->ip());
$currency = $ipLookupResponse?->currency;
$organization = $organizationService->createOrganization(
$request->getName(),
$user,
false,
$currency
);
$user->switchTeam($organization);
// Note: The refresh is necessary for currently unknown reasons. Do not remove it.
$organization = $organization->refresh();
AfterCreateOrganization::dispatch($organization);
return new OrganizationResource($organization, true);
}
/**
* Delete organization
*
* @operationId deleteOrganization
*
* @throws AuthorizationException
*/
public function destroy(Organization $organization, DeletionService $deletionService): JsonResponse
{
$this->checkPermission($organization, 'organizations:delete');
$deletionService->deleteOrganization($organization);
return response()->json(null, 204);
}
} }

View File

@@ -4,26 +4,15 @@ declare(strict_types=1);
namespace App\Http\Controllers\Api\V1; namespace App\Http\Controllers\Api\V1;
use App\Exceptions\Api\CanNotDeleteUserWhoIsOwnerOfOrganizationWithMultipleMembers;
use App\Exceptions\Api\UserResendEmailVerificationNoPendingEmailApiException;
use App\Http\Requests\V1\User\UserUpdateRequest;
use App\Http\Resources\V1\User\UserResource; use App\Http\Resources\V1\User\UserResource;
use App\Mail\VerifyUpdatedEmailMail;
use App\Models\User;
use App\Service\DeletionService;
use App\Support\Base64File;
use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
class UserController extends Controller class UserController extends Controller
{ {
/** /**
* Get the current user * Get the current user
* *
* This endpoint is independent of the organization. * This endpoint is independent of organization.
* *
* @operationId getMe * @operationId getMe
* *
@@ -35,114 +24,4 @@ class UserController extends Controller
return new UserResource($user); return new UserResource($user);
} }
/**
* Update the current user
*
* This endpoint is independent of the organization.
*
* @operationId updateUser
*/
public function update(User $user, UserUpdateRequest $request): UserResource
{
if ($user->getKey() !== $this->user()->getKey()) {
throw new AuthorizationException;
}
if ($request->getPhoto() !== null) {
$photo = Base64File::decode($request->getPhoto());
assert($photo !== null);
$extension = Base64File::extension($photo['mime_type']);
assert($extension !== null);
$previousPhotoPath = $user->profile_photo_path;
$photoPath = 'profile-photos/'.Str::uuid().'.'.$extension;
$photoDisk = (string) config('jetstream.profile_photo_disk', 'public');
Storage::disk($photoDisk)->put($photoPath, $photo['data'], 'public');
$user->profile_photo_path = $photoPath;
if ($previousPhotoPath !== null) {
Storage::disk($photoDisk)->delete($previousPhotoPath);
}
}
$emailToVerify = null;
$email = $request->getEmail();
if ($email !== null && $email !== Str::lower($user->email)) {
$emailToVerify = $email;
$user->pending_email = $email;
}
if ($request->getName() !== null) {
$user->name = $request->getName();
}
if ($request->getTimezone() !== null) {
$user->timezone = $request->getTimezone();
}
if ($request->getWeekStart() !== null) {
$user->week_start = $request->getWeekStart();
}
$user->save();
if ($emailToVerify !== null) {
Mail::to($emailToVerify)->send(new VerifyUpdatedEmailMail($user, $emailToVerify));
}
return new UserResource($user);
}
/**
* Resend the pending email update verification email.
*
* This endpoint is independent of the organization.
*
* @operationId resendUserEmailVerification
*
* @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.
*/
public function resendEmailVerification(User $user): JsonResponse
{
if ($user->getKey() !== $this->user()->getKey()) {
throw new AuthorizationException;
}
if ($user->pending_email === null) {
throw new UserResendEmailVerificationNoPendingEmailApiException;
}
Mail::to($user->pending_email)
->queue(new VerifyUpdatedEmailMail($user, $user->pending_email));
return response()->json(null, 204);
}
/**
* Handles the deletion of a user.
*
* This endpoint is independent of the organization.
*
* @operationId deleteUser
*
* @param User $user The user instance to be deleted.
* @param DeletionService $deletionService The service responsible for performing the user deletion.
* @return JsonResponse A JSON response with a 204 No Content status upon successful deletion.
*
* @throws AuthorizationException Thrown when the authenticated user does not match the user to be deleted.
* @throws CanNotDeleteUserWhoIsOwnerOfOrganizationWithMultipleMembers Thrown when the user to be deleted is the owner of an organization with multiple members.
*/
public function destroy(User $user, DeletionService $deletionService): JsonResponse
{
if ($user->getKey() !== $this->user()->getKey()) {
throw new AuthorizationException;
}
$deletionService->deleteUser($user);
return response()->json(null, 204);
}
} }

View File

@@ -14,7 +14,7 @@ class UserMembershipController extends Controller
/** /**
* Get the memberships of the current user * Get the memberships of the current user
* *
* This endpoint is independent of the organization. * This endpoint is independent of organization.
* *
* @operationId getMyMemberships * @operationId getMyMemberships
* *

View File

@@ -17,7 +17,7 @@ class UserTimeEntryController extends Controller
/** /**
* Get the active time entry of the current user * Get the active time entry of the current user
* *
* This endpoint is independent of the organization. * This endpoint is independent of organization.
* *
* @operationId getMyActiveTimeEntry * @operationId getMyActiveTimeEntry
*/ */

View File

@@ -4,13 +4,30 @@ declare(strict_types=1);
namespace App\Http\Controllers\Web; namespace App\Http\Controllers\Web;
use App\Enums\Role;
use App\Service\DashboardService;
use App\Service\PermissionStore;
use Illuminate\Auth\Access\AuthorizationException;
use Inertia\Inertia; use Inertia\Inertia;
use Inertia\Response; use Inertia\Response;
class DashboardController extends Controller class DashboardController extends Controller
{ {
public function dashboard(): Response /**
* @throws AuthorizationException
*/
public function dashboard(DashboardService $dashboardService, PermissionStore $permissionStore): Response
{ {
$user = $this->user();
$organization = $this->currentOrganization();
$latestTeamActivity = null;
if ($permissionStore->has($organization, 'time-entries:view:all')) {
$latestTeamActivity = $dashboardService->latestTeamActivity($organization);
}
$showBillableRate = $this->member($organization)->role !== Role::Employee->value || $organization->employees_can_see_billable_rates;
return Inertia::render('Dashboard'); return Inertia::render('Dashboard');
} }
} }

View File

@@ -1,75 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Web;
use App\Enums\Role;
use App\Models\OrganizationInvitation;
use App\Models\User;
use App\Service\MemberService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use RuntimeException;
class OrganizationInvitationController extends Controller
{
public function accept(OrganizationInvitation $invitation, MemberService $memberService): RedirectResponse
{
$email = strtolower($invitation->email);
$role = Role::tryFrom($invitation->role);
if ($role === null || $role === Role::Owner || $role === Role::Placeholder) {
throw new RuntimeException('Invalid role');
}
$organization = $invitation->organization;
$invitee = User::query()
->where('email', $email)
->where('is_placeholder', '=', false)
->first();
// No account yet — finish on registration.
if ($invitee === null) {
if ($invitation->accepted_at === null) {
$invitation->accepted_at = now();
$invitation->save();
}
return redirect(route('register'))
->with('bannerText', __('Please create an account to finish joining the :organization organization.', [
'organization' => $organization->name,
]))
->with('bannerStyle', 'info');
}
$alreadyMember = $memberService->isEmailAlreadyMember($organization, $email);
if (! $alreadyMember) {
$memberService->addMember($invitee, $organization, $role);
$invitation->delete();
}
// Logged out — banner on /login.
if (! Auth::check()) {
return redirect(route('login'))
->with('bannerText', __('Great! You have accepted the invitation to join the :organization organization. Please log in to access it.', [
'organization' => $organization->name,
]))
->with('bannerStyle', 'success');
}
// Logged in — banner on /dashboard.
if ($alreadyMember) {
return redirect(route('dashboard'))
->with('bannerText', __('You are already a member of the :organization organization.', [
'organization' => $organization->name,
]))
->with('bannerStyle', 'danger');
}
return redirect(route('dashboard'))
->with('bannerText', __('Great! You have accepted the invitation to join the :organization organization.', [
'organization' => $organization->name,
]))
->with('bannerStyle', 'success');
}
}

View File

@@ -1,55 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Web;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
class UserController extends Controller
{
public function verifyEmailChange(Request $request, User $user): RedirectResponse
{
if ($request->user()?->getAuthIdentifier() !== $user->getKey()) {
abort(403);
}
$email = $request->query('email');
if (! is_string($email)) {
abort(403);
}
$email = Str::lower($email);
if ($user->pending_email !== $email) {
abort(403);
}
$emailAlreadyInUse = User::query()
->where('email', '=', $email)
->where('is_placeholder', '=', false)
->whereKeyNot($user->getKey())
->exists();
if ($emailAlreadyInUse) {
return redirect(route('dashboard', [
'bannerStyle' => 'danger',
'bannerText' => __('The email address is already in use.'),
]));
}
$user->email = $email;
$user->pending_email = null;
$user->email_verified_at = Carbon::now();
$user->save();
return redirect(route('dashboard', [
'bannerStyle' => 'success',
'bannerText' => __('Your email address has been updated successfully.'),
]));
}
}

View File

@@ -60,8 +60,6 @@ class HandleInertiaRequests extends Middleware
] : null, ] : null,
'flash' => [ 'flash' => [
'message' => fn () => $request->session()->get('message'), 'message' => fn () => $request->session()->get('message'),
'bannerText' => fn () => $request->session()->get('bannerText'),
'bannerStyle' => fn () => $request->session()->get('bannerStyle'),
], ],
]); ]);
} }

View File

@@ -39,6 +39,7 @@ class ShareInertiaData
'canUpdatePassword' => Features::enabled(Features::updatePasswords()), 'canUpdatePassword' => Features::enabled(Features::updatePasswords()),
'canUpdateProfileInformation' => Features::canUpdateProfileInformation(), 'canUpdateProfileInformation' => Features::canUpdateProfileInformation(),
'hasEmailVerification' => Features::enabled(Features::emailVerification()), 'hasEmailVerification' => Features::enabled(Features::emailVerification()),
'flash' => $request->session()->get('flash', []),
'hasAccountDeletionFeatures' => Jetstream::hasAccountDeletionFeatures(), 'hasAccountDeletionFeatures' => Jetstream::hasAccountDeletionFeatures(),
'hasApiFeatures' => Jetstream::hasApiFeatures(), 'hasApiFeatures' => Jetstream::hasApiFeatures(),
'hasTeamFeatures' => Jetstream::hasTeamFeatures(), 'hasTeamFeatures' => Jetstream::hasTeamFeatures(),

View File

@@ -1,35 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\V1\Organization;
use App\Http\Requests\V1\BaseFormRequest;
use App\Models\Organization;
/**
* @property Organization $organization Organization from model binding
*/
class OrganizationStoreRequest extends BaseFormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array<string, array<string|\Illuminate\Contracts\Validation\Rule>>
*/
public function rules(): array
{
return [
'name' => [
'required',
'string',
'max:255',
],
];
}
public function getName(): string
{
return (string) $this->input('name');
}
}

View File

@@ -1,88 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\V1\User;
use App\Enums\Weekday;
use App\Http\Requests\V1\BaseFormRequest;
use App\Models\User;
use App\Rules\Base64ImageRule;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Korridor\LaravelModelValidationRules\Rules\UniqueEloquent;
/**
* @property User $user User from model binding
*/
class UserUpdateRequest extends BaseFormRequest
{
protected function prepareForValidation(): void
{
if ($this->has('email') && is_string($this->input('email'))) {
$this->merge([
'email' => Str::lower((string) $this->input('email')),
]);
}
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, array<string|\Illuminate\Contracts\Validation\Rule|ValidationRule>>
*/
public function rules(): array
{
return [
'name' => [
'string',
'max:255',
],
'email' => [
'email',
'max:255',
UniqueEloquent::make(User::class, 'email')->ignore($this->user->id)->query(function (Builder $query) {
/** @var Builder<User> $query */
return $query->where('is_placeholder', '=', false);
}),
],
'photo' => [
'nullable',
new Base64ImageRule,
],
'timezone' => [
'timezone:all',
],
'week_start' => [
Rule::enum(Weekday::class),
],
];
}
public function getName(): ?string
{
return $this->has('name') ? (string) $this->input('name') : null;
}
public function getEmail(): ?string
{
return $this->has('email') ? Str::lower((string) $this->input('email')) : null;
}
public function getTimezone(): ?string
{
return $this->has('timezone') ? (string) $this->input('timezone') : null;
}
public function getWeekStart(): ?Weekday
{
return $this->has('week_start') ? Weekday::from($this->input('week_start')) : null;
}
public function getPhoto(): ?string
{
return $this->has('photo') ? (string) $this->input('photo') : null;
}
}

View File

@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace App\Listeners;
use App\Models\Member;
use App\Models\User;
use App\Service\MemberService;
use Illuminate\Database\Eloquent\Builder;
use Laravel\Jetstream\Events\TeamMemberAdded;
class RemovePlaceholder
{
/**
* Handle the event.
*/
public function handle(TeamMemberAdded $event): void
{
$memberService = app(MemberService::class);
$member = Member::query()
->whereBelongsTo($event->team, 'organization')
->whereBelongsTo($event->user, 'user')
->firstOrFail();
$placeholders = Member::query()
->whereHas('user', function (Builder $query) use ($event): void {
/** @var Builder<User> $query */
$query->where('is_placeholder', '=', true)
->where('email', '=', $event->user->email);
})
->whereBelongsTo($event->team, 'organization')
->with(['user'])
->get();
foreach ($placeholders as $placeholder) {
/** @var Member $placeholder */
$placeholderUser = $placeholder->user;
$memberService->assignOrganizationEntitiesToDifferentMember($event->team, $placeholder, $member);
$placeholder->delete();
$placeholderUser->delete();
}
}
}

View File

@@ -8,7 +8,6 @@ use App\Models\OrganizationInvitation;
use Illuminate\Bus\Queueable; use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable; use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\URL; use Illuminate\Support\Facades\URL;
class OrganizationInvitationMail extends Mailable class OrganizationInvitationMail extends Mailable
@@ -33,12 +32,9 @@ class OrganizationInvitationMail extends Mailable
public function build(): self public function build(): self
{ {
return $this->markdown('emails.organization-invitation', [ return $this->markdown('emails.organization-invitation', [
'acceptUrl' => URL::to(URL::signedRoute( 'acceptUrl' => URL::signedRoute('team-invitations.accept', [
'organization-invitations.accept', 'invitation' => $this->invitation,
['invitation' => $this->invitation->getKey()], ]),
Carbon::now()->addDays(90),
false
)),
])->subject(__('Organization Invitation')); ])->subject(__('Organization Invitation'));
} }
} }

View File

@@ -1,48 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Mail;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;
class VerifyUpdatedEmailMail extends Mailable
{
use Queueable, SerializesModels;
public User $user;
public string $email;
public function __construct(User $user, string $email)
{
$this->user = $user;
$this->email = Str::lower($email);
}
/**
* Build the message.
*/
public function build(): self
{
$verificationUrl = URL::temporarySignedRoute(
'users.verify-email-change',
Carbon::now()->addMinutes((int) config('auth.verification.expire', 60)),
[
'user' => $this->user->getKey(),
'email' => $this->email,
],
false
);
return $this->markdown('emails.verify-updated-email', [
'verificationUrl' => URL::to($verificationUrl),
])->subject(__('Verify Email Address'));
}
}

View File

@@ -36,7 +36,6 @@ use OwenIt\Auditing\Contracts\Auditable as AuditableContract;
* @property string $user_id * @property string $user_id
* @property bool $employees_can_see_billable_rates * @property bool $employees_can_see_billable_rates
* @property bool $employees_can_manage_tasks * @property bool $employees_can_manage_tasks
* @property bool $prevent_overlapping_time_entries
* @property User $owner * @property User $owner
* @property Carbon|null $created_at * @property Carbon|null $created_at
* @property Carbon|null $updated_at * @property Carbon|null $updated_at

View File

@@ -18,7 +18,6 @@ use OwenIt\Auditing\Contracts\Auditable as AuditableContract;
* @property string $email * @property string $email
* @property string $role * @property string $role
* @property string $organization_id * @property string $organization_id
* @property Carbon|null $accepted_at
* @property Carbon|null $updated_at * @property Carbon|null $updated_at
* @property Carbon|null $created_at * @property Carbon|null $created_at
* @property-read Organization $organization * @property-read Organization $organization
@@ -42,16 +41,14 @@ class OrganizationInvitation extends JetstreamTeamInvitation implements Auditabl
protected $table = 'organization_invitations'; protected $table = 'organization_invitations';
/** /**
* Get the attributes that should be cast. * The attributes that are mass assignable.
* *
* @return array<string, string> * @var array<int, string>
*/ */
public function casts(): array protected $fillable = [
{ 'email',
return [ 'role',
'accepted_at' => 'datetime',
]; ];
}
/** /**
* Get the organization that the invitation belongs to. * Get the organization that the invitation belongs to.

View File

@@ -36,7 +36,6 @@ use OwenIt\Auditing\Contracts\Auditable as AuditableContract;
* @property string $id * @property string $id
* @property string $name * @property string $name
* @property string $email * @property string $email
* @property string|null $pending_email
* @property Carbon|null $email_verified_at * @property Carbon|null $email_verified_at
* @property string|null $password * @property string|null $password
* @property string|null $two_factor_secret * @property string|null $two_factor_secret
@@ -106,7 +105,6 @@ class User extends Authenticatable implements AuditableContract, FilamentUser, M
protected $casts = [ protected $casts = [
'name' => 'string', 'name' => 'string',
'email' => 'string', 'email' => 'string',
'pending_email' => 'string',
'email_verified_at' => 'datetime', 'email_verified_at' => 'datetime',
'is_admin' => 'boolean', 'is_admin' => 'boolean',
'is_placeholder' => 'boolean', 'is_placeholder' => 'boolean',

View File

@@ -62,6 +62,18 @@ class OrganizationPolicy
return app(PermissionStore::class)->userHas($organization, $user, 'organizations:update'); return app(PermissionStore::class)->userHas($organization, $user, 'organizations:update');
} }
/**
* Determine whether the user can add team members.
*/
public function addTeamMember(User $user, Organization $organization): bool
{
if (Filament::isServing()) {
return true;
}
return true;
}
/** /**
* Determine whether the user can update team member permissions. * Determine whether the user can update team member permissions.
*/ */

View File

@@ -4,9 +4,11 @@ declare(strict_types=1);
namespace App\Providers; namespace App\Providers;
use App\Listeners\RemovePlaceholder;
use Illuminate\Auth\Events\Registered; use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification; use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Laravel\Jetstream\Events\TeamMemberAdded;
class EventServiceProvider extends ServiceProvider class EventServiceProvider extends ServiceProvider
{ {
@@ -19,6 +21,9 @@ class EventServiceProvider extends ServiceProvider
Registered::class => [ Registered::class => [
SendEmailVerificationNotification::class, SendEmailVerificationNotification::class,
], ],
TeamMemberAdded::class => [
RemovePlaceholder::class,
],
]; ];
/** /**

View File

@@ -17,7 +17,6 @@ use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\RateLimiter; use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider; use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Inertia\Inertia;
use Laravel\Fortify\Contracts\TwoFactorLoginResponse; use Laravel\Fortify\Contracts\TwoFactorLoginResponse;
use Laravel\Fortify\Fortify; use Laravel\Fortify\Fortify;
use Laravel\Fortify\Http\Responses\LoginResponse; use Laravel\Fortify\Http\Responses\LoginResponse;
@@ -42,14 +41,6 @@ class FortifyServiceProvider extends ServiceProvider
Fortify::updateUserPasswordsUsing(UpdateUserPassword::class); Fortify::updateUserPasswordsUsing(UpdateUserPassword::class);
Fortify::resetUserPasswordsUsing(ResetUserPassword::class); Fortify::resetUserPasswordsUsing(ResetUserPassword::class);
Fortify::registerView(function () {
return Inertia::render('Auth/Register', [
'terms_url' => config('auth.terms_url'),
'privacy_policy_url' => config('auth.privacy_policy_url'),
'newsletter_consent' => config('auth.newsletter_consent'),
]);
});
Fortify::authenticateUsing(function (Request $request): ?User { Fortify::authenticateUsing(function (Request $request): ?User {
/** @var User|null $user */ /** @var User|null $user */
$user = User::query() $user = User::query()

View File

@@ -13,18 +13,20 @@ use App\Actions\Jetstream\RemoveOrganizationMember;
use App\Actions\Jetstream\UpdateMemberRole; use App\Actions\Jetstream\UpdateMemberRole;
use App\Actions\Jetstream\UpdateOrganization; use App\Actions\Jetstream\UpdateOrganization;
use App\Actions\Jetstream\ValidateOrganizationDeletion; use App\Actions\Jetstream\ValidateOrganizationDeletion;
use App\Enums\Role;
use App\Enums\Weekday; use App\Enums\Weekday;
use App\Models\Member; use App\Models\Member;
use App\Models\Organization; use App\Models\Organization;
use App\Models\OrganizationInvitation; use App\Models\OrganizationInvitation;
use App\Models\User; use App\Models\User;
use App\Service\PermissionStore;
use App\Service\TimezoneService; use App\Service\TimezoneService;
use Brick\Money\Currency; use Brick\Money\Currency;
use Brick\Money\ISOCurrencyProvider; use Brick\Money\ISOCurrencyProvider;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider; use Illuminate\Support\ServiceProvider;
use Inertia\Inertia;
use Laravel\Fortify\Fortify;
use Laravel\Jetstream\Actions\UpdateTeamMemberRole; use Laravel\Jetstream\Actions\UpdateTeamMemberRole;
use Laravel\Jetstream\Actions\ValidateTeamDeletion; use Laravel\Jetstream\Actions\ValidateTeamDeletion;
use Laravel\Jetstream\Jetstream; use Laravel\Jetstream\Jetstream;
@@ -58,6 +60,13 @@ class JetstreamServiceProvider extends ServiceProvider
Jetstream::useTeamInvitationModel(OrganizationInvitation::class); Jetstream::useTeamInvitationModel(OrganizationInvitation::class);
app()->singleton(UpdateTeamMemberRole::class, UpdateMemberRole::class); app()->singleton(UpdateTeamMemberRole::class, UpdateMemberRole::class);
app()->singleton(ValidateTeamDeletion::class, ValidateOrganizationDeletion::class); app()->singleton(ValidateTeamDeletion::class, ValidateOrganizationDeletion::class);
Fortify::registerView(function () {
return Inertia::render('Auth/Register', [
'terms_url' => config('auth.terms_url'),
'privacy_policy_url' => config('auth.privacy_policy_url'),
'newsletter_consent' => config('auth.newsletter_consent'),
]);
});
Gate::define('removeTeamMember', function (User $user, Organization $team) { Gate::define('removeTeamMember', function (User $user, Organization $team) {
return false; return false;
}); });
@@ -70,10 +79,205 @@ class JetstreamServiceProvider extends ServiceProvider
{ {
Jetstream::defaultApiTokenPermissions([]); Jetstream::defaultApiTokenPermissions([]);
foreach (PermissionStore::roleDefinitions() as $role => $definition) { Jetstream::role(Role::Owner->value, 'Owner', [
Jetstream::role($role, $definition['name'], $definition['permissions']) 'charts:view:own',
->description($definition['description']); 'charts:view:all',
} 'projects:view',
'projects:view:all',
'projects:create',
'projects:update',
'projects:delete',
'project-members:view',
'project-members:create',
'project-members:update',
'project-members:delete',
'tasks:view',
'tasks:view:all',
'tasks:create',
'tasks:create:all',
'tasks:update',
'tasks:update:all',
'tasks:delete',
'tasks:delete:all',
'time-entries:view:all',
'time-entries:create:all',
'time-entries:update:all',
'time-entries:delete:all',
'time-entries:view:own',
'time-entries:create:own',
'time-entries:update:own',
'time-entries:delete:own',
'tags:view',
'tags:create',
'tags:update',
'tags:delete',
'clients:view',
'clients:view:all',
'clients:create',
'clients:update',
'clients:delete',
'organizations:view',
'organizations:update',
'organizations:delete',
'import',
'export',
'invitations:view',
'invitations:create',
'invitations:resend',
'invitations:remove',
'members:view',
'members:invite-placeholder',
'members:change-ownership',
'members:make-placeholder',
'members:merge-into',
'members:update',
'members:delete',
'billing',
'reports:view',
'reports:create',
'reports:update',
'reports:delete',
'invoices:view',
'invoices:create',
'invoices:update',
'invoices:download',
'invoices:delete',
'invoice-settings:view',
'invoice-settings:update',
])->description('Owner users can perform any action. There is only one owner per organization.');
Jetstream::role(Role::Admin->value, 'Administrator', [
'charts:view:own',
'charts:view:all',
'projects:view',
'projects:view:all',
'projects:create',
'projects:update',
'projects:delete',
'project-members:view',
'project-members:create',
'project-members:update',
'project-members:delete',
'tasks:view',
'tasks:view:all',
'tasks:create',
'tasks:create:all',
'tasks:update',
'tasks:update:all',
'tasks:delete',
'tasks:delete:all',
'time-entries:view:all',
'time-entries:create:all',
'time-entries:update:all',
'time-entries:delete:all',
'time-entries:view:own',
'time-entries:create:own',
'time-entries:update:own',
'time-entries:delete:own',
'tags:view',
'tags:create',
'tags:update',
'tags:delete',
'clients:view',
'clients:view:all',
'clients:create',
'clients:update',
'clients:delete',
'organizations:view',
'organizations:update',
'import',
'export',
'invitations:view',
'invitations:create',
'invitations:resend',
'invitations:remove',
'members:view',
'members:invite-placeholder',
'members:make-placeholder',
'members:merge-into',
'members:delete',
'members:update',
'reports:view',
'reports:create',
'reports:update',
'reports:delete',
'invoices:view',
'invoices:create',
'invoices:update',
'invoices:download',
'invoices:delete',
'invoice-settings:view',
'invoice-settings:update',
])->description('Administrator users can perform any action, except accessing the billing dashboard.');
Jetstream::role(Role::Manager->value, 'Manager', [
'charts:view:own',
'charts:view:all',
'projects:view',
'projects:view:all',
'projects:create',
'projects:update',
'projects:delete',
'project-members:view',
'project-members:create',
'project-members:update',
'project-members:delete',
'tasks:view',
'tasks:view:all',
'tasks:create',
'tasks:create:all',
'tasks:update',
'tasks:update:all',
'tasks:delete',
'tasks:delete:all',
'time-entries:view:all',
'time-entries:create:all',
'time-entries:update:all',
'time-entries:delete:all',
'time-entries:view:own',
'time-entries:create:own',
'time-entries:update:own',
'time-entries:delete:own',
'tags:view',
'tags:create',
'tags:update',
'tags:delete',
'clients:view',
'clients:view:all',
'clients:create',
'clients:update',
'clients:delete',
'organizations:view',
'invitations:view',
'members:view',
'reports:view',
'reports:create',
'reports:update',
'reports:delete',
'invoices:view',
'invoices:create',
'invoices:update',
'invoices:download',
'invoices:delete',
'invoice-settings:view',
'invoice-settings:update',
])->description('Managers have full access to all projects, time entries, ect. but cannot manage the organization (add/remove member, edit the organization, ect.).');
Jetstream::role(Role::Employee->value, 'Employee', [
'charts:view:own',
'projects:view',
'tags:view',
'tasks:view',
'clients:view',
'time-entries:view:own',
'time-entries:create:own',
'time-entries:update:own',
'time-entries:delete:own',
'organizations:view',
])->description('Employees have the ability to read, create, and update their own time entries, they can see the projects that they are members of and the clients they are assigned to.');
Jetstream::role(Role::Placeholder->value, 'Placeholder', [
])->description('Placeholders are used for importing data. They cannot log in and have no permissions.');
Jetstream::inertia() Jetstream::inertia()
->whenRendering( ->whenRendering(
@@ -100,8 +304,28 @@ class JetstreamServiceProvider extends ServiceProvider
'owner' => [ 'owner' => [
'id' => $owner->getKey(), 'id' => $owner->getKey(),
'name' => $owner->name, 'name' => $owner->name,
'email' => $owner->email,
'profile_photo_url' => $owner->profile_photo_url, 'profile_photo_url' => $owner->profile_photo_url,
], ],
'users' => $teamModel->users->map(function (User $user): array {
return [
'id' => $user->getKey(),
'name' => $user->name,
'email' => $user->email,
'profile_photo_url' => $user->profile_photo_url,
'membership' => [
'id' => $user->membership->id,
'role' => $user->membership->role,
],
];
}),
'team_invitations' => $teamModel->teamInvitations->map(function (OrganizationInvitation $invitation): array {
return [
'id' => $invitation->getKey(),
'email' => $invitation->email,
'role' => $invitation->role,
];
}),
], ],
'currencies' => array_map(function (Currency $currency): string { 'currencies' => array_map(function (Currency $currency): string {
return $currency->getName(); return $currency->getName();

View File

@@ -1,37 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Rules;
use App\Support\Base64File;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Translation\PotentiallyTranslatedString;
class Base64ImageRule implements ValidationRule
{
private const array ALLOWED_MIME_TYPES = [
'image/jpeg',
'image/png',
];
/**
* Run the validation rule.
*
* @param Closure(string): PotentiallyTranslatedString $fail
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (! is_string($value)) {
$fail(__('validation.string'));
return;
}
$file = Base64File::decode($value);
if ($file === null || ! in_array($file['mime_type'], self::ALLOWED_MIME_TYPES, true)) {
$fail(__('validation.mimes', ['values' => 'jpg, png']));
}
}
}

View File

@@ -8,11 +8,9 @@ use App\Enums\Role;
use App\Exceptions\Api\InvitationForTheEmailAlreadyExistsApiException; use App\Exceptions\Api\InvitationForTheEmailAlreadyExistsApiException;
use App\Exceptions\Api\UserIsAlreadyMemberOfOrganizationApiException; use App\Exceptions\Api\UserIsAlreadyMemberOfOrganizationApiException;
use App\Mail\OrganizationInvitationMail; use App\Mail\OrganizationInvitationMail;
use App\Models\Member;
use App\Models\Organization; use App\Models\Organization;
use App\Models\OrganizationInvitation; use App\Models\OrganizationInvitation;
use App\Models\User;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Mail;
use Laravel\Jetstream\Events\InvitingTeamMember; use Laravel\Jetstream\Events\InvitingTeamMember;
@@ -23,7 +21,11 @@ class InvitationService
*/ */
public function inviteUser(Organization $organization, string $email, Role $role): OrganizationInvitation public function inviteUser(Organization $organization, string $email, Role $role): OrganizationInvitation
{ {
if (app(MemberService::class)->isEmailAlreadyMember($organization, $email)) { if (Member::query()
->whereBelongsTo($organization, 'organization')
->whereRelation('user', 'email', '=', $email)
->where('role', '!=', Role::Placeholder->value)
->exists()) {
throw new UserIsAlreadyMemberOfOrganizationApiException; throw new UserIsAlreadyMemberOfOrganizationApiException;
} }
@@ -46,37 +48,4 @@ class InvitationService
return $invitation; return $invitation;
} }
/**
* @return Collection<int, Organization>
*/
public function processAcceptedInvitations(User $user): Collection
{
$organizations = new Collection;
$invitations = OrganizationInvitation::query()
->where('email', $user->email)
->whereNotNull('accepted_at')
->get();
foreach ($invitations as $invitation) {
$organization = $invitation->organization;
$role = Role::tryFrom($invitation->role);
if ($role === null) {
Log::error('Invalid role in invitation', [
'invitation' => $invitation->getKey(),
'role' => $invitation->role,
]);
continue;
}
app(MemberService::class)->addMember($user, $organization, $role);
$invitation->delete();
$organizations->push($organization);
}
return $organizations;
}
} }

View File

@@ -5,8 +5,6 @@ declare(strict_types=1);
namespace App\Service; namespace App\Service;
use App\Enums\Role; use App\Enums\Role;
use App\Events\MemberAdded;
use App\Events\MemberAdding;
use App\Events\MemberRemoved; use App\Events\MemberRemoved;
use App\Exceptions\Api\CanNotRemoveOwnerFromOrganization; use App\Exceptions\Api\CanNotRemoveOwnerFromOrganization;
use App\Exceptions\Api\ChangingRoleOfPlaceholderIsNotAllowed; use App\Exceptions\Api\ChangingRoleOfPlaceholderIsNotAllowed;
@@ -38,8 +36,7 @@ class MemberService
public function addMember(User $user, Organization $organization, Role $role, bool $asSuperAdmin = false): Member public function addMember(User $user, Organization $organization, Role $role, bool $asSuperAdmin = false): Member
{ {
if (! $asSuperAdmin) { if (! $asSuperAdmin) {
MemberAdding::dispatch($user, $organization, $role); AddingTeamMember::dispatch($organization, $user);
AddingTeamMember::dispatch($organization, $user); // Legacy event
} }
$member = new Member; $member = new Member;
@@ -52,37 +49,14 @@ class MemberService
$user->currentOrganization()->associate($organization); $user->currentOrganization()->associate($organization);
$user->save(); $user->save();
}); });
$this->mergePlaceholderMembersIntoExistingMember($member, $organization, $user);
if (! $asSuperAdmin) { if (! $asSuperAdmin) {
MemberAdded::dispatch($member, $organization, $user); TeamMemberAdded::dispatch($organization, $user);
TeamMemberAdded::dispatch($organization, $user); // Legacy event
} }
return $member; return $member;
} }
private function mergePlaceholderMembersIntoExistingMember(Member $member, Organization $organization, User $user): void
{
$placeholders = Member::query()
->whereHas('user', function (Builder $query) use ($user): void {
/** @var Builder<User> $query */
$query->where('is_placeholder', '=', true)
->where('email', '=', $user->email);
})
->whereBelongsTo($organization, 'organization')
->with(['user'])
->get();
foreach ($placeholders as $placeholder) {
/** @var Member $placeholder */
$placeholderUser = $placeholder->user;
$this->assignOrganizationEntitiesToDifferentMember($organization, $placeholder, $member);
$placeholder->delete();
$placeholderUser->delete();
}
}
/** /**
* @throws CanNotRemoveOwnerFromOrganization * @throws CanNotRemoveOwnerFromOrganization
* @throws EntityStillInUseApiException * @throws EntityStillInUseApiException
@@ -235,13 +209,4 @@ class MemberService
$this->userService->makeSureUserHasCurrentOrganization($user); $this->userService->makeSureUserHasCurrentOrganization($user);
} }
} }
public function isEmailAlreadyMember(Organization $organization, string $email): bool
{
return Member::query()
->whereBelongsTo($organization, 'organization')
->whereRelation('user', 'email', '=', $email)
->where('role', '!=', Role::Placeholder->value)
->exists();
}
} }

View File

@@ -4,238 +4,14 @@ declare(strict_types=1);
namespace App\Service; namespace App\Service;
use App\Enums\Role;
use App\Models\Organization; use App\Models\Organization;
use App\Models\User; use App\Models\User;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Laravel\Jetstream\Jetstream;
use Laravel\Jetstream\Role;
class PermissionStore class PermissionStore
{ {
/**
* @var array<string, array{name: string, permissions: array<string>, description: string}>
*/
private const array ROLE_DEFINITIONS = [
'owner' => [
'name' => 'Owner',
'permissions' => [
'charts:view:own',
'charts:view:all',
'projects:view',
'projects:view:all',
'projects:create',
'projects:update',
'projects:delete',
'project-members:view',
'project-members:create',
'project-members:update',
'project-members:delete',
'tasks:view',
'tasks:view:all',
'tasks:create',
'tasks:create:all',
'tasks:update',
'tasks:update:all',
'tasks:delete',
'tasks:delete:all',
'time-entries:view:all',
'time-entries:create:all',
'time-entries:update:all',
'time-entries:delete:all',
'time-entries:view:own',
'time-entries:create:own',
'time-entries:update:own',
'time-entries:delete:own',
'tags:view',
'tags:create',
'tags:update',
'tags:delete',
'clients:view',
'clients:view:all',
'clients:create',
'clients:update',
'clients:delete',
'organizations:view',
'organizations:update',
'organizations:delete',
'import',
'export',
'invitations:view',
'invitations:create',
'invitations:resend',
'invitations:remove',
'members:view',
'members:invite-placeholder',
'members:change-ownership',
'members:make-placeholder',
'members:merge-into',
'members:update',
'members:delete',
'billing',
'reports:view',
'reports:create',
'reports:update',
'reports:delete',
'invoices:view',
'invoices:create',
'invoices:update',
'invoices:download',
'invoices:delete',
'invoice-settings:view',
'invoice-settings:update',
],
'description' => 'Owner users can perform any action. There is only one owner per organization.',
],
'admin' => [
'name' => 'Administrator',
'permissions' => [
'charts:view:own',
'charts:view:all',
'projects:view',
'projects:view:all',
'projects:create',
'projects:update',
'projects:delete',
'project-members:view',
'project-members:create',
'project-members:update',
'project-members:delete',
'tasks:view',
'tasks:view:all',
'tasks:create',
'tasks:create:all',
'tasks:update',
'tasks:update:all',
'tasks:delete',
'tasks:delete:all',
'time-entries:view:all',
'time-entries:create:all',
'time-entries:update:all',
'time-entries:delete:all',
'time-entries:view:own',
'time-entries:create:own',
'time-entries:update:own',
'time-entries:delete:own',
'tags:view',
'tags:create',
'tags:update',
'tags:delete',
'clients:view',
'clients:view:all',
'clients:create',
'clients:update',
'clients:delete',
'organizations:view',
'organizations:update',
'import',
'export',
'invitations:view',
'invitations:create',
'invitations:resend',
'invitations:remove',
'members:view',
'members:invite-placeholder',
'members:make-placeholder',
'members:merge-into',
'members:delete',
'members:update',
'reports:view',
'reports:create',
'reports:update',
'reports:delete',
'invoices:view',
'invoices:create',
'invoices:update',
'invoices:download',
'invoices:delete',
'invoice-settings:view',
'invoice-settings:update',
],
'description' => 'Administrator users can perform any action, except accessing the billing dashboard.',
],
'manager' => [
'name' => 'Manager',
'permissions' => [
'charts:view:own',
'charts:view:all',
'projects:view',
'projects:view:all',
'projects:create',
'projects:update',
'projects:delete',
'project-members:view',
'project-members:create',
'project-members:update',
'project-members:delete',
'tasks:view',
'tasks:view:all',
'tasks:create',
'tasks:create:all',
'tasks:update',
'tasks:update:all',
'tasks:delete',
'tasks:delete:all',
'time-entries:view:all',
'time-entries:create:all',
'time-entries:update:all',
'time-entries:delete:all',
'time-entries:view:own',
'time-entries:create:own',
'time-entries:update:own',
'time-entries:delete:own',
'tags:view',
'tags:create',
'tags:update',
'tags:delete',
'clients:view',
'clients:view:all',
'clients:create',
'clients:update',
'clients:delete',
'organizations:view',
'invitations:view',
'members:view',
'reports:view',
'reports:create',
'reports:update',
'reports:delete',
'invoices:view',
'invoices:create',
'invoices:update',
'invoices:download',
'invoices:delete',
'invoice-settings:view',
'invoice-settings:update',
],
'description' => 'Managers have full access to all projects, time entries, ect. but cannot manage the organization (add/remove member, edit the organization, ect.).',
],
'employee' => [
'name' => 'Employee',
'permissions' => [
'charts:view:own',
'projects:view',
'tags:view',
'tasks:view',
'clients:view',
'time-entries:view:own',
'time-entries:create:own',
'time-entries:update:own',
'time-entries:delete:own',
'organizations:view',
],
'description' => 'Employees have the ability to read, create, and update their own time entries, they can see the projects that they are members of and the clients they are assigned to.',
],
'placeholder' => [
'name' => 'Placeholder',
'permissions' => [],
'description' => 'Placeholders are used for importing data. They cannot log in and have no permissions.',
],
];
/**
* @var array<string, array<string>>
*/
private static array $customRolePermissions = [];
/** /**
* @var array<string, array<string>> * @var array<string, array<string>>
*/ */
@@ -246,37 +22,6 @@ class PermissionStore
$this->permissionCache = []; $this->permissionCache = [];
} }
/**
* @return array<string, array{name: string, permissions: array<string>, description: string}>
*/
public static function roleDefinitions(): array
{
return self::ROLE_DEFINITIONS;
}
/**
* @param array<string> $permissions
*/
public static function registerCustomRole(string $role, array $permissions): void
{
self::$customRolePermissions[$role] = $permissions;
}
public static function resetCustomRoles(): void
{
self::$customRolePermissions = [];
}
/**
* @return array<string>
*/
public static function permissionsForRole(string $role): array
{
return self::$customRolePermissions[$role]
?? self::ROLE_DEFINITIONS[$role]['permissions']
?? [];
}
public function has(Organization $organization, string $permission): bool public function has(Organization $organization, string $permission): bool
{ {
/** @var User|null $user */ /** @var User|null $user */
@@ -323,11 +68,14 @@ class PermissionStore
return []; return [];
} }
$permissions = self::permissionsForRole($role); /** @var Role|null $roleObj */
$roleObj = Jetstream::findRole($role);
$permissions = $roleObj->permissions ?? [];
// If the organization allows employees to manage tasks and the user is an employee, // If the organization allows employees to manage tasks and the user is an employee,
// add the task management permissions for accessible projects // add the task management permissions for accessible projects
if ($role === Role::Employee->value && $organization->employees_can_manage_tasks) { if ($role === \App\Enums\Role::Employee->value && $organization->employees_can_manage_tasks) {
$permissions = array_merge($permissions, [ $permissions = array_merge($permissions, [
'tasks:create', 'tasks:create',
'tasks:update', 'tasks:update',

View File

@@ -38,7 +38,7 @@ class UserService
): User { ): User {
$user = new User; $user = new User;
$user->name = $name; $user->name = $name;
$user->email = strtolower($email); $user->email = $email;
$user->password = Hash::make($password); $user->password = Hash::make($password);
$user->timezone = $timezone; $user->timezone = $timezone;
$user->week_start = $weekStart; $user->week_start = $weekStart;
@@ -47,9 +47,6 @@ class UserService
} }
$user->save(); $user->save();
$organizations = app(InvitationService::class)->processAcceptedInvitations($user);
if ($organizations->isEmpty()) {
$organization = app(OrganizationService::class)->createOrganization( $organization = app(OrganizationService::class)->createOrganization(
$this->getOrganizationNameForUserName($user->name), $this->getOrganizationNameForUserName($user->name),
$user, $user,
@@ -61,8 +58,8 @@ class UserService
$intervalFormat, $intervalFormat,
$timeFormat, $timeFormat,
); );
$user->ownedTeams()->save($organization); $user->ownedTeams()->save($organization);
}
return $user; return $user;
} }

View File

@@ -1,45 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Support;
use Symfony\Component\Mime\MimeTypes;
class Base64File
{
/**
* @return array{data: string, mime_type: string}|null
*/
public static function decode(string $value): ?array
{
if (str_contains($value, ',')) {
[, $value] = explode(',', $value, 2);
}
$value = preg_replace('/\s+/', '', $value);
if ($value === null || $value === '') {
return null;
}
$decoded = base64_decode($value, true);
if ($decoded === false) {
return null;
}
$mimeType = (new \finfo(FILEINFO_MIME_TYPE))->buffer($decoded);
if ($mimeType === false) {
return null;
}
return [
'data' => $decoded,
'mime_type' => $mimeType,
];
}
public static function extension(string $mimeType): ?string
{
return MimeTypes::getDefault()->getExtensions($mimeType)[0] ?? null;
}
}

View File

@@ -25,24 +25,9 @@ class OrganizationInvitationFactory extends Factory
'email' => $this->faker->unique()->safeEmail(), 'email' => $this->faker->unique()->safeEmail(),
'role' => Role::Employee->value, 'role' => Role::Employee->value,
'organization_id' => Organization::factory(), 'organization_id' => Organization::factory(),
'accepted_at' => null,
]; ];
} }
public function role(Role $role): self
{
return $this->state(fn (array $attributes) => [
'role' => $role->value,
]);
}
public function accepted(): self
{
return $this->state(fn (array $attributes): array => [
'accepted_at' => $this->faker->dateTime(),
]);
}
public function forOrganization(Organization $organization): self public function forOrganization(Organization $organization): self
{ {
return $this->state(fn (array $attributes) => [ return $this->state(fn (array $attributes) => [

View File

@@ -1,30 +0,0 @@
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('organization_invitations', function (Blueprint $table): void {
$table->timestamp('accepted_at')->nullable()->after('email');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('organization_invitations', function (Blueprint $table): void {
$table->dropColumn('accepted_at');
});
}
};

View File

@@ -1,30 +0,0 @@
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('users', function (Blueprint $table): void {
$table->string('pending_email')->nullable()->after('email');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('users', function (Blueprint $table): void {
$table->dropColumn('pending_email');
});
}
};

View File

@@ -1,64 +0,0 @@
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
/**
* Run the migrations.
*
* @throws RuntimeException
*/
public function up(): void
{
$duplicateEmails = DB::table('users')
->selectRaw('LOWER(email) as normalized_email')
->selectRaw('COUNT(*) as user_count')
->selectRaw("STRING_AGG(id::text || ' <' || email || '>', ', ' ORDER BY email) as users")
->where('is_placeholder', false)
->groupByRaw('LOWER(email)')
->havingRaw('COUNT(*) > 1')
->orderBy('normalized_email')
->get();
if ($duplicateEmails->isNotEmpty()) {
$duplicateEmailMessage = $duplicateEmails
->take(20)
->map(fn (\stdClass $duplicateEmail): string => sprintf(
'%s (%d users: %s)',
$duplicateEmail->normalized_email,
$duplicateEmail->user_count,
$duplicateEmail->users,
))
->implode('; ');
$remainingDuplicateCount = $duplicateEmails->count() - 20;
$remainingDuplicateMessage = $remainingDuplicateCount > 0
? sprintf('; and %d more duplicate normalized emails', $remainingDuplicateCount)
: '';
throw new RuntimeException(
'Cannot lowercase users.email because doing so would create duplicate non-placeholder user emails and violate the unique index on users.email for non-placeholder users. Resolve these case-insensitive duplicates first: '.
$duplicateEmailMessage.
$remainingDuplicateMessage
);
}
DB::table('users')
->whereRaw('email <> LOWER(email)')
->update([
'email' => DB::raw('LOWER(email)'),
]);
}
/**
* Reverse the migrations.
*/
public function down(): void
{
//
}
};

View File

@@ -68,6 +68,7 @@ RUN apt-get update; \
wget \ wget \
vim \ vim \
git \ git \
gosu \
ncdu \ ncdu \
procps \ procps \
unzip \ unzip \
@@ -193,9 +194,20 @@ COPY --link --chown=${WWWUSER}:${WWWUSER} . .
#COPY --link --chown=${WWWUSER}:${WWWUSER} --from=build ${ROOT}/public public #COPY --link --chown=${WWWUSER}:${WWWUSER} --from=build ${ROOT}/public public
RUN mkdir -p \ RUN mkdir -p \
storage/framework/{sessions,views,cache,testing} \ storage/framework/{sessions,views,cache/data,testing} \
storage/logs \ storage/logs \
bootstrap/cache && chmod -R a+rw storage storage/app/public \
storage/app/private \
bootstrap/cache && \
ln -s ../storage/app/public public/storage && \
chmod -R a+rw storage bootstrap/cache
# OpenShift / arbitrary-UID compatibility: group 0 (root group) gets read+write+execute
# on writable paths. Any UID can run the container if it joins the root group.
# https://docs.openshift.com/container-platform/latest/openshift_images/create-images.html
USER root
RUN chgrp -R 0 storage bootstrap/cache && \
chmod -R g+rwX storage bootstrap/cache
#RUN composer install \ #RUN composer install \
# --classmap-authoritative \ # --classmap-authoritative \

View File

@@ -1,7 +1,6 @@
[program:octane] [program:octane]
process_name = %(program_name)s_%(process_num)s process_name = %(program_name)s_%(process_num)s
command = php %(ENV_ROOT)s/artisan octane:frankenphp --host=0.0.0.0 --port=8000 --admin-port=2019 --caddyfile=%(ENV_ROOT)s/docker/prod/deployment/octane/FrankenPHP/Caddyfile command = php %(ENV_ROOT)s/artisan octane:frankenphp --host=0.0.0.0 --port=8000 --admin-port=2019 --caddyfile=%(ENV_ROOT)s/docker/prod/deployment/octane/FrankenPHP/Caddyfile
user = %(ENV_USER)s
priority = 1 priority = 1
autostart = true autostart = true
autorestart = true autorestart = true
@@ -14,7 +13,6 @@ stderr_logfile_maxbytes = 0
[program:horizon] [program:horizon]
process_name = %(program_name)s_%(process_num)s process_name = %(program_name)s_%(process_num)s
command = php %(ENV_ROOT)s/artisan horizon command = php %(ENV_ROOT)s/artisan horizon
user = %(ENV_USER)s
priority = 3 priority = 3
autostart = %(ENV_WITH_HORIZON)s autostart = %(ENV_WITH_HORIZON)s
autorestart = true autorestart = true
@@ -27,7 +25,6 @@ stopwaitsecs = 3600
[program:scheduler] [program:scheduler]
process_name = %(program_name)s_%(process_num)s process_name = %(program_name)s_%(process_num)s
command = supercronic -overlapping /etc/supercronic/laravel command = supercronic -overlapping /etc/supercronic/laravel
user = %(ENV_USER)s
autostart = %(ENV_WITH_SCHEDULER)s autostart = %(ENV_WITH_SCHEDULER)s
autorestart = true autorestart = true
stdout_logfile = %(ENV_ROOT)s/storage/logs/scheduler.log stdout_logfile = %(ENV_ROOT)s/storage/logs/scheduler.log
@@ -38,7 +35,6 @@ stderr_logfile_maxbytes = 200MB
[program:clear-scheduler-cache] [program:clear-scheduler-cache]
process_name = %(program_name)s_%(process_num)s process_name = %(program_name)s_%(process_num)s
command = php %(ENV_ROOT)s/artisan schedule:clear-cache command = php %(ENV_ROOT)s/artisan schedule:clear-cache
user = %(ENV_USER)s
autostart = %(ENV_WITH_SCHEDULER)s autostart = %(ENV_WITH_SCHEDULER)s
autorestart = false autorestart = false
startsecs = 0 startsecs = 0
@@ -51,7 +47,6 @@ stderr_logfile_maxbytes = 200MB
[program:reverb] [program:reverb]
process_name = %(program_name)s_%(process_num)s process_name = %(program_name)s_%(process_num)s
command = php %(ENV_ROOT)s/artisan reverb:start command = php %(ENV_ROOT)s/artisan reverb:start
user = %(ENV_USER)s
priority = 2 priority = 2
autostart = %(ENV_WITH_REVERB)s autostart = %(ENV_WITH_REVERB)s
autorestart = true autorestart = true

View File

@@ -1,6 +1,240 @@
#!/usr/bin/env sh #!/bin/bash
set -e set -e
# ============================================================================
# Solidtime container entrypoint.
#
# Layout:
# 1. Storage tree bootstrap (idempotent, runs as any user)
# 2. UID/GID remap + chown (root only, controlled by PUID/PGID env vars)
# 3. Pre-flight write test (fails fast with a diagnosis message)
# 4. Privilege drop via gosu, then re-exec self as APP_USER
# 5. Original CONTAINER_MODE routing (runs as APP_USER)
#
# Env vars:
# PUID, PGID UID/GID for the application user. Defaults 1000:1000.
# Only takes effect when the container starts as root
# (which is the image's default — if you set a
# `user:` directive in compose, PUID/PGID are ignored
# and a startup warning is printed).
# SOLIDTIME_DROP_PRIVILEGES auto (default) | never
# auto: if started as root, drop privileges to APP_USER; otherwise just exec.
# never: never drop privileges. Run as whatever UID/GID was started.
# ============================================================================
APP_USER="octane"
APP_PATH="${ROOT:-/var/www/html}"
STORAGE_PATH="${APP_PATH}/storage"
CACHE_PATH="${APP_PATH}/bootstrap/cache"
DEFAULT_UID=1000
DEFAULT_GID=1000
TARGET_UID="${PUID:-${DEFAULT_UID}}"
TARGET_GID="${PGID:-${DEFAULT_GID}}"
DROP_PRIVS="${SOLIDTIME_DROP_PRIVILEGES:-auto}"
WRITABLE_PATHS=(
"${STORAGE_PATH}/framework/cache/data"
"${STORAGE_PATH}/framework/sessions"
"${STORAGE_PATH}/framework/views"
"${STORAGE_PATH}/framework/testing"
"${STORAGE_PATH}/logs"
"${STORAGE_PATH}/app/public"
"${STORAGE_PATH}/app/private"
"${CACHE_PATH}"
)
case "${DROP_PRIVS}" in
never) SHOULD_DROP=0 ;;
auto)
if [ "$(id -u)" = "0" ]; then
SHOULD_DROP=1
else
SHOULD_DROP=0
fi
;;
*)
echo "[entrypoint] ERROR: invalid SOLIDTIME_DROP_PRIVILEGES='${DROP_PRIVS}'" >&2
echo "[entrypoint] Valid values: auto (default), never" >&2
exit 1
;;
esac
# Warn if PUID/PGID are set but the container started non-root. PUID/PGID only
# take effect during the drop-privileges flow, which requires starting as root.
# A common cause is leaving `user:` in the compose file alongside PUID env vars.
if { [ -n "${PUID}" ] || [ -n "${PGID}" ]; } \
&& [ "$(id -u)" != "0" ] \
&& [ "${SOLIDTIME_PRIVILEGES_DROPPED:-0}" != "1" ]; then
cat >&2 <<EOF
[entrypoint] WARNING: PUID/PGID is set but the container started as UID $(id -u) (not root).
[entrypoint] WARNING: PUID/PGID only apply when the entrypoint runs as root and drops privileges.
[entrypoint] WARNING:
[entrypoint] WARNING: To use PUID/PGID: remove any 'user:' directive from your compose file.
[entrypoint] WARNING: To run as a fixed UID: remove PUID/PGID from your env.
[entrypoint] WARNING:
[entrypoint] WARNING: Continuing as UID $(id -u). See:
[entrypoint] WARNING: https://docs.solidtime.io/self-hosting/guides/permissions
EOF
fi
bootstrap_storage_tree() {
mkdir -p "${WRITABLE_PATHS[@]}" 2>/dev/null || return 1
}
# Proactive warning when the existing storage directory is owned by a non-default
# UID (typical on NAS systems where host users aren't UID 1000) and PUID/PGID
# aren't set. Without this nudge, the chown step silently re-owns the files to
# 1000:1000 and the user only discovers the mismatch later when host-side tools
# (backup, file browser, rsync) show unfamiliar ownership.
maybe_warn_ownership_mismatch() {
[ "${SHOULD_DROP}" = "1" ] || return 0
[ -n "${PUID}" ] && return 0
[ -n "${PGID}" ] && return 0
[ -d "${STORAGE_PATH}" ] || return 0
local owner_uid owner_gid
owner_uid="$(stat -c '%u' "${STORAGE_PATH}" 2>/dev/null)" || return 0
owner_gid="$(stat -c '%g' "${STORAGE_PATH}" 2>/dev/null)" || return 0
# Root-owned: probably freshly created by the entrypoint, will be chowned shortly.
[ "${owner_uid}" = "0" ] && return 0
# Already the target: nothing to warn about.
[ "${owner_uid}" = "${TARGET_UID}" ] && return 0
cat >&2 <<EOF
[entrypoint] NOTE: ${STORAGE_PATH} is owned by UID ${owner_uid}:${owner_gid},
[entrypoint] but the container is starting as UID ${TARGET_UID}:${TARGET_GID}.
[entrypoint] Files will be chowned to ${TARGET_UID}:${TARGET_GID} and may
[entrypoint] appear with an unfamiliar owner on the host.
[entrypoint]
[entrypoint] If you want the container to write as UID ${owner_uid} (common
[entrypoint] on Synology / TrueNAS / Unraid where host users aren't UID
[entrypoint] 1000), set in your env and restart:
[entrypoint]
[entrypoint] PUID=${owner_uid}
[entrypoint] PGID=${owner_gid}
[entrypoint]
[entrypoint] More: https://docs.solidtime.io/self-hosting/guides/permissions
EOF
}
print_write_test_failure() {
local owner
owner="$(stat -c '%u:%g' "${STORAGE_PATH}" 2>/dev/null || echo unknown)"
local runtime_uid
local runtime_gid
if [ "$(id -u)" = "0" ] && [ "${SHOULD_DROP}" = "1" ]; then
runtime_uid="${TARGET_UID}"
runtime_gid="${TARGET_GID}"
else
runtime_uid="$(id -u)"
runtime_gid="$(id -g)"
fi
local owner_uid
owner_uid="$(stat -c '%u' "${STORAGE_PATH}" 2>/dev/null || echo 1000)"
local owner_gid
owner_gid="$(stat -c '%g' "${STORAGE_PATH}" 2>/dev/null || echo 1000)"
cat >&2 <<EOF
============================================================
ERROR: Solidtime writable directories are not writable.
Diagnosis:
Container will run as: UID ${runtime_uid}, GID ${runtime_gid}
Storage directory owner: ${owner}
Likely cause: a bind-mounted host directory is owned by a different
user than the container's application user.
Fix on the host:
sudo chown -R ${runtime_uid}:${runtime_gid} <your-bind-mount-path>
Or set PUID/PGID to match the host directory owner:
PUID=${owner_uid}
PGID=${owner_gid}
To run intentionally as root, set:
SOLIDTIME_DROP_PRIVILEGES=never
For more help: https://docs.solidtime.io/self-hosting/guides/permissions
============================================================
EOF
}
write_test_as_user() {
local user="$1"
local script='
set -e
for dir in "$@"; do
test_file="${dir}/.solidtime-write-test"
touch "${test_file}"
rm -f "${test_file}"
done
'
if [ -n "${user}" ]; then
gosu "${user}" sh -c "${script}" sh "${WRITABLE_PATHS[@]}" 2>/dev/null
else
sh -c "${script}" sh "${WRITABLE_PATHS[@]}" 2>/dev/null
fi
}
# ----------------------------------------------------------------------------
# Root preamble: bootstrap, remap, chown, write-test, then drop and re-exec.
# ----------------------------------------------------------------------------
if [ "$(id -u)" = "0" ]; then
if ! bootstrap_storage_tree; then
echo "[entrypoint] ERROR: failed to create storage subdirectories at ${STORAGE_PATH}" >&2
exit 1
fi
if [ "${SHOULD_DROP}" = "1" ]; then
maybe_warn_ownership_mismatch
if [ "${TARGET_UID}" != "${DEFAULT_UID}" ] || [ "${TARGET_GID}" != "${DEFAULT_GID}" ]; then
echo "[entrypoint] Remapping ${APP_USER} to ${TARGET_UID}:${TARGET_GID}"
groupmod -o -g "${TARGET_GID}" "${APP_USER}"
usermod -o -u "${TARGET_UID}" "${APP_USER}"
fi
# Idempotent chown: only fix entries whose owner or group is wrong.
# On large storage volumes (lots of user uploads) this is dramatically
# faster than a blanket `chown -R` every restart. Pattern borrowed from
# docker-library/postgres and linuxserver.io's baseimage.
find "${STORAGE_PATH}" "${CACHE_PATH}" \
\( ! -user "${TARGET_UID}" -o ! -group "${TARGET_GID}" \) \
-exec chown "${TARGET_UID}:${TARGET_GID}" {} + 2>/dev/null || true
if ! write_test_as_user "${APP_USER}"; then
print_write_test_failure
exit 1
fi
exec gosu "${APP_USER}" env SOLIDTIME_PRIVILEGES_DROPPED=1 "$0" "$@"
fi
if ! write_test_as_user ""; then
print_write_test_failure
exit 1
fi
else
if ! bootstrap_storage_tree; then
echo "[entrypoint] WARNING: could not create some storage subdirectories at ${STORAGE_PATH} (will continue if existing tree is writable)" >&2
fi
if ! write_test_as_user ""; then
print_write_test_failure
exit 1
fi
fi
# ----------------------------------------------------------------------------
# Application: runs as APP_USER (or whatever non-root UID was started).
# ----------------------------------------------------------------------------
unset SOLIDTIME_PRIVILEGES_DROPPED
container_mode=${CONTAINER_MODE:-"http"} container_mode=${CONTAINER_MODE:-"http"}
octane_server=${OCTANE_SERVER} octane_server=${OCTANE_SERVER}
auto_db_migrate=${AUTO_DB_MIGRATE:-false} auto_db_migrate=${AUTO_DB_MIGRATE:-false}
@@ -8,14 +242,16 @@ auto_db_migrate=${AUTO_DB_MIGRATE:-false}
initialStuff() { initialStuff() {
echo "Container mode: $container_mode" echo "Container mode: $container_mode"
if [ ${auto_db_migrate} = "true" ]; then if [ "${auto_db_migrate}" = "true" ]; then
echo "Auto database migration enabled." echo "Auto database migration enabled."
php artisan migrate --isolated --force php artisan migrate --isolated --force
fi fi
php artisan storage:link; \ if [ ! -L "${APP_PATH}/public/storage" ]; then
php artisan optimize:clear; \ php artisan storage:link
php artisan optimize; fi
php artisan optimize:clear
php artisan optimize
} }
if [ "$1" != "" ]; then if [ "$1" != "" ]; then

View File

@@ -1,6 +1,5 @@
[supervisord] [supervisord]
nodaemon = true nodaemon = true
user = %(ENV_USER)s
logfile = /var/log/supervisor/supervisord.log logfile = /var/log/supervisor/supervisord.log
pidfile = /var/run/supervisord.pid pidfile = /var/run/supervisord.pid

View File

@@ -1,7 +1,6 @@
[program:horizon] [program:horizon]
process_name = %(program_name)s_%(process_num)s process_name = %(program_name)s_%(process_num)s
command = php %(ENV_ROOT)s/artisan horizon command = php %(ENV_ROOT)s/artisan horizon
user = %(ENV_USER)s
autostart = true autostart = true
autorestart = true autorestart = true
stdout_logfile = /dev/stdout stdout_logfile = /dev/stdout

View File

@@ -1,7 +1,6 @@
[program:reverb] [program:reverb]
process_name = %(program_name)s_%(process_num)s process_name = %(program_name)s_%(process_num)s
command = php %(ENV_ROOT)s/artisan reverb:start command = php %(ENV_ROOT)s/artisan reverb:start
user = %(ENV_USER)s
autostart = true autostart = true
autorestart = true autorestart = true
stdout_logfile = /dev/stdout stdout_logfile = /dev/stdout

View File

@@ -1,7 +1,6 @@
[program:scheduler] [program:scheduler]
process_name = %(program_name)s_%(process_num)s process_name = %(program_name)s_%(process_num)s
command = supercronic -overlapping /etc/supercronic/laravel command = supercronic -overlapping /etc/supercronic/laravel
user = %(ENV_USER)s
autostart = true autostart = true
autorestart = true autorestart = true
stdout_logfile = /dev/stdout stdout_logfile = /dev/stdout
@@ -12,7 +11,6 @@ stderr_logfile_maxbytes = 0
[program:clear-scheduler-cache] [program:clear-scheduler-cache]
process_name = %(program_name)s_%(process_num)s process_name = %(program_name)s_%(process_num)s
command = php %(ENV_ROOT)s/artisan schedule:clear-cache command = php %(ENV_ROOT)s/artisan schedule:clear-cache
user = %(ENV_USER)s
autostart = true autostart = true
autorestart = false autorestart = false
startsecs = 0 startsecs = 0

View File

@@ -1,7 +1,6 @@
[program:worker] [program:worker]
process_name = %(program_name)s_%(process_num)s process_name = %(program_name)s_%(process_num)s
command = %(ENV_WORKER_COMMAND)s command = %(ENV_WORKER_COMMAND)s
user = %(ENV_USER)s
autostart = true autostart = true
autorestart = true autorestart = true
stdout_logfile = /dev/stdout stdout_logfile = /dev/stdout

View File

@@ -1,158 +0,0 @@
import { expect, test } from '../playwright/fixtures';
import { PLAYWRIGHT_BASE_URL, TEST_USER_PASSWORD } from '../playwright/config';
import { getInvitationAcceptUrl } from './utils/mailpit';
import { registerUser } from './utils/members';
// Invitation acceptance flows touch mail delivery + redirects.
test.describe.configure({ timeout: 45000 });
test.describe('invitation accept banners', () => {
test('shows success banner on dashboard when a logged-in registered user accepts an invitation', async ({
page,
browser,
}) => {
const memberId = Math.floor(Math.random() * 100000);
const memberEmail = `success+${memberId}@invite-banner.test`;
// Invitee already has an account and is logged in.
const invitee = await registerUser(browser, 'Banner Success', memberEmail);
// Owner sends the invitation.
await page.goto(PLAYWRIGHT_BASE_URL + '/members');
await page.getByRole('button', { name: 'Invite Member' }).click();
await expect(page.getByPlaceholder('Member Email')).toBeVisible();
await page.getByLabel('Email').fill(memberEmail);
await page.getByRole('button', { name: 'Employee' }).click();
await Promise.all([
page.waitForResponse(
(response) =>
response.url().includes('/invitations') &&
response.request().method() === 'POST' &&
response.status() === 204
),
page.getByRole('button', { name: 'Invite Member', exact: true }).click(),
]);
// Invitee clicks the email link.
const acceptUrl = await getInvitationAcceptUrl(invitee.page.request, memberEmail);
await invitee.page.goto(acceptUrl);
await invitee.page.waitForURL(/\/dashboard$/);
const banner = invitee.page.getByTestId('banner');
await expect(banner).toBeVisible();
await expect(banner).toContainText(
/Great! You have accepted the invitation to join the .* organization\./
);
await invitee.close();
});
test('shows info banner on login screen when a registered-but-logged-out invitee clicks the accept link', async ({
page,
browser,
}) => {
const memberId = Math.floor(Math.random() * 100000);
const memberEmail = `loggedout+${memberId}@invite-banner.test`;
// Invitee has an account, but the context that clicks the link has no session.
const invitee = await registerUser(browser, 'Banner Loggedout', memberEmail);
await invitee.close();
// Owner sends the invitation.
await page.goto(PLAYWRIGHT_BASE_URL + '/members');
await page.getByRole('button', { name: 'Invite Member' }).click();
await expect(page.getByPlaceholder('Member Email')).toBeVisible();
await page.getByLabel('Email').fill(memberEmail);
await page.getByRole('button', { name: 'Employee' }).click();
await Promise.all([
page.waitForResponse(
(response) =>
response.url().includes('/invitations') &&
response.request().method() === 'POST' &&
response.status() === 204
),
page.getByRole('button', { name: 'Invite Member', exact: true }).click(),
]);
// Open the accept link in a fresh browser context (no session).
const context = await browser.newContext();
const inviteePage = await context.newPage();
const acceptUrl = await getInvitationAcceptUrl(inviteePage.request, memberEmail);
await inviteePage.goto(acceptUrl);
await inviteePage.waitForURL(/\/login$/);
const banner = inviteePage.getByTestId('banner');
await expect(banner).toBeVisible();
await expect(banner).toContainText(
/Great! You have accepted the invitation to join the .* organization\. Please log in to access it\./
);
// Logging in lands the invitee on the dashboard — they were already added silently
// by the accept controller, so the inviter's members list shows them.
await inviteePage.getByLabel('Email').fill(memberEmail);
await inviteePage.getByLabel('Password', { exact: true }).fill(TEST_USER_PASSWORD);
await inviteePage.getByRole('button', { name: 'Log in' }).click();
await inviteePage.waitForURL(/\/dashboard/);
await page.goto(PLAYWRIGHT_BASE_URL + '/members');
const memberRow = page.getByRole('row').filter({ hasText: 'Banner Loggedout' });
await expect(memberRow).toBeVisible();
await expect(memberRow.getByText('Employee', { exact: true })).toBeVisible();
await context.close();
});
test('shows info banner on register screen when an unregistered email accepts an invitation, then auto-joins on registration', async ({
page,
browser,
}) => {
const memberId = Math.floor(Math.random() * 100000);
const memberEmail = `info+${memberId}@invite-banner.test`;
// Owner invites an email that has no account yet.
await page.goto(PLAYWRIGHT_BASE_URL + '/members');
await page.getByRole('button', { name: 'Invite Member' }).click();
await expect(page.getByPlaceholder('Member Email')).toBeVisible();
await page.getByLabel('Email').fill(memberEmail);
await page.getByRole('button', { name: 'Employee' }).click();
await Promise.all([
page.waitForResponse(
(response) =>
response.url().includes('/invitations') &&
response.request().method() === 'POST' &&
response.status() === 204
),
page.getByRole('button', { name: 'Invite Member', exact: true }).click(),
]);
// Open the accept link in a fresh browser context (no session).
const context = await browser.newContext();
const inviteePage = await context.newPage();
const acceptUrl = await getInvitationAcceptUrl(inviteePage.request, memberEmail);
await inviteePage.goto(acceptUrl);
await inviteePage.waitForURL(/\/register$/);
const banner = inviteePage.getByTestId('banner');
await expect(banner).toBeVisible();
await expect(banner).toContainText(
/Please create an account to finish joining the .* organization\./
);
// Complete registration — the invitee should auto-join the inviter's org
// (no fresh personal organization is created on top).
await inviteePage.getByLabel('Name').fill('Banner Info');
await inviteePage.getByLabel('Email').fill(memberEmail);
await inviteePage.getByLabel('Password', { exact: true }).fill(TEST_USER_PASSWORD);
await inviteePage.getByLabel('Confirm Password').fill(TEST_USER_PASSWORD);
await inviteePage.getByLabel('I agree to the Terms of').click();
await inviteePage.getByRole('button', { name: 'Register' }).click();
await inviteePage.waitForURL(/\/dashboard/);
await page.goto(PLAYWRIGHT_BASE_URL + '/members');
const memberRow = page.getByRole('row').filter({ hasText: 'Banner Info' });
await expect(memberRow).toBeVisible();
await expect(memberRow.getByText('Employee', { exact: true })).toBeVisible();
await context.close();
});
});

View File

@@ -46,9 +46,7 @@ export async function getInvitationAcceptUrl(
expect(searchResult.messages.length).toBeGreaterThan(0); expect(searchResult.messages.length).toBeGreaterThan(0);
const message = await getMessage(request, searchResult.messages[0].ID); const message = await getMessage(request, searchResult.messages[0].ID);
const acceptUrlMatch = message.HTML.match( const acceptUrlMatch = message.HTML.match(/href="([^"]*team-invitations[^"]*)"/);
/href="([^"]*(?:organization-invitations|team-invitations)[^"]*)"/
);
expect(acceptUrlMatch).toBeTruthy(); expect(acceptUrlMatch).toBeTruthy();
return acceptUrlMatch![1].replace(/&amp;/g, '&'); return acceptUrlMatch![1].replace(/&amp;/g, '&');

View File

@@ -23,7 +23,6 @@ use App\Exceptions\Api\TimeEntryStillRunningApiException;
use App\Exceptions\Api\UserIsAlreadyMemberOfOrganizationApiException; use App\Exceptions\Api\UserIsAlreadyMemberOfOrganizationApiException;
use App\Exceptions\Api\UserIsAlreadyMemberOfProjectApiException; use App\Exceptions\Api\UserIsAlreadyMemberOfProjectApiException;
use App\Exceptions\Api\UserNotPlaceholderApiException; use App\Exceptions\Api\UserNotPlaceholderApiException;
use App\Exceptions\Api\UserResendEmailVerificationNoPendingEmailApiException;
use App\Service\Export\ExportException; use App\Service\Export\ExportException;
return [ return [
@@ -50,7 +49,6 @@ return [
ThisPlaceholderCanNotBeInvitedUseTheMergeToolInsteadException::KEY => 'This placeholder can not be invited use the merge tool instead', ThisPlaceholderCanNotBeInvitedUseTheMergeToolInsteadException::KEY => 'This placeholder can not be invited use the merge tool instead',
InvitationForTheEmailAlreadyExistsApiException::KEY => 'The email has already been invited to the organization. Please wait for the user to accept the invitation or resend the invitation email.', InvitationForTheEmailAlreadyExistsApiException::KEY => 'The email has already been invited to the organization. Please wait for the user to accept the invitation or resend the invitation email.',
OverlappingTimeEntryApiException::KEY => 'Overlapping time entries are not allowed.', OverlappingTimeEntryApiException::KEY => 'Overlapping time entries are not allowed.',
UserResendEmailVerificationNoPendingEmailApiException::KEY => 'Resend email not possible, no pending email.',
], ],
'unknown_error_in_admin_panel' => 'An unknown error occurred. Please check the logs.', 'unknown_error_in_admin_panel' => 'An unknown error occurred. Please check the logs.',
]; ];

2
package-lock.json generated
View File

@@ -7413,7 +7413,7 @@
}, },
"resources/js/packages/ui": { "resources/js/packages/ui": {
"name": "@solidtime/ui", "name": "@solidtime/ui",
"version": "0.0.21", "version": "0.0.17",
"license": "AGPL-3.0", "license": "AGPL-3.0",
"devDependencies": { "devDependencies": {
"@types/chroma-js": "^3.1.0", "@types/chroma-js": "^3.1.0",

View File

@@ -1,38 +1,36 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref } from 'vue'; import { ref, watchEffect } from 'vue';
import { usePage } from '@inertiajs/vue3'; import { usePage } from '@inertiajs/vue3';
const ALLOWED_STYLES = ['success', 'danger', 'info', 'warning'] as const;
type BannerStyle = (typeof ALLOWED_STYLES)[number];
const page = usePage<{ const page = usePage<{
jetstream: {
flash: { flash: {
bannerText?: string; banner: string;
bannerStyle?: string; bannerStyle: string;
};
}; };
}>(); }>();
const rawStyle = page.props.flash?.bannerStyle;
const message = page.props.flash?.bannerText ?? '';
const style: BannerStyle = (ALLOWED_STYLES as readonly string[]).includes(rawStyle ?? '')
? (rawStyle as BannerStyle)
: 'success';
const show = ref(true); const show = ref(true);
const style = ref('success');
const message = ref('');
watchEffect(async () => {
style.value = page.props.jetstream.flash?.bannerStyle || 'success';
message.value = page.props.jetstream.flash?.banner || '';
show.value = true;
});
</script> </script>
<template> <template>
<div> <div>
<div <div v-if="show && message" class="bg-secondary border-b border-border-secondary">
v-if="show && message"
data-testid="banner"
class="bg-secondary border-b border-border-secondary">
<div class="mx-auto py-1 px-3 sm:px-6 lg:px-8"> <div class="mx-auto py-1 px-3 sm:px-6 lg:px-8">
<div class="flex items-center justify-between flex-wrap"> <div class="flex items-center justify-between flex-wrap">
<div class="w-0 flex-1 flex items-center min-w-0"> <div class="w-0 flex-1 flex items-center min-w-0">
<span class="flex"> <span class="flex">
<svg <svg
v-if="style === 'success'" v-if="style == 'success'"
class="h-6 w-6 text-text-secondary" class="h-6 w-6 text-text-secondary"
xmlns="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg"
fill="none" fill="none"
@@ -46,7 +44,7 @@ const show = ref(true);
</svg> </svg>
<svg <svg
v-if="style === 'danger'" v-if="style == 'danger'"
class="h-5 w-5 text-text-primary" class="h-5 w-5 text-text-primary"
xmlns="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg"
fill="none" fill="none"
@@ -58,20 +56,6 @@ const show = ref(true);
stroke-linejoin="round" stroke-linejoin="round"
d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" /> d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
</svg> </svg>
<svg
v-if="style === 'info'"
class="h-6 w-6 text-text-secondary"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor">
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M11.25 11.25l.041-.02a.75.75 0 011.063.852l-.708 2.836a.75.75 0 001.063.853l.041-.021M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-9-3.75h.008v.008H12V8.25z" />
</svg>
</span> </span>
<p class="ms-3 font-medium text-sm text-text-primary truncate"> <p class="ms-3 font-medium text-sm text-text-primary truncate">

View File

@@ -2,7 +2,6 @@
import { Head, Link, useForm, usePage } from '@inertiajs/vue3'; import { Head, Link, useForm, usePage } from '@inertiajs/vue3';
import AuthenticationCard from '@/Components/AuthenticationCard.vue'; import AuthenticationCard from '@/Components/AuthenticationCard.vue';
import AuthenticationCardLogo from '@/Components/AuthenticationCardLogo.vue'; import AuthenticationCardLogo from '@/Components/AuthenticationCardLogo.vue';
import Banner from '@/Components/Banner.vue';
import { Field, FieldLabel, FieldError } from '@/packages/ui/src/field'; import { Field, FieldLabel, FieldError } from '@/packages/ui/src/field';
import PrimaryButton from '@/packages/ui/src/Buttons/PrimaryButton.vue'; import PrimaryButton from '@/packages/ui/src/Buttons/PrimaryButton.vue';
import TextInput from '@/packages/ui/src/Input/TextInput.vue'; import TextInput from '@/packages/ui/src/Input/TextInput.vue';
@@ -37,8 +36,6 @@ const page = usePage<{
<template> <template>
<Head title="Log in" /> <Head title="Log in" />
<Banner />
<AuthenticationCard> <AuthenticationCard>
<template #logo> <template #logo>
<AuthenticationCardLogo /> <AuthenticationCardLogo />

View File

@@ -2,7 +2,6 @@
import { Head, Link, useForm, usePage } from '@inertiajs/vue3'; import { Head, Link, useForm, usePage } from '@inertiajs/vue3';
import AuthenticationCard from '@/Components/AuthenticationCard.vue'; import AuthenticationCard from '@/Components/AuthenticationCard.vue';
import AuthenticationCardLogo from '@/Components/AuthenticationCardLogo.vue'; import AuthenticationCardLogo from '@/Components/AuthenticationCardLogo.vue';
import Banner from '@/Components/Banner.vue';
import Checkbox from '@/packages/ui/src/Input/Checkbox.vue'; import Checkbox from '@/packages/ui/src/Input/Checkbox.vue';
import { Field, FieldLabel, FieldError } from '@/packages/ui/src/field'; import { Field, FieldLabel, FieldError } from '@/packages/ui/src/field';
import PrimaryButton from '@/packages/ui/src/Buttons/PrimaryButton.vue'; import PrimaryButton from '@/packages/ui/src/Buttons/PrimaryButton.vue';
@@ -42,8 +41,6 @@ const page = usePage<{
<template> <template>
<Head title="Register" /> <Head title="Register" />
<Banner />
<AuthenticationCard> <AuthenticationCard>
<template #logo> <template #logo>
<AuthenticationCardLogo /> <AuthenticationCardLogo />

View File

@@ -0,0 +1,448 @@
<script setup lang="ts">
import { computed, ref } from 'vue';
import { router, useForm, usePage } from '@inertiajs/vue3';
import ActionMessage from '@/Components/ActionMessage.vue';
import ActionSection from '@/Components/ActionSection.vue';
import ConfirmationModal from '@/Components/ConfirmationModal.vue';
import DangerButton from '@/packages/ui/src/Buttons/DangerButton.vue';
import DialogModal from '@/packages/ui/src/DialogModal.vue';
import FormSection from '@/Components/FormSection.vue';
import { Field, FieldLabel, FieldError } from '@/packages/ui/src/field';
import PrimaryButton from '@/packages/ui/src/Buttons/PrimaryButton.vue';
import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue';
import SectionBorder from '@/Components/SectionBorder.vue';
import TextInput from '@/packages/ui/src/Input/TextInput.vue';
import type { Organization, OrganizationInvitation, User } from '@/types/models';
import type { Membership, Permissions, Role } from '@/types/jetstream';
import { filterRoles } from '@/utils/roles';
type UserWithMembership = User & { membership: Membership };
const props = defineProps<{
team: Organization;
availableRoles: Role[];
userPermissions: Permissions;
}>();
const users = computed(() => {
return props.team.users as Array<UserWithMembership>;
});
const page = usePage<{
auth: {
user: User;
};
}>();
const addTeamMemberForm = useForm({
email: '',
role: null as string | null,
});
const updateRoleForm = useForm({
role: null as string | null,
});
const leaveTeamForm = useForm({});
const removeTeamMemberForm = useForm({});
const currentlyManagingRole = ref(false);
const managingRoleFor = ref<User | null>(null);
const confirmingLeavingTeam = ref(false);
const teamMemberBeingRemoved = ref<User | null>(null);
const addTeamMember = () => {
addTeamMemberForm.post(route('team-members.store', props.team.id), {
errorBag: 'addTeamMember',
preserveScroll: true,
onSuccess: () => addTeamMemberForm.reset(),
});
};
const cancelTeamInvitation = (invitation: OrganizationInvitation) => {
router.delete(route('team-invitations.destroy', invitation.id), {
preserveScroll: true,
});
};
const manageRole = (teamMember: User & { membership: Membership }) => {
managingRoleFor.value = teamMember;
updateRoleForm.role = teamMember.membership.role;
currentlyManagingRole.value = true;
};
const updateRole = () => {
updateRoleForm.put(
route('team-members.update', {
team: props.team.id,
user: managingRoleFor.value?.id,
}),
{
preserveScroll: true,
onSuccess: () => (currentlyManagingRole.value = false),
}
);
};
const confirmLeavingTeam = () => {
confirmingLeavingTeam.value = true;
};
const leaveTeam = () => {
leaveTeamForm.delete(route('team-members.destroy', [props.team.id, page.props.auth.user.id]));
};
const confirmTeamMemberRemoval = (teamMember: User) => {
teamMemberBeingRemoved.value = teamMember;
};
const removeTeamMember = () => {
removeTeamMemberForm.delete(
route('team-members.destroy', {
team: props.team.id,
user: teamMemberBeingRemoved.value?.id,
}),
{
errorBag: 'removeTeamMember',
preserveScroll: true,
preserveState: true,
onSuccess: () => (teamMemberBeingRemoved.value = null),
}
);
};
const displayableRole = (role: string) => {
return props.availableRoles.find((r) => r.key === role)?.name;
};
</script>
<template>
<div>
<div v-if="userPermissions.canAddTeamMembers">
<SectionBorder />
<!-- Add Organization Member -->
<FormSection @submitted="addTeamMember">
<template #title> Add Organization Member</template>
<template #description>
Add a new member to your organization, allowing them to collaborate with you.
</template>
<template #form>
<div class="col-span-6">
<div class="max-w-xl text-sm text-muted">
Please provide the email address of the person you would like to add to
this organization.
</div>
</div>
<!-- Member Email -->
<Field class="col-span-6 sm:col-span-4">
<FieldLabel for="email">Email</FieldLabel>
<TextInput
id="email"
v-model="addTeamMemberForm.email"
type="email"
class="block w-full" />
<FieldError v-if="addTeamMemberForm.errors.email">{{
addTeamMemberForm.errors.email
}}</FieldError>
</Field>
<!-- Role -->
<div v-if="availableRoles.length > 0" class="col-span-6 lg:col-span-4">
<FieldLabel for="roles">Role</FieldLabel>
<FieldError v-if="addTeamMemberForm.errors.role">{{
addTeamMemberForm.errors.role
}}</FieldError>
<div
class="relative z-0 mt-1 border border-card-border rounded-lg cursor-pointer">
<button
v-for="(role, i) in filterRoles(availableRoles)"
:key="role.key"
type="button"
class="relative px-4 py-3 inline-flex w-full rounded-lg focus:z-10 focus:outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500"
:class="{
'border-t border-card-border focus:border-none rounded-t-none':
i > 0,
'rounded-b-none': i != Object.keys(availableRoles).length - 1,
}"
@click="addTeamMemberForm.role = role.key">
<div
:class="{
'opacity-50':
addTeamMemberForm.role &&
addTeamMemberForm.role != role.key,
}">
<!-- Role Name -->
<div class="flex items-center">
<div
class="text-sm text-text-primary"
:class="{
'font-semibold': addTeamMemberForm.role == role.key,
}">
{{ role.name }}
</div>
<svg
v-if="addTeamMemberForm.role == role.key"
class="ms-2 h-5 w-5 text-green-400"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor">
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</div>
<!-- Role Description -->
<div class="mt-2 text-xs text-muted text-start">
{{ role.description }}
</div>
</div>
</button>
</div>
</div>
</template>
<template #actions>
<ActionMessage :on="addTeamMemberForm.recentlySuccessful" class="me-3">
Added.
</ActionMessage>
<PrimaryButton
:class="{ 'opacity-25': addTeamMemberForm.processing }"
:disabled="addTeamMemberForm.processing">
Add
</PrimaryButton>
</template>
</FormSection>
</div>
<div v-if="team.team_invitations.length > 0 && userPermissions.canAddTeamMembers">
<SectionBorder />
<!-- Organization Member Invitations -->
<ActionSection class="mt-10 sm:mt-0">
<template #title> Pending Organization Invitations</template>
<template #description>
These people have been invited to your organization and have been sent an
invitation email. They may join the organization by accepting the email
invitation.
</template>
<!-- Pending Organization Member Invitation List -->
<template #content>
<div class="space-y-6">
<div
v-for="invitation in team.team_invitations"
:key="invitation.id"
class="flex items-center justify-between">
<div class="text-muted">
{{ invitation.email }}
</div>
<div class="flex items-center">
<!-- Cancel Organization Invitation -->
<button
v-if="userPermissions.canRemoveTeamMembers"
class="cursor-pointer ms-6 text-sm text-red-500 focus:outline-none"
@click="cancelTeamInvitation(invitation)">
Cancel
</button>
</div>
</div>
</div>
</template>
</ActionSection>
</div>
<div v-if="users.length > 0">
<SectionBorder />
<!-- Manage Organization Members -->
<ActionSection class="mt-10 sm:mt-0">
<template #title> Organization Members</template>
<template #description>
All of the people that are part of this organization.
</template>
<!-- Organization Member List -->
<template #content>
<div class="space-y-6">
<div
v-for="user in users"
:key="user.id"
class="flex items-center justify-between">
<div class="flex items-center">
<img
class="w-8 h-8 rounded-full object-cover"
:src="user.profile_photo_url"
:alt="user.name" />
<div class="ms-4 text-text-primary">
{{ user.name }}
</div>
</div>
<div class="flex items-center">
<!-- Manage Organization Member Role -->
<button
v-if="
userPermissions.canUpdateTeamMembers &&
availableRoles.length
"
class="ms-2 text-sm text-gray-400 underline"
@click="manageRole(user)">
{{ displayableRole(user.membership.role) }}
</button>
<div
v-else-if="availableRoles.length"
class="ms-2 text-sm text-gray-400">
{{ displayableRole(user.membership.role) }}
</div>
<!-- Leave Organization -->
<button
v-if="page.props.auth.user.id === user.id"
class="cursor-pointer ms-6 text-sm text-red-500"
@click="confirmLeavingTeam">
Leave
</button>
<!-- Remove Organization Member -->
<button
v-else-if="userPermissions.canRemoveTeamMembers"
class="cursor-pointer ms-6 text-sm text-red-500"
@click="confirmTeamMemberRemoval(user)">
Remove
</button>
</div>
</div>
</div>
</template>
</ActionSection>
</div>
<!-- Role Management Modal -->
<DialogModal :show="currentlyManagingRole" @close="currentlyManagingRole = false">
<template #title> Manage Role</template>
<template #content>
<div v-if="managingRoleFor">
<div
class="relative z-0 mt-1 border border-card-border rounded-lg cursor-pointer">
<button
v-for="(role, i) in availableRoles"
:key="role.key"
type="button"
class="relative px-4 py-3 inline-flex w-full rounded-lg focus:z-10 focus:outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500"
:class="{
'border-t border-card-border focus:border-none rounded-t-none':
i > 0,
'rounded-b-none': i !== Object.keys(availableRoles).length - 1,
}"
@click="updateRoleForm.role = role.key">
<div
:class="{
'opacity-50':
updateRoleForm.role && updateRoleForm.role !== role.key,
}">
<!-- Role Name -->
<div class="flex items-center">
<div
class="text-sm text-muted"
:class="{
'font-semibold': updateRoleForm.role === role.key,
}">
{{ role.name }}
</div>
<svg
v-if="updateRoleForm.role == role.key"
class="ms-2 h-5 w-5 text-green-400"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor">
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</div>
<!-- Role Description -->
<div class="mt-2 text-xs text-muted">
{{ role.description }}
</div>
</div>
</button>
</div>
</div>
</template>
<template #footer>
<SecondaryButton @click="currentlyManagingRole = false"> Cancel </SecondaryButton>
<PrimaryButton
class="ms-3"
:class="{ 'opacity-25': updateRoleForm.processing }"
:disabled="updateRoleForm.processing"
@click="updateRole">
Save
</PrimaryButton>
</template>
</DialogModal>
<!-- Leave Organization Confirmation Modal -->
<ConfirmationModal :show="confirmingLeavingTeam" @close="confirmingLeavingTeam = false">
<template #title> Leave Organization</template>
<template #content> Are you sure you would like to leave this organization? </template>
<template #footer>
<SecondaryButton @click="confirmingLeavingTeam = false"> Cancel </SecondaryButton>
<DangerButton
class="ms-3"
:class="{ 'opacity-25': leaveTeamForm.processing }"
:disabled="leaveTeamForm.processing"
@click="leaveTeam">
Leave
</DangerButton>
</template>
</ConfirmationModal>
<!-- Remove Organization Member Confirmation Modal -->
<ConfirmationModal :show="!!teamMemberBeingRemoved" @close="teamMemberBeingRemoved = null">
<template #title> Remove Organization Member</template>
<template #content>
Are you sure you would like to remove this person from the organization?
</template>
<template #footer>
<SecondaryButton @click="teamMemberBeingRemoved = null"> Cancel </SecondaryButton>
<DangerButton
class="ms-3"
:class="{ 'opacity-25': removeTeamMemberForm.processing }"
:disabled="removeTeamMemberForm.processing"
@click="removeTeamMember">
Remove
</DangerButton>
</template>
</ConfirmationModal>
</div>
</template>

View File

@@ -51,6 +51,9 @@ const updateTeamName = () => {
<div class="text-text-primary"> <div class="text-text-primary">
{{ team.owner.name }} {{ team.owner.name }}
</div> </div>
<div class="text-text-secondary text-sm">
{{ team.owner.email }}
</div>
</div> </div>
</div> </div>
</div> </div>

View File

@@ -35,8 +35,7 @@ watch(open, (isOpen) => {
sortedItems.value = [...props.items].sort((a, b) => { sortedItems.value = [...props.items].sort((a, b) => {
const aSelected = model.value.includes(props.getKeyFromItem(a)) ? 0 : 1; const aSelected = model.value.includes(props.getKeyFromItem(a)) ? 0 : 1;
const bSelected = model.value.includes(props.getKeyFromItem(b)) ? 0 : 1; const bSelected = model.value.includes(props.getKeyFromItem(b)) ? 0 : 1;
if (aSelected !== bSelected) return aSelected - bSelected; return aSelected - bSelected;
return props.getNameForItem(a).localeCompare(props.getNameForItem(b));
}); });
} }
}); });

View File

@@ -22,7 +22,9 @@ export interface Organization {
currency: string; currency: string;
created_at: string | null; created_at: string | null;
updated_at: string | null; updated_at: string | null;
owner: Pick<User, 'id' | 'name' | 'profile_photo_url'>; owner: User;
users: User[];
team_invitations: OrganizationInvitation[];
} }
export interface OrganizationInvitation { export interface OrganizationInvitation {
id: string; id: string;

View File

@@ -29,7 +29,9 @@ export interface Organization {
created_at: string | null; created_at: string | null;
updated_at: string | null; updated_at: string | null;
// relations // relations
owner: Pick<User, 'id' | 'name' | 'profile_photo_url'>; owner: User;
users: User[];
team_invitations: OrganizationInvitation[];
} }
export interface OrganizationInvitation { export interface OrganizationInvitation {

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

View File

@@ -1,8 +1,7 @@
@component('mail::message') @component('mail::message')
{{ __('The API token ":token" will expire in 7 days!', ['token' => $tokenName]) }} {{ __('The API token ":token" expired.', ['token' => $tokenName]) }}
{{ __('Please make sure to create a new API token and use the new one instead before it expires to avoid any disruptions in service.') }}
{{ __('You can create a new API token in your profile:') }} {{ __('You can create a new API token in your profile:') }}

View File

@@ -1,7 +1,8 @@
@component('mail::message') @component('mail::message')
{{ __('The API token ":token" expired.', ['token' => $tokenName]) }} {{ __('The API token ":token" will expire in 7 days!', ['token' => $tokenName]) }}
{{ __('Please make sure to create a new API token and use the new one instead before it expires to avoid any disruptions in service.') }}
{{ __('You can create a new API token in your profile:') }} {{ __('You can create a new API token in your profile:') }}

View File

@@ -1,6 +1,20 @@
@component('mail::message') @component('mail::message')
{{ __('You have been invited to join the :organization organization!', ['organization' => $invitation->organization->name]) }} {{ __('You have been invited to join the :organization organization!', ['organization' => $invitation->organization->name]) }}
@if (Laravel\Fortify\Features::enabled(Laravel\Fortify\Features::registration()))
{{ __('If you do not have an account, you may create one by clicking the button below. After creating an account, you may click the invitation acceptance button in this email to accept the team invitation:') }}
@component('mail::button', ['url' => route('register')])
{{ __('Create Account') }}
@endcomponent
{{ __('If you already have an account, you may accept this invitation by clicking the button below:') }}
@else
{{ __('You may accept this invitation by clicking the button below:') }}
@endif
@component('mail::button', ['url' => $acceptUrl]) @component('mail::button', ['url' => $acceptUrl])
{{ __('Accept Invitation') }} {{ __('Accept Invitation') }}
@endcomponent @endcomponent

View File

@@ -1,9 +0,0 @@
@component('mail::message')
{{ __('Please verify your new email address for your solidtime account.') }}
@component('mail::button', ['url' => $verificationUrl])
{{ __('Verify Email Address') }}
@endcomponent
{{ __('If you did not request this change, you may discard this email.') }}
@endcomponent

View File

@@ -42,10 +42,8 @@ Route::prefix('v1')->name('v1.')->group(static function (): void {
])->group(static function (): void { ])->group(static function (): void {
// Organization routes // Organization routes
Route::name('organizations.')->group(static function (): void { Route::name('organizations.')->group(static function (): void {
Route::post('/organizations', [OrganizationController::class, 'store'])->name('store');
Route::get('/organizations/{organization}', [OrganizationController::class, 'show'])->name('show'); Route::get('/organizations/{organization}', [OrganizationController::class, 'show'])->name('show');
Route::put('/organizations/{organization}', [OrganizationController::class, 'update'])->name('update'); Route::put('/organizations/{organization}', [OrganizationController::class, 'update'])->name('update');
Route::delete('/organizations/{organization}', [OrganizationController::class, 'destroy'])->name('destroy');
}); });
// Member routes // Member routes
@@ -61,9 +59,6 @@ Route::prefix('v1')->name('v1.')->group(static function (): void {
// User routes // User routes
Route::name('users.')->group(static function (): void { Route::name('users.')->group(static function (): void {
Route::get('/users/me', [UserController::class, 'me'])->name('me'); Route::get('/users/me', [UserController::class, 'me'])->name('me');
Route::put('/users/{user}', [UserController::class, 'update'])->name('update');
Route::post('/users/{user}/resend-email-verification', [UserController::class, 'resendEmailVerification'])->name('resend-email-verification');
Route::delete('/users/{user}', [UserController::class, 'destroy'])->name('destroy');
}); });
// Api token routes // Api token routes

View File

@@ -4,8 +4,6 @@ declare(strict_types=1);
use App\Http\Controllers\Web\DashboardController; use App\Http\Controllers\Web\DashboardController;
use App\Http\Controllers\Web\HomeController; use App\Http\Controllers\Web\HomeController;
use App\Http\Controllers\Web\OrganizationInvitationController;
use App\Http\Controllers\Web\UserController;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
use Inertia\Inertia; use Inertia\Inertia;
use Laravel\Jetstream\Jetstream; use Laravel\Jetstream\Jetstream;
@@ -85,14 +83,3 @@ Route::middleware([
})->name('import'); })->name('import');
}); });
Route::get('/team-invitations/{invitation}', [OrganizationInvitationController::class, 'accept'])
->middleware(['signed'])
->name('team-invitations.accept'); // Note: legacy naming
Route::get('/organization-invitations/{invitation}', [OrganizationInvitationController::class, 'accept'])
->middleware(['signed:relative'])
->name('organization-invitations.accept');
Route::get('/users/{user}/verify-email-change', [UserController::class, 'verifyEmailChange'])
->middleware(['auth:web', config('jetstream.auth_session'), 'signed:relative'])
->name('users.verify-email-change');

View File

@@ -88,7 +88,7 @@ class InviteTeamMemberTest extends TestCase
Mail::fake(); Mail::fake();
$placeholder = User::factory()->placeholder()->create(); $placeholder = User::factory()->placeholder()->create();
$owner = User::factory()->withPersonalOrganization()->create(); $owner = User::factory()->withPersonalOrganization()->create();
$placeholderMember = Member::factory()->role(Role::Placeholder)->forOrganization($owner->currentTeam)->forUser($placeholder)->create(); $placeholderMember = Member::factory()->forOrganization($owner->currentTeam)->forUser($placeholder)->create();
$timeEntries = TimeEntry::factory()->forOrganization($owner->currentTeam)->forMember($placeholderMember)->createMany(5); $timeEntries = TimeEntry::factory()->forOrganization($owner->currentTeam)->forMember($placeholderMember)->createMany(5);

View File

@@ -5,12 +5,9 @@ declare(strict_types=1);
namespace Tests\Feature; namespace Tests\Feature;
use App\Enums\Weekday; use App\Enums\Weekday;
use App\Mail\VerifyUpdatedEmailMail;
use App\Models\User; use App\Models\User;
use App\Service\TimezoneService; use App\Service\TimezoneService;
use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\URL;
use Tests\TestCase; use Tests\TestCase;
class ProfileInformationTest extends TestCase class ProfileInformationTest extends TestCase
@@ -33,9 +30,7 @@ class ProfileInformationTest extends TestCase
public function test_profile_information_can_be_updated(): void public function test_profile_information_can_be_updated(): void
{ {
// Arrange // Arrange
$user = User::factory()->create([ $user = User::factory()->create();
'email' => 'test@example.com',
]);
$timezone = app(TimezoneService::class)->getTimezones()[0]; $timezone = app(TimezoneService::class)->getTimezones()[0];
$this->actingAs($user); $this->actingAs($user);
@@ -55,120 +50,4 @@ class ProfileInformationTest extends TestCase
$this->assertEquals($timezone, $user->timezone); $this->assertEquals($timezone, $user->timezone);
$this->assertEquals(Weekday::Sunday, $user->week_start); $this->assertEquals(Weekday::Sunday, $user->week_start);
} }
public function test_email_update_keeps_current_email_verified_until_new_email_is_verified(): void
{
// Arrange
Mail::fake();
$user = User::factory()->create([
'email' => 'current@example.com',
'email_verified_at' => now(),
]);
$timezone = app(TimezoneService::class)->getTimezones()[0];
$this->actingAs($user);
// Act
$response = $this->put('/user/profile-information', [
'name' => 'Test Name',
'email' => 'New.Email@Example.com',
'timezone' => $timezone,
'week_start' => Weekday::Sunday->value,
]);
// Assert
$response->assertValid(errorBag: 'updateProfileInformation');
$user = $user->fresh();
$this->assertEquals('current@example.com', $user->email);
$this->assertEquals('new.email@example.com', $user->pending_email);
$this->assertNotNull($user->email_verified_at);
Mail::assertSent(VerifyUpdatedEmailMail::class, function (VerifyUpdatedEmailMail $mail): bool {
return $mail->hasTo('new.email@example.com') && $mail->email === 'new.email@example.com';
});
}
public function test_pending_email_can_be_verified(): void
{
// Arrange
$user = User::factory()->create([
'email' => 'current@example.com',
'pending_email' => 'new.email@example.com',
]);
$this->actingAs($user);
$verificationUrl = URL::temporarySignedRoute(
'users.verify-email-change',
now()->addMinutes(60),
[
'user' => $user->getKey(),
'email' => 'new.email@example.com',
],
false
);
// Act
$response = $this->get($verificationUrl);
// Assert
$response->assertRedirect(route('dashboard', [
'bannerStyle' => 'success',
'bannerText' => 'Your email address has been updated successfully.',
]));
$user = $user->fresh();
$this->assertEquals('new.email@example.com', $user->email);
$this->assertNull($user->pending_email);
$this->assertNotNull($user->email_verified_at);
}
public function test_profile_update_does_not_clear_pending_email_when_email_is_unchanged(): void
{
// Arrange
$user = User::factory()->create([
'email' => 'current@example.com',
'pending_email' => 'new.email@example.com',
]);
$timezone = app(TimezoneService::class)->getTimezones()[0];
$this->actingAs($user);
// Act
$response = $this->put('/user/profile-information', [
'name' => 'Updated Name',
'email' => 'current@example.com',
'timezone' => $timezone,
'week_start' => Weekday::Sunday->value,
]);
// Assert
$response->assertValid(errorBag: 'updateProfileInformation');
$user = $user->fresh();
$this->assertEquals('Updated Name', $user->name);
$this->assertEquals('current@example.com', $user->email);
$this->assertEquals('new.email@example.com', $user->pending_email);
}
public function test_stale_pending_email_verification_link_is_rejected(): void
{
// Arrange
$user = User::factory()->create([
'email' => 'current@example.com',
'pending_email' => 'newer@example.com',
]);
$this->actingAs($user);
$verificationUrl = URL::temporarySignedRoute(
'users.verify-email-change',
now()->addMinutes(60),
[
'user' => $user->getKey(),
'email' => 'older@example.com',
],
false
);
// Act
$response = $this->get($verificationUrl);
// Assert
$response->assertForbidden();
$user = $user->fresh();
$this->assertEquals('current@example.com', $user->email);
$this->assertEquals('newer@example.com', $user->pending_email);
}
} }

View File

@@ -8,21 +8,21 @@ use App\Enums\Role;
use App\Enums\Weekday; use App\Enums\Weekday;
use App\Events\NewsletterRegistered; use App\Events\NewsletterRegistered;
use App\Models\Member; use App\Models\Member;
use App\Models\OrganizationInvitation;
use App\Models\User; use App\Models\User;
use App\Providers\RouteServiceProvider; use App\Providers\RouteServiceProvider;
use App\Service\IpLookup\IpLookupResponseDto; use App\Service\IpLookup\IpLookupResponseDto;
use App\Service\IpLookup\IpLookupServiceContract; use App\Service\IpLookup\IpLookupServiceContract;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
use Laravel\Fortify\Features; use Laravel\Fortify\Features;
use Laravel\Jetstream\Jetstream; use Laravel\Jetstream\Jetstream;
use Tests\TestCaseWithDatabase; use Tests\TestCase;
use TiMacDonald\Log\LogEntry;
class RegistrationTest extends TestCaseWithDatabase class RegistrationTest extends TestCase
{ {
use RefreshDatabase;
public function test_registration_screen_can_be_rendered(): void public function test_registration_screen_can_be_rendered(): void
{ {
if (! Features::enabled(Features::registration())) { if (! Features::enabled(Features::registration())) {
@@ -346,82 +346,4 @@ class RegistrationTest extends TestCaseWithDatabase
$this->assertAuthenticated(); $this->assertAuthenticated();
$response->assertRedirect(RouteServiceProvider::HOME); $response->assertRedirect(RouteServiceProvider::HOME);
} }
public function test_registration_does_not_create_private_organization_if_invite_was_accepted_for_the_email_with_the_registration_email(): void
{
// Arrange
$user = $this->createUserWithPermission();
$organizationInvitation = OrganizationInvitation::factory()
->forOrganization($user->organization)
->role(Role::Employee)
->accepted()
->create([
'email' => 'test@example.com',
]);
// Act
$response = $this->post('/register', [
'name' => 'Test User',
'email' => 'test@example.com',
'password' => 'password',
'password_confirmation' => 'password',
'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature(),
]);
$this->assertAuthenticated();
$response->assertRedirect(RouteServiceProvider::HOME);
$newUser = User::where('email', 'test@example.com')->first();
$this->assertNotNull($newUser);
$this->assertDatabaseMissing(OrganizationInvitation::class, [
'email' => 'test@example.com',
]);
$organizations = $newUser->organizations;
$this->assertCount(1, $organizations);
$this->assertSame($user->organization->id, $organizations->first()->id);
}
public function test_registration_logs_and_skips_accepted_invitation_with_invalid_role(): void
{
// Arrange
$user = $this->createUserWithPermission();
$organizationInvitation = OrganizationInvitation::factory()
->forOrganization($user->organization)
->accepted()
->create([
'email' => 'test@example.com',
'role' => 'invalid-role',
]);
// Act
$response = $this->post('/register', [
'name' => 'Test User',
'email' => 'test@example.com',
'password' => 'password',
'password_confirmation' => 'password',
'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature(),
]);
// Assert
$this->assertAuthenticated();
$response->assertRedirect(RouteServiceProvider::HOME);
Log::assertLogged(fn (LogEntry $log) => $log->level === 'error'
&& $log->message === 'Invalid role in invitation'
&& $log->context === [
'invitation' => $organizationInvitation->getKey(),
'role' => 'invalid-role',
]);
$newUser = User::where('email', 'test@example.com')->firstOrFail();
$this->assertDatabaseHas(OrganizationInvitation::class, [
'id' => $organizationInvitation->getKey(),
'email' => 'test@example.com',
'role' => 'invalid-role',
]);
$this->assertDatabaseMissing(Member::class, [
'organization_id' => $user->organization->getKey(),
'user_id' => $newUser->getKey(),
]);
$organizations = $newUser->organizations;
$this->assertCount(1, $organizations);
$this->assertNotSame($user->organization->id, $organizations->first()->id);
}
} }

View File

@@ -38,7 +38,7 @@ abstract class TestCase extends BaseTestCase
protected function mockPrivateStorage(): void protected function mockPrivateStorage(): void
{ {
Storage::fake(config('filesystems.private')); Storage::fake(config('filesystems.default'));
} }
protected function mockPublicStorage(): void protected function mockPublicStorage(): void
@@ -50,7 +50,6 @@ abstract class TestCase extends BaseTestCase
{ {
// Note: It is necessary to clear the permission cache after each test, since the "scoped singletons" are not reset between tests. // Note: It is necessary to clear the permission cache after each test, since the "scoped singletons" are not reset between tests.
app(PermissionStore::class)->clear(); app(PermissionStore::class)->clear();
PermissionStore::resetCustomRoles();
parent::tearDown(); parent::tearDown();
} }

View File

@@ -8,7 +8,6 @@ use App\Enums\Role;
use App\Models\Member; use App\Models\Member;
use App\Models\Organization; use App\Models\Organization;
use App\Models\User; use App\Models\User;
use App\Service\PermissionStore;
use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str; use Illuminate\Support\Str;
@@ -27,7 +26,6 @@ abstract class TestCaseWithDatabase extends TestCase
$roleName = 'custom-test-'.Str::uuid(); $roleName = 'custom-test-'.Str::uuid();
Jetstream::role($roleName, 'Custom Test', $permissions) Jetstream::role($roleName, 'Custom Test', $permissions)
->description('Role custom for testing'); ->description('Role custom for testing');
PermissionStore::registerCustomRole($roleName, $permissions);
$user = User::factory()->create(); $user = User::factory()->create();
if ($isOwner) { if ($isOwner) {
$organization = Organization::factory()->withOwner($user)->create(); $organization = Organization::factory()->withOwner($user)->create();

View File

@@ -5,15 +5,9 @@ declare(strict_types=1);
namespace Tests\Unit\Endpoint\Api\V1; namespace Tests\Unit\Endpoint\Api\V1;
use App\Enums\Role; use App\Enums\Role;
use App\Events\AfterCreateOrganization;
use App\Http\Controllers\Api\V1\OrganizationController; use App\Http\Controllers\Api\V1\OrganizationController;
use App\Models\Member;
use App\Models\Organization; use App\Models\Organization;
use App\Service\BillableRateService; use App\Service\BillableRateService;
use App\Service\IpLookup\IpLookupResponseDto;
use App\Service\IpLookup\IpLookupServiceContract;
use Illuminate\Support\Facades\Event;
use Illuminate\Testing\Fluent\AssertableJson;
use Laravel\Passport\Passport; use Laravel\Passport\Passport;
use Mockery\MockInterface; use Mockery\MockInterface;
use PHPUnit\Framework\Attributes\UsesClass; use PHPUnit\Framework\Attributes\UsesClass;
@@ -99,121 +93,6 @@ class OrganizationEndpointTest extends ApiEndpointTestAbstract
$response->assertJsonPath('data.billable_rate', null); $response->assertJsonPath('data.billable_rate', null);
} }
public function test_store_endpoint_creates_new_organization(): void
{
// Arrange
$data = $this->createUserWithPermission();
$organizationFake = Organization::factory()->make();
Event::fake([
AfterCreateOrganization::class,
]);
Passport::actingAs($data->user);
// Act
$response = $this->postJson(route('api.v1.organizations.store'), [
'name' => $organizationFake->name,
]);
// Assert
$response->assertStatus(201);
$response->assertJson(fn (AssertableJson $json) => $json
->has('data')
->where('data.name', $organizationFake->name)
->where('data.is_personal', false)
->where('data.currency', config('app.localization.default_currency'))
->etc()
);
/** @var Organization $newOrganization */
$newOrganization = Organization::query()->where('name', $organizationFake->name)->firstOrFail();
$this->assertTrue($newOrganization->owner->is($data->user));
$this->assertSame($newOrganization->getKey(), $data->user->fresh()->current_team_id);
$this->assertDatabaseHas(Member::class, [
'organization_id' => $newOrganization->getKey(),
'user_id' => $data->user->getKey(),
'role' => Role::Owner->value,
]);
Event::assertDispatched(AfterCreateOrganization::class, function (AfterCreateOrganization $event) use ($newOrganization): bool {
return $event->organization->is($newOrganization);
});
}
public function test_store_endpoint_uses_ip_lookup_currency_for_new_organization(): void
{
// Arrange
$data = $this->createUserWithPermission();
$this->mock(IpLookupServiceContract::class, function (MockInterface $mock): void {
$mock->shouldReceive('lookup')
->once()
->andReturn(new IpLookupResponseDto(null, null, 'USD'));
});
Passport::actingAs($data->user);
// Act
$response = $this->postJson(route('api.v1.organizations.store'), [
'name' => 'Test Organization',
]);
// Assert
$response->assertStatus(201);
$response->assertJsonPath('data.currency', 'USD');
$this->assertDatabaseHas(Organization::class, [
'name' => 'Test Organization',
'currency' => 'USD',
'user_id' => $data->user->getKey(),
'personal_team' => false,
]);
}
public function test_store_endpoint_fails_if_name_is_missing(): void
{
// Arrange
$data = $this->createUserWithPermission();
Passport::actingAs($data->user);
// Act
$response = $this->postJson(route('api.v1.organizations.store'), []);
// Assert
$response->assertStatus(422);
$response->assertJsonValidationErrors(['name']);
$this->assertDatabaseCount(Organization::class, 1);
}
public function test_store_endpoint_fails_if_name_is_not_a_string(): void
{
// Arrange
$data = $this->createUserWithPermission();
Passport::actingAs($data->user);
// Act
$response = $this->postJson(route('api.v1.organizations.store'), [
'name' => ['Test Organization'],
]);
// Assert
$response->assertStatus(422);
$response->assertJsonValidationErrors(['name']);
$this->assertDatabaseCount(Organization::class, 1);
}
public function test_store_endpoint_fails_if_name_is_too_long(): void
{
// Arrange
$data = $this->createUserWithPermission();
Passport::actingAs($data->user);
// Act
$response = $this->postJson(route('api.v1.organizations.store'), [
'name' => str_repeat('a', 256),
]);
// Assert
$response->assertStatus(422);
$response->assertJsonValidationErrors(['name']);
$this->assertDatabaseCount(Organization::class, 1);
}
public function test_update_endpoint_fails_if_user_has_no_permission_to_update_organizations(): void public function test_update_endpoint_fails_if_user_has_no_permission_to_update_organizations(): void
{ {
// Arrange // Arrange
@@ -381,51 +260,4 @@ class OrganizationEndpointTest extends ApiEndpointTestAbstract
'billable_rate' => $organizationFake->billable_rate, 'billable_rate' => $organizationFake->billable_rate,
]); ]);
} }
public function test_delete_endpoint_if_user_does_not_have_permission(): void
{
// Arrange
$data = $this->createUserWithPermission();
Passport::actingAs($data->user);
// Act
$response = $this->deleteJson(route('api.v1.organizations.destroy', [$data->organization->getKey()]));
// Assert
$response->assertForbidden();
}
public function test_delete_endpoint_fails_with_not_found_if_id_is_not_uuid(): void
{
// Arrange
$data = $this->createUserWithPermission([
'organizations:delete',
]);
Passport::actingAs($data->user);
// Act
$response = $this->deleteJson(route('api.v1.organizations.destroy', ['not-uuid']));
// Assert
$response->assertNotFound();
}
public function test_delete_endpoint_can_delete_organization(): void
{
// Arrange
$this->mockPrivateStorage();
$data = $this->createUserWithPermission([
'organizations:delete',
]);
Passport::actingAs($data->user);
// Act
$response = $this->deleteJson(route('api.v1.organizations.destroy', [$data->organization->getKey()]));
// Assert
$response->assertNoContent();
$this->assertDatabaseMissing(Organization::class, [
'id' => $data->organization->getKey(),
]);
}
} }

View File

@@ -4,11 +4,6 @@ declare(strict_types=1);
namespace Tests\Unit\Endpoint\Api\V1; namespace Tests\Unit\Endpoint\Api\V1;
use App\Enums\Weekday;
use App\Mail\VerifyUpdatedEmailMail;
use App\Models\User;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use Laravel\Passport\Passport; use Laravel\Passport\Passport;
class UserEndpointTest extends ApiEndpointTestAbstract class UserEndpointTest extends ApiEndpointTestAbstract
@@ -45,349 +40,4 @@ class UserEndpointTest extends ApiEndpointTestAbstract
], ],
]); ]);
} }
public function test_update_changes_user_name_timezone_and_week_start(): void
{
// Arrange
$data = $this->createUserWithPermission();
Passport::actingAs($data->user);
// Act
$response = $this->putJson(route('api.v1.users.update', $data->user->getKey()), [
'name' => 'Updated Name',
'timezone' => 'America/New_York',
'week_start' => Weekday::Sunday->value,
]);
// Assert
$response->assertSuccessful();
$response->assertJson([
'data' => [
'id' => $data->user->getKey(),
'name' => 'Updated Name',
'timezone' => 'America/New_York',
'week_start' => Weekday::Sunday->value,
],
]);
$user = $data->user->fresh();
$this->assertSame('Updated Name', $user->name);
$this->assertSame('America/New_York', $user->timezone);
$this->assertSame(Weekday::Sunday, $user->week_start);
}
public function test_update_does_not_change_user_fields_that_are_not_given(): void
{
// Arrange
$data = $this->createUserWithPermission();
$data->user->name = 'Original Name';
$data->user->timezone = 'Europe/Vienna';
$data->user->week_start = Weekday::Monday;
$data->user->save();
Passport::actingAs($data->user);
// Act
$response = $this->putJson(route('api.v1.users.update', $data->user->getKey()), []);
// Assert
$response->assertSuccessful();
$response->assertJson([
'data' => [
'id' => $data->user->getKey(),
'name' => 'Original Name',
'timezone' => 'Europe/Vienna',
'week_start' => Weekday::Monday->value,
],
]);
$user = $data->user->fresh();
$this->assertSame('Original Name', $user->name);
$this->assertSame('Europe/Vienna', $user->timezone);
$this->assertSame(Weekday::Monday, $user->week_start);
}
public function test_update_email_stores_pending_email_and_sends_verification_email(): void
{
// Arrange
Mail::fake();
$data = $this->createUserWithPermission();
$data->user->email = 'current@example.com';
$data->user->email_verified_at = now();
$data->user->save();
Passport::actingAs($data->user);
// Act
$response = $this->putJson(route('api.v1.users.update', $data->user->getKey()), [
'email' => 'New.Email@Example.com',
]);
// Assert
$response->assertSuccessful();
$user = $data->user->fresh();
$this->assertSame('current@example.com', $user->email);
$this->assertSame('new.email@example.com', $user->pending_email);
$this->assertNotNull($user->email_verified_at);
Mail::assertSent(VerifyUpdatedEmailMail::class, function (VerifyUpdatedEmailMail $mail): bool {
return $mail->hasTo('new.email@example.com') && $mail->email === 'new.email@example.com';
});
}
public function test_resend_email_verification_sends_pending_email_verification_email(): void
{
// Arrange
Mail::fake();
$data = $this->createUserWithPermission();
$data->user->pending_email = 'new.email@example.com';
$data->user->save();
Passport::actingAs($data->user);
// Act
$response = $this->postJson(route('api.v1.users.resend-email-verification', $data->user->getKey()));
// Assert
$response->assertNoContent();
Mail::assertNotSent(VerifyUpdatedEmailMail::class);
Mail::assertQueued(VerifyUpdatedEmailMail::class, function (VerifyUpdatedEmailMail $mail): bool {
return $mail->hasTo('new.email@example.com') && $mail->email === 'new.email@example.com';
});
}
public function test_resend_email_verification_fails_if_given_id_is_not_the_authenticated_user(): void
{
// Arrange
Mail::fake();
$data = $this->createUserWithPermission();
$otherData = $this->createUserWithPermission();
Passport::actingAs($otherData->user);
// Act
$response = $this->postJson(route('api.v1.users.resend-email-verification', $data->user->getKey()));
// Assert
$response->assertForbidden();
Mail::assertNotSent(VerifyUpdatedEmailMail::class);
Mail::assertNotQueued(VerifyUpdatedEmailMail::class);
}
public function test_resend_email_verification_fails_without_pending_email(): void
{
// Arrange
$data = $this->createUserWithPermission();
$data->user->pending_email = null;
$data->user->save();
Passport::actingAs($data->user);
// Act
$response = $this->postJson(route('api.v1.users.resend-email-verification', $data->user->getKey()));
// Assert
$response->assertStatus(400);
$response->assertJson([
'error' => true,
'key' => 'user_resend_email_verification_no_pending_email',
'message' => 'Resend email not possible, no pending email.',
]);
Mail::assertNotSent(VerifyUpdatedEmailMail::class);
Mail::assertNotQueued(VerifyUpdatedEmailMail::class);
}
public function test_update_changes_user_photo_from_base64_encoded_image(): void
{
// Arrange
$data = $this->createUserWithPermission();
$photoDisk = (string) config('jetstream.profile_photo_disk', 'public');
$previousPhotoPath = 'profile-photos/previous.png';
$photo = file_get_contents(resource_path('testfiles/test.png'));
$this->assertIsString($photo);
Storage::fake($photoDisk);
Storage::disk($photoDisk)->put($previousPhotoPath, 'previous photo');
$data->user->profile_photo_path = $previousPhotoPath;
$data->user->save();
Passport::actingAs($data->user);
// Act
$response = $this->putJson(route('api.v1.users.update', $data->user->getKey()), [
'photo' => base64_encode($photo),
]);
// Assert
$response->assertSuccessful();
$user = $data->user->fresh();
$this->assertNotNull($user->profile_photo_path);
$this->assertNotSame($previousPhotoPath, $user->profile_photo_path);
$this->assertStringStartsWith('profile-photos/', $user->profile_photo_path);
$this->assertStringEndsWith('.png', $user->profile_photo_path);
Storage::disk($photoDisk)->assertExists($user->profile_photo_path);
Storage::disk($photoDisk)->assertMissing($previousPhotoPath);
$this->assertSame($photo, Storage::disk($photoDisk)->get($user->profile_photo_path));
}
public function test_update_fails_if_name_is_not_a_string(): void
{
// Arrange
$data = $this->createUserWithPermission();
Passport::actingAs($data->user);
// Act
$response = $this->putJson(route('api.v1.users.update', $data->user->getKey()), [
'name' => 123,
]);
// Assert
$response->assertUnprocessable();
$response->assertJsonValidationErrors(['name']);
}
public function test_update_fails_if_name_is_too_long(): void
{
// Arrange
$data = $this->createUserWithPermission();
Passport::actingAs($data->user);
// Act
$response = $this->putJson(route('api.v1.users.update', $data->user->getKey()), [
'name' => str_repeat('a', 256),
]);
// Assert
$response->assertUnprocessable();
$response->assertJsonValidationErrors(['name']);
}
public function test_update_fails_if_timezone_is_invalid(): void
{
// Arrange
$data = $this->createUserWithPermission();
Passport::actingAs($data->user);
// Act
$response = $this->putJson(route('api.v1.users.update', $data->user->getKey()), [
'timezone' => 'not-a-timezone',
]);
// Assert
$response->assertUnprocessable();
$response->assertJsonValidationErrors(['timezone']);
}
public function test_update_fails_if_week_start_is_invalid(): void
{
// Arrange
$data = $this->createUserWithPermission();
Passport::actingAs($data->user);
// Act
$response = $this->putJson(route('api.v1.users.update', $data->user->getKey()), [
'week_start' => 'not-a-weekday',
]);
// Assert
$response->assertUnprocessable();
$response->assertJsonValidationErrors(['week_start']);
}
public function test_update_fails_if_photo_is_not_a_string(): void
{
// Arrange
$data = $this->createUserWithPermission();
Passport::actingAs($data->user);
// Act
$response = $this->putJson(route('api.v1.users.update', $data->user->getKey()), [
'photo' => 123,
]);
// Assert
$response->assertUnprocessable();
$response->assertJsonValidationErrors(['photo']);
}
public function test_update_fails_if_photo_is_not_base64_encoded(): void
{
// Arrange
$data = $this->createUserWithPermission();
Passport::actingAs($data->user);
// Act
$response = $this->putJson(route('api.v1.users.update', $data->user->getKey()), [
'photo' => 'not base64 encoded',
]);
// Assert
$response->assertUnprocessable();
$response->assertJsonValidationErrors(['photo']);
}
public function test_update_fails_if_photo_is_not_a_jpg_or_png(): void
{
// Arrange
$data = $this->createUserWithPermission();
$csv = file_get_contents(resource_path('testfiles/generic_projects_import_test_1.csv'));
$this->assertIsString($csv);
Passport::actingAs($data->user);
// Act
$response = $this->putJson(route('api.v1.users.update', $data->user->getKey()), [
'photo' => base64_encode($csv),
]);
// Assert
$response->assertUnprocessable();
$response->assertJsonValidationErrors(['photo']);
}
public function test_delete_fails_if_given_user_is_not_the_authenticated_user(): void
{
// Arrange
$data = $this->createUserWithPermission();
$otherData = $this->createUserWithPermission();
Passport::actingAs($otherData->user);
// Act
$response = $this->deleteJson(route('api.v1.users.destroy', $data->user->getKey()));
// Assert
$response->assertForbidden();
}
public function test_delete_fails_if_not_authenticated(): void
{
// Arrange
$data = $this->createUserWithPermission();
// Act
$response = $this->deleteJson(route('api.v1.users.destroy', $data->user->getKey()));
// Assert
$response->assertUnauthorized();
}
public function test_delete_fails_if_user_does_not_exist(): void
{
// Arrange
$data = $this->createUserWithPermission();
Passport::actingAs($data->user);
// Act
$response = $this->deleteJson(route('api.v1.users.destroy', 'not-valid'));
// Assert
$response->assertNotFound();
}
public function test_delete_removes_user(): void
{
// Arrange
$data = $this->createUserWithPermission();
Passport::actingAs($data->user);
// Act
$response = $this->deleteJson(route('api.v1.users.destroy', $data->user->getKey()));
// Assert
$response->assertNoContent();
$this->assertDatabaseMissing(User::class, ['id' => $data->user->getKey()]);
}
} }

View File

@@ -1,254 +0,0 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Endpoint\Web;
use App\Enums\Role;
use App\Http\Controllers\Web\OrganizationInvitationController;
use App\Models\Member;
use App\Models\OrganizationInvitation;
use App\Models\User;
use App\Service\MemberService;
use Illuminate\Support\Facades\URL;
use PHPUnit\Framework\Attributes\CoversClass;
#[CoversClass(OrganizationInvitationController::class)]
#[CoversClass(MemberService::class)]
class OrganizationInvitationEndpointTest extends EndpointTestAbstract
{
public function test_legacy_url_still_works(): void
{
// Arrange
$user = $this->createUserWithPermission();
$invitation = OrganizationInvitation::factory()
->forOrganization($user->organization)
->create();
// Act
$acceptUrl = URL::temporarySignedRoute(
'team-invitations.accept',
now()->addMinutes(60),
[$invitation->getKey()]
);
$response = $this->get($acceptUrl);
// Assert
$response->assertValid();
$response->assertRedirect(route('register'));
$response->assertSessionHas('bannerText', 'Please create an account to finish joining the '.$user->organization->name.' organization.');
$response->assertSessionHas('bannerStyle', 'info');
$invitation->refresh();
$this->assertNotNull($invitation->accepted_at);
}
public function test_can_accept_invitation_without_an_account_with_the_email_address_and_redirects_to_registration(): void
{
// Arrange
$user = $this->createUserWithPermission();
$invitation = OrganizationInvitation::factory()
->forOrganization($user->organization)
->create();
// Act
$acceptUrl = URL::to(URL::temporarySignedRoute(
'organization-invitations.accept',
now()->addMinutes(60),
[$invitation->getKey()],
false
));
$response = $this->get($acceptUrl);
// Assert
$response->assertValid();
$response->assertRedirect(route('register'));
$response->assertSessionHas('bannerText', 'Please create an account to finish joining the '.$user->organization->name.' organization.');
$response->assertSessionHas('bannerStyle', 'info');
$invitation->refresh();
$this->assertNotNull($invitation->accepted_at);
}
public function test_can_accept_invitation_with_an_account_with_the_email_address_and_redirects_to_dashboard(): void
{
// Arrange
$user = $this->createUserWithPermission();
$user2 = $this->createUserWithPermission();
$invitation = OrganizationInvitation::factory()
->forOrganization($user->organization)
->create([
'role' => Role::Employee->value,
'email' => $user2->user->email,
]);
$this->actingAs($user2->user);
// Act
$acceptUrl = URL::to(URL::temporarySignedRoute(
'organization-invitations.accept',
now()->addMinutes(60),
[$invitation->getKey()],
false
));
$response = $this->get($acceptUrl);
// Assert
$response->assertValid();
$response->assertRedirect(route('dashboard'));
$response->assertSessionHas('bannerText', 'Great! You have accepted the invitation to join the '.$user->organization->name.' organization.');
$response->assertSessionHas('bannerStyle', 'success');
$this->assertDatabaseHas(Member::class, [
'user_id' => $user2->user->getKey(),
'organization_id' => $user->organization->getKey(),
'role' => Role::Employee->value,
]);
$this->assertDatabaseMissing(OrganizationInvitation::class, [
'id' => $invitation->getKey(),
]);
}
public function test_accepting_invitation_while_logged_out_redirects_to_login(): void
{
// Arrange
$user = $this->createUserWithPermission();
$invitee = User::factory()->create([
'email' => 'invitee@example.com',
]);
$invitation = OrganizationInvitation::factory()
->forOrganization($user->organization)
->create([
'role' => Role::Employee->value,
'email' => $invitee->email,
]);
// Act (no actingAs — request is unauthenticated)
$acceptUrl = URL::to(URL::temporarySignedRoute(
'organization-invitations.accept',
now()->addMinutes(60),
[$invitation->getKey()],
false
));
$response = $this->get($acceptUrl);
// Assert
$response->assertValid();
$response->assertRedirect(route('login'));
$response->assertSessionHas('bannerText', 'Great! You have accepted the invitation to join the '.$user->organization->name.' organization. Please log in to access it.');
$response->assertSessionHas('bannerStyle', 'success');
// Member was added silently — invitation is consumed.
$this->assertDatabaseHas(Member::class, [
'user_id' => $invitee->getKey(),
'organization_id' => $user->organization->getKey(),
'role' => Role::Employee->value,
]);
$this->assertDatabaseMissing(OrganizationInvitation::class, [
'id' => $invitation->getKey(),
]);
}
public function test_fails_if_user_is_already_member_of_the_organization(): void
{
// Arrange
$user = $this->createUserWithPermission();
$user2 = $this->createUserWithPermission();
$invitation = OrganizationInvitation::factory()
->forOrganization($user->organization)
->create([
'role' => Role::Employee->value,
'email' => $user2->user->email,
]);
Member::factory()->forOrganization($user->organization)->forUser($user2->user)->create();
$this->actingAs($user2->user);
// Act
$acceptUrl = URL::to(URL::temporarySignedRoute(
'organization-invitations.accept',
now()->addMinutes(60),
[$invitation->getKey()],
false
));
$response = $this->get($acceptUrl);
// Assert
$response->assertValid();
$response->assertRedirect(route('dashboard'));
$response->assertSessionHas('bannerText', 'You are already a member of the '.$user->organization->name.' organization.');
$response->assertSessionHas('bannerStyle', 'danger');
}
public function test_accepting_invitation_with_existing_account_migrates_data_of_placeholder_users_with_same_email_to_new_member(): void
{
// Arrange
$user = $this->createUserWithPermission();
$user2 = $this->createUserWithPermission();
$invitation = OrganizationInvitation::factory()
->forOrganization($user->organization)
->create([
'role' => Role::Employee->value,
'email' => $user2->user->email,
]);
$placeholder1 = User::factory()->placeholder()->create([
'email' => $user2->user->email,
]);
$placeholder1Member = Member::factory()->forOrganization($user->organization)->forUser($placeholder1)->role(Role::Placeholder)->create();
$placeholder2 = User::factory()->placeholder()->create([
'email' => $user2->user->email,
]);
$placeholder2Member = Member::factory()->forOrganization($user->organization)->forUser($placeholder2)->role(Role::Placeholder)->create();
$this->actingAs($user2->user);
// Act
$acceptUrl = URL::to(URL::temporarySignedRoute(
'organization-invitations.accept',
now()->addMinutes(60),
[$invitation->getKey()],
false
));
$response = $this->get($acceptUrl);
// Assert
$response->assertValid();
$response->assertRedirect(route('dashboard'));
$response->assertSessionHas('bannerText', 'Great! You have accepted the invitation to join the '.$user->organization->name.' organization.');
$response->assertSessionHas('bannerStyle', 'success');
$this->assertDatabaseHas(Member::class, [
'user_id' => $user2->user->getKey(),
'organization_id' => $user->organization->getKey(),
'role' => Role::Employee->value,
]);
$this->assertDatabaseMissing(User::class, [
'id' => $placeholder1->getKey(),
]);
$this->assertDatabaseMissing(User::class, [
'id' => $placeholder2->getKey(),
]);
$this->assertDatabaseMissing(Member::class, [
'id' => $placeholder1Member->getKey(),
]);
$this->assertDatabaseMissing(Member::class, [
'id' => $placeholder2Member->getKey(),
]);
$this->assertDatabaseMissing(OrganizationInvitation::class, [
'id' => $invitation->getKey(),
]);
}
public function test_fails_with_invalid_signature(): void
{
// Arrange
$user = $this->createUserWithPermission();
$invitation = OrganizationInvitation::factory()
->forOrganization($user->organization)
->create();
// Act
$response = $this->get(URL::temporarySignedRoute(
'organization-invitations.accept',
now()->addMinutes(60),
[$invitation->getKey()]).
'?invalid'
);
// Assert
$response->assertForbidden();
}
}

View File

@@ -1,45 +0,0 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Endpoint\Web;
use App\Models\OrganizationInvitation;
use App\Providers\JetstreamServiceProvider;
use Inertia\Testing\AssertableInertia as Assert;
use Laravel\Jetstream\Jetstream;
use PHPUnit\Framework\Attributes\CoversClass;
#[CoversClass(JetstreamServiceProvider::class)]
class TeamShowEndpointTest extends EndpointTestAbstract
{
protected function setUp(): void
{
Jetstream::$inertiaManager = null;
parent::setUp();
}
public function test_team_show_does_not_expose_member_roster_invitations_or_owner_email(): void
{
// Arrange
$data = $this->createUserWithPermission([]);
OrganizationInvitation::factory()->forOrganization($data->organization)->create([
'email' => 'pending@example.com',
]);
$this->actingAs($data->user);
// Act
$response = $this->get('/teams/'.$data->organization->getKey());
// Assert
$response->assertOk();
$response->assertInertia(fn (Assert $page) => $page
->missing('team.users')
->missing('team.team_invitations')
->missing('team.owner.email')
->has('team.owner.id')
->has('team.owner.name')
->has('team.owner.profile_photo_url')
);
}
}

View File

@@ -28,6 +28,6 @@ class AuthApiTokenExpirationReminderMailTest extends TestCaseWithDatabase
$rendered = $mail->render(); $rendered = $mail->render();
// Assert // Assert
$this->assertStringContainsString('The API token "TEST" will expire in 7 days!', $rendered); $this->assertStringContainsString('The API token "TEST" expired.', $rendered);
} }
} }

View File

@@ -28,6 +28,6 @@ class AuthApiTokenExpiredMailTest extends TestCaseWithDatabase
$rendered = $mail->render(); $rendered = $mail->render();
// Assert // Assert
$this->assertStringContainsString('The API token "TEST" expired.', $rendered); $this->assertStringContainsString('The API token "TEST" will expire in 7 days!', $rendered);
} }
} }

View File

@@ -1,53 +0,0 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Mail;
use App\Mail\VerifyUpdatedEmailMail;
use App\Models\User;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\URL;
use PHPUnit\Framework\Attributes\CoversClass;
use Tests\TestCaseWithDatabase;
#[CoversClass(VerifyUpdatedEmailMail::class)]
class VerifyUpdatedEmailMailTest extends TestCaseWithDatabase
{
public function test_mail_renders_content_correctly(): void
{
// Arrange
$user = User::factory()->create();
$mail = new VerifyUpdatedEmailMail($user, 'New.Email@Example.com');
// Act
$rendered = $mail->render();
// Assert
$this->assertEquals('new.email@example.com', $mail->email);
$this->assertStringContainsString('Please verify your new email address', $rendered);
}
public function test_mail_uses_relative_signed_verification_url(): void
{
// Arrange
Carbon::setTestNow('2026-05-21 12:00:00');
$user = User::factory()->create();
$mail = new VerifyUpdatedEmailMail($user, 'new.email@example.com');
// Act
$rendered = $mail->render();
$expectedPath = URL::temporarySignedRoute(
'users.verify-email-change',
now()->addMinutes((int) config('auth.verification.expire', 60)),
[
'user' => $user->getKey(),
'email' => 'new.email@example.com',
],
false
);
// Assert
$this->assertStringContainsString(e(URL::to($expectedPath)), $rendered);
}
}

View File

@@ -9,6 +9,7 @@ use App\Models\Organization;
use App\Models\User; use App\Models\User;
use App\Service\PermissionStore; use App\Service\PermissionStore;
use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Jetstream\Jetstream;
use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\CoversClass;
use Tests\TestCase; use Tests\TestCase;
@@ -121,7 +122,7 @@ class PermissionStoreTest extends TestCase
$result = $permissionStore->getPermissions($organization); $result = $permissionStore->getPermissions($organization);
// Assert // Assert
$this->assertSame(PermissionStore::permissionsForRole(Role::Employee->value), $result); $this->assertSame(Jetstream::findRole(Role::Employee->value)->permissions, $result);
} }
public function test_employee_does_not_have_task_permissions_by_default(): void public function test_employee_does_not_have_task_permissions_by_default(): void