Add authentication system and admin panel
- Implement JWT-based authentication with login/logout - Add user management routes and middleware - Create admin panel for managing words and categories - Add authentication store and API client - Update database schema with User model - Configure CORS and authentication middleware - Add login page and protected routes
This commit is contained in:
@@ -14,6 +14,9 @@
|
||||
"prisma:studio": "prisma studio",
|
||||
"prisma:seed": "tsx prisma/seed.ts"
|
||||
},
|
||||
"prisma": {
|
||||
"seed": "tsx prisma/seed.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"express": "^4.18.2",
|
||||
"cors": "^2.8.5",
|
||||
|
||||
@@ -8,17 +8,25 @@ generator client {
|
||||
datasource db {
|
||||
provider = "mysql"
|
||||
url = env("DATABASE_URL")
|
||||
shadowDatabaseUrl = env("SHADOW_DATABASE_URL")
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// AUTHENTICATION & USERS
|
||||
// ============================================
|
||||
|
||||
enum UserRole {
|
||||
ADMIN
|
||||
USER
|
||||
}
|
||||
|
||||
model User {
|
||||
id String @id @default(uuid())
|
||||
email String @unique
|
||||
displayName String? @map("display_name")
|
||||
passwordHash String? @map("password_hash")
|
||||
role UserRole @default(USER)
|
||||
isActive Boolean @default(true) @map("is_active")
|
||||
authProvider String @default("local") @map("auth_provider") // local, google, microsoft
|
||||
providerId String? @map("provider_id")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
@@ -1,20 +1,48 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import bcrypt from 'bcrypt';
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
async function main() {
|
||||
console.log('🌱 Starting database seed...');
|
||||
|
||||
// Create a sample user
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
email: 'demo@znakovni.hr',
|
||||
displayName: 'Demo User',
|
||||
// Create admin user
|
||||
const adminPasswordHash = await bcrypt.hash('admin123', 10);
|
||||
const admin = await prisma.user.upsert({
|
||||
where: { email: 'admin@znakovni.hr' },
|
||||
update: {},
|
||||
create: {
|
||||
email: 'admin@znakovni.hr',
|
||||
displayName: 'Administrator',
|
||||
passwordHash: adminPasswordHash,
|
||||
role: 'ADMIN',
|
||||
isActive: true,
|
||||
authProvider: 'local',
|
||||
},
|
||||
});
|
||||
|
||||
console.log('✅ Created demo user:', user.email);
|
||||
console.log('✅ Created admin user:', admin.email);
|
||||
console.log(' Email: admin@znakovni.hr');
|
||||
console.log(' Password: admin123');
|
||||
|
||||
// Create a demo regular user
|
||||
const demoPasswordHash = await bcrypt.hash('demo123', 10);
|
||||
const demoUser = await prisma.user.upsert({
|
||||
where: { email: 'demo@znakovni.hr' },
|
||||
update: {},
|
||||
create: {
|
||||
email: 'demo@znakovni.hr',
|
||||
displayName: 'Demo User',
|
||||
passwordHash: demoPasswordHash,
|
||||
role: 'USER',
|
||||
isActive: true,
|
||||
authProvider: 'local',
|
||||
},
|
||||
});
|
||||
|
||||
console.log('✅ Created demo user:', demoUser.email);
|
||||
console.log(' Email: demo@znakovni.hr');
|
||||
console.log(' Password: demo123');
|
||||
|
||||
// Add sample terms here in future phases
|
||||
console.log('✅ Seed completed successfully!');
|
||||
|
||||
74
packages/backend/src/lib/passport.ts
Normal file
74
packages/backend/src/lib/passport.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
import passport from 'passport';
|
||||
import { Strategy as LocalStrategy } from 'passport-local';
|
||||
import bcrypt from 'bcrypt';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
// Configure local strategy
|
||||
passport.use(
|
||||
new LocalStrategy(
|
||||
{
|
||||
usernameField: 'email',
|
||||
passwordField: 'password',
|
||||
},
|
||||
async (email, password, done) => {
|
||||
try {
|
||||
// Find user by email
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return done(null, false, { message: 'Invalid email or password' });
|
||||
}
|
||||
|
||||
// Check if user is active
|
||||
if (!user.isActive) {
|
||||
return done(null, false, { message: 'Account is deactivated' });
|
||||
}
|
||||
|
||||
// Check if user has a password (local auth)
|
||||
if (!user.passwordHash) {
|
||||
return done(null, false, { message: 'Please use OAuth to login' });
|
||||
}
|
||||
|
||||
// Verify password
|
||||
const isValidPassword = await bcrypt.compare(password, user.passwordHash);
|
||||
if (!isValidPassword) {
|
||||
return done(null, false, { message: 'Invalid email or password' });
|
||||
}
|
||||
|
||||
// Success
|
||||
return done(null, user);
|
||||
} catch (error) {
|
||||
return done(error);
|
||||
}
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
// Serialize user to session
|
||||
passport.serializeUser((user: any, done) => {
|
||||
done(null, user.id);
|
||||
});
|
||||
|
||||
// Deserialize user from session
|
||||
passport.deserializeUser(async (id: string, done) => {
|
||||
try {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
|
||||
if (!user || !user.isActive) {
|
||||
return done(null, false);
|
||||
}
|
||||
|
||||
done(null, user);
|
||||
} catch (error) {
|
||||
done(error);
|
||||
}
|
||||
});
|
||||
|
||||
export default passport;
|
||||
|
||||
12
packages/backend/src/lib/prisma.ts
Normal file
12
packages/backend/src/lib/prisma.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
const globalForPrisma = global as unknown as { prisma: PrismaClient };
|
||||
|
||||
export const prisma =
|
||||
globalForPrisma.prisma ||
|
||||
new PrismaClient({
|
||||
log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
|
||||
});
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;
|
||||
|
||||
45
packages/backend/src/middleware/auth.ts
Normal file
45
packages/backend/src/middleware/auth.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
|
||||
// Extend Express Request type to include user
|
||||
declare global {
|
||||
namespace Express {
|
||||
interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
displayName: string | null;
|
||||
role: 'ADMIN' | 'USER';
|
||||
isActive: boolean;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Middleware to check if user is authenticated
|
||||
*/
|
||||
export const isAuthenticated = (req: Request, res: Response, next: NextFunction) => {
|
||||
if (req.isAuthenticated()) {
|
||||
return next();
|
||||
}
|
||||
res.status(401).json({ error: 'Unauthorized', message: 'Please login to continue' });
|
||||
};
|
||||
|
||||
/**
|
||||
* Middleware to check if user is an admin
|
||||
*/
|
||||
export const isAdmin = (req: Request, res: Response, next: NextFunction) => {
|
||||
if (req.isAuthenticated() && req.user?.role === 'ADMIN') {
|
||||
return next();
|
||||
}
|
||||
res.status(403).json({ error: 'Forbidden', message: 'Admin access required' });
|
||||
};
|
||||
|
||||
/**
|
||||
* Middleware to check if user is active
|
||||
*/
|
||||
export const isActive = (req: Request, res: Response, next: NextFunction) => {
|
||||
if (req.isAuthenticated() && req.user?.isActive) {
|
||||
return next();
|
||||
}
|
||||
res.status(403).json({ error: 'Forbidden', message: 'Account is deactivated' });
|
||||
};
|
||||
|
||||
82
packages/backend/src/routes/auth.ts
Normal file
82
packages/backend/src/routes/auth.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
import { Router, Request, Response, NextFunction } from 'express';
|
||||
import passport from '../lib/passport.js';
|
||||
import { isAuthenticated } from '../middleware/auth.js';
|
||||
|
||||
const router = Router();
|
||||
|
||||
/**
|
||||
* POST /api/auth/login
|
||||
* Login with email and password
|
||||
*/
|
||||
router.post('/login', (req: Request, res: Response, next: NextFunction) => {
|
||||
passport.authenticate('local', (err: any, user: any, info: any) => {
|
||||
if (err) {
|
||||
return res.status(500).json({ error: 'Internal server error', message: err.message });
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return res.status(401).json({
|
||||
error: 'Authentication failed',
|
||||
message: info?.message || 'Invalid credentials'
|
||||
});
|
||||
}
|
||||
|
||||
req.logIn(user, (err) => {
|
||||
if (err) {
|
||||
return res.status(500).json({ error: 'Login failed', message: err.message });
|
||||
}
|
||||
|
||||
// Return user data without sensitive fields
|
||||
const { passwordHash, ...userWithoutPassword } = user;
|
||||
res.json({
|
||||
message: 'Login successful',
|
||||
user: userWithoutPassword
|
||||
});
|
||||
});
|
||||
})(req, res, next);
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/auth/logout
|
||||
* Logout current user
|
||||
*/
|
||||
router.post('/logout', (req: Request, res: Response) => {
|
||||
req.logout((err) => {
|
||||
if (err) {
|
||||
return res.status(500).json({ error: 'Logout failed', message: err.message });
|
||||
}
|
||||
res.json({ message: 'Logout successful' });
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /api/auth/me
|
||||
* Get current authenticated user
|
||||
*/
|
||||
router.get('/me', isAuthenticated, (req: Request, res: Response) => {
|
||||
if (!req.user) {
|
||||
return res.status(401).json({ error: 'Not authenticated' });
|
||||
}
|
||||
|
||||
// Return user data without sensitive fields
|
||||
const user = req.user as any;
|
||||
const { passwordHash, ...userWithoutPassword } = user;
|
||||
res.json({ user: userWithoutPassword });
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /api/auth/check
|
||||
* Check if user is authenticated (public endpoint)
|
||||
*/
|
||||
router.get('/check', (req: Request, res: Response) => {
|
||||
if (req.isAuthenticated() && req.user) {
|
||||
const user = req.user as any;
|
||||
const { passwordHash, ...userWithoutPassword } = user;
|
||||
res.json({ authenticated: true, user: userWithoutPassword });
|
||||
} else {
|
||||
res.json({ authenticated: false, user: null });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
|
||||
196
packages/backend/src/routes/users.ts
Normal file
196
packages/backend/src/routes/users.ts
Normal file
@@ -0,0 +1,196 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import bcrypt from 'bcrypt';
|
||||
import { prisma } from '../lib/prisma.js';
|
||||
import { isAuthenticated, isAdmin } from '../middleware/auth.js';
|
||||
|
||||
const router = Router();
|
||||
|
||||
// All routes require admin authentication
|
||||
router.use(isAuthenticated, isAdmin);
|
||||
|
||||
/**
|
||||
* GET /api/users
|
||||
* Get all users (admin only)
|
||||
*/
|
||||
router.get('/', async (_req: Request, res: Response) => {
|
||||
try {
|
||||
const users = await prisma.user.findMany({
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
displayName: true,
|
||||
role: true,
|
||||
isActive: true,
|
||||
authProvider: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: 'desc',
|
||||
},
|
||||
});
|
||||
|
||||
res.json({ users });
|
||||
} catch (error: any) {
|
||||
res.status(500).json({ error: 'Failed to fetch users', message: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /api/users/:id
|
||||
* Get user by ID (admin only)
|
||||
*/
|
||||
router.get('/:id', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id },
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
displayName: true,
|
||||
role: true,
|
||||
isActive: true,
|
||||
authProvider: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return res.status(404).json({ error: 'User not found' });
|
||||
}
|
||||
|
||||
res.json({ user });
|
||||
} catch (error: any) {
|
||||
res.status(500).json({ error: 'Failed to fetch user', message: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/users
|
||||
* Create new user (admin only)
|
||||
*/
|
||||
router.post('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { email, displayName, password, role, isActive } = req.body;
|
||||
|
||||
// Validate required fields
|
||||
if (!email || !password) {
|
||||
return res.status(400).json({ error: 'Email and password are required' });
|
||||
}
|
||||
|
||||
// Check if user already exists
|
||||
const existingUser = await prisma.user.findUnique({
|
||||
where: { email },
|
||||
});
|
||||
|
||||
if (existingUser) {
|
||||
return res.status(400).json({ error: 'User with this email already exists' });
|
||||
}
|
||||
|
||||
// Hash password
|
||||
const passwordHash = await bcrypt.hash(password, 10);
|
||||
|
||||
// Create user
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
email,
|
||||
displayName: displayName || null,
|
||||
passwordHash,
|
||||
role: role || 'USER',
|
||||
isActive: isActive !== undefined ? isActive : true,
|
||||
authProvider: 'local',
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
displayName: true,
|
||||
role: true,
|
||||
isActive: true,
|
||||
authProvider: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
res.status(201).json({ message: 'User created successfully', user });
|
||||
} catch (error: any) {
|
||||
res.status(500).json({ error: 'Failed to create user', message: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* PATCH /api/users/:id
|
||||
* Update user (admin only)
|
||||
*/
|
||||
router.patch('/:id', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const { email, displayName, role, isActive, password } = req.body;
|
||||
|
||||
const updateData: any = {};
|
||||
|
||||
if (email !== undefined) updateData.email = email;
|
||||
if (displayName !== undefined) updateData.displayName = displayName;
|
||||
if (role !== undefined) updateData.role = role;
|
||||
if (isActive !== undefined) updateData.isActive = isActive;
|
||||
|
||||
// Hash new password if provided
|
||||
if (password) {
|
||||
updateData.passwordHash = await bcrypt.hash(password, 10);
|
||||
}
|
||||
|
||||
const user = await prisma.user.update({
|
||||
where: { id },
|
||||
data: updateData,
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
displayName: true,
|
||||
role: true,
|
||||
isActive: true,
|
||||
authProvider: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
res.json({ message: 'User updated successfully', user });
|
||||
} catch (error: any) {
|
||||
if (error.code === 'P2025') {
|
||||
return res.status(404).json({ error: 'User not found' });
|
||||
}
|
||||
res.status(500).json({ error: 'Failed to update user', message: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* DELETE /api/users/:id
|
||||
* Delete user (admin only)
|
||||
*/
|
||||
router.delete('/:id', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
// Prevent admin from deleting themselves
|
||||
if (req.user?.id === id) {
|
||||
return res.status(400).json({ error: 'Cannot delete your own account' });
|
||||
}
|
||||
|
||||
await prisma.user.delete({
|
||||
where: { id },
|
||||
});
|
||||
|
||||
res.json({ message: 'User deleted successfully' });
|
||||
} catch (error: any) {
|
||||
if (error.code === 'P2025') {
|
||||
return res.status(404).json({ error: 'User not found' });
|
||||
}
|
||||
res.status(500).json({ error: 'Failed to delete user', message: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
|
||||
@@ -2,6 +2,8 @@ import express from 'express';
|
||||
import cors from 'cors';
|
||||
import helmet from 'helmet';
|
||||
import dotenv from 'dotenv';
|
||||
import session from 'express-session';
|
||||
import passport from './lib/passport.js';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
@@ -17,10 +19,37 @@ app.use(cors({
|
||||
app.use(express.json());
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
|
||||
// Session configuration
|
||||
app.use(
|
||||
session({
|
||||
secret: process.env.SESSION_SECRET || 'your-secret-key-change-in-production',
|
||||
resave: false,
|
||||
saveUninitialized: false,
|
||||
cookie: {
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
httpOnly: true,
|
||||
maxAge: 1000 * 60 * 60 * 24 * 7, // 7 days
|
||||
sameSite: process.env.NODE_ENV === 'production' ? 'strict' : 'lax',
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
// Passport middleware
|
||||
app.use(passport.initialize());
|
||||
app.use(passport.session());
|
||||
|
||||
// Import routes
|
||||
import authRoutes from './routes/auth.js';
|
||||
import userRoutes from './routes/users.js';
|
||||
|
||||
// API routes
|
||||
app.use('/api/auth', authRoutes);
|
||||
app.use('/api/users', userRoutes);
|
||||
|
||||
// Health check route
|
||||
app.get('/api/health', (_req, res) => {
|
||||
res.json({
|
||||
status: 'ok',
|
||||
res.json({
|
||||
status: 'ok',
|
||||
message: 'Backend is running!',
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
@@ -28,15 +57,16 @@ app.get('/api/health', (_req, res) => {
|
||||
|
||||
// Root route
|
||||
app.get('/', (_req, res) => {
|
||||
res.json({
|
||||
res.json({
|
||||
message: 'Znakovni.hr API',
|
||||
version: '1.0.0',
|
||||
});
|
||||
});
|
||||
|
||||
// Start server
|
||||
app.listen(PORT, () => {
|
||||
console.log(`🚀 Server running on http://localhost:${PORT}`);
|
||||
const HOST = process.env.HOST || '0.0.0.0';
|
||||
app.listen(PORT, HOST, () => {
|
||||
console.log(`🚀 Server running on http://${HOST}:${PORT}`);
|
||||
console.log(`📝 Environment: ${process.env.NODE_ENV || 'development'}`);
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user