Alfresco Update File - ERROR POST - javascript

I'm trying to update a file in Alfresco... And I make this code:
var csrf_header = Alfresco.util.CSRFPolicy.getHeader();
var csrf_token = Alfresco.util.CSRFPolicy.getToken();
function getResponse(pdfbase64) {
var fd = new FormData();
if (Alfresco.util.CSRFPolicy && Alfresco.util.CSRFPolicy.isFilterEnabled())
{
fd.append(csrf_header, csrf_token);
}
fd.append("username", "admin");
fd.append("updatenoderef", nodeRef);
fd.append("filedata", pdfbase64);
fd.append("majorversion", "true");
fd.append("overwrite", "true");
alert(fileUpdateURL);
$.ajax({
url: fileUpdateURL,
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
});
}
The variable pdfbase64 is the content to put on the file (the changes that I made on the file to update the file in base64), but maybe this isn't the right format?, nodeRef is the reference of the file like: "workspace://SpacesStore/4fb1b7e7-2502-4011-8870-17e8d626b93b" and fileUpdateURL is the URL to POST: http://localhost:8080/share/proxy/alfresco/api/upload
Source of params
I got the error:
POST http://localhost:8080/share/proxy/alfresco/api/upload 500
Internal Server Error
javax.servlet.ServletException: Possible CSRF attack noted when
comparing token in session and request parameter. Request: POST
/share/proxy/alfresco/api/upload at
org.alfresco.web.site.servlet.CSRFFilter$AssertTokenAction.run(CSRFFilter.java:845)
at
org.alfresco.web.site.servlet.CSRFFilter.doFilter(CSRFFilter.java:312)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241
) at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.alfresco.web.site.servlet.SSOAuthenticationFilter.doFilter(SSOAuthenticationFilter.java:447)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241
) at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.alfresco.web.site.servlet.MTAuthenticationFilter.doFilter(MTAuthenticationFilter.java:74)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241
) at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2466)
at
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2455)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
EDIT:
If I use
http://localhost:8080/alfresco/service/api/upload
instead of
http://localhost:8080/share/proxy/alfresco/api/upload
I get the error:
{
"status" :
{
"code" : 400,
"name" : "Bad Request",
"description" : "Request sent by the client was syntactically incorrect."
},
"message" : "Required parameters are missing",
"exception" : "",
"callstack" :
[
],
"server" : "Community v5.0.0 (d r99759-b2) schema 8,022",
"time" : "Jan 24, 2016 1:14:41 PM"
}
Can anyone help me?
EDIT2:
I try to make the request with http://localhost:8080/share/proxy/alfresco/api/upload with this:
function getResponse(pdfbase64) {
var csrf_header = Alfresco.util.CSRFPolicy.getHeader();
var csrf_token = Alfresco.util.CSRFPolicy.getToken();
var fd = new FormData();
if (Alfresco.util.CSRFPolicy && Alfresco.util.CSRFPolicy.isFilterEnabled())
{
fd.append(csrf_header, csrf_token);
fileUpdateURL += "?" + Alfresco.util.CSRFPolicy.getParameter() + "=" + encodeURIComponent(Alfresco.util.CSRFPolicy.getToken());
}
fd.append("username", "admin");
fd.append("updatenoderef", nodeRef);
fd.append("filedata", pdfbase64);
fd.append("majorversion", "true");
fd.append("overwrite", "true");
alert(fileUpdateURL);
$.ajax({
url: fileUpdateURL,
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
});
}
But I obtain the error:
{
"status" :
{
"code" : 400,
"name" : "Bad Request",
"description" : "Request sent by the client was syntactically incorrect."
},
"message" : "Required parameters are missing",
"exception" : "",
"callstack" :
[
],
"server" : "Community v5.0.0 (d r99759-b2) schema 8,022",
"time" : "Jan 24, 2016 1:14:41 PM"
}

Try moving these lines inside your function:
var csrf_header = Alfresco.util.CSRFPolicy.getHeader();
var csrf_token = Alfresco.util.CSRFPolicy.getToken();
And if that does not solve your problem and the issue turn out to be not a matter of variable scope for csrf_* vars, then you should try hint (2) from here
UPDATE :
As I explained in our chat you should replace :
fd.append("filedata", pdfbase64);
with :
fd.append("filedata", new Blob([pdfbase64], {type: 'application/pdf'}););

Instead of setting the header, pass the token on the url:
if (Alfresco.util.CSRFPolicy && Alfresco.util.CSRFPolicy.isFilterEnabled())
{
url += "?" + Alfresco.util.CSRFPolicy.getParameter() + "=" + encodeURIComponent(Alfresco.util.CSRFPolicy.getToken());
}
As described in CSRF Policy
When uploading a file by submitting a form with enctype
multipart/form-data it is not possible to set a header on the request,
the reason is not because of the enctype specifically but due to the
fact that its not possible to set a header on any form submission in
the browser.
The other solution is to use Alfresco.forms.Form that takes care of everything.

Related

how to consolelog all the the parsed data in json

$.ajax(
{ type : "POST"
, url : "my url link"
, data : fd
, dataType : 'json'
, contentType : false // The content type used when sending data to the server.
, cache : false // To unable request pages to be cached
, processData : false // To send DOMDocument or non processed data file it is set to false
, success: function(data, textStatus, jqXHR)
{
reset_info(true);
msg = "<strong>SUCCESS: </strong>";
if (!(data.sa === null))
{
//add and update case forceDelete=> !(data.notice===null)
msg = "<strong>Submitted Successfully</strong><br/>Your Application ID is: " + data.sa;
}
$("#name").val('');
}
How to console log all the data that i sent through this form?
multiple user fill this form and submit. and get a registration id.

Subscription failed using Stripe API in Google Apps Script

I'm trying to make an add-on using Google Apps Script & Stripe where user can subscribe for an item as an yearly subscription. Every time I purchase the subscription from Stripe checkout, I get error like this,
{
"error": {
"code": "parameter_unknown",
"doc_url": "https://stripe.com/docs/error-codes/parameter-unknown",
"message": "Received unknown parameter: #45b5a607",
"param": "#45b5a607",
"type": "invalid_request_error"
}
}
When I check the log in Stripe Dashboard I get the POST body like this,
{
"items": "[Ljava.lang.Object",
"#45b5a607": null,
"customer": "cus_Dix0eSYM5qP0kx"
}
This is my code in Google Apps Script,
var headers = {
"Authorization" : "Basic " + Utilities.base64Encode(USERNAME + ':' + PASSWORD)
};
var customer = {
'email': customerEmail,
'source': token
};
var optCreate = {
'method' : 'post',
"headers" : headers,
'contentType': 'application/x-www-form-urlencoded',
'payload' : customer,
'muteHttpExceptions' : true
};
var createCustomer = UrlFetchApp.fetch(urlCreate, optCreate);
var respCreate = JSON.parse(createCustomer.getContentText());
var customerId = respCreate.id;
if (customerId == null) { return "Error"; }
var data = {
"customer" : customerId,
"items" : [
{
"plan" : "plan_Diuw7CdAGcSrhm"
}
]
};
var options = {
'method' : 'post',
"headers" : headers,
'contentType': 'application/x-www-form-urlencoded',
'payload' : data,
'muteHttpExceptions' : true
};
var response = UrlFetchApp.fetch(url, options);
var resp = JSON.parse(response.getContentText());
Logger.log(resp);
I think I must be doing something wrong in my data JSON object. The items field is not working correctly that's why POST body is weird. What is the correct way here?
You need to stringify the payload.
var options = {
'method' : 'post',
"headers" : headers,
'contentType': 'application/x-www-form-urlencoded',
'payload' : JSON.stringify(data),
'muteHttpExceptions' : true
};
It looks like you're POSTing JSON data, but Stripe's API does not accept JSON — you need to use form encoding. i.e your code needs to set data to be in this format:
items[0][plan]=plan_CvVNfwZ4pYubYg&customer=cus_Diygqj4wAq6L9T
You can refer to cURL examples in Stripe's API docs for this. Generally you should use an official library to simplify making API requests, but that may not be possible with Apps Script.

How do I bind object property and send the data via ajax?

I'm struggling with sending a data which contains object as a member property.
This is the domain class.
public class Timeline extends Post{
String picture;
User user;
int like;
...
(getters and setters)
}
And I've got the JSON data with this code already so I could get the data from 'obj' variable.
var obj;
$.ajax({
method: "GET",
dataType: "json",
url: serverRoot + "/json/auth/loginUser",
async: false
})
.done(function(data) {
obj = data;
});
And the returned data looks like this.
"user" : {
"userNo" : 1,
"name" : "user01",
...
}
The next JSON data is the data I'd like to send to a server.
{
"no" : 23,
"content" : "hihi",
"createdData" : "2018-07-22",
"picture" : null,
"user" : {
"userNo" : 1,
"name" : "user01",
... **obj JSON data I got above**
}
}
And this is the codes to send to a server.
(Here is the thing I've been stuck)
$("#sh-tl-post-btn").click(() => {
$.ajax({
type: 'POST',
url: '../../../json/timeline/add',
data: {
picture: $('#sh_tl_upload').val(),
content: $('#sh_tl_post_write').val(),
**user: [{"userNo":obj.userNo}]**
},
}).done(function() {
console.log("inserted.");
location.href = "timeline.html"
});
});
The Mapper file looks like this.
<insert id="insert" parameterType="Timeline">
<choose>
<when test="picture != ''">
insert into TML(tmlno, uno, tmlpath)
values(#{no}, #{userNo}, #{picture})
</when>
<otherwise>
insert into TML(tmlno, uno)
values(#{no}, #{userNo})
</otherwise>
</choose>
</insert>
I've been searching what to write on here instead of
user: [{"userNo":obj.userNo}] , this...
I've been trying
user : {"userNo" : obj.userNo}
user.userNo : obj.userNo
user.[0].userNo : obj.userNo
...
but the console keeps saying
[Request processing failed; nested exception is
org.springframework.beans.InvalidPropertyException:.....
this kind of errors.
Is there anyone could help me how to bind the nested object's property via ajax
JSON data? Thanks in advance.

jQuery .ajax() POST Request throws 405 (Method Not Allowed) but GET doesn't

I am working on form updation with ajax. It works fine when i use GET method in ajax but it throws error 405 method not allowed when i use Post method. I am testing this on Localhost. I have done this before in localhost and it worked fine. And by the way i am using Laravel 5.2 for this.
here is my ajax code.
$('#update-modal').on('click',function(){
$.ajax({
method : "POST",
url : updateURL,
data : { client_id : $('#client_id').val(),
client_name : $('#client_name').val(),
client_business : $('#client_business').val(),
client_ref : $('#client_ref').val(),
gmail_mail : $('#gmail_mail').val(),
gmail_pass : $('#gmail_pass').val(),
client_dob : $('#client_dob').val(),
client_addr : $('#client_addr').val(),
client_no1 : $('#client_no1').val(),
client_no2 : $('#client_no2').val(),
domain_name : $('#domain_name').val(),
domain_p_date : $('#domain_p_date').val(),
domain_reg : $('#domain_reg').val(),
domain_ex_date : $('#domain_ex_date').val(),
domain_acc_email : $('#domain_acc_email').val(),
domain_acc_pass : $('#domain_acc_pass').val()},
_token : token
})
.done(function(msg){
console.log(msg['message']);
});
});
Here is my script used inside the view
<script>
var updateURL = '{{ route('updateDomain') }}';
var token = '{{Session::token()}}';
</script>
here is my route
Route::post('/updateDomainModal' ,function(\Illuminate\Http\Request $request){
return response()->json(['message'=> $request['client_name']]);
})->name('updateDomain');
When the method inside ajax function and Route is changed to GET, It print the client's name passed in the console But when the same is done with POST method it throws the error This is the error details
jquery.min.js:2 GET http://localhost:8000/updateDomainModal?client_id=4&client_name=ABCD&client…2+15%3A01%3A40&domain_acc_email=abc123%40gmail.com&domain_acc_pass=123456 405 (Method Not Allowed)
You are wrongly using an } in the line starting with domain_acc_pass. You should use that '}' after assigning the token value. Now, the token won't send to the target, which is required.
Use type "POST'
$.ajax({
type : 'POST',
url : updateURL,
data : { client_id : $('#client_id').val(),
client_name : $('#client_name').val(),
client_business : $('#client_business').val(),
client_ref : $('#client_ref').val(),
gmail_mail : $('#gmail_mail').val(),
gmail_pass : $('#gmail_pass').val(),
client_dob : $('#client_dob').val(),
client_addr : $('#client_addr').val(),
client_no1 : $('#client_no1').val(),
client_no2 : $('#client_no2').val(),
domain_name : $('#domain_name').val(),
domain_p_date : $('#domain_p_date').val(),
domain_reg : $('#domain_reg').val(),
domain_ex_date : $('#domain_ex_date').val(),
domain_acc_email : $('#domain_acc_email').val(),
domain_acc_pass : $('#domain_acc_pass').val()},
_token : token
});
If you submit form
$("#form-name" ).submit(function(ev) {
ev.preventDefault();
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: 'POST',
data: postData,
success: function(data, textStatus, jqXHR)
{
location.reload();
},
error: function(jqXHR, textStatus, errorThrown)
{
consonle.log("error");
}
});
});

Send datas to JSON with jquery

i'm coding a script that send datas (nickname & score) to a JSON file in Jquery but i'm having trouble to make it work.
Here is my Jquery :
function addInfos() {
var nicknameSubmit = $(".nickname").val();
var scoreSubmit = $(".score").val();
var newScore = {
Nickname : nicknameSubmit,
Score : scoreSubmit
};
$.ajax({
url: './js/scores.json',
type: "POST",
data: JSON.stringify(newScore),
contentType: "application/json",
complete: console.log(nicknameSubmit + " " + scoreSubmit )
});
};
$(".submit").click(function(){
addInfos();
});
I used Jquery.post for this ( http://api.jquery.com/jquery.post/ )
And here is my JSON file :
[{
"Nickname" : "Alex",
"Score" : "1000"
},
{
"Nickname" : "Tom",
"Score" : "0"
}]
The script find the JSON file, it show me the correct values in the console but it doesn't add the values to the JSON file...
Can anyone know where i'm wrong ? Do i do the request properly ?
Thanks in advance,
remid
Unless your server is webdav compatible, you can't save a file on it via HTTP.
You need to create a server side script (perhaps PHP) that reads "POSTed"values and add them in your JSON file.

Categories