make a controller in odoo to handle a json - json

I am new to odoo and I have created a module with the scaffold command as follows:
"C:\Program Files (x86)\Odoo 11.0\python\python.exe" "C:\Program Files (x86)\Odoo 11.0\server\odoo-bin" scaffold api4"C:\Users\Carlos\Desktop\custom_addons"
and when i create this base redirect controller it works fine
# - * - coding: utf-8 - * -
from odoo import http
from odoo.http import request
import json
class Api4 (http.Controller):
    # http.route ('/ api4 / api4 /', auth = 'public', website = True)
    def index (self):
        return request.redirect ('/ web /')
but when I create another # http.route to receive a json and be able to process your data it doesn't work for me and the one I have done previously stops working.
    # http.route ('/ api / json_get_request', auth = 'public', type = 'json', csrf = False)
def jsontest (self, ** kw):
     return {'attribute': 'test'}
the code is basic but I wanted to see if sending any json would return {'attribute': 'test'} and instead it returned this:
{
    "jsonrpc": "2.0",
    "id": null,
    "error": {
        "code": 404,
        "message": "404: Not Found",
        "data": {
            "name": "werkzeug.exceptions.NotFound",
            "debug": "Traceback (most recent call last): \ n File \" C: \\ Program Files (x86) \\ Odoo 11.0 \\ server \\ odoo \\ http.py \ ", line 653, in _handle_exception \ n return super (JsonRequest, self) ._ handle_exception (exception) \ n File \ "C: \\ Program Files (x86) \\ Odoo 11.0 \\ server \\ odoo \\ http.py \", line 312, in _handle_exception \ n raise pycompat.reraise (type (exception), exception, sys.exc_info () [2]) \ n File \ "C: \\ Program Files (x86) \\ Odoo 11.0 \\ server \\ odoo \\ tools \\ pycompat.py \ ", line 86, in reraise \ n raise value.with_traceback (tb) \ nwerkzeug.exceptions.NotFound: 404 Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. \ n ",
            "message": "404 Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.",
            "arguments": [],
            "exception_type": "internal_error"
        },
        "http_status": 404
    }
}
error postman

Add -d or --db-filter in your odoo-bin command to single out only one database. For e.g. python3 odoo-bin --addons-path addons,mymodules -d newdatabase. As far as I know, api with auth='public' raise this kind of error when there are multiple odoo databases.
Alternative solution is you can use endpoint with auth='user'. You will need to get login cookie first tho. More on this: How to connect to Odoo database from an android application

Hello Carlos Alberto Florio Luis,
1) Clear all the cache and history in your browser.
2) keep only one database for use and remove other databases
or
1) Use **--db-filter dabase-name** to load a single database.
And make sure your route defines there has no whitespace opt-in('/api/json_get_request').
Thanks

Related

AWS SAM CLI DEPLOYMENT - Issues Parsing Out of the Box secret = get_secret_value_response['SecretString']

I am very green when it comes to Python - so bare with me.
Using the out of the Box Python3 Sample Code provided by AWS to return the 'SecretString' from the AWS: Secrets Manager Service.
No issues there .. I get the returned object (note I have blanked out some details)
{"username":"postgres","password":"XXXXXXXXX","engine":"postgres","host":"srdataset.XXXXXXXXX.ap-southeast-2.rds.amazonaws.com","port":5432,"dbInstanceIdentifier":"srdataset"}
detail are all correct.
I am then using json.loads() to parse the above into my next function so I can extract the details like so
# request details
login_details = get_secret("pg_srdataset_login_details")
# load json
y = json.loads(login_details)
# extract result is a Python dictionary:
print(y["username"])
This again all works fine in my IDE (PyCharm). I can run the code, build in a Docker container .. and I then use the PyCharm AWS SAM CLI to deploy the code to the cloud .. no issues.
However when I test the function in AWS the code bugs out on the line y = json.loads(login_details) step.
the error being ..
{
"errorMessage": "Expecting value: line 1 column 1 (char 0)",
"errorType": "JSONDecodeError",
"stackTrace": [
" File \"/var/task/update_sp_changes.py\", line 229, in lambda_handler\n y = json.loads(login_details)\n",
" File \"/var/lang/lib/python3.8/json/__init__.py\", line 357, in loads\n return _default_decoder.decode(s)\n",
" File \"/var/lang/lib/python3.8/json/decoder.py\", line 337, in decode\n obj, end = self.raw_decode(s, idx=_w(s, 0).end())\n",
" File \"/var/lang/lib/python3.8/json/decoder.py\", line 355, in raw_decode\n raise JSONDecodeError(\"Expecting value\", s, err.value) from None\n"
]
}
To test this I also copied the JSON 'SecretString' returned from AWS, hard coded it as a variable, then passed this variable directly into the y = json.loads(login_details) step. Tested again and works a treat.
What am I doing wrong - how can I work around this issue.
For reference, I'd share Lambda print debug code.
Preparation:
from the Lambda-py38 initial state, SecretsManagerReadWrite policy is attached to Lamda
set SecretId and VersionId
Output:
json.loads() works for plaintext
print() output almost the same for plain_text:str and secret_dict:dict. (Difference is quotation:single/double. Which are treated as the same string when copy-pasted.)
import json
import boto3
def lambda_handler(event, context):
client = boto3.client('secretsmanager')
response = client.get_secret_value(
SecretId='arn:aws:secretsmanager:xxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
VersionId='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
VersionStage='AWSCURRENT'
)
print("type of response: ", type(response))
print("response: ", response)
plaintext = response['SecretString']
print("type of plaintext: ", type(plaintext))
print("plaintext: ", plaintext)
secret_dict = json.loads(plaintext)
print("type of secret_dict: ", type(secret_dict))
print("secret_dict: ", secret_dict)
return 200

Parse JSON with missing fields using cjson Lua module in Openresty

I am trying to parse a json payload sent via a POST request to a NGINX/Openresty location. To do so, I combined Openresty's content_by_lua_block with its cjson module like this:
# other locations above
location /test {
content_by_lua_block {
ngx.req.read_body()
local data_string = ngx.req.get_body_data()
local cjson = require "cjson.safe"
local json = cjson.decode(data_string)
local endpoint_name = json['endpoint']['name']
local payload = json['payload']
local source_address = json['source_address']
local submit_date = json['submit_date']
ngx.say('Parsed')
}
}
Parsing sample data containing all required fields works as expected. A correct JSON object could look like this:
{
"payload": "the payload here",
"submit_date": "2018-08-17 16:31:51",
},
"endpoint": {
"name": "name of the endpoint here"
},
"source_address": "source address here",
}
However, a user might POST a differently formatted JSON object to the location. Assume a simple JSON document like
{
"username": "JohnDoe",
"password": "password123"
}
not containing the desired fields/keys.
According to the cjson module docs, using cjson (without its safe mode) will raise an error if invalid data is encountered. To prevent any errors being raised, I decided to use its safe mode by importing cjson.safe. This should return nil for invalid data and provide the error message instead of raising the error:
The cjson module will throw an error during JSON conversion if any invalid data is encountered. [...]
The cjson.safe module behaves identically to the cjson module, except when errors are encountered during JSON conversion. On error, the cjson_safe.encode and cjson_safe.decode functions will return nil followed by the error message.
However, I do not encounter any different error handling behavior in my case and the following traceback is shown in Openresty's error.log file:
2021/04/30 20:33:16 [error] 6176#6176: *176 lua entry thread aborted: runtime error: content_by_lua(samplesite:50):16: attempt to index field 'endpoint' (a nil value)
Which in turn results in an Internal Server Error:
<html>
<head><title>500 Internal Server Error</title></head>
<body>
<center><h1>500 Internal Server Error</h1></center>
<hr><center>openresty</center>
</body>
</html>
I think a workaround might be writing a dedicated function for parsing the JSON data and calling it with pcall() to catch any errors. However, this would make the safe mode kind of useless. What am I missing here?
Your “simple JSON document” is a valid JSON document. The error you are facing is not related to cjson, it's a standard Lua error:
resty -e 'local t = {foo = 1}; print(t["foo"]); print(t["foo"]["bar"])'
1
ERROR: (command line -e):1: attempt to index field 'foo' (a number value)
stack traceback:
...
“Safeness” of cjson.safe is about parsing of malformed documents:
cjson module raises an error:
resty -e 'print(require("cjson").decode("[1, 2, 3"))'
ERROR: (command line -e):1: Expected comma or array end but found T_END at character 9
stack traceback:
...
cjson.safe returns nil and an error message:
resty -e 'print(require("cjson.safe").decode("[1, 2, 3"))'
nilExpected comma or array end but found T_END at character 9

Elixir, using function from another module

I am extremely new to the programming and to the elixir. So I am very exited to learn as much as I can. But I've got a problem. I looking the way how to use my functions in another module. I am building the web-server which stores the key-value maps in the memory. To keep the maps temporary I've decided to use Agent. Here is the part of my code:
defmodule Storage do
use Agent
def start_link do
Agent.start_link(fn -> %{} end, name: :tmp_storage)
end
def set(key, value) do
Agent.update(:tmp_storage, fn map -> Map.put_new(map, key, value) end)
end
def get(key) do
Agent.get(:tmp_storage, fn map -> Map.get(map, key) end)
end
end
So I'm trying to put this functions to the routes of the web server:
defmodule Storage_router do
use Plug.Router
use Plug.Debugger
require Logger
plug(Plug.Logger, log: :debug)
plug(:match)
plug(:dispatch)
post "/storage/set" do
with {:ok, _} <- Storage.set(key, value) do
send_resp(conn, 200, "getting the value")
else
_ ->
send_resp(conn, 404, "nothing")
end
end
end
And I receive:
warning: variable "key" does not exist and is being expanded to "key()", please use parentheses to remove the ambiguity or change the variable name
lib/storage_route.ex:12
warning: variable "value" does not exist and is being expanded to "value()", please use parentheses to remove the ambiguity or change the variable name
lib/storage_route.ex:12
looking for any suggestions\help
I am extremly new to the programming and to the elixir.
I do not think it is wise to begin learning programming with elixir. I would start with python or ruby, and then after a year or two then I would try elixir.
The first thing you need to learn is how to post code. Search google for how to post code on stackoverflow. Then, you have to get your indenting all lined up. Are you using a computer programming text editor? If not, then you have to get one. There are many free ones. I use vim, which comes installed on Unix like computers. You can learn how to use vim by typing vimtutor in a terminal window.
Next, you have a syntax error in your code:
Agent.start_link(fn -> %{} end, name: :tmp_storage
end)
That should be:
Agent.start_link(fn -> %{} end, name: :tmp_storage)
The warning you got is because your code tries to do the equivalent of:
def show do
IO.puts x
end
Elixir and anyone else reading that code would ask, "What the heck is x?" The variable x is never assigned a value anywhere, and therefore the variable x does not exist, and you cannot output something that is non-existent. You do the same thing here:
with {:ok, _} <- Storage.set(key, value) do
send_resp(conn, 200, "getting the value")
else
_->
send_resp(conn, 404, "nothing")
end
You call the function:
Storage.set(key, value)
but the variables key and value were never assigned a value, and elixir (and anyone else reading that code) wonders, "What the heck are key and value?"
This is the way functions work:
b.ex:
defmodule MyFuncs do
def show(x, y) do
IO.puts x
IO.puts y
end
end
defmodule MyWeb do
def go do
height = 10
width = 20
MyFuncs.show(height, width)
end
end
In iex:
~/elixir_programs$ iex b.ex
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]
Interactive Elixir (1.6.6) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> MyWeb.go
10
20
:ok
iex(2)>
So, in your code you need to write something like this:
post "/storage/set" do
key = "hello"
value = 10
with {:ok, _} <- Storage.set(key, value) do
send_resp(conn, 200, "Server saved the key and value.")
else
_->
send_resp(conn, 404, "nothing")
end
end
However, that will store the same key/value for every post request. Presumably, you want to store whatever is sent in the body of the post request. Do you know the difference between a get request and a post request? A get request tacks data onto the end of the url, while a post request sends the data in the "body of the request", so there are different procedures for extracting the data depending on the type of the request.
What tutorial are you reading? This tutorial: https://www.jungledisk.com/blog/2018/03/19/tutorial-a-simple-http-server-in-elixir/, shows you how to extract the data from the body of a post request. The data in the body of a post request is just a string. If the string is in JSON format, then you can convert the string into an elixir map using Poison.decode!(), which will allow you to easily extract the values associated with the keys that you are interested in. For example:
post "/storage/set" do
{:ok, body_string, conn} = read_body(conn)
body_map = Poison.decode!(body_string)
IO.inspect(body_map) #This outputs to terminal window where server is running
message = get_in(body_map, ["message"])
send_resp(
conn,
201,
"Server received: #{message}\n"
)
end
Then you can use the following curl command in another terminal window to send a post request to that route:
$ curl -v -H 'Content-Type: application/json' "http://localhost:8085/storage/set" -d '{"message": "hello world" }'
(-v => verbose output, -H => request header, -d => data)
Now, based on what I said was wrong with your code above, you should be wondering about this line:
{:ok, body_string, conn} = read_body(conn)
That line calls:
read_body(conn)
but the variable conn is not assigned a value anywhere. However, Plug invisibly creates the conn variable and assigns a value to it.
Here is a complete example using Agent to store post request data (following the tutorial I linked above):
simple_server
config/
lib/
simple_server/
application.ex
router.ex
storage.ex
test/
An elixir convention is to have a directory in the lib/ directory with the same name as your project, in this case that would be simple_server, then you give the modules you define names that reflect the directory structure. So, in router.ex you would define a module named SimpleServer.Router and in storage.ex you would define a module named SimpleServer.Storage. However, the . in a module name means nothing special to elixir, so you will not get an error if you decide to name your module F.R.O.G.S in the file lib/rocks.ex--and your code will work just fine.
router.ex:
defmodule SimpleServer.Router do
use Plug.Router
use Plug.Debugger
require Logger
plug(Plug.Logger, log: :debug)
plug(:match)
plug(:dispatch)
get "/storage/:key" do
resp_msg = case SimpleServer.Storage.get(key) do
nil -> "The key #{key} doesn't exist!\n"
val -> "The key #{key} has value #{val}.\n"
end
send_resp(conn, 200, resp_msg)
end
post "/storage/set" do
{:ok, body_string, conn} = read_body(conn)
body_map = Poison.decode!(body_string)
IO.inspect(body_map) #This outputs to terminal window where server is running
Enum.each(
body_map,
fn {key, val} -> SimpleServer.Storage.set(key,val) end
)
send_resp(
conn,
201,
"Server stored all key-value pairs\n"
)
end
match _ do
send_resp(conn, 404, "not found")
end
end
The first thing to note in the code above is the route:
get "/storage/:key" do
That will match a path like:
/storage/x
and plug will create a variable named key and assign it the value "x", like this:
key = "x"
Also, note that when you call a function:
width = 10
height = 20
show(width, height)
elixir looks at the function definition:
def show(x, y) do
IO.puts x
IO.puts y
end
and matches the function call to the def like this:
show(width, height)
| |
V V
def show( x , y) do
...
end
and performs the assignments:
x = width
y = height
Then, inside the function you can use the x and y variables. In this line:
Enum.each(
body_map,
# | | | | |
# V V V V V
fn {key, val} -> SimpleServer.Storage.set(key,val) end
)
Elixir will call the anonymous function passing values for key and val, like this:
func("x", "10")
Therefore, in the body of the anonymous function you can use the variables key and val:
SimpleServer.Storage.set(key,val)
because the variables key and val will already have been assigned values.
storage.ex:
defmodule SimpleServer.Storage do
use Agent
def start_link(_args) do #<*** Note the change here
Agent.start_link(fn -> %{} end, name: :tmp_storage)
end
def set(key, value) do
Agent.update(
:tmp_storage,
fn(map) -> Map.put_new(map, key, value) end
)
end
def get(key) do
Agent.get(
:tmp_storage,
fn(map) -> Map.get(map, key) end
)
end
end
application.ex:
defmodule SimpleServer.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
#moduledoc false
use Application
def start(_type, _args) do
# List all child processes to be supervised
children = [
Plug.Adapters.Cowboy.child_spec(scheme: :http, plug: SimpleServer.Router, options: [port: 8085]),
{SimpleServer.Storage, []}
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: SimpleServer.Supervisor]
Supervisor.start_link(children, opts)
end
end
mix.exs:
defmodule SimpleServer.MixProject do
use Mix.Project
def project do
[
app: :simple_server,
version: "0.1.0",
elixir: "~> 1.6",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger],
mod: {SimpleServer.Application, []}
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:poison, "~> 4.0"},
{:plug_cowboy, "~> 2.0"}
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"},
]
end
end
Note, if you use the dependencies and versions specified in the tutorial you will get some warnings, including the warning:
~/elixir_programs/simple_server$ iex -S mix
...
...
12:48:57.767 [warn] Setting Ranch options together
with socket options is deprecated. Please use the new
map syntax that allows specifying socket options
separately from other options.
...which is an issue with Plug. Here are the dependencies and versions that I used to get rid of all the warnings:
{:poison, "~> 4.0"},
{:plug_cowboy, "~> 2.0"}
Also, when you list an application as a dependency, you no longer have to enter it in the :extra_applications list. Elixir will automatically start all the applications listed as dependencies before starting your application. See :applications v. :extra_applications.
Once the server has started, you can use another terminal window to send a post request with curl (or you can use some other program):
~$ curl -v -H 'Content-Type: application/json' "http://localhost:8085/storage/set" -d '{"x": "10", "y": "20" }
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8085 (#0)
> POST /storage/set HTTP/1.1
> Host: localhost:8085
> User-Agent: curl/7.58.0
> Accept: */*
> Content-Type: application/json
> Content-Length: 23
>
* upload completely sent off: 23 out of 23 bytes
< HTTP/1.1 201 Created
< server: Cowboy
< date: Fri, 30 Nov 2018 19:22:23 GMT
< content-length: 34
< cache-control: max-age=0, private, must-revalidate
<
Server stored all key-value pairs
* Connection #0 to host localhost left intact
The > lines are the request, and the < lines are the response. Also, check the output in the terminal window where the server is running.
~$ curl -v http://localhost:8085/storage/z
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8085 (#0)
> GET /storage/z HTTP/1.1
> Host: localhost:8085
> User-Agent: curl/7.58.0
> Accept: */*
>
< HTTP/1.1 200 OK
< server: Cowboy
< date: Fri, 30 Nov 2018 19:22:30 GMT
< content-length: 25
< cache-control: max-age=0, private, must-revalidate
<
The key z doesn't exist!
* Connection #0 to host localhost left intact
.
~$ curl -v http://localhost:8085/storage/x
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8085 (#0)
> GET /storage/x HTTP/1.1
> Host: localhost:8085
> User-Agent: curl/7.58.0
> Accept: */*
>
< HTTP/1.1 200 OK
< server: Cowboy
< date: Fri, 30 Nov 2018 19:22:37 GMT
< content-length: 24
< cache-control: max-age=0, private, must-revalidate
<
The key x has value 10.
* Connection #0 to host localhost left intact
I'm not entirely sure what you're trying to accomplish, but the error is telling you that the key and value that are passed to the router with statement are not defined. Elixir thinks you are trying to call a function with those arguments because they are not "bound" to a value. That is why you are seeing warning: variable "value" does not exist and is being expanded to "value()"
I suppose this is not really an answer but maybe more an explanation of the error you're seeing.
You need to pull the key/value params out of your %Plug.Conn{} object (conn). The key/value variables have not yet been defined within the scope of your route. The conn object is only available because it is injected by the post macro provided by Plug.
I am not quite aware of what type of requests you're submitting to the router, but I'll assume it's JSON as an example. You can manually parse the body in your connection by doing something like:
with {:ok, raw_body} <- Plug.Conn.read_body(conn),
{:ok, body} <- Poison.decode(raw_body) do
key = Map.get(body, "key")
value = map.get(body, "value")
# ... other logic
end
The Plug project, however, provides a nice convenience plug for you to parse request bodies in a generic way: Plug.Parsers.
To implement this in your router, you just have to add the plug to the top of your router (below Plug.Logger I think):
plug Plug.Parsers,
parsers: [:urlencoded, :json]
json_decoder: Poison,
pass: ["text/*", "application/json"]
The :urlencoded part will parse your query parameters and the :json part will parse the body of the request.
Then below in your route, you can get the key/value params from your conn object in the :params key like so:
%{params: params} = conn
key = Map.get(params, "key")
value = Map.get(params, "value")
Also, I should note that the best JSON decoder at the moment is Jason which is basically a drop-in replacement for Poison, but faster.
Anyway, reading hexdocs really helps with figuring this stuff out and the Plug project has great documentation. I think Elixir is a great language to start programming with (although it's essential to learn object-oriented paradigms as well). Happy coding!

LuaLaTex using fontspec package and luacode reading JSON file

I'm using Latex since years but I'm new to embedded luacode (with Lualatex). Below you can see a simplified example:
\begin{filecontents*}{data.json}
[
{"firstName":"Max", "lastName":"Möller"},
{"firstName":"Anna", "lastName":"Smith"}
];
\end{filecontents*}
\documentclass[11pt]{article}
\usepackage{fontspec}
%\setmainfont{Carlito}
\usepackage{tikz}
\usepackage{luacode}
\begin{document}
\begin{luacode}
require("lualibs.lua")
local file = io.open('data.json','rb')
local jsonstring = file:read('*a')
file.close()
local jsondata = utilities.json.tolua(jsonstring)
tex.print('\\begin{tabular}{cc}')
for key, value in pairs(jsondata) do
tex.print(value["firstName"] .. ' & ' .. value["lastName"] .. '\\\\')
end
tex.print('\\hline\\end{tabular}')
\end{luacode}
\end{document}
When executing Lualatex following error occurs:
LuaTeX error [\directlua]:6: attempt to index field 'json' (a nil value) [\directlua]:6: in main chunk. \end{luacode}
When commenting the line \usepackage{fontspec} the output will be produced. Alternatively, the error can be avoided by commenting utilities.json.tolua(jsonstring) and all following lua-code lines.
So the question is: How can I use both "fontspec" package and json-data without generating an error message? Apart from this I have another question: How to enable german umlauts in output of luacode (see first "lastName" in example: Möller)?
Ah, I'm using TeX Live 2015/Debian on Ubuntu 16.04.
Thank you,
Jerome

mosquitto - disable subscribing without authorization

I am using mosquitto version 1.4.10 with tls-certificate. I am using this plugin https://github.com/mbachry/mosquitto_pyauth to authorize a user.And it works well for mosquitto_pub ( as in, when someone tries to publish , it gets authorized by the module first ).
However, it seems that mosquitto_sub is able to subscribe to anything without authorizing. How do I force security when someone is just trying to access a topic in read only mode?
I went through the mosquitto.conf file and cant seem to find anything related to this.
for example, I am able to subscribe like this:
mosquitto_sub --cafile /etc/mosquitto/ca.crt --cert /etc/mosquitto/client.crt --key /etc/mosquitto/client.key -h ubuntu -p 1883 -t c/# -d
and able to see messages coming from some publisher like this:
mosquitto_pub --cafile /etc/mosquitto/ca.crt --cert /etc/mosquitto/client.crt --key /etc/mosquitto/client.key -h ubuntu -p 1883 -t c/2/b/3/p/3/rt/13/r/123 -m 32 -q 1
What I am trying to do is prevent mosquitto_sub reading all messages at root level without authorization .
the python code that does the authorization looks like this : ( auth data is stored in cassandra db )
import sys
import mosquitto_auth
from cassandra.cluster import Cluster
from cassandra import ConsistencyLevel
## program entry point from mosquitto...
def plugin_init(opts):
global cluster, session, select_device_query
conf = dict(opts)
cluster = Cluster(['192.168.56.102'])
session = cluster.connect('hub')
select_device_query = session.prepare('SELECT * from devices where uid=?')
select_device_query.consistency_level = ConsistencyLevel.QUORUM
print 'Cassandra cluster initialized'
def acl_check(clientid, username, topic, access):
device_data = session.execute(select_device_query, [username])
if device_data.current_rows.__len__() > 0:
device_data = device_data[0]
# sample device data looks like this :
# Row(uid=u'08:00:27:aa:8f:91', brand=3, company=2, device=15617, property=3, room=490, room_number=u'3511', room_type=13, stamp=datetime.datetime(2016, 12, 12, 6, 29, 54, 723000))
subscribable_topic = 'c/' + str(device_data.company) \
+ '/b/' + str(device_data.brand) \
+ '/p/' + str(device_data.property) \
+ '/rt/' + str(device_data.room_type) \
+ '/r/' + str(device_data.room) \
+ '/#'
matches = mosquitto_auth.topic_matches_sub(subscribable_topic, topic)
print 'ACL: user=%s topic=%s, matches = %s' % (username, topic, matches)
return matches
return False
function acl_check seems to be always called when mosquitto_pub tries to connect, but never called when mosquitto_sub connects.
the C code behind this python module is here: https://github.com/mbachry/mosquitto_pyauth/blob/master/auth_plugin_pyauth.c
add the following to your mosquitto.conf
...
allow_anonymous false
...
This will stop users without credential from logging on to the broker.
You can also add an acl rule for the anonymous user if there are certain topics you would want unauthenticated clients to be able to see.