samp.directory
← Betikler ve kütüphaneler

RJRYT/NcrpUcp

SA-MP New City RP User Control Panel with Discord OAuth2, built with Node.js, Express, React & Vite

Araç★ 0dün güncellendiAGPL-3.0JavaScript
GitHub’da aç

README.md

SampUcpNcrp

User Control Panel (UCP) for the New City RP SA-MP server.
A full-stack web panel built with Node.js, Express, React, and Vite. Provides user authentication via Discord OAuth2, profile and vehicle management, premium VIP tiers, admin tooling, and a Discord-bot-connected backend.


Table of Contents


Features

  • Discord OAuth2 authentication via passport-discord
  • Role-based permission system stored in MongoDB (admin, moderator, user)
  • Route-level permission guards with Express middleware
  • User profiles, vehicles, inventory, factions, and gangs management
  • Premium VIP tiers (Bronze, Silver, Gold, Platinum) with purchase pages
  • Song uploads and management with multer
  • Web push notifications
  • FAQ system
  • Admin console with user management, web logs, and statistics
  • Discord bot integration (discord.js) with a global DiscordClient
  • SA-MP static file hosting (APK downloads, client files)
  • Scheduled alert jobs via node-cron (daily spike and negative-balance checks)
  • Secure defaults: Helmet CSP, CORS, express-rate-limit, express-validator
  • Structured logging with Winston daily rotation
  • Frontend: React 18, Vite, Tailwind CSS, React Router, Axios, Framer Motion, React Toastify, Chart.js

Tech Stack

Backend

LayerTechnology
RuntimeNode.js 18+
FrameworkExpress 4
Database (users/game data)MySQL 8 (mysql2)
Database (permissions/roles)MongoDB (mongoose)
Authenticationpassport, passport-discord, jsonwebtoken
Securityhelmet, cors, express-rate-limit, express-validator
File uploadsmulter
Loggingwinston, winston-daily-rotate-file
Schedulingnode-cron
Discorddiscord.js
Dev toolingnodemon

Frontend

LayerTechnology
Build toolVite 6
UI libraryReact 18
StylingTailwind CSS
RoutingReact Router DOM 7
HTTP clientAxios
AnimationsFramer Motion
NotificationsReact Toastify
ChartsChart.js / react-chartjs-2
IconsLucide React, React Icons
3D models@google/model-viewer

Project Structure

samp-ucp/
├── main.js                    # Express backend entry point
├── socketStore.js             # SA-MP TCP socket state store
├── initPermission.js          # MongoDB permission/role seeder
├── .env                       # Environment variables (gitignored)
├── .env.example               # Example environment template
├── package.json               # Backend dependencies & scripts
├── package-lock.json
├── .gitignore
├── backup.md
├── routes.log
├── src/
│   ├── config/                # db.js, helmetConfig.js, permissions.js, rateLimit.js
│   ├── controllers/           # Route handlers (auth, user, admin, premium, songs, etc.)
│   ├── middleware/            # authMiddleware, errorHandler, requestLogger, accessLogger, restrictToPermission
│   ├── routes/                # Express route definitions (/api/auth, /api/user, /api/admin, ...)
│   ├── services/              # Business logic (userService, transactionService, alertService, ...)
│   ├── utils/                 # hashPassword, generateToken, loggers, syncPermissions, ipUtils
│   └── bot/                   # Discord bot client and API routes
├── client/                    # Vite + React frontend
│   ├── src/
│   │   ├── components/        # Reusable UI components (Navbar, ProtectedRoute, PermCheck, ...)
│   │   ├── context/           # AuthContext
│   │   ├── pages/             # Page components (UserHome, LoginPage, AdminPanel, ...)
│   │   ├── services/          # api.js (Axios instance)
│   │   └── utils/             # handleApiError, constants, debugLogger
│   ├── vite.config.js
│   ├── tailwind.config.js
│   └── package.json           # Frontend dependencies & scripts
├── samp/                      # Static SA-MP files served by Express (APK, client files)
├── test/                      # Placeholder test files (socket.js, client.js)
└── logs/                      # Winston daily-rotated logs (server, request, error, console)

Prerequisites

Verify the following are installed on your machine:

ToolPurposeVerify command
Node.js (18+)JavaScript runtimenode -v
npmPackage managernpm -v
MySQL 8+Primary application databasemysql --version
MongoDB 4+Permissions, roles, route-permissionsmongod --version
Discord applicationOAuth2 credentialsDiscord Developer Portal

Installation

1. Clone the repository

git clone https://github.com/RJRYT/NcrpUcp.git
cd NcrpUcp

2. Install backend dependencies

npm install

3. Install frontend dependencies

cd client
npm install
cd ..

4. Configure environment variables

Create a .env file in the project root. The file is gitignored, so it will not be committed.

See the Environment Variables section below for the full list of required variables.

5. Seed the permission system

Run the MongoDB seeder to initialize permissions, roles, and route-permissions:

node initPermission.js

⚠️ This script clears and repopulates the Permission, Role, and RoutePermission collections. Only run it on a fresh or disposable database.


Environment Variables

Create .env at the project root with the following variables:

VariableExampleDescription
APPLICATION_PORT3000Backend server port
MYSQL_DATABASE_HOSTlocalhostMySQL host
MYSQL_DATABASE_USERrootMySQL username
MYSQL_DATABASE_PASSWORDpasswordMySQL password
MYSQL_DATABASE_NAMEsamp_ucpMySQL database name
MONGO_URImongodb://localhost:27017/samp_ucpMongoDB connection string
DISCORD_0AUTH2_CLIENT_ID1234567890...Discord OAuth2 client ID
DISCORD_0AUTH2_CLIENT_SECRETabcdef123456...Discord OAuth2 client secret
DISCORD_0AUTH2_CALLBACK_URLhttp://localhost:3000/api/auth/discord/callbackDiscord OAuth2 redirect URI
API_DEBUG_LOGtrueEnable MySQL pool debug logging

Keep .env out of version control. Never commit real secrets.


Database Setup

MySQL

Create the database and user referenced in your .env, then run your schema migrations against it. The application expects tables for users, vehicles, factions, gangs, inventory, transactions, and related game data (referenced across src/routes/ and src/services/).

MongoDB

Ensure MongoDB is running, then execute the seeder:

node initPermission.js

This creates default roles (admin, moderator, user) and maps them to permissions and protected routes.


Running the Application

Backend (development)

# With auto-restart via nodemon
npm run dev

# Or plain Node
npm start

The backend starts on http://localhost:3000. It:

  • Connects the Discord bot client (exposed as global.DiscordClient)
  • Serves the production frontend from client/dist/
  • Serves static SA-MP files from samp/
  • Mounts all /api/* routes
  • Runs a daily cron job at 00:05 for alert checks

Frontend (development)

cd client
npm run dev    # Vite dev server (typically http://localhost:5173)

Running both together

You can run the backend and frontend in separate terminals, or use a process manager such as concurrently if you add it to your scripts.


Building for Production

1. Build the frontend

cd client
npm run build   # Outputs to client/dist/
cd ..

2. Start the backend

npm start

Express serves client/dist/ statically, so the built frontend is served by the same Node process that runs the API.

3. Preview the frontend build locally (optional)

cd client
npm run preview

Available Scripts

Root (package.json)

ScriptCommandDescription
devnodemon .Start backend with auto-restart
startnode .Start backend in production
testecho "Error: no test specified" && exit 1No test suite configured

Client (client/package.json)

ScriptCommandDescription
devviteStart frontend dev server
buildvite buildBuild frontend for production
linteslint .Lint frontend source
previewvite previewPreview production build locally

Authentication & Authorization

Authentication flow

  1. User selects Login with Discord.
  2. Browser redirects to Discord OAuth2.
  3. Discord redirects back to the callback route handled by passport-discord.
  4. On success, the backend issues a session/token (see src/controllers/authController.js).
  5. The frontend stores the token and attaches it to outgoing Axios requests via client/src/services/api.js.

Authorization

  • src/middleware/authMiddleware.js protects API routes.
  • src/middleware/restrictToPermission.js enforces MongoDB-based route permissions.
  • Permissions, roles, and route-permissions are seeded by initPermission.js and stored in MongoDB.

Default roles:

  • admin — Full access to all routes
  • moderator — Access to most routes, excluding permission management
  • user — Basic access to personal and public data

API Routes Overview

PrefixControllerPurpose
/api/authauthControllerDiscord login, registration, callbacks
/api/useruserControllerProfile, stats, inventory, vehicles, factions, gangs
/api/premiumpremiumControllerVIP tiers and purchases
/api/adminadminControllerAdmin console, user management, logs
/api/permspermissionControllerPermission, role, and route-permission CRUD
/api/push—Web push notifications
/api/faq—FAQ management
/api/songssongsControllerSong uploads and management
/apisrc/bot/api.jsBot-related API endpoints

SA-MP Integration

  • Express serves static files from the samp/ directory (e.g., APK downloads for the SA-MP client).
  • A TCP server for direct SA-MP communication is defined in main.js but is currently commented out. Uncomment and configure the TCP_PORT / TCP_HOST block if you need live game-server socket integration.
  • socketStore.js tracks the connected SA-MP socket state.
  • global.DiscordClient exposes the Discord bot instance across the Express app.

Logging

Winston with daily rotation writes to:

DirectoryContents
logs/server/Server access logs
logs/request/Categorized request logs
logs/error/Application errors, exceptions, and rejections
logs/console/Console output logs

Log directories are gitignored and generated at runtime.


Testing

There is no test suite configured in this repository. The root package.json defines test as a placeholder that exits with an error.

If you wish to add testing, consider installing vitest or jest + supertest and writing tests for:

  • Auth controllers and middleware
  • Express route validation (express-validator is already a dependency)
  • Service-layer business logic

Placeholder files exist under test/ (socket.js, client.js) but are not wired to a test runner.


Contributing

  1. Fork the repository.
  2. Create a feature branch (git checkout -b feature/your-feature).
  3. Commit your changes (git commit -m "feat: add your feature").
  4. Push to the branch (git push origin feature/your-feature).
  5. Open a Pull Request.

Please follow the existing code style and keep changes focused and minimal.


License

This project is licensed under the GNU Affero General Public License v3.0 (AGPL-3.0). See the LICENSE file for details.


Author

RJRYT — New City RP User Control Panel

discord-botdiscord-oauth2expressgamingmongodbmysqlnodejsreactroleplayroleplay-serversampsan-andreas-multiplayerucpuser-control-panelvite

Bu sayfa GitHub’ın depo hakkında yayımladıklarından oluşturulur. samp.directory kodu barındırmaz. Bu ilanla ilgili bir sorun bildir

RJRYT/NcrpUcp: SA-MP Araç | samp.directory