W
W
webe2018-06-02 16:05:30
Node.js
webe, 2018-06-02 16:05:30

How to forward the data correctly?

Table in the database:
id,login,password,token
After successful authorization, we generate a new token and return it to the client
. Next, we again make a request to the get_links API, but with a token. We check this token through isAuthenticated, if the token is real, then we continue to work, if the token does not exist in the database, then we throw out the
error ERROR_AUTH_TOKEN in middleware isAuthenticated ? When I used sessions, everything was simple, but I don’t know how to do it without sessions. Tell me plz.

app.post("/api/v1/auth", async (req, res) => {
  const { email, password } = req.body;
  const user = await auth.loginUser(db, email, password);
  if (user) {
    const token  =  await auth.updateToken(db, user.id); 
    res.json({ message: "SECCESS", data: { token: token } });
  } else  {
    res.json({ message: "ERROR_AUTH", data: {}});
  }
});

function isAuthenticated(req, res, next) {
  const { token } = req.body;
  console.log('isAuthenticated token',token)
   const user =  auth.checkToken(); 
   // Проверем  есть ли пользователь с таким токеном, 
   // Если есть, то в user  сохраняем объект с пользователем.
   //  777,admin,admin,706669f29acdc5a14d2a2a1f24e45bd898db6898
  if (user) {
    return next();
  } else {
    res.json({ message: "ERROR_AUTH_TOKEN", data: {}});
  }
}


app.post("/api/v1/links/get_links", isAuthenticated, async (req, res) => {
 //777 - это ID пользователя
  const userLinks = await links.getUserLinksByID(db, 777);
  res.json({ message: "USER_LINKS", data: { userLinks } });
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladlen Hellsite, 2018-06-02
@webe

So?

function isAuthenticated(req, res, next) {
  const { token } = req.body;
  console.log('isAuthenticated token',token)
   const user =  auth.checkToken(); 
   // Проверем  есть ли пользователь с таким токеном, 
   // Если есть, то в user  сохраняем объект с пользователем.
   //  777,admin,admin,706669f29acdc5a14d2a2a1f24e45bd898db6898
  if (user) {
    req.user = user;
    return next();
  } else {
    res.json({ message: "ERROR_AUTH_TOKEN", data: {}});
  }
}

app.post("/api/v1/links/get_links", isAuthenticated, async (req, res) => {
 //777 - это ID пользователя
  const userLinks = await links.getUserLinksByID(db, req.user.id);
  res.json({ message: "USER_LINKS", data: { userLinks } });
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question