How to prevent dynamicLink listener from firing multiple times in react-native? - react-native

I have enabled signInWithEmailLink() from firebase in my react-native app.
Everything works successfully, the user is also created but the I think the onLink(handleLink) listener is fired multiple times and leads to an error even after user sign-in.
Logs:
link is tru
LOG email: email#gmail.com //I have hidden the actual email
LOG email: email#gmail.com
LOG email: email#gmail.com
LOG USer created
LOG EROR: [Error: [auth/invalid-action-code] The out of band code is invalid. This can happen if the code is malformed, expired, or has already been used.]
LOG EROR: [Error: [auth/invalid-action-code] The out of band code is invalid. This can happen if the code is malformed, expired, or has already been used.]
LOG EROR: [Error: [auth/invalid-action-code] The out of band code is invalid. This can happen if the code is malformed, expired, or has already been used.]
As you can see its fired multiple times, how can I prevent this??
This is my code:
const handleLink = async link => {
console.log('opened Link: ', link.url);
if (auth().isSignInWithEmailLink(link.url)) {
console.log('link is tru');
try {
const email = await AsyncStorage.getItem('email');
console.log('email: ', email);
await auth()
.signInWithEmailLink(`${email}`, link.url)
.then(() => {
console.log('USer created');
})
.catch(err => {
console.log('EROR: ', err);
});
} catch (err) {
console.log('err: ', err);
}
} else {
console.log('link is false');
}
};
const link = dynamicLinks().onLink(handleLink);
Help would be very much appreciated

Since console.log('email: ', email); is called 3 times, i assume that console.log('link is tru'); is also called 3 times, so the problem is that the whole handleLink function is called 3 times before auth().signInWithEmailLink finishes.

I ran into the same issue here is the answer.
Email link Authentication has a longer expiration time (around 6 hours). If you'll create 2 or more sign in emails in a row, you should be able to login with the latest link being received. You'll also be able to receive an error message for example in iOS, "The action code is invalid. This can happen if the code is malformed, expired, or has already been used" when you clicked the older links.

Related

How can I fix an Axios interceptor causing property 'status' of undefined error

I have a selection to set permissions for elements to global or private. I'm using the Axios interceptor request to handle looking for the permissions field to have data and, if it does, stringify it. The problem is, it causes me to get a "TypeError: Cannot read property 'status' of undefined" when I attempt to reload the program at all. The only "fix" right now is to log out, remove the interceptor, log in, read it, and then run the check again.
Because of this, I can't even get to the home dashboard of the software. If I clear my cookies, I can go back to the login screen, but no further than that after attempting to log in.
Is there something I'm missing for it? below is the interceptor code. If more information or context is needed, please let me know.
export default {
install: (Vue) => {
Vue.$eventBus = new Vue();
Vue.axios.interceptors.response.use(response => {
return response.data;
}, async error => {
if (error.response.status === 401 && error.config.url != '/api/authentication/login') {
var config = await Vue.$configService.find();
window.location = config.accountPortalUrl;
return
}
console.log(error);
Vue.$eventBus.$emit('notifyUser', 'Uh oh, something went wrong!');
return Promise.reject(error);
});
Vue.axios.interceptors.request.use(
config => {
// check request method -> use post if many params
if (config.data.permissions) {
config.data.permissions = JSON.stringify(config.data.permissions);
}
console.log(config);
return config;
}
);
}
};
Looks like your service API is not responding, this might happen if the user is not authenticated . Your error is at line where you check (error.response.status). Its only possible to get an undefined response when the request was interrupted before response. Most probably if you check your browser network pannel you will see that the preflight check for this request causes a 401 network error. Hence because the preflight failed your actual response comes as undefined. You should sanity check first if your server responded with a response or not and then access the response status.
Something like this might help
if (error.response) {
// Request was made and the server responded successfully
// You can now de-structure the response object to get the status
console.log(error.response.status);
} else if (error.request) {
// request was made but not responded by server
console.log(error.request);
}
So, the answer ultimately was something extremely simple.
if (config.data.permissions)
needed to be
if (config.data && config.data.permissions)

nodejs robinhood api login

I am trying to login to the robinhood API, I turned 2fa and sms off in the app but am still getting an error does this look correct below or is robinhood just slow at updating when 2fa is turned off.
var credentials = {
username: '*****',
password: '*****'
};
var Robinhood = require('robinhood')(credentials, function(){
console.log(Robinhood.auth_token());
// <authenticated alphanumeric token>
})
the error
Error: token not found {"statusCode":400,"body":{"detail":"Request blocked, challenge type required.","accept_challenge_types":{"sms":"SMS"}},"headers":{"date":"Mon, 24 May 2021 22:44:07 GMT","content-type":"application/json","content-length":"93","connection":"close","server":"openresty","allow":"POST, OPTIONS","x-robinhood-api-version":"0.0.0","content-security-policy":"default-src 'none'","x-frame-options":"SAMEORIGIN","x-content-type-options":"nosniff","x-xss-protection":"1; mode=block","access-control-allow-origin":"https://robinhood.com","vary":"Origin","trace-uuid":"56ccb9cc-8bca-4dbd-be6f-4a6d86171354"},"request":{"uri":{"protocol":"https:","slashes":true,"auth":null,"host":"api.robinhood.com","port":443,"hostname":"api.robinhood.com","hash":null,"search":null,"query":null,"pathname":"/oauth2/token/","path":"/oauth2/token/","href":"https://api.robinhood.com/oauth2/token/"},"method":"POST","headers":{"Host":"api.robinhood.com","Accept":"*/*","Accept-Encoding":"gzip, deflate","Referer":"https://robinhood.com/","Origin":"https://robinhood.com","content-type":"application/x-www-form-urlencoded","content-length":214}}}
Robinhood recently required 2fa to be enabeld if using the api. It is mentioned in the detail of the request body.
"detail":"Request blocked, challenge type required.","accept_challenge_types":{"sms":"SMS"}}
Go ahead and turn it on and then you can access the api with this snippet
let Robinhood = require('robinhood')(credentials, function(data) {
if (data && data.mfa_required) {
var mfa_code = ""; //Notice this is blank.
Robinhood.set_mfa_code(mfa_code, () => {
console.log(Robinhood.auth_token());
Robinhood.positions((error, response, body) => {
console.log(body);
})
})
}
})
Once you make a request you'll get an error, but the 2fa challenge will be sent to whatever you set your account with. Once you received the 2fa code, set the mfa_code and re-run the snippet. Once you ran the snippet again with a valid 2fa code, then you've successfully logged in. Copy the authorization token and you can use that without the need of going through 2fa again for i believe 24 hrs

express middleware not sending response

I have a delete route that has 2 middleware functions Authcontroller.protect and authcontroller.restrictTo("admin, "lead-guide")
router
.delete(
authController.protect,
authController.restrictTo("admin", "lead-guide"),
tourController.deleteTour
);
Within restrictTo I have a check to see if the user has the proper "role" to perform that task and if they don't, express is supposed ot send a 403. I'm seeing that express never actually sends the response. it enters the if statement(i see the console successfully printing fialure) and then it just skips sending the response.
exports.restrictTo = (...roles) => {
return (req, res, next) => {
console.log(req.user.role);
if (!roles.includes(req.user.role)) {
console.log("failure");
return res.status(403).json({
status: fail,
message: "you do not have permission to perform this action"
});
console.log(req, res);
}
next();
};
};
Put a try/catch in your inner function and see if there's an exception being thrown.
From looking at your code, if the fail variable (which you don't show a definition for) is not defined, then that would throw an exception and keep the res.json() from executing.

AWS Cognito JS SDK returning "AdminUpdateUserAttributes is not a function" error message

I'm trying to create a function which allows me to update a user's phone number in a Cognito User Pool. The code is in a NodeJS application, using the latest aws-sdk library.
I have this function callback structure working for a number of other actions against the user pool, e.g. creating and listing users, updating MFA, etc. So I am confident there's nothing structurally wrong with the way I have laid the code out.
But for this particular function, I am receiving an error that says AdminUpdateUserAttributes "is not a function".
I've tried changing different attributes in case it's a phone number thing, but I got the same result.
function cognitoUpdatePhone(username, phoneNumber, callback) {
var params = {
UserPoolId: '<my pool Id>',
Username: username,
UserAttributes: {
phone_number: phoneNumber
}
};
var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
cognitoidentityserviceprovider.AdminUpdateUserAttributes(params, function (err, data) {
if (err) {
callback(err, false);
}
else {
callback(null, true);
}
});
}
I'm getting following response from the server. The stack trace indicates the source of the error is: aws-sdk/lib/state_machine.js
message: 'cognitoidentityserviceprovider.AdminUpdateUserAttributes is not a function',
code: 'TypeError',
Encountered the exact same problem. Solved it by changing the first letter of the function to lowercase: adminUpdateUserAttributes
Try using this:
var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider({apiVersion: '2016-04-18'});

Invalid CSRF when logging in to keystone

I'm entirely new to coding. I've looked around a bit, but not found anything relevant.
When logging into keystone to view our mongoDB database I get an error message saying:
Something went wrong; please refresh your browser and try again.
Doing that does not help. Neither does deleting the browser history or attempting from another lap top.
Looking at the javascript console in the browser, the error states invalid csrf.
I think this is the relevant source code in the keystone folder:
handleSubmit (e) {
e.preventDefault();
// If either password or mail are missing, show an error
if (!this.state.email || !this.state.password) {
return this.displayError('Please enter an email address and password to sign in.');
}
xhr({
url: `${Keystone.adminPath}/api/session/signin`,
method: 'post',
json: {
email: this.state.email,
password: this.state.password,
},
headers: assign({}, Keystone.csrf.header),
}, (err, resp, body) => {
if (err || body && body.error) {
return body.error === 'invalid csrf'
? this.displayError('Something went wrong; please refresh your browser and try again.')
: this.displayError('The email and password you entered are not valid.');
} else {
// Redirect to where we came from or to the default admin path
if (Keystone.redirect) {
top.location.href = Keystone.redirect;
} else {
top.location.href = this.props.from ? this.props.from : Keystone.adminPath;
}
}
});
},
How can I go about solving this / debugging the error? Thanks for any help!
This usually happens when session affinity fails. Are you using default in-memory session management? Maybe, try using a database for maintaining session state.
If you use MongoDB, Try the following config setting
'session store': 'mongo',
See 'session store' section under http://keystonejs.com/docs/configuration/#options-database for more details.