Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/jmagan/cardano-express-web3-skeleton
Backend skeleton for Cardano Web3 hybrid dApps. This backend uses Express as server and MongoDB as user database. It provides a basic API REST for authentication and authorization using CIP-0008 signing spec and CIP-0030 Cardano dApp-wallet web bridge.
https://github.com/jmagan/cardano-express-web3-skeleton
cardano dapp express jwt-authentication mongodb web3
Last synced: 3 months ago
JSON representation
Backend skeleton for Cardano Web3 hybrid dApps. This backend uses Express as server and MongoDB as user database. It provides a basic API REST for authentication and authorization using CIP-0008 signing spec and CIP-0030 Cardano dApp-wallet web bridge.
- Host: GitHub
- URL: https://github.com/jmagan/cardano-express-web3-skeleton
- Owner: jmagan
- License: mit
- Created: 2022-11-11T19:05:27.000Z (about 2 years ago)
- Default Branch: master
- Last Pushed: 2023-06-08T11:44:17.000Z (over 1 year ago)
- Last Synced: 2024-10-19T05:15:34.538Z (3 months ago)
- Topics: cardano, dapp, express, jwt-authentication, mongodb, web3
- Language: JavaScript
- Homepage:
- Size: 1.74 MB
- Stars: 9
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
- Code of conduct: CODE_OF_CONDUCT.md
Awesome Lists containing this project
README
# Node.js express.js MongoDB JWT REST API - Basic Project Skeleton
[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](https://github.com/jmagan/cardano-express-web3-skeleton/blob/master/LICENSE)
## Getting started
This is a basic API REST skeleton for Cardano dApp authentication and authorization written on JavaScript using async/await. This backend utilizes the standard [CIP-0008 signing spec](https://github.com/cardano-foundation/CIPs/blob/master/CIP-0008/README.md). The project has all necessary endpoints for athentication, authorization and user management. The authentication token is generated as a JWT web token, therefore it can be shared easily by other services.
The authentication process is driven by signed payloads with the [CIP-0030 Cardano dApp-wallet web bridge](https://github.com/cardano-foundation/CIPs/tree/master/CIP-0030). There are three actions that require the user's wallet signature, *Signup*, *Login* and *Reset*. Once the payload with the desired action is signed with the correct private key, a JWT web token is issued and takes control of the session.
## Frontend
This repository is self-contained and you can use ir and test it through the test suite and Postman. You can read more about the Postman examples in the usage section below. This is a good method for developing and debugging the code. But a front end is required to better understand how it works.
I've created another template for creating your web3 applications with ReactJS. You can clone it from the next repository [jmagan/cardano-react-web3-skeleton](https://github.com/jmagan/cardano-react-web3-skeleton).
## Features
* Cardano [CIP-0008 signing spec](https://github.com/cardano-foundation/CIPs/blob/master/CIP-0008/README.md) for the login and registration process.
* Multiple environment ready (development, production)
* Custom email/cardano address user system with basic security and blocking for preventing brute force attacks.
* Compressed responses.
* Secured HTTP headers.
* CORS ready.
* Cache ready (Redis).
* HTTP request logger in development mode.
* i18n ready (for sending emails in multiple languages).
* User roles.
* Pagination ready.
* User profile.
* Users list for admin area.
* Cities model and controller example.
* Login access log with IP, browser and country location (for country it looks for the header `cf-ipcountry` that CloudFlare creates when protecting your website).
* API autogenerated documentation by Postman.
* API collection example for Postman.
* Testing with mocha/chai for API endpoints.
* NPM scripts for cleaning and seeding the MongoDB database.
* NPM script for keeping good source code formatting using prettier and ESLint.
* Use of ESLint for good coding practices.
* Mailer example with Nodemailer and Mailgun.
* HTTPOnly refresh token cookie.
* Ability to refresh token.
* JWT Tokens, make requests with a token after login with `Authorization` header with value `Bearer yourToken` where `yourToken` is the **signed and encrypted token** given in the response from the login process.## Requirements
* Node.js **10+**
* MongoDB **3.6+**
* Redis **5.0+**## How to install
### Using Git (recommended)
1. Clone the project from github. Change "myproject" to your project name.
```bash
git clone https://github.com/jmagan/cardano-express-web3-skeleton.git ./myproject
```### Using manual download ZIP
1. Download repository
2. Uncompress to your desired directory### Install npm dependencies after installing (Git or manual download)
```bash
cd myproject
npm install
npm update
```### Setting up environments (development or production)
1. In the root this repository you will find a file named `.env.example`
2. Create a new file by copying and pasting the file and then renaming it to just `.env`
3. The file `.env` is already ignored, so you never commit your credentials.
4. Change the values of the file to your environment (development or production)
5. Upload the `.env` to your environment server(development or production)
6. If you use the postman collection to try the endpoints, change value of the variable `server` on your environment to the url of your server, for development mode use**IMPORTANT:** By default token expires in 3 days (4320 minutes set in .env.example). You can refresh token at endpoint GET /token. If everything itΒ΄s ok you will get a new token.
### Mailer
To ensure the deliverability of emails sent by this API, `Mailgun` is used for mailing users when they sign up, so if you want to use that feature go sign up at their website
If you want to try a different method itΒ΄s ok, I used for this API and they have different transport methods like: smtp.
### i18n
Language is automatically detected from `Accept-Language` header on the request. So either you send locale manually on the request or your browser will send its default, if `Accept-Language` header is not sent then it will use `en` locale as default.
## How to run
### Database cleaning and seeding samples
There are 3 available commands for this: `fresh`, `clean` and `seed`.
```bash
npm run command
```* `fresh` cleans and then seeds the database with dynamic data.
* `clean` cleans the database.
* `seed` seeds the database with dynamic data.### Running in development mode (lifting API server)
```bash
npm run dev
```You will know server is running by checking the output of the command `npm run dev`
```bash
****************************
* Starting Server
* Port: 3000
* NODE_ENV: development
* Database: MongoDB
* DB Connection: OK
****************************
```### Running tests
ItΒ΄s a good practice to do tests at your code, so a sample of how to do that in `mocha/chai` is also included in the `/test` directory
```bash
npm run test
```### Formatting code
Format your code with prettier by typing:
```bash
npm run format
```### Formatting markdown files
Format all your markdown files with remark by typing:
```bash
npm run remark
```### Linting code
Lint your code with ESLint by typing:
```bash
npm run lint
```## Usage
Once everything is set up to test API routes either use Postman or any other api testing application.
### Mocking Cardano signatures
In order to use some endpoints, we need to sign payloads according to CIP-0008 signing spec. For this purpose, the project has a cli util for creating the keys and signatures. This can simulate 255 unique wallets selecting a number between 0 and 254. The cli util starts with the following command:
```bash
$ node mockWalletSignatures.js
```In order to get the key and signature, we need to go through three steps.
1. First, select the payload for your endpoint. Each end point needs the corresponding action.
2. If the payload needs some additional info, the prompt will ask about them. In the case of the login payload, we will need to insert an email.
3. Select a number between 0 and 254 for selecting a unique wallet. Currently, the number 0 belongs to the admin's wallet and the number 1 to the simple user's wallet. These users are created in the database by the seed script. You can use them for testing purposes in Postman.In the next example, we can find how to create a login payload for the admin's account.
π€ Please, select the action for the payload (S: Signup, R: Reset, L: Login)
Action: L
π€ Creating login payload.
π€ Choose a number between 0 and 254. Each number represents a unique address and private key. For example in the sample data, the number 0 is the wallet for admin and the number 1 for the simple user.
Wallet number: 0
π€ Generating wallet address, key and signature.πͺ Address: stake1u89exkzjnh6898pjg632qv7tnqs6h073dhjg3qq9jp9tcsgq0wfzr
π Key: a201012158203b6a27bcceb6a42d62a3a8d02a6f0d73653215771de243a63ac048a18b59da29
π Signature: 845828a16761646472657373581de1cb9358529df4729c3246a2a033cb9821abbfd16de4888005904abc41a166686173686564f4583a7b22686f7374223a22484f5354222c22616374696f6e223a224c6f67696e222c22656d61696c223a2261646d696e4061646d696e2e636f6d227d5840f93faf1473ad7ff9cdcbc4e2acbb4c24e90329c2ee77b04a8fcc8a716e04df9ae4094fb86f1ff3a88c85e892bf166d1b03bcf5c98cb821be40c285d9fea3e804
The address, key and signature will be used calling the endpoints. This login endpoint call is currently implemented in the `postman-example.json`.
### Postman API example collection
You can import the example collection to Postman. To import, click the import button located and select `postman-example.json` located within the root directory.
Go to `manage environments` to create environments for development, production, etc. On each of the environments you create you will need to:
1. Create a new key `authToken` and within the `/login` request this value is automatically updated after a successfull login through a script located in the `tests` tab. Each time you make a request to the API it will send `Authorization` header with the `token` value in the request, you can check this on the headers of users or cities endpoints in the Postman example.
2. Create a second key `server` with the url of your server, for development mode use
This is a REST API, so it works using the following HTTP methods:
* GET (Read): Gets a list of items, or a single item
* POST (Create): Creates an item
* PATCH (Update): Updates an item
* DELETE: Deletes an item### Creating new models
If you need to add more models to the project just create a new file in `/app/models/` and it will be loaded dynamically.
### Creating new routes
If you need to add more routes to the project just create a new file in `/app/routes/` and it will be loaded dynamically.
### Creating new controllers
When you create a new controller, try to also create another folder with validations and helpers. Ex. `/countries`, `/countries/validators` and `/countries/helpers`. An example of this is included in the repository.
## Support
If you find it useful, please consider inviting me a coffee :)
[![DoItWithLovelace](https://app.doitwithlovelace.io/api/og/assets/donationButton)](https://app.doitwithlovelace.io/users/DoItWithLovelace)
## Bugs or improvements
You are welcome to report any bugs or improvements. Pull requests are always welcome.
## License
This project is open-sourced software licensed under the MIT License. See the LICENSE file for more information.