mirror of
https://github.com/InvoiceShelf/InvoiceShelf.git
synced 2026-04-15 01:04:03 +00:00
Support invitations for unregistered users
When inviting an email without an InvoiceShelf account, the email now
links to a registration page (/register?invitation={token}) instead of
login. After registering, the invitation is auto-accepted.
Backend:
- InvitationRegistrationController: public details() and register()
endpoints. Registration validates token + email match, creates account,
auto-accepts invitation, returns Sanctum token.
- AuthController: login now accepts optional invitation_token param to
auto-accept invitation for existing users clicking the email link.
- CompanyInvitationMail: conditional URL based on user existence.
- Web route for /invitations/{token}/decline (email decline link).
Frontend:
- RegisterWithInvitation.vue: fetches invitation details, shows company
name + role, registration form with pre-filled email.
- Router: /register route added.
Tests: 3 new tests (invitation details, register + accept, email mismatch).
This commit is contained in:
@@ -4,7 +4,9 @@ namespace App\Http\Controllers\Company\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\LoginRequest;
|
||||
use App\Models\CompanyInvitation;
|
||||
use App\Models\User;
|
||||
use App\Services\InvitationService;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
@@ -22,6 +24,17 @@ class AuthController extends Controller
|
||||
]);
|
||||
}
|
||||
|
||||
// Auto-accept invitation if token is provided
|
||||
if ($request->has('invitation_token') && $request->invitation_token) {
|
||||
$invitation = CompanyInvitation::where('token', $request->invitation_token)
|
||||
->pending()
|
||||
->first();
|
||||
|
||||
if ($invitation) {
|
||||
app(InvitationService::class)->accept($invitation, $user);
|
||||
}
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'type' => 'Bearer',
|
||||
'token' => $user->createToken($request->device_name)->plainTextToken,
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Company\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\CompanyInvitation;
|
||||
use App\Models\User;
|
||||
use App\Services\InvitationService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class InvitationRegistrationController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly InvitationService $invitationService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Get invitation details by token (public endpoint for registration page).
|
||||
*/
|
||||
public function details(string $token): JsonResponse
|
||||
{
|
||||
$invitation = CompanyInvitation::where('token', $token)
|
||||
->pending()
|
||||
->with(['company', 'role'])
|
||||
->first();
|
||||
|
||||
if (! $invitation) {
|
||||
return response()->json([
|
||||
'error' => 'Invitation not found or expired.',
|
||||
], 404);
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'email' => $invitation->email,
|
||||
'company_name' => $invitation->company->name,
|
||||
'role_name' => $invitation->role->title,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a new user and auto-accept the invitation.
|
||||
*/
|
||||
public function register(Request $request): JsonResponse
|
||||
{
|
||||
$request->validate([
|
||||
'name' => 'required|string|max:255',
|
||||
'email' => 'required|string|email|max:255|unique:users',
|
||||
'password' => 'required|string|min:8|confirmed',
|
||||
'invitation_token' => 'required|string',
|
||||
]);
|
||||
|
||||
$invitation = CompanyInvitation::where('token', $request->invitation_token)
|
||||
->pending()
|
||||
->first();
|
||||
|
||||
if (! $invitation) {
|
||||
throw ValidationException::withMessages([
|
||||
'invitation_token' => ['Invitation not found or expired.'],
|
||||
]);
|
||||
}
|
||||
|
||||
if ($invitation->email !== $request->email) {
|
||||
throw ValidationException::withMessages([
|
||||
'email' => ['Email does not match the invitation.'],
|
||||
]);
|
||||
}
|
||||
|
||||
$user = User::create([
|
||||
'name' => $request->name,
|
||||
'email' => $request->email,
|
||||
'password' => $request->password,
|
||||
]);
|
||||
|
||||
$this->invitationService->accept($invitation, $user);
|
||||
|
||||
return response()->json([
|
||||
'type' => 'Bearer',
|
||||
'token' => $user->createToken('web')->plainTextToken,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,13 @@ class CompanyInvitationMail extends Mailable
|
||||
|
||||
public function content(): Content
|
||||
{
|
||||
$token = $this->invitation->token;
|
||||
$hasAccount = $this->invitation->user_id !== null;
|
||||
|
||||
$acceptUrl = $hasAccount
|
||||
? url("/login?invitation={$token}")
|
||||
: url("/register?invitation={$token}");
|
||||
|
||||
return new Content(
|
||||
markdown: 'emails.company-invitation',
|
||||
with: [
|
||||
@@ -35,8 +42,9 @@ class CompanyInvitationMail extends Mailable
|
||||
'companyName' => $this->invitation->company->name,
|
||||
'roleName' => $this->invitation->role->title,
|
||||
'inviterName' => $this->invitation->invitedBy->name,
|
||||
'acceptUrl' => url("/invitations/{$this->invitation->token}/accept"),
|
||||
'declineUrl' => url("/invitations/{$this->invitation->token}/decline"),
|
||||
'acceptUrl' => $acceptUrl,
|
||||
'declineUrl' => url("/invitations/{$token}/decline"),
|
||||
'hasAccount' => $hasAccount,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
8
resources/scripts/admin/admin-router.js
vendored
8
resources/scripts/admin/admin-router.js
vendored
@@ -138,8 +138,16 @@ const AdminFileDisk = () =>
|
||||
|
||||
const NoCompanyView = () =>
|
||||
import('@/scripts/admin/views/NoCompanyView.vue')
|
||||
const RegisterWithInvitation = () =>
|
||||
import('@/scripts/admin/views/auth/RegisterWithInvitation.vue')
|
||||
|
||||
export default [
|
||||
{
|
||||
path: '/register',
|
||||
name: 'register',
|
||||
component: RegisterWithInvitation,
|
||||
meta: { requiresAuth: false },
|
||||
},
|
||||
{
|
||||
path: '/admin/no-company',
|
||||
name: 'no.company',
|
||||
|
||||
195
resources/scripts/admin/views/auth/RegisterWithInvitation.vue
Normal file
195
resources/scripts/admin/views/auth/RegisterWithInvitation.vue
Normal file
@@ -0,0 +1,195 @@
|
||||
<template>
|
||||
<div class="flex items-center justify-center min-h-screen bg-gray-50">
|
||||
<div class="w-full max-w-md p-8">
|
||||
<!-- Loading -->
|
||||
<div v-if="isLoading" class="text-center">
|
||||
<p class="text-gray-500">Loading invitation details...</p>
|
||||
</div>
|
||||
|
||||
<!-- Invalid/Expired -->
|
||||
<div v-else-if="error" class="text-center">
|
||||
<BaseIcon
|
||||
name="ExclamationCircleIcon"
|
||||
class="w-16 h-16 mx-auto text-red-400 mb-4"
|
||||
/>
|
||||
<h1 class="text-xl font-semibold text-gray-900 mb-2">
|
||||
Invalid Invitation
|
||||
</h1>
|
||||
<p class="text-gray-500">{{ error }}</p>
|
||||
<router-link to="/login" class="text-primary-500 mt-4 inline-block">
|
||||
Go to Login
|
||||
</router-link>
|
||||
</div>
|
||||
|
||||
<!-- Registration Form -->
|
||||
<div v-else>
|
||||
<div class="text-center mb-6">
|
||||
<h1 class="text-2xl font-semibold text-gray-900">
|
||||
Create Your Account
|
||||
</h1>
|
||||
<p class="text-gray-500 mt-2">
|
||||
You've been invited to join
|
||||
<strong>{{ invitationDetails.company_name }}</strong> as
|
||||
<strong>{{ invitationDetails.role_name }}</strong>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<BaseCard class="p-6">
|
||||
<form @submit.prevent="submitRegistration">
|
||||
<div class="space-y-4">
|
||||
<BaseInputGroup
|
||||
label="Name"
|
||||
:error="v$.name.$error && v$.name.$errors[0].$message"
|
||||
required
|
||||
>
|
||||
<BaseInput
|
||||
v-model="form.name"
|
||||
:invalid="v$.name.$error"
|
||||
@input="v$.name.$touch()"
|
||||
/>
|
||||
</BaseInputGroup>
|
||||
|
||||
<BaseInputGroup label="Email">
|
||||
<BaseInput
|
||||
v-model="form.email"
|
||||
type="email"
|
||||
disabled
|
||||
/>
|
||||
</BaseInputGroup>
|
||||
|
||||
<BaseInputGroup
|
||||
label="Password"
|
||||
:error="v$.password.$error && v$.password.$errors[0].$message"
|
||||
required
|
||||
>
|
||||
<BaseInput
|
||||
v-model="form.password"
|
||||
type="password"
|
||||
:invalid="v$.password.$error"
|
||||
@input="v$.password.$touch()"
|
||||
/>
|
||||
</BaseInputGroup>
|
||||
|
||||
<BaseInputGroup
|
||||
label="Confirm Password"
|
||||
:error="
|
||||
v$.password_confirmation.$error &&
|
||||
v$.password_confirmation.$errors[0].$message
|
||||
"
|
||||
required
|
||||
>
|
||||
<BaseInput
|
||||
v-model="form.password_confirmation"
|
||||
type="password"
|
||||
:invalid="v$.password_confirmation.$error"
|
||||
@input="v$.password_confirmation.$touch()"
|
||||
/>
|
||||
</BaseInputGroup>
|
||||
</div>
|
||||
|
||||
<BaseButton
|
||||
:loading="isSubmitting"
|
||||
:disabled="isSubmitting"
|
||||
class="w-full mt-6"
|
||||
type="submit"
|
||||
>
|
||||
Create Account & Join
|
||||
</BaseButton>
|
||||
</form>
|
||||
</BaseCard>
|
||||
|
||||
<div class="text-center mt-4">
|
||||
<router-link to="/login" class="text-sm text-gray-500 hover:text-primary-500">
|
||||
Already have an account? Log in
|
||||
</router-link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, reactive, computed, onMounted } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { helpers, required, minLength, sameAs } from '@vuelidate/validators'
|
||||
import { useVuelidate } from '@vuelidate/core'
|
||||
import http from '@/scripts/http'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
|
||||
const isLoading = ref(true)
|
||||
const isSubmitting = ref(false)
|
||||
const error = ref(null)
|
||||
const invitationDetails = ref({})
|
||||
|
||||
const form = reactive({
|
||||
name: '',
|
||||
email: '',
|
||||
password: '',
|
||||
password_confirmation: '',
|
||||
})
|
||||
|
||||
const rules = computed(() => ({
|
||||
name: {
|
||||
required: helpers.withMessage('Name is required', required),
|
||||
},
|
||||
password: {
|
||||
required: helpers.withMessage('Password is required', required),
|
||||
minLength: helpers.withMessage('Password must be at least 8 characters', minLength(8)),
|
||||
},
|
||||
password_confirmation: {
|
||||
required: helpers.withMessage('Please confirm your password', required),
|
||||
sameAs: helpers.withMessage('Passwords do not match', sameAs(form.password)),
|
||||
},
|
||||
}))
|
||||
|
||||
const v$ = useVuelidate(
|
||||
rules,
|
||||
computed(() => form)
|
||||
)
|
||||
|
||||
const token = computed(() => route.query.invitation)
|
||||
|
||||
onMounted(async () => {
|
||||
if (!token.value) {
|
||||
error.value = 'No invitation token provided.'
|
||||
isLoading.value = false
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await http.get(`/api/v1/invitations/${token.value}/details`)
|
||||
invitationDetails.value = response.data
|
||||
form.email = response.data.email
|
||||
} catch (e) {
|
||||
error.value = 'This invitation is invalid or has expired.'
|
||||
} finally {
|
||||
isLoading.value = false
|
||||
}
|
||||
})
|
||||
|
||||
async function submitRegistration() {
|
||||
v$.value.$touch()
|
||||
if (v$.value.$invalid) return
|
||||
|
||||
isSubmitting.value = true
|
||||
try {
|
||||
const response = await http.post('/api/v1/auth/register-with-invitation', {
|
||||
name: form.name,
|
||||
email: form.email,
|
||||
password: form.password,
|
||||
password_confirmation: form.password_confirmation,
|
||||
invitation_token: token.value,
|
||||
})
|
||||
|
||||
// Store the token and redirect
|
||||
window.Ls.set('auth.token', response.data.token)
|
||||
router.push('/admin/dashboard')
|
||||
} catch (e) {
|
||||
// Validation errors handled by http interceptor
|
||||
} finally {
|
||||
isSubmitting.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@@ -3,8 +3,14 @@
|
||||
|
||||
**{{ $inviterName }}** has invited you to join **{{ $companyName }}** as **{{ $roleName }}**.
|
||||
|
||||
@if($hasAccount)
|
||||
Log in to accept the invitation:
|
||||
@else
|
||||
Create your account to get started:
|
||||
@endif
|
||||
|
||||
<x-mail::button :url="$acceptUrl">
|
||||
Accept Invitation
|
||||
{{ $hasAccount ? 'Log In & Accept' : 'Create Account & Accept' }}
|
||||
</x-mail::button>
|
||||
|
||||
If you don't want to join, you can <a href="{{ $declineUrl }}">decline this invitation</a>.
|
||||
|
||||
@@ -15,6 +15,7 @@ use App\Http\Controllers\Admin\UsersController;
|
||||
use App\Http\Controllers\AppVersionController;
|
||||
use App\Http\Controllers\Company\Auth\AuthController;
|
||||
use App\Http\Controllers\Company\Auth\ForgotPasswordController;
|
||||
use App\Http\Controllers\Company\Auth\InvitationRegistrationController;
|
||||
use App\Http\Controllers\Company\Auth\ResetPasswordController;
|
||||
use App\Http\Controllers\Company\Customer\CustomersController;
|
||||
use App\Http\Controllers\Company\Customer\CustomerStatsController;
|
||||
@@ -115,6 +116,12 @@ Route::prefix('/v1')->group(function () {
|
||||
Route::post('reset/password', [ResetPasswordController::class, 'reset']);
|
||||
});
|
||||
|
||||
// Invitation Registration (public)
|
||||
// ----------------------------------
|
||||
|
||||
Route::get('/invitations/{token}/details', [InvitationRegistrationController::class, 'details']);
|
||||
Route::post('/auth/register-with-invitation', [InvitationRegistrationController::class, 'register']);
|
||||
|
||||
// Countries
|
||||
// ----------------------------------
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ use App\Http\Controllers\Modules\ScriptController;
|
||||
use App\Http\Controllers\Modules\StyleController;
|
||||
use App\Http\Controllers\Pdf\DocumentPdfController;
|
||||
use App\Models\Company;
|
||||
use App\Models\CompanyInvitation;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
// Module Asset Includes
|
||||
@@ -76,6 +77,21 @@ Route::middleware('auth:sanctum')->prefix('reports')->group(function () {
|
||||
// PDF Endpoints
|
||||
// ----------------------------------------------
|
||||
|
||||
// Invitation email link handlers
|
||||
// -------------------------------------------------
|
||||
|
||||
Route::get('/invitations/{token}/decline', function (string $token) {
|
||||
$invitation = CompanyInvitation::where('token', $token)->pending()->first();
|
||||
|
||||
if (! $invitation) {
|
||||
return view('app')->with(['message' => 'Invitation not found or already expired.']);
|
||||
}
|
||||
|
||||
$invitation->update(['status' => CompanyInvitation::STATUS_DECLINED]);
|
||||
|
||||
return view('app')->with(['message' => 'Invitation declined.']);
|
||||
});
|
||||
|
||||
Route::middleware('pdf-auth')->group(function () {
|
||||
|
||||
// invoice pdf
|
||||
|
||||
@@ -225,3 +225,89 @@ test('bootstrap includes pending invitations', function () {
|
||||
$response->assertOk();
|
||||
$response->assertJsonStructure(['pending_invitations']);
|
||||
});
|
||||
|
||||
test('get invitation details by token', function () {
|
||||
Mail::fake();
|
||||
|
||||
$company = Company::first();
|
||||
$role = Role::where('name', 'owner')->first();
|
||||
|
||||
// Create invitation for non-existent user
|
||||
$invitation = CompanyInvitation::create([
|
||||
'company_id' => $company->id,
|
||||
'user_id' => null,
|
||||
'email' => 'newperson@example.com',
|
||||
'role_id' => $role->id,
|
||||
'token' => 'test-details-token',
|
||||
'status' => 'pending',
|
||||
'invited_by' => User::first()->id,
|
||||
'expires_at' => now()->addDays(7),
|
||||
]);
|
||||
|
||||
$response = getJson("api/v1/invitations/{$invitation->token}/details");
|
||||
|
||||
$response->assertOk();
|
||||
$response->assertJsonPath('email', 'newperson@example.com');
|
||||
$response->assertJsonPath('company_name', $company->name);
|
||||
});
|
||||
|
||||
test('register with invitation creates account and accepts', function () {
|
||||
$company = Company::first();
|
||||
$role = Role::where('name', 'owner')->first();
|
||||
|
||||
$invitation = CompanyInvitation::create([
|
||||
'company_id' => $company->id,
|
||||
'user_id' => null,
|
||||
'email' => 'register@example.com',
|
||||
'role_id' => $role->id,
|
||||
'token' => 'test-register-token',
|
||||
'status' => 'pending',
|
||||
'invited_by' => User::first()->id,
|
||||
'expires_at' => now()->addDays(7),
|
||||
]);
|
||||
|
||||
$response = postJson('api/v1/auth/register-with-invitation', [
|
||||
'name' => 'New User',
|
||||
'email' => 'register@example.com',
|
||||
'password' => 'password123',
|
||||
'password_confirmation' => 'password123',
|
||||
'invitation_token' => 'test-register-token',
|
||||
]);
|
||||
|
||||
$response->assertOk();
|
||||
$response->assertJsonStructure(['type', 'token']);
|
||||
|
||||
$newUser = User::where('email', 'register@example.com')->first();
|
||||
$this->assertNotNull($newUser);
|
||||
$this->assertTrue($newUser->hasCompany($company->id));
|
||||
$this->assertDatabaseHas('company_invitations', [
|
||||
'token' => 'test-register-token',
|
||||
'status' => 'accepted',
|
||||
]);
|
||||
});
|
||||
|
||||
test('cannot register with mismatched email', function () {
|
||||
$company = Company::first();
|
||||
$role = Role::where('name', 'owner')->first();
|
||||
|
||||
CompanyInvitation::create([
|
||||
'company_id' => $company->id,
|
||||
'user_id' => null,
|
||||
'email' => 'correct@example.com',
|
||||
'role_id' => $role->id,
|
||||
'token' => 'test-mismatch-token',
|
||||
'status' => 'pending',
|
||||
'invited_by' => User::first()->id,
|
||||
'expires_at' => now()->addDays(7),
|
||||
]);
|
||||
|
||||
$response = postJson('api/v1/auth/register-with-invitation', [
|
||||
'name' => 'Wrong User',
|
||||
'email' => 'wrong@example.com',
|
||||
'password' => 'password123',
|
||||
'password_confirmation' => 'password123',
|
||||
'invitation_token' => 'test-mismatch-token',
|
||||
]);
|
||||
|
||||
$response->assertStatus(422);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user