I am new to polymer and I have a few problems. I have the following code polymer code for my polymerfire registration page.
Polymer({
is: 'my-register',
properties: {
message: {
type: String,
value: '',
},
email:{
type: String,
value: '',
},
password: {
type: String,
value: '',
},
user: {
type: Object,
notify: true,
},
customUser: {
value: {},
notify: true,
},
},
loginSuccess: function(){
this.customUser['status'] = 1;
if(this.customUser['status'] == 1 && this.message == ""){
console.log("done");
// this.$.ironLocation.set('path', '/profile');
}
},
createUserWithEmailAndPassword: function() {
this.error = null;
this.$.auth.createUserWithEmailAndPassword(this.email, this.password)
.then(function(response) {
this.loginSuccess();
console.log("success");
})
.catch(function(error) {
console.log("Error");
});
this.password = null;
},
ready: function(){
this.customUser['status'] = 0;
},
handleError: function(e) {
this.message = 'Error: ' + e.detail.message;
},
signOut: function() {
this.error = null;
this.$.auth.signOut();
},
});
The problem is that I can't call the loginSuccess function from the createUserWithEmailAndPassword success function. Is it possible to access external methods from the firebase-auth create function?
And is there a way to track custom attributes in the firebase user object instead of creating a second custom user object? I don't think this is very efficient because I have to access both properties in the whole application.
You can try this..
createUserWithEmailAndPassword: function () {
var self = this;
// Or ES6
// let self = this;
this.error = null;
this.$.auth.createUserWithEmailAndPassword(this.email, this.password)
.then(function (response) {
self.loginSuccess();
console.log("success");
}).catch(function (error) {
console.log("Error");
});
this.password = null;
}
I use this trick and work for me.
Cheers..!
Related
Im trying to get the data from the generated firebase dynamic link.
I passed Id while generating the dynamic link. I need to get the particular id from the generated dynamic link. Can you please help me.
Where it generates link as :https://thejyotistore.page.link/jNngseAasXzE5SuSA
const ShareLink = ({
fallbackUrl, id, product }) =>
{
const buildLink = async () =>
{
let link = await axios({
method: "POST",
url:
`https://firebasedynamiclinks
.googleapis.com/v1/shortLinks?
key=AIzaSyDNZvtkjAqf8c9esg
gSEzV2 L7. 3vEUv1FfQ`,
headers: {
"Content-Type":
"application/json",
},
data: {
dynamicLinkInfo: {
domainUriPrefix: `https://thejyotistore.page.link`,
link: `https://youtube.com/${id}`,
androidInfo: {
androidPackageName: "com.jyotistore.main",
},
},
},
});
if (link.status === 200 && link.data.hasOwnProperty("shortLink")) {
console.log(link.data.shortLink);
return link.data.shortLink;
}
};
const shareLink = async () =>
{
let shareUrl;
try {
shareUrl = await buildLink();
console.log(shareUrl);
} catch (error) {
console.log(error);
}
try {
if (shareUrl !== "") {
const result = await Share.share({
message: `Hey, ${"\n \n"}I would like to invite you to check out this New App from Jyoti Store. ${"\n \n"} ${product}Download the App now: ${"\n \n"} ${shareUrl}`,
});
}
} catch (error) {
console.log(error);
}
};
The validate function for basic
await server.register(require('#hapi/basic'));
const validate = async (request, email, password, id_customer) => {
console.log(request)
if (!email || !password || !id_customer) {
return { credentials: null, isValid: false };
}
const results = await getHash(id_customer);
if (results.length == 0) {
return { credentials: null, isValid: false };
}
if (bcrypt.compareSync(password, results[0]['passwd'])) {
const credentials = { id: id_customer, email: email };
return { isValid: true, credentials };
}
return { credentials: null, isValid: false };
};
server.auth.strategy('simple', 'basic', { validate });
Route example :
{
method: 'POST',
path: '/home/getCategories',
config: {
auth: 'simple',
description: 'Get Home',
payload: {
multipart: true
},
handler: Home.getCategories
},
/* options: {
auth: 'simple'
},*/
//handler: Home.getCategories
},
Here is the axios call from the App :
axios.post('https://api.domain.com/home/getCategories', {
code: code
},
{
headers: {
'email': email,
'password': password,
'id_customer': id_customer
},
})
When I do the call I got a 401 unauthorized but I cant see the output of 'console.log(request)'
Any help ?
Have you tried the following? What version of Hapi.js are you using?
const categoryPostValidation = {
payload: Joi.object({
name: Joi.string().label("Name").min(1).max(30).error((errors) => new Error('Name is invalid, and must be 1 to 30 characters in length')).required(),
description: Joi.string().label("Description").min(1).max(255).error((errors) => new Error('Description is invalid, and must be 1 to 255 characters in length')).required()
}),
failAction: async (request, h, err) => {
throw err;
}
};
const categoryPostRouteOptions = {
description: "Posts one category.",
cors: true,
payload: {
output: 'data', // These are default options
parse: true // These are default options
},
auth: {
mode: 'required' // or 'try', etc
strategy: 'simple'
},
validate: categoryPostValidation,
handler: Home.getCategories
};
{
method: 'POST',
path: '/home/getCategories',
options: categoryPostRouteOptions
},
I'm working with next.js and apollo client to get an access token with a refresh token from the server and I searched the web and find apollo-link-token-refresh that does something like silent refresh, so I follow along with example and was happy that after 2 days I finish my project Authentication but no it didn't work. is there any problem in my code?
const refreshLink = new TokenRefreshLink({
accessTokenField: "token",
isTokenValidOrUndefined: () => {
if (!cookie.get("JWT")) {
return true;
}
if (token && jwt.decode(token)?.exp * 1000 > Date.now()) {
return true;
}
},
fetchAccessToken: async () => {
if (!cookie.get("JWT")) {
return true;
}
const response = await fetch(`${NEXT_PUBLIC_SERVER_API_URL}`, {
method: "POST",
headers: {
authorization: token ? "JWT " + token : "",
"content-type": "application/json",
},
body: JSON.stringify({
query: `
mutation {
refreshToken(refreshToken: "${cookie.get("JWTRefreshToken")}") {
token
payload
refreshToken
refreshExpiresIn
}
}
`,
}),
});
return response.json();
},
handleFetch: (newToken) => {
cookie.remove("JWT", { path: "" });
cookie.set("JWT", newToken, {
expires: data.tokenAuth.payload.exp,
secure: process.env.NODE_ENV !== "production",
path: "",
});
},
handleResponse: (operation, accessTokenField) => (response) => {
if (!response) return { newToken: null };
return { newToken: response.data?.refreshUserToken?.token };
},
handleError: (error) => {
console.error("Cannot refresh access token:", error);
},
});
function createApolloClient() {
return new ApolloClient({
ssrMode: typeof window === "undefined",
link: authLink.concat(refreshLink).concat(
new HttpLink({
uri: process.env.NEXT_PUBLIC_SERVER_API_URL,
credentials: "same-origin",
}),
),
cache
})
)
Below this code downloadcontroller.js
// Retrieve all downloads from the database.
exports.findAll = async (req, res) => {
downloadObj
.findAll(
{
include: [
{
model: composerObj,
required: false,
},
{
model: raagaObj,
required: false,
},
{
model: taalaObj,
required: false,
},
],
where: req.query,
raw:true,
nest: true,
})
.then((data) => {
data.forEach(async (element) => {
const artistsArray = [];
let whereConstraint = {};
JSON.parse(element.artists).forEach( async (ele) => {
artistsArray.push(ele.artistId);
});;
whereConstraint = {
id : {
[Op.in]: artistsArray
}
}
element.Active = "true11";
const artistData = artistService.customfindAll(whereConstraint);
element.artistData = artistData;
console.log("artistData",artistData);
});
console.log("data",data);
console.log("3");
res.status(200).send({
status:200,
message: "ok",
data:data
});
console.log("4");
})
.catch((err) => {
res.status(500).send({
status:500,
message:
err.message || "Some error occurred while retrieving Download.",
});
});
};
Below this code, artistServer.js file
exports.customfindAll = async (whereConstraint) => {
return new Promise(function(resolve, reject) {
artistObj
.findAll({
attributes:{
include: [
[fn('IF',literal('imagePath!=""'),(fn('CONCAT', artistImagePath, 'artist/', col('imagePath'))),artistImageDefaultPath), 'imageFullPath'],
],
},
where: whereConstraint,
order: [
['artistName', 'ASC'],
],
raw:true,
nest: true,
})
.then((data) => {
resolve(data);
});
});
}
Here my problem is
const artistData = artistService.customfindAll(whereConstraint);
not waiting for the data. .So that I got the result, below have mentioned. Actually the artistData attribute column, need result data.
{
"status": 200,
"message": "ok",
"data": [
{
"id": 1,
"fileType": "1",
"customFileName": "test filename",
"artists": "[{\"artistId\":1},{\"artistId\":4},{\"artistId\":2}]",
"accompanyingArtists": "[{\"instrumentId\":1,\"accompanyingArtistId\":1},{\"instrumentId\":2,\"accompanyingArtistId\":6},{\"instrumentId\":3,\"accompanyingArtistId\":4}]",
"Active": "true11",
"artistData": {}
},
{
"id": 2,
"fileType": "1",
"customFileName": "new file name",
"artists": "[{\"artistId\":1},{\"artistId\":4},{\"artistId\":2},{\"artistId\":6},{\"artistId\":3}]",
"accompanyingArtists": "[{\"instrumentId\":1,\"accompanyingArtistId\":1},{\"instrumentId\":2,\"accompanyingArtistId\":6},{\"instrumentId\":3,\"accompanyingArtistId\":4},{\"instrumentId\":3,\"accompanyingArtistId\":3},{\"instrumentId\":4,\"accompanyingArtistId\":2}]",
"Active": "true11",
"artistData": {}
}
]
}
In console page, I artistdata attribute pending...
enter image description here
The customFindAll function returns a Promise but the forEach does not wait for it. Add an await:
const artistData = await artistService.customfindAll(whereConstraint);
Also, forEach does not wait, it just fires off the async functions and move on. To wait for the forEach to finish, you need a map and a Promise.all, like this:
await Promise.all(data.map(async (element) => {
const artistsArray = [];
let whereConstraint = {};
JSON.parse(element.artists).forEach( async (ele) => {
artistsArray.push(ele.artistId);
});;
whereConstraint = {
id : {
[Op.in]: artistsArray
}
}
element.Active = "true11";
const artistData = await artistService.customfindAll(whereConstraint);
element.artistData = artistData;
console.log("artistData",artistData);
}));
The way it works this way is that data.forEach(async (e) => ... runs the async function and discards the results (the Promises). If you use a map, like data.map(async (e) => ..., you'll get an array of Promises, then use await Promise.all(...) to wait for them.
I want to upload image from my RN app to meteor backend. I am using "react-native-image-picker": "^0.26.7" for getting imagefile from gallery or camera and uploading to meteor using package react-native-meteor to collectionFs this is my code of RN app where I am calling meteor method for image upload as soon as user select image:
_handleSelectFile() {
const { order } = this.state;
var options = {
title: 'Select Avatar',
storageOptions: {
skipBackup: true,
path: 'images'
}
};
ImagePicker.showImagePicker(options, (response) => {
if (response.didCancel) {
console.log('User cancelled image picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else {
// let source = { uri: response.uri };
// You can also display the image using data:
let source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
order: {
...order,
fileName: response.fileName
}
});
let fileData = response.data;
// const body = new FormData();
// body.append('file',fileData);
var photo = {
url: fileData,
type: 'image/jpeg',
name: 'photo.jpg',
};
Meteor.FSCollection('orderImages').insert(photo, function (err, res) {
if (err) {
console.log('error during uploading');
} else {
console.log('uploading successfully');
// _this.props.navigator.pop();
}
});
}
});
}
and this is my server side code:
export const Orders = new Mongo.Collection('orders');
export const OrderImages = new FS.Collection("orderImages", {
filter: {
maxSize: 1048576,
allow: {
contentTypes: ['image/*'],
}
},
stores: [new FS.Store.FileSystem("orderImages")]
});
if (Meteor.isServer) {
OrderImages.allow({
insert: function () {
return true;
}
});
}
and I am getting error like this:
ExceptionsManager.js:65
Cannot read property 'apply' of undefined