symfony 3.4 - vuejs, logged user data under vuejs unavailable - fosuserbundle

Like in the title. I have a problem with recieving logged user data under vuejs.
I use
- FOS User - to login
- Fos Rest - to api
- Jms Serializer
This is my function to take data from database
public function getUser()
{
$userId = $this->container->get('security.token_storage')->getToken()->getUser('id');
return $this->repository->FindOneBy(['id' => $userId]);
}
Now, when it is in form like above, console.log return an empty object, in vuejs. However, when I change $userId to 5 for example -
$this->repository->FindOneBy(['id' => 5]);
object is available with data.
now. I checked api addres in both cases - works. i also return a dump in both cases. everything in both cases is identical.
this is my log
when $userId
127.0.0.1 - - [07/Apr/2018:03:55:24 +0200] "GET /ekopanel2/web/app_dev.php/api/v1/greenker/user HTTP/1.1" 204 380 "http://localhost:8080/greenker" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:59.0) Gecko/20100101 Firefox/59.0"
and this is when 5
127.0.0.1 - - [07/Apr/2018:03:55:34 +0200] "GET /ekopanel2/web/app_dev.php/api/v1/greenker/user HTTP/1.1" 200 895 "http://localhost:8080/greenker" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:59.0) Gecko/20100101 Firefox/59.0"
i noticed that status code is different, when 5 it is 200 and working, when $userId, status code is 204, so it looks like it gets empty data.
Can you help please?

Let's suppose you are logged in.
If not, $this->container->get('security.token_storage')->getToken()->getUser() would return the string "anon."
Have you tried with this :
$userId = $this->container->get('security.token_storage')->getToken()->getUser()->getId();
Be carefull to check if the user is logged in. Otherwise, it will throw an exception like "Call to a member function getId() on string".

Related

Multiple Request with Flask API and Reactjs

Below is the request that I did. Everything works except when I try the put /stats-batch which shows this error. I don't know what is the options that is being displayed, I only noticed it today.
The /stats-batch also just prints hello when access
27.0.0.1 - - [25/May/2021 16:20:46] "OPTIONS /user HTTP/1.1" 200 -
127.0.0.1 - - [25/May/2021 16:20:46] "POST /user HTTP/1.1" 200 -
127.0.0.1 - - [25/May/2021 16:20:48] "OPTIONS /product HTTP/1.1" 200 -
127.0.0.1 - - [25/May/2021 16:20:48] "GET /product HTTP/1.1" 200 -
127.0.0.1 - - [25/May/2021 16:20:48] "OPTIONS /new-batch HTTP/1.1" 200 -
127.0.0.1 - - [25/May/2021 16:20:48] "GET /new-batch HTTP/1.1" 200 -
127.0.0.1 - - [25/May/2021 16:21:21] "OPTIONS /new-batch HTTP/1.1" 200 -
oks
127.0.0.1 - - [25/May/2021 16:21:21] "PUT /new-batch HTTP/1.1" 200 -
127.0.0.1 - - [25/May/2021 16:21:21] "GET /new-batch HTTP/1.1" 200 -
127.0.0.1 - - [25/May/2021 16:21:43] "OPTIONS /stats-batch HTTP/1.1" 200 -
127.0.0.1 - - [25/May/2021 16:21:44] "PUT /stats-batch HTTP/1.1" 500 -
Traceback (most recent call last):
File "C:\Users\USER\Desktop\Allen\santeh\env\Lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
.......
.......
File "C:\Users\USER\AppData\Local\Programs\Python\Python39\Lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type function is not JSON serializable
I call this functions with a button click using axios like this. config has the authorization header just like all the other request
const startBatch = async () => {
const status = 'start'
await axios
.put('http://127.0.0.1:5000/stats-batch', status, config)
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
})
}
The console shows the error that No Access-Control-Allow-Origin header is present on the requested resource.
I also have flask_cors installed and the other axios request is working. I don't know what cause this error if its the backend or the frontend.
I see an issue; "/new-batch" endpoint is throwing 500 exceptions, which could be related to "Object of type function is not JSON serializable".
Based on the description / Error "No Access-Control-Allow-Origin header is present on the requested resource" message what I understand is
CORS configuration has been missed for PUT VERB.
Because you wrote that rest of the endpoints work without issues, only PUT on this specific "/new-batch" endpoint fails.
Options: In CORS, a preflight request is sent with the OPTIONS method so that the server can respond if it is acceptable to send the request.
URL: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS

python flask + Server Sent Events(SSE) in Google App Engine(GAE)

Hi I am trying to do SSE(Server-Sent Events) with python flask quite similar to this question
I am using SSE to plot a real-time graph in the web app.
My codes are working fine when applied in local, but when I deploy it in GAE(Google App Engine), the data does not seem to be returned(yield)
I found that I should make the response header as following
X-Accel-Buffering: no
in this guide here
So, I tried this code on "main.py"
# render "plot.html" and plot the real-time graph
# plot.html gets the value from /chart-data event stream, and update the graph
#app.route('/plot_graph', methods=["GET", "POST"])
def plot_graph():
return render_template('plot.html')
#app.route('/chart-data')
def chart_data():
def generate_random_data():
while True:
# generating random data
json_data = json.dumps(
{'time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 'value': random() * 100})
yield f"data:{json_data}\n\n"
time.sleep(0.5)
resp = Response(generate_random_data(), mimetype='text/event-stream')
resp.headers["X-Accel-Buffering"] = "no"
return resp
Also, in "plot.html" file, it is getting values from /chart-data like this
const source = new EventSource("/chart-data");
source.onmessage = function (event) {
const data = JSON.parse(event.data);
...
}
and this also works well when executed in local machine, but not working on GAE..
for the logs and error messages, when I tried the code on local machine,
and went to the root dir, /plot_graph, /chart-data, the log looks like
127.0.0.1 - - [03/Jul/2020 14:14:19] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [03/Jul/2020 14:14:20] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [03/Jul/2020 14:14:23] "GET /plot_graph HTTP/1.1" 200 -
127.0.0.1 - - [03/Jul/2020 14:14:24] "GET /chart-data HTTP/1.1" 200 -
127.0.0.1 - - [03/Jul/2020 14:15:04] "GET /chart-data HTTP/1.1" 200 -
when I went into /plot_graph, I see a GET request from /chart-data and it works fine(/plot_graph shows a real-time graph). Also, when I go into /chart-data, I can see yielded values being displayed on the web.
In the GAE logs,
2020-07-03 05:22:23 default[20200703t141524] "GET / HTTP/1.1" 200
2020-07-03 05:22:23 default[20200703t141524] "GET /favicon.ico HTTP/1.1" 404
2020-07-03 05:22:38 default[20200703t141524] "GET /plot_graph HTTP/1.1" 200
for the GAE, even if I entered /plot_graph, the GET request does not seemed to be happening. and since it is not getting any values, the graph is not plotted(only the frame for the graph is displayed).
Also, I tried to go into /chart-data of GAE web server, but I could not enter and cannot see any GET request in the logs as I saw on the server on local machine.
Please can you help me with this problem?

Can't call a function to create a object on #route function even tough it works on python interpreter

I'm creating a database for a school project and doing the backend between it and the app.(I'm using Flask and SQLAlchemy for it)
So the problem is that i can't call a function User(entrances), the function User() is a construction function used to create and object ,well it's what it looks like for me at least. But the function itself works when i do it in the interpreter.
WHY can i do it in my interpreter and can't do it on the flask tiny web framework???
here's the github link:BackEndRepository
Before taking a look at the samples here's the output form the interpreter that works:
Interperter
here's the code for my route:
from app import app,db
from models import User
from flask import render_template,Flask,request,redirect,url_for
#app.route('/index')
def index():
return "Hello, World!"
#app.route('/teste')
def teste():
users = db.session.query(User).all()
return u"<br>".join([u"{0}: {1}".format(user.name, user.email) for user in users])
#app.route('/teste2')
def teste2():
teste=User(name='susan',email='susan#example.com')
#u = User(name=request.args.get('1'), email=request.args.get('2'))
return teste
And here is the code for my model:
from app import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
def __init__(self,name,email):
self.name = name
self.email= email
def __repr__(self):
return '<User {0} {1}>'.format(self.name,self.email)
so i run in my terminal "flask run" and get the error in response:(theese is all the log i had after doing what i explained)
#Arthur:~/Public/ProjetoBackEnd(Original)$ flask run
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [21/Nov/2018 14:24:41] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [21/Nov/2018 14:24:41] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [21/Nov/2018 14:24:46] "GET /index HTTP/1.1" 200 -
127.0.0.1 - - [21/Nov/2018 14:24:46] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [21/Nov/2018 14:24:52] "GET /teste HTTP/1.1" 200 -
127.0.0.1 - - [21/Nov/2018 14:24:53] "GET /favicon.ico HTTP/1.1" 404 -
[2018-11-21 14:24:57,004] ERROR in app: Exception on /teste2 [GET]
Traceback (most recent call last):
File "/home/arthur/.local/lib/python2.7/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/home/arthur/.local/lib/python2.7/site-packages/flask/app.py", line 1816, in full_dispatch_request
return self.finalize_request(rv)
File "/home/arthur/.local/lib/python2.7/site-packages/flask/app.py", line 1831, in finalize_request
response = self.make_response(rv)
File "/home/arthur/.local/lib/python2.7/site-packages/flask/app.py", line 1982, in make_response
reraise(TypeError, new_error, sys.exc_info()[2])
File "/home/arthur/.local/lib/python2.7/site-packages/flask/app.py", line 1974, in make_response
rv = self.response_class.force_type(rv, request.environ)
File "/home/arthur/.local/lib/python2.7/site-packages/werkzeug/wrappers.py", line 921, in force_type
response = BaseResponse(*_run_wsgi_app(response, environ))
File "/home/arthur/.local/lib/python2.7/site-packages/werkzeug/test.py", line 923, in run_wsgi_app
app_rv = app(environ, start_response)
TypeError: 'User' object is not callable
The view function did not return a valid response. The return type must be a string, tuple, Response instance, or WSGI callable, but it was a User.
127.0.0.1 - - [21/Nov/2018 14:24:57] "GET /teste2 HTTP/1.1" 500 -
127.0.0.1 - - [21/Nov/2018 14:24:57] "GET /favicon.ico HTTP/1.1" 404 -
JUST highlighting the part that's bugging me out the most here:
TypeError: 'User' object is not callable
The problem is here:
#app.route('/teste2')
def teste2():
teste=User(name='susan',email='susan#example.com')
#u = User(name=request.args.get('1'), email=request.args.get('2'))
return teste
You are returning teste which is a User. That's not a valid return type here as the error tells you:
The return type must be a string, tuple, Response instance, or WSGI callable, but it was a User.
It's fine to return a string for example, so this should work:
#app.route('/teste2')
def teste2():
teste=User(name='susan',email='susan#example.com')
#u = User(name=request.args.get('1'), email=request.args.get('2'))
return teste.name

camel netty4http and camel rest dsl: Get remote address

I'm looking for a way to get the ip address with camel rest dsl and the Netty4 Http component.
I checked on the documentation, I've put a breakpoint on my rest and checked on the headers, the properties,...everywhere, and couldn't find a proper way get this information.
Headers log:
GET: http://localhost:8080/category,
{Accept=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8, Accept-Encoding=gzip, deflate, sdch, Accept-Language=fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4, breadcrumbId=ID-nateriver-54582-1445489005229-0-1, CamelCATEGORY_ACTION=listAction, CamelHttpMethod=GET, CamelHttpPath=, CamelHttpUri=/category, CamelHttpUrl=http://localhost:8080/category, CamelJmsDeliveryMode=2, Connection=keep-alive, Content-Length=0, Cookie=JSESSIONID=fowfzar8n09e16ej9jui6nmsv, Host=localhost:8080, JMSCorrelationID=null, JMSDeliveryMode=2, JMSDestination=topic://Statistics, JMSExpiration=0, JMSMessageID=ID:nateriver-54592-1445489009836-3:1:7:1:1, JMSPriority=4, JMSRedelivered=false, JMSReplyTo=null, JMSTimestamp=1445489017233, JMSType=null, JMSXGroupID=null, JMSXUserID=null, Upgrade-Insecure-Requests=1, User-Agent=Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36}
You should get two headers populated:
CamelNettyLocalAddress and CamelNettyRemoteAddress.
See here where the debug log of netty-http shows this clearly.
http://camel.465427.n5.nabble.com/How-to-create-case-insensitive-URI-route-with-netty4-http-td5766517.html#a5766558

C code : cURL POST

I have some hard time with my code. I'm trying to connect to a website using cURL.
Let's see the code of the website :
<td class="input "><input tabindex="1" class="text" name="authentificationLogin" id="authentificationLogin" type="text"/></td>
<td class="input "><input tabindex="2" class="text" autocapitalize="off" autocorrect="off" name="authentificationPassword" id="authentificationPassword" type="password"/></td>
<td class="input "><input name="authentificationRedirection" id="authentificationRedirection" type="hidden" value="http://myWebsite/?Redirect"/><input name="authentification08e11696a1" id="authentification08e11696a1" type="hidden" value=""/><br/><button class="button button-style" type="submit" name="Submit" id="authentificationSubmit" onclick="return lock("id:authentificationSubmit");">
Now, let's see my code :
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
#include <curl/easy.h>
void Demarrage(void){
CURLcode res;
const char *userAgentMozilla = "Mozilla/5.0 (Windows; U; Windows NT 6.1; fr; rv:1.8.1.20) Gecko/20081217 Firefox/2.0.0.20"; // set userAgent
const char *data = "&to=gaia&login=myName&password=myPassword&isBoxStyle="; // set the data to send
curl_global_init(CURL_GLOBAL_ALL);
CURL *handle;
handle = curl_easy_init();
curl_easy_setopt(handle,CURLOPT_COOKIESESSION,1); // clean up session.
curl_easy_setopt(handle,CURLOPT_USERAGENT,userAgentMozilla); // set the user agent
curl_easy_setopt(handle,CURLOPT_URL,"http://myWebsite.com/logIn"); // set the url
curl_easy_perform(handle); // perform
// I must to take cookies that the website gave to me.
curl_easy_setopt(handle,CURLOPT_POSTFIELDSIZE,58L); // size of the request.
curl_easy_setopt(handle,CURLOPT_POSTFIELDS,data); // aray of the POST request
curl_easy_perform(handle); // perform and connect to the Website
}
I also use Wireshark,
What i have when i do it manually ( that's printable caract only )
$QU9Eq#*Y!P9?PDpPOST /site/doLogIn HTTP/1.1
I don't know what it is.
Host: myWebsite.com
The host.
Connection: keep-alive
Content-Length: 140
Accept: text/html, */*; q=0.01
Some formalities I think.
Origin: http://myWebsite.com
Host again. with type.
X-Requested-With: XMLHttpRequest
I don't know what it is.
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36
User Agent. I don't really understand why there is 4 types of user agent.
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://myWebsite/logIn
Accept-Encoding: gzip, deflate
Accept-Language: fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
Formalities.
Cookie: advertisementcookie=1; __utma=108225430.1356423961.1414526372.1414789248.1414921274.6; __utmz=108225430.1414526372.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); sessionprod=oekotlo6tfbujtpfirddvvqlp1; _gat=1; _ga=GA1.2.1356423961.1414526372
Well, that start to be interessant. This is cookies sent to the website during the HTTP request. They changed each time I sent a new HTTP request.
&to=gaia&login=myName&password=myPassword&redirection=http%3A%2F%2FmyWebsite.com%2%2F%3Fidentification%3D1&isBoxStyle=&08e11696a1=
This is the principal of my request. Name and password are sent to the server.
I have no error but my code is not working because my hour of last connection isn't change... Probably because i don't set cookies.
I'm really inexperienced and I know I'm doing probably so many stupid error. But, please, if you have any informations, answer to my question...
Have you some genious ideas for repair this code ?
Best regards.
Xavier.
You want to set the string "&to=gaia&login=myName&password=myPassword&redirection=http%3A%" ... to the CURLOPT_POSTFIELDS option for such a "regular" POST.
The CURLOPT_HTTPPOST option that you use (in combination with curl_formadd etc) is for multipart formposts, which you obviously don't want!
I'm happy to told you that i finally did it.
Thanks Daniel for your library and example on your website :
char *data = &togaia&login=login&password=pswd&isBoxStyle=
const char *userAgentMozilla = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6";
CURLcode res;
CURLcode err;
curl_easy_setopt(handle,CURLOPT_COOKIESESSION,1); // clean up session.
curl_easy_setopt(handle,CURLOPT_COOKIEJAR,"cookie.txt"); // save cookie. use it for each action on a website when you are register, juste doing curl_easy_setopt(handle,CURLOPT_COOKIE,"cookie.txt");
curl_easy_setopt(handle,CURLOPT_USERAGENT,userAgentMozilla); // set the user agent
curl_easy_setopt(handle,CURLOPT_URL,"http://thewebsite/site/doLogIn"); // set the url // perform
curl_easy_setopt(handle,CURLOPT_POSTFIELDSIZE,strlen(data)); // size of the request.
curl_easy_setopt(handle,CURLOPT_POSTFIELDS,data); // aray of the POST request
res = curl_easy_perform(handle); // perform and connect to the Website
If you have probleme, do no hesitate to post, and i will try to help you :)
It is the answer to connect to the website, you can also look what i sniffed to have an example ;)

Resources