Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

User service backend #9

Merged
Merged
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
10 changes: 10 additions & 0 deletions backend/user-service/.env.sample
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
DB_CLOUD_URI=<CONNECTION_STRING>
PORT=3001

# Secret for creating JWT signature
JWT_SECRET=you-can-replace-this-with-your-own-secret

# admin default credentials
ADMIN_USERNAME=administrator
[email protected]
ADMIN_PASSWORD=Admin@123
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added backend/user-service/GuideAssets/Creation.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added backend/user-service/GuideAssets/Network.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added backend/user-service/GuideAssets/Security.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added backend/user-service/GuideAssets/Selection.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added backend/user-service/GuideAssets/Selection1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added backend/user-service/GuideAssets/Selection2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added backend/user-service/GuideAssets/Selection3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added backend/user-service/GuideAssets/Selection4.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added backend/user-service/GuideAssets/SidePane.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
60 changes: 60 additions & 0 deletions backend/user-service/MongoDBSetup.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Setting up MongoDB Instance for User Service

1. Visit the MongoDB Atlas Site [https://www.mongodb.com/atlas](https://www.mongodb.com/atlas) and click on "Try Free"

2. Sign Up/Sign In with your preferred method.

3. You will be greeted with welcome screens. Feel free to skip them till you reach the Dashboard page.

4. Create a Database Deployment by clicking on the green `+ Create` Button:

![alt text](./GuideAssets/Creation.png)

5. Make selections as followings:

- Select Shared Cluster
- Select `aws` as Provider

![alt text](./GuideAssets/Selection1.png)

- Select `Singapore` for Region

![alt text](./GuideAssets/Selection2.png)

- Select `M0 Sandbox` Cluster (Free Forever - No Card Required)

> Ensure to select M0 Sandbox, else you may be prompted to enter card details and may be charged!

![alt text](./GuideAssets/Selection3.png)

- Leave `Additional Settings` as it is

- Provide a suitable name to the Cluster

![alt text](./GuideAssets/Selection4.png)

6. You will be prompted to set up Security for the database by providing `Username and Password`. Select that option and enter `Username` and `Password`. Please keep this safe as it will be used in User Service later on.

![alt text](./GuideAssets/Security.png)

7. Next, click on `Add my Current IP Address`. This will whiteliste your IP address and allow you to connect to the MongoDB Database.

![alt text](./GuideAssets/Network.png)

8. Click `Finish and Close` and the MongoDB Instance should be up and running.

## Whitelisting All IP's

1. Select `Network Access` from the left side pane on Dashboard.

![alt text](./GuideAssets/SidePane.png)

2. Click on the `Add IP Address` Button

![alt text](./GuideAssets/AddIPAddress.png)

3. Select the `ALLOW ACCESS FROM ANYWHERE` Button and Click `Confirm`

![alt text](./GuideAssets/IPWhitelisting.png)

Now, any IP Address can access this Database.
284 changes: 284 additions & 0 deletions backend/user-service/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,284 @@
# User Service Guide

## Setting-up

> :notebook: If you are familiar to MongoDB and wish to use a local instance, please feel free to do so. This guide utilizes MongoDB Cloud Services.

1. Set up a MongoDB Shared Cluster by following the steps in this [Guide](./MongoDBSetup.md).

2. After setting up, go to the Database Deployment Page. You would see a list of the Databases you have set up. Select `Connect` on the cluster you just created earlier on for User Service.

![alt text](./GuideAssets/ConnectCluster.png)

3. Select the `Drivers` option, as we have to link to a Node.js App (User Service).

![alt text](./GuideAssets/DriverSelection.png)

4. Select `Node.js` in the `Driver` pull-down menu, and copy the connection string.

Notice, you may see `<password>` in this connection string. We will be replacing this with the admin account password that we created earlier on when setting up the Shared Cluster.

![alt text](./GuideAssets/ConnectionString.png)

5. In the `user-service` directory, create a copy of the `.env.sample` file and name it `.env`.

6. Update the `DB_CLOUD_URI` of the `.env` file, and paste the string we copied earlier in step 4. Also remember to replace the `<password>` placeholder with the actual password.

## Running User Service

1. Open Command Line/Terminal and navigate into the `user-service` directory.

2. Run the command: `npm install`. This will install all the necessary dependencies.

3. If you are running the user service for the first time, run `npm run seed`, to seed the database with a default admin account. If you wish to change the default, please update the `.env` file. Alternatively, you can also edit your credentials and user profile after you have created the default account.

4. Run the command `npm start` to start the User Service in production mode, or use `npm run dev` for development mode, which includes features like automatic server restart when you make code changes.

5. Using applications like Postman, you can interact with the User Service on port 3001. If you wish to change this, please update the `.env` file.

## User Service API Guide

### Create User

- This endpoint allows adding a new user to the database (i.e., user registration).

- HTTP Method: `POST`

- Endpoint: http://localhost:3001/users

- Body

- Required: `username` (string), `email` (string), `password` (string)

```json
{
"username": "SampleUserName",
"email": "[email protected]",
"password": "SecurePassword"
}
```

- Responses:

| Response Code | Explanation |
| --------------------------- | ----------------------------------------------------- |
| 201 (Created) | User created successfully, created user data returned |
| 400 (Bad Request) | Missing fields |
| 409 (Conflict) | Duplicate username or email encountered |
| 500 (Internal Server Error) | Database or server error |

### Get User

- This endpoint allows retrieval of a single user's data from the database using the user's ID.

> :bulb: The user ID refers to the MongoDB Object ID, a unique identifier automatically generated by MongoDB for each document in a collection.

- HTTP Method: `GET`

- Endpoint: http://localhost:3001/users/{userId}

- Parameters

- Required: `userId` path parameter
- Example: `http://localhost:3001/users/60c72b2f9b1d4c3a2e5f8b4c`

- <a name="auth-header">Headers</a>

- Required: `Authorization: Bearer <JWT_ACCESS_TOKEN>`

- Explanation: This endpoint requires the client to include a JWT (JSON Web Token) in the HTTP request header for authentication and authorization. This token is generated during the authentication process (i.e., login) and contains information about the user's identity. The server verifies this token to ensure that the client is authorized to access the data.

- Auth Rules:

- Admin users: Can retrieve any user's data. The server verifies the user associated with the JWT token is an admin user and allows access to the requested user's data.
- Non-admin users: Can only retrieve their own data. The server checks if the user ID in the request URL matches the ID of the user associated with the JWT token. If it matches, the server returns the user's own data.

- Responses:

| Response Code | Explanation |
| --------------------------- | -------------------------------------------------------- |
| 200 (OK) | Success, user data returned |
| 401 (Unauthorized) | Access denied due to missing/invalid/expired JWT |
| 403 (Forbidden) | Access denied for non-admin users accessing others' data |
| 404 (Not Found) | User with the specified ID not found |
| 500 (Internal Server Error) | Database or server error |

### Get All Users

- This endpoint allows retrieval of all users' data from the database.
- HTTP Method: `GET`
- Endpoint: http://localhost:3001/users
- Headers

- Required: `Authorization: Bearer <JWT_ACCESS_TOKEN>`
- Auth Rules:

- Admin users: Can retrieve all users' data. The server verifies the user associated with the JWT token is an admin user and allows access to all users' data.
- Non-admin users: Not allowed access.

- Responses:

| Response Code | Explanation |
| --------------------------- | ------------------------------------------------ |
| 200 (OK) | Success, all user data returned |
| 401 (Unauthorized) | Access denied due to missing/invalid/expired JWT |
| 403 (Forbidden) | Access denied for non-admin users |
| 500 (Internal Server Error) | Database or server error |

### Update User

- This endpoint allows updating a user and their related data in the database using the user's ID.

- HTTP Method: `PATCH`

- Endpoint: http://localhost:3001/users/{userId}

- Parameters

- Required: `userId` path parameter

- Body

- At least one of the following fields is required: `username` (string), `email` (string), `password` (string)

```json
{
"username": "SampleUserName",
"email": "[email protected]",
"password": "SecurePassword"
}
```

- Headers

- Required: `Authorization: Bearer <JWT_ACCESS_TOKEN>`
- Auth Rules:

- Admin users: Can update any user's data. The server verifies the user associated with the JWT token is an admin user and allows the update of requested user's data.
- Non-admin users: Can only update their own data. The server checks if the user ID in the request URL matches the ID of the user associated with the JWT token. If it matches, the server updates the user's own data.

- Responses:

| Response Code | Explanation |
| --------------------------- | ------------------------------------------------------- |
| 200 (OK) | User updated successfully, updated user data returned |
| 400 (Bad Request) | Missing fields |
| 401 (Unauthorized) | Access denied due to missing/invalid/expired JWT |
| 403 (Forbidden) | Access denied for non-admin users updating others' data |
| 404 (Not Found) | User with the specified ID not found |
| 409 (Conflict) | Duplicate username or email encountered |
| 500 (Internal Server Error) | Database or server error |

### Update User Privilege

- This endpoint allows updating a user’s privilege, i.e., promoting or demoting them from admin status.

- HTTP Method: `PATCH`

- Endpoint: http://localhost:3001/users/{userId}

- Parameters

- Required: `userId` path parameter

- Body

- Required: `isAdmin` (boolean)

```json
{
"isAdmin": true
}
```

- Headers

- Required: `Authorization: Bearer <JWT_ACCESS_TOKEN>`
- Auth Rules:

- Admin users: Can update any user's privilege. The server verifies the user associated with the JWT token is an admin user and allows the privilege update.
- Non-admin users: Not allowed access.

> :bulb: You may need to manually assign admin status to the first user by directly editing the database document before using this endpoint.

- Responses:

| Response Code | Explanation |
| --------------------------- | --------------------------------------------------------------- |
| 200 (OK) | User privilege updated successfully, updated user data returned |
| 400 (Bad Request) | Missing fields |
| 401 (Unauthorized) | Access denied due to missing/invalid/expired JWT |
| 403 (Forbidden) | Access denied for non-admin users |
| 404 (Not Found) | User with the specified ID not found |
| 500 (Internal Server Error) | Database or server error |

### Delete User

- This endpoint allows deletion of a user and their related data from the database using the user's ID.
- HTTP Method: `DELETE`
- Endpoint: http://localhost:3001/users/{userId}
- Parameters

- Required: `userId` path parameter

- Headers

- Required: `Authorization: Bearer <JWT_ACCESS_TOKEN>`

- Auth Rules:

- Admin users: Can delete any user's data. The server verifies the user associated with the JWT token is an admin user and allows the deletion of requested user's data.

- Non-admin users: Can only delete their own data. The server checks if the user ID in the request URL matches the ID of the user associated with the JWT token. If it matches, the server deletes the user's own data.

- Responses:

| Response Code | Explanation |
| --------------------------- | ------------------------------------------------------- |
| 200 (OK) | User deleted successfully |
| 401 (Unauthorized) | Access denied due to missing/invalid/expired JWT |
| 403 (Forbidden) | Access denied for non-admin users deleting others' data |
| 404 (Not Found) | User with the specified ID not found |
| 500 (Internal Server Error) | Database or server error |

### Login

- This endpoint allows a user to authenticate with an email and password and returns a JWT access token. The token is valid for 1 day and can be used subsequently to access protected resources. For example usage, refer to the [Authorization header section in the Get User endpoint](#auth-header).
- HTTP Method: `POST`
- Endpoint: http://localhost:3001/auth/login
- Body

- Required: `email` (string), `password` (string)

```json
{
"email": "[email protected]",
"password": "SecurePassword"
}
```

- Responses:

| Response Code | Explanation |
| --------------------------- | -------------------------------------------------- |
| 200 (OK) | Login successful, JWT token and user data returned |
| 400 (Bad Request) | Missing fields |
| 401 (Unauthorized) | Incorrect email or password |
| 500 (Internal Server Error) | Database or server error |

### Verify Token

- This endpoint allows one to verify a JWT access token to authenticate and retrieve the user's data associated with the token.
- HTTP Method: `GET`
- Endpoint: http://localhost:3001/auth/verify-token
- Headers

- Required: `Authorization: Bearer <JWT_ACCESS_TOKEN>`

- Responses:

| Response Code | Explanation |
| --------------------------- | -------------------------------------------------- |
| 200 (OK) | Token verified, authenticated user's data returned |
| 401 (Unauthorized) | Missing/invalid/expired JWT |
| 500 (Internal Server Error) | Database or server error |
Loading