def forward_request(): pdns_api_url = Setting().get('pdns_api_url') pdns_api_key = Setting().get('pdns_api_key') headers = {} data = None msg_str = "Sending request to powerdns API {0}" if request.method != 'GET' and request.method != 'DELETE': msg = msg_str.format(request.get_json(force=True)) logging.debug(msg) data = request.get_json(force=True) verify = False headers = { 'user-agent': 'powerdnsadmin/0', 'pragma': 'no-cache', 'cache-control': 'no-cache', 'accept': 'application/json; q=1', 'X-API-KEY': pdns_api_key } url = urljoin(pdns_api_url, request.path) resp = requests.request(request.method, url, headers=headers, verify=verify, json=data) return resp
def initial_apikey_data(): pdns_proto = os.environ['PDNS_PROTO'] pdns_host = os.environ['PDNS_HOST'] pdns_port = os.environ['PDNS_PORT'] pdns_api_url = '{0}://{1}:{2}'.format(pdns_proto, pdns_host, pdns_port) api_url_setting = Setting('pdns_api_url', pdns_api_url) api_key_setting = Setting('pdns_api_key', os.environ['PDNS_API_KEY']) allow_create_domain_setting = Setting('allow_user_create_domain', True) try: with app.app_context(): flask_migrate.upgrade() db.session.add(api_url_setting) db.session.add(api_key_setting) db.session.add(allow_create_domain_setting) test_user_apikey = app.config.get('TEST_USER_APIKEY') test_admin_apikey = app.config.get('TEST_ADMIN_APIKEY') dummy_apikey = ApiKey( desc="dummy", role_name="Administrator" ) admin_key = dummy_apikey.get_hashed_password( plain_text_password=test_admin_apikey ).decode('utf-8') admin_apikey = ApiKey( key=admin_key, desc="test admin apikey", role_name="Administrator" ) admin_apikey.create() user_key = dummy_apikey.get_hashed_password( plain_text_password=test_user_apikey ).decode('utf-8') user_apikey = ApiKey( key=user_key, desc="test user apikey", role_name="User" ) user_apikey.create() except Exception as e: logging.error("Unexpected ERROR: {0}".format(e)) raise e yield db.session.close() os.unlink(app.config['TEST_DB_LOCATION'])
def initial_data(): pdns_proto = os.environ['PDNS_PROTO'] pdns_host = os.environ['PDNS_HOST'] pdns_port = os.environ['PDNS_PORT'] pdns_api_url = '{0}://{1}:{2}'.format(pdns_proto, pdns_host, pdns_port) api_url_setting = Setting('pdns_api_url', pdns_api_url) api_key_setting = Setting('pdns_api_key', os.environ['PDNS_API_KEY']) allow_create_domain_setting = Setting('allow_user_create_domain', True) try: with app.app_context(): flask_migrate.upgrade() db.session.add(api_url_setting) db.session.add(api_key_setting) db.session.add(allow_create_domain_setting) test_user_pass = app.config.get('TEST_USER_PASSWORD') test_user = app.config.get('TEST_USER') test_admin_user = app.config.get('TEST_ADMIN_USER') test_admin_pass = app.config.get('TEST_ADMIN_PASSWORD') admin_user = User( username=test_admin_user, plain_text_password=test_admin_pass, email="*****@*****.**" ) msg = admin_user.create_local_user() if not msg: raise Exception("Error occurred creating user {0}".format(msg)) ordinary_user = User( username=test_user, plain_text_password=test_user_pass, email="*****@*****.**" ) msg = ordinary_user.create_local_user() if not msg: raise Exception("Error occurred creating user {0}".format(msg)) except Exception as e: logging.error("Unexpected ERROR: {0}".format(e)) raise e yield db.session.close() os.unlink(app.config['TEST_DB_LOCATION'])
def github_oauth(): if not Setting().get('github_oauth_enabled'): return None def fetch_github_token(): return session.get('github_token') github = authlib_oauth_client.register( 'github', client_id=Setting().get('github_oauth_key'), client_secret=Setting().get('github_oauth_secret'), request_token_params={'scope': Setting().get('github_oauth_scope')}, api_base_url=Setting().get('github_oauth_api_url'), request_token_url=None, access_token_url=Setting().get('github_oauth_token_url'), authorize_url=Setting().get('github_oauth_authorize_url'), client_kwargs={'scope': Setting().get('github_oauth_scope')}, fetch_token=fetch_github_token, ) @app.route('/github/authorized') def github_authorized(): session['github_oauthredir'] = url_for('.github_authorized', _external=True) token = github.authorize_access_token() if token is None: return 'Access denied: reason=%s error=%s' % ( request.args['error'], request.args['error_description']) session['github_token'] = (token) return redirect(url_for('.login')) return github
def api_login_delete_zone(domain_name): pdns_api_url = Setting().get('pdns_api_url') pdns_api_key = Setting().get('pdns_api_key') pdns_version = Setting().get('pdns_version') api_uri_with_prefix = utils.pdns_api_extended_uri(pdns_version) api_full_uri = api_uri_with_prefix + '/servers/localhost/zones' api_full_uri += '/' + domain_name headers = {} headers['X-API-Key'] = pdns_api_key domain = Domain.query.filter(Domain.name == domain_name) if not domain: abort(404) if g.user.role.name not in ['Administrator', 'Operator']: user_domains_obj_list = g.user.get_domains() user_domains_list = [item.name for item in user_domains_obj_list] if domain_name not in user_domains_list: raise DomainAccessForbidden() msg_str = "Sending request to powerdns API {0}" logging.debug(msg_str.format(domain_name)) try: resp = utils.fetch_remote( urljoin(pdns_api_url, api_full_uri), method='DELETE', headers=headers, accept='application/json; q=1' ) if resp.status_code == 204: logging.debug("Request to powerdns API successful") history = History( msg='Delete domain {0}'.format(domain_name), detail='', created_by=g.user.username ) history.add() domain = Domain() domain.update() except Exception as e: logging.error('Error: {0}'.format(e)) abort(500) return resp.content, resp.status_code, resp.headers.items()
def updatesettings(state): record = Setting.objects.first() if record: record.current = state else: record = Setting(current=state) record.save()
def decorated_function(*args, **kwargs): if g.user.role.name not in [ 'Administrator', 'Operator' ] and not Setting().get('allow_user_create_domain'): return redirect(url_for('error', code=401)) return f(*args, **kwargs)
def decorated_function(*args, **kwargs): if g.user.role.name not in [ 'Administrator', 'Operator' ] and not Setting().get('allow_user_create_domain'): msg = "User {0} does not have enough privileges to create domain" logging.error(msg.format(g.user.username)) raise NotEnoughPrivileges() return f(*args, **kwargs)
def admin_settings_toggle(): """View to toggle an admin setting.""" setting = request.form.get('setting') result = Setting().toggle(setting) if result: return make_response(jsonify({'status': 'ok', 'msg': 'Toggled setting successfully.'}), 200) else: return make_response(jsonify({'status': 'error', 'msg': 'Unable to toggle setting.'}), 500)
def google_oauth(): if not Setting().get('google_oauth_enabled'): return None google = oauth_client.remote_app( 'google', consumer_key=Setting().get('google_oauth_client_id'), consumer_secret=Setting().get('google_oauth_client_secret'), request_token_params=literal_eval(Setting().get('google_token_params')), base_url=Setting().get('google_base_url'), request_token_url=None, access_token_method='POST', access_token_url=Setting().get('google_token_url'), authorize_url=Setting().get('google_authorize_url'), ) @app.route('/google/authorized') def google_authorized(): resp = google.authorized_response() if resp is None: return 'Access denied: reason=%s error=%s' % ( request.args['error_reason'], request.args['error_description'] ) session['google_token'] = (resp['access_token'], '') return redirect(url_for('.login')) @google.tokengetter def get_google_oauth_token(): return session.get('google_token') return google
def github_oauth(): if not Setting().get('github_oauth_enabled'): return None github = oauth_client.remote_app( 'github', consumer_key = Setting().get('github_oauth_key'), consumer_secret = Setting().get('github_oauth_secret'), request_token_params = {'scope': Setting().get('github_oauth_scope')}, base_url = Setting().get('github_oauth_api_url'), request_token_url = None, access_token_method = 'POST', access_token_url = Setting().get('github_oauth_token_url'), authorize_url = Setting().get('github_oauth_authorize_url') ) @app.route('/github/authorized') def github_authorized(): session['github_oauthredir'] = url_for('.github_authorized', _external=True) resp = github.authorized_response() if resp is None: return 'Access denied: reason=%s error=%s' % ( request.args['error'], request.args['error_description'] ) session['github_token'] = (resp['access_token'], '') return redirect(url_for('.login')) @github.tokengetter def get_github_oauth_token(): return session.get('github_token') return github
def admin_settings_edit(): """View to Edit Settings.""" setting = request.form.get('setting') new_value = request.form.get('value') result = Setting().set(setting, new_value) if result: return make_response(jsonify({'status': 'ok', 'msg': 'Modified setting successfully.'}), 200) else: return make_response(jsonify({'status': 'error', 'msg': 'Unable to modify setting.'}), 500)
def api_login_create_zone(): pdns_api_url = Setting().get('pdns_api_url') pdns_api_key = Setting().get('pdns_api_key') pdns_version = Setting().get('pdns_version') api_uri_with_prefix = utils.pdns_api_extended_uri(pdns_version) api_full_uri = api_uri_with_prefix + '/servers/localhost/zones' headers = {} headers['X-API-Key'] = pdns_api_key msg_str = "Sending request to powerdns API {0}" msg = msg_str.format(request.get_json(force=True)) logging.debug(msg) resp = utils.fetch_remote( urljoin(pdns_api_url, api_full_uri), method='POST', data=request.get_json(force=True), headers=headers, accept='application/json; q=1' ) if resp.status_code == 201: logging.debug("Request to powerdns API successful") data = request.get_json(force=True) history = History( msg='Add domain {0}'.format(data['name'].rstrip('.')), detail=json.dumps(data), created_by=g.user.username ) history.add() if g.user.role.name not in ['Administrator', 'Operator']: logging.debug("User is ordinary user, assigning created domain") domain = Domain(name=data['name'].rstrip('.')) domain.update() domain.grant_privileges([g.user.username]) domain = Domain() domain.update() return resp.content, resp.status_code, resp.headers.items()
def create_db(): "Create RoseGuarden database" print "Create database (this will remove old data)" db.create_all() User.query.delete() # add syncmaster-user for synchronisation print "Add syncmaster user" syncMasterUser = User('*****@*****.**', SYNC_MASTER_DEFAULT_PASSWORD, 'Sync', 'Master', 1) syncMasterUser.syncMaster = 1 db.session.add(syncMasterUser) # you can add some default user here print "Add admin user" defaultUser1 = User('Administrator', 'Admin1234', 'RoseGuarden', 'Admin', 1) defaultUser1.accessType = 1 db.session.add(defaultUser1) #db.session.add(Door(id = 0, name = 'front door', address = 'http://192.168.2.137', keyMask = 0x01, local = 0x00 )) #db.session.add(Door(id = 0, name = 'front door', address = 'http://192.168.2.138', keyMask = 0x01, local = 0x00 )) #db.session.add(Door(id = 0, name = 'front door', address = 'http://192.168.2.139', keyMask = 0x01, local = 0x00 )) print "Add local door" Door.query.delete() db.session.add( Door(name=config.NODE_NAME, displayName='Local', address='http://localhost', keyMask=0x03, local=0x01, password=config.SYNC_MASTER_DEFAULT_PASSWORD)) print "Add default settings" Setting.query.delete() db.session.add( Setting('NODE_VALID_KEYS_MASK', '3', Setting.SETTINGTYPE_INT)) print "Add log-entry" Action.query.delete() db.session.add( Action(datetime.datetime.utcnow(), config.NODE_NAME, syncMasterUser.firstName + ' ' + syncMasterUser.lastName, syncMasterUser.email, 'Remove all data & regenerate database', 'Init systen', 'L1', 1, 'Internal')) print "Save new database" db.session.commit() print "Successfully create new database"
def select(self, request): pesan = "" if request.method == "GET" and 'stopwords' in request.GET: datatrain = Setting.objects.filter(tag = st.setting_stopwords_file) if len(datatrain) == 0: set = Setting(tag = st.setting_stopwords_file, valuedata = request.GET['stopwords']) set.save() else: datatrain[0].valuedata = request.GET['stopwords'] datatrain[0].save() return self.tampilHalaman(request, pesan)
def get_settings(username): if not username: abort(404) u = User.query.filter_by(username=username).first_or_404() s = Setting.query.filter_by(user_id=u.id) if s.count() == 0: data = UI_SETTINGS s = Setting(user_id=u.id, data=data) db.session.add(s) db.session.commit() else: data = s[0].data return jsonify(data), 201
def init_records(): # Create initial user roles and turn off maintenance mode init_roles(db, [Role('Administrator', 'Administrator'), Role('User', 'User')]) init_settings(db, [ Setting('maintenance', 'False'), Setting('fullscreen_layout', 'True'), Setting('record_helper', 'True'), Setting('login_ldap_first', 'True'), Setting('default_record_table_size', '15'), Setting('default_domain_table_size', '10'), Setting('auto_ptr', 'False') ]) db_commit = db.session.commit() commit_version_control(db_commit)
def update_settings(username): if not username: abort(404) u = User.query.filter_by(username=username).first_or_404() s = Setting.query.filter_by(user_id=u.id) modified = datetime.utcnow() data = request.get_json(force=True) if s.count() == 0: s = Setting(user_id=u.id, data=data, modified=modified) db.session.add(s) else: s = s[0] s.modified = modified s.data = data db.session.commit() return jsonify({'settings update': True}), 201
def add(): try: data = request.json if data is None: return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA) settings = [] response_json = [] for item in data: setting = Setting(name=item['name'], status=item.get('status', 0), value=item.get('value', 0)) db.session.add(setting) db.session.flush() settings.append(setting) response_json.append(setting.to_json()) db.session.commit() return response_ok(response_json) except Exception, ex: db.session.rollback() return response_error(ex.message)
def init_records(): # Create initial user roles and turn off maintenance mode init_roles(db, [Role('Administrator', 'Administrator'), Role('User', 'User')]) init_settings(db, [ Setting('maintenance', 'False'), Setting('fullscreen_layout', 'True'), Setting('record_helper', 'True'), Setting('login_ldap_first', 'True'), Setting('default_record_table_size', '15'), Setting('default_domain_table_size', '10'), Setting('auto_ptr', 'False') ]) # TODO: add sample records to sample templates init_domain_templates(db, [ DomainTemplate('basic_template_1', 'Basic Template #1'), DomainTemplate('basic_template_2', 'Basic Template #2'), DomainTemplate('basic_template_3', 'Basic Template #3') ]) db_commit = db.session.commit() commit_version_control(db_commit)
#!flask/bin/python from migrate.versioning import api from config import SQLALCHEMY_DATABASE_URI from config import SQLALCHEMY_MIGRATE_REPO from app import db from app.models import Role, Setting import os.path db.create_all() # create initial user roles and turn off maintenance mode admin_role = Role('Administrator', 'Administrator') user_role = Role('User', 'User') maintenance_setting = Setting('maintenance', 'False') db.session.add(admin_role) db.session.add(user_role) db.session.add(maintenance_setting) db.session.commit() if not os.path.exists(SQLALCHEMY_MIGRATE_REPO): api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository') api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO) else: api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, api.version(SQLALCHEMY_MIGRATE_REPO))
'MAINTENANCE', 'FULLSCREEN_LAYOUT', 'RECORD_HELPER', 'LOGIN_LDAP_FIRST', 'DEFAULT_RECORD_TABLE_SIZE', 'DEFAULT_DOMAIN_TABLE_SIZE', 'AUTO_PTR', 'RECORD_QUICK_EDIT', 'PRETTY_IPV6_PTR', 'DNSSEC_ADMINS_ONLY', 'ALLOW_USER_CREATE_DOMAIN', 'BG_DOMAIN_UPDATES', 'SITE_NAME', 'SESSION_TIMEOUT', 'PDNS_API_URL', 'PDNS_API_KEY', 'PDNS_VERSION', 'LOCAL_DB_ENABLED', 'SIGNUP_ENABLED', 'LDAP_ENABLED', 'LDAP_TYPE', 'LDAP_URI', 'LDAP_BASE_DN', 'LDAP_ADMIN_USERNAME', 'LDAP_ADMIN_PASSWORD', 'LDAP_FILTER_BASIC', 'LDAP_FILTER_USERNAME', 'LDAP_SG_ENABLED', 'LDAP_ADMIN_GROUP', 'LDAP_OPERATOR_GROUP', 'LDAP_USER_GROUP', 'LDAP_DOMAIN', 'GITHUB_OAUTH_ENABLED', 'GITHUB_OAUTH_KEY', 'GITHUB_OAUTH_SECRET', 'GITHUB_OAUTH_SCOPE', 'GITHUB_OAUTH_API_URL', 'GITHUB_OAUTH_TOKEN_URL', 'GITHUB_OAUTH_AUTHORIZE_URL', 'GOOGLE_OAUTH_ENABLED', 'GOOGLE_OAUTH_CLIENT_ID', 'GOOGLE_OAUTH_CLIENT_SECRET', 'GOOGLE_TOKEN_URL', 'GOOGLE_OAUTH_SCOPE', 'GOOGLE_AUTHORIZE_URL', 'GOOGLE_BASE_URL', 'OIDC_OAUTH_ENABLED', 'OIDC_OAUTH_KEY', 'OIDC_OAUTH_SECRET', 'OIDC_OAUTH_SCOPE', 'OIDC_OAUTH_API_URL', 'OIDC_OAUTH_TOKEN_URL', 'OIDC_OAUTH_AUTHORIZE_URL', 'FORWARD_RECORDS_ALLOW_EDIT', 'REVERSE_RECORDS_ALLOW_EDIT', 'TTL_OPTIONS') # add every setting from environment variables import os import sys for v in legal_envvars_setting: if v in os.environ: name = v.lower() value = os.environ[v] setting = Setting(name=name, value=value) db.session.add(setting) db.session.commit()
def decorated_function(*args, **kwargs): if g.user.role.name != 'Administrator' and Setting().get( 'dnssec_admins_only'): return redirect(url_for('error', code=401)) return f(*args, **kwargs)
(None, 14, None), (None, 15, None), (None, 16, None), (None, 17, None), (None, 18, None), (None, 19, None)] default_cfg = { 'DEBUG': True, 'SECRET_KEY': ''.join([ random.choice(string.ascii_letters + string.digits) for n in xrange(50) ]), 'SQLALCHEMY_COMMIT_ON_TEARDOWN': True, } default_settings = [ Setting(name=u'namespace', value=u''), Setting(name=u'base_url', value=u'2015.igem.org'), Setting(name=u'show_register_page', value=u'true'), Setting(name=u'theme', value=u'simple') ] def make_config(config_folder): with open(os.path.join(config_folder, 'config.yml'), 'w') as f: f.write(yaml.safe_dump(default_cfg, default_flow_style=False)) def install_data(): for setting in default_settings: db.session.add(setting)
#!/usr/bin/env python3 from app import app, db from app.models import Role, Setting, DomainTemplate admin_role = Role(name='Administrator', description='Administrator') user_role = Role(name='User', description='User') setting_1 = Setting(name='maintenance', value='False') setting_2 = Setting(name='fullscreen_layout', value='True') setting_3 = Setting(name='record_helper', value='True') setting_4 = Setting(name='login_ldap_first', value='True') setting_5 = Setting(name='default_record_table_size', value='15') setting_6 = Setting(name='default_domain_table_size', value='10') setting_7 = Setting(name='auto_ptr', value='False') template_1 = DomainTemplate(name='basic_template_1', description='Basic Template #1') template_2 = DomainTemplate(name='basic_template_2', description='Basic Template #2') template_3 = DomainTemplate(name='basic_template_3', description='Basic Template #3') db.session.add(admin_role) db.session.add(user_role) db.session.add(setting_1) db.session.add(setting_2) db.session.add(setting_3) db.session.add(setting_4) db.session.add(setting_5)
from datetime import datetime from app import db from app.models import Setting, Alert_Log, Sensor, Reading_Temperature # Settings db.session.query(Setting).delete() if not Setting.query.filter_by(name='ALARM_THRESHOLD').first(): appset = Setting(name='ALARM_THRESHOLD', value=125) appset.type = "SETTING" db.session.add(appset) db.session.commit() if not Setting.query.filter_by(name='WARNING_THRESHOLD').first(): appset = Setting(name='WARNING_THRESHOLD', value=115) appset.type = "SETTING" db.session.add(appset) db.session.commit() if not Setting.query.filter_by(name='RELAY_1_TYPE').first(): appset = Setting(name='RELAY_1_TYPE', value='latched', type='RELAY_1') db.session.add(appset) appset = Setting(name='RELAY_1_DELAY', value=500, type='RELAY_1') db.session.add(appset) appset = Setting(name='RELAY_1_PIN', value=26, type='RELAY_1') db.session.add(appset) appset = Setting(name='RELAY_2_TYPE', value='momentary', type='RELAY_2') db.session.add(appset) appset = Setting(name='RELAY_2_DELAY', value=1000, type='RELAY_2') db.session.add(appset) appset = Setting(name='RELAY_2_PIN', value=20, type='RELAY_2') db.session.add(appset) appset = Setting(name='RELAY_3_TYPE', value='latched', type='RELAY_3')
syncMasterUser = User('*****@*****.**','pleasechangethepassword','Sync','Master',1) syncMasterUser.syncMaster = 1 defaultUser1 = User('*****@*****.**','konglo2015','Konglomerat','Kommando', 0) defaultUser1.accessType = 1 defaultUser2 = User('*****@*****.**','1234','Marcus','Drobisch',1,'01754404298',0x00,0x03) defaultUser2.accessType = 1 db.session.add(defaultUser1) db.session.add(defaultUser2) #db.session.add(User(id = 0, password = flask_bcrypt.generate_password_hash('1234'), token = base64.encodestring('[email protected]:1234'), tokenExpirationDate= datetime.datetime.utcnow(), firstName = 'Marcus', lastName = 'Drobisch', phone = '0175 4404298', email='*****@*****.**', card_id = '1.1.1.1' , doorLicense = 0x01, deviceLicense = 0x01)) #db.session.add(User(id = 1, password = flask_bcrypt.generate_password_hash('1234'), token = base64.encodestring('[email protected]:1234'), tokenExpirationDate= datetime.datetime.utcnow(), firstName = 'Max', lastName = 'Mustermann', phone = '0175 4404298', email='*****@*****.**', card_id = '2.1.1.1' , doorLicense = 0x00, deviceLicense = 0x00)) Door.query.delete() #db.session.add(Door(id = 0, name = 'front door', address = 'http://192.168.2.137', keyMask = 0x01, local = 0x00 )) #db.session.add(Door(id = 0, name = 'front door', address = 'http://192.168.2.138', keyMask = 0x01, local = 0x00 )) #db.session.add(Door(id = 0, name = 'front door', address = 'http://192.168.2.139', keyMask = 0x01, local = 0x00 )) db.session.add(Door(name = 'Local door', address = 'http://localhost', keyMask = 0x03, local = 0x01 )) db.session.add(Door(name = 'Outer door', address = 'http://192.168.0.59', keyMask = 0x03, local = 0x00 )) db.session.add(Door(name = 'Inner door', address = 'http://10.43.125.7', keyMask = 0x03, local = 0x00 )) Setting.query.delete() db.session.add(Setting('NodeName','Test door',Setting.VALUETYPE_STRING)) db.session.add(Setting('NodeValidKey','0x03',Setting.VALUETYPE_INT)) Log.query.delete() db.session.add(Log(datetime.datetime.utcnow(), 'Test door', syncMasterUser.firstName + ' ' + syncMasterUser.lastName, syncMasterUser.email, 'Remove all data & regenerate database', 'Init systen', 'L1', 1, 'Internal')) db.session.commit()