Why is my passport auth code giving a reference letter despite following the documentation? - passport-local-mongoose

I've used this code before to authenticate a secrets type of application and for some reason this time it isn't working.. all node package modules are install and this error pops up on display:
ReferenceError: respond is not defined
at C:\Users\user\Desktop\Ayanda Gatsha Full Stack JS Web Developer\Ayandas Digital School For Digital Developers\SRS Saver App\app.js:102:5
at Layer.handle [as handle_request] (C:\Users\user\Desktop\Ayanda Gatsha Full Stack JS Web Developer\Ayandas Digital School For Digital Developers\SRS Saver App\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\user\Desktop\Ayanda Gatsha Full Stack JS Web Developer\Ayandas Digital School For Digital Developers\SRS Saver App\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\user\Desktop\Ayanda Gatsha Full Stack JS Web Developer\Ayandas Digital School For Digital Developers\SRS Saver App\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\user\Desktop\Ayanda Gatsha Full Stack JS Web Developer\Ayandas Digital School For Digital Developers\SRS Saver App\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\user\Desktop\Ayanda Gatsha Full Stack JS Web Developer\Ayandas Digital School For Digital Developers\SRS Saver App\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\user\Desktop\Ayanda Gatsha Full Stack JS Web Developer\Ayandas Digital School For Digital Developers\SRS Saver App\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\user\Desktop\Ayanda Gatsha Full Stack JS Web Developer\Ayandas Digital School For Digital Developers\SRS Saver App\node_modules\express\lib\router\index.js:275:10)
at SessionStrategy.strategy.pass (C:\Users\user\Desktop\Ayanda Gatsha Full Stack JS Web Developer\Ayandas Digital School For Digital Developers\SRS Saver App\node_modules\passport\lib\middleware\authenticate.js:343:9)
at C:\Users\user\Desktop\Ayanda Gatsha Full Stack JS Web Developer\Ayandas Digital School For Digital Developers\SRS Saver App\node_modules\passport\lib\strategies\session.js:69:12
at pass (C:\Users\user\Desktop\Ayanda Gatsha Full Stack JS Web Developer\Ayandas Digital School For Digital Developers\SRS Saver App\node_modules\passport\lib\authenticator.js:337:31)
at deserialized (C:\Users\user\Desktop\Ayanda Gatsha Full Stack JS Web Developer\Ayandas Digital School For Digital Developers\SRS Saver App\node_modules\passport\lib\authenticator.js:349:7)
at C:\Users\user\Desktop\Ayanda Gatsha Full Stack JS Web Developer\Ayandas Digital School For Digital Developers\SRS Saver App\node_modules\mongoose\lib\model.js:5074:18
at processTicksAndRejections (internal/process/task_queues.js:75:11)
// jshint esversion:6
require("dotenv").config();
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const passportLocalMongoose = require("passport-local-mongoose");
const passport = require("passport");
const session = require("express-session");
const script = require(__dirname + "/lib/script.js");
const Schema = mongoose.Schema;
moment = require("moment"); // require
// Load the full build.
const _ = require("lodash");
// const lowerCase = require('lodash.lowercase');
const app = express();
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
app.use(
session({
secret: "keyboard cat",
resave: false,
saveUninitialized: false,
}),
);
app.use(passport.initialize());
app.use(passport.session());
const url = "mongodb://127.0.0.1:27017/userDB";
mongoose.connect(url, { useNewUrlParser: true });
mongoose.set("useCreateIndex", true);
const userSchema = new mongoose.Schema({
name: String,
email: String,
password: String,
});
userSchema.plugin(passportLocalMongoose);
// const secret = "mysecret";
// userSchema.plugin(encrypt, {secret: process.env.SECRET, encryptedFields:["password"]});
const User = new mongoose.model("User", userSchema);
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.get("/", function (req, res) {
res.render("home");
});
app.post("/", function (req, res) {
User.register(
{ username: req.body.username },
req.body.password,
function (err, user) {
if (err) {
console.log(err);
res.redirect("/");
} else {
passport.authenticate("local")(req, res, function () {
res.redirect("/dashboard");
});
}
},
);
});
app.get("/dashboard", function (req, res) {
respond.render("dashboard", { packageData: momentData });
});
app.listen(3000, function () {
console.log("Server started on port 3000");
});

This is not related to Passport at all, or any external documentation.
You have a simple typo.
app.get("/dashboard", function (req, res) {
respond.render("dashboard", { packageData: momentData });
});
should be
app.get("/dashboard", function (req, res) {
res.render("dashboard", { packageData: momentData });
});
since there is no respond variable.

Related

Expo Notification on Android

I have setup the expo push notification in my app. I am able to get the device token for both android and ios in my expo go app. when i publish my app to test-flight i am able to get the device token as well. But when i publish the app to PLaystore for testing i notice the device token is not working because i am saving the token to my laravel backend.
below is my code
const registerForPushNotificationsAsync = async () => {
let token;
if (Device.isDevice) {
const { status: existingStatus } =
await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== "granted") {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== "granted") {
alert("Failed to get push token for push notification!");
return;
}
token = (await Notifications.getExpoPushTokenAsync()).data;
sendDeviceTokenToBackend(token)
} else {
alert("Must use physical device for Push Notifications");
}
if (Platform.OS === "android") {
Notifications.setNotificationChannelAsync("default", {
name: "default",
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: "#FF231F7C",
});
}
return token;
};
Below is the code i use to send to my backend
const sendDeviceTokenToBackend=(token)={
const obj = {
device_token: data,
};
const response = await db.communicate(
"POST",
"/device/tokens",
obj,
"auth"
);
}
i read a couple of answers on stackoverflow that i need to configure FCM in order for my android noticifation to work. but here i will be using php sdk for my notification configuration so i am saving the device token to the backend. so i have a few questions
if i am to use firebase to save my device token how will i send my device token to my php backend from firebase .
since i will be managing it on my php server instead of expo push notification how do i get the token in andriod when i publish it to playstore
any help on this i will appreciate

Google cloud function with different end point sheducle with google

I have created a project in express
const express = require('express');
const app = express();
const PORT = 5555;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
app.get('/tr', (req, res, next) => {
res.json({ status: 200, data: 'tr' })
});
app.get('/po', (req, res, next) => {
res.json({ status: 200, data: 'po' })
});
module.exports = {
app
};
deployed on cloud function with name my-transaction
and i am scheduling with google clound giving the url like
http://url/my-transaction/po
When I deployed without authentiation scheduler runs job success, but when I do with authentication it fails.
similary if i create a sample project like below
exports.helloHttp = (req, res) => {
res.json({ status: 200, data: 'test hello' })
};
and deploy similary configuring same as above with authentication it works.
only differce is in last function name is similar to entry point means
while above entry point is app with different end points.
any help,
appreciated
Thanks
This is because you need to add auth information to your http requests on cloud Scheduler
First you need to create a service account with the role Cloud Functions Invoker
when you have created the service account, you can see that has a email associated fro example:
cfinvoker#fakeproject.iam.gserviceaccount.com
After that you can create a new scheduler job with auth information by following these steps:
Select target http
Write the url (cloud function url)
Click on "show more"
Select Auth header > Add OIDC token
Write the full email address of the service account
This new job scheduler will be send the http request with the auth infromation to execute successfully your cloud function.

Amplify Push Notification problem (React Native)

i'm using amplify to configurate push notification messages in react native, all is good but i need send notification to determinate devices, not for all devices.
I'm using:
Aws Pinpoint (to send notification).
Amplify (to recieve notifications)
Mobile Hub (to configurate integration)
Index.js (Main project file)
...
import InformApp from './app/App';
const loggerMiddleware = createLogger({ predicate: () => false });
const persistedReducer = persistReducer({ key: 'root', storage, blacklist: ['filter', 'modals'] }, reducers);
//AWS
import Amplify from 'aws-amplify';
import aws_exports from './src/aws-exports';
Amplify.configure(aws_exports);
...
App.js (Main View):
...
componentDidMount() {
// get the notification data when notification is received
PushNotification.onNotification(notification => {
// console.warn(notification)
this.props.recieveNotification(notification._data.data.jsonBody);
// required on iOS only (see fetchCompletionHandler docs: https://facebook.github.io/react-native/docs/pushnotificationios.html)
if (PushNotificationIOS != undefined) {
notification.finish(PushNotificationIOS.FetchResult.NoData);
}
});
// get the registration token
PushNotification.onRegister(token => {
console.log("in app registration", token);
});
// get the notification data when notification is opened
PushNotification.onNotificationOpened(notification => {
alert(notification);
// console.warn(notification);
// console.warn("the notification is opened", notification);
});
}
...
Thanks in advance and sorry for my english

Invoke another player when one media response(audio playing) is done

I have a problem.
I pick up a dialogflow, google action sample (playing a audio file)
I want to build for several audio files.
So when media response is done, media status is invoked.
So at that time, I want to play next audio automatically.
Please help me. I need your kind help.
Thanks.
This is my code.
'use strict';
const {
dialogflow,
SimpleResponse,
Image,
Suggestions,
MediaObject,
} = require('actions-on-google');
const functions = require('firebase-functions');
const app = dialogflow({debug: true});
app.intent('Media Response', (conv) => {
if (!conv.surface.capabilities
.has('actions.capability.MEDIA_RESPONSE_AUDIO')) {
conv.ask('Sorry, this device does not support audio playback.');
conv.ask('Which response would you like to see next?');
return;
}
conv.ask('This is a media response example.');
conv.ask(new MediaObject({
name: 'Jazz in Paris',
url: 'https://storage.googleapis.com/automotive-media/Jazz_In_Paris.mp3',
description: 'A funky Jazz tune',
icon: new Image({
url: 'https://storage.googleapis.com/automotive-media/album_art.jpg',
alt: 'Album cover of an ocean view',
}),
}));
conv.ask(new Suggestions(['cancel']));
});
app.intent('Media Status', (conv) => {
const mediaStatus = conv.arguments.get('MEDIA_STATUS');
let response = 'Unknown media status received.';
if (mediaStatus && mediaStatus.status === 'FINISHED') {
response = 'Hope you enjoyed the tune! ';
}
conv.ask(response);
conv.ask('Media ended successfully');
conv.ask(new Suggestions(['exit']));
});
exports.dialogflowFirebaseFulfillment = functions.https.onRequest(app);
I tried to invoke another response on 'Media Status' intent.
app.intent('Media Status', (conv) => {
const mediaStatus = conv.arguments.get('MEDIA_STATUS');
let response = 'Unknown media status received.';
if (mediaStatus && mediaStatus.status === 'FINISHED') {
conv.ask(new MediaObject({
name: 'Jazz in Paris',
url: 'https://storage.googleapis.com/automotive-media/Jazz_In_Paris.mp3',
description: 'A funky Jazz tune',
icon: new Image({
url: 'https://storage.googleapis.com/automotive-media/album_art.jpg',
alt: 'Album cover of an ocean view',
}),
}));
conv.ask(new Suggestions(['cancel']));
});
}
});
Then "Webhook failed for intent: Media Status" error happend. How should I solve this problem? Thank you.
All responses that include a MediaObject must also include a SimpleResponse - which is usually just some text that is said before the Media.
For example, in the "Media Response" Intent Handler when you send your first MediaObject, you have the line:
conv.ask('This is a media response example.');
But this sort of line is missing from the "Media Status" Intent Handler.

loopback's User Model (login & logout) methods usage in middleware

Is there a way to use the User(model) methods like (login & logout) in our code? Like in my case I want to use the User.login(....) method in the middle-ware that is defined in the route phase of middle-ware.
I tried to import the User model in this way in the middle-ware file.
var loopback = require('loopback');
var boot = require('loopback-boot');
var app = module.exports = loopback();
var User = app.models.user;
It gives me the error that "app is undefined".
Kindly let me know is there a way to use the login etc methods in my middle-ware.
Thank you
'use strict';
var mysql = require('mysql')
var loopback = require('loopback');
var boot = require('loopback-boot');
var app = module.exports = loopback();
app.start = function() {
// start the web server
return app.listen(function() {
app.emit('started');
var baseUrl = app.get('url').replace(/\/$/, '');
console.log('Web server listening at: %s', baseUrl);
if (app.get('loopback-component-explorer')) {
var explorerPath = app.get('loopback-component-explorer').mountPath;
console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
}
});
};
// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, function(err) {
if (err) throw err;
// start the server if $ node server.js
if (require.main === module)
app.start();
});
You need to bootstrap the application in advance before using the models
var loopback = require('loopback');
var boot = require('loopback-boot');
var app = module.exports = loopback();
boot(app, __dirname, function(err) {
// You can start your application here
app.start();
// Models have been loaded to app object after boot(). You can use it here if you want
var User = app.models.user;
});
From their official document
The LoopBack bootstrapper, loopback-boot, performs application
initialization (also called bootstrapping). When an application
starts, the bootstrapper:
Configures data sources.
Defines custom models Configures models and attaches models to data-sources.
Configures application settings
Runs boot scripts in the /server/boot directory.
You may want to look at their sample server.js for better reference