Firebase Auth电子邮件问题 - 部署

时间:2018-06-13 17:42:21

标签: javascript node.js firebase google-cloud-functions nodemailer

我从项目中克隆了Index.js的错误。它是Firebase项目,这应该使用Firebase功能(nodemailer)发送带有用于验证创建的帐户的令牌的验证电子邮件。我的代码位于顶部,错误如下:

const functions = require('firebase-functions');
const admin = require('firebase-admin');

const nodemailer = require('nodemailer');
var cors = require('cors');
const secureCompare = require('secure-compare');

// Configure the email transport using the default SMTP transport and a GMail account.
// For other types of transports such as Sendgrid see https://nodemailer.com/transports/
// TODO: Configure the `gmail.email` and `gmail.password` Google Cloud environment variables.
const gmailEmail = encodeURIComponent(functions.config().gmail.email);
const gmailPassword = encodeURIComponent(functions.config().gmail.password);

const mailTransport = nodemailer.createTransport(
  `smtps://${gmailEmail}:${gmailPassword}@smtp.gmail.com`);

const APP_NAME = 'The Ride Share';

//admin.initializeApp(functions.config().firebase);
// var firebaseConfig = functions.config().firebase;
// firebaseConfig.databaseAuthVariableOverride = {
//   uid: 'fbcfunction',
// };

admin.initializeApp();


function sendWelcomeEmail(email, displayName, token) {
  const mailOptions = {
    from: 'The Ride Share',
    to: email
  };

  // The user unsubscribed to the newsletter.
  mailOptions.subject = `Welcome to ${APP_NAME}!`;
  mailOptions.text = `Hey ${displayName}!, Welcome to ${APP_NAME}. Your token is ${token}, Please enter the token in the portal to verify the account.`;
  return mailTransport.sendMail(mailOptions).then(() => {
    console.log('New welcome email sent to:', email);
  });
}

exports.prepareVerificationMail = functions.database.ref('/users/{uid}/shellMailId')
  .onWrite((change,context)=>{
    console.log('event', change);
    console.log('Mail id is', change.after.val());
    if (change.after.val() != null) {
      return change.after.parent.once('value').then(function (snapshot) {
        console.log('snapval is the user id', snapshot.key);
        var userId = snapshot.key;
        //console.log('this is the userId', userId);
        return userId;
      }).then(function (userId) {
        console.log('this should be user id', userId);

        return admin.database().ref().child('userTokens').child(userId).child('token').once('value')
          .then(function (token) {
            console.log('this is the token', token);
            var displayName = change.after.val().toString();
            if (displayName.indexOf('@') > -1) {
              displayName = displayName.substring(0, displayName.indexOf('@'));
            }
            console.log('displayName', displayName);
            return sendWelcomeEmail(change.after.val(), displayName, token.val());
          }).catch(function (error) {
            console.log('error in reading the user token', error);
            return;
          });

      }).catch(function (error) {
        console.log('error in getting user key', error);
        return;
      });
    } else {
      return;
    }
  });

exports.setTheToken = functions.database.ref('/users/{uid}/personalEmail')
  .onWrite((change,context)=>{

    console.log('event data val', change.after.val());
    console.log(change);
    if (change.after.val() != null) {
      //
      return change.after.parent.once('value').then(function (snapshot) {
        console.log('snapval is the user id', snapshot.key);
        var userId = snapshot.key;
        //console.log('this is the userId', userId);
        return userId;
      }).then(function (userId) {
        console.log('this should be user id', userId);  
        var token = parseInt(Math.random() * 100000);
        console.log('this is the token', token);
        return admin.database().ref().child('userTokens').child(userId).child('token').set(token).then(function (success) {

          console.log('success token set');
        }).catch(function (error) {
          console.log('Error token not set', error);
        });
      }).catch(function (error) {
        console.log('Error token not set', error);
      });
      //TOKEN PREVIOUSLY DOESNT EXIST THEN CREATE AND ASSIGN

    }
    else {
      console.log('personal email field value not present');
      return;
    }
  });


exports.removeActiveRequests = functions.https.onRequest((req, res) => {
  const key = req.query.key;

  // Exit if the keys don't match
  if (!secureCompare(key, functions.config().cron.key)) {
    console.log('The key provided in the request does not match the key set in the environment. Check that', key,
      'matches the cron.key attribute in `firebase env:get`');
    res.status(403).send('Security key does not match. Make sure your "key" URL query parameter matches the ' +
      'cron.key environment variable.');
    return;
  }

  console.log('delete all the active requests here');
  var userSeatsToUpdate = [];
  var firebaseRef = admin.database().ref().child('requests');

  return firebaseRef.once('value').then(function (snapshot) {
    snapshot.forEach(function (child) {
      if (userSeatsToUpdate.indexOf(child.val().requestedTo) < 0) {
        userSeatsToUpdate.push(child.val().requestedTo);
      }
    });
    return userSeatsToUpdate;
  }).then(function (success) {
    var promises = success.map(function (key) {
      return admin.database().ref().child('users').child(key).once("value");
    });

    return Promise.all(promises);
  }).then(function (snapshots) {
    var updates = {};
    snapshots.forEach(function (snapshot) {
      updates[snapshot.key + "/remainingSeats"] = snapshot.val().capacity;
    });
    return updates;

  }).then(function (listToUpdate) {
    var ref = admin.database().ref().child('users');
    return ref.update(listToUpdate);
  }).then(function (success) {
    console.log('success', success);
    //Add logic to move active requests to past requests, may for analytics    
    return firebaseRef.remove()    
  }).then(function(sucess) {
    console.log('active requests deleted', success);
    res.status(200).send('All requests are deleted');
  }).fcatch(function (error) {
    console.log('error:nightlyJob:', error);
    res.status(400).send('error', error);
  });

});



// CORS and Cloud Functions export logic
exports.verifyToken = functions.https.onRequest((req, res) => {
  var corsFn = cors();
  corsFn(req, res, function () {
    verifyTheUserToken(req, res);

  });
});


function verifyTheUserToken(req, res) {

  console.log('in verify token');
  if (req.method === 'PUT') {
    res.status(403).send('Forbidden!');
  }

  if (!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ')) {
    console.error('No Firebase ID token was passed as a Bearer token in the Authorization header.',
      'Make sure you authorize your request by providing the following HTTP header:',
      'Authorization: Bearer <Firebase ID Token>');
    res.status(403).send('Unauthorized');
  }



  const firebaseToken = req.headers.authorization.split('Bearer ')[1];
  const userId = req.body.uid;
  const receievedToken = req.body.token;

  return admin.auth().verifyIdToken(firebaseToken).then(decodedFirebaseToken => {
    console.log('ID Token correctly decoded', decodedFirebaseToken);
    console.log('req', req.body);
    return 'sucess';

  }).then(function (receivedValues) {

    return admin.database().ref().child('userTokens').child(userId).child('token').once('value');

  }).then(function (snapshot) {

    console.log('this is the snap', snapshot);
    if (!snapshot.val()) {
      return Promise.reject('token is not set ');
    }

    console.log('snapshot.val(): ', snapshot.val(), 'receievedToken :', receievedToken);
    if (snapshot.val() != receievedToken) {
      return Promise.reject('token doesnt match');
    }

    return 'verified';

  }).then(function (sucess) {

    return admin.database().ref().child('users').child(userId).child('isVerified').set(true);

  }).then(function (sucess) {
    //DO A REDIRECT
    console.log('success in setting verified to true');
    res.send();
  }).catch(function (error) {
    //DECIDE WHAT YOU WANT TO DO
    console.log('Error', error);
    return admin.database().ref().child('users').child(userId).child('isVerified').set(true).then(function (success) {
      console.log('Setting verified to false');
      res.send();
    }).catch(function (error) {
      //DECIDE WHAT YOU WANT TO DO
      console.log('Error in setting false', error);
      res.send();
    });

  });

}


exports.handleRequestsForCarpooling = functions.database.ref('/requests/{uid}/')
  .onWrite((change,context)=>{

    console.log('new val', change.after.val());
    console.log('old val', change.before.previous.val());

    var rootRef = change.before.adminRef.root.child("users");

    if (change.after.val() !== null) {
      if (change.before.previous.val() !== null) {
        let firebaseRef = rootRef.child(change.before.previous.val().requestedTo).child('remainingSeats');

        firebaseRef.transaction(function (remainingSeats) {
          console.log('remainingSeats11111', remainingSeats);
          return remainingSeats + 1;
        }).then(function (success) {

          console.log('sucss', success);
        }).catch(function (error) {
          console.warn('error', error);
        });
      }
      let firebaseRef = rootRef.child(change.after.val().requestedTo).child('remainingSeats');
      firebaseRef.transaction(function (remainingSeats) {
        console.log('remainingSeats', remainingSeats);
        return remainingSeats - 1;
      }).then(function (success) {

        console.log('req', success);
      }).catch(function (error) {
        console.warn('error', error);
      });
    } else {
      console.log('no data');

    }

  });


exports.setRemainingSeatsOnCapacityChange = functions.database.ref('/users/{uid}/capacity')
  .onWrite((change,context)=>{

    if (change.before.previous.val() == change.after.val())
      return;

    var userId = '';

    if (change.before && change.after.val() != null) {
      return change.after.adminRef.parent.once('value').then(function (snapshot) {
        console.log('snapval is the user id', snapshot.key);
        userId = snapshot.key;
        console.log('userid', userId);
        return userId;
      }).then(function (userId) {
        return admin.database().ref().child('requests').orderByChild("requestedTo").equalTo(userId).once('value');

      }).then(function (snapshot) {

        if (snapshot.val())
          return Object.keys(snapshot.val()).length;
        else
          return 0;
      }).then(function (activeRequest) {
        var userRef = admin.database().ref().child("users").child(userId);
        console.log('this is the capacity', change.after.val());
        console.log('this is the activeRequest', activeRequest);
        var remainingSeats = change.after.val() - activeRequest;
        return userRef.update({
          remainingSeats: remainingSeats,
        });
      }).then(function (success) {
        console.log('success');
      }).catch(function (error) {
        console.error('error:', error);

      });
    }
  });
  

我部署数据库,功能,托管运行命令:npm   --prefix&#34; functions&#34;运行lint

     
    

函数@ lint c:\ ridesmartnew \ functions     eslint。

  
     

c:\ ridesmartnew \ functions \ index.js 44:51错误每个()   应该返回一个值或抛出承诺/总是返回
  54:23错误使用&#39; ===&#39;与null比较   no-eq-null 54:40错误预期&#39;!==&#39;而是看到&#39;!=&#39;
  eqeqeq 55:60警告意外的功能表达

  prefer-arrow-callback 60:15警告意外功能   表达偏好-arrow-callback 63:16
  警告避免嵌套承诺
  承诺/不筑巢63:16警告避免筑巢承诺
  promise / no-nesting 64:17警告意外的函数表达式   prefer-arrow-callback 72:20警告意外功能   表达偏好-arrow-callback 77:16
  警告意外的功能表达

  prefer-arrow-callback 82:7警告箭头函数预期a   返回值一致 - 返回91:9错误使用   &#39; ===&#39;与null no-eq-null 91:26进行比较   错误预期&#39;!==&#39;而是看到&#39;!=&#39; eqeqeq   93:60警告意外的功能表达

  prefer-arrow-callback 98:15警告意外功能   表达式prefer-arrow-callback 102:16
  警告避免嵌套承诺
  保证/不嵌套102:16警告避免嵌套承诺
  promise / no-nesting 102:104 warning意外的函数表达式   prefer-arrow-callback 102:104 error每个then()都应返回一个   价值或抛出承诺/总是回报105:18警告   意外的功能表达

  prefer-arrow-callback 108:16警告意外功能   表达式prefer-arrow-callback 116:7
  警告箭头功能预期返回值
  一致 - 返回137:3警告箭头功能预期没有   返回值一致 - 返回137:41警告   意外的功能表达

  prefer-arrow-callback 138:22警告意外功能   表达prefer-arrow-callback 144:11
  警告意外的功能表达

  prefer-arrow-callback 145:32警告意外功能   表达prefer-arrow-callback 150:11
  警告意外的功能表达

  prefer-arrow-callback 152:23警告意外功能   表达prefer-arrow-callback 157:11
  警告意外的功能表达

  prefer-arrow-callback 160:11警告意外功能   表达首选 - arrow-callback 164:11
  警告意外的功能表达

  prefer-arrow-callback 164:11 error每个then()应该返回一个   价值或抛出承诺/总是返回167:13警告   意外的功能表达

  prefer-arrow-callback 179:20警告意外功能   表达首选 - arrow-callback 211:11
  警告意外的功能表达

  prefer-arrow-callback 215:11警告意外功能   表达式prefer-arrow-callback 219:14
  错误预期Promise拒绝原因是错误   prefer-promise-reject-errors 223:24错误预期&#39;!==&#39;和   而是看到&#39;!=&#39; eqeqeq 224:14错误预期   承诺拒绝原因是一个错误   prefer-promise-reject-errors 229:11警告意外功能   表达prefer-arrow-callback 233:11
  警告意外的功能表达

  prefer-arrow-callback 233:11 error每个then()应该返回一个   价值或抛出承诺/总是返回237:12警告   意外的功能表达

  prefer-arrow-callback 240:12警告避免嵌套承诺
  保证/不嵌套240:12警告避免嵌套承诺
  promise / no-nesting 240:100 error每个then()都应返回一个   值或抛出承诺/总是返回240:100警告   意外的功能表达

  prefer-arrow-callback 243:14警告意外功能   表达prefer-arrow-callback 266:33
  警告意外的功能表达

  prefer-arrow-callback 269:17警告意外功能   表达prefer-arrow-callback 269:17
  error每个then()应返回一个值或抛出
  promise / always-return 272:18警告意外功能   表达prefer-arrow-callback 277:31
  警告意外的功能表达

  prefer-arrow-callback 280:15警告意外功能   表达式prefer-arrow-callback 280:15
  error每个then()应返回一个值或抛出
  promise / always-return 283:16警告意外功能   表达prefer-arrow-callback 297:35
  错误预期&#39; ===&#39;而是看到&#39; ==&#39; eqeqeq   302:23错误使用&#39; ===&#39;与null比较   no-eq-null 302:40错误预期&#39;!==&#39;而是看到&#39;!=&#39;
  eqeqeq 303:7警告箭头功能预期没有返回值
  一致返回303:60警告意外的功能表达

  prefer-arrow-callback 308:15警告意外功能   表达prefer-arrow-callback 311:15
  警告意外的功能表达

  prefer-arrow-callback 317:15警告意外功能   表达prefer-arrow-callback 325:15
  警告意外的功能表达

  prefer-arrow-callback 325:15 error每个then()应返回一个   值或抛出承诺/总是返回327:16警告   意外的功能表达

  喜欢箭头回调

     

✖68个问题(18个错误,50个警告)0个错误,40个警告   可以通过--fix选项进行修复。

     

npm ERR!代码ELIFECYCLE npm ERR!错误1 npm ERR!函数@lint:   eslint . npm ERR!退出状态1 npm ERR!错误的ERR!失败了   函数@lint脚本。错误的ERR!这可能不是问题   NPM。上面可能有额外的日志记录输出。

     

npm ERR!可以在以下位置找到此运行的完整日志:npm ERR!
  C:\ Users \用户Administrator.ME-IT-01 \应用程序数据\漫游\ NPM-cache_logs \ 2018-06-13T17_24_30_283Z-的debug.log

     

错误:函数预部署错误:命令以非零结束   退出代码1

0 个答案:

没有答案