adamhalasz/diet

API middleware with token authentication except some routes

Closed this issue · 1 comments

Is this the right way to make a middleware for all routes with token authentication except /sign-in route?

const api = diet()

api.listen("http://api.example.sk")

const accountsSchema = new mongoose.Schema({
  firstName: String,
  lastName: String,
  email: String,
  password: String
})

const accounts = mongoose.model("accounts", accountsSchema)

api.header(($) => {
  let a = $.url.pathname

  if (a !== "/sign-in") {
    if ($.query.token) {
      jwt.verify($.query.token, secret, (error, decoded) => {
        if (error) {
          $.end("Token is not correct.")
        } else {
          $.return()
        }
      })
    } else {
      $.end("An unknown error occurred.")
    }
  } else {
    $.return()
  }
})

api.get("/sign-in", ($) => {
  let email = "A"
  let password = "B"

  accounts.findOne({
    email: email,
    password: crypto.createHash("sha256").update(password).digest("hex")
  }, (error, account) => {
    let response = {}

    if(account) {
      response = {
        token: jwt.sign(account, secret)
      }
    } else {
      response = {
        response: "The data do not match."
      }
    }

    $.json({response})
  })
})

Only this is the right way?

api.header(($) => {
  let a = $.url.pathname

  if (a !== "/sign-in" || a !== "/sign-up" || a !== "blabla") {

  }
}

hey @marekkobida

Both ways seems to be right. i can tell you want to make authorizations on your application, but depending on the behavior you seek to achieve, i would recommend creating a custom module for diet that handles authorization of this kind or extend another header to the application, there's no problem on adding multiple headers, diet will execute them sequentially.

Please note that issues are for tracking bugs and making requests for the project, for this kind of question you can ask for help on stackoverflow, you can also ask on Diet's gitter, or if you prefer you can e-mail to me