Certainly! Below is a well-structured implementation of the Player Service (Authentication & Authorization) microservice for the Futuristic Snake 3D Game as outlined in the revised architecture. This service handles user registration, login, and session management using Node.js, Express.js, PostgreSQL, and JWT for authentication.
The implementation follows best practices, includes comprehensive comments for clarity, and is organized for maintainability and scalability.
Table of Contents
- Project Structure
- Prerequisites
- Setup Instructions
- Code Implementation
- Testing the API
- Conclusion
Project Structure
player-service/
├── config/
│ └── db.js
├── controllers/
│ └── authController.js
├── middleware/
│ └── authMiddleware.js
├── models/
│ └── user.js
├── routes/
│ └── auth.js
├── utils/
│ └── generateToken.js
├── .env
├── package.json
└── server.js
Prerequisites
Ensure you have the following installed on your system:
- Node.js (v14 or later)
- npm (Node Package Manager)
- PostgreSQL (v12 or later)
- Redis (for session caching, optional but recommended)
Setup Instructions
-
Clone the Repository
git clone https://github.com/yourusername/player-service.git
cd player-service
-
Install Dependencies
npm install
-
Configure Environment Variables
Create a .env file in the root directory and add the following configurations:
PORT=5000
DATABASE_URL=postgresql://username:password@localhost:5432/playerdb
JWT_SECRET=your_jwt_secret_key
JWT_EXPIRE=30d
BCRYPT_SALT=10
Note: Replace username, password, and other placeholder values with your actual configurations.
-
Initialize the Database
-
Create the Database
-- Connect to PostgreSQL and run:
CREATE DATABASE playerdb;
-
Run Migrations
For simplicity, we'll create the users table manually. In a production environment, consider using migration tools like Sequelize or Knex.js.
-- Connect to `playerdb` and run:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-
Start the Server
npm start
The server should be running on http://localhost:5000.
Code Implementation
1. package.json
Defines the project dependencies and scripts.
{
"name": "player-service",
"version": "1.0.0",
"description": "Player Service for Futuristic Snake 3D Game - Handles Authentication & Authorization",
"main": "server.js",
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
},
"keywords": [
"player",
"authentication",
"authorization",
"microservice",
"nodejs",
"express"
],
"author": "Your Name",
"license": "MIT",
"dependencies": {
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"express-async-handler": "^1.2.0",
"jsonwebtoken": "^9.0.0",
"pg": "^8.8.0"
},
"devDependencies": {
"nodemon": "^2.0.20"
}
}
2. .env
Environment variables for configuration. Ensure this file is added to .gitignore to prevent sensitive data from being exposed.
PORT=5000
DATABASE_URL=postgresql://username:password@localhost:5432/playerdb
JWT_SECRET=your_jwt_secret_key
JWT_EXPIRE=30d
BCRYPT_SALT=10
3. config/db.js
Handles the connection to the PostgreSQL database.
// config/db.js
const { Pool } = require('pg');
const dotenv = require('dotenv');
// Load environment variables
dotenv.config();
// Create a new pool instance
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
// Test the database connection
pool.connect((err, client, release) => {
if (err) {
return console.error('Error acquiring client', err.stack);
}
console.log('Connected to PostgreSQL database');
release();
});
module.exports = pool;
4. models/user.js
Defines the User model for interacting with the users table in PostgreSQL.
// models/user.js
const pool = require('../config/db');
const createUser = async (username, email, password) => {
const query = `
INSERT INTO users (username, email, password)
VALUES ($1, $2, $3)
RETURNING id, username, email, created_at
`;
const values = [username, email, password];
const { rows } = await pool.query(query, values);
return rows[0];
};
const findUserByEmail = async (email) => {
const query = `
SELECT * FROM users WHERE email = $1
`;
const values = [email];
const { rows } = await pool.query(query, values);
return rows[0];
};
const findUserById = async (id) => {
const query = `
SELECT id, username, email, created_at FROM users WHERE id = $1
`;
const values = [id];
const { rows } = await pool.query(query, values);
return rows[0];
};
module.exports = {
createUser,
findUserByEmail,
findUserById,
};
5. utils/generateToken.js
Generates JWT tokens for authenticated users.
// utils/generateToken.js
const jwt = require('jsonwebtoken');
const dotenv = require('dotenv');
// Load environment variables
dotenv.config();
/**
* Generates a JWT token for a given user ID.
* @param {number} id - The user's ID.
* @returns {string} - Signed JWT token.
*/
const generateToken = (id) => {
return jwt.sign({ id }, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRE,
});
};
module.exports = generateToken;
6. middleware/authMiddleware.js
Middleware to protect routes and ensure that only authenticated users can access them.
// middleware/authMiddleware.js
const jwt = require('jsonwebtoken');
const asyncHandler = require('express-async-handler');
const pool = require('../config/db');
const dotenv = require('dotenv');
// Load environment variables
dotenv.config();
/**
* Middleware to protect routes. Ensures that the request has a valid JWT token.
*/
const protect = asyncHandler(async (req, res, next) => {
let token;
// Check if the Authorization header is present and starts with 'Bearer'
if (
req.headers.authorization &&
req.headers.authorization.startsWith('Bearer')
) {
try {
// Get token from header
token = req.headers.authorization.split(' ')[1];
// Verify token
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// Get user from the token
const query = 'SELECT id, username, email FROM users WHERE id = $1';
const values = [decoded.id];
const { rows } = await pool.query(query, values);
req.user = rows[0];
next();
} catch (error) {
console.error(error);
res.status(401);
throw new Error('Not authorized, token failed');
}
}
if (!token) {
res.status(401);
throw new Error('Not authorized, no token');
}
});
module.exports = { protect };
7. controllers/authController.js
Handles the business logic for authentication routes.
// controllers/authController.js
const asyncHandler = require('express-async-handler');
const bcrypt = require('bcryptjs');
const {
createUser,
findUserByEmail,
findUserById,
} = require('../models/user');
const generateToken = require('../utils/generateToken');
/**
* @desc Register a new user
* @route POST /api/auth/register
* @access Public
*/
const registerUser = asyncHandler(async (req, res) => {
const { username, email, password } = req.body;
// Validate input
if (!username || !email || !password) {
res.status(400);
throw new Error('Please provide username, email, and password');
}
// Check if user already exists
const existingUser = await findUserByEmail(email);
if (existingUser) {
res.status(400);
throw new Error('User with this email already exists');
}
// Hash password
const salt = await bcrypt.genSalt(parseInt(process.env.BCRYPT_SALT));
const hashedPassword = await bcrypt.hash(password, salt);
// Create user
const user = await createUser(username, email, hashedPassword);
if (user) {
res.status(201).json({
id: user.id,
username: user.username,
email: user.email,
created_at: user.created_at,
token: generateToken(user.id),
});
} else {
res.status(400);
throw new Error('Invalid user data');
}
});
/**
* @desc Authenticate user & get token
* @route POST /api/auth/login
* @access Public
*/
const authUser = asyncHandler(async (req, res) => {
const { email, password } = req.body;
// Validate input
if (!email || !password) {
res.status(400);
throw new Error('Please provide email and password');
}
// Check for user
const user = await findUserByEmail(email);
if (user && (await bcrypt.compare(password, user.password))) {
res.json({
id: user.id,
username: user.username,
email: user.email,
token: generateToken(user.id),
});
} else {
res.status(401);
throw new Error('Invalid email or password');
}
});
/**
* @desc Get user profile
* @route GET /api/auth/profile
* @access Private
*/
const getUserProfile = asyncHandler(async (req, res) => {
const user = await findUserById(req.user.id);
if (user) {
res.json(user);
} else {
res.status(404);
throw new Error('User not found');
}
});
module.exports = {
registerUser,
authUser,
getUserProfile,
};
8. routes/auth.js
Defines the authentication routes.
// routes/auth.js
const express = require('express');
const router = express.Router();
const {
registerUser,
authUser,
getUserProfile,
} = require('../controllers/authController');
const { protect } = require('../middleware/authMiddleware');
/**
* @route POST /api/auth/register
* @desc Register a new user
* @access Public
*/
router.post('/register', registerUser);
/**
* @route POST /api/auth/login
* @desc Authenticate user & get token
* @access Public
*/
router.post('/login', authUser);
/**
* @route GET /api/auth/profile
* @desc Get user profile
* @access Private
*/
router.get('/profile', protect, getUserProfile);
module.exports = router;
9. server.js
Entry point of the application. Sets up the Express server and middleware.
// server.js
const express = require('express');
const dotenv = require('dotenv');
const cors = require('cors');
const authRoutes = require('./routes/auth');
// Load environment variables
dotenv.config();
// Initialize Express app
const app = express();
// Middleware
app.use(express.json()); // Parse JSON bodies
app.use(express.urlencoded({ extended: false })); // Parse URL-encoded bodies
app.use(cors()); // Enable CORS
// Routes
app.use('/api/auth', authRoutes);
// Root Route
app.get('/', (req, res) => {
res.send('Player Service API is running');
});
// Error Handling Middleware
app.use((err, req, res, next) => {
console.error(err.stack);
const statusCode = res.statusCode === 200 ? 500 : res.statusCode;
res.status(statusCode).json({
message: err.message,
// stack: process.env.NODE_ENV === 'production' ? null : err.stack, // Uncomment in production
});
});
// Start the server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Player Service running on port ${PORT}`);
});
Testing the API
You can use tools like Postman or cURL to test the API endpoints.
-
Register a New User
-
Endpoint: POST http://localhost:5000/api/auth/register
-
Headers: Content-Type: application/json
-
Body:
{
"username": "snakePlayer",
"email": "snakeplayer@example.com",
"password": "SecureP@ssw0rd"
}
-
Response:
{
"id": 1,
"username": "snakePlayer",
"email": "snakeplayer@example.com",
"created_at": "2023-10-05T12:34:56.789Z",
"token": "jwt_token_here"
}
-
Login User
-
Endpoint: POST http://localhost:5000/api/auth/login
-
Headers: Content-Type: application/json
-
Body:
{
"email": "snakeplayer@example.com",
"password": "SecureP@ssw0rd"
}
-
Response:
{
"id": 1,
"username": "snakePlayer",
"email": "snakeplayer@example.com",
"token": "jwt_token_here"
}
-
Get User Profile
-
Endpoint: GET http://localhost:5000/api/auth/profile
-
Headers:
Content-Type: application/json
Authorization: Bearer jwt_token_here
-
Response:
{
"id": 1,
"username": "snakePlayer",
"email": "snakeplayer@example.com",
"created_at": "2023-10-05T12:34:56.789Z"
}
Conclusion
The above implementation provides a robust Player Service microservice that handles user authentication and authorization for the Futuristic Snake 3D Game. The service is designed with scalability, security, and maintainability in mind, adhering to best practices and coding standards.
Key Features:
-
Secure Password Handling: Passwords are hashed using bcrypt.js before storage to ensure security.
-
JWT-Based Authentication: Utilizes JSON Web Tokens for stateless and scalable authentication.
-
Protected Routes: Implements middleware to protect routes, ensuring that only authenticated users can access certain endpoints.
-
Modular Structure: Organized into separate directories for configuration, controllers, models, routes, middleware, and utilities, enhancing maintainability.
-
Error Handling: Centralized error handling middleware provides consistent responses and logging.
-
Environment Configuration: Sensitive information is managed through environment variables, promoting security and flexibility.
Next Steps:
To integrate this microservice into the broader architecture:
-
Connect with Other Services: Use API Gateway to route requests to this service and others as defined in the architecture.
-
Implement Additional Features: Extend the service to handle roles, permissions, password resets, and other user management functionalities.
-
Scale the Service: Deploy the service using Docker and Kubernetes for containerization and orchestration, enabling horizontal scaling.
-
Enhance Security: Incorporate additional security measures like rate limiting, input validation, and monitoring for suspicious activities.
-
Monitor and Log: Integrate with monitoring tools like Prometheus and logging systems like ELK Stack to track performance and troubleshoot issues.
By following this implementation and continuously iterating based on system requirements and user feedback, the Player Service will serve as a reliable and secure foundation for the game's authentication needs.