{"id":23235786,"url":"https://github.com/seifsheikhelarab/ts-rest-api","last_synced_at":"2026-04-09T19:53:26.444Z","repository":{"id":268274242,"uuid":"903837529","full_name":"seifsheikhelarab/ts-rest-api","owner":"seifsheikhelarab","description":"A TypeScript-based REST API for user authentication and management with JWT-based authentication, bcrypt password hashing, and secure session handling.","archived":false,"fork":false,"pushed_at":"2024-12-23T22:40:18.000Z","size":37,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-06-06T05:02:24.031Z","etag":null,"topics":["bcrypt","body-parser","compression","cookie-parser","cors","crypto","dotenv","express-js","http","jsonwebtoken","lodash","mongodb","mongoose","morgan","node-js","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/seifsheikhelarab.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-12-15T17:24:18.000Z","updated_at":"2024-12-23T22:40:22.000Z","dependencies_parsed_at":"2025-04-05T20:35:43.027Z","dependency_job_id":"54678dc1-d75b-4960-b1e1-af6ec3647fc2","html_url":"https://github.com/seifsheikhelarab/ts-rest-api","commit_stats":null,"previous_names":["seifsheikhelarab/ts-rest-api"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/seifsheikhelarab/ts-rest-api","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/seifsheikhelarab%2Fts-rest-api","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/seifsheikhelarab%2Fts-rest-api/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/seifsheikhelarab%2Fts-rest-api/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/seifsheikhelarab%2Fts-rest-api/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/seifsheikhelarab","download_url":"https://codeload.github.com/seifsheikhelarab/ts-rest-api/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/seifsheikhelarab%2Fts-rest-api/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":266413520,"owners_count":23924745,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-07-22T02:00:09.085Z","response_time":66,"last_error":null,"robots_txt_status":null,"robots_txt_updated_at":null,"robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bcrypt","body-parser","compression","cookie-parser","cors","crypto","dotenv","express-js","http","jsonwebtoken","lodash","mongodb","mongoose","morgan","node-js","typescript"],"created_at":"2024-12-19T03:29:32.496Z","updated_at":"2025-12-30T19:19:38.875Z","avatar_url":"https://github.com/seifsheikhelarab.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# User Auth REST API with TS\n\nA TypeScript-based REST API for user authentication and management with JWT-based authentication, bcrypt password hashing, and secure session handling.\n\n## Features\n\n- **User Registration and Login**: Allows users to register and log in, with password hashing and JWT-based session tokens.\n- **JWT Authentication**: Routes protected by JWT authentication middleware.\n- **User Management**: Users can be created, updated, and deleted through the API.\n- **Session Tokens**: Uses JWT for maintaining secure user sessions.\n- **Database**: MongoDB is used for persistent data storage.\n\n## Requirements\n\n- Node.js\n- MongoDB (for data storage)\n\n## Installation\n\n### 1. Clone the repository:\n\n```bash\ngit clone https://github.com/seifsheikhelarab/ts-rest-api.git\ncd ts-rest-api\n```\n\n### 2. Install dependencies:\n\n```bash\nnpm install\n```\n\n### 3. Set up environment variables:\n\nCreate a `.env` file in the root of the project and add the following environment variables:\n\n```bash\nPORT=8080           \nMONGO_URL=mongodb://localhost:27017/yourdbname\nNODE_ENV = DEVELOPMENT \nJWT_SECRET=your_jwt_secret\nJWT_EXPIRATION = exp_time_in_ms\n```\n\n### 4. Start the application:\n\nTo run the application in development mode:\n\n```bash\nnpm run dev\n```\n\nThe server will start on `http://localhost:8080` (or any port you configure in `.env`).\n\n## API Endpoints\n\n### Authentication\n\n- **POST `/auth/register`**: Register a new user.\n  \n  **Request body**:\n  ```json\n  {\n    \"email\": \"user@example.com\",\n    \"password\": \"password123\",\n    \"username\": \"user123\"\n  }\n  ```\n\n  **Response**:\n  ```json\n  {\n    \"_id\": \"user-id\",\n    \"email\": \"user@example.com\",\n    \"username\": \"user123\",\n    \"authentication\": {\n      \"password\": \"hashed-password\",\n      \"sessionToken\": \"jwt-token\"\n    }\n  }\n  ```\n\n- **POST `/auth/login`**: Log in to get a valid token.\n\n  **Request body**:\n  ```json\n  {\n    \"email\": \"user@example.com\",\n    \"password\": \"password123\"\n  }\n  ```\n\n  **Response**:\n  ```json\n  {\n    \"authentication\": {\n        \"password\": \"hashedpassword\"\n    },\n    \"_id\": \"id\",\n    \"username\": \"username\",\n    \"email\": \"example@gmail.com\",\n    \"__v\": 0\n  }\n  ```\n\n### User Management\n\n- **GET `/users`**: Get a list of all users. (Protected route)\n\n  **Response**:\n  ```json\n  [\n    {\n      \"_id\": \"user-id\",\n      \"email\": \"user@example.com\",\n      \"username\": \"user123\",\n      \"authentication\": {\n        \"password\": \"hashed-password\",\n        \"sessionToken\": \"jwt-token\"\n      }\n    }\n  ]\n  ```\n\n\n\n- **PATCH `/users/:id`**: Update a user's details (only if the logged-in user is the owner).\n\n  **Request body**:\n  ```json\n  {\n    \"username\": \"newUsername\"\n  }\n  ```\n\n  **Response**:\n  ```json\n  {\n    \"_id\": \"user-id\",\n    \"email\": \"user@example.com\",\n    \"username\": \"newUsername\",\n    \"authentication\": {\n      \"password\": \"hashed-password\",\n      \"sessionToken\": \"jwt-token\"\n    }\n  }\n  ```\n\n- **DELETE `/users/:id`**: Delete a user (only if the logged-in user is the owner).\n\n  **Response**:\n  ```json\n  {\n    \"_id\": \"user-id\",\n    \"username\": \"Username\",\n    \"email\": \"example1@gmail.com\",\n    \"__v\": 0\n  }\n\n## Postman Collection\n\nFor easier usage and testing of the API, I have included a Postman collection. This collection contains all the necessary API endpoints along with sample requests and responses to help you interact with the application without needing to manually configure each request.\n\n### How to Use the Postman Collection:\n1. Download the [Postman Collection](https://github.com/seifsheikhelarab/postman_collection/ts-rest-api.postman_collection.json) file.\n2. Import the collection into Postman by clicking on **Import** in the top-left corner of the Postman app and selecting the collection file.\n3. Ensure your API server is running locally (or on the specified environment).\n4. Use the pre-configured endpoints in Postman to test the API.\n\nThe collection includes:\n- **Authentication Endpoints**: Register, login, and obtain a JWT token.\n- **User Endpoints**: Get all users, update user details, and delete users.\n- **Error Handling**: Examples of responses for invalid or expired tokens.\n\nBy using the Postman collection, you can quickly test and interact with the API, making development and debugging more efficient.\n\n\n\n## Middleware\n\n### isAuthenticated\n\nThis middleware ensures that the user is authenticated by checking the JWT token in the cookies. If valid, it attaches the user identity to the `req` object.\n\n### isOwner\n\nThis middleware ensures that the user is trying to update or delete their own data. It compares the logged-in user's ID to the ID in the route parameters.\n\n\n## Error Handling\n\nThe API returns appropriate HTTP status codes and JSON error messages in case of failure:\n\n- **400**: Bad Request (e.g., invalid input)\n- **401**: Unauthorized (e.g., invalid token)\n- **403**: Forbidden (e.g., unauthorized access)\n- **404**: Not Found (e.g., missing token)\n- **500**: Internal Server Error\n\n## Modules Used\n\n### 1. `dotenv`\n- **Functionality**: Loads environment variables from a `.env` file into `process.env`, allowing you to securely manage sensitive data like API keys and database credentials.\n  \n### 2. `express`\n- **Functionality**: Web framework for building the REST API. It handles HTTP requests, routes, middleware, and responses.\n\n### 3. `http`\n- **Functionality**: Provides Node.js's built-in HTTP server functionality, used to create and manage the server for the application.\n\n### 4. `body-parser`\n- **Functionality**: Middleware used to parse incoming request bodies in JSON format. This is necessary for handling POST requests with JSON data.\n\n### 5. `cookie-parser`\n- **Functionality**: Middleware for parsing cookies attached to the request. It is used to retrieve the JWT token from the cookies in order to authenticate requests.\n\n### 6. `compression`\n- **Functionality**: Middleware for gzip compression, reducing the size of the response body, improving API performance by minimizing the data transferred over the network.\n\n### 7. `cors`\n- **Functionality**: Cross-Origin Resource Sharing (CORS) middleware, allowing or restricting resources to be requested from another domain. It helps prevent security risks when making cross-origin requests.\n\n### 8. `mongoose`\n- **Functionality**: ODM (Object Data Modeling) library for MongoDB, used to define schemas and interact with the MongoDB database. It simplifies database operations and queries.\n\n### 9. `morgan`\n- **Functionality**: HTTP request logger middleware for logging requests in the console. It helps monitor and debug the API by providing a log of incoming requests.\n\n### 10. `bcrypt`\n- **Functionality**: A library for hashing and comparing passwords securely. It is used to hash passwords before storing them in the database and to compare plain-text passwords during login.\n\n### 11. `crypto`\n- **Functionality**: Built-in Node.js module used for generating secure random values, such as random strings for session tokens.\n\n### 12. `jsonwebtoken`\n- **Functionality**: Used for creating and verifying JSON Web Tokens (JWT). It enables authentication by issuing a JWT upon login and validating the token for protected routes.\n\n### 13. `lodash`\n- **Functionality**: A utility library providing helper functions for common tasks like deep object merging, getting nested values, and performing operations on collections.\n\n### 14. `express-async-handler`\n- **Functionality**: Simplifies error handling in asynchronous Express routes by wrapping functions in a try/catch block, automatically passing errors to the next middleware.\n\n---\n\nEach of these modules contributes to the structure and functionality of your API, making it easier to implement secure authentication, database interactions, and efficient API responses.\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fseifsheikhelarab%2Fts-rest-api","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fseifsheikhelarab%2Fts-rest-api","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fseifsheikhelarab%2Fts-rest-api/lists"}