Postman authentication for Odoo 14 - api

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')

Related

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

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.

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":[]
}
}

Socialtables Layout Automation API returns error "Access Denied to this feature"

I am trying to use the Layout Automation feature of the Social Tables API. When I submit my request, the following error response is returned:
{ "message": "Access Denied to this feature" }
This is the only API method that returns this message. I am able to perform other API actions successfully.
Here is the body for my request. Is something wrong with my request, or is there currently an issue with this API method?
{ "attendee_management": true,
"category": "Association",
"end_time": "2017-05-30T18:56:03.318Z",
"name": "Test Event",
"public": true,
"start_time": "2017-05-30T18:56:03.318Z",
"uses_metric": true,
"spaces": [
{
"name": "Test Space",
"venue_id": "131935",
"wizard": {
"attendees": 100,
"setup": "staggered",
"spacing": {
"x": 2,
"y": 2
}
}
}
],
"venue_mapper_version": 0 }
Your request structure is correct, but access to the Layout Automation API endpoints is currently a paid feature. A good next step might be to contact sales and explore the option of adding access to your account.
Cheers,
Robert

GitHub API File Update : "Not Found"

I am attempting to update a file in one of my repos via the API.
Here is my get of that file (works nicely):
curl -XGET 'https://git.fake.local/api/v3/repos/jsmith/repo_version/contents/version.html?ref=gh-pages'
{
"name": "version.html",
"path": "version.html",
"sha": "b1b716105590454bfc4c0247f193a04088f39c7f",
"size": 5,
"url": "https://git.fake.local/api/v3/repos/jsmith/post_version/contents/version.html?ref=gh-pages",
"html_url": "https://git.fake.local/jsmith/post_version/blob/gh-pages/version.html",
"git_url": "https://git.fake.local/api/v3/repos/jsmith/post_version/git/blobs/b1b716105590454bfc4c0247f193a04088f39c7f",
"type": "file",
"content": "aW5pdAo=\n",
"encoding": "base64",
"_links": {
...
}
}
Here is my attempt to update that file via PUT:
curl -XPUT 'https://git.fake.local/api/v3/repos/jsmith/repo_version/contents/version.html?ref=gh-pages' -d '{
"message": "update from api",
"committer": {
"name": "Joe Smith",
"email": "jsmith#fake.com"
},
"content": "bXkgdXBkYXRlZCBmaWxlIGNvbnRlbnRz",
"sha": "b1b716105590454bfc4c0247f193a04088f39c7f"
}'
RESULT:
{
"message": "Not Found"
}
Okay... I think I got it.
From the github doco:
Authentication
There are three ways to authenticate through GitHub API v3. Requests
that require authentication will return 404 Not Found, instead
of 403 Forbidden, in some places. This is to prevent the
accidental leakage of private repositories to unauthorized users.
I was expecting a 403 if Auth was a problem but they are throwing a 404, so basically I probably need to make sure I am auth'd correctly and all will be well.
SOLVED:
I created a personal oauth token (under settings/applications) and add to curl request in header and it all works great.
curl -XPUT -H "Authorization: token MYSECRETTOKEN"