user management and authentication system

This commit is contained in:
2024-08-20 09:14:52 +02:00
parent 1d40161f27
commit 88991c9de0
3 changed files with 332 additions and 0 deletions

176
pages/admin/users.tsx Normal file
View File

@@ -0,0 +1,176 @@
import { useState, useEffect } from "react"
import type { NextPage } from "next"
import Head from "next/head"
import Link from "next/link"
interface User {
id: number
email: string
role: string
is_active: boolean
created_at: string
last_login: string | null
sources_moderated: number
}
const UsersManagement: NextPage = () => {
const [users, setUsers] = useState<User[]>([])
const [loading, setLoading] = useState(true)
const [showAddForm, setShowAddForm] = useState(false)
const [newUser, setNewUser] = useState({ email: '', password: '', role: 'moderator' })
useEffect(() => {
fetchUsers()
}, [])
const fetchUsers = async () => {
try {
const response = await fetch('/api/admin/users')
const data = await response.json()
setUsers(data.users || [])
} catch (error) {
console.error('Error fetching users:', error)
}
setLoading(false)
}
const handleAddUser = async (e: React.FormEvent) => {
e.preventDefault()
if (!newUser.email || !newUser.password) return
try {
const response = await fetch('/api/admin/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(newUser)
})
if (response.ok) {
setNewUser({ email: '', password: '', role: 'moderator' })
setShowAddForm(false)
fetchUsers()
} else {
const error = await response.json()
alert('Error: ' + error.error)
}
} catch (error) {
alert('Failed to add user')
}
}
if (loading) return <div>Loading...</div>
return (
<div>
<Head>
<title>Users Management - Infohliadka</title>
</Head>
<div style={{ padding: '20px' }}>
<div style={{ marginBottom: '20px' }}>
<Link href="/admin"> Back to Admin</Link>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
<h1>Users Management</h1>
<button
onClick={() => setShowAddForm(!showAddForm)}
style={{ padding: '10px 15px', backgroundColor: '#28a745', color: 'white', border: 'none', borderRadius: '4px' }}
>
Add User
</button>
</div>
{showAddForm && (
<div style={{ marginBottom: '20px', padding: '15px', backgroundColor: '#f8f9fa', border: '1px solid #ddd' }}>
<h3>Add New User</h3>
<form onSubmit={handleAddUser}>
<div style={{ marginBottom: '10px' }}>
<input
type="email"
placeholder="Email"
value={newUser.email}
onChange={(e) => setNewUser({...newUser, email: e.target.value})}
required
style={{ width: '200px', padding: '5px', marginRight: '10px' }}
/>
<input
type="password"
placeholder="Password"
value={newUser.password}
onChange={(e) => setNewUser({...newUser, password: e.target.value})}
required
style={{ width: '200px', padding: '5px', marginRight: '10px' }}
/>
<select
value={newUser.role}
onChange={(e) => setNewUser({...newUser, role: e.target.value})}
style={{ padding: '5px', marginRight: '10px' }}
>
<option value="moderator">Moderator</option>
<option value="admin">Admin</option>
</select>
<button type="submit" style={{ padding: '5px 15px', backgroundColor: '#007bff', color: 'white', border: 'none' }}>
Add
</button>
</div>
</form>
</div>
)}
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
<thead>
<tr style={{ backgroundColor: '#f8f9fa' }}>
<th style={{ padding: '10px', textAlign: 'left', border: '1px solid #ddd' }}>Email</th>
<th style={{ padding: '10px', textAlign: 'left', border: '1px solid #ddd' }}>Role</th>
<th style={{ padding: '10px', textAlign: 'left', border: '1px solid #ddd' }}>Status</th>
<th style={{ padding: '10px', textAlign: 'left', border: '1px solid #ddd' }}>Sources Moderated</th>
<th style={{ padding: '10px', textAlign: 'left', border: '1px solid #ddd' }}>Created</th>
<th style={{ padding: '10px', textAlign: 'left', border: '1px solid #ddd' }}>Last Login</th>
</tr>
</thead>
<tbody>
{users.map((user) => (
<tr key={user.id}>
<td style={{ padding: '10px', border: '1px solid #ddd' }}>{user.email}</td>
<td style={{ padding: '10px', border: '1px solid #ddd' }}>
<span style={{
padding: '2px 6px',
borderRadius: '3px',
backgroundColor: user.role === 'admin' ? '#dc3545' : '#17a2b8',
color: 'white',
fontSize: '12px'
}}>
{user.role}
</span>
</td>
<td style={{ padding: '10px', border: '1px solid #ddd' }}>
<span style={{
color: user.is_active ? 'green' : 'red'
}}>
{user.is_active ? 'Active' : 'Inactive'}
</span>
</td>
<td style={{ padding: '10px', border: '1px solid #ddd' }}>{user.sources_moderated}</td>
<td style={{ padding: '10px', border: '1px solid #ddd' }}>
{new Date(user.created_at).toLocaleDateString()}
</td>
<td style={{ padding: '10px', border: '1px solid #ddd' }}>
{user.last_login ? new Date(user.last_login).toLocaleDateString() : 'Never'}
</td>
</tr>
))}
</tbody>
</table>
{users.length === 0 && (
<p style={{ textAlign: 'center', marginTop: '20px', color: '#666' }}>
No users found.
</p>
)}
</div>
</div>
)
}
export default UsersManagement

81
pages/api/admin/users.ts Normal file
View File

@@ -0,0 +1,81 @@
import type { NextApiRequest, NextApiResponse } from "next"
import sqlite3 from "sqlite3"
import path from "path"
import crypto from "crypto"
function hashPassword(password: string): { hash: string, salt: string } {
const salt = crypto.randomBytes(32).toString('hex')
const hash = crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha256').toString('hex')
return { hash, salt }
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const dbPath = path.join(process.cwd(), "database", "antihoax.db")
const db = new sqlite3.Database(dbPath)
try {
if (req.method === "GET") {
const users = await new Promise<any[]>((resolve, reject) => {
db.all(
`SELECT id, email, role, is_active, created_at, last_login,
(SELECT COUNT(*) FROM sources WHERE moderator_id = users.id) as sources_moderated
FROM users ORDER BY created_at DESC`,
(err, rows) => {
if (err) reject(err)
else resolve(rows)
}
)
})
res.json({ users })
} else if (req.method === "POST") {
const { email, password, role } = req.body
if (!email || !password || !role) {
return res.status(400).json({ error: "Email, password and role required" })
}
if (!['admin', 'moderator'].includes(role)) {
return res.status(400).json({ error: "Invalid role" })
}
const { hash, salt } = hashPassword(password)
const result = await new Promise<any>((resolve, reject) => {
db.run(
`INSERT INTO users (email, password_hash, salt, role, is_active, created_at)
VALUES (?, ?, ?, ?, 1, datetime('now'))`,
[email, hash, salt, role],
function(err) {
if (err) reject(err)
else resolve({ id: this.lastID })
}
)
})
res.json({
success: true,
user: {
id: result.id,
email,
role,
is_active: true
}
})
} else {
res.status(405).json({ error: "Method not allowed" })
}
} catch (error) {
console.error('Users API error:', error)
if (error.code === 'SQLITE_CONSTRAINT_UNIQUE') {
res.status(400).json({ error: "User already exists" })
} else {
res.status(500).json({ error: "Operation failed" })
}
} finally {
db.close()
}
}

75
pages/api/auth/login.ts Normal file
View File

@@ -0,0 +1,75 @@
import type { NextApiRequest, NextApiResponse } from "next"
import sqlite3 from "sqlite3"
import path from "path"
import crypto from "crypto"
function hashPassword(password: string, salt: string): string {
return crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha256').toString('hex')
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "POST") return res.status(405).json({ error: "Method not allowed" })
const { email, password } = req.body
if (!email || !password) {
return res.status(400).json({ error: "Email and password required" })
}
const dbPath = path.join(process.cwd(), "database", "antihoax.db")
const db = new sqlite3.Database(dbPath)
try {
const user = await new Promise<any>((resolve, reject) => {
db.get(
"SELECT id, email, password_hash, salt, role, is_active FROM users WHERE email = ?",
[email],
(err, row) => {
if (err) reject(err)
else resolve(row)
}
)
})
if (!user) {
return res.status(401).json({ error: "Invalid credentials" })
}
if (!user.is_active) {
return res.status(401).json({ error: "Account is disabled" })
}
const hashedPassword = hashPassword(password, user.salt)
if (hashedPassword !== user.password_hash) {
return res.status(401).json({ error: "Invalid credentials" })
}
// Update last login
await new Promise<void>((resolve, reject) => {
db.run(
"UPDATE users SET last_login = datetime('now') WHERE id = ?",
[user.id],
(err) => {
if (err) reject(err)
else resolve()
}
)
})
res.json({
success: true,
user: {
id: user.id,
email: user.email,
role: user.role
},
token: Buffer.from(`${user.id}:${Date.now()}`).toString('base64')
})
} catch (error) {
console.error('Login error:', error)
res.status(500).json({ error: "Login failed" })
} finally {
db.close()
}
}