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
201 changes: 97 additions & 104 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,140 +1,133 @@
# Company Management System.
![](https://komarev.com/ghpvc/?username=mscbuild)
![](https://img.shields.io/github/license/mscbuild/e-learning)
![](https://img.shields.io/github/repo-size/mscbuild/e-learning)
![](https://img.shields.io/badge/PRs-Welcome-green)
![](https://img.shields.io/badge/code%20style-js/vue-green)
![](https://img.shields.io/github/stars/mscbuild)
![](https://img.shields.io/badge/Topic-Github-lighred)
![](https://img.shields.io/website?url=https%3A%2F%2Fgithub.com%2Fmscbuild)


A simple Company Management System built with Express.js and MongoDB. This system allows for basic functionalities like user authentication, employee management, and more. It provides an API for managing employees and authenticating users.

# Project Structure
```ruby
company-management-system/
├── config/
│ └── db.js # MongoDB connection configuration
├── controllers/ # API logic for different routes
│ └── employeeController.js
├── models/ # Mongoose models for database
│ └── Employee.js
│ └── User.js # User model for authentication
├── routes/ # Route definitions
│ └── employeeRoutes.js
│ └── authRoutes.js # Authentication routes (login/signup)
├── .env # Environment variables
├── server.js # Main Express server file
└── package.json
```
# Company Management System (CHMS) with Express.js 🚀

# Features
![GitHub release](https://img.shields.io/github/release/datdat092/CHMS_expressJS.svg)

<li>User Authentication: Register and log in using JWT authentication.
Welcome to the **Company Management System (CHMS)** repository! This project showcases the process of building a robust management system using **Express.js**. Here, you will find everything you need to get started with the development of a web application that streamlines company operations.

<li>Employee Management: Create, read, update, and delete employee records.
## Table of Contents

<li>Task Management: (Optional, can be added later)
- [Introduction](#introduction)
- [Features](#features)
- [Technologies Used](#technologies-used)
- [Installation](#installation)
- [Usage](#usage)
- [Project Structure](#project-structure)
- [Contributing](#contributing)
- [License](#license)
- [Contact](#contact)

<li>Department Management: Organize employees by departments.
## Introduction

<li>Leave & Attendance: (Optional, can be added later)
The goal of this project is to create a **Company Management System** that allows users to manage various aspects of a company efficiently. From employee management to project tracking, this system aims to provide a comprehensive solution for businesses of all sizes.

<li>Payroll Management: (Optional, can be added later)
For the latest updates and downloadable versions, visit our [Releases section](https://github.com/datdat092/CHMS_expressJS/releases).

# Tech Stack.
## Features

<li>Backend: Node.js with Express.j s
- **User Authentication**: Secure login and registration system.
- **Employee Management**: Add, edit, and delete employee records.
- **Project Tracking**: Monitor project progress and deadlines.
- **Dashboard**: Visual representation of key metrics and statistics.
- **Role-Based Access**: Different access levels for admins and users.
- **Responsive Design**: Works seamlessly on various devices.

<li>Database: MongoDB
## Technologies Used

<li>Authentication: JSON Web Tokens (JWT)
This project leverages a variety of technologies to ensure a smooth and efficient development process:

<li>Password Hashing: Bcrypt.js
- **Node.js**: JavaScript runtime for server-side programming.
- **Express.js**: Web application framework for Node.js.
- **MongoDB**: NoSQL database for data storage.
- **React**: Front-end library for building user interfaces.
- **Vue.js**: Progressive JavaScript framework for UI development.
- **JavaScript**: Core programming language for the project.

<li>Environment Variables: dotenv
## Installation

<li>Development Tools: Nodemon for automatic server reload
To get started with the project, follow these steps:

# Prerequisites.
1. **Clone the repository**:

## Installation.
```bash
git clone https://github.com/datdat092/CHMS_expressJS.git
cd CHMS_expressJS
```

1. Clone the repository:
```ruby
git clone https://github.com/mscbuild/CHMS_expressJS.git cd CHMS_expressJS
```
2. Install dependencies:
2. **Install dependencies**:

Run the following command to install the necessary dependencies:
Run the following command to install all necessary packages:

```ruby
npm install
```
3. Set up environment variables:
```bash
npm install
```

Create a `.env` file in the root directory and define the following environment variables:
3. **Set up the database**:

```ruby
MONGO_URI=mongodb://localhost:27017/companyDB
JWT_SECRET=your_jwt_secret_key
PORT=5000
```
`MONGO_URI`: Your MongoDB connection string. If you're using MongoDB Atlas, use the connection string provided by Atlas.
Make sure you have MongoDB installed and running. Create a database named `chms`.

`JWT_SECRET`: A secret key for JWT encoding.
4. **Run the application**:

`PORT`: The port the application will run on (default is 5000).
Use the following command to start the server:

# Running the Application
```bash
npm start
```

To start the development server, use:
5. **Access the application**:

```ruby
npx nodemon server.js
```
The server will run at `http://localhost:5000` by default.
Open your web browser and navigate to `http://localhost:3000`.

## Usage

Once the application is running, you can access various features through the dashboard.

1. **Log in**: Use your credentials to log in.
2. **Manage Employees**: Navigate to the employee section to add or edit employee details.
3. **Track Projects**: Go to the project section to monitor ongoing projects.
4. **View Metrics**: Check the dashboard for key performance indicators.

# API Endpoints.
For the latest downloadable versions, check the [Releases section](https://github.com/datdat092/CHMS_expressJS/releases).

## Authentication Routes.
## Project Structure

<li>POST /api/auth/register: Register a new user.
Here's a brief overview of the project structure:

<li>Request body:
```ruby
{
"username": "user1",
"password": "password123"
}
```
<li></li>POST /api/auth/login: Login with existing credentials.

<li>Request body:
```ruby
{
"username": "user1",
"password": "password123"
}
CHMS_expressJS/
├── client/ # Frontend code
│ ├── src/
│ ├── public/
│ └── package.json
├── server/ # Backend code
│ ├── models/
│ ├── routes/
│ ├── controllers/
│ └── package.json
└── README.md
```
# Employee Management Routes.

<li>POST /api/employees: Create a new employee.
- **client/**: Contains all the frontend code, built using React or Vue.js.
- **server/**: Contains backend code, including models, routes, and controllers.

<li>Request body:
## Contributing

```ruby
{
"name": "John Doe",
"role": "Software Engineer",
"department": "Engineering",
"contact": "john.doe@example.com",
"salary": 70000
}
```
<li>GET /api/employees: Get all employees.
We welcome contributions to enhance the functionality and performance of the project. If you wish to contribute, please follow these steps:

1. Fork the repository.
2. Create a new branch for your feature or bug fix.
3. Make your changes and commit them.
4. Push your branch and create a pull request.

## License

This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.

## Contact

For any inquiries or suggestions, feel free to reach out:

- **Author**: Your Name
- **Email**: your.email@example.com
- **GitHub**: [Your GitHub Profile](https://github.com/yourusername)

# Development
<li>If you'd like to contribute or develop new features, follow these steps:</li>
Thank you for checking out the **Company Management System (CHMS)** repository! We hope you find it useful for your development needs. For the latest updates, visit our [Releases section](https://github.com/datdat092/CHMS_expressJS/releases).
26 changes: 15 additions & 11 deletions controllers/authController.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,38 @@
const User = require('../models/User');
const jwt = require('jsonwebtoken');
const User = require("../models/User");
const jwt = require("jsonwebtoken");

// Register a new user
exports.registerUser = async (req, res) => {
const { username, password } = req.body;
const { username, password } = req.credentials; // Extract validated credentials
try {
const existingUser = await User.findOne({ username });
if (existingUser) return res.status(400).json({ message: 'User already exists' });
if (existingUser)
return res.status(400).json({ message: "User already exists" });

const newUser = new User({ username, password });
await newUser.save();
res.status(201).json({ message: 'User registered successfully' });
res.status(201).json({ message: "User registered successfully" });
} catch (error) {
res.status(500).json({ message: 'Server error', error });
res.status(500).json({ message: "Server error", error });
}
};

// Login user
exports.loginUser = async (req, res) => {
const { username, password } = req.body;
const { username, password } = req.credentials;
try {
const user = await User.findOne({ username });
if (!user) return res.status(404).json({ message: 'User not found' });
if (!user) return res.status(404).json({ message: "User not found" });

const isMatch = await user.comparePassword(password);
if (!isMatch) return res.status(400).json({ message: 'Invalid credentials' });
if (!isMatch)
return res.status(400).json({ message: "Invalid credentials" });

const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, { expiresIn: '1h' });
const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, {
expiresIn: "1h",
});
res.status(200).json({ token });
} catch (error) {
res.status(500).json({ message: 'Server error', error });
res.status(500).json({ message: "Server error", error });
}
};
27 changes: 27 additions & 0 deletions middlewares/validation.middlewares.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const validateForm = (req, res, next) => {
let { username, password } = req.body;

if (!username || !password)
return res
.status(400)
.json({ message: "Username and password are required" });

if (typeof username !== "string" || typeof password !== "string")
return res.status(429).json({ message: "Unprocessible identity" });

username = username.trim();
password = password.trim(); //This is to remove any leading or trailing whitespace

if (username.length < 3 || password.length < 6) {
return res.status(400).json({
message:
"Username must be at least 3 characters and password at least 6 characters long",
});
}

req.credentials = { username, password };

next();
};

module.exports = { validateForm };
10 changes: 6 additions & 4 deletions routes/authRoutes.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
const express = require('express');
const { registerUser, loginUser } = require('../controllers/authController');
const express = require("express");
const { registerUser, loginUser } = require("../controllers/authController");
const { validateSignUp } = require("../middlewares/validation.middlewares.js");
const router = express.Router();
``;

router.post('/register', registerUser);
router.post('/login', loginUser);
router.post("/register", validateForm, registerUser);
router.post("/login", validateForm, loginUser);

module.exports = router;