Beispiel #1
0
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
Beispiel #2
0
 def handle(self, *args, **options):
     try:
         Setting.set_processing(True)
         eps = 0.05
         try:
             rates = ExchangeRate.objects.all()
             last_date = rates.last().date
             last_rates = rates.filter(date=last_date)
         except:
             raise CommandError('No old rates')
         today = t()
         while last_date != today:
             next_date = last_date + relativedelta(days=1)
             next_rates = []
             for rate in last_rates:
                 delta = (random() * eps) + 1 - (eps / 2)
                 exchange_rate = ExchangeRate(
                     date=next_date,
                     from_currency=rate.from_currency,
                     to_currency=rate.to_currency,
                     index=rate.index * delta)
                 next_rates.append(exchange_rate)
                 exchange_rate.save()
             last_date, last_rates = next_date, next_rates
     finally:
         Setting.set_processing(False)
Beispiel #3
0
def updatesettings(state):
    record = Setting.objects.first()
    if record:
        record.current = state
    else:
        record = Setting(current=state)
    record.save()
 def handle(self, *args, **options):
     try:
         days = ((today() + relativedelta(months=1)) - today()).days
         for _ in range(days):
             jump_day.Command().handle()
     finally:
         Setting.set_processing(False)
Beispiel #5
0
def create_user():
    user = User(request.json)
    if user.create():
        Setting.create(user.username)
        return dict()
    else:
        return error_response('User with this email or number already exists',
                              409)
Beispiel #6
0
 def handle(self, *args, **options):
     try:
         Setting.set_processing(True)
         hours = Setting.objects.get_or_create(name='hours')[0]
         hours.value += 1
         hours.save()
     finally:
         Setting.set_processing(False)
Beispiel #7
0
 def handle(self, *args, **options):
     try:
         Setting.set_processing(True)
         call_command('loaddata', '100/users', app_label='app')
         call_command('loaddata', '100/bill', app_label='app')
         call_command('loaddata', '100/contract', app_label='app')
     finally:
         Setting.set_processing(False)
Beispiel #8
0
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'])
Beispiel #9
0
 def handle(self, *args, **options):
     try:
         Setting.set_processing(True)
         pay_contracts = Contract.objects.filter(
             is_act=True
         )
         for contract in pay_contracts:
             contract.super_pay()
     finally:
         Setting.set_processing(False)
Beispiel #10
0
 def handle(self, *args, **options):
     try:
         Setting.set_processing(True)
         pay.Command().handle()
         days = Setting.objects.get_or_create(name='days')[0]
         days.value += 1
         days.save()
         rates.Command().handle()
     finally:
         Setting.set_processing(False)
Beispiel #11
0
 def handle(self, *args, **options):
     try:
         Setting.set_processing(True)
         call_command('loaddata', 'users', app_label='app')
         call_command('loaddata', 'currencies', app_label='app')
         call_command('loaddata', 'exchangerate', app_label='app')
         call_command('loaddata', 'bill', app_label='app')
         call_command('loaddata', 'DepositType', app_label='app')
         call_command('loaddata', 'Deposit', app_label='app')
         rates.Command().handle()
     finally:
         Setting.set_processing(False)
    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)
Beispiel #13
0
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'])
Beispiel #14
0
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 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 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)
Beispiel #17
0
 def current_year(now=datetime.now()):
     """
     :return: current learning year
     """
     # if now.month < 9:  # if not september yet
     #     return now.year - 1
     # return now.year
     return Setting.instance().active_year
 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)
Beispiel #19
0
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)
Beispiel #20
0
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
Beispiel #21
0
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
Beispiel #22
0
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)
Beispiel #23
0
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()
Beispiel #24
0
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
Beispiel #25
0
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 remove(id):
    try:
        setting = Setting.find_setting_by_id(id)
        if setting is not None:
            db.session.delete(setting)
            db.session.commit()
            return response_ok(
                message="{} has been deleted!".format(setting.id))
        else:
            return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

    except Exception, ex:
        db.session.rollback()
        return response_error(ex.message)
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)
Beispiel #28
0
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
Beispiel #29
0
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)
Beispiel #30
0
def inject_admin():
    data = {}
    message = Message.query.order_by(desc(Message.created_at)).first()
    if current_user_is_logged():
        groups = Group.query.order_by(Group.title).order_by(Group.year, Group.title).all()
        admin_groups = OrderedDict()
        for year in Group.active_years():
            admin_groups[year] = [group for group in groups if group.year == year]

        settings = Setting.instance()

        data = {
            'COMPLEX_CHOICES': Task.COMPLEX_CHOICES,
            'current_year': settings.active_year,
            'site_disabled': settings.site_disabled,
            'admin_groups': admin_groups,
            'admin_disciplines': Discipline.query.all(),
        }
    data.update({
        'message': message,
    })
    return data
Beispiel #31
0
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)
Beispiel #32
0
 def get(self):
     instance = Setting.instance()
     return {
         'active_year': instance.active_year
     }