Example #1
0
    def add_user(self, data, req_info, session, curs=None):
        a = Authenticator()
        env_id = session.environment_id
        salt = a.salt()
        u_data = {'environment_id': env_id, 'email': data.get('email'),
            'role': data.get('role', User.ROLE_USER),
            'password': a.encrypt_password(data.get('password'), salt),
            'salt': salt, 'is_active': data.get('is_active', True),
            'lang': data.get('lang', User.DEFAULT_LANG)
        }
        if u_data['role'] == User.ROLE_SUPER:
            raise SuperUserCreationDenied

        groups_ids = data.get('groups_ids', [])
        filtered_g_ids = self._filter_existed_groups(curs, session, groups_ids)
        u_data['groups_ids'] = filtered_g_ids
        user = User(**u_data)
        try:
            mapping.save(curs, user)
        except ObjectCreationError:
            raise HelixauthObjectAlreadyExists

        # For correct action logging
        data['id'] = [user.id]
        n = Notifier()
        n_process = n.register_user(curs, user, session)
        return response_ok(id=user.id, notification=n_process)
Example #2
0
    def register_user(self, data, req_info, curs=None):
        env_name = data.get('environment_name')
        env_f = EnvironmentFilter({'name': env_name}, {}, None)
        env = env_f.filter_one_obj(curs)

        # creating user
        a = Authenticator()
        salt = a.salt()
        lang = data.get('lang', User.DEFAULT_LANG)
        u_data = {'environment_id': env.id, 'email': data.get('email'),
            'password': a.encrypt_password(data.get('password'), salt),
            'salt': salt, 'role': User.ROLE_USER,
            'lang': lang}

        group_f = GroupFilter(env.id, {'is_default': True}, {}, None)
        groups = group_f.filter_objs(curs)
        groups_ids = [g.id for g in groups]

        u_data['groups_ids'] = groups_ids
        user = User(**u_data)

        # For correct action logging
        data['environment_id'] = env.id
        try:
            mapping.save(curs, user)
        except ObjectCreationError:
            raise UserAlreadyExists
        auth = Authenticator()
        session = auth.create_session(curs, env, user, req_info)
        _add_log_info(data, session)

        n = Notifier()
        n_process = n.register_user(curs, user, session)
        return response_ok(session_id=session.session_id, id=user.id,
                           notification=n_process)
Example #3
0
    def add_environment(self, data, req_info, curs=None):
        env_data = {'name': data.get('name')}
        env = Environment(**env_data)
        try:
            mapping.save(curs, env)
        except ObjectCreationError:
            raise HelixauthObjectAlreadyExists('Environment %s already exists' % env.name)

        # creating user
        a = Authenticator()
        salt = a.salt()
        u_data = {'environment_id': env.id, 'email': data.get('su_email'),
            'password': a.encrypt_password(data.get('su_password'), salt),
            'salt': salt, 'role': User.ROLE_SUPER,
            'lang': User.DEFAULT_LANG}
        user = User(**u_data)
        mapping.save(curs, user)

        # creating default services and groups
        self._create_default_objects(req_info, curs, env)

        # creating session for super user
        auth = Authenticator()
        session = auth.create_session(curs, env, user, req_info)

        _add_log_info(data, session)

        return response_ok(session_id=session.session_id,
            environment_id=env.id, user_id=session.user_id)
Example #4
0
 def add_group(self, data, req_info, session, curs=None):
     group = Group(**data)
     group.environment_id = session.environment_id
     try:
         mapping.save(curs, group)
     except ObjectCreationError:
         raise GroupAlreadyExists('Group %s already exists' % group.name)
     return response_ok(id=group.id)
Example #5
0
 def _create_default_notifications(self, curs, env, events):
     notifier = Notifier()
     for event in events:
         e_msgs = notifier.default_email_notif_struct(event)
         n = Notification(environment_id=env.id, event=event,
             is_active=True, type=Notification.TYPE_EMAIL,
             messages=e_msgs)
         mapping.save(curs, n)
Example #6
0
 def _get_session_db(self, session_id, curs=None):
     f = SessionFilter({'session_id': session_id}, {}, {})
     session = f.filter_one_obj(curs, for_update=True)
     valid_after_date = self._session_valid_after_update_date()
     if session.update_date > valid_after_date:
         self._set_update_date(session)
         mapping.save(curs, session)
     else:
         raise SessionExpired()
     return session
Example #7
0
 def add_service(self, data, req_info, session, curs=None):
     d = dict(data)
     d['environment_id'] = session.environment_id
     d['is_possible_deactiate'] = True
     s = Service(**d)
     try:
         mapping.save(curs, s)
     except ObjectCreationError:
         raise HelixauthObjectAlreadyExists
     return response_ok(id=s.id)
Example #8
0
    def _change_session_ip(self, sess_id, curs=None):
        # changing ip in session
        f = SessionFilter({"session_id": sess_id}, {}, None)
        s = f.filter_one_obj(curs)
        data = json.loads(s.serialized_data)
        data["ip"] = "new_%s" % data["ip"]
        s.serialized_data = json.dumps(data)
        mapping.save(curs, s)

        a = Authenticator()
        a._save_session_to_cache(s)
Example #9
0
 def reset_notifications(self, data, req_info, session, curs=None):
     n_ids = data['ids']
     f = NotificatonFilter(session.environment_id, {'ids': n_ids},
         {}, None)
     objs = f.filter_objs(curs, for_update=True)
     n = Notifier()
     for o in objs:
         if o.type == Notification.TYPE_EMAIL:
             msg_struct = n.default_email_notif_struct(o.event)
             o.serialized_messages = json.dumps(msg_struct)
             mapping.save(curs, o)
     return response_ok()
Example #10
0
    def __create_session(self, curs, env, user, req_info,
        bind_to_ip=False, lifetime_minutes=None,
        services_access_list=None):
        """
        @param curs - db cursor
        @param env - environment dataobject
        @param user - user dataobject
        @param req_info - request info, for fetching ip address
        @param bind_to_ip - if True session will be binded with ip from req_info.
          Usage session binded to ip from another ip generates AccessDenied error.
        @param lifetime_minutes - session lifetime. If not None session will be
          valid number of specified minutes after session generating time.
        @param services_acess_list - dict of specified acl for generating sessions
          with restricted access. Access list can't add privileges to user - it used
          only for restriction. All superior privileges will be ignored.
          This behaviour used in password restoration.
        """
        d = datetime.now(pytz.utc)
        session_data = self._get_session_data(curs, env, user)
        self.__merge_access_list(session_data, services_access_list)
        session_data['ip'] = req_info.remote_addr
        session_data['bind_to_ip'] = bind_to_ip
        session_data['fixed_lifetime'] = lifetime_minutes is not None
        if lifetime_minutes is not None:
            if lifetime_minutes > settings.session_max_fixed_lifetime_minutes:
                raise SessionTooLargeFixedLifetime()
            session_data['fixed_lifetime'] = True
            td = lifetime_minutes - settings.session_valid_minutes
            upd_d = d + timedelta(minutes=td)
        else:
            session_data['fixed_lifetime'] = False
            upd_d = d
        data = {
            'session_id': '%s' % uuid4(),
            'environment_id': env.id,
            'user_id': user.id,
            'serialized_data': json.dumps(session_data),
            'start_date': d,
            'update_date': upd_d,
        }
        session = Session(**data)
        mapping.save(curs, session)

        # adding session into memcached
        if settings.session_caching_enabled:
            self._save_session_to_cache(session)

        return session
Example #11
0
    def save_rule(self, data, session, curs=None):
        all_t_f = TariffFilter(session, {}, {}, None)
        all_ts = all_t_f.filter_objs(curs)
        all_ts_idx = build_index(all_ts)

        all_to_f = TarifficationObjectFilter(session, {}, {}, None)
        all_tos = all_to_f.filter_objs(curs)
        all_tos_idx = build_index(all_tos)

        all_r_f = RuleFilter(session, {}, {}, None)
        all_rs = all_r_f.filter_objs(curs)
        all_rs_idx = build_index(all_rs)

        r_data = {
            'environment_id': session.environment_id,
            'tariff_id': data['tariff_id'],
            'status': data['status'],
            'tariffication_object_id': data['tariffication_object_id'],
            'draft_rule': data['draft_rule']
        }
        r_data['view_order'] = data.get('view_order', 0)
        rule_id = data.get('id')
        if rule_id:
            r_data['id'] = rule_id
        r = Rule(**r_data)

        if rule_id and rule_id not in all_rs_idx:
            raise RuleNotFound(id=rule_id)
        if r.tariff_id not in all_ts_idx:
            raise TariffNotFound(rule_id=rule_id, tariff_id=r.tariff_id)
        if r.tariffication_object_id not in all_tos_idx:
            raise TarifficationObjectNotFound(
                rule_id=rule_id,
                tariffication_object_id=r.tariffication_object_id)
        checker = RuleChecker()
        checker.check(r.draft_rule)

        try:
            mapping.save(curs, r)
        except ObjectCreationError:
            raise RuleAlreadyExsits(r)
        return response_ok(id=r.id)
Example #12
0
    def modify_used_currencies(self, data, session, curs=None):
        f = CurrencyFilter({}, {}, None)
        currs = f.filter_objs(curs)
        currs_code_idx = build_index(currs, idx_field='code')
        new_currs_codes = data.pop('new_currencies_codes', [])

        for curr_code in new_currs_codes:
            if curr_code not in currs_code_idx:
                raise CurrencyNotFound(code=curr_code)

        new_currs_ids = [curr.id for curr in currs if curr.code in new_currs_codes]
        data['new_currencies_ids'] = new_currs_ids
        f = UsedCurrencyFilter(session, {}, {}, None)
        try:
            loader = partial(f.filter_one_obj, curs, for_update=True)
            self.update_obj(curs, data, loader)
        except ObjectNotFound:
            u_currs = UsedCurrency(environment_id=session.environment_id,
                currencies_ids=new_currs_ids)
            mapping.save(curs, u_currs)
        return response_ok()
Example #13
0
 def _dump_session(mem_cache, session, curs=None):
     f = SessionFilter({'session_id': session.session_id}, {}, None)
     try:
         s = f.filter_one_obj(curs, for_update=True)
         sess_id = s.session_id.encode('utf8')
         cached_s = mem_cache.get(sess_id)
         if cached_s is None:
             logger.debug("Session %s not found in cache", sess_id)
         else:
             logger.debug("Cached session %s update date: %s",
                 cached_s.session_id, cached_s.update_date)
             logger.debug("Db session %s update date: %s",
                 s.session_id, s.update_date)
             if cached_s.update_date > s.update_date:
                 s.update_date = cached_s.update_date
                 mapping.save(curs, s)
                 logger.debug("Session %s dumped from cache into db", sess_id)
             else:
                 logger.debug("Session %s update_date in db greater or equal " \
                     "cached value. Noting to dump", sess_id)
     except SessionNotFound, e:
         logger.debug("Dumping session failed: %s", e)
Example #14
0
    def save_rule(self, data, session, curs=None):
        all_t_f = TariffFilter(session, {}, {}, None)
        all_ts = all_t_f.filter_objs(curs)
        all_ts_idx = build_index(all_ts)

        all_to_f = TarifficationObjectFilter(session, {}, {}, None)
        all_tos = all_to_f.filter_objs(curs)
        all_tos_idx = build_index(all_tos)

        all_r_f = RuleFilter(session, {}, {}, None)
        all_rs = all_r_f.filter_objs(curs)
        all_rs_idx = build_index(all_rs)

        r_data = {'environment_id': session.environment_id,
            'tariff_id': data['tariff_id'], 'status': data['status'],
            'tariffication_object_id': data['tariffication_object_id'],
            'draft_rule': data['draft_rule']}
        r_data['view_order'] = data.get('view_order', 0)
        rule_id = data.get('id')
        if rule_id:
            r_data['id'] = rule_id
        r = Rule(**r_data)

        if rule_id and rule_id not in all_rs_idx:
            raise RuleNotFound(id=rule_id)
        if r.tariff_id not in all_ts_idx:
            raise TariffNotFound(rule_id=rule_id, tariff_id=r.tariff_id)
        if r.tariffication_object_id not in all_tos_idx:
            raise TarifficationObjectNotFound(rule_id=rule_id,
                tariffication_object_id=r.tariffication_object_id)
        checker = RuleChecker()
        checker.check(r.draft_rule)

        try:
            mapping.save(curs, r)
        except ObjectCreationError:
            raise RuleAlreadyExsits(r)
        return response_ok(id=r.id)
Example #15
0
    def modify_used_currencies(self, data, session, curs=None):
        f = CurrencyFilter({}, {}, None)
        currs = f.filter_objs(curs)
        currs_code_idx = build_index(currs, idx_field='code')
        new_currs_codes = data.pop('new_currencies_codes', [])

        for curr_code in new_currs_codes:
            if curr_code not in currs_code_idx:
                raise CurrencyNotFound(code=curr_code)

        new_currs_ids = [
            curr.id for curr in currs if curr.code in new_currs_codes
        ]
        data['new_currencies_ids'] = new_currs_ids
        f = UsedCurrencyFilter(session, {}, {}, None)
        try:
            loader = partial(f.filter_one_obj, curs, for_update=True)
            self.update_obj(curs, data, loader)
        except ObjectNotFound:
            u_currs = UsedCurrency(environment_id=session.environment_id,
                                   currencies_ids=new_currs_ids)
            mapping.save(curs, u_currs)
        return response_ok()
Example #16
0
 def inactivate_user(self, user, curs=None):
     user.is_active = False
     mapping.save(curs, user)
Example #17
0
 def make_session_expired(self, session_id, curs=None):
     td = timedelta(minutes=settings.session_valid_minutes)
     session = self.get_session(session_id, for_update=True)
     session.start_date = session.start_date - td
     session.update_date = session.update_date - td
     mapping.save(curs, session)
Example #18
0
    def _create_default_services_group(self, req_info, curs, env):
        # adding default service auth
        a_data = self.get_authorized_api_actions({}, req_info)
        actions_auth = a_data['actions']
        d = {'environment_id': env.id, 'name': 'Auth',
            'type': Service.TYPE_AUTH, 'is_active': True,
            'is_possible_deactiate': False, 'properties': actions_auth}
        s_auth = Service(**d)
        mapping.save(curs, s_auth)

        # adding default service billing
        actions_billing = ['get_currencies', 'get_used_currencies', 'modify_used_currencies',
            'get_action_logs', 'get_action_logs_self',
            'add_balance', 'get_balances', 'get_balances_self', 'modify_balances',
            'add_receipt', 'add_bonus', 'lock', 'unlock', 'charge_off',
            'get_locks', 'get_locks_self',
            'get_transactions', 'get_transactions_self']
        d = {'environment_id': env.id, 'name': 'Billing',
            'type': Service.TYPE_BILLING, 'is_active': True,
            'is_possible_deactiate': True, 'properties': actions_billing}
        s_billing = Service(**d)
        mapping.save(curs, s_billing)

        # adding default service tariff
        actions_tariff = ['add_tariffication_object', 'modify_tariffication_object',
            'delete_tariffication_object', 'get_tariffication_objects',
            'add_tariff', 'modify_tariff', 'delete_tariff', 'get_tariffs',
            'save_rule', 'delete_rule', 'apply_draft_rules',
            'get_tariffs_prices', 'get_price', 'get_draft_price',
            'add_user_tariff', 'delete_user_tariff', 'get_user_tariffs']
        d = {'environment_id': env.id, 'name': 'Tariff',
            'type': Service.TYPE_TARIFF, 'is_active': True,
            'is_possible_deactiate': True, 'properties': actions_tariff}
        s_tariff = Service(**d)
        mapping.save(curs, s_tariff)

        # adding groups of administrators and users
        d = {'environment_id': env.id, 'name': 'Administrators', 'is_active': True,
            'rights': [
                {'service_id': s_auth.id, 'properties': actions_auth},
                {'service_id': s_billing.id, 'properties': []}
            ]}
        g = Group(**d)
        mapping.save(curs, g)

        d = {'environment_id': env.id, 'name': 'Billing Administrators', 'is_active': True,
            'rights': [
                {'service_id': s_auth.id, 'properties': ['check_user_exist']},
                {'service_id': s_billing.id, 'properties': actions_billing}
            ]}
        g = Group(**d)
        mapping.save(curs, g)

        d = {'environment_id': env.id, 'name': 'Tariff Administrators', 'is_active': True,
            'rights': [
                {'service_id': s_auth.id, 'properties': ['check_user_exist']},
                {'service_id': s_tariff.id, 'properties': actions_tariff}
            ]}
        g = Group(**d)
        mapping.save(curs, g)

        d = {'environment_id': env.id, 'name': 'Users',
            'is_active': True, 'is_default': True,
            'rights': [
                {'service_id': s_auth.id, 'properties': [
                    'get_user_self', 'modify_user_self',
                    'get_user_rights', 'check_access', 'get_action_logs_self',
                    'set_password_self']},
                {'service_id': s_billing.id, 'properties': []},
            ]}
        g = Group(**d)
        mapping.save(curs, g)

        d = {'environment_id': env.id, 'name': 'Billing Users',
            'is_active': True, 'is_default': True,
            'rights': [
                {'service_id': s_auth.id, 'properties': []},
                {'service_id': s_billing.id, 'properties': [
                    'get_action_logs_self', 'get_balances_self',
                    'get_locks_self', 'get_transactions_self']},
            ]}
        g = Group(**d)
        mapping.save(curs, g)