├── .gitignore
├── laravel
├── public
│ ├── favicon.ico
│ ├── robots.txt
│ ├── vendor
│ │ └── telescope
│ │ │ ├── favicon.ico
│ │ │ └── mix-manifest.json
│ ├── .htaccess
│ └── index.php
├── resources
│ ├── css
│ │ └── app.css
│ └── js
│ │ ├── app.js
│ │ └── bootstrap.js
├── database
│ ├── .gitignore
│ ├── migrations
│ │ ├── 2014_10_12_100000_create_password_reset_tokens_table.php
│ │ ├── 2014_10_12_000000_create_users_table.php
│ │ ├── 2019_08_19_000000_create_failed_jobs_table.php
│ │ ├── 2019_12_14_000001_create_personal_access_tokens_table.php
│ │ ├── 2018_08_08_100000_create_telescope_entries_table.php
│ │ └── 2024_11_16_102217_create_permission_tables.php
│ ├── factories
│ │ └── UserFactory.php
│ └── seeders
│ │ └── DatabaseSeeder.php
├── storage
│ ├── logs
│ │ └── .gitignore
│ ├── app
│ │ ├── public
│ │ │ └── .gitignore
│ │ └── .gitignore
│ └── framework
│ │ ├── sessions
│ │ └── .gitignore
│ │ ├── testing
│ │ └── .gitignore
│ │ ├── views
│ │ └── .gitignore
│ │ ├── cache
│ │ ├── data
│ │ │ └── .gitignore
│ │ └── .gitignore
│ │ └── .gitignore
├── bootstrap
│ ├── cache
│ │ └── .gitignore
│ └── app.php
├── tests
│ ├── TestCase.php
│ ├── Unit
│ │ └── ExampleTest.php
│ ├── Feature
│ │ └── ExampleTest.php
│ └── CreatesApplication.php
├── .gitattributes
├── .gitignore
├── vite.config.js
├── package.json
├── .editorconfig
├── app
│ ├── Http
│ │ ├── Controllers
│ │ │ ├── Controller.php
│ │ │ └── Auth
│ │ │ │ ├── EmailVerificationNotificationController.php
│ │ │ │ ├── VerifyEmailController.php
│ │ │ │ ├── RegisteredUserController.php
│ │ │ │ ├── AuthenticatedSessionController.php
│ │ │ │ └── PasswordResetLinkController.php
│ │ ├── Middleware
│ │ │ ├── EncryptCookies.php
│ │ │ ├── VerifyCsrfToken.php
│ │ │ ├── PreventRequestsDuringMaintenance.php
│ │ │ ├── TrimStrings.php
│ │ │ ├── TrustHosts.php
│ │ │ ├── Authenticate.php
│ │ │ ├── ValidateSignature.php
│ │ │ ├── TrustProxies.php
│ │ │ ├── EnsureEmailIsVerified.php
│ │ │ └── RedirectIfAuthenticated.php
│ │ └── Kernel.php
│ ├── Providers
│ │ ├── BroadcastServiceProvider.php
│ │ ├── AppServiceProvider.php
│ │ ├── AuthServiceProvider.php
│ │ ├── EventServiceProvider.php
│ │ ├── RouteServiceProvider.php
│ │ └── TelescopeServiceProvider.php
│ ├── Console
│ │ └── Kernel.php
│ ├── Models
│ │ └── User.php
│ ├── Exceptions
│ │ └── Handler.php
│ └── Notifications
│ │ └── VerifyEmail.php
├── apache-config.conf
├── routes
│ ├── web.php
│ ├── channels.php
│ ├── console.php
│ └── api.php
├── docker-entrypoint.sh
├── config
│ ├── cors.php
│ ├── services.php
│ ├── view.php
│ ├── hashing.php
│ ├── broadcasting.php
│ ├── filesystems.php
│ ├── queue.php
│ ├── sanctum.php
│ ├── cache.php
│ ├── logging.php
│ ├── mail.php
│ ├── auth.php
│ └── database.php
├── phpunit.xml
├── README.md
├── .env.example
├── artisan
├── Dockerfile
├── .env.docker.dev
└── composer.json
├── nextjs
├── .eslintrc.json
├── public
│ └── favicon.ico
├── jsconfig.json
├── src
│ ├── pages
│ │ ├── fonts
│ │ │ ├── GeistVF.woff
│ │ │ └── GeistMonoVF.woff
│ │ ├── 403.js
│ │ ├── _document.js
│ │ ├── _app.js
│ │ ├── api
│ │ │ └── auth
│ │ │ │ ├── verify.js
│ │ │ │ ├── user.js
│ │ │ │ ├── forgot-password.js
│ │ │ │ ├── reset-password.js
│ │ │ │ ├── email
│ │ │ │ ├── verify-email-notification.js
│ │ │ │ └── verify-email.js
│ │ │ │ ├── csrf.js
│ │ │ │ ├── logout.js
│ │ │ │ ├── login.js
│ │ │ │ └── register.js
│ │ ├── profile.js
│ │ ├── verify-email.js
│ │ ├── dashboard.js
│ │ ├── forgot-password.js
│ │ ├── email
│ │ │ └── verify
│ │ │ │ └── [userId]
│ │ │ │ └── [hash].js
│ │ ├── index.js
│ │ ├── login.js
│ │ ├── reset-password
│ │ │ └── [token].js
│ │ └── register.js
│ ├── components
│ │ ├── Label.js
│ │ ├── Input.js
│ │ ├── AuthSessionStatus.js
│ │ ├── AuthCard.js
│ │ ├── Layouts
│ │ │ ├── GuestLayout.js
│ │ │ └── AppLayout.js
│ │ ├── Button.js
│ │ ├── InputError.js
│ │ ├── NavLink.js
│ │ ├── DropdownLink.js
│ │ ├── ResponsiveNavLink.js
│ │ ├── Dropdown.js
│ │ └── ApplicationLogo.js
│ ├── lib
│ │ ├── utils.js
│ │ ├── withValidation.js
│ │ ├── csrf.js
│ │ ├── authorize.js
│ │ ├── route-service-provider.js
│ │ ├── withAuth.js
│ │ └── axios.js
│ ├── styles
│ │ └── globals.css
│ └── contexts
│ │ └── AuthContext.js
├── next.config.mjs
├── postcss.config.mjs
├── Dockerfile
├── docker-entrypoint.sh
├── tailwind.config.js
├── .gitignore
├── package.json
├── .env.docker.dev
└── .env.example
├── LICENSE
└── docker-compose.yml
/.gitignore:
--------------------------------------------------------------------------------
1 | mysql_data
--------------------------------------------------------------------------------
/laravel/public/favicon.ico:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/laravel/resources/css/app.css:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/laravel/database/.gitignore:
--------------------------------------------------------------------------------
1 | *.sqlite*
2 |
--------------------------------------------------------------------------------
/laravel/resources/js/app.js:
--------------------------------------------------------------------------------
1 | import './bootstrap';
2 |
--------------------------------------------------------------------------------
/laravel/storage/logs/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/laravel/bootstrap/cache/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/laravel/public/robots.txt:
--------------------------------------------------------------------------------
1 | User-agent: *
2 | Disallow:
3 |
--------------------------------------------------------------------------------
/laravel/storage/app/public/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/laravel/storage/app/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !public/
3 | !.gitignore
4 |
--------------------------------------------------------------------------------
/laravel/storage/framework/sessions/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/laravel/storage/framework/testing/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/laravel/storage/framework/views/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/laravel/storage/framework/cache/data/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/nextjs/.eslintrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "next/core-web-vitals"
3 | }
4 |
--------------------------------------------------------------------------------
/laravel/storage/framework/cache/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !data/
3 | !.gitignore
4 |
--------------------------------------------------------------------------------
/nextjs/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CODE-AXION/nextjs-ssr-laravel-kit/HEAD/nextjs/public/favicon.ico
--------------------------------------------------------------------------------
/nextjs/jsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "paths": {
4 | "@/*": ["./src/*"]
5 | }
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/nextjs/src/pages/fonts/GeistVF.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CODE-AXION/nextjs-ssr-laravel-kit/HEAD/nextjs/src/pages/fonts/GeistVF.woff
--------------------------------------------------------------------------------
/nextjs/src/pages/fonts/GeistMonoVF.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CODE-AXION/nextjs-ssr-laravel-kit/HEAD/nextjs/src/pages/fonts/GeistMonoVF.woff
--------------------------------------------------------------------------------
/laravel/public/vendor/telescope/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CODE-AXION/nextjs-ssr-laravel-kit/HEAD/laravel/public/vendor/telescope/favicon.ico
--------------------------------------------------------------------------------
/nextjs/next.config.mjs:
--------------------------------------------------------------------------------
1 | /** @type {import('next').NextConfig} */
2 | const nextConfig = {
3 | reactStrictMode: true,
4 | };
5 |
6 | export default nextConfig;
7 |
--------------------------------------------------------------------------------
/nextjs/postcss.config.mjs:
--------------------------------------------------------------------------------
1 | /** @type {import('postcss-load-config').Config} */
2 | const config = {
3 | plugins: {
4 | tailwindcss: {},
5 | },
6 | };
7 |
8 | export default config;
9 |
--------------------------------------------------------------------------------
/laravel/storage/framework/.gitignore:
--------------------------------------------------------------------------------
1 | compiled.php
2 | config.php
3 | down
4 | events.scanned.php
5 | maintenance.php
6 | routes.php
7 | routes.scanned.php
8 | schedule-*
9 | services.json
10 |
--------------------------------------------------------------------------------
/nextjs/src/pages/403.js:
--------------------------------------------------------------------------------
1 | const Page = () => {
2 | return (
3 |
4 |
You are not authorized to access this page
5 |
6 | );
7 | };
8 |
9 | export default Page;
--------------------------------------------------------------------------------
/laravel/tests/TestCase.php:
--------------------------------------------------------------------------------
1 | (
2 |
5 | {children}
6 |
7 | )
8 |
9 | export default Label
10 |
--------------------------------------------------------------------------------
/laravel/.gitignore:
--------------------------------------------------------------------------------
1 | /.phpunit.cache
2 | /node_modules
3 | /public/build
4 | /public/hot
5 | /public/storage
6 | /storage/*.key
7 | /vendor
8 | .env
9 | .env.backup
10 | .env.production
11 | Homestead.json
12 | Homestead.yaml
13 | auth.json
14 | npm-debug.log
15 | yarn-error.log
16 | /.fleet
17 | /.idea
18 | /.vscode
19 |
--------------------------------------------------------------------------------
/laravel/vite.config.js:
--------------------------------------------------------------------------------
1 | import { defineConfig } from 'vite';
2 | import laravel from 'laravel-vite-plugin';
3 |
4 | export default defineConfig({
5 | plugins: [
6 | laravel({
7 | input: ['resources/css/app.css', 'resources/js/app.js'],
8 | refresh: true,
9 | }),
10 | ],
11 | });
12 |
--------------------------------------------------------------------------------
/laravel/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "private": true,
3 | "scripts": {
4 | "dev": "vite",
5 | "build": "vite build"
6 | },
7 | "devDependencies": {
8 | "@tailwindcss/forms": "^0.5.9",
9 | "axios": "^1.7.7",
10 | "laravel-vite-plugin": "^0.7.2",
11 | "vite": "^4.0.0"
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/nextjs/src/pages/_document.js:
--------------------------------------------------------------------------------
1 | import { Html, Head, Main, NextScript } from "next/document";
2 |
3 | export default function Document() {
4 | return (
5 |
6 |
8 |
9 |
10 |
11 |
12 | );
13 | }
14 |
--------------------------------------------------------------------------------
/laravel/tests/Unit/ExampleTest.php:
--------------------------------------------------------------------------------
1 | assertTrue(true);
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/nextjs/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM node:18-alpine
2 |
3 | WORKDIR /app
4 |
5 | COPY package*.json ./
6 |
7 | RUN npm install
8 |
9 | COPY . .
10 |
11 | COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
12 | RUN chmod +x /usr/local/bin/docker-entrypoint.sh
13 |
14 | EXPOSE 3000
15 |
16 | ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
17 |
--------------------------------------------------------------------------------
/laravel/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | charset = utf-8
5 | end_of_line = lf
6 | indent_size = 4
7 | indent_style = space
8 | insert_final_newline = true
9 | trim_trailing_whitespace = true
10 |
11 | [*.md]
12 | trim_trailing_whitespace = false
13 |
14 | [*.{yml,yaml}]
15 | indent_size = 2
16 |
17 | [docker-compose.yml]
18 | indent_size = 4
19 |
--------------------------------------------------------------------------------
/nextjs/docker-entrypoint.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | # Check if node_modules directory exists
4 | if [ ! -d "node_modules" ]; then
5 |
6 | npm install
7 | fi
8 |
9 | # Copy .env file if it doesn't exist
10 | if [ ! -f .env.local ]; then
11 | cp .env.docker.dev .env.local
12 | fi
13 |
14 |
15 |
16 | # Start the Next.js development server
17 | npm run dev
--------------------------------------------------------------------------------
/nextjs/src/components/Input.js:
--------------------------------------------------------------------------------
1 | const Input = ({ disabled = false, className, ...props }) => (
2 |
7 | )
8 |
9 | export default Input
10 |
--------------------------------------------------------------------------------
/laravel/app/Http/Controllers/Controller.php:
--------------------------------------------------------------------------------
1 | (
2 | <>
3 | {status && (
4 |
7 | {status}
8 |
9 | )}
10 | >
11 | )
12 |
13 | export default AuthSessionStatus
14 |
--------------------------------------------------------------------------------
/laravel/apache-config.conf:
--------------------------------------------------------------------------------
1 |
2 | ServerName localhost
3 | DocumentRoot ${APACHE_DOCUMENT_ROOT}
4 |
5 |
6 | Options Indexes FollowSymLinks
7 | AllowOverride All
8 | Require all granted
9 |
10 |
11 | ErrorLog ${APACHE_LOG_DIR}/error.log
12 | CustomLog ${APACHE_LOG_DIR}/access.log combined
13 |
--------------------------------------------------------------------------------
/laravel/app/Http/Middleware/EncryptCookies.php:
--------------------------------------------------------------------------------
1 |
13 | */
14 | protected $except = [
15 | //
16 | ];
17 | }
18 |
--------------------------------------------------------------------------------
/laravel/app/Http/Middleware/VerifyCsrfToken.php:
--------------------------------------------------------------------------------
1 |
13 | */
14 | protected $except = [
15 | //
16 | ];
17 | }
18 |
--------------------------------------------------------------------------------
/nextjs/src/components/AuthCard.js:
--------------------------------------------------------------------------------
1 | const AuthCard = ({ logo, children }) => (
2 |
3 |
{logo}
4 |
5 |
6 | {children}
7 |
8 |
9 | )
10 |
11 | export default AuthCard
12 |
--------------------------------------------------------------------------------
/nextjs/src/components/Layouts/GuestLayout.js:
--------------------------------------------------------------------------------
1 | import Head from 'next/head'
2 |
3 | const GuestLayout = ({ children }) => {
4 | return (
5 |
6 |
7 |
Laravel
8 |
9 |
10 |
11 | {children}
12 |
13 |
14 | )
15 | }
16 |
17 | export default GuestLayout
--------------------------------------------------------------------------------
/laravel/tests/Feature/ExampleTest.php:
--------------------------------------------------------------------------------
1 | get('/');
16 |
17 | $response->assertStatus(200);
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/laravel/app/Providers/BroadcastServiceProvider.php:
--------------------------------------------------------------------------------
1 |
13 | */
14 | protected $except = [
15 | //
16 | ];
17 | }
18 |
--------------------------------------------------------------------------------
/laravel/tests/CreatesApplication.php:
--------------------------------------------------------------------------------
1 | make(Kernel::class)->bootstrap();
18 |
19 | return $app;
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/nextjs/src/pages/_app.js:
--------------------------------------------------------------------------------
1 | import "@/styles/globals.css";
2 | import { AuthProvider } from "@/contexts/AuthContext";
3 | import { ToastContainer } from 'react-toastify';
4 | import 'react-toastify/dist/ReactToastify.css';
5 |
6 | export default function App({Component, pageProps: { session, ...pageProps }}) {
7 |
8 | return (
9 |
10 |
11 |
12 |
13 | );
14 | }
15 |
--------------------------------------------------------------------------------
/nextjs/tailwind.config.js:
--------------------------------------------------------------------------------
1 | /** @type {import('tailwindcss').Config} */
2 | module.exports = {
3 | content: [
4 | "./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
5 | "./src/components/**/*.{js,ts,jsx,tsx,mdx}",
6 | "./src/app/**/*.{js,ts,jsx,tsx,mdx}",
7 | ],
8 | theme: {
9 | extend: {
10 | colors: {
11 | background: "var(--background)",
12 | foreground: "var(--foreground)",
13 | },
14 | },
15 | },
16 | plugins: [require('@tailwindcss/forms')],
17 | };
18 |
--------------------------------------------------------------------------------
/laravel/app/Http/Middleware/TrimStrings.php:
--------------------------------------------------------------------------------
1 |
13 | */
14 | protected $except = [
15 | 'current_password',
16 | 'password',
17 | 'password_confirmation',
18 | ];
19 | }
20 |
--------------------------------------------------------------------------------
/laravel/app/Http/Middleware/TrustHosts.php:
--------------------------------------------------------------------------------
1 |
13 | */
14 | public function hosts(): array
15 | {
16 | return [
17 | $this->allSubdomainsOfApplicationUrl(),
18 | ];
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/laravel/app/Http/Middleware/Authenticate.php:
--------------------------------------------------------------------------------
1 | expectsJson() ? null : route('login');
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/nextjs/src/components/Button.js:
--------------------------------------------------------------------------------
1 | const Button = ({ type = 'submit', className, ...props }) => (
2 |
7 | )
8 |
9 | export default Button
10 |
--------------------------------------------------------------------------------
/nextjs/src/components/InputError.js:
--------------------------------------------------------------------------------
1 | const InputError = ({ messages = [], className = '' }) => (
2 | <>
3 | {messages.length > 0 && (
4 | <>
5 | {messages.map((message, index) => (
6 |
9 | {message}
10 |
11 | ))}
12 | >
13 | )}
14 | >
15 | )
16 |
17 | export default InputError
18 |
--------------------------------------------------------------------------------
/nextjs/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 | .yarn/install-state.gz
8 |
9 | # testing
10 | /coverage
11 |
12 | # next.js
13 | /.next/
14 | /out/
15 |
16 | # production
17 | /build
18 |
19 | # misc
20 | .DS_Store
21 | *.pem
22 |
23 | # debug
24 | npm-debug.log*
25 | yarn-debug.log*
26 | yarn-error.log*
27 |
28 | # local env files
29 | .env*.local
30 |
31 | # vercel
32 | .vercel
33 |
34 | # typescript
35 | *.tsbuildinfo
36 | next-env.d.ts
37 |
--------------------------------------------------------------------------------
/laravel/routes/web.php:
--------------------------------------------------------------------------------
1 |
13 | */
14 | protected $except = [
15 | // 'fbclid',
16 | // 'utm_campaign',
17 | // 'utm_content',
18 | // 'utm_medium',
19 | // 'utm_source',
20 | // 'utm_term',
21 | ];
22 | }
23 |
--------------------------------------------------------------------------------
/nextjs/src/styles/globals.css:
--------------------------------------------------------------------------------
1 | @tailwind base;
2 | @tailwind components;
3 | @tailwind utilities;
4 |
5 | :root {
6 | --background: #ffffff;
7 | --foreground: #171717;
8 | }
9 |
10 | @media (prefers-color-scheme: dark) {
11 | :root {
12 | --background: #0a0a0a;
13 | --foreground: #ededed;
14 | }
15 | }
16 |
17 | body {
18 | color: var(--foreground);
19 | background: var(--background);
20 | font-family: Arial, Helvetica, sans-serif;
21 | }
22 |
23 | @layer utilities {
24 | .text-balance {
25 | text-wrap: balance;
26 | }
27 | }
28 |
29 | .canvas-container{
30 | margin-inline: auto !important;
31 | }
--------------------------------------------------------------------------------
/laravel/routes/channels.php:
--------------------------------------------------------------------------------
1 | id === (int) $id;
18 | });
19 |
--------------------------------------------------------------------------------
/nextjs/src/components/NavLink.js:
--------------------------------------------------------------------------------
1 | import Link from 'next/link'
2 |
3 | const NavLink = ({ active = false, children, ...props }) => (
4 |
11 | {children}
12 |
13 | )
14 |
15 | export default NavLink
16 |
--------------------------------------------------------------------------------
/nextjs/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "laravel-nextjs-auth-starter-kit",
3 | "version": "0.1.0",
4 | "private": true,
5 | "scripts": {
6 | "dev": "next dev",
7 | "build": "next build",
8 | "start": "next start",
9 | "lint": "next lint"
10 | },
11 | "dependencies": {
12 | "@headlessui/react": "^2.2.0",
13 | "axios": "^1.7.7",
14 | "next": "14.2.17",
15 | "react": "^18",
16 | "react-dom": "^18",
17 | "react-toastify": "^10.0.6"
18 | },
19 | "devDependencies": {
20 | "@tailwindcss/forms": "^0.5.9",
21 | "eslint": "^8",
22 | "eslint-config-next": "14.2.17",
23 | "postcss": "^8",
24 | "tailwindcss": "^3.4.1"
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/laravel/routes/console.php:
--------------------------------------------------------------------------------
1 | comment(Inspiring::quote());
19 | })->purpose('Display an inspiring quote');
20 |
--------------------------------------------------------------------------------
/nextjs/.env.docker.dev:
--------------------------------------------------------------------------------
1 | # Important
2 | # When your app is running inside a docker container, localhost points no longer to your development laptop (or server) it points to the container itself.
3 | # As each application is running in separeted container when the front access to the back, you cannot use localhost. As localhost points to the front container, and the back is not deployed there.
4 | # You should use the container name instead localhost when specificying the connection urls.
5 | # In this case, the container name is laravel-app.
6 | NEXT_BACKEND_URL=http://laravel-app
7 | CSRF_SECRET_KEY=secret #generate a random string
8 | USE_SECURE_COOKIES=false
9 | COOKIE_PREFIX=__Host-
10 | ENVIRONMENT=local
--------------------------------------------------------------------------------
/nextjs/src/pages/api/auth/verify.js:
--------------------------------------------------------------------------------
1 | import { verifyCsrfToken } from "@/lib/csrf";
2 |
3 | export default function handler(req, res) {
4 |
5 | if (req.method !== 'POST') {
6 | return res.status(405).json({ message: 'Method not allowed' });
7 | }
8 |
9 | const { csrf_token, csrf_signature } = req.cookies;
10 |
11 | if (!csrf_token || !csrf_signature) {
12 | return res.status(419).json({ message: "CSRF token missing" });
13 | }
14 | if (!verifyCsrfToken(csrf_token, csrf_signature)) {
15 | return res.status(419).json({ message: "CSRF token invalid" });
16 | }
17 |
18 | res.status(200).json({ message: "CSRF token verified" });
19 |
20 | }
21 |
22 |
--------------------------------------------------------------------------------
/laravel/public/.htaccess:
--------------------------------------------------------------------------------
1 |
2 |
3 | Options -MultiViews -Indexes
4 |
5 |
6 | RewriteEngine On
7 |
8 | # Handle Authorization Header
9 | RewriteCond %{HTTP:Authorization} .
10 | RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
11 |
12 | # Redirect Trailing Slashes If Not A Folder...
13 | RewriteCond %{REQUEST_FILENAME} !-d
14 | RewriteCond %{REQUEST_URI} (.+)/$
15 | RewriteRule ^ %1 [L,R=301]
16 |
17 | # Send Requests To Front Controller...
18 | RewriteCond %{REQUEST_FILENAME} !-d
19 | RewriteCond %{REQUEST_FILENAME} !-f
20 | RewriteRule ^ index.php [L]
21 |
22 |
--------------------------------------------------------------------------------
/laravel/docker-entrypoint.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Install composer dependencies
4 | echo "Installing composer dependencies..."
5 | composer install --no-interaction --optimize-autoloader
6 |
7 | echo "Copying .env file..."
8 |
9 | # Copy .env file if it doesn't exist
10 | if [ ! -f .env ]; then
11 | cp .env.docker.dev .env
12 | fi
13 |
14 | echo "Generating application key..."
15 | # Generate application key if not already set
16 | php artisan key:generate --no-interaction --force
17 |
18 | echo "Running migrations and seeding..."
19 | # Run migrations and seed
20 | php artisan migrate --seed --no-interaction --force
21 |
22 | echo "Starting Apache..."
23 |
24 | # Start Apache
25 | apache2-foreground
26 |
--------------------------------------------------------------------------------
/laravel/app/Console/Kernel.php:
--------------------------------------------------------------------------------
1 | command('inspire')->hourly();
16 | }
17 |
18 | /**
19 | * Register the commands for the application.
20 | */
21 | protected function commands(): void
22 | {
23 | $this->load(__DIR__.'/Commands');
24 |
25 | require base_path('routes/console.php');
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/laravel/app/Providers/AppServiceProvider.php:
--------------------------------------------------------------------------------
1 | app->environment('local')) {
15 | $this->app->register(\Laravel\Telescope\TelescopeServiceProvider::class);
16 | $this->app->register(TelescopeServiceProvider::class);
17 | }
18 | }
19 |
20 | /**
21 | * Bootstrap any application services.
22 | */
23 | public function boot(): void
24 | {
25 | //
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/nextjs/src/pages/profile.js:
--------------------------------------------------------------------------------
1 | import { useAuth } from "@/contexts/AuthContext";
2 | import { useRouter } from "next/router";
3 |
4 | export default function Profile() {
5 |
6 | const { user } = useAuth();
7 | const router = useRouter();
8 |
9 | return (
10 |
11 |
{user?.name}
12 |
{user?.email}
13 |
router.push('/dashboard')}>back to dashboard
14 |
15 | );
16 | }
17 |
18 | // export async function getServerSideProps(context) {
19 | // // const session = await getServerSession(context.req, context.res, authOptions);
20 | // return {
21 | // props: {}
22 | // };
23 | // }
24 |
--------------------------------------------------------------------------------
/nextjs/src/pages/api/auth/user.js:
--------------------------------------------------------------------------------
1 | import axios from "axios";
2 | import { createAxiosInstance } from "@/lib/axios";
3 | import { USER_ROUTE } from '@/lib/route-service-provider';
4 |
5 | export default async function handler(req, res) {
6 | try {
7 | const axios = createAxiosInstance(req, res);
8 | const response = await axios.get(USER_ROUTE);
9 |
10 | res.status(200).json(response.data);
11 | } catch (error) {
12 |
13 | if (error.response && error.response.data) {
14 |
15 | res.status(error.response.status).json(error.response.data);
16 | } else {
17 | res.status(500).json({ message: 'Internal Server Error' });
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/nextjs/.env.example:
--------------------------------------------------------------------------------
1 | # use this for docker
2 | # When your app is running inside a docker container, localhost points no longer to your development laptop (or server) it points to the container itself.
3 | # As each application is running in separeted container when the front access to the back, you cannot use localhost. As localhost points to the front container, and the back is not deployed there.
4 | # You should use the container name instead localhost when specificying the connection urls.
5 | # In this case, the container name is laravel-app.
6 | NEXT_BACKEND_URL=http://laravel-app
7 |
8 | # use this for local
9 | # NEXT_BACKEND_URL=http://localhost:8000
10 |
11 | CSRF_SECRET_KEY=secret #generate a random string
12 | USE_SECURE_COOKIES=false
13 | COOKIE_PREFIX=__Host-
14 | ENVIRONMENT=local
--------------------------------------------------------------------------------
/laravel/app/Http/Middleware/TrustProxies.php:
--------------------------------------------------------------------------------
1 | |string|null
14 | */
15 | protected $proxies;
16 |
17 | /**
18 | * The headers that should be used to detect proxies.
19 | *
20 | * @var int
21 | */
22 | protected $headers =
23 | Request::HEADER_X_FORWARDED_FOR |
24 | Request::HEADER_X_FORWARDED_HOST |
25 | Request::HEADER_X_FORWARDED_PORT |
26 | Request::HEADER_X_FORWARDED_PROTO |
27 | Request::HEADER_X_FORWARDED_AWS_ELB;
28 | }
29 |
--------------------------------------------------------------------------------
/nextjs/src/components/Layouts/AppLayout.js:
--------------------------------------------------------------------------------
1 | import Navigation from '@/components/Layouts/Navigation'
2 | import { useAuth } from '@/contexts/AuthContext';
3 |
4 | const AppLayout = ({ header, children }) => {
5 | // const { user } = useAuth({ middleware: 'auth' })
6 | const { user } = useAuth();
7 |
8 | return (
9 |
10 |
11 |
12 | {/* Page Heading */}
13 |
14 |
15 | {header}
16 |
17 |
18 |
19 | {/* Page Content */}
20 |
{children}
21 |
22 | )
23 | }
24 |
25 | export default AppLayout
--------------------------------------------------------------------------------
/laravel/database/migrations/2014_10_12_100000_create_password_reset_tokens_table.php:
--------------------------------------------------------------------------------
1 | string('email')->primary();
16 | $table->string('token');
17 | $table->timestamp('created_at')->nullable();
18 | });
19 | }
20 |
21 | /**
22 | * Reverse the migrations.
23 | */
24 | public function down(): void
25 | {
26 | Schema::dropIfExists('password_reset_tokens');
27 | }
28 | };
29 |
--------------------------------------------------------------------------------
/laravel/app/Http/Controllers/Auth/EmailVerificationNotificationController.php:
--------------------------------------------------------------------------------
1 | user()->hasVerifiedEmail()) {
19 | return response()->json(['message' => 'Email already verified']);
20 | }
21 |
22 | $request->user()->notify(new VerifyEmail);
23 |
24 | return response()->json(['status' => 'verification-link-sent']);
25 | }
26 | }
--------------------------------------------------------------------------------
/laravel/app/Http/Middleware/EnsureEmailIsVerified.php:
--------------------------------------------------------------------------------
1 | user() || ($request->user() instanceof MustVerifyEmail && ! $request->user()->hasVerifiedEmail())) {
20 | return response()->json(['message' => 'Your email address is not verified.'], 409);
21 | }
22 |
23 | return $next($request);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/nextjs/src/pages/api/auth/forgot-password.js:
--------------------------------------------------------------------------------
1 | import axios from "axios";
2 | import { withValidation } from "@/lib/withValidation";
3 | import { FORGOT_PASSWORD_ROUTE } from '@/lib/route-service-provider';
4 |
5 | export const handler = async (req, res) => {
6 |
7 | try {
8 | const { email } = req.body;
9 |
10 | const response = await axios.post(`${process.env.NEXT_BACKEND_URL}${FORGOT_PASSWORD_ROUTE}`, { email });
11 |
12 | res.status(200).json(response.data);
13 | } catch (error) {
14 |
15 | if (error.response && error.response.data) {
16 | res.status(error.response.status).json(error.response.data);
17 | } else {
18 | res.status(500).json({ message: 'Internal Server Error' });
19 | }
20 | }
21 | }
22 |
23 | export default withValidation({ verifyCsrfTokenCheck: true })(handler);
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/laravel/app/Http/Middleware/RedirectIfAuthenticated.php:
--------------------------------------------------------------------------------
1 | check()) {
24 | return redirect(RouteServiceProvider::HOME);
25 | }
26 | }
27 |
28 | return $next($request);
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/nextjs/src/pages/api/auth/reset-password.js:
--------------------------------------------------------------------------------
1 | import axios from "axios";
2 | import { withValidation } from "@/lib/withValidation";
3 | import { RESET_PASSWORD_ROUTE } from '@/lib/route-service-provider';
4 |
5 | const handler = async (req, res) => {
6 |
7 | try {
8 | const { token, email, password, password_confirmation } = req.body;
9 |
10 | const response = await axios.post(`${process.env.NEXT_BACKEND_URL}${RESET_PASSWORD_ROUTE}`, { token, email, password, password_confirmation });
11 |
12 | res.status(200).json(response.data);
13 | } catch (error) {
14 |
15 | if (error.response && error.response.data) {
16 | res.status(error.response.status).json(error.response.data);
17 | } else {
18 | res.status(500).json({ message: 'Internal Server Error' });
19 | }
20 | }
21 |
22 | }
23 |
24 | export default withValidation({ verifyCsrfTokenCheck: true })(handler);
25 |
26 |
--------------------------------------------------------------------------------
/laravel/database/migrations/2014_10_12_000000_create_users_table.php:
--------------------------------------------------------------------------------
1 | id();
16 | $table->string('name');
17 | $table->string('email')->unique();
18 | $table->timestamp('email_verified_at')->nullable();
19 | $table->string('password');
20 | $table->rememberToken();
21 | $table->timestamps();
22 | });
23 | }
24 |
25 | /**
26 | * Reverse the migrations.
27 | */
28 | public function down(): void
29 | {
30 | Schema::dropIfExists('users');
31 | }
32 | };
33 |
--------------------------------------------------------------------------------
/laravel/database/migrations/2019_08_19_000000_create_failed_jobs_table.php:
--------------------------------------------------------------------------------
1 | id();
16 | $table->string('uuid')->unique();
17 | $table->text('connection');
18 | $table->text('queue');
19 | $table->longText('payload');
20 | $table->longText('exception');
21 | $table->timestamp('failed_at')->useCurrent();
22 | });
23 | }
24 |
25 | /**
26 | * Reverse the migrations.
27 | */
28 | public function down(): void
29 | {
30 | Schema::dropIfExists('failed_jobs');
31 | }
32 | };
33 |
--------------------------------------------------------------------------------
/nextjs/src/pages/api/auth/email/verify-email-notification.js:
--------------------------------------------------------------------------------
1 | import { createAxiosInstance } from '@/lib/axios';
2 | import { withValidation } from "@/lib/withValidation";
3 | import { EMAIL_VERIFICATION_NOTIFICATION_ROUTE } from '@/lib/route-service-provider';
4 |
5 | const handler = async (req, res) => {
6 | if (req.method !== 'POST') {
7 | return res.status(405).json({ message: 'Method Not Allowed' });
8 | }
9 |
10 | const axios = createAxiosInstance(req, res);
11 |
12 | try {
13 | const response = await axios.post(EMAIL_VERIFICATION_NOTIFICATION_ROUTE);
14 |
15 | return res.status(response.status).json(response.data);
16 |
17 | } catch (error) {
18 | if (error.response && error.response.data) {
19 | res.status(error.response.status).json(error.response.data);
20 | } else {
21 | res.status(500).json({ message: 'Internal Server Error' });
22 | }
23 | }
24 | }
25 |
26 | export default withValidation({ verifyCsrfTokenCheck: true })(handler);
27 |
28 |
--------------------------------------------------------------------------------
/laravel/app/Providers/AuthServiceProvider.php:
--------------------------------------------------------------------------------
1 |
16 | */
17 | protected $policies = [
18 | // 'App\Models\Model' => 'App\Policies\ModelPolicy',
19 | ];
20 |
21 | /**
22 | * Register any authentication / authorization services.
23 | */
24 | public function boot(): void
25 | {
26 | $this->registerPolicies();
27 |
28 | ResetPassword::createUrlUsing(function ($user, string $token) {
29 | return config('app.frontend_url') . '/reset-password/' . $token . '?email=' . $user->email;
30 | });
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/laravel/config/cors.php:
--------------------------------------------------------------------------------
1 | ['api/*', 'sanctum/csrf-cookie'],
19 |
20 | 'allowed_methods' => ['*'],
21 |
22 | 'allowed_origins' => ['http://localhost:3000'],
23 |
24 | 'allowed_origins_patterns' => [],
25 |
26 | 'allowed_headers' => ['*'],
27 |
28 | 'exposed_headers' => [],
29 |
30 | 'max_age' => 0,
31 |
32 | 'supports_credentials' => true,
33 |
34 | ];
35 |
--------------------------------------------------------------------------------
/laravel/database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php:
--------------------------------------------------------------------------------
1 | id();
16 | $table->morphs('tokenable');
17 | $table->string('name');
18 | $table->string('token', 64)->unique();
19 | $table->text('abilities')->nullable();
20 | $table->timestamp('last_used_at')->nullable();
21 | $table->timestamp('expires_at')->nullable();
22 | $table->timestamps();
23 | });
24 | }
25 |
26 | /**
27 | * Reverse the migrations.
28 | */
29 | public function down(): void
30 | {
31 | Schema::dropIfExists('personal_access_tokens');
32 | }
33 | };
34 |
--------------------------------------------------------------------------------
/laravel/app/Providers/EventServiceProvider.php:
--------------------------------------------------------------------------------
1 | >
16 | */
17 | protected $listen = [
18 | Registered::class => [
19 | SendEmailVerificationNotification::class,
20 | ],
21 | ];
22 |
23 | /**
24 | * Register any events for your application.
25 | */
26 | public function boot(): void
27 | {
28 | //
29 | }
30 |
31 | /**
32 | * Determine if events and listeners should be automatically discovered.
33 | */
34 | public function shouldDiscoverEvents(): bool
35 | {
36 | return false;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/laravel/config/services.php:
--------------------------------------------------------------------------------
1 | [
18 | 'domain' => env('MAILGUN_DOMAIN'),
19 | 'secret' => env('MAILGUN_SECRET'),
20 | 'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
21 | 'scheme' => 'https',
22 | ],
23 |
24 | 'postmark' => [
25 | 'token' => env('POSTMARK_TOKEN'),
26 | ],
27 |
28 | 'ses' => [
29 | 'key' => env('AWS_ACCESS_KEY_ID'),
30 | 'secret' => env('AWS_SECRET_ACCESS_KEY'),
31 | 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
32 | ],
33 |
34 | ];
35 |
--------------------------------------------------------------------------------
/nextjs/src/pages/api/auth/email/verify-email.js:
--------------------------------------------------------------------------------
1 | import { createAxiosInstance } from '@/lib/axios';
2 | import { withValidation } from "@/lib/withValidation";
3 | import { VERIFY_HASH_ROUTE, getDynamicRoute } from '@/lib/route-service-provider';
4 |
5 | export const handler = async (req, res) => {
6 |
7 | try {
8 | const { userId, hash, expires, signature } = req.query;
9 |
10 | const axios = createAxiosInstance(req, res);
11 | const response = await axios.get(getDynamicRoute(VERIFY_HASH_ROUTE, { userId, hash, expires, signature }));
12 |
13 | res.status(200).json(response.data);
14 |
15 | } catch (error) {
16 |
17 | if (error.response && error.response.data) {
18 | res.status(error.response.status).json({
19 | success: false,
20 | error: error.response.data.message,
21 | data: error.response.data,
22 | });
23 | } else {
24 | res.status(500).json({ message: 'Internal Server Error' });
25 | }
26 | }
27 | }
28 |
29 | export default withValidation({ verifyCsrfTokenCheck: true })(handler);
30 |
31 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2024 Rayees Aadil
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/nextjs/src/components/DropdownLink.js:
--------------------------------------------------------------------------------
1 | import Link from 'next/link'
2 | import { Menu } from '@headlessui/react'
3 |
4 | const DropdownLink = ({ children, ...props }) => (
5 |
6 | {({ active }) => (
7 |
12 | {children}
13 |
14 | )}
15 |
16 | )
17 |
18 | export const DropdownButton = ({ children, ...props }) => (
19 |
20 | {({ active }) => (
21 |
26 | {children}
27 |
28 | )}
29 |
30 | )
31 |
32 | export default DropdownLink
33 |
--------------------------------------------------------------------------------
/nextjs/src/components/ResponsiveNavLink.js:
--------------------------------------------------------------------------------
1 | import Link from 'next/link'
2 |
3 | const ResponsiveNavLink = ({ active = false, children, ...props }) => (
4 |
11 | {children}
12 |
13 | )
14 |
15 | export const ResponsiveNavButton = props => (
16 |
20 | )
21 |
22 | export default ResponsiveNavLink
23 |
--------------------------------------------------------------------------------
/laravel/database/factories/UserFactory.php:
--------------------------------------------------------------------------------
1 |
10 | */
11 | class UserFactory extends Factory
12 | {
13 | /**
14 | * Define the model's default state.
15 | *
16 | * @return array
17 | */
18 | public function definition(): array
19 | {
20 | return [
21 | 'name' => fake()->name(),
22 | 'email' => fake()->unique()->safeEmail(),
23 | 'email_verified_at' => now(),
24 | 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
25 | 'remember_token' => Str::random(10),
26 | ];
27 | }
28 |
29 | /**
30 | * Indicate that the model's email address should be unverified.
31 | *
32 | * @return $this
33 | */
34 | public function unverified(): static
35 | {
36 | return $this->state(fn (array $attributes) => [
37 | 'email_verified_at' => null,
38 | ]);
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/laravel/app/Models/User.php:
--------------------------------------------------------------------------------
1 |
20 | */
21 | protected $fillable = [
22 | 'name',
23 | 'email',
24 | 'password',
25 | ];
26 |
27 | /**
28 | * The attributes that should be hidden for serialization.
29 | *
30 | * @var array
31 | */
32 | protected $hidden = [
33 | 'password',
34 | 'remember_token',
35 | ];
36 |
37 | /**
38 | * The attributes that should be cast.
39 | *
40 | * @var array
41 | */
42 | protected $casts = [
43 | 'email_verified_at' => 'datetime',
44 | ];
45 | }
46 |
--------------------------------------------------------------------------------
/laravel/config/view.php:
--------------------------------------------------------------------------------
1 | [
17 | resource_path('views'),
18 | ],
19 |
20 | /*
21 | |--------------------------------------------------------------------------
22 | | Compiled View Path
23 | |--------------------------------------------------------------------------
24 | |
25 | | This option determines where all the compiled Blade templates will be
26 | | stored for your application. Typically, this is within the storage
27 | | directory. However, as usual, you are free to change this value.
28 | |
29 | */
30 |
31 | 'compiled' => env(
32 | 'VIEW_COMPILED_PATH',
33 | realpath(storage_path('framework/views'))
34 | ),
35 |
36 | ];
37 |
--------------------------------------------------------------------------------
/nextjs/src/lib/withValidation.js:
--------------------------------------------------------------------------------
1 | import { verifyCsrfToken } from '@/lib/csrf';
2 | import { defaultValue } from '@/lib/csrf';
3 |
4 | /**
5 | * This function is used to wrap a Next.js API route with csrf protection logic.
6 | *
7 | * @param {object} options - The options object.
8 | * @param {boolean} options.verifyCsrfTokenCheck - Whether to check for a CSRF token. default is false.
9 | *
10 | * @returns {function} - The wrapped function.
11 | */
12 | export const withValidation = (options = {}) => (handler) => async (req, res) => {
13 | const { apiKey = false, verifyCsrfTokenCheck = false } = options;
14 |
15 | // if (apiKey && !validateApiKey(req)) {
16 | // return res.status(401).json({ error: 'Unauthorized: Invalid API key' });
17 | // }
18 |
19 | const csrfToken = defaultValue(req);
20 | if(!req.cookies.csrf_token || !req.cookies.csrf_signature || !csrfToken) {
21 | return res.status(419).json({ error: 'CSRF token missing' });
22 | }
23 |
24 | if (verifyCsrfTokenCheck && !verifyCsrfToken(req.cookies.csrf_token, req.cookies.csrf_signature, csrfToken)) {
25 | return res.status(419).json({ error: 'CSRF token invalid' });
26 | }
27 |
28 | return handler(req, res);
29 | };
30 |
--------------------------------------------------------------------------------
/laravel/app/Exceptions/Handler.php:
--------------------------------------------------------------------------------
1 | , \Psr\Log\LogLevel::*>
14 | */
15 | protected $levels = [
16 | //
17 | ];
18 |
19 | /**
20 | * A list of the exception types that are not reported.
21 | *
22 | * @var array>
23 | */
24 | protected $dontReport = [
25 | //
26 | ];
27 |
28 | /**
29 | * A list of the inputs that are never flashed to the session on validation exceptions.
30 | *
31 | * @var array
32 | */
33 | protected $dontFlash = [
34 | 'current_password',
35 | 'password',
36 | 'password_confirmation',
37 | ];
38 |
39 | /**
40 | * Register the exception handling callbacks for the application.
41 | */
42 | public function register(): void
43 | {
44 | $this->reportable(function (Throwable $e) {
45 | //
46 | });
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/laravel/phpunit.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
9 | ./tests/Unit
10 |
11 |
12 | ./tests/Feature
13 |
14 |
15 |
16 |
17 | ./app
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/nextjs/src/lib/csrf.js:
--------------------------------------------------------------------------------
1 | import crypto from "crypto";
2 |
3 | const secretKey = process.env.CSRF_SECRET_KEY;
4 |
5 | export const generateCsrfToken = () => {
6 | const token = crypto.randomBytes(32).toString('hex'); // Random token
7 | const signature = crypto.createHmac('sha256', secretKey).update(token).digest('hex');
8 |
9 | return { token, signature };
10 | };
11 |
12 |
13 | export const verifyCsrfToken = (token, signature, bodyToken) => {
14 |
15 | const validSignature = crypto.createHmac('sha256', secretKey).update(token).digest('hex');
16 | return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(validSignature)) && token === bodyToken;
17 | };
18 |
19 | /**
20 | * Default Value function, checking req.body
21 | * and req.query for the csrf token
22 | *
23 | * @param {*} req
24 | * @return {String} csrf token
25 | */
26 |
27 | export const defaultValue = (req) => {
28 |
29 | return (req.body && req.body._csrf) ||
30 | (req.body && req.body.csrf_token) ||
31 | (req.headers && req.headers['csrf_token']) ||
32 | (req.headers && req.headers['csrf-token']) ||
33 | (req.headers && req.headers['xsrf-token']) ||
34 | (req.headers && req.headers['x-csrf-token']) ||
35 | (req.headers && req.headers['x-xsrf-token']);
36 | };
37 |
--------------------------------------------------------------------------------
/nextjs/src/pages/api/auth/csrf.js:
--------------------------------------------------------------------------------
1 | import { generateCsrfToken } from "@/lib/csrf";
2 |
3 | export default function handler(req, res) {
4 | if (req.method !== 'GET') {
5 | return res.status(405).json({ error: 'Method not allowed' });
6 | }
7 |
8 | const { token, signature } = generateCsrfToken();
9 |
10 | let csrfCookiePrefix = process.env.ENVIRONMENT === 'local' ? '' : process.env.COOKIE_PREFIX;
11 |
12 | // Using signed cookies to prevent CSRF
13 | // https://owasp.org/www-chapter-london/assets/slides/David_Johansson-Double_Defeat_of_Double-Submit_Cookie.pdf
14 | // https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html
15 |
16 | // Securing cookies using OWASP recommendations
17 | // https://owasp.org/www-chapter-london/assets/slides/OWASPLondon20171130_Cookie_Security_Myths_Misconceptions_David_Johansson.pdf
18 |
19 | // create http only cookie with the token
20 | res.setHeader('Set-Cookie', [
21 | `${csrfCookiePrefix}csrf_token=${token}; HttpOnly; Path=/; Secure; SameSite=Lax; Max-Age=3600`,
22 | `${csrfCookiePrefix}csrf_signature=${signature}; HttpOnly; Path=/; Secure; SameSite=Lax; Max-Age=3600`,
23 | ]);
24 |
25 | res.status(200).json({ token, signature });
26 | }
27 |
28 |
--------------------------------------------------------------------------------
/laravel/app/Http/Controllers/Auth/VerifyEmailController.php:
--------------------------------------------------------------------------------
1 | user()->hasVerifiedEmail()) {
19 | return response()->json([
20 | 'status' => 'redirect',
21 | 'message' => 'Email already verified',
22 | 'redirect_url' => config('app.frontend_url').RouteServiceProvider::HOME.'?verified=1'
23 | ]);
24 | }
25 |
26 | if ($request->user()->markEmailAsVerified()) {
27 | event(new Verified($request->user()));
28 | }
29 |
30 | return response()->json([
31 | 'status' => 'redirect',
32 | 'message' => 'Email verified',
33 | 'redirect_url' => config('app.frontend_url').RouteServiceProvider::HOME.'?verified=1'
34 | ]);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/laravel/README.md:
--------------------------------------------------------------------------------
1 | # Laravel 10
2 |
3 | ## Introduction
4 |
5 | This is a laravel 10 backend for a nextjs frontend which includes authentication, authorization, csrf protection, and more.
6 | This includes Token based authentication using Access Token and Refresh Token Logic.
7 |
8 | #### Important Note:
9 | > Note: After this Setup you need to setup the Nextjs frontend and set the NEXT_BACKEND_URL (optional if you want to use the default url) in the .env.local file.
10 |
11 |
12 | ## Prerequisites
13 |
14 | - Laravel Sanctum (Token Based Authentication)
15 |
16 | ### Installation
17 |
18 | First clone this laravel backend and install its dependencies.
19 |
20 | ```
21 | git clone https://github.com/CODE-AXION/laravel-next-ssr.git
22 | ```
23 |
24 | ```
25 | composer install
26 | ```
27 |
28 | ```
29 | php artisan migrate
30 | ```
31 |
32 | ```
33 | php artisan db:seed
34 | ```
35 |
36 | ```
37 | php artisan serve --host=localhost --port=8000
38 | ```
39 |
40 | ### Additional Information:
41 | - Reset password url is set in the AuthServiceProvider.php file
42 |
43 | ```php
44 | ResetPassword::createUrlUsing(function ($user, string $token) {
45 | return config('app.frontend_url') . '/reset-password/' . $token . '?email=' . $user->email;
46 | });
47 | ```
48 |
49 |
50 | - Email verification url and mail is set in the Notifications/VerifyEmail.php file
--------------------------------------------------------------------------------
/laravel/resources/js/bootstrap.js:
--------------------------------------------------------------------------------
1 | /**
2 | * We'll load the axios HTTP library which allows us to easily issue requests
3 | * to our Laravel back-end. This library automatically handles sending the
4 | * CSRF token as a header based on the value of the "XSRF" token cookie.
5 | */
6 |
7 | import axios from 'axios';
8 | window.axios = axios;
9 |
10 | window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
11 |
12 | /**
13 | * Echo exposes an expressive API for subscribing to channels and listening
14 | * for events that are broadcast by Laravel. Echo and event broadcasting
15 | * allows your team to easily build robust real-time web applications.
16 | */
17 |
18 | // import Echo from 'laravel-echo';
19 |
20 | // import Pusher from 'pusher-js';
21 | // window.Pusher = Pusher;
22 |
23 | // window.Echo = new Echo({
24 | // broadcaster: 'pusher',
25 | // key: import.meta.env.VITE_PUSHER_APP_KEY,
26 | // cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER ?? 'mt1',
27 | // wsHost: import.meta.env.VITE_PUSHER_HOST ? import.meta.env.VITE_PUSHER_HOST : `ws-${import.meta.env.VITE_PUSHER_APP_CLUSTER}.pusher.com`,
28 | // wsPort: import.meta.env.VITE_PUSHER_PORT ?? 80,
29 | // wssPort: import.meta.env.VITE_PUSHER_PORT ?? 443,
30 | // forceTLS: (import.meta.env.VITE_PUSHER_SCHEME ?? 'https') === 'https',
31 | // enabledTransports: ['ws', 'wss'],
32 | // });
33 |
--------------------------------------------------------------------------------
/laravel/.env.example:
--------------------------------------------------------------------------------
1 | APP_NAME=Laravel
2 | APP_ENV=local
3 | APP_KEY=
4 | APP_DEBUG=true
5 | APP_URL=http://localhost
6 |
7 | API_URL=http://localhost:8000/api
8 | FRONTEND_URL=http://localhost:3000
9 |
10 | LOG_CHANNEL=stack
11 | LOG_DEPRECATIONS_CHANNEL=null
12 | LOG_LEVEL=debug
13 |
14 | DB_CONNECTION=mysql
15 | DB_HOST=127.0.0.1
16 | DB_PORT=3306
17 | DB_DATABASE=laravel_react
18 | DB_USERNAME=root
19 | DB_PASSWORD=
20 |
21 | BROADCAST_DRIVER=log
22 | CACHE_DRIVER=file
23 | FILESYSTEM_DISK=local
24 | QUEUE_CONNECTION=sync
25 | SESSION_DRIVER=file
26 | SESSION_LIFETIME=120
27 |
28 | MEMCACHED_HOST=127.0.0.1
29 |
30 | REDIS_HOST=127.0.0.1
31 | REDIS_PASSWORD=null
32 | REDIS_PORT=6379
33 |
34 | # use this for local Testing for emails all the emails will be stored in laravel.log file.
35 | MAIL_MAILER=log
36 | MAIL_HOST=mailpit
37 | MAIL_PORT=1025
38 | MAIL_USERNAME=null
39 | MAIL_PASSWORD=null
40 | MAIL_ENCRYPTION=null
41 | MAIL_FROM_ADDRESS="hello@example.com"
42 | MAIL_FROM_NAME="${APP_NAME}"
43 |
44 | AWS_ACCESS_KEY_ID=
45 | AWS_SECRET_ACCESS_KEY=
46 | AWS_DEFAULT_REGION=us-east-1
47 | AWS_BUCKET=
48 | AWS_USE_PATH_STYLE_ENDPOINT=false
49 |
50 | PUSHER_APP_ID=
51 | PUSHER_APP_KEY=
52 | PUSHER_APP_SECRET=
53 | PUSHER_HOST=
54 | PUSHER_PORT=443
55 | PUSHER_SCHEME=https
56 | PUSHER_APP_CLUSTER=mt1
57 |
58 | VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
59 | VITE_PUSHER_HOST="${PUSHER_HOST}"
60 | VITE_PUSHER_PORT="${PUSHER_PORT}"
61 | VITE_PUSHER_SCHEME="${PUSHER_SCHEME}"
62 | VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
63 |
--------------------------------------------------------------------------------
/laravel/app/Providers/RouteServiceProvider.php:
--------------------------------------------------------------------------------
1 | configureRateLimiting();
28 |
29 | $this->routes(function () {
30 | Route::middleware('api')
31 | ->prefix('api')
32 | ->group(base_path('routes/api.php'));
33 |
34 | Route::middleware('web')
35 | ->group(base_path('routes/web.php'));
36 | });
37 | }
38 |
39 | /**
40 | * Configure the rate limiters for the application.
41 | */
42 | protected function configureRateLimiting(): void
43 | {
44 | RateLimiter::for('api', function (Request $request) {
45 | return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
46 | });
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/nextjs/src/pages/api/auth/logout.js:
--------------------------------------------------------------------------------
1 | import axios from "axios";
2 | import { withValidation } from "@/lib/withValidation";
3 | import { refresh_token_key, access_token_key } from "@/lib/utils";
4 | import { LOGOUT_ROUTE } from '@/lib/route-service-provider';
5 |
6 | const handler = async (req, res) => {
7 |
8 | if(req.method !== 'POST') {
9 | res.status(405).json({ message: 'Method not allowed' });
10 | return;
11 | }
12 |
13 | try {
14 | const response = await axios.post(`${process.env.NEXT_BACKEND_URL}${LOGOUT_ROUTE}`, {}, {
15 | headers: {
16 | 'Authorization': `Bearer ${req.cookies[refresh_token_key]}`
17 | }
18 | });
19 |
20 | res.status(200).json({ message: 'Logged out' });
21 |
22 | } catch (error) {
23 |
24 | if(error.response && error.response.status === 401) {
25 |
26 | // if refresh token is expired, then we need to remove the access token and refresh token to logout the user
27 | res.setHeader('Set-Cookie', [
28 | `${access_token_key}=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0`,
29 | `${refresh_token_key}=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0`,
30 | ]);
31 |
32 | res.status(200).json({ message: 'Logged out' });
33 | }
34 |
35 | res.status(error.response.status).json({ message: error.response.data.message });
36 | }
37 | }
38 |
39 | export default withValidation({ verifyCsrfTokenCheck: true })(handler);
40 |
41 |
--------------------------------------------------------------------------------
/nextjs/src/lib/authorize.js:
--------------------------------------------------------------------------------
1 | /**
2 | * This file contains reusable helpers for authorization logic. just like laravel spatie roles and permissions package.
3 | */
4 |
5 | export function hasRole(user, roleName) {
6 | return user?.roles?.some(role => role.name === roleName) ?? false;
7 | }
8 |
9 |
10 | export function hasPermission(user, permissionName) {
11 | const hasDirectPermission = user?.permissions?.some(permission => permission.name === permissionName) ?? false;
12 | const hasPermissionThroughRole = user?.roles?.some(role =>
13 | role.permissions?.some(permission => permission.name === permissionName)
14 | ) ?? false;
15 |
16 | return hasDirectPermission || hasPermissionThroughRole;
17 | }
18 |
19 |
20 | export function can(user, permissionName) {
21 | return hasPermission(user, permissionName);
22 | }
23 |
24 |
25 | export function cannot(user, permissionName) {
26 | return !hasPermission(user, permissionName);
27 | }
28 |
29 |
30 | export function hasAnyRole(user, roleNames) {
31 | return roleNames.some(roleName => hasRole(user, roleName));
32 | }
33 |
34 |
35 | export function hasAllRoles(user, roleNames) {
36 | return roleNames.every(roleName => hasRole(user, roleName));
37 | }
38 |
39 |
40 | export function hasAnyPermission(user, permissionNames) {
41 | return permissionNames.some(permissionName => hasPermission(user, permissionName));
42 | }
43 |
44 |
45 | export function hasAllPermissions(user, permissionNames) {
46 | return permissionNames.every(permissionName => hasPermission(user, permissionName));
47 | }
48 |
--------------------------------------------------------------------------------
/docker-compose.yml:
--------------------------------------------------------------------------------
1 | version: '3.8'
2 |
3 | services:
4 | # Laravel Application
5 | app:
6 | build:
7 | context: ./laravel
8 | dockerfile: Dockerfile
9 | args:
10 | - UID=${UID:-1000}
11 | - GID=${GID:-1000}
12 | container_name: laravel-app
13 | user: laravel
14 | volumes:
15 | - ./laravel:/var/www/html
16 | ports:
17 | - "8000:80"
18 | command:
19 | - /bin/bash
20 | - -c
21 | - |
22 | php artisan migrate --seed --no-interaction --force
23 | environment:
24 | - APACHE_DOCUMENT_ROOT=/var/www/html/public
25 | depends_on:
26 | - mysql-db
27 | networks:
28 | - laravel-net
29 |
30 | # NextJS Application
31 | nextjs:
32 | build:
33 | context: ./nextjs
34 | dockerfile: Dockerfile
35 | container_name: nextjs-app
36 | volumes:
37 | - ./nextjs:/app
38 | - /app/node_modules # Ignore node_modules directory
39 | ports:
40 | - "3000:3000"
41 | networks:
42 | - laravel-net
43 |
44 | # MySQL Database
45 | mysql-db:
46 | image: mysql:8
47 | container_name: laravel-mysql
48 | ports:
49 | - "3306:3306"
50 | environment:
51 | MYSQL_DATABASE: laravel_react
52 | MYSQL_ALLOW_EMPTY_PASSWORD: 1
53 | volumes:
54 | - ./mysql_data:/var/lib/mysql
55 | networks:
56 | - laravel-net
57 |
58 | # phpmyadmin
59 | phpmyadmin:
60 | depends_on:
61 | - mysql-db
62 | image: phpmyadmin
63 | restart: always
64 | ports:
65 | - "8080:80"
66 | environment:
67 | PMA_HOST: mysql-db
68 | networks:
69 | - laravel-net
70 |
71 | networks:
72 | laravel-net:
--------------------------------------------------------------------------------
/laravel/config/hashing.php:
--------------------------------------------------------------------------------
1 | 'bcrypt',
19 |
20 | /*
21 | |--------------------------------------------------------------------------
22 | | Bcrypt Options
23 | |--------------------------------------------------------------------------
24 | |
25 | | Here you may specify the configuration options that should be used when
26 | | passwords are hashed using the Bcrypt algorithm. This will allow you
27 | | to control the amount of time it takes to hash the given password.
28 | |
29 | */
30 |
31 | 'bcrypt' => [
32 | 'rounds' => env('BCRYPT_ROUNDS', 10),
33 | ],
34 |
35 | /*
36 | |--------------------------------------------------------------------------
37 | | Argon Options
38 | |--------------------------------------------------------------------------
39 | |
40 | | Here you may specify the configuration options that should be used when
41 | | passwords are hashed using the Argon algorithm. These will allow you
42 | | to control the amount of time it takes to hash the given password.
43 | |
44 | */
45 |
46 | 'argon' => [
47 | 'memory' => 65536,
48 | 'threads' => 1,
49 | 'time' => 4,
50 | ],
51 |
52 | ];
53 |
--------------------------------------------------------------------------------
/laravel/bootstrap/app.php:
--------------------------------------------------------------------------------
1 | singleton(
30 | Illuminate\Contracts\Http\Kernel::class,
31 | App\Http\Kernel::class
32 | );
33 |
34 | $app->singleton(
35 | Illuminate\Contracts\Console\Kernel::class,
36 | App\Console\Kernel::class
37 | );
38 |
39 | $app->singleton(
40 | Illuminate\Contracts\Debug\ExceptionHandler::class,
41 | App\Exceptions\Handler::class
42 | );
43 |
44 | /*
45 | |--------------------------------------------------------------------------
46 | | Return The Application
47 | |--------------------------------------------------------------------------
48 | |
49 | | This script returns the application instance. The instance is given to
50 | | the calling script so we can separate the building of the instances
51 | | from the actual running of the application and sending responses.
52 | |
53 | */
54 |
55 | return $app;
56 |
--------------------------------------------------------------------------------
/laravel/artisan:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env php
2 | make(Illuminate\Contracts\Console\Kernel::class);
34 |
35 | $status = $kernel->handle(
36 | $input = new Symfony\Component\Console\Input\ArgvInput,
37 | new Symfony\Component\Console\Output\ConsoleOutput
38 | );
39 |
40 | /*
41 | |--------------------------------------------------------------------------
42 | | Shutdown The Application
43 | |--------------------------------------------------------------------------
44 | |
45 | | Once Artisan has finished running, we will fire off the shutdown events
46 | | so that any final work may be done by the application before we shut
47 | | down the process. This is the last thing to happen to the request.
48 | |
49 | */
50 |
51 | $kernel->terminate($input, $status);
52 |
53 | exit($status);
54 |
--------------------------------------------------------------------------------
/laravel/app/Providers/TelescopeServiceProvider.php:
--------------------------------------------------------------------------------
1 | hideSensitiveRequestDetails();
20 |
21 | $isLocal = $this->app->environment('local');
22 |
23 | Telescope::filter(function (IncomingEntry $entry) use ($isLocal) {
24 | return $isLocal ||
25 | $entry->isReportableException() ||
26 | $entry->isFailedRequest() ||
27 | $entry->isFailedJob() ||
28 | $entry->isScheduledTask() ||
29 | $entry->hasMonitoredTag();
30 | });
31 | }
32 |
33 | /**
34 | * Prevent sensitive request details from being logged by Telescope.
35 | */
36 | protected function hideSensitiveRequestDetails(): void
37 | {
38 | if ($this->app->environment('local')) {
39 | return;
40 | }
41 |
42 | Telescope::hideRequestParameters(['_token']);
43 |
44 | Telescope::hideRequestHeaders([
45 | 'cookie',
46 | 'x-csrf-token',
47 | 'x-xsrf-token',
48 | ]);
49 | }
50 |
51 | /**
52 | * Register the Telescope gate.
53 | *
54 | * This gate determines who can access Telescope in non-local environments.
55 | */
56 | protected function gate(): void
57 | {
58 | Gate::define('viewTelescope', function ($user) {
59 | return in_array($user->email, [
60 | //
61 | ]);
62 | });
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/laravel/public/index.php:
--------------------------------------------------------------------------------
1 | make(Kernel::class);
50 |
51 | $response = $kernel->handle(
52 | $request = Request::capture()
53 | )->send();
54 |
55 | $kernel->terminate($request, $response);
56 |
--------------------------------------------------------------------------------
/laravel/app/Http/Controllers/Auth/RegisteredUserController.php:
--------------------------------------------------------------------------------
1 | validate([
23 | 'name' => ['required', 'string', 'max:255'],
24 | 'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
25 | 'password' => ['required', 'confirmed', Rules\Password::defaults()],
26 | ]);
27 |
28 | $user = User::create([
29 | 'name' => $request->name,
30 | 'email' => $request->email,
31 | 'password' => Hash::make($request->string('password')),
32 | ]);
33 |
34 | $accessToken = $user->createToken('access_token', ['*'], now()->addSeconds(config('sanctum.access_token_expiration')))->plainTextToken;
35 | $refreshToken = $user->createToken('refresh_token', ['*'], now()->addSeconds(config('sanctum.refresh_token_expiration')))->plainTextToken;
36 |
37 | if(!$user->hasVerifiedEmail()){
38 | $user->notify(new VerifyEmail);
39 | }
40 |
41 | return response()->json([
42 | 'user' => $user,
43 | 'access_token' => $accessToken,
44 | 'refresh_token' => $refreshToken,
45 | 'access_token_expiration' => config('sanctum.access_token_expiration'),
46 | 'refresh_token_expiration' => config('sanctum.refresh_token_expiration'),
47 | ], 201);
48 | }
49 | }
--------------------------------------------------------------------------------
/laravel/Dockerfile:
--------------------------------------------------------------------------------
1 | # Use an official PHP image with Apache as the base image.
2 | FROM php:8.2-apache
3 |
4 | ARG UID
5 | ARG GID
6 |
7 | ENV UID=${UID}
8 | ENV GID=${GID}
9 |
10 |
11 | # Create a group with the specified GID
12 | RUN groupadd -g ${GID} laravel
13 |
14 | # Create a user with the specified UID and add it to the laravel group
15 | RUN useradd -g laravel -u ${UID} -s /bin/sh -m laravel
16 |
17 |
18 |
19 | # Set environment variables.
20 | ENV ACCEPT_EULA=Y
21 | LABEL maintainer="codeaxion77@gmail.com"
22 |
23 |
24 | # Install system dependencies.
25 | RUN apt-get update && apt-get install -y \
26 | libpng-dev \
27 | libjpeg-dev \
28 | libfreetype6-dev \
29 | zip \
30 | unzip \
31 | git \
32 | default-mysql-client \
33 | && rm -rf /var/lib/apt/lists/*
34 |
35 | # Enable Apache modules required for Laravel.
36 | RUN a2enmod rewrite
37 |
38 | # Set the Apache document root
39 | ENV APACHE_DOCUMENT_ROOT /var/www/html/public
40 |
41 | # Update the default Apache site configuration
42 | COPY apache-config.conf /etc/apache2/sites-available/000-default.conf
43 |
44 | # Install PHP extensions.
45 | RUN docker-php-ext-configure gd --with-freetype --with-jpeg \
46 | && docker-php-ext-install -j$(nproc) gd pdo pdo_mysql mysqli && docker-php-ext-enable pdo_mysql mysqli
47 |
48 |
49 | # Install Composer globally.
50 | RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
51 |
52 |
53 | # Create a directory for your Laravel application.
54 | WORKDIR /var/www/html
55 |
56 | # Copy the Laravel application files into the container.
57 | COPY . .
58 |
59 | # Copy and set up entrypoint script
60 | COPY docker-entrypoint.sh /usr/local/bin/
61 | RUN chmod +x /usr/local/bin/docker-entrypoint.sh
62 |
63 | # Set permissions for Laravel.
64 | RUN chown -R laravel:laravel storage bootstrap/cache
65 |
66 | USER laravel
67 |
68 |
69 | # Expose port 80 for Apache.
70 | EXPOSE 80
71 |
72 | ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
73 |
--------------------------------------------------------------------------------
/nextjs/src/contexts/AuthContext.js:
--------------------------------------------------------------------------------
1 | import { createContext, useContext, useState, useEffect } from 'react';
2 | import * as authHelpers from '@/lib/authorize';
3 | import axios from 'axios';
4 |
5 | const AuthContext = createContext();
6 |
7 | export function AuthProvider({ children, initialUser }) {
8 |
9 |
10 | const [user, setUser] = useState(initialUser);
11 | const [csrf, setCsrf] = useState({
12 | token: null,
13 | signature: null
14 | });
15 |
16 | useEffect(() => {
17 | let isMounted = true;
18 |
19 | if (!csrf.token) {
20 | const fetchCsrfToken = async () => {
21 | try {
22 | const response = await axios.get('/api/auth/csrf');
23 | if (isMounted) {
24 | setCsrf({
25 | token: response.data.token,
26 | });
27 | }
28 | } catch (error) {
29 | toast.error('PAGE EXPIRED')
30 | }
31 | };
32 | fetchCsrfToken();
33 | }
34 |
35 | return () => {
36 | isMounted = false;
37 | };
38 | }, [csrf.token]);
39 |
40 |
41 |
42 |
43 | useEffect(() => {
44 | if (initialUser) {
45 | setUser(initialUser);
46 | }
47 | }, [initialUser]);
48 |
49 | const authHelpersFunctions = {
50 | user,
51 | ...Object.fromEntries(
52 | Object.entries(authHelpers).map(([key, func]) => [key, (...args) => func(user, ...args)])
53 | ),
54 | };
55 |
56 | return (
57 |
58 | {children}
59 |
60 | );
61 | }
62 |
63 | export const useAuth = () => {
64 | const context = useContext(AuthContext);
65 | if (!context) {
66 | throw new Error('useAuth must be used within an AuthProvider');
67 | }
68 | return context;
69 | };
--------------------------------------------------------------------------------
/laravel/.env.docker.dev:
--------------------------------------------------------------------------------
1 | APP_NAME=Laravel
2 | APP_ENV=local
3 | APP_KEY=
4 | APP_DEBUG=true
5 |
6 | # Important
7 | # When your app is running inside a docker container, localhost points no longer to your development laptop (or server) it points to the container itself.
8 | # As each application is running in separeted container when the front access to the back, you cannot use localhost. As localhost points to the front container, and the back is not deployed there.
9 | # You should use the container name instead localhost when specificying the connection urls.
10 |
11 | # In this case, the container name is laravel-app.
12 | APP_URL=http://laravel-app
13 |
14 | API_URL=http://laravel-app/api
15 | FRONTEND_URL=http://localhost:3000
16 |
17 | LOG_CHANNEL=stack
18 | LOG_DEPRECATIONS_CHANNEL=null
19 | LOG_LEVEL=debug
20 |
21 |
22 | # In this case, the container name is mysql-db.
23 | DB_CONNECTION=mysql
24 | DB_HOST=mysql-db
25 | DB_PORT=3306
26 | DB_DATABASE=laravel_react
27 | DB_USERNAME=root
28 | DB_PASSWORD=
29 |
30 | BROADCAST_DRIVER=log
31 | CACHE_DRIVER=file
32 | FILESYSTEM_DISK=local
33 | QUEUE_CONNECTION=sync
34 | SESSION_DRIVER=file
35 | SESSION_LIFETIME=120
36 |
37 | MEMCACHED_HOST=127.0.0.1
38 |
39 | REDIS_HOST=127.0.0.1
40 | REDIS_PASSWORD=null
41 | REDIS_PORT=6379
42 |
43 | # use this for local Testing for emails all the emails will be stored in laravel.log file.
44 | MAIL_MAILER=log
45 | MAIL_HOST=mailpit
46 | MAIL_PORT=1025
47 | MAIL_USERNAME=null
48 | MAIL_PASSWORD=null
49 | MAIL_ENCRYPTION=null
50 | MAIL_FROM_ADDRESS="hello@example.com"
51 | MAIL_FROM_NAME="${APP_NAME}"
52 |
53 | AWS_ACCESS_KEY_ID=
54 | AWS_SECRET_ACCESS_KEY=
55 | AWS_DEFAULT_REGION=us-east-1
56 | AWS_BUCKET=
57 | AWS_USE_PATH_STYLE_ENDPOINT=false
58 |
59 | PUSHER_APP_ID=
60 | PUSHER_APP_KEY=
61 | PUSHER_APP_SECRET=
62 | PUSHER_HOST=
63 | PUSHER_PORT=443
64 | PUSHER_SCHEME=https
65 | PUSHER_APP_CLUSTER=mt1
66 |
67 | VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
68 | VITE_PUSHER_HOST="${PUSHER_HOST}"
69 | VITE_PUSHER_PORT="${PUSHER_PORT}"
70 | VITE_PUSHER_SCHEME="${PUSHER_SCHEME}"
71 | VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
--------------------------------------------------------------------------------
/nextjs/src/components/Dropdown.js:
--------------------------------------------------------------------------------
1 | import React, { useState } from 'react'
2 | import { Menu, Transition } from '@headlessui/react'
3 |
4 | const Dropdown = ({
5 | align = 'right',
6 | width = 48,
7 | contentClasses = 'py-1 bg-white',
8 | trigger,
9 | children,
10 | }) => {
11 | let alignmentClasses
12 |
13 | switch (width) {
14 | case '48':
15 | width = 'w-48'
16 | break
17 | }
18 |
19 | switch (align) {
20 | case 'left':
21 | alignmentClasses = 'origin-top-left left-0'
22 | break
23 | case 'top':
24 | alignmentClasses = 'origin-top'
25 | break
26 | case 'right':
27 | default:
28 | alignmentClasses = 'origin-top-right right-0'
29 | break
30 | }
31 |
32 | const [open, setOpen] = useState(false)
33 |
34 | return (
35 |
36 | {({ open }) => (
37 | <>
38 | {trigger}
39 |
40 |
48 |
50 |
53 | {children}
54 |
55 |
56 |
57 | >
58 | )}
59 |
60 | )
61 | }
62 |
63 | export default Dropdown
64 |
--------------------------------------------------------------------------------
/laravel/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "laravel/laravel",
3 | "type": "project",
4 | "description": "The Laravel Framework.",
5 | "keywords": ["framework", "laravel"],
6 | "license": "MIT",
7 | "require": {
8 | "php": "^8.1",
9 | "guzzlehttp/guzzle": "^7.2",
10 | "laravel/framework": "^10.0",
11 | "laravel/sanctum": "^3.2",
12 | "laravel/telescope": "^5.2",
13 | "laravel/tinker": "^2.8",
14 | "spatie/laravel-permission": "^6.10"
15 | },
16 | "require-dev": {
17 | "fakerphp/faker": "^1.9.1",
18 | "laravel/pint": "^1.0",
19 | "laravel/sail": "^1.18",
20 | "mockery/mockery": "^1.4.4",
21 | "nunomaduro/collision": "^7.0",
22 | "phpunit/phpunit": "^10.0",
23 | "spatie/laravel-ignition": "^2.0"
24 | },
25 | "autoload": {
26 | "psr-4": {
27 | "App\\": "app/",
28 | "Database\\Factories\\": "database/factories/",
29 | "Database\\Seeders\\": "database/seeders/"
30 | }
31 | },
32 | "autoload-dev": {
33 | "psr-4": {
34 | "Tests\\": "tests/"
35 | }
36 | },
37 | "scripts": {
38 | "post-autoload-dump": [
39 | "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
40 | "@php artisan package:discover --ansi"
41 | ],
42 | "post-update-cmd": [
43 | "@php artisan vendor:publish --tag=laravel-assets --ansi --force"
44 | ],
45 | "post-root-package-install": [
46 | "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
47 | ],
48 | "post-create-project-cmd": [
49 | "@php artisan key:generate --ansi"
50 | ]
51 | },
52 | "extra": {
53 | "branch-alias": {
54 | "dev-master": "10.x-dev"
55 | },
56 | "laravel": {
57 | "dont-discover": [
58 | "laravel/telescope"
59 | ]
60 | }
61 | },
62 | "config": {
63 | "optimize-autoloader": true,
64 | "preferred-install": "dist",
65 | "sort-packages": true,
66 | "allow-plugins": {
67 | "pestphp/pest-plugin": true
68 | }
69 | },
70 | "minimum-stability": "stable",
71 | "prefer-stable": true
72 | }
73 |
--------------------------------------------------------------------------------
/laravel/config/broadcasting.php:
--------------------------------------------------------------------------------
1 | env('BROADCAST_DRIVER', 'null'),
19 |
20 | /*
21 | |--------------------------------------------------------------------------
22 | | Broadcast Connections
23 | |--------------------------------------------------------------------------
24 | |
25 | | Here you may define all of the broadcast connections that will be used
26 | | to broadcast events to other systems or over websockets. Samples of
27 | | each available type of connection are provided inside this array.
28 | |
29 | */
30 |
31 | 'connections' => [
32 |
33 | 'pusher' => [
34 | 'driver' => 'pusher',
35 | 'key' => env('PUSHER_APP_KEY'),
36 | 'secret' => env('PUSHER_APP_SECRET'),
37 | 'app_id' => env('PUSHER_APP_ID'),
38 | 'options' => [
39 | 'host' => env('PUSHER_HOST') ?: 'api-'.env('PUSHER_APP_CLUSTER', 'mt1').'.pusher.com',
40 | 'port' => env('PUSHER_PORT', 443),
41 | 'scheme' => env('PUSHER_SCHEME', 'https'),
42 | 'encrypted' => true,
43 | 'useTLS' => env('PUSHER_SCHEME', 'https') === 'https',
44 | ],
45 | 'client_options' => [
46 | // Guzzle client options: https://docs.guzzlephp.org/en/stable/request-options.html
47 | ],
48 | ],
49 |
50 | 'ably' => [
51 | 'driver' => 'ably',
52 | 'key' => env('ABLY_KEY'),
53 | ],
54 |
55 | 'redis' => [
56 | 'driver' => 'redis',
57 | 'connection' => 'default',
58 | ],
59 |
60 | 'log' => [
61 | 'driver' => 'log',
62 | ],
63 |
64 | 'null' => [
65 | 'driver' => 'null',
66 | ],
67 |
68 | ],
69 |
70 | ];
71 |
--------------------------------------------------------------------------------
/laravel/database/seeders/DatabaseSeeder.php:
--------------------------------------------------------------------------------
1 | create();
16 |
17 | // \App\Models\User::factory()->create([
18 | // 'name' => 'Test User',
19 | // 'email' => 'test@example.com',
20 | // ]);
21 |
22 | try {
23 | \DB::beginTransaction();
24 |
25 | \App\Models\User::create([
26 | 'name' => 'Admin User',
27 | 'email' => 'admin@gmail.com',
28 | 'password' => \Illuminate\Support\Facades\Hash::make('password'),
29 | ]);
30 |
31 | $user = \App\Models\User::where('email', 'admin@gmail.com')->first();
32 |
33 | // // create admin role and customer role and assign some permissions
34 | $adminRole = \Spatie\Permission\Models\Role::create(['name' => 'admin']);
35 | $customerRole = \Spatie\Permission\Models\Role::create(['name' => 'author']);
36 |
37 | // create permissions
38 | $createPostPermission = \Spatie\Permission\Models\Permission::create(['name' => 'create post']);
39 | $editPostPermission = \Spatie\Permission\Models\Permission::create(['name' => 'edit post']);
40 | $deletePostPermission = \Spatie\Permission\Models\Permission::create(['name' => 'delete post']);
41 |
42 | $adminRole->givePermissionTo($createPostPermission);
43 | $adminRole->givePermissionTo($editPostPermission);
44 | $adminRole->givePermissionTo($deletePostPermission);
45 |
46 | $customerRole->givePermissionTo($createPostPermission);
47 |
48 | $user->assignRole('admin');
49 |
50 | $user->assignRole('author');
51 |
52 | $changeSystemSettingPermission = \Spatie\Permission\Models\Permission::create(['name' => 'change system setting']);
53 |
54 | $user->givePermissionTo($changeSystemSettingPermission);
55 |
56 | \DB::commit();
57 | } catch (\Throwable $th) {
58 | \DB::rollBack();
59 | // throw $th;
60 | }
61 | }
62 | }
63 |
64 |
--------------------------------------------------------------------------------
/laravel/database/migrations/2018_08_08_100000_create_telescope_entries_table.php:
--------------------------------------------------------------------------------
1 | getConnection());
23 |
24 | $schema->create('telescope_entries', function (Blueprint $table) {
25 | $table->bigIncrements('sequence');
26 | $table->uuid('uuid');
27 | $table->uuid('batch_id');
28 | $table->string('family_hash')->nullable();
29 | $table->boolean('should_display_on_index')->default(true);
30 | $table->string('type', 20);
31 | $table->longText('content');
32 | $table->dateTime('created_at')->nullable();
33 |
34 | $table->unique('uuid');
35 | $table->index('batch_id');
36 | $table->index('family_hash');
37 | $table->index('created_at');
38 | $table->index(['type', 'should_display_on_index']);
39 | });
40 |
41 | $schema->create('telescope_entries_tags', function (Blueprint $table) {
42 | $table->uuid('entry_uuid');
43 | $table->string('tag');
44 |
45 | $table->primary(['entry_uuid', 'tag']);
46 | $table->index('tag');
47 |
48 | $table->foreign('entry_uuid')
49 | ->references('uuid')
50 | ->on('telescope_entries')
51 | ->onDelete('cascade');
52 | });
53 |
54 | $schema->create('telescope_monitoring', function (Blueprint $table) {
55 | $table->string('tag')->primary();
56 | });
57 | }
58 |
59 | /**
60 | * Reverse the migrations.
61 | */
62 | public function down(): void
63 | {
64 | $schema = Schema::connection($this->getConnection());
65 |
66 | $schema->dropIfExists('telescope_entries_tags');
67 | $schema->dropIfExists('telescope_entries');
68 | $schema->dropIfExists('telescope_monitoring');
69 | }
70 | };
71 |
--------------------------------------------------------------------------------
/laravel/routes/api.php:
--------------------------------------------------------------------------------
1 | get('/user', function (Request $request) {
25 | $user = $request->user();
26 |
27 | $user->load(['roles' => function($query) {
28 | $query->with('permissions');
29 | }, 'permissions']);
30 |
31 | return $user;
32 | });
33 |
34 |
35 | Route::middleware('auth:sanctum')->group(function () {
36 |
37 | Route::post('/refresh-token', [AuthenticatedSessionController::class, 'refreshToken'])
38 | ->name('refresh-token');
39 |
40 | Route::post('/email/verification-notification', [EmailVerificationNotificationController::class, 'store'])
41 | ->middleware('throttle:6,1')
42 | ->name('email.verification-notification');
43 |
44 | Route::get('/email/verify/{id}/{hash}', VerifyEmailController::class)
45 | ->middleware(['signed','throttle:6,1'])
46 | ->name('verification.verify');
47 |
48 | });
49 |
50 | Route::middleware('guest')->group(function () {
51 |
52 | Route::post('/register', [RegisteredUserController::class, 'store'])
53 | ->name('register');
54 |
55 | Route::post('/login', [AuthenticatedSessionController::class, 'store'])
56 | ->name('login');
57 |
58 | Route::post('/logout', [AuthenticatedSessionController::class, 'destroy'])
59 | ->name('logout');
60 |
61 | Route::post('/forgot-password', [PasswordResetLinkController::class, 'store'])
62 | ->name('password.email');
63 |
64 | Route::post('/reset-password', [PasswordResetLinkController::class, 'resetPassword'])
65 | ->name('password.reset');
66 | });
67 |
68 |
69 |
70 |
71 |
--------------------------------------------------------------------------------
/nextjs/src/lib/route-service-provider.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Route Service Provider
3 | *
4 | * This file contains the routes for the application.
5 | * It also contains a helper function to generate dynamic routes.
6 | */
7 |
8 | /**
9 | * Protected Routes
10 | *
11 | * These are the routes that require authentication.
12 | */
13 | export const PROTECTED_ROUTES = ['/dashboard', '/profile', '/verify-email'];
14 |
15 |
16 | /**
17 | * Guest Routes
18 | *
19 | * These are the routes that do not require authentication.
20 | */
21 | export const GUEST_ROUTES = ['/login', '/register', '/forgot-password'];
22 |
23 |
24 | /**
25 | * Redirect If Authenticated
26 | *
27 | * This is the route that the user will be redirected to if they are authenticated.
28 | */
29 | export const REDIRECT_IF_AUTHENTICATED = '/dashboard';
30 |
31 |
32 | /**
33 | * Redirect If Not Authenticated
34 | *
35 | * This is the route that the user will be redirected to if they are not authenticated.
36 | */
37 | export const REDIRECT_IF_NOT_AUTHENTICATED = '/login';
38 |
39 |
40 | /**
41 | * Email Verification Route
42 | *
43 | * This is the route that the user will be redirected to if they need to verify their email.
44 | */
45 | export const EMAIL_VERIFICATION_ROUTE = '/verify-email';
46 | export const VERIFY_EMAIL_ROUTE = '/email/verify';
47 |
48 |
49 | /**
50 | * Laravel Authentication Routes
51 | */
52 | export const REFRESH_TOKEN_ROUTE = '/refresh-token';
53 | export const EMAIL_VERIFICATION_NOTIFICATION_ROUTE = '/api/email/verification-notification';
54 | export const FORGOT_PASSWORD_ROUTE = '/api/forgot-password';
55 | export const RESET_PASSWORD_ROUTE = '/api/reset-password';
56 | export const REGISTER_ROUTE = '/api/register';
57 | export const LOGIN_ROUTE = '/api/login';
58 | export const LOGOUT_ROUTE = '/api/logout';
59 | export const USER_ROUTE = '/api/user';
60 | export const VERIFY_HASH_ROUTE = '/api/email/verify/[userId]/[hash]?expires=[expires]&signature=[signature]';
61 |
62 |
63 | /**
64 | * Generates a dynamic route by replacing placeholders with actual values.
65 | *
66 | * @param {string} route - The route template with placeholders.
67 | * @param {Object} params - An object containing values to replace placeholders.
68 | * @returns {string} - The dynamically generated route.
69 | */
70 |
71 | export const getDynamicRoute = (route, params) => {
72 | return Object.keys(params).reduce((resultRoute, key) => {
73 | return resultRoute.replace(`[${key}]`, params[key]);
74 | }, route);
75 | }
76 |
--------------------------------------------------------------------------------
/laravel/config/filesystems.php:
--------------------------------------------------------------------------------
1 | env('FILESYSTEM_DISK', 'local'),
17 |
18 | /*
19 | |--------------------------------------------------------------------------
20 | | Filesystem Disks
21 | |--------------------------------------------------------------------------
22 | |
23 | | Here you may configure as many filesystem "disks" as you wish, and you
24 | | may even configure multiple disks of the same driver. Defaults have
25 | | been set up for each driver as an example of the required values.
26 | |
27 | | Supported Drivers: "local", "ftp", "sftp", "s3"
28 | |
29 | */
30 |
31 | 'disks' => [
32 |
33 | 'local' => [
34 | 'driver' => 'local',
35 | 'root' => storage_path('app'),
36 | 'throw' => false,
37 | ],
38 |
39 | 'public' => [
40 | 'driver' => 'local',
41 | 'root' => storage_path('app/public'),
42 | 'url' => env('APP_URL').'/storage',
43 | 'visibility' => 'public',
44 | 'throw' => false,
45 | ],
46 |
47 | 's3' => [
48 | 'driver' => 's3',
49 | 'key' => env('AWS_ACCESS_KEY_ID'),
50 | 'secret' => env('AWS_SECRET_ACCESS_KEY'),
51 | 'region' => env('AWS_DEFAULT_REGION'),
52 | 'bucket' => env('AWS_BUCKET'),
53 | 'url' => env('AWS_URL'),
54 | 'endpoint' => env('AWS_ENDPOINT'),
55 | 'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
56 | 'throw' => false,
57 | ],
58 |
59 | ],
60 |
61 | /*
62 | |--------------------------------------------------------------------------
63 | | Symbolic Links
64 | |--------------------------------------------------------------------------
65 | |
66 | | Here you may configure the symbolic links that will be created when the
67 | | `storage:link` Artisan command is executed. The array keys should be
68 | | the locations of the links and the values should be their targets.
69 | |
70 | */
71 |
72 | 'links' => [
73 | public_path('storage') => storage_path('app/public'),
74 | ],
75 |
76 | ];
77 |
--------------------------------------------------------------------------------
/nextjs/src/pages/api/auth/login.js:
--------------------------------------------------------------------------------
1 | import axios from "axios";
2 | import { withValidation } from "@/lib/withValidation";
3 | import { access_token_key, refresh_token_key, access_token_expiration_key, refresh_token_expiration_key } from "@/lib/utils";
4 | import { LOGIN_ROUTE } from '@/lib/route-service-provider';
5 |
6 | const handler = async (req, res) => {
7 |
8 | if (req.method !== 'POST') {
9 | return res.status(405).json({ error: 'Method not allowed' });
10 | }
11 |
12 | const { email, password } = req.body;
13 |
14 | try {
15 |
16 | const response = await axios.post(`${process.env.NEXT_BACKEND_URL}${LOGIN_ROUTE}`, { email, password });
17 |
18 | // create access and refresh tokens from the response with http only cookies
19 | const accessToken = response.data[access_token_key];
20 | const refreshToken = response.data[refresh_token_key];
21 |
22 | let cookiePrefix = process.env.ENVIRONMENT === 'local' ? '' : process.env.COOKIE_PREFIX;
23 | let secure = process.env.ENVIRONMENT === 'local' ? 'Secure' : '';
24 | let accessTokenExpiration = response.data[access_token_expiration_key];
25 | let refreshTokenExpiration = response.data[refresh_token_expiration_key];
26 |
27 |
28 | // Securing cookies using OWASP recommendations
29 | // https://owasp.org/www-chapter-london/assets/slides/OWASPLondon20171130_Cookie_Security_Myths_Misconceptions_David_Johansson.pdf
30 |
31 | res.setHeader('Set-Cookie', [
32 | `${cookiePrefix}${access_token_key}=${accessToken}; HttpOnly; ${secure}; SameSite=Lax; Path=/; Max-Age=${accessTokenExpiration}`, // 1 min
33 | `${cookiePrefix}${refresh_token_key}=${refreshToken}; HttpOnly; ${secure}; SameSite=Lax; Path=/; Max-Age=${refreshTokenExpiration}`, // 2 mins
34 | ]);
35 |
36 | res.status(response.status).json(response.data);
37 |
38 | } catch (error) {
39 |
40 | if (error?.response) {
41 | if (error?.response?.status === 422) {
42 | res.status(error?.response?.status).json(error?.response?.data);
43 | } else {
44 | res.status(error?.response?.status).json({
45 | message: `An error occurred during login (${error?.response?.status})`,
46 | });
47 | }
48 | } else {
49 |
50 | // Handle errors without a response (e.g., network issues)
51 | res.status(500).json({
52 | message: 'An unexpected error occurred. Please try again later.',
53 | error: error?.message, // Optionally include error details for debugging
54 | });
55 | }
56 | }
57 | };
58 |
59 | export default withValidation({ verifyCsrfTokenCheck: true })(handler);
60 |
61 |
--------------------------------------------------------------------------------
/laravel/app/Http/Kernel.php:
--------------------------------------------------------------------------------
1 |
15 | */
16 | protected $middleware = [
17 | // \App\Http\Middleware\TrustHosts::class,
18 | \App\Http\Middleware\TrustProxies::class,
19 | \Illuminate\Http\Middleware\HandleCors::class,
20 | \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
21 | \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
22 | \App\Http\Middleware\TrimStrings::class,
23 | \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
24 | ];
25 |
26 | /**
27 | * The application's route middleware groups.
28 | *
29 | * @var array>
30 | */
31 | protected $middlewareGroups = [
32 | 'web' => [
33 | \App\Http\Middleware\EncryptCookies::class,
34 | \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
35 | \Illuminate\Session\Middleware\StartSession::class,
36 | \Illuminate\View\Middleware\ShareErrorsFromSession::class,
37 | \App\Http\Middleware\VerifyCsrfToken::class,
38 | \Illuminate\Routing\Middleware\SubstituteBindings::class,
39 | ],
40 |
41 | 'api' => [
42 | // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
43 | \Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
44 | \Illuminate\Routing\Middleware\SubstituteBindings::class,
45 | ],
46 | ];
47 |
48 | /**
49 | * The application's middleware aliases.
50 | *
51 | * Aliases may be used to conveniently assign middleware to routes and groups.
52 | *
53 | * @var array
54 | */
55 | protected $middlewareAliases = [
56 | 'auth' => \App\Http\Middleware\Authenticate::class,
57 | 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
58 | 'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
59 | 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
60 | 'can' => \Illuminate\Auth\Middleware\Authorize::class,
61 | 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
62 | 'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
63 | 'signed' => \App\Http\Middleware\ValidateSignature::class,
64 | 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
65 | 'verified' => \App\Http\Middleware\EnsureEmailIsVerified::class,
66 | ];
67 | }
68 |
--------------------------------------------------------------------------------
/nextjs/src/pages/verify-email.js:
--------------------------------------------------------------------------------
1 | import Button from '@/components/Button'
2 | import { useState } from 'react'
3 | import { withAuth } from "@/lib/withAuth";
4 | import GuestLayout from '@/components/Layouts/GuestLayout';
5 | import AuthCard from '@/components/AuthCard';
6 | import { front } from '@/lib/axios';
7 | import { useAuth } from '@/contexts/AuthContext';
8 |
9 | const VerifyEmail = () => {
10 | const { csrf } = useAuth();
11 |
12 | const [loading, setLoading] = useState(false);
13 |
14 | const resendEmailVerification = async ({ setStatus }) => {
15 | try {
16 | setLoading(true);
17 | const response = await front.post('/api/auth/email/verify-email-notification', {},{
18 | headers: {
19 | 'x-csrf-token': csrf.token
20 | },
21 | });
22 | setStatus(response.data.status)
23 | } catch (error) {
24 | setLoading(false);
25 | } finally {
26 | setLoading(false);
27 | }
28 | }
29 |
30 |
31 | const [status, setStatus] = useState(null)
32 |
33 | return (
34 |
35 |
36 |
37 |
38 | Thanks for signing up! Before getting started, could you verify
39 | your email address by clicking on the link we just
40 | emailed to you? If you didn't receive the email, we will gladly
41 | send you another.
42 |
43 |
44 | {status === 'verification-link-sent' && (
45 |
46 | A new verification link has been sent to the email address
47 | you provided during registration.
48 |
49 | )}
50 |
51 |
52 | resendEmailVerification({ setStatus })}
53 | disabled={loading}
54 | >
55 | {loading ? 'Sending Verification Email...' : 'Resend Verification Email'}
56 |
57 |
58 |
59 |
60 | )
61 | }
62 |
63 | export default VerifyEmail
64 |
65 | export const getServerSideProps = withAuth(async (context, user) => {
66 | const { req } = context;
67 |
68 | // if (!hasPermission(user, 'create post')) {
69 |
70 | // // return redirect back to 403 page
71 | // return {
72 | // redirect: {
73 | // destination: '/403',
74 | // permanent: false,
75 | // },
76 | // };
77 | // }
78 |
79 |
80 | return {
81 | props: { user }, // Pass the user data to the page component
82 | };
83 | });
--------------------------------------------------------------------------------
/nextjs/src/pages/api/auth/register.js:
--------------------------------------------------------------------------------
1 | import axios from "axios";
2 | import { withValidation } from "@/lib/withValidation";
3 | import { access_token_key, refresh_token_key, access_token_expiration_key, refresh_token_expiration_key } from "@/lib/utils";
4 | import { REGISTER_ROUTE } from '@/lib/route-service-provider';
5 |
6 | const handler = async (req, res) => {
7 |
8 | if (req.method !== 'POST') {
9 | return res.status(405).json({ error: 'Method not allowed' });
10 | }
11 |
12 | const { name, email, password, password_confirmation } = req.body;
13 |
14 | try {
15 |
16 | const response = await axios.post(`${process.env.NEXT_BACKEND_URL}${REGISTER_ROUTE}`, {
17 | name,
18 | email,
19 | password,
20 | password_confirmation
21 | });
22 |
23 | // create access and refresh tokens from the response with http only cookies
24 | const accessToken = response.data[access_token_key];
25 | const refreshToken = response.data[refresh_token_key];
26 |
27 | let cookiePrefix = process.env.ENVIRONMENT === 'local' ? '' : process.env.COOKIE_PREFIX;
28 | let secure = process.env.ENVIRONMENT === 'local' ? 'Secure' : '';
29 | let accessTokenExpiration = response.data[access_token_expiration_key];
30 | let refreshTokenExpiration = response.data[refresh_token_expiration_key];
31 |
32 |
33 | // Securing cookies using OWASP recommendations
34 | // https://owasp.org/www-chapter-london/assets/slides/OWASPLondon20171130_Cookie_Security_Myths_Misconceptions_David_Johansson.pdf
35 |
36 | res.setHeader('Set-Cookie', [
37 | `${cookiePrefix}${access_token_key}=${accessToken}; HttpOnly; ${secure}; SameSite=Lax; Path=/; Max-Age=${accessTokenExpiration}`, // 1 min
38 | `${cookiePrefix}${refresh_token_key}=${refreshToken}; HttpOnly; ${secure}; SameSite=Lax; Path=/; Max-Age=${refreshTokenExpiration}`, // 2 mins
39 | ]);
40 |
41 | res.status(response.status).json(response.data);
42 |
43 | } catch (error) {
44 | if (error?.response) {
45 | if (error?.response?.status === 422) {
46 | res.status(error?.response?.status).json(error?.response?.data);
47 | } else {
48 | res.status(error?.response?.status).json({
49 | message: `An error occurred during register (${error?.response?.status})`,
50 | });
51 | }
52 | } else {
53 | // Handle errors without a response (e.g., network issues)
54 | res.status(500).json({
55 | message: 'An unexpected error occurred. Please try again later.',
56 | error: error?.message, // Optionally include error details for debugging
57 | });
58 | }
59 |
60 | }
61 | };
62 |
63 | export default withValidation({ verifyCsrfTokenCheck: true })(handler);
64 |
65 |
--------------------------------------------------------------------------------
/nextjs/src/pages/dashboard.js:
--------------------------------------------------------------------------------
1 | import { useAuth } from "@/contexts/AuthContext";
2 | import { withAuth } from "@/lib/withAuth";
3 | import AppLayout from "@/components/Layouts/AppLayout";
4 |
5 | export default function Dashboard({ user }) {
6 |
7 | /**
8 | * use this for checking if the user has a role there are several other authorization helpers in the authorize.js file
9 | */
10 | const { hasRole } = useAuth();
11 |
12 | return (
13 | <>
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
User Details
22 | {user && (
23 |
24 |
25 |
Name
26 |
{user.name}
27 |
28 |
29 |
Email
30 |
{user.email}
31 |
32 |
33 |
34 |
35 |
36 |
37 | )}
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 | >
47 | );
48 | }
49 |
50 | export const getServerSideProps = withAuth(async (context, user) => {
51 | const { req } = context;
52 |
53 | /**
54 | * Authorization helpers example of permission check
55 | *
56 | */
57 |
58 | // if (!hasPermission(user, 'create post')) {
59 |
60 | // // return redirect back to 403 page
61 | // return {
62 | // redirect: {
63 | // destination: '/403',
64 | // permanent: false,
65 | // },
66 | // };
67 | // }
68 |
69 |
70 | return {
71 | props: { user }, // Pass the user data to the page component
72 | };
73 | });
--------------------------------------------------------------------------------
/laravel/app/Http/Controllers/Auth/AuthenticatedSessionController.php:
--------------------------------------------------------------------------------
1 | validate([
18 | 'email' => ['required', 'string', 'email'],
19 | 'password' => ['required', 'string'],
20 | ]);
21 |
22 | if (!auth()->attempt($request->only('email', 'password'))) {
23 | return response()->json([
24 | 'message' => 'Invalid login credentials'
25 | ], 422);
26 | }
27 |
28 | $user = User::with(['roles','permissions'])->where('email', $request->email)->first();
29 |
30 | $accessToken = $user->createToken('access_token', ['*'], now()->addSeconds(config('sanctum.access_token_expiration')))->plainTextToken;
31 | $refreshToken = $user->createToken('refresh_token', ['*'], now()->addSeconds(config('sanctum.refresh_token_expiration')))->plainTextToken;
32 |
33 | if(!$user->hasVerifiedEmail()){
34 | $user->notify(new VerifyEmail);
35 | }
36 |
37 | return response()->json([
38 | 'user' => $user,
39 | 'access_token' => $accessToken,
40 | 'refresh_token' => $refreshToken,
41 | 'access_token_expiration' => config('sanctum.access_token_expiration'),
42 | 'refresh_token_expiration' => config('sanctum.refresh_token_expiration'),
43 | ], 200);
44 | }
45 |
46 | public function refreshToken(Request $request)
47 | {
48 | $request->user()->tokens()->delete();
49 | $accessToken = $request->user()->createToken('access_token', ['issue-access-token'], now()->addSeconds(config('sanctum.access_token_expiration',null)));
50 | $refreshToken = $request->user()->createToken('refresh_token', ['access-api'], now()->addSeconds(config('sanctum.refresh_token_expiration',3)));
51 |
52 | return response()->json([
53 | 'user' => $request->user(),
54 | 'access_token' => $accessToken->plainTextToken,
55 | 'refresh_token' => $refreshToken->plainTextToken,
56 | 'access_token_expiration' => config('sanctum.access_token_expiration'),
57 | 'refresh_token_expiration' => config('sanctum.refresh_token_expiration'),
58 | ]);
59 | }
60 |
61 | /**
62 | * Destroy an authenticated session.
63 | */
64 | public function destroy(Request $request)
65 | {
66 | if(!$request->user()){
67 | return response()->json([
68 | 'message' => 'Unauthorized'
69 | ], 401);
70 | }
71 |
72 | $request->user()->tokens()->delete();
73 |
74 | return response()->json(['message' => 'Logged out successfully']);
75 | }
76 | }
--------------------------------------------------------------------------------
/nextjs/src/components/ApplicationLogo.js:
--------------------------------------------------------------------------------
1 | const ApplicationLogo = props => (
2 |
3 |
4 |
5 | )
6 |
7 | export default ApplicationLogo
8 |
--------------------------------------------------------------------------------
/laravel/app/Http/Controllers/Auth/PasswordResetLinkController.php:
--------------------------------------------------------------------------------
1 | validate([
24 | 'token' => ['required'],
25 | 'email' => ['required', 'email'],
26 | 'password' => ['required', 'confirmed', Rules\Password::defaults()],
27 | ]);
28 |
29 | // Here we will attempt to reset the user's password. If it is successful we
30 | // will update the password on an actual user model and persist it to the
31 | // database. Otherwise we will parse the error and return the response.
32 | $status = Password::reset(
33 | $request->only('email', 'password', 'password_confirmation', 'token'),
34 | function ($user) use ($request) {
35 | $user->forceFill([
36 | 'password' => Hash::make($request->string('password')),
37 | 'remember_token' => Str::random(60),
38 | ])->save();
39 |
40 | event(new PasswordReset($user));
41 | }
42 | );
43 |
44 | if ($status != Password::PASSWORD_RESET) {
45 | throw ValidationException::withMessages([
46 | 'email' => [__($status)],
47 | ]);
48 | }
49 |
50 | return response()->json([
51 | 'message' => 'Password has been reset successfully. You can now login.',
52 | 'status' => __($status),
53 | ]);
54 | }
55 |
56 | /**
57 | * Handle an incoming password reset link request.
58 | *
59 | * @throws \Illuminate\Validation\ValidationException
60 | */
61 | public function store(Request $request)
62 | {
63 | $request->validate([
64 | 'email' => ['required', 'email'],
65 | ]);
66 |
67 | // We will send the password reset link to this user. Once we have attempted
68 | // to send the link, we will examine the response then see the message we
69 | // need to show to the user. Finally, we'll send out a proper response.
70 | $status = Password::sendResetLink(
71 | $request->only('email')
72 | );
73 |
74 | if ($status != Password::RESET_LINK_SENT) {
75 | throw ValidationException::withMessages([
76 | 'email' => [__($status)],
77 | ]);
78 | }
79 |
80 | return response()->json([
81 | 'message' => 'Password reset link sent.',
82 | 'status' => __($status),
83 | ]);
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/laravel/config/queue.php:
--------------------------------------------------------------------------------
1 | env('QUEUE_CONNECTION', 'sync'),
17 |
18 | /*
19 | |--------------------------------------------------------------------------
20 | | Queue Connections
21 | |--------------------------------------------------------------------------
22 | |
23 | | Here you may configure the connection information for each server that
24 | | is used by your application. A default configuration has been added
25 | | for each back-end shipped with Laravel. You are free to add more.
26 | |
27 | | Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null"
28 | |
29 | */
30 |
31 | 'connections' => [
32 |
33 | 'sync' => [
34 | 'driver' => 'sync',
35 | ],
36 |
37 | 'database' => [
38 | 'driver' => 'database',
39 | 'table' => 'jobs',
40 | 'queue' => 'default',
41 | 'retry_after' => 90,
42 | 'after_commit' => false,
43 | ],
44 |
45 | 'beanstalkd' => [
46 | 'driver' => 'beanstalkd',
47 | 'host' => 'localhost',
48 | 'queue' => 'default',
49 | 'retry_after' => 90,
50 | 'block_for' => 0,
51 | 'after_commit' => false,
52 | ],
53 |
54 | 'sqs' => [
55 | 'driver' => 'sqs',
56 | 'key' => env('AWS_ACCESS_KEY_ID'),
57 | 'secret' => env('AWS_SECRET_ACCESS_KEY'),
58 | 'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
59 | 'queue' => env('SQS_QUEUE', 'default'),
60 | 'suffix' => env('SQS_SUFFIX'),
61 | 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
62 | 'after_commit' => false,
63 | ],
64 |
65 | 'redis' => [
66 | 'driver' => 'redis',
67 | 'connection' => 'default',
68 | 'queue' => env('REDIS_QUEUE', 'default'),
69 | 'retry_after' => 90,
70 | 'block_for' => null,
71 | 'after_commit' => false,
72 | ],
73 |
74 | ],
75 |
76 | /*
77 | |--------------------------------------------------------------------------
78 | | Failed Queue Jobs
79 | |--------------------------------------------------------------------------
80 | |
81 | | These options configure the behavior of failed queue job logging so you
82 | | can control which database and table are used to store the jobs that
83 | | have failed. You may change them to any database / table you wish.
84 | |
85 | */
86 |
87 | 'failed' => [
88 | 'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
89 | 'database' => env('DB_CONNECTION', 'mysql'),
90 | 'table' => 'failed_jobs',
91 | ],
92 |
93 | ];
94 |
--------------------------------------------------------------------------------
/laravel/config/sanctum.php:
--------------------------------------------------------------------------------
1 | explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
19 | '%s%s',
20 | 'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
21 | Sanctum::currentApplicationUrlWithPort()
22 | ))),
23 |
24 | /*
25 | |--------------------------------------------------------------------------
26 | | Sanctum Guards
27 | |--------------------------------------------------------------------------
28 | |
29 | | This array contains the authentication guards that will be checked when
30 | | Sanctum is trying to authenticate a request. If none of these guards
31 | | are able to authenticate the request, Sanctum will use the bearer
32 | | token that's present on an incoming request for authentication.
33 | |
34 | */
35 |
36 | 'guard' => ['web'],
37 |
38 | /*
39 | |--------------------------------------------------------------------------
40 | | Expiration Minutes
41 | |--------------------------------------------------------------------------
42 | |
43 | | This value controls the number of minutes until an issued token will be
44 | | considered expired. If this value is null, personal access tokens do
45 | | not expire. This won't tweak the lifetime of first-party sessions.
46 | |
47 | */
48 |
49 | 'expiration' => null,
50 |
51 | /*
52 | |--------------------------------------------------------------------------
53 | | Access Token Expiration
54 | |--------------------------------------------------------------------------
55 | |
56 | | This value controls the number of seconds until an issued token will be
57 | | considered expired. Do not set this value to minutes or hours. always set
58 | | this value to seconds or else the frontend will not be able to set the
59 | | cookie expiration time properly.
60 | |
61 | */
62 |
63 | // -- Example of how to set the expiration time --
64 | 'access_token_expiration' => 60 * 24, // 1 day
65 | 'refresh_token_expiration' => 60 * 24 * 7, // 7 days
66 |
67 | // 'access_token_expiration' => 60, // 1 minute
68 | // 'refresh_token_expiration' => 60 * 2, // 2 minutes
69 |
70 | /*
71 | |--------------------------------------------------------------------------
72 | | Sanctum Middleware
73 | |--------------------------------------------------------------------------
74 | |
75 | | When authenticating your first-party SPA with Sanctum you may need to
76 | | customize some of the middleware Sanctum uses while processing the
77 | | request. You may change the middleware listed below as required.
78 | |
79 | */
80 |
81 | 'middleware' => [
82 | 'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class,
83 | 'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class,
84 | ],
85 |
86 | ];
87 |
--------------------------------------------------------------------------------
/nextjs/src/pages/forgot-password.js:
--------------------------------------------------------------------------------
1 | import ApplicationLogo from '@/components/ApplicationLogo'
2 | import AuthCard from '@/components/AuthCard'
3 | import AuthSessionStatus from '@/components/AuthSessionStatus'
4 | import Button from '@/components/Button'
5 | import GuestLayout from '@/components/Layouts/GuestLayout'
6 | import Input from '@/components/Input'
7 | import InputError from "@/components/InputError";
8 |
9 | import Label from '@/components/Label'
10 | import Link from 'next/link'
11 | import { useState } from 'react'
12 | import { front } from '@/lib/axios'
13 | import { useAuth } from '@/contexts/AuthContext';
14 |
15 | const ForgotPassword = () => {
16 |
17 | const { csrf } = useAuth();
18 | const [email, setEmail] = useState('')
19 | const [errors, setErrors] = useState([])
20 | const [status, setStatus] = useState(null)
21 |
22 | const submitForm = event => {
23 | event.preventDefault()
24 |
25 | const forgotPassword = async ({ setErrors, setStatus, email }) => {
26 |
27 | setErrors([])
28 | setStatus(null)
29 |
30 | front
31 | .post('/api/auth/forgot-password', { email }, {
32 | headers: {
33 | 'x-csrf-token': csrf.token
34 | },
35 | })
36 | .then(response => setStatus(response.data.status))
37 | .catch(error => {
38 | if (error.response.status !== 422) throw error
39 |
40 | setErrors(error.response.data.errors)
41 | })
42 | }
43 |
44 | forgotPassword({ email, setErrors, setStatus })
45 | }
46 |
47 | return (
48 |
49 |
52 |
53 |
54 | }>
55 |
56 | Forgot your password? No problem. Just let us know your
57 | email address and we will email you a password reset link
58 | that will allow you to choose a new one.
59 |
60 |
61 | {/* Session Status */}
62 |
63 |
64 |
86 |
87 |
88 | )
89 | }
90 |
91 | export default ForgotPassword
--------------------------------------------------------------------------------
/laravel/app/Notifications/VerifyEmail.php:
--------------------------------------------------------------------------------
1 | verificationUrl($notifiable);
48 |
49 | if (static::$toMailCallback) {
50 | return call_user_func(static::$toMailCallback, $notifiable, $verificationUrl);
51 | }
52 |
53 | return $this->buildMailMessage($verificationUrl);
54 | }
55 |
56 | /**
57 | * Get the verify email notification mail message for the given URL.
58 | *
59 | * @param string $url
60 | * @return \Illuminate\Notifications\Messages\MailMessage
61 | */
62 | protected function buildMailMessage($url)
63 | {
64 | return (new MailMessage)
65 | ->subject(Lang::get('Verify Email Address'))
66 | ->line(Lang::get('Please click the button below to verify your email address.'))
67 | ->action(Lang::get('Verify Email Address'), $url)
68 | ->line(Lang::get('If you did not create an account, no further action is required.'));
69 | }
70 |
71 | /**
72 | * Get the verification URL for the given notifiable.
73 | *
74 | * @param mixed $notifiable
75 | * @return string
76 | */
77 | protected function verificationUrl($notifiable)
78 | {
79 | if (static::$createUrlCallback) {
80 | return call_user_func(static::$createUrlCallback, $notifiable);
81 | }
82 |
83 | $url = URL::temporarySignedRoute('verification.verify', Carbon::now()->addMinutes(Config::get('auth.verification.expire', 60)), [
84 | 'id' => $notifiable->getKey(),
85 | 'hash' => sha1($notifiable->getEmailForVerification()),
86 | ]);
87 |
88 | return str_replace(Config::get('app.api_url') , Config::get('app.frontend_url'), $url);
89 | }
90 |
91 | /**
92 | * Set a callback that should be used when creating the email verification URL.
93 | *
94 | * @param \Closure $callback
95 | * @return void
96 | */
97 | public static function createUrlUsing($callback)
98 | {
99 | static::$createUrlCallback = $callback;
100 | }
101 |
102 | /**
103 | * Set a callback that should be used when building the notification mail message.
104 | *
105 | * @param \Closure $callback
106 | * @return void
107 | */
108 | public static function toMailUsing($callback)
109 | {
110 | static::$toMailCallback = $callback;
111 | }
112 | }
--------------------------------------------------------------------------------
/laravel/config/cache.php:
--------------------------------------------------------------------------------
1 | env('CACHE_DRIVER', 'file'),
19 |
20 | /*
21 | |--------------------------------------------------------------------------
22 | | Cache Stores
23 | |--------------------------------------------------------------------------
24 | |
25 | | Here you may define all of the cache "stores" for your application as
26 | | well as their drivers. You may even define multiple stores for the
27 | | same cache driver to group types of items stored in your caches.
28 | |
29 | | Supported drivers: "apc", "array", "database", "file",
30 | | "memcached", "redis", "dynamodb", "octane", "null"
31 | |
32 | */
33 |
34 | 'stores' => [
35 |
36 | 'apc' => [
37 | 'driver' => 'apc',
38 | ],
39 |
40 | 'array' => [
41 | 'driver' => 'array',
42 | 'serialize' => false,
43 | ],
44 |
45 | 'database' => [
46 | 'driver' => 'database',
47 | 'table' => 'cache',
48 | 'connection' => null,
49 | 'lock_connection' => null,
50 | ],
51 |
52 | 'file' => [
53 | 'driver' => 'file',
54 | 'path' => storage_path('framework/cache/data'),
55 | ],
56 |
57 | 'memcached' => [
58 | 'driver' => 'memcached',
59 | 'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
60 | 'sasl' => [
61 | env('MEMCACHED_USERNAME'),
62 | env('MEMCACHED_PASSWORD'),
63 | ],
64 | 'options' => [
65 | // Memcached::OPT_CONNECT_TIMEOUT => 2000,
66 | ],
67 | 'servers' => [
68 | [
69 | 'host' => env('MEMCACHED_HOST', '127.0.0.1'),
70 | 'port' => env('MEMCACHED_PORT', 11211),
71 | 'weight' => 100,
72 | ],
73 | ],
74 | ],
75 |
76 | 'redis' => [
77 | 'driver' => 'redis',
78 | 'connection' => 'cache',
79 | 'lock_connection' => 'default',
80 | ],
81 |
82 | 'dynamodb' => [
83 | 'driver' => 'dynamodb',
84 | 'key' => env('AWS_ACCESS_KEY_ID'),
85 | 'secret' => env('AWS_SECRET_ACCESS_KEY'),
86 | 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
87 | 'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
88 | 'endpoint' => env('DYNAMODB_ENDPOINT'),
89 | ],
90 |
91 | 'octane' => [
92 | 'driver' => 'octane',
93 | ],
94 |
95 | ],
96 |
97 | /*
98 | |--------------------------------------------------------------------------
99 | | Cache Key Prefix
100 | |--------------------------------------------------------------------------
101 | |
102 | | When utilizing the APC, database, memcached, Redis, or DynamoDB cache
103 | | stores there might be other applications using the same cache. For
104 | | that reason, you may prefix every cache key to avoid collisions.
105 | |
106 | */
107 |
108 | 'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache_'),
109 |
110 | ];
111 |
--------------------------------------------------------------------------------
/laravel/config/logging.php:
--------------------------------------------------------------------------------
1 | env('LOG_CHANNEL', 'stack'),
21 |
22 | /*
23 | |--------------------------------------------------------------------------
24 | | Deprecations Log Channel
25 | |--------------------------------------------------------------------------
26 | |
27 | | This option controls the log channel that should be used to log warnings
28 | | regarding deprecated PHP and library features. This allows you to get
29 | | your application ready for upcoming major versions of dependencies.
30 | |
31 | */
32 |
33 | 'deprecations' => [
34 | 'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
35 | 'trace' => false,
36 | ],
37 |
38 | /*
39 | |--------------------------------------------------------------------------
40 | | Log Channels
41 | |--------------------------------------------------------------------------
42 | |
43 | | Here you may configure the log channels for your application. Out of
44 | | the box, Laravel uses the Monolog PHP logging library. This gives
45 | | you a variety of powerful log handlers / formatters to utilize.
46 | |
47 | | Available Drivers: "single", "daily", "slack", "syslog",
48 | | "errorlog", "monolog",
49 | | "custom", "stack"
50 | |
51 | */
52 |
53 | 'channels' => [
54 | 'stack' => [
55 | 'driver' => 'stack',
56 | 'channels' => ['single'],
57 | 'ignore_exceptions' => false,
58 | ],
59 |
60 | 'single' => [
61 | 'driver' => 'single',
62 | 'path' => storage_path('logs/laravel.log'),
63 | 'level' => env('LOG_LEVEL', 'debug'),
64 | ],
65 |
66 | 'daily' => [
67 | 'driver' => 'daily',
68 | 'path' => storage_path('logs/laravel.log'),
69 | 'level' => env('LOG_LEVEL', 'debug'),
70 | 'days' => 14,
71 | ],
72 |
73 | 'slack' => [
74 | 'driver' => 'slack',
75 | 'url' => env('LOG_SLACK_WEBHOOK_URL'),
76 | 'username' => 'Laravel Log',
77 | 'emoji' => ':boom:',
78 | 'level' => env('LOG_LEVEL', 'critical'),
79 | ],
80 |
81 | 'papertrail' => [
82 | 'driver' => 'monolog',
83 | 'level' => env('LOG_LEVEL', 'debug'),
84 | 'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class),
85 | 'handler_with' => [
86 | 'host' => env('PAPERTRAIL_URL'),
87 | 'port' => env('PAPERTRAIL_PORT'),
88 | 'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'),
89 | ],
90 | ],
91 |
92 | 'stderr' => [
93 | 'driver' => 'monolog',
94 | 'level' => env('LOG_LEVEL', 'debug'),
95 | 'handler' => StreamHandler::class,
96 | 'formatter' => env('LOG_STDERR_FORMATTER'),
97 | 'with' => [
98 | 'stream' => 'php://stderr',
99 | ],
100 | ],
101 |
102 | 'syslog' => [
103 | 'driver' => 'syslog',
104 | 'level' => env('LOG_LEVEL', 'debug'),
105 | ],
106 |
107 | 'errorlog' => [
108 | 'driver' => 'errorlog',
109 | 'level' => env('LOG_LEVEL', 'debug'),
110 | ],
111 |
112 | 'null' => [
113 | 'driver' => 'monolog',
114 | 'handler' => NullHandler::class,
115 | ],
116 |
117 | 'emergency' => [
118 | 'path' => storage_path('logs/laravel.log'),
119 | ],
120 | ],
121 |
122 | ];
123 |
--------------------------------------------------------------------------------
/laravel/config/mail.php:
--------------------------------------------------------------------------------
1 | env('MAIL_MAILER', 'smtp'),
17 |
18 | /*
19 | |--------------------------------------------------------------------------
20 | | Mailer Configurations
21 | |--------------------------------------------------------------------------
22 | |
23 | | Here you may configure all of the mailers used by your application plus
24 | | their respective settings. Several examples have been configured for
25 | | you and you are free to add your own as your application requires.
26 | |
27 | | Laravel supports a variety of mail "transport" drivers to be used while
28 | | sending an e-mail. You will specify which one you are using for your
29 | | mailers below. You are free to add additional mailers as required.
30 | |
31 | | Supported: "smtp", "sendmail", "mailgun", "ses",
32 | | "postmark", "log", "array", "failover"
33 | |
34 | */
35 |
36 | 'mailers' => [
37 | 'smtp' => [
38 | 'transport' => 'smtp',
39 | 'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
40 | 'port' => env('MAIL_PORT', 587),
41 | 'encryption' => env('MAIL_ENCRYPTION', 'tls'),
42 | 'username' => env('MAIL_USERNAME'),
43 | 'password' => env('MAIL_PASSWORD'),
44 | 'timeout' => null,
45 | 'local_domain' => env('MAIL_EHLO_DOMAIN'),
46 | ],
47 |
48 | 'ses' => [
49 | 'transport' => 'ses',
50 | ],
51 |
52 | 'mailgun' => [
53 | 'transport' => 'mailgun',
54 | // 'client' => [
55 | // 'timeout' => 5,
56 | // ],
57 | ],
58 |
59 | 'postmark' => [
60 | 'transport' => 'postmark',
61 | // 'client' => [
62 | // 'timeout' => 5,
63 | // ],
64 | ],
65 |
66 | 'sendmail' => [
67 | 'transport' => 'sendmail',
68 | 'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'),
69 | ],
70 |
71 | 'log' => [
72 | 'transport' => 'log',
73 | 'channel' => env('MAIL_LOG_CHANNEL'),
74 | ],
75 |
76 | 'array' => [
77 | 'transport' => 'array',
78 | ],
79 |
80 | 'failover' => [
81 | 'transport' => 'failover',
82 | 'mailers' => [
83 | 'smtp',
84 | 'log',
85 | ],
86 | ],
87 | ],
88 |
89 | /*
90 | |--------------------------------------------------------------------------
91 | | Global "From" Address
92 | |--------------------------------------------------------------------------
93 | |
94 | | You may wish for all e-mails sent by your application to be sent from
95 | | the same address. Here, you may specify a name and address that is
96 | | used globally for all e-mails that are sent by your application.
97 | |
98 | */
99 |
100 | 'from' => [
101 | 'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
102 | 'name' => env('MAIL_FROM_NAME', 'Example'),
103 | ],
104 |
105 | /*
106 | |--------------------------------------------------------------------------
107 | | Markdown Mail Settings
108 | |--------------------------------------------------------------------------
109 | |
110 | | If you are using Markdown based email rendering, you may configure your
111 | | theme and component paths here, allowing you to customize the design
112 | | of the emails. Or, you may simply stick with the Laravel defaults!
113 | |
114 | */
115 |
116 | 'markdown' => [
117 | 'theme' => 'default',
118 |
119 | 'paths' => [
120 | resource_path('views/vendor/mail'),
121 | ],
122 | ],
123 |
124 | ];
125 |
--------------------------------------------------------------------------------
/nextjs/src/pages/email/verify/[userId]/[hash].js:
--------------------------------------------------------------------------------
1 | import { useAuth } from '@/contexts/AuthContext';
2 | import { useRouter } from 'next/router';
3 | import { useEffect, useState } from 'react';
4 | import { withAuth } from '@/lib/withAuth';
5 | import { front } from '@/lib/axios';
6 |
7 | const VerifyEmail = () => {
8 | const { csrf } = useAuth();
9 | const router = useRouter();
10 | const { expires, signature, userId, hash } = router.query;
11 | const [state, setState] = useState({
12 | loading: true,
13 | error: "",
14 | });
15 |
16 | useEffect(() => {
17 | const verifyEmail = async () => {
18 | try {
19 | if (csrf.token) {
20 | const res = await front.get(
21 | `/api/auth/email/verify-email?userId=${userId}&hash=${hash}&expires=${expires}&signature=${signature}`,
22 | {
23 | headers: {
24 | 'x-csrf-token': csrf.token,
25 | },
26 | }
27 | );
28 |
29 | if (res.data.status === 'redirect') {
30 | setState({
31 | ...state,
32 | loading: false,
33 | error: "",
34 | });
35 |
36 | // Redirect to Home route of the user after 3 seconds.
37 | setTimeout(() => {
38 | router.push(res.data.redirect_url);
39 | }, 3000);
40 | return;
41 | }
42 |
43 | // Set error message if verification failed.
44 | if (res.error) {
45 | setState({
46 | ...state,
47 | loading: false,
48 | error: res.error,
49 | });
50 | }
51 | }
52 | } catch (error) {
53 | // Handle errors
54 | console.error("Error verifying email:", error);
55 | setState({
56 | ...state,
57 | loading: false,
58 | error: "An unexpected error occurred while verifying the email.",
59 | });
60 | }
61 | };
62 |
63 | verifyEmail();
64 | }, [csrf.token]);
65 |
66 |
67 | const headerText = () => {
68 | if (state.loading) {
69 | return "We are currently validating your email address...";
70 | } else if (!state.loading && !state.error) {
71 | return "Verification successfull!";
72 | }
73 | return "Verification failed!";
74 | }
75 |
76 | const header = headerText();
77 |
78 | const paragraphText = () => {
79 | if (state.loading) {
80 | return "";
81 | } else if (!state.loading && !state.error) {
82 | return "Perfect! You will be redirected shortly....";
83 | }
84 | return "Sorry, something went wrong!";
85 | };
86 |
87 | const paragraph = paragraphText();
88 |
89 | return (
90 |
91 |
92 | {/* Card */}
93 | <>
94 | {/* Header */}
95 |
96 | {header}
97 |
98 |
99 | {/* Paragraph */}
100 |
101 | {state.loading && Loading... }
102 | {paragraph}
103 |
104 | >
105 |
106 |
107 | );
108 | }
109 |
110 |
111 | export const getServerSideProps = withAuth(async (context, user) => {
112 | const { req } = context;
113 |
114 |
115 | return {
116 | props: {
117 |
118 | },
119 | };
120 | });
121 |
122 | export default VerifyEmail;
--------------------------------------------------------------------------------
/laravel/config/auth.php:
--------------------------------------------------------------------------------
1 | [
17 | 'guard' => 'web',
18 | 'passwords' => 'users',
19 | ],
20 |
21 | /*
22 | |--------------------------------------------------------------------------
23 | | Authentication Guards
24 | |--------------------------------------------------------------------------
25 | |
26 | | Next, you may define every authentication guard for your application.
27 | | Of course, a great default configuration has been defined for you
28 | | here which uses session storage and the Eloquent user provider.
29 | |
30 | | All authentication drivers have a user provider. This defines how the
31 | | users are actually retrieved out of your database or other storage
32 | | mechanisms used by this application to persist your user's data.
33 | |
34 | | Supported: "session"
35 | |
36 | */
37 |
38 | 'guards' => [
39 | 'web' => [
40 | 'driver' => 'session',
41 | 'provider' => 'users',
42 | ],
43 | ],
44 |
45 | /*
46 | |--------------------------------------------------------------------------
47 | | User Providers
48 | |--------------------------------------------------------------------------
49 | |
50 | | All authentication drivers have a user provider. This defines how the
51 | | users are actually retrieved out of your database or other storage
52 | | mechanisms used by this application to persist your user's data.
53 | |
54 | | If you have multiple user tables or models you may configure multiple
55 | | sources which represent each model / table. These sources may then
56 | | be assigned to any extra authentication guards you have defined.
57 | |
58 | | Supported: "database", "eloquent"
59 | |
60 | */
61 |
62 | 'providers' => [
63 | 'users' => [
64 | 'driver' => 'eloquent',
65 | 'model' => App\Models\User::class,
66 | ],
67 |
68 | // 'users' => [
69 | // 'driver' => 'database',
70 | // 'table' => 'users',
71 | // ],
72 | ],
73 |
74 | /*
75 | |--------------------------------------------------------------------------
76 | | Resetting Passwords
77 | |--------------------------------------------------------------------------
78 | |
79 | | You may specify multiple password reset configurations if you have more
80 | | than one user table or model in the application and you want to have
81 | | separate password reset settings based on the specific user types.
82 | |
83 | | The expire time is the number of minutes that each reset token will be
84 | | considered valid. This security feature keeps tokens short-lived so
85 | | they have less time to be guessed. You may change this as needed.
86 | |
87 | | The throttle setting is the number of seconds a user must wait before
88 | | generating more password reset tokens. This prevents the user from
89 | | quickly generating a very large amount of password reset tokens.
90 | |
91 | */
92 |
93 | 'passwords' => [
94 | 'users' => [
95 | 'provider' => 'users',
96 | 'table' => 'password_reset_tokens',
97 | 'expire' => 60,
98 | 'throttle' => 60,
99 | ],
100 | ],
101 |
102 | /*
103 | |--------------------------------------------------------------------------
104 | | Password Confirmation Timeout
105 | |--------------------------------------------------------------------------
106 | |
107 | | Here you may define the amount of seconds before a password confirmation
108 | | times out and the user is prompted to re-enter their password via the
109 | | confirmation screen. By default, the timeout lasts for three hours.
110 | |
111 | */
112 |
113 | 'password_timeout' => 10800,
114 |
115 | ];
116 |
--------------------------------------------------------------------------------
/nextjs/src/lib/withAuth.js:
--------------------------------------------------------------------------------
1 | import axios from 'axios';
2 | import { createAxiosInstance } from './axios';
3 | import { PROTECTED_ROUTES, GUEST_ROUTES, VERIFY_EMAIL_ROUTE, REDIRECT_IF_AUTHENTICATED, REDIRECT_IF_NOT_AUTHENTICATED, EMAIL_VERIFICATION_ROUTE } from './route-service-provider';
4 |
5 | /**
6 | * This function is used to wrap a Next.js page component with authentication logic
7 | * which includes several middleware checks just like laravel and to pass auth user object to the page component.
8 | * use it to protect your routes and redirect the user to the login page if they are not authenticated.
9 | *
10 | * @param {function} getServerSidePropsFunc - The function to get the server side props.
11 | *
12 | * @returns {function} - The wrapped function.
13 | */
14 |
15 | export function withAuth(getServerSidePropsFunc) {
16 | return async (context) => {
17 |
18 | const { req, res } = context;
19 |
20 |
21 | async function getUserData() {
22 |
23 | try {
24 | const axiosInstance = createAxiosInstance(req, res);
25 | const response = await axiosInstance.get('/api/user');
26 | return response.data;
27 | } catch (error) {
28 |
29 | if (axios.isAxiosError(error) && error.response?.status === 409 && error.response?.data?.message === 'Your email address is not verified.')
30 | {
31 | return {
32 | redirect: {
33 | emailVerified: false,
34 | destination: EMAIL_VERIFICATION_ROUTE,
35 | },
36 | };
37 | }
38 | return null;
39 | }
40 | }
41 |
42 |
43 | const user = await getUserData();
44 | const pathname = context.resolvedUrl.split('?')[0];
45 |
46 | let isDynamicPath = false;
47 | let dynamicPathName = null;
48 | const queryKey = Object.keys(context.query)[0];
49 | if (queryKey && ['id', 'slug'].includes(queryKey)) {
50 | const value = context.query[queryKey];
51 | // check for UUID or numeric value
52 | if (/^[0-9a-fA-F-]{36}$/.test(value) || /^[0-9]+$/.test(value)) {
53 | isDynamicPath = true;
54 | dynamicPathName = pathname.replace(value, `[${queryKey}]`);
55 | }
56 | }
57 |
58 | const isProtectedRoute = isDynamicPath ? PROTECTED_ROUTES.includes(dynamicPathName) : PROTECTED_ROUTES.includes(pathname);
59 | const isGuestRoute = GUEST_ROUTES.includes(pathname);
60 | const isEmailVerifiedRoute = pathname.includes(VERIFY_EMAIL_ROUTE) || pathname.includes(EMAIL_VERIFICATION_ROUTE);
61 |
62 | if (user?.redirect?.emailVerified === false && !isEmailVerifiedRoute) {
63 | return {
64 | redirect: {
65 | destination: EMAIL_VERIFICATION_ROUTE,
66 | permanent: false,
67 | },
68 | };
69 | }
70 |
71 | if(user && context.resolvedUrl == EMAIL_VERIFICATION_ROUTE && user.email_verified_at)
72 | {
73 | return {
74 | redirect: {
75 | destination: REDIRECT_IF_AUTHENTICATED,
76 | permanent: false,
77 | }
78 | }
79 | }
80 |
81 | if (!user && isProtectedRoute) {
82 | // User is not authenticated and trying to access a protected route
83 | return {
84 | redirect: {
85 | destination: REDIRECT_IF_NOT_AUTHENTICATED,
86 | permanent: false,
87 | },
88 | };
89 | }
90 |
91 |
92 | if (user && isGuestRoute) {
93 | // User is authenticated and trying to access a guest route
94 | return {
95 | redirect: {
96 | destination: REDIRECT_IF_AUTHENTICATED,
97 | permanent: false,
98 | },
99 | };
100 | }
101 |
102 |
103 | // For non-protected and non-guest routes, or when authentication requirements are met
104 | if (getServerSidePropsFunc) {
105 | const pageProps = await getServerSidePropsFunc(context, user);
106 | if ('props' in pageProps) {
107 | return {
108 | props: {
109 | ...pageProps.props,
110 | user: user || null,
111 | },
112 | };
113 | }
114 | return pageProps;
115 | }
116 |
117 |
118 | // Default case: return the user data (or null if not authenticated)
119 | return { props: { user: user || null } };
120 | };
121 | }
122 |
--------------------------------------------------------------------------------
/nextjs/src/pages/index.js:
--------------------------------------------------------------------------------
1 | import Image from "next/image";
2 | import localFont from "next/font/local";
3 |
4 | const geistSans = localFont({
5 | src: "./fonts/GeistVF.woff",
6 | variable: "--font-geist-sans",
7 | weight: "100 900",
8 | });
9 | const geistMono = localFont({
10 | src: "./fonts/GeistMonoVF.woff",
11 | variable: "--font-geist-mono",
12 | weight: "100 900",
13 | });
14 |
15 | export default function Home() {
16 | return (
17 |
20 |
21 |
29 |
30 |
31 | Get started by editing{" "}
32 |
33 | src/pages/index.js
34 |
35 | .
36 |
37 | Save and see your changes instantly.
38 |
39 |
40 |
65 |
66 |
113 |
114 | );
115 | }
116 |
--------------------------------------------------------------------------------
/nextjs/src/lib/axios.js:
--------------------------------------------------------------------------------
1 | import axios from 'axios';
2 | import { toast } from 'react-toastify';
3 | import { access_token_key, refresh_token_key, access_token_expiration_key, refresh_token_expiration_key } from "@/lib/utils";
4 |
5 | // frontend axios instance
6 | export const front = axios.create({
7 | headers: {
8 | 'Content-Type': 'application/json',
9 | 'Accept': 'application/json',
10 | },
11 | withCredentials: true,
12 | });
13 |
14 | front.interceptors.response.use(
15 | (response) => response,
16 | (error) => {
17 | if (error.response?.status === 401 ) {
18 | toast.error(error.response?.data?.message);
19 | }
20 |
21 | if(error.response?.status === 419) {
22 | toast.error("PAGE EXPIRED");
23 | }
24 | if (error.response?.status === 429) {
25 | toast.error(error.response?.data?.message);
26 | }
27 | if (error.response?.status === 500) {
28 | toast.error("Oops some error occured");
29 | }
30 | return Promise.reject(error);
31 | }
32 | );
33 |
34 |
35 |
36 | // nextjs backend axios instance
37 | export const api = axios.create({
38 | baseURL: process.env.NEXT_BACKEND_URL,
39 | headers: {
40 | 'Content-Type': 'application/json',
41 | 'Accept': 'application/json',
42 | },
43 | withCredentials: true,
44 | });
45 |
46 | let isRefreshing = false;
47 |
48 | export const createAxiosInstance = (req, res) => {
49 | const access_token = req.cookies[access_token_key];
50 |
51 | const axiosInstance = axios.create({
52 | baseURL: process.env.NEXT_BACKEND_URL,
53 | headers: {
54 | 'Content-Type': 'application/json',
55 | 'Accept': 'application/json',
56 | },
57 | withCredentials: true,
58 | });
59 |
60 | axiosInstance.interceptors.request.use(async (config) => {
61 | if (access_token) {
62 | config.headers.Authorization = `Bearer ${access_token}`;
63 | }
64 | return config;
65 | });
66 |
67 | axiosInstance.interceptors.response.use(
68 | async (response) => response,
69 | async (error) => {
70 | const originalRequest = error.config;
71 |
72 |
73 | if (error.response?.status === 401 && !originalRequest._retry) {
74 |
75 | if (isRefreshing) {
76 | return Promise.reject({
77 | response: {
78 | status: 401,
79 | data: {
80 | message: 'Unauthorized please log in again',
81 | },
82 | },
83 | });
84 | }
85 |
86 | originalRequest._retry = true;
87 | isRefreshing = true;
88 |
89 | try {
90 | const old_refresh_token = req.cookies[refresh_token_key];
91 | const response = await axiosInstance.post('/api/refresh-token', {}, {
92 | headers: {
93 | Authorization: `Bearer ${old_refresh_token}`,
94 | },
95 | });
96 |
97 | const accessToken = response.data[access_token_key];
98 | const refreshToken = response.data[refresh_token_key];
99 | const accessTokenExpiration = response.data[access_token_expiration_key];
100 | const refreshTokenExpiration = response.data[refresh_token_expiration_key];
101 |
102 | res.setHeader('Set-Cookie', [
103 | `${access_token_key}=${accessToken}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=${accessTokenExpiration}`,
104 | `${refresh_token_key}=${refreshToken}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=${refreshTokenExpiration}`,
105 | ]);
106 |
107 | isRefreshing = false;
108 |
109 | originalRequest.headers.Authorization = `Bearer ${accessToken}`;
110 | return axiosInstance(originalRequest);
111 | } catch (err) {
112 |
113 | isRefreshing = false;
114 |
115 | res.setHeader('Set-Cookie', [
116 | `${access_token_key}=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0`,
117 | `${refresh_token_key}=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0`,
118 | ]);
119 |
120 | return Promise.reject(err);
121 | }
122 | }
123 |
124 | return Promise.reject(error);
125 | }
126 | );
127 |
128 | return axiosInstance;
129 | };
130 |
131 | export default api;
--------------------------------------------------------------------------------
/nextjs/src/pages/login.js:
--------------------------------------------------------------------------------
1 | import { useEffect, useState } from "react";
2 | import { useRouter } from "next/router";
3 | import { useAuth } from "@/contexts/AuthContext";
4 | import { withAuth } from "@/lib/withAuth";
5 | import AuthCard from "@/components/AuthCard";
6 | import GuestLayout from "@/components/Layouts/GuestLayout";
7 | import InputError from "@/components/InputError";
8 | import { REDIRECT_IF_AUTHENTICATED } from "@/lib/route-service-provider";
9 | import { front } from "@/lib/axios";
10 | import Button from "@/components/Button";
11 | import Link from "next/link";
12 | import Label from "@/components/Label";
13 | import Input from "@/components/Input";
14 | import AuthSessionStatus from "@/components/AuthSessionStatus";
15 | import ApplicationLogo from "@/components/ApplicationLogo";
16 |
17 | export default function Login() {
18 | const { csrf } = useAuth();
19 |
20 | const [email, setEmail] = useState("");
21 | const [password, setPassword] = useState("");
22 | const [errors, setErrors] = useState([]);
23 | const [loading, setLoading] = useState(false);
24 | const [status, setStatus] = useState(null)
25 |
26 | const router = useRouter();
27 |
28 | useEffect(() => {
29 | if (router.reset?.length > 0 && errors.length === 0) {
30 | setStatus(atob(router.reset))
31 | } else {
32 | setStatus(null)
33 | }
34 | })
35 |
36 |
37 | const submitForm = async (e) => {
38 | e.preventDefault();
39 | setLoading(true);
40 | setErrors([]);
41 | try {
42 |
43 | const result = await front.post('/api/auth/login', {
44 | email,
45 | password,
46 | csrf_token: csrf.token
47 | });
48 |
49 | await new Promise(resolve => setTimeout(resolve, 500));
50 | router.push(REDIRECT_IF_AUTHENTICATED);
51 |
52 | } catch (error) {
53 | if(error.response.status == 422) {
54 | setErrors(error.response.data.errors ?? error.response.data);
55 | } else {
56 | setErrors({
57 | message: `An error occurred during login (${error.response.data.error})`,
58 | // email: "An error occurred during login",
59 | // password: "An error occurred during login",
60 | });
61 | }
62 | } finally {
63 | setLoading(false);
64 | }
65 | };
66 |
67 |
68 | return (
69 |
70 |
73 |
74 |
75 | }>
76 | {/* Session Status */}
77 |
78 |
79 |
80 | {
81 | errors?.message && (
82 |
83 |
{errors?.message}
84 |
85 | )
86 | }
87 |
139 |
140 |
141 | );
142 | }
143 |
144 | export const getServerSideProps = withAuth(async (context) => {
145 | return {
146 | props: {},
147 | };
148 | });
--------------------------------------------------------------------------------
/nextjs/src/pages/reset-password/[token].js:
--------------------------------------------------------------------------------
1 | import ApplicationLogo from '@/components/ApplicationLogo'
2 | import AuthCard from '@/components/AuthCard'
3 | import AuthSessionStatus from '@/components/AuthSessionStatus'
4 | import Button from '@/components/Button'
5 | import GuestLayout from '@/components/Layouts/GuestLayout'
6 | import Input from '@/components/Input'
7 | import InputError from "@/components/InputError";
8 | import Label from '@/components/Label'
9 | import Link from 'next/link'
10 | import { useAuth } from '@/contexts/AuthContext';
11 | import { useEffect, useState } from 'react'
12 | import { useRouter } from 'next/router'
13 | import { front } from '@/lib/axios'
14 |
15 | const PasswordReset = () => {
16 | const router = useRouter()
17 | const { csrf } = useAuth();
18 | const { token } = router.query
19 |
20 | const [email, setEmail] = useState('')
21 | const [password, setPassword] = useState('')
22 | const [passwordConfirmation, setPasswordConfirmation] = useState('')
23 | const [errors, setErrors] = useState([])
24 | const [status, setStatus] = useState(null)
25 |
26 | const submitForm = event => {
27 | event.preventDefault()
28 |
29 | const resetPassword = async ({ setErrors, setStatus, ...props }) => {
30 |
31 | setErrors([])
32 | setStatus(null)
33 |
34 | front
35 | .post('/api/auth/reset-password', { token, ...props }, {
36 | headers: {
37 | 'x-csrf-token': csrf.token
38 | },
39 | })
40 | .then(response => {
41 | setStatus(response.data.message)
42 |
43 | setTimeout(() => {
44 | router.push('/login?reset=' + btoa(response.data.status))
45 | }, 3000)
46 | })
47 | .catch(error => {
48 | if (error.response.status !== 422) throw error
49 | // setStatus(error.response.data.message)
50 | setErrors(error.response.data.errors)
51 | })
52 | }
53 |
54 | resetPassword({
55 | email,
56 | password,
57 | password_confirmation: passwordConfirmation,
58 | setErrors,
59 | setStatus,
60 | })
61 | }
62 |
63 | useEffect(() => {
64 | setEmail(router.query.email || '')
65 | }, [router.query.email])
66 |
67 | return (
68 |
69 |
72 |
73 |
74 | }>
75 | {/* Session Status */}
76 |
77 |
78 |
141 |
142 |
143 | )
144 | }
145 |
146 | export default PasswordReset
--------------------------------------------------------------------------------
/laravel/config/database.php:
--------------------------------------------------------------------------------
1 | env('DB_CONNECTION', 'mysql'),
19 |
20 | /*
21 | |--------------------------------------------------------------------------
22 | | Database Connections
23 | |--------------------------------------------------------------------------
24 | |
25 | | Here are each of the database connections setup for your application.
26 | | Of course, examples of configuring each database platform that is
27 | | supported by Laravel is shown below to make development simple.
28 | |
29 | |
30 | | All database work in Laravel is done through the PHP PDO facilities
31 | | so make sure you have the driver for your particular database of
32 | | choice installed on your machine before you begin development.
33 | |
34 | */
35 |
36 | 'connections' => [
37 |
38 | 'sqlite' => [
39 | 'driver' => 'sqlite',
40 | 'url' => env('DATABASE_URL'),
41 | 'database' => env('DB_DATABASE', database_path('database.sqlite')),
42 | 'prefix' => '',
43 | 'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
44 | ],
45 |
46 | 'mysql' => [
47 | 'driver' => 'mysql',
48 | 'url' => env('DATABASE_URL'),
49 | 'host' => env('DB_HOST', '127.0.0.1'),
50 | 'port' => env('DB_PORT', '3306'),
51 | 'database' => env('DB_DATABASE', 'forge'),
52 | 'username' => env('DB_USERNAME', 'forge'),
53 | 'password' => env('DB_PASSWORD', ''),
54 | 'unix_socket' => env('DB_SOCKET', ''),
55 | 'charset' => 'utf8mb4',
56 | 'collation' => 'utf8mb4_unicode_ci',
57 | 'prefix' => '',
58 | 'prefix_indexes' => true,
59 | 'strict' => true,
60 | 'engine' => null,
61 | 'options' => extension_loaded('pdo_mysql') ? array_filter([
62 | PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
63 | ]) : [],
64 | ],
65 |
66 | 'pgsql' => [
67 | 'driver' => 'pgsql',
68 | 'url' => env('DATABASE_URL'),
69 | 'host' => env('DB_HOST', '127.0.0.1'),
70 | 'port' => env('DB_PORT', '5432'),
71 | 'database' => env('DB_DATABASE', 'forge'),
72 | 'username' => env('DB_USERNAME', 'forge'),
73 | 'password' => env('DB_PASSWORD', ''),
74 | 'charset' => 'utf8',
75 | 'prefix' => '',
76 | 'prefix_indexes' => true,
77 | 'search_path' => 'public',
78 | 'sslmode' => 'prefer',
79 | ],
80 |
81 | 'sqlsrv' => [
82 | 'driver' => 'sqlsrv',
83 | 'url' => env('DATABASE_URL'),
84 | 'host' => env('DB_HOST', 'localhost'),
85 | 'port' => env('DB_PORT', '1433'),
86 | 'database' => env('DB_DATABASE', 'forge'),
87 | 'username' => env('DB_USERNAME', 'forge'),
88 | 'password' => env('DB_PASSWORD', ''),
89 | 'charset' => 'utf8',
90 | 'prefix' => '',
91 | 'prefix_indexes' => true,
92 | // 'encrypt' => env('DB_ENCRYPT', 'yes'),
93 | // 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'),
94 | ],
95 |
96 | ],
97 |
98 | /*
99 | |--------------------------------------------------------------------------
100 | | Migration Repository Table
101 | |--------------------------------------------------------------------------
102 | |
103 | | This table keeps track of all the migrations that have already run for
104 | | your application. Using this information, we can determine which of
105 | | the migrations on disk haven't actually been run in the database.
106 | |
107 | */
108 |
109 | 'migrations' => 'migrations',
110 |
111 | /*
112 | |--------------------------------------------------------------------------
113 | | Redis Databases
114 | |--------------------------------------------------------------------------
115 | |
116 | | Redis is an open source, fast, and advanced key-value store that also
117 | | provides a richer body of commands than a typical key-value system
118 | | such as APC or Memcached. Laravel makes it easy to dig right in.
119 | |
120 | */
121 |
122 | 'redis' => [
123 |
124 | 'client' => env('REDIS_CLIENT', 'phpredis'),
125 |
126 | 'options' => [
127 | 'cluster' => env('REDIS_CLUSTER', 'redis'),
128 | 'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
129 | ],
130 |
131 | 'default' => [
132 | 'url' => env('REDIS_URL'),
133 | 'host' => env('REDIS_HOST', '127.0.0.1'),
134 | 'username' => env('REDIS_USERNAME'),
135 | 'password' => env('REDIS_PASSWORD'),
136 | 'port' => env('REDIS_PORT', '6379'),
137 | 'database' => env('REDIS_DB', '0'),
138 | ],
139 |
140 | 'cache' => [
141 | 'url' => env('REDIS_URL'),
142 | 'host' => env('REDIS_HOST', '127.0.0.1'),
143 | 'username' => env('REDIS_USERNAME'),
144 | 'password' => env('REDIS_PASSWORD'),
145 | 'port' => env('REDIS_PORT', '6379'),
146 | 'database' => env('REDIS_CACHE_DB', '1'),
147 | ],
148 |
149 | ],
150 |
151 | ];
152 |
--------------------------------------------------------------------------------
/nextjs/src/pages/register.js:
--------------------------------------------------------------------------------
1 | import { useState } from "react";
2 | import { useRouter } from "next/router";
3 | import { useAuth } from "@/contexts/AuthContext";
4 | import { withAuth } from "@/lib/withAuth";
5 | import AuthCard from "@/components/AuthCard";
6 | import GuestLayout from "@/components/Layouts/GuestLayout";
7 | import InputError from "@/components/InputError";
8 | import { REDIRECT_IF_AUTHENTICATED } from "@/lib/route-service-provider";
9 | import { front } from "@/lib/axios";
10 | import Button from "@/components/Button";
11 | import Link from "next/link";
12 | import Label from "@/components/Label";
13 | import Input from "@/components/Input";
14 | import AuthSessionStatus from "@/components/AuthSessionStatus";
15 | import ApplicationLogo from "@/components/ApplicationLogo";
16 |
17 | export default function Login() {
18 | const { csrf } = useAuth();
19 | const [name, setName] = useState("");
20 | const [email, setEmail] = useState("");
21 | const [password, setPassword] = useState("");
22 | const [passwordConfirmation, setPasswordConfirmation] = useState("");
23 | const [errors, setErrors] = useState([]);
24 | const [status, setStatus] = useState(null)
25 | const [loading, setLoading] = useState(false);
26 | const router = useRouter();
27 |
28 |
29 | const submitForm = async (e) => {
30 | e.preventDefault();
31 | setLoading(true);
32 | setErrors([]);
33 | try {
34 |
35 | const result = await front.post('/api/auth/register', {
36 | name,
37 | email,
38 | password,
39 | password_confirmation: passwordConfirmation,
40 | csrf_token: csrf.token
41 | });
42 |
43 | await new Promise(resolve => setTimeout(resolve, 500));
44 | router.push(REDIRECT_IF_AUTHENTICATED);
45 |
46 | } catch (error) {
47 | if(error.response.status == 422) {
48 | setErrors(error.response.data.errors ?? error.response.data);
49 | } else {
50 | setErrors({
51 | message: `An error occurred during login (${error.response.data.error})`,
52 | });
53 | }
54 | } finally {
55 | setLoading(false);
56 | }
57 | };
58 |
59 | // Add error message display
60 | ;
61 |
62 | return (
63 |
64 |
67 |
68 |
69 | }>
70 | {/* Session Status */}
71 |
72 |
73 | {errors?.message && (
74 |
75 |
{errors?.message}
76 |
77 | )}
78 |
79 |
165 |
166 |
167 | );
168 | }
169 |
170 | export const getServerSideProps = withAuth(async (context) => {
171 | return {
172 | props: {},
173 | };
174 | });
175 |
--------------------------------------------------------------------------------
/laravel/database/migrations/2024_11_16_102217_create_permission_tables.php:
--------------------------------------------------------------------------------
1 | engine('InnoDB');
29 | $table->bigIncrements('id'); // permission id
30 | $table->string('name'); // For MyISAM use string('name', 225); // (or 166 for InnoDB with Redundant/Compact row format)
31 | $table->string('guard_name'); // For MyISAM use string('guard_name', 25);
32 | $table->timestamps();
33 |
34 | $table->unique(['name', 'guard_name']);
35 | });
36 |
37 | Schema::create($tableNames['roles'], function (Blueprint $table) use ($teams, $columnNames) {
38 | //$table->engine('InnoDB');
39 | $table->bigIncrements('id'); // role id
40 | if ($teams || config('permission.testing')) { // permission.testing is a fix for sqlite testing
41 | $table->unsignedBigInteger($columnNames['team_foreign_key'])->nullable();
42 | $table->index($columnNames['team_foreign_key'], 'roles_team_foreign_key_index');
43 | }
44 | $table->string('name'); // For MyISAM use string('name', 225); // (or 166 for InnoDB with Redundant/Compact row format)
45 | $table->string('guard_name'); // For MyISAM use string('guard_name', 25);
46 | $table->timestamps();
47 | if ($teams || config('permission.testing')) {
48 | $table->unique([$columnNames['team_foreign_key'], 'name', 'guard_name']);
49 | } else {
50 | $table->unique(['name', 'guard_name']);
51 | }
52 | });
53 |
54 | Schema::create($tableNames['model_has_permissions'], function (Blueprint $table) use ($tableNames, $columnNames, $pivotPermission, $teams) {
55 | $table->unsignedBigInteger($pivotPermission);
56 |
57 | $table->string('model_type');
58 | $table->unsignedBigInteger($columnNames['model_morph_key']);
59 | $table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_permissions_model_id_model_type_index');
60 |
61 | $table->foreign($pivotPermission)
62 | ->references('id') // permission id
63 | ->on($tableNames['permissions'])
64 | ->onDelete('cascade');
65 | if ($teams) {
66 | $table->unsignedBigInteger($columnNames['team_foreign_key']);
67 | $table->index($columnNames['team_foreign_key'], 'model_has_permissions_team_foreign_key_index');
68 |
69 | $table->primary([$columnNames['team_foreign_key'], $pivotPermission, $columnNames['model_morph_key'], 'model_type'],
70 | 'model_has_permissions_permission_model_type_primary');
71 | } else {
72 | $table->primary([$pivotPermission, $columnNames['model_morph_key'], 'model_type'],
73 | 'model_has_permissions_permission_model_type_primary');
74 | }
75 |
76 | });
77 |
78 | Schema::create($tableNames['model_has_roles'], function (Blueprint $table) use ($tableNames, $columnNames, $pivotRole, $teams) {
79 | $table->unsignedBigInteger($pivotRole);
80 |
81 | $table->string('model_type');
82 | $table->unsignedBigInteger($columnNames['model_morph_key']);
83 | $table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_roles_model_id_model_type_index');
84 |
85 | $table->foreign($pivotRole)
86 | ->references('id') // role id
87 | ->on($tableNames['roles'])
88 | ->onDelete('cascade');
89 | if ($teams) {
90 | $table->unsignedBigInteger($columnNames['team_foreign_key']);
91 | $table->index($columnNames['team_foreign_key'], 'model_has_roles_team_foreign_key_index');
92 |
93 | $table->primary([$columnNames['team_foreign_key'], $pivotRole, $columnNames['model_morph_key'], 'model_type'],
94 | 'model_has_roles_role_model_type_primary');
95 | } else {
96 | $table->primary([$pivotRole, $columnNames['model_morph_key'], 'model_type'],
97 | 'model_has_roles_role_model_type_primary');
98 | }
99 | });
100 |
101 | Schema::create($tableNames['role_has_permissions'], function (Blueprint $table) use ($tableNames, $pivotRole, $pivotPermission) {
102 | $table->unsignedBigInteger($pivotPermission);
103 | $table->unsignedBigInteger($pivotRole);
104 |
105 | $table->foreign($pivotPermission)
106 | ->references('id') // permission id
107 | ->on($tableNames['permissions'])
108 | ->onDelete('cascade');
109 |
110 | $table->foreign($pivotRole)
111 | ->references('id') // role id
112 | ->on($tableNames['roles'])
113 | ->onDelete('cascade');
114 |
115 | $table->primary([$pivotPermission, $pivotRole], 'role_has_permissions_permission_id_role_id_primary');
116 | });
117 |
118 | app('cache')
119 | ->store(config('permission.cache.store') != 'default' ? config('permission.cache.store') : null)
120 | ->forget(config('permission.cache.key'));
121 | }
122 |
123 | /**
124 | * Reverse the migrations.
125 | */
126 | public function down(): void
127 | {
128 | $tableNames = config('permission.table_names');
129 |
130 | if (empty($tableNames)) {
131 | throw new \Exception('Error: config/permission.php not found and defaults could not be merged. Please publish the package configuration before proceeding, or drop the tables manually.');
132 | }
133 |
134 | Schema::drop($tableNames['role_has_permissions']);
135 | Schema::drop($tableNames['model_has_roles']);
136 | Schema::drop($tableNames['model_has_permissions']);
137 | Schema::drop($tableNames['roles']);
138 | Schema::drop($tableNames['permissions']);
139 | }
140 | };
141 |
--------------------------------------------------------------------------------