Disable or Bypass login of odoo when trying to hit from external application - odoo

I am trying to open odoo url from my hosted application but its redirecting to login screen. As user is already logged in to my application logically user should not be redirected to login screen again...How can I bypass this security check of odoo???
Thanks In advance

From your question, I think what you are trying to achieve is to authenticate your user's odoo session automatically if that user is already authenticated in your non-odoo application. To achieve that, you can implement your application such that, on authentication of a user, your backend will authenticate a session in odoo with corresponding user, and set session_id cookie of user's browser to that authenticated session_id. I guess that may be achievable if both application are served under same domain with reverse proxying using nginx or apache, as other's already commented, there is no way you can totally disable or bypass authentication of odoo itself, as this is a well developed business related software, and that will just defeat it's purpose.

It is possible to bypass the security of odoo. These changes are required in these two files
`
**server/odoo/http.py**
line number 406 in odoo 12
def validate_csrf(self, csrf):
# if not csrf:
# return False
#
# try:
# hm, _, max_ts = str(csrf).rpartition('o')
# except UnicodeEncodeError:
# return False
#
# if max_ts:
# try:
# if int(max_ts) < int(time.time()):
# return False
# except ValueError:
# return False
#
# token = self.session.sid
#
# msg = '%s%s' % (token, max_ts)
# secret = self.env['ir.config_parameter'].sudo().get_param('database.secret')
# assert secret, "CSRF protection requires a configured database secret"
# hm_expected = hmac.new(secret.encode('ascii'), msg.encode('utf-8'), hashlib.sha1).hexdigest()
# return consteq(hm, hm_expected)
return True
def setup_session(self, httprequest):
explicit_session = True
# recover or create session
# session_gc(self.session_store)
#
# sid = httprequest.args.get('session_id')
# explicit_session = True
# if not sid:
# sid = httprequest.headers.get("X-Openerp-Session-Id")
# if not sid:
# sid = httprequest.cookies.get('session_id')
# explicit_session = False
# if sid is None:
# httprequest.session = self.session_store.new()
# else:
# httprequest.session = self.session_store.get(sid)
httprequest.session = self.session_store.new()
httprequest.session.uid =2
httprequest.session.login = 'root'
httprequest.session.db = 'odoo'
httprequest.session.sid = '7aa5500f30365aead781465ec08bbb03c3a5024b'
return explicit_session
line number 1348
def setup_session(self, httprequest):
explicit_session = True
# recover or create session
# session_gc(self.session_store)
#
# sid = httprequest.args.get('session_id')
# explicit_session = True
# if not sid:
# sid = httprequest.headers.get("X-Openerp-Session-Id")
# if not sid:
# sid = httprequest.cookies.get('session_id')
# explicit_session = False
# if sid is None:
# httprequest.session = self.session_store.new()
# else:
# httprequest.session = self.session_store.get(sid)
httprequest.session = self.session_store.new()
httprequest.session.uid =2
httprequest.session.login = 'root'
httprequest.session.db = 'odoo'
httprequest.session.sid = '7aa5500f30365aead781465ec08bbb03c3a5024b'
return explicit_session
**server/odoo/service/security.py**
line number 18
def check_session(session, env):
# self = env['res.users'].browse(session.uid)
# expected = self._compute_session_token(session.sid)
# if expected and odoo.tools.misc.consteq(expected, session.session_token):
# return True
# self._invalidate_session_cache()
return True

Related

packet-in request after idle timeout in sdn switch using ryu controller

I'm working on the Ryu controller to set the idle and hard timeout for flows. I'm assigning the idle timeout to 10s and hard timeout to 30s. On the very first, when I run pingall on mininet this will install the flow rules by generating a packet miss-match request. When a timeout event occurs it will remove the flow rule from the flow table. Now when I again run pingall on mininet it is not generating a packet miss-match request. all the packets are dropped. Please help me with how I can fix this. The code for the Ryu app is given below.
# Copyright (C) 2011 Nippon Telegraph and Telephone Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_3
from ryu.lib.packet import packet
from ryu.lib.packet import ethernet
from ryu.lib.packet import ether_types
class SimpleSwitch13(app_manager.RyuApp):
OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]
def __init__(self, *args, **kwargs):
super(SimpleSwitch13, self).__init__(*args, **kwargs)
self.mac_to_port = {}
#set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)
def switch_features_handler(self, ev):
datapath = ev.msg.datapath
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
# install table-miss flow entry
#
# We specify NO BUFFER to max_len of the output action due to
# OVS bug. At this moment, if we specify a lesser number, e.g.,
# 128, OVS will send Packet-In with invalid buffer_id and
# truncated packet data. In that case, we cannot output packets
# correctly. The bug has been fixed in OVS v2.1.0.
match = parser.OFPMatch()
actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,
ofproto.OFPCML_NO_BUFFER)]
self.add_flow(datapath, 0, match, actions)
def add_flow(self, datapath, priority, match, actions, buffer_id=None):
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS,
actions)]
if buffer_id:
mod = parser.OFPFlowMod(datapath=datapath, buffer_id=buffer_id,
idle_timeout=10, hard_timeout=30, priority=priority, match=match,
instructions=inst)
else:
mod = parser.OFPFlowMod(datapath=datapath, priority=priority,
idle_timeout=10, hard_timeout=30, match=match, instructions=inst)
datapath.send_msg(mod)
#set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
def _packet_in_handler(self, ev):
# If you hit this you might want to increase
# the "miss_send_length" of your switch
if ev.msg.msg_len < ev.msg.total_len:
self.logger.debug("packet truncated: only %s of %s bytes",
ev.msg.msg_len, ev.msg.total_len)
msg = ev.msg
datapath = msg.datapath
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
in_port = msg.match['in_port']
pkt = packet.Packet(msg.data)
eth = pkt.get_protocols(ethernet.ethernet)[0]
if eth.ethertype == ether_types.ETH_TYPE_LLDP:
# ignore lldp packet
return
dst = eth.dst
src = eth.src
dpid = datapath.id
self.mac_to_port.setdefault(dpid, {})
self.logger.info("packet in %s %s %s %s", dpid, src, dst, in_port)
# learn a mac address to avoid FLOOD next time.
self.mac_to_port[dpid][src] = in_port
if dst in self.mac_to_port[dpid]:
out_port = self.mac_to_port[dpid][dst]
else:
out_port = ofproto.OFPP_FLOOD
actions = [parser.OFPActionOutput(out_port)]
# install a flow to avoid packet_in next time
if out_port != ofproto.OFPP_FLOOD:
match = parser.OFPMatch(in_port=in_port, eth_dst=dst, eth_src=src)
# verify if we have a valid buffer_id, if yes avoid to send both
# flow_mod & packet_out
if msg.buffer_id != ofproto.OFP_NO_BUFFER:
self.add_flow(datapath, 1, match, actions, msg.buffer_id)
return
else:
self.add_flow(datapath, 1, match, actions)
data = None
if msg.buffer_id == ofproto.OFP_NO_BUFFER:
data = msg.data
out = parser.OFPPacketOut(datapath=datapath, buffer_id=msg.buffer_id,
in_port=in_port, actions=actions, data=data)
datapath.send_msg(out)

iothub_registry_manager_bulk_create_sample

I am trying to run below code in Visual Studio:
import sys
import os
from azure.iot.hub import IoTHubRegistryManager
from azure.iot.hub.models import ExportImportDevice, AuthenticationMechanism, SymmetricKey
iothub_connection_str = "HostName=bulkdevice.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=YsKedao6li9wKbpMC5sJftPXNhB0km6Jt6bAD3KqBes="
try:
# Create IoTHubRegistryManager
iothub_registry_manager = IoTHubRegistryManager(iothub_connection_str)
# primary_key1 = "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnoo"
# secondary_key1 = "111222333444555666777888999000aaabbbcccdddee"
# symmetric_key1 = SymmetricKey(
# primary_key=primary_key1, secondary_key=secondary_key1)
# authentication1 = AuthenticationMechanism(
# type="sas", symmetric_key=symmetric_key1)
device1 = ExportImportDevice(
id="BulkDevice1")
# primary_key2 = "cccbbbaaadddeeefffggghhhiiijjjkkklllmmmnnnoo"
# secondary_key2 = "333222111444555666777888999000aaabbbcccdddee"
# symmetric_key2 = SymmetricKey(
# primary_key=primary_key2, secondary_key=secondary_key2)
# authentication2 = AuthenticationMechanism(
# type="sas", symmetric_key=symmetric_key2)
device2 = ExportImportDevice(
id="BulkDevice2")
# Create devices
device1.import_mode = "create"
device2.import_mode = "create"
device_list = [device1, device2]
iothub_registry_manager.bulk_create_or_update_devices(device_list)
# Get devices (max. 1000 with get_devices API)
# max_number_of_devices = 10
# devices = iothub_registry_manager.get_devices(max_number_of_devices)
# if devices:
# x = 0
# for d in devices:
# print_device_info("Get devices {0}".format(x), d)
# x += 1
# else:
# print("No device found")
# Delete devices
# device1.import_mode = "delete"
# device2.import_mode = "delete"
# device_list = [device1, device2]
# iothub_registry_manager.bulk_create_or_update_devices(device_list)
except Exception as ex:
print("Unexpected error {0}".format(ex))
except KeyboardInterrupt:
print("iothub_registry_manager_sample stopped")
I am getting an error unable to register multiple devices in IoThub, please help me register.

Writing loop values within a function into Pandas dataframe

The function below is part of googlesheets quickstart.py to allow people to read a Googlesheet URL.
I am able to run the test and getting the print to work.
See the print statement in the function below:
print('%s, %s,%s,%s,%s,%s,%s,%s' % (row[0],row[1],row[2],row[3], row[4], row[5],row[6],row[7]))
My ultimate goal is to capture the data in the print into a pandas dataframe instead. All my attempts did not work.
def main():
"""Shows basic usage of the Sheets API.
Prints values from a sample spreadsheet.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('sheets', 'v4', credentials=creds)
# Call the Sheets API
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
range=SAMPLE_RANGE_NAME).execute()
values = result.get('values', [])
if not values:
print('No data found.')
else:
#print('Name, Major:')
for row in values:
# d = {'Case_Type':row.Case_Type,
# 'Date':row.Date,
# 'Cases':row.Cases,
# 'Country_Region':row.Country_Region,
# 'Lat':Lat,
# 'Long':Long}
# L.append(d)
# df = pd.DataFrame(L)
#Print columns A and E, which correspond to indices 0 and 7.
print('%s, %s,%s,%s,%s,%s,%s,%s' % (row[0],row[1],row[2],row[3], row[4], row[5],row[6],row[7]))
if __name__ == '__main__':
main()
Since values seems to be a 2D list, try doing
pd.DataFrame.from_records(values, columns=['Date', 'Cases', 'Country_Region', 'Lat', 'Long'])

requests + bs4 no results from pages

Here the code that can get info from https://www.gabar.org/membersearchresults.cfm
but cannot from https://www.gabar.org/membersearchresults.cfm?start=1&id=70FFBD1B-9C8E-9913-79DBB8B989DED6C1
from bs4 import BeautifulSoup
import requests
import traceback
links_to_visit = []
navigation_links = [] # for testing next button
base_url = 'https://www.gabar.org'
def make_soup(link):
r = requests.get(link)
soup = BeautifulSoup(r.content, 'html.parser')
return soup
def all_results(url):
global links_to_visit
global navigation_links
soup = make_soup(url)
print(soup)
div = soup.find('div', {'class': 'cs_control'})
links = div.find_all('a')
print(links)
for link in links:
try:
if link.text == 'Next': # prev, next, new search
navigation_links.append(link)
print('got it')
elif not '/MemberSearchDetail.cfm?ID=' in link.get('href'):
pass # I dont need that link
else:
links_to_visit.append(link)
except:
traceback.print_exc()
print(len(links_to_visit))
print(links_to_visit)
#print(links_to_visit[-1].get('href'))
def start():
flag = 1
page = 1
while page < 60716:
flag = 0
if navigation_links[-1].text == 'Next':
flag = 1
next_link = navigation_links[-1]
#print(next_link.get('href'))
page += 25
print(base_url + next_link.get('href'))
all_results(base_url + next_link.get('href'))
print('page is:', page)
if __name__ == '__main__':
all_results('https://www.gabar.org/membersearchresults.cfm')
start()
What I need to understand or do if I want to get full result?
What you need to understand is that there is more than a URL to an HTTP-request. In this case, a search result is only available to the session that executed the search and can therefore only be paged through if you are the "owner" of that session. Most websites identify a session using session-cookies that you need to send along with your HTTP-request.
This can be a huge hassle, but luckily pythons requests takes care of all of that for you with requests.session. Instead of using requests.get(url) you initialize the session session=requests.session() and then use that session in subsequent requests session.get(url). This will automagically preserve cookies for you and in many ways behave like an actual browser would.
You can read more about how requests.session works here.
And last but not least, your fixed code =)
from bs4 import BeautifulSoup
import requests
import traceback
links_to_visit = []
navigation_links = [] # for testing next button
# we initialize the session here
session = requests.session()
base_url = 'https://www.gabar.org'
def make_soup(link):
# r = requests.get(link)
# we use the session here in order to preserve cookies across requests
r = session.get(link)
soup = BeautifulSoup(r.content, 'html.parser')
return soup
def all_results(url):
# globals are almost never needed or recommended and certainly not here.
# you can just leave this out
# global links_to_visit
# global navigation_links
soup = make_soup(url)
print(soup)
div = soup.find('div', {'class': 'cs_control'})
links = div.find_all('a')
print(links)
for link in links:
try:
if link.text == 'Next': # prev, next, new search
navigation_links.append(link)
print('got it')
elif not '/MemberSearchDetail.cfm?ID=' in link.get('href'):
pass # I dont need that link
else:
links_to_visit.append(link)
except:
traceback.print_exc()
print(len(links_to_visit))
print(links_to_visit)
#print(links_to_visit[-1].get('href'))
def start():
flag = 1
page = 1
while page < 60716:
flag = 0
if navigation_links[-1].text == 'Next':
flag = 1
next_link = navigation_links[-1]
#print(next_link.get('href'))
page += 25
print(base_url + next_link.get('href'))
all_results(base_url + next_link.get('href'))
print('page is:', page)
if __name__ == '__main__':
all_results('https://www.gabar.org/membersearchresults.cfm')
start()

In Middleman how do I generate day, month, and year blog archive links?

I'm trying to generate year and month archive links.
Right now I can set one of the three.
When I set two or more and look at the Sitemap I get the error:
NoMethodError at /__middleman/sitemap/
undefined method `add_path' for #<Middleman::MetaPages::SitemapResource:0x007fedd61597a0>`
Here is my blog from config.rb
activate :blog do |blog|
blog.name = "blog"
blog.permalink = "/{title}/"
blog.taglink = "blog/:tag.html"
blog.year_link = "blog/{year}/"
blog.month_link = "blog/{year}/{month}/"
blog.day_link = "blog/{year}/{month}/{day}/"
blog.sources = "blog/{year}-{month}-{day}-{title}.html"
#blog.year_template = "blog/calendar.html"
blog.month_template = "blog/calendar.html"
#blog.day_template = "blog/calendar.html"
blog.layout = "blog-layout"
blog.tag_template = "blog/tag.html"
#blog.calendar_template = "blog/calendar.html"
# This will add a prefix to all links, template references and source paths
# blog.prefix = "blog"
# Matcher for blog source files
# blog.sources = "{year}-{month}-{day}-{title}.html"
# blog.summary_separator = /(READMORE)/
# blog.summary_length = 250
# blog.default_extension = ".markdown"
# Enable pagination
# blog.paginate = true
# blog.per_page = 10
# blog.page_link = "page/{num}"
end