Fix python code as suggestion from LGTM

This commit is contained in:
Khanh Ngo 2018-08-31 18:00:41 +07:00
parent 3457d9214a
commit e6f82160c1
No known key found for this signature in database
GPG Key ID: B9AE3BAF6D5A7B22
10 changed files with 87 additions and 109 deletions

View File

@ -29,7 +29,7 @@ login_manager = LoginManager()
login_manager.init_app(app) login_manager.init_app(app)
db = SQLAlchemy(app) # database db = SQLAlchemy(app) # database
migrate = Migrate(app, db) # flask-migrate migrate = Migrate(app, db) # flask-migrate
oauth = OAuth(app) # oauth oauth_client = OAuth(app) # oauth
if app.config.get('SAML_ENABLED') and app.config.get('SAML_ENCRYPT'): if app.config.get('SAML_ENABLED') and app.config.get('SAML_ENCRYPT'):
from app.lib import certutil from app.lib import certutil

View File

@ -1,8 +1,7 @@
from functools import wraps from functools import wraps
from flask import g, request, redirect, url_for from flask import g, redirect, url_for
from app import app from app.models import Setting
from app.models import Role, Setting
def admin_role_required(f): def admin_role_required(f):

View File

@ -1,4 +1,3 @@
import os
import logging import logging
class logger(object): class logger(object):

View File

@ -1,5 +1,4 @@
import re import re
import sys
import json import json
import requests import requests
import hashlib import hashlib
@ -10,12 +9,10 @@ from urllib.parse import urlparse
from datetime import datetime, timedelta from datetime import datetime, timedelta
from threading import Thread from threading import Thread
from .certutil import * from .certutil import KEY_FILE, CERT_FILE
if app.config['SAML_ENABLED']: if app.config['SAML_ENABLED']:
from onelogin.saml2.auth import OneLogin_Saml2_Auth from onelogin.saml2.auth import OneLogin_Saml2_Auth
from onelogin.saml2.utils import OneLogin_Saml2_Utils
from onelogin.saml2.settings import OneLogin_Saml2_Settings
from onelogin.saml2.idp_metadata_parser import OneLogin_Saml2_IdPMetadataParser from onelogin.saml2.idp_metadata_parser import OneLogin_Saml2_IdPMetadataParser
idp_timestamp = datetime(1970, 1, 1) idp_timestamp = datetime(1970, 1, 1)
idp_data = None idp_data = None
@ -227,7 +224,7 @@ def prepare_flask_request(request):
def init_saml_auth(req): def init_saml_auth(req):
own_url = '' own_url = ''
if req['https'] is 'on': if req['https'] == 'on':
own_url = 'https://' own_url = 'https://'
else: else:
own_url = 'http://' own_url = 'http://'

View File

@ -1,7 +1,6 @@
import os import os
import ldap import ldap
import ldap.filter import ldap.filter
import time
import base64 import base64
import bcrypt import bcrypt
import itertools import itertools
@ -11,7 +10,6 @@ import re
import dns.reversename import dns.reversename
import dns.inet import dns.inet
import dns.name import dns.name
import sys
import logging as logger import logging as logger
from ast import literal_eval from ast import literal_eval
@ -434,9 +432,9 @@ class User(db.Model):
User.query.filter(User.username == self.username).delete() User.query.filter(User.username == self.username).delete()
db.session.commit() db.session.commit()
return True return True
except: except Exception as e:
db.session.rollback() db.session.rollback()
logging.error('Cannot delete user {0} from DB'.format(self.username)) logging.error('Cannot delete user {0} from DB. DETAIL: {1}'.format(self.username, e))
return False return False
def revoke_privilege(self): def revoke_privilege(self):
@ -451,9 +449,9 @@ class User(db.Model):
DomainUser.query.filter(DomainUser.user_id == user_id).delete() DomainUser.query.filter(DomainUser.user_id == user_id).delete()
db.session.commit() db.session.commit()
return True return True
except: except Exception as e:
db.session.rollback() db.session.rollback()
logging.error('Cannot revoke user {0} privielges'.format(self.username)) logging.error('Cannot revoke user {0} privielges. DETAIL: {1}'.format(self.username, e))
return False return False
return False return False
@ -571,9 +569,9 @@ class Account(db.Model):
db.session.commit() db.session.commit()
return True return True
except: except Exception as e:
db.session.rollback() db.session.rollback()
logging.error('Cannot delete account {0} from DB'.format(self.username)) logging.error('Cannot delete account {0} from DB. DETAIL: {1}'.format(self.username, e))
return False return False
def get_user(self): def get_user(self):
@ -602,18 +600,18 @@ class Account(db.Model):
for uid in removed_ids: for uid in removed_ids:
AccountUser.query.filter(AccountUser.user_id == uid).filter(AccountUser.account_id==account_id).delete() AccountUser.query.filter(AccountUser.user_id == uid).filter(AccountUser.account_id==account_id).delete()
db.session.commit() db.session.commit()
except: except Exception as e:
db.session.rollback() db.session.rollback()
logging.error('Cannot revoke user privielges on account {0}'.format(self.name)) logging.error('Cannot revoke user privielges on account {0}. DETAIL: {1}'.format(self.name, e))
try: try:
for uid in added_ids: for uid in added_ids:
au = AccountUser(account_id, uid) au = AccountUser(account_id, uid)
db.session.add(au) db.session.add(au)
db.session.commit() db.session.commit()
except: except Exception as e:
db.session.rollback() db.session.rollback()
logging.error('Cannot grant user privileges to account {0}'.format(self.name)) logging.error('Cannot grant user privileges to account {0}. DETAIL: {1}'.format(self.name, e))
def revoke_privileges_by_id(self, user_id): def revoke_privileges_by_id(self, user_id):
""" """
@ -634,9 +632,9 @@ class Account(db.Model):
db.session.add(au) db.session.add(au)
db.session.commit() db.session.commit()
return True return True
except: except Exception as e:
db.session.rollback() db.session.rollback()
logging.error('Cannot add user privielges on account {0}'.format(self.name)) logging.error('Cannot add user privielges on account {0}. DETAIL: {1}'.format(self.name, e))
return False return False
def remove_user(self, user): def remove_user(self, user):
@ -647,9 +645,9 @@ class Account(db.Model):
AccountUser.query.filter(AccountUser.user_id == user.id).filter(AccountUser.account_id == self.id).delete() AccountUser.query.filter(AccountUser.user_id == user.id).filter(AccountUser.account_id == self.id).delete()
db.session.commit() db.session.commit()
return True return True
except: except Exception as e:
db.session.rollback() db.session.rollback()
logging.error('Cannot revoke user privielges on account {0}'.format(self.name)) logging.error('Cannot revoke user privielges on account {0}. DETAIL: {1}'.format(self.name, e))
return False return False
@ -698,8 +696,8 @@ class DomainSetting(db.Model):
self.value = value self.value = value
db.session.commit() db.session.commit()
return True return True
except: except Exception as e:
logging.error('Unable to set DomainSetting value') logging.error('Unable to set DomainSetting value. DETAIL: {0}'.format(e))
logging.debug(traceback.format_exc()) logging.debug(traceback.format_exc())
db.session.rollback() db.session.rollback()
return False return False
@ -775,7 +773,8 @@ class Domain(db.Model):
try: try:
domain = Domain.query.filter(Domain.name==name).first() domain = Domain.query.filter(Domain.name==name).first()
return domain.id return domain.id
except: except Exception as e:
logging.error('Domain does not exist. ERROR: {1}'.format(e))
return None return None
def update(self): def update(self):
@ -809,8 +808,8 @@ class Domain(db.Model):
# then remove domain # then remove domain
Domain.query.filter(Domain.name == d).delete() Domain.query.filter(Domain.name == d).delete()
db.session.commit() db.session.commit()
except: except Exception as e:
logging.error('Can not delete domain from DB') logging.error('Can not delete domain from DB. DETAIL: {0}'.format(e))
logging.debug(traceback.format_exc()) logging.debug(traceback.format_exc())
db.session.rollback() db.session.rollback()
@ -902,7 +901,7 @@ class Domain(db.Model):
return {'status': 'ok', 'msg': 'Added domain successfully'} return {'status': 'ok', 'msg': 'Added domain successfully'}
except Exception as e: except Exception as e:
logging.error('Cannot add domain {0}'.format(domain_name)) logging.error('Cannot add domain {0}'.format(domain_name))
logging.debug(traceback.print_exc()) logging.debug(traceback.format_exc())
return {'status': 'error', 'msg': 'Cannot add this domain.'} return {'status': 'error', 'msg': 'Cannot add this domain.'}
def update_soa_setting(self, domain_name, soa_edit_api): def update_soa_setting(self, domain_name, soa_edit_api):
@ -1000,12 +999,12 @@ class Domain(db.Model):
headers = {} headers = {}
headers['X-API-Key'] = self.PDNS_API_KEY headers['X-API-Key'] = self.PDNS_API_KEY
try: try:
jdata = utils.fetch_json(urljoin(self.PDNS_STATS_URL, self.API_EXTENDED_URL + '/servers/localhost/zones/{0}'.format(domain_name)), headers=headers, method='DELETE') utils.fetch_json(urljoin(self.PDNS_STATS_URL, self.API_EXTENDED_URL + '/servers/localhost/zones/{0}'.format(domain_name)), headers=headers, method='DELETE')
logging.info('Delete domain {0} successfully'.format(domain_name)) logging.info('Delete domain {0} successfully'.format(domain_name))
return {'status': 'ok', 'msg': 'Delete domain successfully'} return {'status': 'ok', 'msg': 'Delete domain successfully'}
except Exception as e: except Exception as e:
logging.error('Cannot delete domain {0}'.format(domain_name)) logging.error('Cannot delete domain {0}'.format(domain_name))
logging.debug(traceback.print_exc()) logging.debug(traceback.format_exc())
return {'status': 'error', 'msg': 'Cannot delete domain'} return {'status': 'error', 'msg': 'Cannot delete domain'}
def get_user(self): def get_user(self):
@ -1035,18 +1034,18 @@ class Domain(db.Model):
for uid in removed_ids: for uid in removed_ids:
DomainUser.query.filter(DomainUser.user_id == uid).filter(DomainUser.domain_id==domain_id).delete() DomainUser.query.filter(DomainUser.user_id == uid).filter(DomainUser.domain_id==domain_id).delete()
db.session.commit() db.session.commit()
except: except Exception as e:
db.session.rollback() db.session.rollback()
logging.error('Cannot revoke user privielges on domain {0}'.format(self.name)) logging.error('Cannot revoke user privielges on domain {0}. DETAIL: {1}'.format(self.name, e))
try: try:
for uid in added_ids: for uid in added_ids:
du = DomainUser(domain_id, uid) du = DomainUser(domain_id, uid)
db.session.add(du) db.session.add(du)
db.session.commit() db.session.commit()
except: except Exception as e:
db.session.rollback() db.session.rollback()
logging.error('Cannot grant user privielges to domain {0}'.format(self.name)) logging.error('Cannot grant user privielges to domain {0}. DETAIL: {1}'.format(self.name, e))
def update_from_master(self, domain_name): def update_from_master(self, domain_name):
""" """
@ -1057,9 +1056,10 @@ class Domain(db.Model):
headers = {} headers = {}
headers['X-API-Key'] = self.PDNS_API_KEY headers['X-API-Key'] = self.PDNS_API_KEY
try: try:
jdata = utils.fetch_json(urljoin(self.PDNS_STATS_URL, self.API_EXTENDED_URL + '/servers/localhost/zones/{0}/axfr-retrieve'.format(domain.name)), headers=headers, method='PUT') utils.fetch_json(urljoin(self.PDNS_STATS_URL, self.API_EXTENDED_URL + '/servers/localhost/zones/{0}/axfr-retrieve'.format(domain.name)), headers=headers, method='PUT')
return {'status': 'ok', 'msg': 'Update from Master successfully'} return {'status': 'ok', 'msg': 'Update from Master successfully'}
except: except Exception as e:
logging.error('Cannot update from master. DETAIL: {0}'.format(e))
return {'status': 'error', 'msg': 'There was something wrong, please contact administrator'} return {'status': 'error', 'msg': 'There was something wrong, please contact administrator'}
else: else:
return {'status': 'error', 'msg': 'This domain doesnot exist'} return {'status': 'error', 'msg': 'This domain doesnot exist'}
@ -1078,7 +1078,8 @@ class Domain(db.Model):
return {'status': 'error', 'msg': 'DNSSEC is not enabled for this domain'} return {'status': 'error', 'msg': 'DNSSEC is not enabled for this domain'}
else: else:
return {'status': 'ok', 'dnssec': jdata} return {'status': 'ok', 'dnssec': jdata}
except: except Exception as e:
logging.error('Cannot get domain dnssec. DETAIL: {0}'.format(e))
return {'status': 'error', 'msg': 'There was something wrong, please contact administrator'} return {'status': 'error', 'msg': 'There was something wrong, please contact administrator'}
else: else:
return {'status': 'error', 'msg': 'This domain doesnot exist'} return {'status': 'error', 'msg': 'This domain doesnot exist'}
@ -1111,8 +1112,9 @@ class Domain(db.Model):
return {'status': 'ok'} return {'status': 'ok'}
except: except Exception as e:
logging.error(traceback.print_exc()) logging.error('Cannot enable dns sec. DETAIL: {}'.format(e))
logging.debug(traceback.format_exc())
return {'status': 'error', 'msg': 'There was something wrong, please contact administrator'} return {'status': 'error', 'msg': 'There was something wrong, please contact administrator'}
else: else:
@ -1142,8 +1144,9 @@ class Domain(db.Model):
return {'status': 'ok'} return {'status': 'ok'}
except: except Exception as e:
logging.error(traceback.print_exc()) logging.error('Cannot delete dnssec key. DETAIL: {0}'.format(e))
logging.debug(traceback.format_exc())
return {'status': 'error', 'msg': 'There was something wrong, please contact administrator','domain': domain.name, 'id': key_id} return {'status': 'error', 'msg': 'There was something wrong, please contact administrator','domain': domain.name, 'id': key_id}
else: else:
@ -1181,10 +1184,9 @@ class Domain(db.Model):
if 'error' in jdata.keys(): if 'error' in jdata.keys():
logging.error(jdata['error']) logging.error(jdata['error'])
return {'status': 'error', 'msg': jdata['error']} return {'status': 'error', 'msg': jdata['error']}
else: else:
self.update() self.update()
logging.info('account changed for domain {0} successfully'.format(domain_name)) logging.info('Account changed for domain {0} successfully'.format(domain_name))
return {'status': 'ok', 'msg': 'account changed successfully'} return {'status': 'ok', 'msg': 'account changed successfully'}
except Exception as e: except Exception as e:
@ -1193,8 +1195,6 @@ class Domain(db.Model):
logging.error('Cannot change account for domain {0}'.format(domain_name)) logging.error('Cannot change account for domain {0}'.format(domain_name))
return {'status': 'error', 'msg': 'Cannot change account for this domain.'} return {'status': 'error', 'msg': 'Cannot change account for this domain.'}
return {'status': True, 'msg': 'Domain association successful'}
def get_account(self): def get_account(self):
""" """
Get current account associated with this domain Get current account associated with this domain
@ -1264,8 +1264,8 @@ class Record(object):
headers['X-API-Key'] = self.PDNS_API_KEY headers['X-API-Key'] = self.PDNS_API_KEY
try: try:
jdata = utils.fetch_json(urljoin(self.PDNS_STATS_URL, self.API_EXTENDED_URL + '/servers/localhost/zones/{0}'.format(domain)), headers=headers) jdata = utils.fetch_json(urljoin(self.PDNS_STATS_URL, self.API_EXTENDED_URL + '/servers/localhost/zones/{0}'.format(domain)), headers=headers)
except: except Exception as e:
logging.error("Cannot fetch domain's record data from remote powerdns api") logging.error("Cannot fetch domain's record data from remote powerdns api. DETAIL: {0}".format(e))
return False return False
if self.NEW_SCHEMA: if self.NEW_SCHEMA:
@ -1562,7 +1562,6 @@ class Record(object):
self.add(domain_reverse_name) self.add(domain_reverse_name)
for r in deleted_records: for r in deleted_records:
if r['type'] in ['A', 'AAAA']: if r['type'] in ['A', 'AAAA']:
r_name = r['name'] + '.'
r_content = r['content'] r_content = r['content']
reverse_host_address = dns.reversename.from_address(r_content).to_text() reverse_host_address = dns.reversename.from_address(r_content).to_text()
domain_reverse_name = d.get_reverse_domain_name(reverse_host_address) domain_reverse_name = d.get_reverse_domain_name(reverse_host_address)
@ -1595,8 +1594,8 @@ class Record(object):
jdata = utils.fetch_json(urljoin(self.PDNS_STATS_URL, self.API_EXTENDED_URL + '/servers/localhost/zones/{0}'.format(domain)), headers=headers, method='PATCH', data=data) jdata = utils.fetch_json(urljoin(self.PDNS_STATS_URL, self.API_EXTENDED_URL + '/servers/localhost/zones/{0}'.format(domain)), headers=headers, method='PATCH', data=data)
logging.debug(jdata) logging.debug(jdata)
return {'status': 'ok', 'msg': 'Record was removed successfully'} return {'status': 'ok', 'msg': 'Record was removed successfully'}
except: except Exception as e:
logging.error("Cannot remove record {0}/{1}/{2} from domain {3}".format(self.name, self.type, self.data, domain)) logging.error("Cannot remove record {0}/{1}/{2} from domain {3}. DETAIL: {4}".format(self.name, self.type, self.data, domain, e))
return {'status': 'error', 'msg': 'There was something wrong, please contact administrator'} return {'status': 'error', 'msg': 'There was something wrong, please contact administrator'}
def is_allowed_edit(self): def is_allowed_edit(self):
@ -1672,7 +1671,7 @@ class Record(object):
] ]
} }
try: try:
jdata = utils.fetch_json(urljoin(self.PDNS_STATS_URL, self.API_EXTENDED_URL + '/servers/localhost/zones/{0}'.format(domain)), headers=headers, method='PATCH', data=data) utils.fetch_json(urljoin(self.PDNS_STATS_URL, self.API_EXTENDED_URL + '/servers/localhost/zones/{0}'.format(domain)), headers=headers, method='PATCH', data=data)
logging.debug("dyndns data: {0}".format(data)) logging.debug("dyndns data: {0}".format(data))
return {'status': 'ok', 'msg': 'Record was updated successfully'} return {'status': 'ok', 'msg': 'Record was updated successfully'}
except Exception as e: except Exception as e:
@ -1719,8 +1718,8 @@ class Server(object):
try: try:
jdata = utils.fetch_json(urljoin(self.PDNS_STATS_URL, self.API_EXTENDED_URL + '/servers/{0}/config'.format(self.server_id)), headers=headers, method='GET') jdata = utils.fetch_json(urljoin(self.PDNS_STATS_URL, self.API_EXTENDED_URL + '/servers/{0}/config'.format(self.server_id)), headers=headers, method='GET')
return jdata return jdata
except: except Exception as e:
logging.error("Can not get server configuration.") logging.error("Can not get server configuration. DETAIL: {0}".format(e))
logging.debug(traceback.format_exc()) logging.debug(traceback.format_exc())
return [] return []
@ -1734,8 +1733,8 @@ class Server(object):
try: try:
jdata = utils.fetch_json(urljoin(self.PDNS_STATS_URL, self.API_EXTENDED_URL + '/servers/{0}/statistics'.format(self.server_id)), headers=headers, method='GET') jdata = utils.fetch_json(urljoin(self.PDNS_STATS_URL, self.API_EXTENDED_URL + '/servers/{0}/statistics'.format(self.server_id)), headers=headers, method='GET')
return jdata return jdata
except: except Exception as e:
logging.error("Can not get server statistics.") logging.error("Can not get server statistics. DETAIL: {0}".format(e))
logging.debug(traceback.format_exc()) logging.debug(traceback.format_exc())
return [] return []
@ -1773,13 +1772,13 @@ class History(db.Model):
Remove all history from DB Remove all history from DB
""" """
try: try:
num_rows_deleted = db.session.query(History).delete() db.session.query(History).delete()
db.session.commit() db.session.commit()
logging.info("Removed all history") logging.info("Removed all history")
return True return True
except: except Exception as e:
db.session.rollback() db.session.rollback()
logging.error("Cannot remove history") logging.error("Cannot remove history. DETAIL: {0}".format(e))
logging.debug(traceback.format_exc()) logging.debug(traceback.format_exc())
return False return False
@ -1863,8 +1862,8 @@ class Setting(db.Model):
maintenance.value = mode maintenance.value = mode
db.session.commit() db.session.commit()
return True return True
except: except Exception as e:
logging.error('Cannot set maintenance to {0}'.format(mode)) logging.error('Cannot set maintenance to {0}. DETAIL: {1}'.format(mode, e))
logging.debug(traceback.format_exec()) logging.debug(traceback.format_exec())
db.session.rollback() db.session.rollback()
return False return False
@ -1884,8 +1883,8 @@ class Setting(db.Model):
current_setting.value = "True" current_setting.value = "True"
db.session.commit() db.session.commit()
return True return True
except: except Exception as e:
logging.error('Cannot toggle setting {0}'.format(setting)) logging.error('Cannot toggle setting {0}. DETAIL: {1}'.format(setting, e))
logging.debug(traceback.format_exec()) logging.debug(traceback.format_exec())
db.session.rollback() db.session.rollback()
return False return False
@ -1903,8 +1902,8 @@ class Setting(db.Model):
current_setting.value = value current_setting.value = value
db.session.commit() db.session.commit()
return True return True
except: except Exception as e:
logging.error('Cannot edit setting {0}'.format(setting)) logging.error('Cannot edit setting {0}. DETAIL: {1}'.format(setting, e))
logging.debug(traceback.format_exec()) logging.debug(traceback.format_exec())
db.session.rollback() db.session.rollback()
return False return False

View File

@ -1,8 +1,7 @@
from ast import literal_eval from ast import literal_eval
from flask import request, session, redirect, url_for from flask import request, session, redirect, url_for
from flask_oauthlib.client import OAuth
from app import app, oauth from app import app, oauth_client
from app.models import Setting from app.models import Setting
# TODO: # TODO:
@ -13,7 +12,7 @@ def github_oauth():
if not Setting().get('github_oauth_enabled'): if not Setting().get('github_oauth_enabled'):
return None return None
github = oauth.remote_app( github = oauth_client.remote_app(
'github', 'github',
consumer_key = Setting().get('github_oauth_key'), consumer_key = Setting().get('github_oauth_key'),
consumer_secret = Setting().get('github_oauth_secret'), consumer_secret = Setting().get('github_oauth_secret'),
@ -48,7 +47,7 @@ def google_oauth():
if not Setting().get('google_oauth_enabled'): if not Setting().get('google_oauth_enabled'):
return None return None
google = oauth.remote_app( google = oauth_client.remote_app(
'google', 'google',
consumer_key=Setting().get('google_oauth_client_id'), consumer_key=Setting().get('google_oauth_client_id'),
consumer_secret=Setting().get('google_oauth_client_secret'), consumer_secret=Setting().get('google_oauth_client_secret'),

View File

@ -1,5 +1,4 @@
import base64 import base64
import json
import logging as logger import logging as logger
import os import os
import traceback import traceback
@ -10,13 +9,11 @@ from functools import wraps
from io import BytesIO from io import BytesIO
from ast import literal_eval from ast import literal_eval
import jinja2
import qrcode as qrc import qrcode as qrc
import qrcode.image.svg as qrc_svg import qrcode.image.svg as qrc_svg
from flask import g, request, make_response, jsonify, render_template, session, redirect, url_for, send_from_directory, abort, flash from flask import g, request, make_response, jsonify, render_template, session, redirect, url_for, send_from_directory, abort, flash
from flask_login import login_user, logout_user, current_user, login_required from flask_login import login_user, logout_user, current_user, login_required
from werkzeug import secure_filename from werkzeug import secure_filename
from werkzeug.security import gen_salt
from .models import User, Account, Domain, Record, Role, Server, History, Anonymous, Setting, DomainSetting, DomainTemplate, DomainTemplateRecord from .models import User, Account, Domain, Record, Role, Server, History, Anonymous, Setting, DomainSetting, DomainTemplate, DomainTemplateRecord
from app import app, login_manager from app import app, login_manager
@ -25,7 +22,6 @@ from app.oauth import github_oauth, google_oauth
from app.decorators import admin_role_required, operator_role_required, can_access_domain, can_configure_dnssec from app.decorators import admin_role_required, operator_role_required, can_access_domain, can_configure_dnssec
if app.config['SAML_ENABLED']: if app.config['SAML_ENABLED']:
from onelogin.saml2.auth import OneLogin_Saml2_Auth
from onelogin.saml2.utils import OneLogin_Saml2_Utils from onelogin.saml2.utils import OneLogin_Saml2_Utils
google = None google = None
@ -284,7 +280,6 @@ def saml_authorized():
@app.route('/login', methods=['GET', 'POST']) @app.route('/login', methods=['GET', 'POST'])
@login_manager.unauthorized_handler @login_manager.unauthorized_handler
def login(): def login():
LOGIN_TITLE = app.config['LOGIN_TITLE'] if 'LOGIN_TITLE' in app.config.keys() else ''
SAML_ENABLED = app.config.get('SAML_ENABLED') SAML_ENABLED = app.config.get('SAML_ENABLED')
if g.user is not None and current_user.is_authenticated: if g.user is not None and current_user.is_authenticated:
@ -454,7 +449,7 @@ def dashboard():
BG_DOMAIN_UPDATE = Setting().get('bg_domain_updates') BG_DOMAIN_UPDATE = Setting().get('bg_domain_updates')
if not BG_DOMAIN_UPDATE: if not BG_DOMAIN_UPDATE:
logging.debug('Update domains in foreground') logging.debug('Update domains in foreground')
d = Domain().update() Domain().update()
else: else:
logging.debug('Update domains in background') logging.debug('Update domains in background')
@ -580,7 +575,7 @@ def domain(domain_name):
if StrictVersion(Setting().get('pdns_version')) >= StrictVersion('4.0.0'): if StrictVersion(Setting().get('pdns_version')) >= StrictVersion('4.0.0'):
for jr in jrecords: for jr in jrecords:
if jr['type'] in Setting().get_records_allow_to_edit(): if jr['type'] in records_allow_to_edit:
for subrecord in jr['records']: for subrecord in jr['records']:
record = Record(name=jr['name'], type=jr['type'], status='Disabled' if subrecord['disabled'] else 'Active', ttl=jr['ttl'], data=subrecord['content']) record = Record(name=jr['name'], type=jr['type'], status='Disabled' if subrecord['disabled'] else 'Active', ttl=jr['ttl'], data=subrecord['content'])
records.append(record) records.append(record)
@ -591,7 +586,7 @@ def domain(domain_name):
return render_template('domain.html', domain=domain, records=records, editable_records=editable_records, quick_edit=quick_edit) return render_template('domain.html', domain=domain, records=records, editable_records=editable_records, quick_edit=quick_edit)
else: else:
for jr in jrecords: for jr in jrecords:
if jr['type'] in Setting().get_records_allow_to_edit(): if jr['type'] in records_allow_to_edit:
record = Record(name=jr['name'], type=jr['type'], status='Disabled' if jr['disabled'] else 'Active', ttl=jr['ttl'], data=jr['content']) record = Record(name=jr['name'], type=jr['type'], status='Disabled' if jr['disabled'] else 'Active', ttl=jr['ttl'], data=jr['content'])
records.append(record) records.append(record)
if not re.search('ip6\.arpa|in-addr\.arpa$', domain_name): if not re.search('ip6\.arpa|in-addr\.arpa$', domain_name):
@ -651,7 +646,7 @@ def domain_add():
else: else:
return render_template('errors/400.html', msg=result['msg']), 400 return render_template('errors/400.html', msg=result['msg']), 400
except: except:
logging.error(traceback.print_exc()) logging.error(traceback.format_exc())
return redirect(url_for('error', code=500)) return redirect(url_for('error', code=500))
else: else:
@ -697,10 +692,6 @@ def domain_management(domain_name):
# username in right column # username in right column
new_user_list = request.form.getlist('domain_multi_user[]') new_user_list = request.form.getlist('domain_multi_user[]')
# get list of user ids to compare
d = Domain(name=domain_name)
domain_user_ids = d.get_user()
# grant/revoke user privielges # grant/revoke user privielges
d.grant_privielges(new_user_list) d.grant_privielges(new_user_list)
@ -718,7 +709,7 @@ def domain_change_soa_edit_api(domain_name):
if not domain: if not domain:
return redirect(url_for('error', code=404)) return redirect(url_for('error', code=404))
new_setting = request.form.get('soa_edit_api') new_setting = request.form.get('soa_edit_api')
if new_setting == None: if new_setting is None:
return redirect(url_for('error', code=500)) return redirect(url_for('error', code=500))
if new_setting == '0': if new_setting == '0':
return redirect(url_for('domain_management', domain_name=domain_name)) return redirect(url_for('domain_management', domain_name=domain_name))
@ -787,7 +778,7 @@ def record_apply(domain_name):
else: else:
return make_response(jsonify( result ), 400) return make_response(jsonify( result ), 400)
except: except:
logging.error(traceback.print_exc()) logging.error(traceback.format_exc())
return make_response(jsonify( {'status': 'error', 'msg': 'Error when applying new changes'} ), 500) return make_response(jsonify( {'status': 'error', 'msg': 'Error when applying new changes'} ), 500)
@ -810,7 +801,7 @@ def record_update(domain_name):
else: else:
return make_response(jsonify( {'status': 'error', 'msg': result['msg']} ), 500) return make_response(jsonify( {'status': 'error', 'msg': result['msg']} ), 500)
except: except:
logging.error(traceback.print_exc()) logging.error(traceback.format_exc())
return make_response(jsonify( {'status': 'error', 'msg': 'Error when applying new changes'} ), 500) return make_response(jsonify( {'status': 'error', 'msg': 'Error when applying new changes'} ), 500)
@ -824,7 +815,7 @@ def record_delete(domain_name, record_name, record_type):
if result['status'] == 'error': if result['status'] == 'error':
print(result['msg']) print(result['msg'])
except: except:
logging.error(traceback.print_exc()) logging.error(traceback.format_exc())
return redirect(url_for('error', code=500)), 500 return redirect(url_for('error', code=500)), 500
return redirect(url_for('domain', domain_name=domain_name)) return redirect(url_for('domain', domain_name=domain_name))
@ -866,7 +857,7 @@ def domain_dnssec_disable(domain_name):
dnssec = domain.get_domain_dnssec(domain_name) dnssec = domain.get_domain_dnssec(domain_name)
for key in dnssec['dnssec']: for key in dnssec['dnssec']:
response = domain.delete_dnssec_key(domain_name,key['id']); domain.delete_dnssec_key(domain_name,key['id']);
return make_response(jsonify( { 'status': 'ok', 'msg': 'DNSSEC removed.' } )) return make_response(jsonify( { 'status': 'ok', 'msg': 'DNSSEC removed.' } ))
@ -907,7 +898,7 @@ def admin_setdomainsetting(domain_name):
else: else:
return make_response(jsonify( { 'status': 'error', 'msg': 'Action not supported.' } ), 400) return make_response(jsonify( { 'status': 'error', 'msg': 'Action not supported.' } ), 400)
except: except:
logging.error(traceback.print_exc()) logging.error(traceback.format_exc())
return make_response(jsonify( { 'status': 'error', 'msg': 'There is something wrong, please contact Administrator.' } ), 400) return make_response(jsonify( { 'status': 'error', 'msg': 'There is something wrong, please contact Administrator.' } ), 400)
@ -938,6 +929,7 @@ def create_template():
if DomainTemplate.query.filter(DomainTemplate.name == name).first(): if DomainTemplate.query.filter(DomainTemplate.name == name).first():
flash("A template with the name {0} already exists!".format(name), 'error') flash("A template with the name {0} already exists!".format(name), 'error')
return redirect(url_for('create_template')) return redirect(url_for('create_template'))
t = DomainTemplate(name=name, description=description) t = DomainTemplate(name=name, description=description)
result = t.create() result = t.create()
if result['status'] == 'ok': if result['status'] == 'ok':
@ -948,9 +940,8 @@ def create_template():
flash(result['msg'], 'error') flash(result['msg'], 'error')
return redirect(url_for('create_template')) return redirect(url_for('create_template'))
except: except:
logging.error(traceback.print_exc()) logging.error(traceback.format_exc())
return redirect(url_for('error', code=500)) return redirect(url_for('error', code=500))
return redirect(url_for('templates'))
@app.route('/template/createfromzone', methods=['POST']) @app.route('/template/createfromzone', methods=['POST'])
@ -1003,13 +994,13 @@ def create_template_from_zone():
if result_records['status'] == 'ok': if result_records['status'] == 'ok':
return make_response(jsonify({'status': 'ok', 'msg': result['msg']}), 200) return make_response(jsonify({'status': 'ok', 'msg': result['msg']}), 200)
else: else:
result = t.delete_template() t.delete_template()
return make_response(jsonify({'status': 'error', 'msg': result_records['msg']}), 500) return make_response(jsonify({'status': 'error', 'msg': result_records['msg']}), 500)
else: else:
return make_response(jsonify({'status': 'error', 'msg': result['msg']}), 500) return make_response(jsonify({'status': 'error', 'msg': result['msg']}), 500)
except: except:
logging.error(traceback.print_exc()) logging.error(traceback.format_exc())
return make_response(jsonify({'status': 'error', 'msg': 'Error when applying new changes'}), 500) return make_response(jsonify({'status': 'error', 'msg': 'Error when applying new changes'}), 500)
@ -1029,7 +1020,7 @@ def edit_template(template):
return render_template('template_edit.html', template=t.name, records=records, editable_records=records_allow_to_edit) return render_template('template_edit.html', template=t.name, records=records, editable_records=records_allow_to_edit)
except: except:
logging.error(traceback.print_exc()) logging.error(traceback.format_exc())
return redirect(url_for('error', code=500)) return redirect(url_for('error', code=500))
return redirect(url_for('templates')) return redirect(url_for('templates'))
@ -1060,7 +1051,7 @@ def apply_records(template):
else: else:
return make_response(jsonify(result), 400) return make_response(jsonify(result), 400)
except: except:
logging.error(traceback.print_exc()) logging.error(traceback.format_exc())
return make_response(jsonify({'status': 'error', 'msg': 'Error when applying new changes'}), 500) return make_response(jsonify({'status': 'error', 'msg': 'Error when applying new changes'}), 500)
@ -1080,7 +1071,7 @@ def delete_template(template):
flash(result['msg'], 'error') flash(result['msg'], 'error')
return redirect(url_for('templates')) return redirect(url_for('templates'))
except: except:
logging.error(traceback.print_exc()) logging.error(traceback.format_exc())
return redirect(url_for('error', code=500)) return redirect(url_for('error', code=500))
return redirect(url_for('templates')) return redirect(url_for('templates'))
@ -1226,7 +1217,7 @@ def admin_manageuser():
else: else:
return make_response(jsonify( { 'status': 'error', 'msg': 'Action not supported.' } ), 400) return make_response(jsonify( { 'status': 'error', 'msg': 'Action not supported.' } ), 400)
except: except:
logging.error(traceback.print_exc()) logging.error(traceback.format_exc())
return make_response(jsonify( { 'status': 'error', 'msg': 'There is something wrong, please contact Administrator.' } ), 400) return make_response(jsonify( { 'status': 'error', 'msg': 'There is something wrong, please contact Administrator.' } ), 400)
@ -1315,7 +1306,7 @@ def admin_manageaccount():
else: else:
return make_response(jsonify( { 'status': 'error', 'msg': 'Action not supported.' } ), 400) return make_response(jsonify( { 'status': 'error', 'msg': 'Action not supported.' } ), 400)
except: except:
logging.error(traceback.print_exc()) logging.error(traceback.format_exc())
return make_response(jsonify( { 'status': 'error', 'msg': 'There is something wrong, please contact Administrator.' } ), 400) return make_response(jsonify( { 'status': 'error', 'msg': 'There is something wrong, please contact Administrator.' } ), 400)

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from app import app, db from app import db
from app.models import Role, Setting, DomainTemplate from app.models import Role, DomainTemplate
admin_role = Role(name='Administrator', description='Administrator') admin_role = Role(name='Administrator', description='Administrator')
user_role = Role(name='User', description='User') user_role = Role(name='User', description='User')

6
run.py
View File

@ -1,11 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from app import app from app import app
from config import PORT from config import PORT
from config import BIND_ADDRESS
try:
from config import BIND_ADDRESS
except:
BIND_ADDRESS = '127.0.0.1'
if __name__ == '__main__': if __name__ == '__main__':
app.run(debug = True, host=BIND_ADDRESS, port=PORT) app.run(debug = True, host=BIND_ADDRESS, port=PORT)

View File

@ -10,8 +10,6 @@
############################################################## ##############################################################
### Imports ### Imports
from app import app
from app.lib import log
from app.models import Domain from app.models import Domain
from config import BG_DOMAIN_UPDATES from config import BG_DOMAIN_UPDATES