0

I'm trying to get my login api working inside azure function, but it keeps saying await is only valid in async function. This is an async function so I'm just super confused.

This line const user = await db.collection('users').findOne({ email: userLoggingIn.email })

is throwing the error.

const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");


var MongoClient = require('mongodb').MongoClient;



module.exports = async function (context, req) {


  MongoClient.connect(process.env.CosmosDBConnectionString, (err, client) => {


    let userLoggingIn = ({ email, password } = req.body);

    console.log("userLoggingIn");
    console.log(userLoggingIn.email);
    let send = response(client, context);

    if (err) send(500, err.message);


    console.log("DBNAME: " + process.env.dbName);
    let user;
    let db = client.db(process.env.dbName);


   const user = await db.collection('users').findOne({ email: userLoggingIn.email })



    console.log("USER");
    console.log(user);


  let userName= user.instagramName;
    if (!user) {

      send(401, { message: "Auth failed" });

    }

    const { username } = user;
    console.log("PASSWORD");
    console.log(context.req.password);
    console.log(user.password);
    const goodPassword = bcrypt.compareSync(context.req.password, user.password);

    if (!goodPassword) {
      return send(401, { message: "Auth failed" });

    }

    const token = jwt.sign(
      {
        email: user.email,
        userId: user._id,
        username: userName
      },
      "secret_this_should_be_longer",
      { expiresIn: "1h" }
    );

    context.res = { status: 200, token: token, expiresIn: 3600, userId: user._id, username: username};


  })
}




function response(client, context) {
  return function (status, body) {
    context.res = {
      status: status,
      body: body
    };

    client.close();
    context.done();
  };
}

1 Answer 1

1
MongoClient.connect(process.env.CosmosDBConnectionString, (err, client) => {

on this line, the annonymous callback function receiving err and client as parameter is the function that needs to be async

MongoClient.connect(process.env.CosmosDBConnectionString, async (err, client) => {
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.