Route param is getting weird - angularjs

I have few routes in which i add token or id dynamically on user actions.
so the issue is dynamic params is turning weird and causing problem for my backend. some of buggy url mention below
/feedback/:token which changes to /feedback?token=%7B%7BcurrentSharingImage%7D%7D
this is the code which is causing this issue
Feedback.get({token: $routeParams.token})
.$promise
.then(feedback => {
$scope.feedbackDetails = feedback;
// remaining code
});
/download-file/:id which changes to /download-files/{{currentSharingImage}}
DownloadFile.getOne({id: $routeParams.id})
.$promise
.then((fileRequest) => {
}).catch(()=>{
$scope.control.isLoading = false;
Alert.errorToast('Error getting file.');
});
/hub-admin/manual-messaging/:id which changes to /hub-admin/manual-messaging/{{currentSharingImage}}
There are many URLs but I have came across this.
I am using angular 1.5.8 and specifically issue is with FireFox. Can I get some clue what is causing this issue?

Related

React native axios crashing and werid behaviour

Axios is behaving weird on my react native webview if you have any idea how to solve or how i can track the problem it would be of much help.
On the onMessage of the webview i recieve the html of the website so i can get a specific link. I send the message when the user taps anywhere on screen.
Injected js:
var body_of_html = document.body;
body_of_html.addEventListener('click',function(e){
window.ReactNativeWebView.postMessage(document.documentElement.innerHTML)
},false);
Case 1
This doesnt console.log anything and after some time crashes the app.
onMessage={event => {
// console.log('asdas');
var regex = new RegExp('token=[a-zA-z0-9]+');
if (event.nativeEvent.data.toString().match(regex) != null) {
let asd =
'https://fvs.io/redirector?' +
event.nativeEvent.data.toString().match(regex);
axios.get(asd).then(rs => {
console.log(rs);
});
Case 2
This one works perfectly fine and logs "Anything".
onMessage={event => {
var regex = new RegExp('token=[a-zA-z0-9]+');
if (event.nativeEvent.data.toString().match(regex) != null) {
let asd =
'https://fvs.io/redirector?' +
event.nativeEvent.data.toString().match(regex);
axios.get(asd).then(console.log("Anything"));
As you can see from the above cases i am unable to get the response from the axios call. Which always after some time crashes the app. Am i doing something wrong on reciving the response ?
Edit: I think I know what might have caused my application to crash but this is just what I found after looking at the data consumed. The link i was sending to the axios.get was retriving bits of a video until it fully buffered. But the way my code was , it would do this action each time i tapped the screen. I guess at some point axios couldnt handle reciving 10x + videos at 1080p at the same time. Just to clarify my intention was just to get the redirection link i didnt know it would cause the video to buffer.
As in all promises, in order to debug the error, e.g. in cases where event.nativeEvent.data may be undefined, causing .toString() to throw error, use a catch block.
axios.get(asd).then(rs => {
console.log(rs);
}).catch(error => console.log("error from axios", error))

getInitialProps causing ERR_TOO_MANY_REDIRECTS error on my live site, but not on my local version

So, I've been trying to implement cookies on my website, to keep track of a list of JavaScript objects, so the page stays consistent when the user comes back to it. I've been following this tutorial here.
On my local machine, using npm run dev on localhost:3000, it works absolutely perfect. However, when I push the commit to GitHub, it builds on Vercel without any issue, but when I try and access the live website on the internet, it gives me a 'ERR_TOO_MANY_REDIRECTS' error.
I'm pretty confused as to why it would work perfectly fine on my locally hosted site, but freaks out and does not work when it's put into production.
I think I have narrowed the problem down to getInitialProps because when I comment out the implementation in my index.js file, it still doesn't work, but when I comment out getInitialProps, it works again.
Here is the code I think may be the problem.
Home.getInitialProps = async ({req, res}) => {
const data = parseCookies(req)
if (res) {
if (Object.keys(data).length === 0 && data.constructor === Object) {
res.writeHead(301, { Location: "/" })
res.end()
}
}
return {
data: data && data,
}
}
And here is the code for that parseCookies method, which is imported as
import { parseCookies } from "../helpers/index"
within my index.js
import cookie from "cookie"
export function parseCookies(req) {
return cookie.parse(req ? req.headers.cookie || "" : document.cookie)
}
I'm super confused at this point, I've walked myself through the code a dozen times now and still have no idea what I might be doing wrong. Any help would be much appreciated! And please lemme know if there's anymore info I can provide!
The ERR_TOO_MANY_REDIRECTS error occurs because Object.keys(data).length === 0 && data.constructor === Object returns true when no cookies are set and you access the homepage. When this happens the redirect takes you back to / (the homepage) which then makes the check again and a new redirect occurs, and so on.
Locally, you probably have cookies set, so you don't experience the issue. However, when you access the website hosted on Vercel, no cookies are present initially, which triggers the infinite redirect cycle.
To fix the issue simply remove the logic from the homepage, since that's the redirect destination. You can still have it on other pages and redirect to the homepage, though.

auth0 parseHash can't create property '__enableIdPInitiatedLogin' on hash string

I'm trying to upgrade my React web app from auth0-js 9.6.1 to 9.7.3. After installing the new library, my Slack login flow no longer works, it appears to be breaking in the callback.
TypeError: Cannot create property '__enableIdPInitiatedLogin' on string '#access_token={token string}&token_type=Bearer&state={state string}'
My parseHash call is:
this.auth0.parseHash(hash, (err, authResult) => {
if (authResult && authResult.idToken) {
AuthService.setToken(authResult.idToken); // JWT returned from Auth0;
// Redirect user to content.
const returnUrl = localStorage.getItem(Variables.RETURN_URL_KEY);
localStorage.removeItem(Variables.RETURN_URL_KEY);
returnUrl
? window.location.replace(returnUrl)
: window.location.replace("/");
} else if (err) {
console.log("Error with auth callback", err);
window.location.replace("https://foo.com"); // If auth fails, send user to home page.
}
}
This works fine in 9.6.1, but fails in 9.7.x and I can't find anything about any breaking changes that would cause it to start failing. Any ideas?
I had the same issue as you so I opened a ticket on the Auth0.js library github page.
This is the response I got from the developers:
It was working by accident then (also, the string is being ignored in your case), considering that we expect the first parameter to either be an object or a callback function.
All of our docs mention that:
https://github.com/auth0/auth0.js#api
https://auth0.github.io/auth0.js/global.html#parseHash
https://auth0.com/docs/libraries/auth0js/v9#extract-the-authresult-and-get-user-info
In your case, the simplest fix is to just remove the first parameter and keep only the callback. window.location.hash is already used when there's no options object.
(emphasis on the fix mine)
I tested 9.7.3 with this.auth.auth0.parseHash((err, result) => ... and it worked like a charm.
I hope this'll help!

MVC6 Prevent Redirect on unauthorized

I'm developing an ASP.NET MVC 6 Web API app, with AngularJs frontend.
When I leave a session to decade, or I'm trying to call a Web API action unauthorized, I expect to receive a 401 status code.
Instead, I get a 302, and tries to redirect to the default path for login ("/Account/Login").
So I need to handle this in Angular.
From other forum posts here and googling I found that some people resolved their problems using in startup.cs:
services.Configure<CookieAuthenticationOptions>(options =>
{
options.LoginPath = PathString.Empty;
});
No luck for me.
I use Identity as authentication backend and even adding
services.ConfigureIdentityApplicationCookie(options =>
{
options.LoginPath = PathString.Empty;
});
does not give me the expected result. ASP.NET docs suggest this way to return a 401.
Using 1.0.0-beta7 CLR x86, IIS Express.
EDIT: the solution proposed by #EZI is correct.
Below my answer, which doesn't work on recent release.
Finally! I found the solution!
To be complete, I started with this comment found on source code in aspnet/Identity github.
// If the LoginPath is null or empty, the middleware will not look for 401 Unauthorized status codes, and it will not redirect automatically when a login occurs.
which give me the wrong directions.
Digging with debug on ConfigureIdentityApplicationCookie' options, I found that there is a delegate on "Notifications" property
OnApplyRedirect
Bingo!
Now I can control the redirect.
services.ConfigureIdentityApplicationCookie(options =>
{
options.LoginPath = PathString.Empty;
options.Notifications = new CookieAuthenticationNotifications {
OnApplyRedirect = context => { context.Response.StatusCode = 401; }
};
});
This maybe isn't a good way to handle the problem, but finally I receive a 401 Unauthorized when the web.api action is called without authentication.
For me it worked to just set the AutometicAuthenticate to false.
services.Configure<IdentityOptions>(options =>
{
options.Cookies.ApplicationCookie.AutomaticAuthenticate = false;
options.Cookies.ApplicationCookie.AutomaticChallenge = false;
options.Cookies.ApplicationCookie.LoginPath = PathString.Empty;
});
my solution was similar to #Ezi
Confirmed working for RC2
services.AddIdentity<IdentityUser, IdentityRole>(options =>
{
options.Cookies.ApplicationCookie.AutomaticChallenge = false;
});

Angularjs Passing array between controllers

I have been through several tutorials and posts about this topic and still can't seem to figure out what is wrong with my code. To me it seems I am having scoping issues with the data within my service. My code is split up into separate files. Here is my code:
github link : https://github.com/StudentJoeyJMStudios/PetPinterest.git
//in dataService.js
var app = angular.module('se165PetPinterestWebApp');
app.service('SharedData', function ()
{
var categoryOfSelectedAnimals = [];
this.setCatOfSelAnimals = function(pulledCategoriesFromParse)
{
categoryOfSelectedAnimals = pulledCategoriesFromParse;
console.log('after assignment in set::' + categoryOfSelectedAnimals);
};
this.getCatOfSelAnimals = function()
{
console.log('in get::::' + categoryOfSelectedAnimals);
return categoryOfSelectedAnimals;
};
});
in my first controller to set the data in signup.js
app.controller('SignupCtrl',['$scope', 'SharedData', function ($scope, SharedData)
{
var Categories = Parse.Object.extend('Categories');
var query = new Parse.Query(Categories);
query.find({
success: function(results)
{
$scope.availableCategoriesOfAnimals = results;
SharedData.setCatOfSelAnimals(results);
},
error: function(error)
{
alert('Error: ' + error.code + ' ' + error.message);
}
});
};
}]);
Then in my other controller trying to get the data from the array within my service:
var app = angular.module('se165PetPinterestWebApp');
app.controller('CatSelCtrl', function ($scope, SharedData)
{
$scope.availableCategoriesOfAnimals = SharedData.getCatOfSelAnimals();
});
When I print the contents from the SharedData.getCatOfSelAnimals I get 0 every time. Please help. Thank you very much in advance.
EDIT: After playing around with a string a bit I am finding the changed string in the set function is not saved into the service and when I call my get function within my service the string is not changed from the set method. Please help, thank you in advance.
EDIT: So it looks like when I navigate to new page by using window.location.href = '../views/categorySelection.html'; in my signup.js it reloads my dataService.js which re-sets my variables back to nothing. Does anyone have any ideas as to how to fix this?
Edit
First: why you lose data
You need to setup routing properly. Right now you are not changing views but rather using window.location.href to load a new bootstrap file (dashboard.html), i.e. everything saved in memory will be lost. So you have been doing it right, sort of, but the moment you change to dashboard.html all data from Parse is lost.
You can solve this by configuring routes and use $location.url() to change URL. Read more about angular.route here: https://docs.angularjs.org/api/ngRoute/service/$route
The angular way
After looking at your code and running your app I think we need to take a step back. Angular is tricky to get used to but there is a lot of good tutorials. I think you might wanna read some of them to get a better grasp of how it works and how to setup and build your app.
Start here: http://www.airpair.com/angularjs
Boilerplate
Found this boilerplate for an Angular app using Parse. It might be something you could use. https://github.com/brandid/parse-angular-demo
Original
Or an even quicker way to empty $scope.availableCategoriesOfAnimals and then merge new data without breaking reference:
$scope.availableCategoriesOfAnimals.length = 0;
Array.prototype.push.apply($scope.availableCategoriesOfAnimals, pulledCategoriesFromParse);
You are breaking the reference on assignment. This is a JavaScript issue, not an angular one for that matter ;)
Try this in your set function:
categoryOfSelectedAnimals.length=0;
pulledCategoriesFromParse.forEach(function (e) {categoryOfSelectedAnimals.push(e)});
in stead of reassigning
edit: angular extend works on objects, not arrays, so replaced it with a bit of JS.

Resources