"web/session/authenticate" API endpoint returns an error instead of session_info in ODOO V16 - odoo

I am using odoo V16. When I send a POST request to web/session/authenticate endpoint with the correct user credentials in the body like this:
{
"params": {
"db":<DB>,
"login": <LOGIN>,
"password": <PASSWORD>
}
}
I get a bad response with the error message "'NoneType' object has no attribute 'user'".
The expected behavior is a JSON response with session info like:
{
"jsonrpc": "2.0",
"id": null,
"result": {...}
}
I'm not sure if it is a bug in the new odoo version or I'm doing something wrong. Any help is appreciated. Thanks!
Full error response:
{
"jsonrpc": "2.0",
"id": null,
"error": {
"code": 200,
"message": "Odoo Server Error",
"data": {
"name": "builtins.AttributeError",
"debug": "Traceback (most recent call last):
File "/odoo-16/odoo/http.py", line 1963, in call
response = request._serve_nodb()
File "/odoo-16/odoo/http.py", line 1516, in _serve_nodb
response = self.dispatcher.dispatch(rule.endpoint, args)
File "/odoo-16/odoo/http.py", line 1775, in dispatch
result = endpoint(**self.request.params)
File "/odoo-16/odoo/http.py", line 673, in route_wrapper
result = endpoint(self, *args, **params_ok)
File "/odoo-16/addons/web/controllers/session.py", line 52, in authenticate
print('session_info', env['ir.http'].session_info())
File "/odoo-16/addons/web_tour/models/ir_http.py", line 12, in session_info
result = super().session_info()
File "/odoo-16/addons/web/models/ir_http.py", line 68, in session_info
user = request.env.user
AttributeError: 'NoneType' object has no attribute 'user'
",
"message": "'NoneType' object has no attribute 'user'",
"arguments": [
"'NoneType' object has no attribute 'user'"
],
"context": {}
}
}
}

I faced the same problem, and I found a workaround.
Problem
The problem happen when you call the Odoo API for authentication web/session/authenticate.
We usually send the login data like this in POST request to the server
{"params":{"db":"odoo16","login":"admin","password":"***"}}
I got the error saying:
File "/usr/lib/python3/dist-packages/odoo/addons/mail/models/ir_http.py", line 17, in session_info
user = request.env.user
AttributeError: 'NoneType' object has no attribute 'user'
Solution
This problem Happen when you has many databases in the server, so the request handler fail in fetching the user from env variable.
But if you update your odoo.conf and added a dbfilter = odoo16, and restart the server. you will have only one database like this:
Then if you call the API you will get the CORRECT response and works fine with you,
{
"jsonrpc": "2.0",
"id": null,
"result": {
"uid": 2,
"is_system": true,
"is_admin": true,
"user_context": {
"lang": "en_US",
"tz": "Africa/Cairo",
"uid": 2
},
...
...
...
}
}
Hope this help you fixing your issue till Odoo fix there bug.

Related

how can I manage custom errors coming from the server?

I use Jhipster with react as frontend with loopback as server side, I should show custom error ( ex. tax code already present in the archive).
this is format error
{
"error": {
"statusCode": 422,
"name": "UnprocessableEntityError",
"message": "The request body is invalid. See error object `details` property for more info.",
"code": "VALIDATION_FAILED",
"details": [
{
"path": "partitaIva",
"message": "Partita Iva giĆ  presente",
"code": "CUSTOM_ERROR",
"info": {}
}
]
}
}
There could be more errors too, like for a form.
I want to know how to display the error returned by server.

Withings API Body Sample

I'm trying to get data back from this Withings endpoint: https://developer.withings.com/api-reference/#operation/measure-getmeas
But every combination of things I've tried simply returns:
status body error
503 Invalid Params
This is the most recent body that isn't working: action=getmeas&meastype=meastype&meastypes=11&category=1&startdate=1641168000&enddate=1641254399
For reference: https://developer.withings.com/api-reference/#operation/measure-getmeas
Based on what you posted, the problem is your parameter meastype=meastype. If you remove this then it should run fine.
Assuming you have followed the procedure to get an access token your call from PowerShell would look like this:
Invoke-RestMethod -Method 'Post' -Headers #{ "Authorization" = "Bearer XXXXXXXXXXXXXXXXXX" } -Body "action=getmeas&meastypes=11&category=1&startdate=1641168000&enddate=1641254399" -Uri 'https://wbsapi.withings.net/measure'
This will return a JSON structure as per the docs you link to in the question e.g.
{
"status": 0,
"body": {
"updatetime": "string",
"timezone": "string",
"measuregrps": [
{
"grpid": 12,
"attrib": 1,
"date": 1594245600,
"created": 1594246600,
"category": 1594257200,
"deviceid": "892359876fd8805ac45bab078c4828692f0276b1",
"measures": [
{
"value": 65750,
"type": 1,
"unit": -3,
"algo": 3425,
"fm": 1,
"fw": 1000
}
],
"comment": "A measurement comment"
}
],
"more": 0,
"offset": 0
}
}
If your "measuregrps" is empty (like mine is below) then it means there is no data available for the time period you selected so either your device doesn't record that parameter or the data has not been synchronised to your Withings account.
What I get when I run it (my device doesn't record HR):
status body
------ ----
0 #{updatetime=1641470158; timezone=Europe/London; measuregrps=System.Object[]}
Another option is to use Windows Subsystem for Linux to run curl commands. You essentially get the same thing:
curl --header "Authorization: Bearer XXXXXXXXXXXXXXXXXXXXXX" --data "action=getmeas&meastype=11&category=1&startdate=1609925332&enddate=1641461360" 'https://wbsapi.withings.net/measure'
gives
{
"status":0,
"body":{
"updatetime":1641470640,
"timezone":"Europe\/London",
"measuregrps":[]
}
}

Postman authentication for Odoo 14

How to use postman to test odoo 14.0 controller methods that require authentication?
I used to have a simple request for authentication:
url: http://localhost:8014/web/session/authenticate
method: GET
headers: Content-Type: application/json
body:
{
"jsonrpc": "2.0",
"params": {
"db": "v14pos",
"login": "admin",
"password": "admin"
}
}
After sending the authentication request, postman will set the session_id cookie, and it will work.
But in 14.0 even though the session_id cookie is set, I get the following error when trying to call a url that requires authenticatoin:
{
"jsonrpc": "2.0",
"id": null,
"error": {
"code": 200,
"message": "Odoo Server Error",
"data": {
"name": "odoo.exceptions.AccessDenied",
"debug": "Traceback (most recent call last):\n File \"/home/obi/src/vs/odoo14/addons/http_routing/models/ir_http.py\", line 450, in _dispatch\n cls._authenticate(func)\n File \"/home/obi/src/vs/odoo14/odoo/addons/base/models/ir_http.py\", line 132, in _authenticate\n raise AccessDenied()\nException\n\nThe above exception was the direct cause of the following exception:\n\nTraceback (most recent call last):\n File \"/home/obi/src/vs/odoo14/odoo/http.py\", line 639, in _handle_exception\n return super(JsonRequest, self)._handle_exception(exception)\n File \"/home/obi/src/vs/odoo14/odoo/http.py\", line 315, in _handle_exception\n raise exception.with_traceback(None) from new_cause\nodoo.exceptions.AccessDenied: Access Denied\n",
"message": "Access Denied",
"arguments": [
"Access Denied"
],
"context": {}
}
}
}
This worked for me for version 11.0.
I noticed that the HTTP header in 14.0 includes the cookie in a different way:
Cookie: TWISTED_SESSION=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2luZm8iOnsiYW5vbnltb3VzIjp0cnVlfSwiZXhwIjoxNjAzNjM0NDM5fQ.pJs2oOjQYOQrFnolafUlNZ4Bg4OMJ_itRaZPEUoaLeE; frontend_lang=en_US; fileToken=dummy-because-api-expects-one; tz=Africa/Khartoum; session_id=d36df662e749f368c32dcbecc07bf578dd57de8a
What is the TWISTED_SESSOIN? is it causing the problem?
I found the solution, or rather the problem.
I set wrong value for auth in the controller method, it was:
#http.route('/route/', auth='auth', type='json')
And changed it to:
#http.route('/route/', auth='user', type='json')

cloudwatch metric Filter Pattern doesn't match with the json logs

I am trying to configure a custom metric for my service which will monitor the uptime of the service, I am trying to get the value of status code and raise an alarm if the value is 4* and 5* I am trying to match the statusCode using json filter patter but not able to get it correct
{
"res": {
"statusCode": 500
},
"req": {
"url": "",
"headers": {
"host": "",
"connection": "close",
"user-agent": "",
"accept-encoding": "gzip, compressed"
},
"method": "GET",
"httpVersion": "1.1",
"originalUrl": "",
"query": {}
},
"responseTime": 1,
"requestId": "",
"level": "info",
"message": "",
"timestamp": ""
}
my filter pattern is
I tried these both but none of them worked
{$.res.statusCode = 500}
{($.res.statusCode = 2*)||($.res.statusCode = 5*)}
I am trying to follow https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/FilterAndPatternSyntax.html
It seems to be the issue with json when we copy paste the json doesn't work,
if selected from Log Data to Test dropdown , the filter worked for me in this case.
The answer that worked for me is the one in, AWS Cloudwatch Json Metric Filter Pattern
which quotes,
When using the Test Metric Filter feature in the AWS Console, each log
event has to be in a separate line. You can still run the same test,
but you have to remove all new lines from the sample data.

AWS xray put trace segment command return error

I am trying to send segment doc manually using the CLI with example on this page: https://docs.aws.amazon.com/xray/latest/devguide/xray-api-sendingdata.html#xray-api-segments
I created my own Trace ID and also start and end time.
The command i used are:
> DOC='{"trace_id": "'$TRACE_ID'", "id": "6226467e3f841234", "start_time": 1581596193, "end_time": 1581596198, "name": "test.com"}'
>echo $DOC
{"trace_id": "1-5e453c54-3dc3e03a3c86f97231d06c88", "id": "6226467e3f845502", "start_time": 1581596193, "end_time": 1581596198, "name": "test.com"}
> aws xray put-trace-segments --trace-segment-documents $DOC
{
"UnprocessedTraceSegments": [
{
"ErrorCode": "ParseError",
"Message": "Invalid segment. ErrorCode: ParseError"
},
{
"ErrorCode": "MissingId",
"Message": "Invalid segment. ErrorCode: MissingId"
},
{
"ErrorCode": "MissingId",
"Message": "Invalid segment. ErrorCode: MissingId"
},
.................
The put-trace-segment keep giving me error. The segment doc comply with the JSON schema too. Am i missing something else?
Thanks.
I need to enclose the JSON with "..". The command that works for me was: aws xray put-trace-segments --trace-segment-documents "$DOC"
This is probably due an error in the documentation or that the xray team was using another kind of shell.