├── .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 | 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 | 7 | 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 | 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 | 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 | 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 | 26 |
{user.name}
27 |
28 |
29 | 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 |
65 | {/* Email Address */} 66 |
67 | 68 | setEmail(event.target.value)} 75 | required 76 | autoFocus 77 | /> 78 | 79 | 80 |
81 | 82 |
83 | 84 |
85 |
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 | Next.js logo 29 |
    30 |
  1. 31 | Get started by editing{" "} 32 | 33 | src/pages/index.js 34 | 35 | . 36 |
  2. 37 |
  3. Save and see your changes instantly.
  4. 38 |
39 | 40 |
41 | 47 | Vercel logomark 54 | Deploy now 55 | 56 | 62 | Read our docs 63 | 64 |
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 |
88 | {/* Email Address */} 89 |
90 | 91 | 92 | setEmail(event.target.value)} 98 | required 99 | autoFocus 100 | /> 101 | 102 | 103 |
104 | 105 | {/* Password */} 106 |
107 | 108 | 109 | setPassword(event.target.value)} 115 | required 116 | autoComplete="current-password" 117 | /> 118 | 119 | 123 |
124 | 125 | 126 | 127 |
128 | 131 | Forgot your password? 132 | 133 | 134 | 137 |
138 |
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 |
79 | {/* Email Address */} 80 |
81 | 82 | 83 | setEmail(event.target.value)} 89 | required 90 | autoFocus 91 | /> 92 | 93 | 94 |
95 | 96 | {/* Password */} 97 |
98 | 99 | setPassword(event.target.value)} 105 | required 106 | /> 107 | 108 | 112 |
113 | 114 | {/* Confirm Password */} 115 |
116 | 119 | 120 | 126 | setPasswordConfirmation(event.target.value) 127 | } 128 | required 129 | /> 130 | 131 | 135 |
136 | 137 |
138 | 139 |
140 |
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 |
80 | {/* Name */} 81 |
82 | 83 | 84 | setName(event.target.value)} 90 | required 91 | autoFocus 92 | /> 93 | 94 | 95 |
96 | 97 | {/* Email Address */} 98 |
99 | 100 | 101 | setEmail(event.target.value)} 107 | required 108 | /> 109 | 110 | 111 |
112 | 113 | {/* Password */} 114 |
115 | 116 | 117 | setPassword(event.target.value)} 123 | required 124 | autoComplete="new-password" 125 | /> 126 | 127 | 128 |
129 | 130 | {/* Confirm Password */} 131 |
132 | 135 | 136 | 142 | setPasswordConfirmation(event.target.value) 143 | } 144 | required 145 | /> 146 | 147 | 151 |
152 | 153 |
154 | 157 | Already registered? 158 | 159 | 160 | 163 |
164 |
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 | --------------------------------------------------------------------------------