how to get the URL valuel for ajax url and flask? - ajax

I want to get the reser Password token from the displayed URL to display it in ajax url
in python file:
#app.route('/resetRequest', methods=['GET', 'POST'])
def resetRequest():
............... # here it generates a token to reset password and send an email to reset the password with the token link.
#app.route('/resetPassword/<token>', methods=['GET', 'POST'])
def resetPassword(token):
...............
After the link displayed link this:
http://<domainName>/resetPassword/eyJhbGciOiJIUzUxMiIsImlhdCI6MTU2Njg3OTQ0OCwiZXhwIjoxNTY2ODgyNDQ4fQ.eyJ1c2VyX2lkIjo0fQ.EedgKKd-WKYWVrSAvLX8lxTdC2AgNqw3QkHDH3j1TzoTa1v8WNIqcZ4YdGwG6MyWuFnQe34A9z4KYQO57cGWBA?
I need to get this token:
eyJhbGciOiJIUzUxMiIsImlhdCI6MTU2Njg3OTQ0OCwiZXhwIjoxNTY2ODgyNDQ4fQ.eyJ1c2VyX2lkIjo0fQ.EedgKKd-WKYWVrSAvLX8lxTdC2AgNqw3QkHDH3j1TzoTa1v8WNIqcZ4YdGwG6MyWuFnQe34A9z4KYQO57cGWBA?
from the URL to display it in ajax url
my ajax
$('#resetTokenForm').on('submit', function(event) {
// define the url variables
var url = window.location.href; // not responding
token = url.split('/').pop(); // not responding
$.ajax({
data : {
newPassword: $('#passwordReset').val(),
confirmNewPassword: $('#confirmPasswordReset').val()
},
type : 'POST',
url : '/resetPassword/'+token
})
I tried to get the URL and use split() but still doesn't work with me...Is there any way to get the token from URL for ajax url?

Related

MSAL and OAuth 2.0 - Request an authorization code programmatically

Goal is to get access token from MSAL programmatically for Cypress e2e tests.
We use V2.0 API.
According to this I first need to get the authorization code: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow#request-an-authorization-code
to get the access token https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow#request-an-access-token
So in order to get authorization code I would need to do this request
// GET
// Line breaks for legibility only
https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&response_type=code
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
&response_mode=query
&scope=openid%20offline_access%20https%3A%2F%2Fgraph.microsoft.com%2Fmail.read
&state=12345
&code_challenge=YTFjNjI1OWYzMzA3MTI4ZDY2Njg5M2RkNmVjNDE5YmEyZGRhOGYyM2IzNjdmZWFhMTQ1ODg3NDcxY2Nl
&code_challenge_method=S256
But this returns text/html so I would need to manually login to get the code.
Is there any way to progammatically to get the authorization code?
This is how I got it solved by creating a login command. The command fetches the token programatically and stores it into localStorage.
import 'cypress-localstorage-commands';
Cypress.Commands.add('login', () => {
const request = {
method: 'POST',
form: true,
url: `https://login.microsoftonline.com/${Cypress.config('tenantId')}/oauth2/v2.0/token`,
body: {
grant_type: 'client_credentials',
client_id: Cypress.config('clientId'),
client_secret: Cypress.config('clientSecret'),
scope: `${Cypress.config('clientId')}/.default`,
},
};
cy.request(request).then(response => cy.setLocalStorage('msal.idtoken', response.body.access_token));
});

Axios AJAX call nulls parameter

I use Vuejs to create my frontend for my project.
At the creation of one component ('TimeCapsy.vue'), I make an AJAX call to my backend like this:
created: function () {
if (verify.verify_login()) {
let token = this.$cookies.get('jwt_us_cas');
let params = {'jwt': token};
console.log(params);
axios({
method: 'post',
url: dev.HOST+'getuserinfoobject',
params: queryString.stringify(params)
})
.then(response => {
console.log(response.data)
})
}
}
As you can see I use the
this.$cookies.get('jwt_us_cas');
to get the a json web token, that I set on the client at the login.
I use the queryString Library to stringify my parameters for my request.
I also tried it without the queryString.stringify(params) call, but I get the same error, e.g. the parameter still turns into null.
When I look at the console log, where I check the params variable, I get this output:
{jwt: "my token comes here"}
So I can see, that it gets the correct value from the cookie.
But when I check the answer from my backend (PHP), I get this error:
Undefined index: jwt in <b>D:\casb\public\index.php</b> on line <b>52</b>
Of course I know that it means, that jwt is null, but I can't understand why.
As I said, right before I make the call I check the params and it shows the token.
I checked the endpoint with Postman and the token as the jwt parameter and it returned a successfull call with the correct answer.
A correct answer is basically just a nested object with some information in it.
My PHP endpoint is pretty basic too:
Router::add('/getuserinfoobject', function () {
$response['response'] = User::getUserInfoObject($_POST['jwt']);
echo json_encode($response);
}, 'post');
So I guess that right before or in my call it nulls my parameter. But I can't understand how, since I make a lot of requests and never had this problem.
From axios docs
params are the URL parameters to be sent with the request
Which means, you should get the value with PHP $_GET.
Or $_REQUEST (which stores both $_GET, $_POST. Also $_COOKIE).
The other hand, you can use data key as docs says
data is the data to be sent as the request body
Only applicable for request methods PUT, POST, and PATCH
So the value would be available in $_POST
axios({
method: 'post',
url: dev.HOST+'getuserinfoobject',
data: {
jwt: token
}
})

How do Laravel get GET request made by vue.js?

Vue.js HTTP call
methods :{
login(){
var data ={
client_id: 2,
client_secret: '5YVQ6rsSehoh5BOWsxAU3KxGeqT1tCRGHn5dx1iX',
grant_type: 'password',
username : this.email,
password: this.password
}
//send a GET request using Vue-Resource
this.$http.get("http://localhost/kubikt2/public/api/login", data)
.then(response=>{
console.log(response)
})
}
}
Laravel
Route::get('api/login',function(Illuminate\Http\Request $req){
$arr["echo"]=$req->all();
$arr["test"]="OK!!";
return json_encode($arr);
}
As you can see, echo $req->getContent(); return nothing in Laravel.
check this out
How do I access the var data sent by Vue.js in Laravel ?
$req->all() is empty because no data is passed!
A GET request only evaluates data passed as query-string in the URI. It acts like the data parameter is null.
You could send your data as query (like "localhost/kubikt2/public/api/login?email"+email+"&someMore"+someMore) or use a POST request (which would be the better option here)

ajax json request , always returning error

Hello i've got a problem with ajax json request. Im always getting an error, even if the requests are succeeded. At the moment i have this code:
function sumbitLoginForm(user, pass) {
if (user.trim() == '' || pass.trim() == '') {
alert("You must enter username and password!");
} else {
$.ajax({
type : 'POST',
url : 'https://url.php',
dataType : 'json',
data : {
userlogin : user,
userpass : pass
},
contentType: "application/json;",
success : function(data) {
$("#images").html("uspeshno");
},
error : function(data) {
$("#images").html("greshka");
}
});
}
return false;
}
$(document).ready(function() {
clearPageInputs();
$("#submitButton").click(function() {
sumbitLoginForm($("#username").val(), $("#password").val());
});
});
Im always getting an error , no matter what username and password i type . But the status of request is changing , if i type correct user and pass i get status 302 Moved temporarly , but when i type wrong user or pass i get status 200 OK . What am i doing wrong ?
PRG Pattern and Ajax
It looks like your server returns a HTTP 200 status code when the userid and password will not validate. This is proper behavior, as HTTP error codes not meant for application errors, but for HTTP protocol errors.
When the userid and password are matched succesfully, you are redirected to another page. This is also normal behavior, e.g. to prevent other people to re-use your login credentials using the back key.
This is called the Post/Redirect/Get pattern.
See: http://en.wikipedia.org/wiki/Post/Redirect/Get
The problem is that the PRG pattern does not play nice with Ajax applications. The redirect should be handled by the browser. It is therefore transparent for the jQuery code. The Ajax html response will be the page that is mentioned in the Location header of the 302. Your Ajax application will not be able to see that it is being redirected. So your are stuck.
In one of my projects I solved this on the server side. If I detected an Ajax call, I would not send a redirect but a normal 200 response. This only works if you have access to the server code.
If you cannot change the redirect for your Ajax calls, then you can parse the response headers or the html to see if you were being redirected and act accordingly. Probably the login will set a cookie, so you might try and look for the presence of that cookie.

Django: relative url not working with post calls in ajax

I am trying to use relative url with a post ajax call as follows:
Current url path:
http://localhost:8000/customer/0/location/0/user/0/
I need to change to different directoy.
var absolute = "http://localhost:8000/customer/0/location/0/line_group/addLine/2/";//+phone_id;
var relative= "../../line_group/addLine/1"
$.get(relative,function(data){
//this works
alert(data);
});
$.ajax({
type: "POST",
url: relative,
data: "test=test1",
error:function(data){
//throws error when using relative path
alert('error');
},
success:function(data){
// works fine when using absolute path
alert('success');
}
});
//same thing using just post
$.post(relative,test,function(data){
//Error on relative path
alert(data);
return false;
});
For my get calls both, absolute and relative url, return data.
But for POST call, when I use relative url, I get internal server error.(absolute URL works fine)
I do not think it has got to do with CSRF, as in my view I have also include #csrf_exempt for test purposes.
(I have included https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax in request)
The chrome debugger gives me the following error message on the post call with relative URL.
Failed to load resource: the server responded with a status of 500 (INTERNAL SERVER ERROR) http://localhost:8000/customer/0/location/0/line_group/addLine/1
However as you can see it does provide me the complete url link, which I want to access.
And when I click directly on the link, I get the data of the page.
The view is really simple:
#csrf_exempt
def addNewLine(request, customer_id, location_id, phone_id,**kwargs):
error_msg = u"No POST data sent."
context = {}
return render_to_response('line_group/mytest.html', context)
Any body has any suggestion, as to why the relative url path fails on POST call?
Thanks in advance..
In Chrome Network section you can preview the error explanation if you have DEBUG=True.
As you have no slash at the end of var relative= "../../line_group/addLine/1", it might be that CommonMiddleware redirects your request. Set APPEND_SLASH = False in project settings if you want to keep your URL as it is.

Resources