Add two factor (#632)

This commit is contained in:
Saeed Vaziry
2025-06-27 01:07:33 +02:00
committed by GitHub
parent 73c836bfe7
commit 194143d7ef
12 changed files with 388 additions and 49 deletions

View File

@ -49,6 +49,18 @@ public function store(Request $request): RedirectResponse
RateLimiter::clear($this->throttleKey());
Session::regenerate();
if (user()->two_factor_secret) {
$request->session()->invalidate();
$request->session()->regenerateToken();
$request->session()->put([
'login.id' => user()->id,
'login.remember' => $request->boolean('remember'),
]);
return redirect()->route('two-factor.login');
}
return redirect()->intended(route('servers', absolute: false));
}

View File

@ -0,0 +1,63 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Models\User;
use Illuminate\Contracts\Auth\StatefulGuard;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Routing\Controller;
use Inertia\Inertia;
use Laravel\Fortify\Contracts\FailedTwoFactorLoginResponse;
use Laravel\Fortify\Contracts\TwoFactorLoginResponse;
use Laravel\Fortify\Events\RecoveryCodeReplaced;
use Laravel\Fortify\Events\TwoFactorAuthenticationFailed;
use Laravel\Fortify\Events\ValidTwoFactorAuthenticationCodeProvided;
use Laravel\Fortify\Http\Requests\TwoFactorLoginRequest;
use Spatie\RouteAttributes\Attributes\Get;
use Spatie\RouteAttributes\Attributes\Post;
use Symfony\Component\HttpFoundation\Response;
class TwoFactorAuthenticatedSessionController extends Controller
{
protected StatefulGuard $guard;
public function __construct(StatefulGuard $guard)
{
$this->guard = $guard;
}
#[Get('two-factor', name: 'two-factor.login')]
public function create(TwoFactorLoginRequest $request): \Inertia\Response
{
if (! $request->hasChallengedUser()) {
throw new HttpResponseException(redirect()->route('login'));
}
return Inertia::render('auth/two-factor');
}
#[Post('two-factor', name: 'two-factor.store')]
public function store(TwoFactorLoginRequest $request): TwoFactorLoginResponse|Response
{
/** @var User $user */
$user = $request->challengedUser();
if ($code = $request->validRecoveryCode()) {
$user->replaceRecoveryCode($code);
event(new RecoveryCodeReplaced($user, $code));
} elseif (! $request->hasValidCode()) {
event(new TwoFactorAuthenticationFailed($user));
return app(FailedTwoFactorLoginResponse::class)->toResponse($request);
}
event(new ValidTwoFactorAuthenticationCodeProvided($user));
$this->guard->login($user, $request->remember());
$request->session()->regenerate();
return redirect()->intended(route('servers', absolute: false));
}
}

View File

@ -11,9 +11,12 @@
use Illuminate\Validation\Rules\Password;
use Inertia\Inertia;
use Inertia\Response;
use Laravel\Fortify\Actions\DisableTwoFactorAuthentication;
use Laravel\Fortify\Actions\EnableTwoFactorAuthentication;
use Spatie\RouteAttributes\Attributes\Get;
use Spatie\RouteAttributes\Attributes\Middleware;
use Spatie\RouteAttributes\Attributes\Patch;
use Spatie\RouteAttributes\Attributes\Post;
use Spatie\RouteAttributes\Attributes\Prefix;
use Spatie\RouteAttributes\Attributes\Put;
@ -65,4 +68,30 @@ public function password(Request $request): RedirectResponse
return to_route('profile');
}
#[Post('/enable-two-factor', name: 'profile.enable-two-factor')]
public function enableTwoFactor(): RedirectResponse
{
$user = user();
app(EnableTwoFactorAuthentication::class)($user);
return back()
->with('success', 'Two factor authentication enabled.')
->with('data', [
'qr_code' => $user->twoFactorQrCodeSvg(),
'qr_code_url' => $user->twoFactorQrCodeUrl(),
'recovery_codes' => $user->recoveryCodes(),
]);
}
#[Post('/disable-two-factor', name: 'profile.disable-two-factor')]
public function disableTwoFactor(): RedirectResponse
{
$user = user();
app(DisableTwoFactorAuthentication::class)($user);
return back()->with('success', 'Two factor authentication disabled.');
}
}

View File

@ -2,8 +2,10 @@
namespace App\Http\Middleware;
use App\Http\Resources\ProjectResource;
use App\Http\Resources\ServerResource;
use App\Http\Resources\SiteResource;
use App\Http\Resources\UserResource;
use App\Models\Server;
use App\Models\Site;
use App\Models\User;
@ -84,11 +86,11 @@ public function share(Request $request): array
'version' => config('app.version'),
'demo' => config('app.demo'),
'quote' => ['message' => trim($message), 'author' => trim($author)],
'auth' => [
'user' => $user,
'projects' => $user?->allProjects()->get(),
'currentProject' => $user?->currentProject,
],
'auth' => $user ? [
'user' => UserResource::make($user->load('projects')),
'projects' => ProjectResource::collection($user->allProjects()->get()),
'currentProject' => ProjectResource::make($user->currentProject),
] : null,
'public_key_text' => __('servers.create.public_key_text', ['public_key' => get_public_key_content()]),
'project_servers' => $servers,
'configs' => [

View File

@ -19,6 +19,7 @@ public function toArray(Request $request): array
'name' => $this->name,
'email' => $this->email,
'role' => $this->role,
'two_factor_enabled' => (bool) $this->two_factor_secret,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'projects' => ProjectResource::collection($this->whenLoaded('projects')),

View File

@ -34,6 +34,9 @@ public function boot(): void
$this->app->bind('plugins', fn (): Plugins => new Plugins);
Sanctum::usePersonalAccessTokenModel(PersonalAccessToken::class);
Fortify::twoFactorChallengeView(function () {
return view('app');
});
if (config('app.force_https')) {
URL::forceHttps();

View File

@ -1,7 +1,7 @@
import { AppSidebar } from '@/components/app-sidebar';
import { AppHeader } from '@/components/app-header';
import { type BreadcrumbItem, NavItem, SharedData } from '@/types';
import { type PropsWithChildren } from 'react';
import { type PropsWithChildren, useEffect } from 'react';
import { SidebarInset, SidebarProvider } from '@/components/ui/sidebar';
import { usePage } from '@inertiajs/react';
import { Toaster } from '@/components/ui/sonner';
@ -20,6 +20,7 @@ export default function Layout({
}>) {
const page = usePage<SharedData>();
useEffect(() => {
if (page.props.flash && page.props.flash.success) {
toast(
<div className="flex items-center gap-2">
@ -52,6 +53,7 @@ export default function Layout({
</div>,
);
}
}, [page.props.flash]);
const queryClient = new QueryClient();

View File

@ -0,0 +1,76 @@
import { Head, Link, useForm } from '@inertiajs/react';
import { LoaderCircle } from 'lucide-react';
import { FormEventHandler } from 'react';
import InputError from '@/components/ui/input-error';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import AuthLayout from '@/layouts/auth/layout';
import { Form, FormField, FormFields } from '@/components/ui/form';
export default function TwoFactor() {
const form = useForm<Required<{ code: string; recovery_code: string }>>({
code: '',
recovery_code: '',
});
const submit: FormEventHandler = (e) => {
e.preventDefault();
form.post(route('two-factor.store'), {
onFinish: () => form.reset(),
});
};
return (
<AuthLayout title="Two factor challenge" description="Please enter the two-factor authentication code to continue.">
<Head title="Confirm password" />
<Form onSubmit={submit}>
<FormFields>
<FormField>
<Label htmlFor="code">Code</Label>
<Input
id="code"
type="text"
name="code"
placeholder="Two factor code"
value={form.data.code}
autoFocus
onChange={(e) => form.setData('code', e.target.value)}
/>
<InputError message={form.errors.code} />
</FormField>
<FormField>
<Label htmlFor="recovery_code">Recovery Code</Label>
<Input
id="recovery_code"
type="text"
name="recovery_code"
placeholder="Or enter your recovery code"
value={form.data.recovery_code}
onChange={(e) => form.setData('recovery_code', e.target.value)}
/>
<InputError message={form.errors.recovery_code} />
</FormField>
<div className="space-y-2">
<Button className="w-full" disabled={form.processing}>
{form.processing && <LoaderCircle className="h-4 w-4 animate-spin" />}
Confirm
</Button>
<Button variant="ghost" asChild>
<Link className="block w-full" method="post" href={route('logout')}>
Back to login
</Link>
</Button>
</div>
</FormFields>
</Form>
</AuthLayout>
);
}

View File

@ -0,0 +1,139 @@
import { useForm, usePage } from '@inertiajs/react';
import type { SharedData } from '@/types';
import { FormEventHandler, ReactNode, useState } from 'react';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { CheckCircle2Icon, LoaderCircleIcon, XCircleIcon } from 'lucide-react';
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { FormField, FormFields } from '@/components/ui/form';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Alert, AlertDescription } from '@/components/ui/alert';
function Disable(): ReactNode {
const [open, setOpen] = useState(false);
const form = useForm();
const submit = () => {
form.post(route('profile.disable-two-factor'), {
preserveScroll: true,
onSuccess: () => setOpen(false),
});
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button variant="destructive">Disable Two Factor</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Disable two factor</DialogTitle>
<DialogDescription className="sr-only">Disable two factor</DialogDescription>
</DialogHeader>
<p className="p-4">Are you sure you want to enable two factor authentication?</p>
<DialogFooter>
<DialogClose asChild>
<Button variant="outline">Cancel</Button>
</DialogClose>
<Button onClick={submit} variant="destructive" disabled={form.processing}>
{form.processing && <LoaderCircleIcon className="animate-spin" />}
Disable
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
function Enable() {
const form = useForm();
const submit: FormEventHandler = (e) => {
e.preventDefault();
form.post(route('profile.enable-two-factor'));
};
return (
<Button onClick={submit} disabled={form.processing}>
{form.processing && <LoaderCircleIcon className="animate-spin" />}
Enable Two Factor
</Button>
);
}
export default function TwoFactor() {
const page = usePage<
SharedData & {
flash: {
data?: {
qr_code?: string;
qr_code_url?: string;
recovery_codes?: string[];
};
};
}
>();
return (
<Card>
<CardHeader>
<CardTitle>Two factor authentication</CardTitle>
<CardDescription>Enable or Disable two factor authentication</CardDescription>
</CardHeader>
<CardContent className="space-y-2 p-4">
{page.props.flash.data?.qr_code && (
<FormFields>
<FormField>
<Label htmlFor="qr-code">Scan this QR code with your authenticator app</Label>
<div className="flex max-h-[400px] items-center">
<div dangerouslySetInnerHTML={{ __html: page.props.flash.data.qr_code }}></div>
</div>
</FormField>
<FormField>
<Label htmlFor="qr-code-url">QR Code URL</Label>
<Input id="qr-code-url" value={page.props.flash.data.qr_code_url} disabled />
</FormField>
<FormField>
<Label htmlFor="recovery-codes">Recovery Codes</Label>
<Textarea id="recovery-codes" value={page.props.flash.data.recovery_codes?.join('\n') || ''} disabled rows={5} />
</FormField>
</FormFields>
)}
{page.props.auth.user.two_factor_enabled ? (
<Alert>
<AlertDescription>
<div className="flex items-center gap-2">
<CheckCircle2Icon className="text-success size-4" />
<p>Two factor authentication is enabled</p>
</div>
</AlertDescription>
</Alert>
) : (
<Alert>
<AlertDescription>
<div className="flex items-center gap-2">
<XCircleIcon className="text-danger size-4" />
Two factor authentication is <strong>not</strong> enabled
</div>
</AlertDescription>
</Alert>
)}
</CardContent>
<CardFooter className="gap-2">
{!page.props.auth.user.two_factor_enabled && <Enable />}
{page.props.auth.user.two_factor_enabled && <Disable />}
</CardFooter>
</Card>
);
}

View File

@ -4,15 +4,34 @@ import Container from '@/components/container';
import UpdatePassword from '@/pages/profile/components/update-password';
import UpdateProfile from '@/pages/profile/components/update-profile';
import Heading from '@/components/heading';
import TwoFactor from '@/pages/profile/components/two-factor';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useState } from 'react';
export default function Profile() {
const [tab, setTab] = useState('info');
return (
<SettingsLayout>
<Head title="Profile settings" />
<Container className="max-w-5xl">
<Heading title="Profile settings" description="Manage your profile settings." />
<Tabs defaultValue={tab} onValueChange={setTab}>
<TabsList>
<TabsTrigger value="info">Info</TabsTrigger>
<TabsTrigger value="password">Password</TabsTrigger>
<TabsTrigger value="two_factor">Two Factor</TabsTrigger>
</TabsList>
<TabsContent value="info">
<UpdateProfile />
</TabsContent>
<TabsContent value="password">
<UpdatePassword />
</TabsContent>
<TabsContent value="two_factor">
<TwoFactor />
</TabsContent>
</Tabs>
</Container>
</SettingsLayout>
);

View File

@ -5,7 +5,7 @@ import HeaderContainer from '@/components/header-container';
import Heading from '@/components/heading';
import { Button } from '@/components/ui/button';
import ServerLayout from '@/layouts/server/layout';
import { BookOpenIcon, MoreVerticalIcon } from 'lucide-react';
import { MoreVerticalIcon } from 'lucide-react';
import { Card, CardContent, CardDescription, CardHeader, CardRow, CardTitle } from '@/components/ui/card';
import React from 'react';
import { Site, SiteFeature } from '@/types/site';
@ -29,14 +29,6 @@ export default function SiteFeatures() {
<Container className="max-w-5xl">
<HeaderContainer>
<Heading title="Features" description="Your site has some features enabled by Vito or other plugins" />
<div className="flex items-center gap-2">
<a href="https://vitodeploy.com/docs/sites/features" target="_blank">
<Button variant="outline">
<BookOpenIcon />
<span className="hidden lg:block">Docs</span>
</Button>
</a>
</div>
</HeaderContainer>
<Card>

View File

@ -10,6 +10,7 @@ export interface User {
updated_at: string;
timezone: string;
projects?: Project[];
two_factor_enabled: boolean;
role: string;
[key: string]: unknown; // This allows for additional properties...
}