Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions app/admin.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { useState, useEffect } from 'react';
import axios from 'axios';
import { requireAuthentication } from './middleware';

export async function getServerSideProps(context) {
await requireAuthentication(context.req, context.res, () => {});

return { props: {} };
}

export default function AdminPage() {
const [users, setUsers] = useState([]);
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');

useEffect(() => {
async function fetchUsers() {
const response = await axios.get('/api/users');
setUsers(response.data);
}
fetchUsers();
}, []);

const handleCreateUser = async (e: React.FormEvent) => {
e.preventDefault();
try {
await axios.post('/api/auth/signup', { username, password });
setUsername('');
setPassword('');
setError('');
} catch (error) {
setError('User already exists');
}
};

return (
<div className="container">
<h1>Admin Page</h1>
<form onSubmit={handleCreateUser}>
<input
type="text"
placeholder="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button type="submit">Create User</button>
</form>
{error && <p className="error">{error}</p>}
<h2>Existing Users</h2>
<ul>
{users.map((user) => (
<li key={user.id}>{user.username}</li>
))}
</ul>
</div>
);
}
10 changes: 10 additions & 0 deletions app/api/auth/check.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { NextApiRequest, NextApiResponse } from 'next';
import { getLoginSession } from '../../auth';

export default async function handle(req: NextApiRequest, res: NextApiResponse) {
const user = await getLoginSession(req);
if (!user) {
return res.status(401).json({ loggedIn: false });
}
return res.status(200).json({ loggedIn: true });
}
30 changes: 30 additions & 0 deletions app/api/auth/login.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { NextApiRequest, NextApiResponse } from 'next';
import bcrypt from 'bcrypt';
import { prisma } from '../../prisma';
import { setLoginSession } from '../../auth';

export default async function handle(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'POST') {
return res.status(405).end();
}

const { username, password } = req.body;

const user = await prisma.user.findUnique({
where: { username },
});

if (!user) {
return res.status(401).json({ error: 'Invalid username or password' });
}

const isValid = await bcrypt.compare(password, user.password);

if (!isValid) {
return res.status(401).json({ error: 'Invalid username or password' });
}

await setLoginSession(res, user);

res.status(200).json({ message: 'Login successful' });
}
26 changes: 26 additions & 0 deletions app/api/auth/signup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { NextApiRequest, NextApiResponse } from 'next';
import bcrypt from 'bcrypt';
import { prisma } from '../../prisma';

export default async function handle(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'POST') {
return res.status(405).end();
}

const { username, password } = req.body;

const hashedPassword = await bcrypt.hash(password, 10);

try {
const user = await prisma.user.create({
data: {
username,
password: hashedPassword,
role: 'admin',
},
});
res.status(200).json({ message: 'User created successfully' });
} catch (error) {
res.status(500).json({ error: 'User already exists' });
}
}
46 changes: 46 additions & 0 deletions app/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { serialize, parse } from 'cookie';
import { NextApiResponse } from 'next';
import { v4 as uuidv4 } from 'uuid';
import { prisma } from './prisma';

const TOKEN_NAME = 'token';

export async function setLoginSession(res: NextApiResponse, user: any) {
const token = uuidv4();

await prisma.session.create({
data: {
token,
userId: user.id,
expiresAt: new Date(Date.now() + 60 * 60 * 24 * 7 * 1000), // 1 week
},
});

const cookie = serialize(TOKEN_NAME, token, {
maxAge: 60 * 60 * 24 * 7, // 1 week
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
path: '/',
sameSite: 'lax',
});

res.setHeader('Set-Cookie', cookie);
}

export async function getLoginSession(req: any) {
const cookies = parse(req.headers.cookie || '');
const token = cookies[TOKEN_NAME];

if (!token) return null;

const session = await prisma.session.findUnique({
where: { token },
include: { user: true },
});

if (!session || session.expiresAt < new Date()) {
return null;
}

return session.user;
}
46 changes: 46 additions & 0 deletions app/context/AuthContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
"use client";

import React, { createContext, useState, useEffect, useContext } from 'react';

interface AuthContextType {
isAuthenticated: boolean;
login: () => void;
logout: () => void;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);

useEffect(() => {
// Add your authentication logic here
const checkAuth = async () => {
// For example, call an API to check if the user is authenticated
setIsAuthenticated(true); // or false, depending on the result
};
checkAuth();
}, []);

const login = () => {
setIsAuthenticated(true);
};

const logout = () => {
setIsAuthenticated(false);
};

return (
<AuthContext.Provider value={{ isAuthenticated, login, logout }}>
{children}
</AuthContext.Provider>
);
};

export const useAuth = () => {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
};
15 changes: 8 additions & 7 deletions app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import "./globals.css";
import type { Metadata } from "next";
"use client";

export const metadata: Metadata = {
title: "Metabase Manager",
description: "Manage your Metabase instance",
};
import "./globals.css";
import { AuthProvider } from '@/app/context/AuthContext'; // Import AuthProvider

export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
<body>
<AuthProvider>
{children}
</AuthProvider>
</body>
</html>
);
}
42 changes: 42 additions & 0 deletions app/login.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { useState } from 'react';
import { useRouter } from 'next/router';
import axios from 'axios';

export default function LoginPage() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const router = useRouter();

const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
await axios.post('/api/auth/login', { username, password });
router.push('/');
} catch (error) {
setError('Invalid username or password');
}
};

return (
<div className="container">
<h1>Login</h1>
{error && <p className="error">{error}</p>}
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button type="submit">Login</button>
</form>
</div>
);
}
7 changes: 7 additions & 0 deletions app/metadata.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// app/metadata.ts
import type { Metadata } from "next";

export const metadata: Metadata = {
title: "Metabase Manager",
description: "Manage your Metabase instance",
};
22 changes: 22 additions & 0 deletions app/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { NextApiRequest, NextApiResponse, NextPageContext } from 'next';
import { getLoginSession } from './auth';

export async function requireAuthentication(
req: NextApiRequest | NextPageContext['req'],
res: NextApiResponse | NextPageContext['res'],
next: () => void
) {
const user = await getLoginSession(req);

if (!user) {
if (res) {
res.statusCode = 302;
res.setHeader('Location', '/login');
res.end();
}
return;
}

req.user = user;
next();
}
16 changes: 16 additions & 0 deletions app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,24 @@ import {
} from "./api";

import React, { Fragment } from "react"; // needed for collapsible
import { useAuth } from '@/app/context/AuthContext'; // Update this line
import { useRouter } from 'next/router';

export default function Home() {
//AUTH LOGIN ROUTING
const { isAuthenticated } = useAuth();
const router = useRouter();

useEffect(() => {
if (!isAuthenticated) {
router.push('/login'); // Redirect to login page if not authenticated
}
}, [isAuthenticated, router]);

if (!isAuthenticated) {
return <p>Loading...</p>;
}

const [sourceServers, setSourceServers] = useState<Server[]>([]);
const [proceedLoading, setProceedLoading] = useState(false);
const [destinationServers, setDestinationServers] = useState<Server[]>([]);
Expand Down
5 changes: 5 additions & 0 deletions app/prisma.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export { prisma };
Binary file modified bun.lockb
Binary file not shown.
Loading