Home > Back-end >  How to using regex in express-unless?
How to using regex in express-unless?

Time:02-17

I am trying to make a auth middleware in express.js and making some api's open with the help of express-unless package, in them there i added a dynamic path for ignore auth for all the urls which have 7 digit alphanumeric character. so, i added a regex [0-9a-zA-Z]{7} but it is not working.

below is the javascript code i wrote

const unprotected = ["api/token", "/", "/api/login",   /\/[0-9A-Za-z]{7}/];

module.exports.tokenAuth = jwt({...}).unless({ path: unprotected });

an edited code for ref:

require("dotenv").config();

const express = require("express");
const app = express();
const path = require("path");
const bodyParser = require("body-parser");
const morganMiddleware = require("./middlewares/morganMiddleware");
const jwt = require("express-jwt");

// setting up middleware
app.use(express.static(path.join(__dirname, "public")));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(morganMiddleware);


const unprotected = [ "/api/login", /\/[0-9A-Za-z]{7}/];
app.use(jwt({ secret: 'shhhhhhared-secret', algorithms: ['HS256']}).unless({ path: unprotected }));


app.get("/:id([a-zA-Z0-9]{7})", (req, res) => {
    res.json({
        message: "unprotected",
        id: req.params.id
    })
})

app.post("/api/urlShortener", (req, res) => {
    console.log(req.user)  //undefined
    res.json({
        message: "should be protected, but still works without token",
        user: req.user
    })
})

let PORT = process.env.PORT || 3333;
app.listen(PORT, () => {
  console.log("Application listening on port            
  • Related