Authentication is now simplified in node js!

Authentication is now simplified in node js!

A quick introduction to authenticatejs

ยท

5 min read

Every kind of website, be it an e-commerce or a blog, requires an authentication system. When making such an authentication system, however, one must work with web tokens, cookies, sessions, hashes, salts and much more. To simplify this problem, I created authenticatejs. Authenticatejs is the perfect Node.js package that will allow you to authenticate and authorize your user with easy-to-call functions. The best part? You don't need to deal with any of the problems of a conventional authentication system!

Installation

Let's install authenticatejs first:

npm install authenticatejs

Since authenticatejs works with express and mongoose, let's install these packages as well:

npm install express mongoose

Importing modules

To begin, we must first import all of our packages:

const express = require("express");
const mongoose = require("mongoose");
const auth = require("authenticatejs");

Configuring the database

The next step is to make a mongoose model that the package will use to authenticate and create new users:

mongoose.connect("mongodb://localhost:27017/authDB", {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

const userSchema = new mongoose.Schema({
    name: String,
    email: String,
    password: String
})

const User = mongoose.model("User", userSchema);

Setting up the server

Now we will set up an express server and call the initialize function in authenticatejs. The express app must be passed as a parameter for this function:

const app = express();
app.use(express.json());
auth.initialize(app);

app.post("/login", (req, res) => {

})

app.post("/register", (req, res) => {

})

app.listen(3000, () => console.log("Server running at port 3000"));

Registering a new user

In the register route, we can call the register function:

const app = express();
app.use(express.json());
auth.initialize(app);

app.post("/login", (req, res) => {

})

app.post("/register", async (req, res) => {
    const register = await auth.register(User, req.body.email, req.body.password, "email", "password", [["name", req.body.name]]);
    if (register.success){
       res.json({msg: "Success"});
    } else{
       res.json({msg: register.msg});
    }
})

app.listen(3000, () => console.log("Server running at port 3000"));

The first parameter we pass is the User model.

The next two are the input values you received from the form as the email and the password.

The final two parameters are the field names of the email and password as defined in the user schema.

Finally, the last parameter contains a list of pairs of values - the first list element being the field name and the second being the corresponding input. The last parameter basically provides any extra values you want authenticatejs to store when registering a new user.

Finally, we can check if any errors occurred. If so, we can even send the type of error to the frontend.

That is it ! We have successfully registered a new user ! Also, the passwords are hashed and stored in the database.

Logging our user

Now let's complete our login route:

const app = express();
app.use(express.json());
auth.initialize(app);

app.post("/login", async (req, res) => {
    const login = await auth.login(res, User, "secret", req.body.email, req.body.password, "email", "password");
    if (login.success){
        res.json({msg: "Success!"});
    } else{
        const errorType = login.msg;
        res.json({msg: errorType});
    }
})

app.post("/register", async (req, res) => {
    const register = await auth.register(User, req.body.email, req.body.password, "email", "password", [["name", req.body.name]]);
    if (register.success){
       res.json({msg: "Success"});
    } else{
       res.json({msg: register.msg});
    }
})

app.listen(3000, () => console.log("Server running at port 3000"));

In the login function, we must pass a few more parameters.

Firstly, the response we receive from express in a callback must be sent.

And then, we must also provide a secret that is used to sign json web tokens. Make sure it is stored as an environment variable for security purposes.

Authentication

If we have a certain page that must be seen by only users that are logged in, we can use authenticatejs for that as well !

app.get("/home", (req, res) => {
    const isLoggedIn = auth.isLoggedIn(req, "secret");
    if (isLoggedIn){
        res.send("Hello user!");
    } else{
        res.send("Please login first");
    }
})

For the isLoggedIn function, we must pass the request received from express callback and the secret we used for the login function as well.

Getting user details

We can customize a certain page according to the user details as well. This is crucial for all types of websites and can now be achieved with just one line of code:

app.get("/home", (req, res) => {
    const isLoggedIn = auth.isLoggedIn(req, "secret");
    if (isLoggedIn){
        const email = auth.getUsername(req, "email", "secret");
        User.findOne({email: email}, (err, userDetails) => {
            const name = userDetails.name;
            res.send(`Hello ${name} !`);
        })
    } else{
        res.send("Please login first");
    }
})

For the getUsername function, we must pass the request from express callback, the field name of our email input in the mongoose Schema and the secret.

Logout

Finally, a user can logout using the logout function:

app.post("/logout", (req, res) => {
    auth.logout(res);
});

All the code

// Importing modules

const express = require("express");
const mongoose = require("mongoose");
const auth = require("authenticatejs");

// Configuring database

mongoose.connect("mongodb://localhost:27017/authDB", {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

const userSchema = new mongoose.Schema({
    name: String,
    email: String,
    password: String
})

const User = mongoose.model("User", userSchema);

// Routes

const app = express();
app.use(express.json());

auth.initialize(app);

app.get("/home", (req, res) => {
    const isLoggedIn = auth.isLoggedIn(req, "secret");
    if (isLoggedIn){
        const email = auth.getUsername(req, "email", "secret");
        User.findOne({email: email}, (err, userDetails) => {
            const name = userDetails.name;
            res.send(`Hello ${name} !`);
        })
    } else{
        res.send("Please login first");
    }
})

app.post("/login", async (req, res) => {
    const login = await auth.login(res, User, "secret", req.body.email, req.body.password, "email", "password");
    if (login.success){
        res.json({msg: "Success!"});
    } else{
        const errorType = login.msg;
        res.json({msg: errorType});
    }
})

app.post("/register", async (req, res) => {
    const register = await auth.register(User, req.body.email, req.body.password, "email", "password", [["name", req.body.name]]);
    if (register.success){
       res.json({msg: "Success"});
    } else{
       res.json({msg: register.msg});
    }
})

app.post("/logout", (req, res) => {
    auth.logout(res);
});

app.listen(3000, () => console.log("Server running at port 3000"));

Conclusion

And with that, you can easily make your authentication system with the help of authenticatejs. But wait ! We are not over yet ! In the coming time, authenticatejs will bring new features such as google sign in, facebook sign in and much more ! Stay tuned and happy coding.

ย