Пример #1
0
    def auth_user_role_detail(cls, account_id) -> dict:
        acc: Accounts = Accounts.select(Accounts).where(
            Accounts.id == account_id).first()
        rs = AuthUser.select().where(AuthUser.acc_id == account_id)
        auth_user_dict = {
            'acc':
            Accounts.to_dict(
                acc, BASE_FIELDS + [
                    "id", "password", "fuzzy_id", "login_token",
                    "login_updated_at", "pin"
                ])
        }
        if rs:
            au: AuthUser = rs[0]
            auth_user_dict['au'] = {
                'oid': au.org_id,
                'rfid': au.ref_id,
                'rid': au.role_id,
                't': au.type
            }
            auth_user_dict['role'] = cls._get_roles(au)
            role_list = []
            role_obj_list = Role.select()
            for r in role_obj_list:
                role_list.append(Role.to_dict(r, BASE_FIELDS))
            auth_user_dict['roles'] = role_list

        return auth_user_dict
Пример #2
0
 def query_user_list_by_keyword(cls, keyword, offset=0, limit=100):
     if keyword:
         return Accounts.select().where(
             Accounts.name.startswith(keyword)
             | Accounts.fuzzy_id.startswith(keyword)).limit(limit).offset(
                 offset)
     else:
         return Accounts.select().limit(limit).offset(offset)
Пример #3
0
 def update_account_by_pk(cls, pk_id, params):
     """
     :param pk_id:
     :param params:
     :return:
     """
     _params = {p: params[p] for p in params if p in Accounts.field_names()}
     with db:
         Accounts.update(**params).where(Accounts.id == pk_id).execute()
Пример #4
0
    def account_list(cls, pin=None, _type=None, offset=0, page_size=30):
        if pin and _type:
            account_list = Accounts.select(Accounts, AuthUser).join(
                AuthUser, on=(Accounts.id == AuthUser.acc_id),
                attr='auth').where(Accounts.pin == pin,
                                   AuthUser.type == _type).order_by(
                                       Accounts.created_at.desc()).offset(
                                           offset).limit(page_size)
        elif _type:
            account_list = Accounts.select(Accounts, AuthUser).join(
                AuthUser, on=(Accounts.id == AuthUser.acc_id),
                attr='auth').where(AuthUser.type == _type).order_by(
                    Accounts.created_at.desc()).offset(offset).limit(page_size)
        elif pin:
            account_list = Accounts.select().where(
                Accounts.pin == pin).order_by(
                    Accounts.created_at.desc()).offset(offset).limit(page_size)
        else:
            account_list = Accounts.select(Accounts).order_by(
                Accounts.created_at.desc()).offset(offset).limit(page_size)
        # print("account_list:", account_list)
        rs = []
        n = 0
        acc_ids = []
        for acc in account_list:
            acc_dict = Accounts.to_dict(acc)
            if hasattr(acc, 'auth') and acc.auth:
                auth_user_dict = AuthUser.to_dict(acc.auth, BASE_FIELDS)
                acc_dict['auth'] = auth_user_dict
            else:
                acc_ids.append(acc.id)
            if not acc.fuzzy_id:
                acc_dict['fuzzy_id'] = obfuscate_id(acc.id)
            rs.append(acc_dict)

            n = n + 1
        au_list = AuthUser.select().where(AuthUser.acc_id.in_(acc_ids))
        au_dict = {}
        if au_list:
            for au in au_list:
                au_dict[au.acc_id] = AuthUser.to_dict(au)

        for acc_dict in rs:
            if acc_dict['id'] in au_dict:
                acc_dict['auth'] = au_dict[acc_dict['id']]
            uoe_list = UserOrgExtend.select().where(
                UserOrgExtend.acc_id == acc_dict['id'])
            if uoe_list:
                acc_dict['extorgs'] = [uoe.org_id for uoe in uoe_list]
            ure_list = UserRoleExtend.select().where(
                UserRoleExtend.acc_id == acc_dict['id'])
            if ure_list:
                acc_dict['extroles'] = [ure.role_id for ure in ure_list]
            acc_dict.pop('id')
        return rs, n == page_size
Пример #5
0
 def default_guest_account(cls):
     guest: Accounts = Accounts.select().where(
         Accounts.name == "guest").first()
     if guest:
         if not guest.fuzzy_id:
             fuzzy_id = obfuscate_id(guest.id)
             guest.fuzzy_id = fuzzy_id
             with db:
                 Accounts.update(fuzzy_id=fuzzy_id).where(
                     Accounts.id == guest.id).execute()
     return guest
Пример #6
0
 def update_account_by_pk(cls, pk_id, params):
     """
     :param pk_id:
     :param params:
     :return:
     """
     fields = [
         'password', 'client_id', 'client_secret', 'access_token',
         'login_token', 'token_updated_at', 'login_updated_at', 'mobile_no',
         'fuzzy_id', 'pin', 'last_login_at', 'nickname'
     ]
     _params = {p: params[p] for p in params if p in fields}
     with db:
         Accounts.update(**params).where(Accounts.id == pk_id).execute()
Пример #7
0
 def user_list(self, kw, size, offset):
     items = DataDao.query_user_list_by_keyword(kw,
                                                offset=offset,
                                                limit=size)
     item_json_list = []
     # print("items:", items)
     for item in items:
         item_json_list.append(Accounts.to_dict(item, BASE_FIELDS + ['id']))
     return item_json_list
Пример #8
0
 def account_by_passwd(cls, name, passwd):
     account_list = Accounts.select().where(
         (Accounts.name == name) | (Accounts.mobile_no == name),
         Accounts.password == passwd)
     print("account_list:", account_list)
     for acc in account_list:
         print("acc id:", acc.id)
         # return object_to_dict(acc)
         return acc
     return None
Пример #9
0
    def auth_user_detail(cls, account_id) -> dict:
        acc: Accounts = Accounts.select(Accounts).where(
            Accounts.id == account_id).first()
        rs = AuthUser.select().where(AuthUser.acc_id == account_id)
        auth_user_dict = {
            'acc':
            Accounts.to_dict(
                acc, BASE_FIELDS + [
                    "id", "password", "fuzzy_id", "login_token",
                    "login_updated_at", "pin"
                ])
        }
        if rs:
            au: AuthUser = rs[0]
            org: Org = Org.select().where(Org.id == au.org_id).first()
            auth_user_dict['org'] = {
                'base': Org.to_dict(org, BASE_FIELDS),
                'parent': {
                    'id': 0,
                    'name': '无'
                }
            }
            if org.parent:
                porg: Org = Org.select().where(Org.id == org.parent).first()
                auth_user_dict['org']['parent'] = porg
            ext_org_list = Org.select(Org).join(
                UserOrgExtend, on=(UserOrgExtend.org_id == Org.id)).where(
                    UserOrgExtend.acc_id == au.acc_id)
            if ext_org_list:
                ext_org = auth_user_dict['org']['ext'] = []
                for org in ext_org_list:
                    ext_org.append(Org.to_dict(org, BASE_FIELDS))
            auth_user_dict['au'] = {
                'oid': au.org_id,
                'rfid': au.ref_id,
                'rid': au.role_id,
                't': au.type
            }
            auth_user_dict['role'] = cls._get_roles(au)

        return auth_user_dict
Пример #10
0
    def new_account(cls,
                    name,
                    nickname,
                    mobile_no,
                    password,
                    org_id,
                    role_id,
                    _type,
                    extorgs,
                    extroles,
                    now,
                    envelop_user_lambda: Callable[..., Tuple[str,
                                                             dict]] = None,
                    ctx=None):
        with db:
            user_token = None
            user_ext_dict = {}
            acc: Accounts = Accounts(name=name,
                                     mobile_no=mobile_no,
                                     nickname=nickname,
                                     password=password)
            acc.save(force_insert=True)
            acc_id = acc.id
            ur: UReference = UReference()
            ur.save(force_insert=True)
            au: AuthUser = AuthUser(acc_id=acc_id,
                                    org_id=org_id,
                                    role_id=role_id,
                                    ref_id=ur.id,
                                    type=_type)
            au.save(force_insert=True)
            if extorgs:
                for oid in extorgs:
                    UserOrgExtend(acc_id=acc_id,
                                  org_id=oid).save(force_insert=True)
            if extroles:
                for rid in extroles:
                    UserRoleExtend(acc_id=acc_id,
                                   role_id=rid).save(force_insert=True)
            if envelop_user_lambda:
                if ctx:
                    user_token, user_ext_dict = envelop_user_lambda(acc, ctx)
                else:
                    user_token, user_ext_dict = envelop_user_lambda(acc)

                cls.update_account_by_pk(pk_id=acc_id,
                                         params={
                                             "fuzzy_id": user_ext_dict['id'],
                                             "login_updated_at": now,
                                             "login_token": user_token
                                         })
            return user_token, user_ext_dict
Пример #11
0
    def new_account(cls, mobile_no, password, now,
                    envelop_user_lambda: Callable[..., Tuple[str, dict]]):
        with db:
            acc: Accounts = Accounts(name=mobile_no,
                                     mobile_no=mobile_no,
                                     nickname=mobile_no,
                                     password=password)
            acc.save(force_insert=True)
            acc_id = acc.id
        if acc_id:
            # fuzzy_id = obfuscate_id(acc_id)
            # token = make_token(fuzzy_id, acc)

            user_token, user_ext_dict = envelop_user_lambda(acc)
            cls.update_account_by_pk(pk_id=acc_id,
                                     params={
                                         "fuzzy_id": user_ext_dict['id'],
                                         "login_updated_at": now,
                                         "login_token": user_token
                                     })
            return user_token, user_ext_dict
Пример #12
0
 def check_user_only_by_name(cls, username):
     return Accounts.select().where(Accounts.name == username).exists()
Пример #13
0
 def check_user(cls, username, mobile_no):
     return Accounts.select().where((Accounts.name == username) | (
         Accounts.mobile_no == mobile_no)).exists()
Пример #14
0
 def account_by_id(cls, pk_id) -> Accounts:
     return Accounts.select().where(Accounts.id == pk_id).first()
Пример #15
0
 def account_by_name(cls, name):
     account_list = Accounts.select().where((Accounts.name == name)
                                            | (Accounts.mobile_no == name))
     for acc in account_list:
         return acc
     return None
Пример #16
0
    def update_account(cls, acc_id, name, nickname, password, org_id, role_id,
                       _type, extorgs, extroles, now,
                       envelop_user_lambda: Callable[..., Tuple[str, dict]]):
        with db:
            update_params = dict(name=name,
                                 nickname=nickname,
                                 login_updated_at=now)
            if password:
                update_params['password'] = password
            user_token = None
            user_ext_dict = {}
            au_params = {}
            au: AuthUser = AuthUser.select().where(
                AuthUser.acc_id == acc_id).first()
            if not au:
                ur: UReference = UReference()
                ur.save(force_insert=True)
                au = AuthUser(acc_id=acc_id,
                              org_id=org_id,
                              role_id=role_id,
                              ref_id=ur.id,
                              type=_type)
                au.save(force_insert=True)
            if au.role_id != role_id:
                au_params['role_id'] = role_id
            if au.org_id != org_id:
                au_params['org_id'] = org_id
            if au.type != _type:
                au_params['type'] = _type
            if au_params:
                AuthUser.update(**au_params).where(
                    AuthUser.acc_id == acc_id).execute()

            if extorgs:
                uoe_list = UserOrgExtend.select().where(
                    UserOrgExtend.acc_id == acc_id,
                    UserOrgExtend.org_id.not_in(extorgs))
                del_uoe_ids = [uoe.org_id for uoe in uoe_list]
                if del_uoe_ids:
                    UserOrgExtend.delete().where(
                        UserOrgExtend.acc_id == acc_id,
                        UserOrgExtend.org_id.in_(del_uoe_ids))
                exc_uoe_list = UserOrgExtend.select().where(
                    UserOrgExtend.acc_id == acc_id,
                    UserOrgExtend.org_id.in_(extorgs))
                exc_ext_org_ids = [uoe.org_id for uoe in exc_uoe_list]
                insert_ext_org_ids = extorgs
                if exc_ext_org_ids:
                    insert_ext_org_ids = [
                        oid for oid in extorgs if oid not in exc_ext_org_ids
                    ]
                for oid in insert_ext_org_ids:
                    UserOrgExtend(acc_id=acc_id,
                                  org_id=oid).save(force_insert=True)
            if extroles:
                ure_list = UserRoleExtend.select().where(
                    UserRoleExtend.acc_id == acc_id,
                    UserRoleExtend.role_id.not_in(extroles))
                del_ure_ids = [ure.role_id for ure in ure_list]
                if del_ure_ids:
                    UserRoleExtend.delete().where(
                        UserRoleExtend.acc_id == acc_id,
                        UserRoleExtend.role_id.in_(del_ure_ids))
                exc_ure_list = UserOrgExtend.select().where(
                    UserOrgExtend.acc_id == acc_id,
                    UserOrgExtend.org_id.in_(extorgs))
                exc_ext_role_ids = [ure.role_id for ure in exc_ure_list]
                insert_ext_role_ids = extroles
                if exc_ext_role_ids:
                    insert_ext_role_ids = [
                        rid for rid in extroles if rid not in exc_ext_role_ids
                    ]
                for rid in insert_ext_role_ids:
                    UserRoleExtend(acc_id=acc_id,
                                   role_id=rid).save(force_insert=True)
            if envelop_user_lambda:
                acc: Accounts = Accounts.select().where(
                    Accounts.id == acc_id).first()
                user_token, user_ext_dict = envelop_user_lambda(acc)
                update_params['fuzzy_id'] = user_ext_dict['id']
                update_params['login_token'] = user_token
            Accounts.update(**update_params).where(
                Accounts.id == acc_id).execute()
            return user_token, user_ext_dict
Пример #17
0
    def login_check_user(self,
                         acc: Accounts,
                         need_update_login_time=True,
                         source="BD"):
        need_renew_pan_acc = []
        if acc:
            pan_acc_list = DataDao.pan_account_list(acc.id)
            # pan_acc: PanAccounts = DataDao.pan_account_list(acc.id)
            need_renew_access_token = False
            l = len(pan_acc_list)
            for pan_acc in pan_acc_list:
                if pan_acc.client_id != self.client_id or pan_acc.client_secret != self.client_secret:
                    need_renew_access_token = True
                    need_renew_pan_acc.append({
                        "id": pan_acc.id,
                        "name": pan_acc.name,
                        "use_cnt": pan_acc.use_count,
                        "refresh": False,
                        'auth': self.pan_auth
                    })
                elif pan_acc.access_token and pan_acc.token_updated_at:
                    tud = arrow.get(pan_acc.token_updated_at).replace(
                        tzinfo=self.default_tz)
                    if (arrow.now(self.default_tz) -
                            tud).total_seconds() > PAN_ACCESS_TOKEN_TIMEOUT:
                        need_renew_access_token = True
                        need_renew_pan_acc.append({
                            "id": pan_acc.id,
                            "name": pan_acc.name,
                            "use_cnt": pan_acc.use_count,
                            "refresh": True,
                            'auth': self.pan_auth
                        })
                else:
                    need_renew_access_token = True
                    need_renew_pan_acc.append({
                        "id": pan_acc.id,
                        "name": pan_acc.name,
                        "use_cnt": pan_acc.use_count,
                        "refresh": True,
                        'auth': self.pan_auth
                    })
            if l == 0:
                need_renew_access_token = True
            # if pan_acc and pan_acc['access_token'] and pan_acc['token_updated_at']:
            #     tud = arrow.get(pan_acc['token_updated_at']).replace(tzinfo=self.default_tz)
            #     if (arrow.now(self.default_tz) - tud).total_seconds() < PAN_ACCESS_TOKEN_TIMEOUT:
            #         need_renew_access_token = False

            lud = arrow.get(
                acc.login_updated_at).replace(tzinfo=self.default_tz)
            diff = arrow.now(self.default_tz) - lud
            params = {}
            if (need_update_login_time and diff.total_seconds() >
                    LOGIN_TOKEN_TIMEOUT) or not acc.login_token:
                if not acc.fuzzy_id:
                    acc.fuzzy_id = obfuscate_id(acc.id)
                    params["fuzzy_id"] = acc.fuzzy_id
                # login_token = make_token(acc.fuzzy_id)
                login_token, _ = auth_service.build_user_payload(acc)
                acc.login_token = login_token
                params["login_token"] = login_token
                lud = params["login_updated_at"] = get_now_datetime()
                DataDao.update_account_by_pk(acc.id, params=params)
            else:
                tk = acc.login_token
                if tk:
                    user_payload = get_payload_from_token(tk)
                    if user_payload:
                        tm = user_payload['tm']
                        ctm = get_now_ts()
                        if ctm - tm > LOGIN_TOKEN_TIMEOUT:
                            # login_token = make_token(acc.fuzzy_id)
                            login_token, _ = auth_service.build_user_payload(
                                acc)
                            acc.login_token = login_token
                            params["login_token"] = login_token
                            lud = params[
                                "login_updated_at"] = get_now_datetime()
                            DataDao.update_account_by_pk(acc.id, params=params)
            log.debug("login_token:{}".format(acc.login_token))
            result = {"need_renew_access_token": need_renew_access_token}
            if need_renew_access_token:
                result['auth'] = self.pan_auth
            result['token'] = acc.login_token
            result['login_at'] = int(arrow.get(lud).timestamp * 1000)
            # print('login_at:', result['login_at'])
            result['pan_acc_list'] = need_renew_pan_acc
            self.__patch_acc_ext(acc, result, source)
            # account_ext = DataDao.account_ext_by_acc_id(acc.id)
            # result['username'] = account_ext.username
            # result['portrait'] = account_ext.portrait
            result['id'] = acc.fuzzy_id
            return result

        return None