Skip to content
Open
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
10 changes: 10 additions & 0 deletions code/henry-ogun-blog-api-1/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
node_modules/
.env
.DS_Store
public/uploads/
*.log
npm-debug.log*
.npm
.eslintcache
.nyc_output
coverage/
65 changes: 65 additions & 0 deletions code/henry-ogun-blog-api-1/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import dbConnect from './db.js';

// Import routes
import authRoutes from './routes/auth.js';
import userRoutes from './routes/users.js';
import postRoutes from './routes/posts.js';

dotenv.config();

const app = express();
const PORT = process.env.PORT || 4000;

// Connect to database
dbConnect();

// Middleware
app.use(cors({
origin: process.env.NODE_ENV === 'production'
? 'https://yourdomain.com'
: 'http://localhost:3000',
credentials: true
}));
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));

// Serve static files (for profile photos, featured images, etc.)
app.use('/images', express.static('public/images'));

// Routes
app.use('/api/auth', authRoutes);
app.use('/api/users', userRoutes);
app.use('/api/posts', postRoutes);

// Health check route
app.get('/health', (req, res) => {
res.json({
message: 'Blog API is running!',
timestamp: new Date().toISOString()
});
});

// 404 handler
app.use('*', (req, res) => {
res.status(404).json({
error: 'Route not found',
path: req.originalUrl
});
});

// Global error handler
app.use((error, req, res, next) => {
console.error('Global error handler:', error);
res.status(500).json({
error: 'Something went wrong!',
...(process.env.NODE_ENV === 'development' && { details: error.message })
});
});

app.listen(PORT, () => {
console.log(`🚀 Blog API server running on port ${PORT}`);
console.log(`📱 Health check: http://localhost:${PORT}/health`);
});
129 changes: 129 additions & 0 deletions code/henry-ogun-blog-api-1/controllers/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import User from '../models/User.js';

// Register new user
export const register = async (req, res) => {
try {
const { email, password, username, displayName, bio, tagline } = req.body;

// Validation
if (!email || !password || !username) {
return res.status(400).json({
error: 'Email, password, and username are required.'
});
}

if (password.length < 6) {
return res.status(400).json({
error: 'Password must be at least 6 characters long.'
});
}

// Check if user already exists
const existingUser = await User.findOne({
$or: [{ email }, { username }]
});

if (existingUser) {
return res.status(409).json({
error: 'User with this email or username already exists.'
});
}

// Hash password
const saltRounds = parseInt(process.env.SALT_ROUNDS) || 10;
const hashedPassword = await bcrypt.hash(password, saltRounds);

// Create user
const newUser = new User({
email,
password: hashedPassword,
username,
displayName: displayName || username,
bio: bio || '',
tagline: tagline || '',
});

await newUser.save();

// Generate token
const token = jwt.sign(
{ userId: newUser._id },
process.env.JWT_SECRET,
{ expiresIn: '24h' }
);

res.status(201).json({
message: 'User registered successfully',
token,
user: {
id: newUser._id,
email: newUser.email,
username: newUser.username,
displayName: newUser.displayName,
}
});

} catch (error) {
console.error('Registration error:', error);
res.status(500).json({
error: 'Internal server error during registration.'
});
}
};

// Login user
export const login = async (req, res) => {
try {
const { email, password } = req.body;

if (!email || !password) {
return res.status(400).json({
error: 'Email and password are required.'
});
}

// Find user by email
const user = await User.findOne({ email: email.toLowerCase() });
if (!user || !user.isActive) {
return res.status(401).json({
error: 'Invalid credentials.'
});
}

// Check password
const isValidPassword = await bcrypt.compare(password, user.password);
if (!isValidPassword) {
return res.status(401).json({
error: 'Invalid credentials.'
});
}

// Generate token
const token = jwt.sign(
{ userId: user._id },
process.env.JWT_SECRET,
{ expiresIn: '24h' }
);

res.json({
message: 'Login successful',
token,
user: {
id: user._id,
email: user.email,
username: user.username,
displayName: user.displayName,
bio: user.bio,
tagline: user.tagline,
}
});

} catch (error) {
console.error('Login error:', error);
res.status(500).json({
error: 'Internal server error during login.'
});
}
};
Loading