Coder Social home page Coder Social logo

davellanedam / node-express-mongodb-jwt-rest-api-skeleton Goto Github PK

View Code? Open in Web Editor NEW
884.0 47.0 285.0 1.94 MB

This is a basic API REST skeleton written on JavaScript using async/await. Great for building a starter web API for your front-end (Android, iOS, Vue, react, angular, or anything that can consume an API). Demo of frontend in VueJS here: https://github.com/davellanedam/vue-skeleton-mvp

License: MIT License

JavaScript 99.20% HTML 0.48% Shell 0.32%
javascript api node express mongodb jwt postman jwt-authentication token eslint

node-express-mongodb-jwt-rest-api-skeleton's People

Contributors

antibioticvz avatar ariadi avatar ciriak avatar davellanedam avatar depfu[bot] avatar markim avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-express-mongodb-jwt-rest-api-skeleton's Issues

How to change Password via API

Hey,

I wanted to ask how to change the password of a user. I tried adding the password field in the form data using postman but it doesn't update. Is there any other way?

Thanks

Duplicate user creation flow

There are two API endpoints for user creation:

  • POST /register (doesn't require auth) [auth.register]
  • POST /users (requires Admin level auth) [user.createItem]

The only difference is that POST /users allows predefinition of the 'role' field.
From what I could understand, this solves a very niche problem of giving Admin higher authority to create accounts (by allowing one additional field). Is this all there is to this, or am I missing some important usage here? Was this the intended behaviour and difference between the two?

MognoAltas issue ?

Doubt. Since a few months ago I am a user of your repository and I have several projects in production using, in 2 of these projects I have had the same problem. Which I don't know if it's something in the code or more in the server configuration. As I mentioned it is just a query to know if the same thing has happened to someone else. The problem is that I have a connection with MongoAtlas and suddenly the connection number goes up to the limit. Attached are screenshots of two projects

image

image

I understand that it can be assumed of an increase of users using the application, but the truth is that it is not the case the number of users is relatively equal always

Thank you !

Email Links Not Working

@davellanedam
I am registering a new user and an email has been sent, however, the verification link emailed is in the format [FRONTEND_URL]/verify/[VERIFICATION] while the verify method called by the endpoint upon clicking the link is looking for an id in the POST request.
This yields the error: {"errors":{"msg":"URL_NOT_FOUND"}}

Unit tests do not reveal this issue as the generated verification code is returned in development mode but not in production.

I believe the same applies to the Reset Password email. Please take a look.

refresh token implementation

User has to relogin everytime the jwt token expires and that is a problem

so I believe implementing refresh token would be great

Mailgun fails for hosting in EU regions

Mailgun will fail when the app is hosted on a european server (no explicit error) due to Mailgun configuration.

To reproduce:

  • install/run the app from an EU location/server
  • try to trigger email sending (ie: register)
  • vague error in console

PS: my solution for hosting the app in the EU region:
Edit sendEmail.js like this:

  const auth = {
    auth: {
      // eslint-disable-next-line camelcase
      api_key: process.env.EMAIL_SMTP_API_MAILGUN,
      domain: process.env.EMAIL_SMTP_DOMAIN_MAILGUN
    },
    host: 'api.eu.mailgun.net'
  }

Related issue:
mailgun/mailgun-php#471

Migrating passwords from another system

Firstly, thank you for this awesome project!!

I am trying to find a way to migrate users & passwords from a previous fullstack system that is built using node-express-mongoose-bcrypt. Your structure is far superior, and it would save me A LOT of time to mgirate.

Steps I followed:

  1. Change SALT_ROUNDS to 10, to match the old system
  2. Registered for a new user with this project
  3. Copied the password hash from the OLD mongo User collection
  4. Pasted it (using a mongo visualization tool) to this project's User collection in the password field.

When I try /login via Postman, the system crashes with this error:

TypeError: this.buildErrObject is not a function
    at user.comparePassword (/Users/w/Github/wfs/app/middleware/auth.js:16:23)
    at bcrypt.compare (/Users/w/Github/wfs/app/models/user.js:115:11)
    at /Users/w/Github/wfs/node_modules/bcrypt-nodejs/bCrypt.js:689:3
    at process._tickCallback (internal/process/next_tick.js:61:11)

Can you please weigh in on this error? Otherwise, can you please suggest the best way to migrate passwords?

Many thanks!
W

Emails with points

Hello Daniel, I've tried your code seems great, but I realized a small error, when the electronic mail that registers the user has points does not place them. Example:

[email protected]

in records records

[email protected]

completely removes any point that has the address.

Add role validation to USer creator

When creating a user, if you don't use an expected role from the user model enum then it crashes out with:

(node:8996) [DEP0106] DeprecationWarning: crypto.createDecipher is deprecated.
warning.js:27
TypeError: Cannot read property 'toObject' of undefined
at /Users/rob/Documents/Projects/oped/oped/app/controllers/users.js:42:43
at /Users/rob/Documents/Projects/oped/oped/node_modules/mongoose/lib/model.js:4732:16

To solve, add:

.isIn(['admin', 'user','superuser'])
.withMessage('USER_NOT_IN_KNOWN_ROLE'),

to the user validation in users.validate.js.

Thanks,

Rob

Feature: Code coverage

Hey, I just found that your project currently is not use any coverage tool, I suggest adding nyc.

No length verification on password when updating profile

When updating profile with PATCH /profile if you change password, there's no check on length. So if the user change password for a 3 chars word, no error is returned and then when trying to login, the verification on login works and it doesn't allows you to enter a 3 chars word as password.

More error message standardization

There are some error messages to standardize as words and dashes:

app/models/userAccess.js:

     type: String,
       validate: {
         validator: validator.isEmail,
-        message: 'Not a valid email address'
+        message: 'EMAIL_IS_NOT_VALID'
       },
       lowercase: true,
       required: true

app/models/users.js:

       type: String,
       validate: {
         validator: validator.isEmail,
-        message: 'Not a valid email address'
+        message: 'EMAIL_IS_NOT_VALID'
       },
       lowercase: true,
       unique: true,

app/models/forgotPassword.js:

       type: String,
       validate: {
         validator: validator.isEmail,
-        message: 'Not a valid email address'
+        message: 'EMAIL_IS_NOT_VALID'
       },
       lowercase: true,
       required: true

Add Logout Feature to User with Code

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like
A clear and concise description of what you want to happen.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

Auto-generated "model" and "controller"

Is your feature request related to a problem? Please describe.
It's not a problem. I just though about an idéa for the repo, which could improve the skeleton even more.

Describe the solution you'd like
Most of the people using your skeleton, will (mostly) start by replacing "City/Cities", or clone it manually, to create a new model and controller for "Vegetabels", or... anything else.

A solution to create a new model including controller for new item(s), would be great to see.

I'm not sure if there's 3rd-party tools, which could be integrated, to do that kind of magic?

Simple example:
"Vegetabels" are needed in the new project, and therefore I'll run through the structure, and secure that every model and controller are cloned, renamed and alligned, so it's now "Vegetabels", instead of "City/Cities".

Hereafter, I need to do the same thing in the Vue Front-End, to secure the proper handling.

If it should be done with a simple command, the workflow will be way faster, for adding the needed data-structure/handlers.

Additional context
I think it will require long time, to do a thing like this. But now I've suggested it. If there's a good way to do it today, maybe by using 3rd-party libs, that's awesome! I'm just not sure, where to start. And oh, if there is any, maybe it could be added to the documentation, too.

Thanks for awesome skeletons, for both frontend and backend.

app crashed - waiting for file changes before starting

[nodemon] 1.18.6
[nodemon] to restart at any time, enter rs
[nodemon] watching: .
[nodemon] starting node server.js
events.js:183
throw er; // Unhandled 'error' event
^

Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1191:14)
[nodemon] app crashed - waiting for file changes before starting...

Install nodemon in devDependencies

Hello Daniel, I'd suggest to install nodemon as a local dev Dependency, and run "npm run dev" without the need of install nodemon globally.

A way to simplify internationalization?

Very inspiring project. Thanks for posting it!

I had an idea, which may make internationalization more concise:

Right now, every place where there is internationalized text, you must include $t() around it - but this may not be necessary.

Given that Vue is a framework that automatically re-renders in response to changes in state, what if you used an approach like in this blog posting?

https://ourcodeworld.com/articles/read/395/getting-started-with-internationalization-i18n-in-react

The idea is to set the language by changing the required file path for the internationalized strings, and have a state variable depend on this change, such that components automatically update.

Its just an idea; see what you think.

Thanks again for posting this repo!

event error

$ npm run dev

[email protected] dev D:\Downloads__projects\N
odeJs\Angular\node-express-mongodb-jwt-rest-api-skeleton
SET NODE_ENV=development & nodemon server.js

[nodemon] 1.18.9
[nodemon] to restart at any time, enter rs
[nodemon] watching: .
[nodemon] starting node server.js
events.js:167
throw er; // Unhandled 'error' event
^

Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.
1:6379
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1113:14)
Emitted 'error' event at:
at RedisClient.on_error (D:\Downloads__projects\NodeJs\Angular\node-express
-mongodb-jwt-rest-api-skeleton\node_modules\redis\index.js:401:14)
at Socket. (D:\Downloads__projects\NodeJs\Angular\node-express-m
ongodb-jwt-rest-api-skeleton\node_modules\redis\index.js:279:14)
at Socket.emit (events.js:182:13)
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
[nodemon] app crashed - waiting for file changes before starting...

Confirmation emails in development

Hi Daniel, for testing purposes I modified the base controller to also send emails in development, so I can test the mailing system when developing. Just in case you think the change could be interesting to implement, here are my modifications:

app/controllers/base.js:

118 +    this.sendEmail(data, messageSent =>
119 +        messageSent
120 +          ? console.log(`Email SENT to: ${user.email}`)
121 +          : console.log(`Email FAILED to: ${user.email}`)
122 +    )

141 -      messageSent
142 -        ? console.log(`Email SENT to: ${user.email}`)
143 -        : console.log(`Email FAILED to: ${user.email}`)
146 +        messageSent
147 +            ? console.log(`Email SENT to: ${user.email}`)
148 +            : console.log(`Email FAILED to: ${user.email}`)
149     )
150    } else if (process.env.NODE_ENV === 'development') {
151      console.log(email)
152 +    this.sendEmail(data, messageSent =>
153 +        messageSent
154 +            ? console.log(`Email SENT to: ${user.email}`)
155 +            : console.log(`Email FAILED to: ${user.email}`)
156 +      )

Util for accessing userId from token

When business logic requires a userId to do something such as create a new City, the userId should be pulled from the encrypted JWT and therefore the engineer needs easy access to that ID.

Update to Vue 3

Is your feature request related to a problem? Please describe.
There currently is no problem

Describe the solution you'd like
Vue has updated to major version 3. This will bring performance improvements and keep the project fresh.

Describe alternatives you've considered
We could remain at version 2, but that may not work long term

Additional context
Here's the release news for version 3 of vue:
https://news.vuejs.org/issues/186
Here's a basic guide for update from version 2 to 3:
https://dev.to/blacksonic/the-vue-3-upgrade-guide-4dc4

Flexible Route Authorization

Is your feature request related to a problem? Please describe.
Sometimes I find myself calling an endpoint to perform an action only to find out that I do not have the necessary permissions to perform the action. Here is the example:

  • As a non-admin user, I would like to delete my own account. However, the DELETE /users/:id endpoint is restricted to the admin role.

Describe the solution you'd like
Because the role auth is handled in the route component, I would like to see some way for the API request to go ahead if the requested resource is regarding the user him/herself but not another user.
The example here may be that user 1 is an admin and therefore able to delete all users. User 2 may be a standard user and can delete the account if the returned resource is the user's own data but not someone else's (I hope that makes sense).

Describe alternatives you've considered
N/A

npm test fails on Windows 10

The 'npm test' command is failing on Windows 10 displaying the following errors:

npm test
'NODE_ENV' is not recognized as an internal or external command, operable program or batch file.
npm ERR! Test failed.  See above for more details.

Steps to reproduce the behavior on Windows 10:

git clone https://github.com/davellanedam/node-express-mongodb-jwt-rest-api-skeleton.git
cd node-express-mongodb-jwt-rest-api-skeleton
cp .env.example .env
npm test

PS: I fixed the error by editing package.json like this:

    "test:unit": "cross-env NODE_ENV=test jest --coverage",
    "test:e2e": "cross-env NODE_ENV=test npm run fresh && npm run mocha",

Nested array of subdocuments

Hello,

If I have an array of nested documents in my model, how would you go about implementing the controller and its validation? And how would you pass the data to Postman?

Here is what my model looks like:

const LeadSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true
    },
.
.
.
contacts: [
      {
        firstName: {
          type: String,
        },
        lastName: {
          type: String,
        },
        title: {
          type: String,
        }
        }
      }
    ]
.
.
.

Thank you very much!

Filter on objectid

I want to be able to search for all cities I created (for example).

If I add a 'userid' field to the cities model then I want to be able to

cities?filter=5aa1c2c35ef7a4e97b5e995b&fields=userid&limit=2&page=1

That way, I can utilise the pagination pattern built into the API.

I can add in
query['userId'] = new ObjectId(req.user.id)
to the controller but this feels like a workaround to the pattern.

why Auto add OPTIONS request to Server

Describe the bug
auto add OPTIONS request to Server

To Reproduce
Steps to reproduce the behavior:

  1. Press F12 on FireFox -> Network->XHR
  2. Go to Login by Admin
  3. Click on Delete,Add,Update
  4. See error

Screenshots
.
Screenshot from 2019-10-09 20-36-28

  • OS: [Ubuntu]

Best way to check logged in user from another service?

Thanks for maintaining what looks like a great authentication api. I'm trying to setup a user service that my other api's can pass a JWT to to check if a user is authenticated. As this package uses a blocklist am I right in thinking that I need to call this central service as opposed to decrypting the JWT to get the user ID?

Would it be a case of adding a new route like the refresh token route, something like this?
router.get( '/whoami', requireAuth, roleAuthorization(['user', 'admin']), trimRequest.all )

Password not hashed when updating in profile

Describe the bug
When I try to change password, the patch method on profile works, but saves the password without hashing it.

To Reproduce
Steps to reproduce the behavior:
Call http://localhost:5000/profile with
{
"password": "newpassword"
}
as body.

The result is the profile object and when you check the Mongo db, you see the password field un-hashed.

Correct syntax for Redis cache

Hello,
Thank you for this wonderful API skeleton, it helps a lot.

Trying to enable Redis cache, I got this error:

Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379

Changing connection syntax to this:

    engine: require('expeditious-engine-redis')({
      redis: {
        host: process.env.REDIS_HOST,
        port: process.env.REDIS_PORT
      }
    })

fixed the error for me.
Thank you.

Error in the comparison of the password in the case of being different

hi dave! how much the route / login is executed, in the case that the password is different, an error is stored in the update of the loginAttempts field of the user model.

Cast to Number failed for value "NaN" at path loginAttempts

checking the model is selected: false and should be true.

    loginAttempts: {
      type: Number,
      default: 0,
      select: false
    },

    loginAttempts: {
      type: Number,
      default: 0,
      select: true
    },

PassportJS based Social auth feature

Email signup and login is getting outdated lately and people prefer oAuth based logins from their existing logins. Add passport strategies for Facebook, Google, Twitter, Github.

mysql integration

HI

Thanks for the project

is there any easy way to convert this to my sql

Thanks

Validation results are doubled

Validation results are doubled when calling API with zero parameters.

On a post to /cities with nothing added other than bearer token for example, the following occurs:

{
    "errors": {
        "msg": [
            {
                "location": "body",
                "param": "name",
                "msg": "MISSING"
            },
            {
                "location": "body",
                "param": "name",
                "msg": "IS_EMPTY"
            }
        ]
    }
}

Filter on Sub Documents

how to filter data in subdocument, I have data like

"tournament": {
                "_id": "61b856a44509680799f619b6",
                "name": "Turnamen Amatir",
                "organizer": "Club Golf Indonesia",
                "venue": "Bukit Darmo Golf",
                "date": "2022-02-10T08:04:42.558Z",
                "tournamentPicture": "tournamentPicture-1640157632545.png"
            },
            "user": {
                "_id": "5aa1c2c35ef7a4e97b5e995a",
                "name": "Super Administrator",
                "city": "Bucaramanga",
                "country": "Colombia"
            },
            "pointTotal": 1

I want to filter tournament name, I tried by writing param fields=tournament.name&filter=Turnamen Amatir but always fail

Not standardized response on error

When fetching data from the backend you got a response object. When there are errors the object is called 'errors' and if the errors are from validation, you get an array with the location, param, value and msg.

The problem is with POST /register, when you send an incorrect email like "asdasd@asdas" you don't get the validation error object, just a plain error object:

Object
errors: msg: "User validation failed: email: EMAIL_IS_NOT_VALID"
proto: Objec
t__proto__: Object

Instead of:

Object
errors:
msg: Array(1)
0: {location: "body", param: "email", value: "asdasd@asdas", msg: "EMAIL_IS_NOT_VALID"}
length: 1
proto: Array(0)
proto: Object
proto: Object

On the other hand, if you send an invalid email in POST /login you get the right validation error.

It's possible to standardize all errors to just get WHATEVER_WHATEVER (like IS_EMPTY)?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.