grab query params from redirect angular 5 - javascript

My problem is I'm using auth0 as my authentication service, now when a user logs in and is authenticated it gets redirected back to my callback url which then decides where to send the user now my problem is when you get redirected back to your callback url from auth0 there are queryParams in the url string like so..
http://localhost:4200/account/login/callback#access_token="dsadsadsadsa dasdsaa" just as an example but then in a split second the query string is removed and its left at http://localhost:4200 now Im trying to grab the query Params using this method
this.activatedRoute.queryParams.subscribe(params => {
console.log(params);
});
now this should work but the console.log is an empty object every time, I think its because of that url change that happens..
Is there some way I can grab the query params before that removal??
EDIT
Basically what is happening is I'm getting authenticated then I get redirected to
localhost:4200/account/login/callback?acessToken="dasdasdaefssves"
but then the route changes to
localhost:4200/account/login/callback
without the query parameters before the activatedRoute function gets a chance to run!
Any help would be appreciated!

Notice your redirect-url is http://localhost:4200/account/login/callback?access_token="dsadsadsadsa dasdsaa"
but angular routes it to localhost:4200/account/callback
NOTE
You don't have that /account/login/callback route defined in angular. But you have /account/callback route instead. Angular tries to resolve the route and redirects its to /account/callback without the queryParams.
Define the route in angular and your issue will be resolved.

I didn't get your complete question but as much as I understand. You want to get query parameter from URL.
To get query parameter from URL You need to do this.
constructor(private activatedRoute: ActivatedRoute){}
This is how you can get all the query params from URL.
this.activatedRoute.queryParamMap
.map((params: Params) => params.params)
.subscribe( (params) => {
if(params && params['access_token']){
console.log(params['access_token']);
}
});

Related

Dynamic route and additional search params in url in NextJS

I'm trying to redirect a user with router.push(url); where an url is like the following: [:lang]/something/[...dynamicRouteParams]?searchParam=true.
There's an issue, that a user is redirected to a page with URL: [:lang]/something/[...dynamicRouteParams]?searchParam=true&lang=something&dynamicRouteParams=item1&dynamicRouteParams=item2.
How can I get rid of the search params related to route params?
Yes, you can do this with getServerSideProps or getStaticProps
export async function getServerSideProps({res, params }) {
//get data you need from API or params
const data = api or params
//now redirect to a link with params
res.setHeader("location", "/URL_WITH_PARAMS");
// you still need 'return' because of react structure
return {
props: {
data
},
}
}
Notice: Router.push() only client-side (rendering)
P.S You can pass any params and retrieve it page you land. Check documentation

Laravel + Angular - Get 401 unauthenticated on 1 GET method

I'm developing a Laravel + Angular app and i'm getting 401 Unauthorized in only 1 GET request.
Here I explain how I developed my authentication and how it work on Backend and Frontend. I wish you can help me.
I use Laravel Sanctum for manage authentication in my app. Here is how I program the backend.
I get users from my BD table:
Note: I have created a separate controller, to separate the authentication functions from the user functions, even so, I have tried to put this function in my AuthController and it has not given me any result.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UsersController extends Controller
{
public function getAllUsers()
{
return User::all();
}
}
As I want you to only be able to retrieve all the DB users if you are authenticated, in my api.php file I put the path inside the middleware:
Route::middleware('auth:sanctum')->group(function()
{
Route::post('logout', [\App\Http\Controllers\AuthController::class, 'logout']);
Route::get('getAuthUser', [\App\Http\Controllers\AuthController::class, 'getAuthUser']);
//Admin actions
Route::post('createUser', [\App\Http\Controllers\AuthController::class, 'createUser']);
Route::get('getAllUsers', [\App\Http\Controllers\UsersController::class, 'getAllUsers']);
});
If I make the request from the Postman everything works correctly, if I am not authenticated it gives me an error and if I have previously authenticated it returns all the DB users just as I expected. By the way, I am using cookies to send the jwt to the Frontend.
The problem is when in my Angular app I request my backend with the GET method to retrieve these users and display them in a table. In addition, the code to retrieve the users is within a condition in which it is looking at whether the user is authenticated or not. The truth is that I do not understand what may be happening.
getUsers(): void
{
//Check if user is authenticated
this.http.get('http://localhost:8000/api/getAuthUser', { withCredentials: true }). subscribe(
(res: any) =>
{
Emitters.authEmitter.emit(true);
Emitters.roleEmitter.emit(res.role);
//Get all users
this.http.get('http://127.0.0.1:8000/api/getAllUsers', { withCredentials: true }). subscribe(
res =>
{
this.users = res;
}
)
},
err =>
{
Emitters.authEmitter.emit(false);
Emitters.roleEmitter.emit("none");
alert("You should be authenticated for this.");
}
);
}
The first request that you see above getAuthUser, makes the request to the Backend in the same way as the second request getAllUsers and the first one works perfectly and the second one does not, it is in which I get an err. I call the getUsers() method in the ngInit().
I hope I have explained myself well. Any information you need to know let me know. Thank you.
The solution was in the request that gave the error to change the path of the api, instead of putting 127.0.0.1 putting localhost.

NextJS: How to send data from one page to another page's getInitialProps function

I'm trying to send data from Page B (login) to Page A's (index) getInitialProps as I need a key for Page A's getInitProps to actually get the props...
I'm currently trying to do it by sending a POST request to a custom express route and use that route to render the Page server side so getInitialProps will run. But the problem is that the browser won't render the page even though it gets built server side.
POST Request From Login Page (happens Client Side):
const headers = {'Content-type': 'application/json; charset=UTF-8'}
await fetch(`${getRootUrl()}/loadKey`, {method: "POST", body: JSON.stringify({key}), headers})
Express Route:
server.post('/loadKey', (req, res) => {
// const {key} = req.body
// console.log(key)
next({dev}).render('/') //index page
})
The key gets logged fine and in the terminal, nextjs is saying that the index page is getting built,and getInitialProps gets ran, but nothing happens on the browser. No redirect.
I've tried using express.redirect, express.render, and I've tried to force a client-side redirect, but for the former two, the same thing happens when I use next.render; the page gets built, getInitialProps runs, but no redirect happens on the browser. And when I force a redirect using Link or Router, then Index's getInitialProps won't get the key passed in from the POST request.
Try this one
server.post('/loadKey', (req, res) => {
const {key} = req.body
// Do whatever you need to do
const actualPage = '/'
const queryParams = { key }
next({dev}).render(req, res, actualPage, queryParams)
})
Now you should have access to key in index page by props.
Your approach will only work for server-side rendered pages (since you need to use req), not for client-side. Even if you get it work once, your logic might break when you try navigating to this route, or you might end up with part of your app being SPA and then some refreshes when visiting this page.
From nextjs documentation:
For the initial page load, getInitialProps will execute on the server only. getInitialProps will only be executed on the client when navigating to a different route via the Link component or using the routing APIs.
Some possible solutions that I've used in the past:
Implement your page B as a component, and call it from page A if certain criteria it's met. Page B won't have getInitialProps but page A does, and it seems like you need to know something from page A getInitialProps in order to correctly render page B, so why not use a single page instead? The user won't know the difference.
Use Redux or the likes. You can store the value of your prop in the store, which it's available globally, even to getInitialProps. But beware! Save your prop to the store before trying to access it on page B. A page's getInitialProps runs before the HoC's.

Rewrite URL in AngularJS Factory

The app I'm developing allows users to change the IP of the server (where the REST API is). This address is stored in a variable that can change, but the problem is that when the services are instantiated, the base URL cannot be changed. Following this answer I was able to change the url of some of the services, but I can't do the same for those who have POST actions.
I've tried several configurations, but there's always a problem. For example, this:
// Services file
app.factory('Bookings', BookingsFactory)
function BookingsFactory($resource, GlobalVariables) {
return $resource('http://:url/api/bookings/:id/', null, {url: '#url'});
}
//Controllers file
Bookings.save(booking, {url: GlobalVariables.IPServer});
Throws this error message "net::ERR_NAME_NOT_RESOLVED", because the request URL is not correct: "http://api/bookings/?end_time=2015-06-30T09:30&name=Reunion&room=1&start_time=2015-06-30T09:43&started=true".
If I call it like this:
//Services file
app.factory('Bookings', BookingsFactory)
function BookingsFactory($resource, GlobalVariables) {
return $resource('http://:url/api/bookings/:id/', {url: '#url'});
}
//Controllers file
Bookings.save({booking: booking, url: GlobalVariables.IPServer});
I get a 400 BAD REQUEST error, and the response asks for content for all the required fields: "This field is required."
I'm using AngularJS v1.3.13. Is there a way to change the base URL in every petition with this approach, even on POST requests? Or even better, is there a way to update the URL in every factory of the application after the app is started?
In an app that I work on I use the $rootScope to hold my base server URL for all requests. I don't know if that's a good way to use $rootScope or not, but what's for sure is that the app is working.
oops sorry I forgot to also add that I can change the base URL while the app is running, which is what you need.

AngularJS unwanted Behavior when reloading page

I'm developing an Angular application with the MEAN stack, so suppose you got an express route that make a query to the databse, the results are sent in the response:
app.get('/api', function(req, res){
Todo.find({}, "", function(err,todos){
if (err)
res.send(err);
res.json(todos);
});
});
In the client-side:
Controller :
...
Todo.get().success(function(data){ //i got the service with the $http call
$scope.todos = data;
});
When I go to localhost:8080/#/api, I can see my partial and the data I requested.
The problem that I'm having is that if I omit the hashtag, i don't see the partial, I only see the response data in JSON format.
I also tried to use html5 mode, but if I reload I got the same behavior.
Any ideas on how can I avoid this behavior??
Anything after the # isn't sent to the server. So when you go to localhost:8080/#/api, expressjs just sees a request to / and returns the AngularJS template. AngularJS then routes the browser page using the /#/api, which called the Todo.get() and (I assume) makes a call to localhost:8080/api, returning the data from the DB.
That's why you only get the data when you omit the hash and when you use html5 mode.
I would suggest changing your API call to:
/api/todos - return data from the db
And change your AngularJS route to just use:
/todos - show the partial and data requested

Categories

Resources