Пример #1
0
def link_user(app_id: str, body: Dict[str, Any]):
    alias = int(body['social_id'])
    if alias <= 0:
        raise BadRequestError('Invalid social_id: ' +
                              str(body.get('social_id')))
    user_pk = body['user_id']

    SocialProfiles.link_with_user(app_id=app_id,
                                  alias=alias,
                                  user_pk=user_pk,
                                  create_if_not_exist=body.get(
                                      'create_user', 'true') == 'true')
    db.session.commit()
Пример #2
0
    def _handle_authentication(
            self,
            params: OAuthCallbackParams) -> Tuple[SocialProfiles, Tokens]:
        """
        Handle authentication, return authenticated profile + token info
        :param params:
        :return:
        """
        oauth_verifier = params.oauth_verifier
        token_tup = self._get_token_oa1(oauth_verifier)
        user_id, attrs = self._get_profile_oa1(token_tup=token_tup)

        profile, existed = SocialProfiles.add_or_update(app_id=self.log.app_id,
                                                        provider=self.provider,
                                                        scope_id=user_id,
                                                        attrs=attrs)
        self.log.set_authorized(social_id=profile._id,
                                is_login=existed,
                                nonce=gen_random_token(nbytes=32))
        token = Tokens(provider=self.provider,
                       token_type='OAuth',
                       oa_version=Tokens.OA_VERSION_1A,
                       oa1_token=token_tup[0],
                       oa1_secret=token_tup[1],
                       social_id=profile._id)
        db.session.add(token)
        return profile, token
Пример #3
0
def get_user(app_id: str, body: Dict[str, Any]):
    user_pk, alias = _parse_and_validate_identifiers(body)
    return SocialProfiles.get_full_profile(app_id=app_id,
                                           user_pk=user_pk,
                                           alias=alias,
                                           pretty=body.get('pretty',
                                                           'false') == 'true')
Пример #4
0
def get_associate_token(app_id: str, body: Dict[str, Any]):
    provider = body.get('provider')
    if not is_valid_provider(provider):
        raise BadRequestError('Invalid provider')
    user_pk, alias = _parse_and_validate_identifiers(body)

    profiles = SocialProfiles.find_by_pk(app_id=app_id, user_pk=user_pk)\
        if user_pk else SocialProfiles.query.filter_by(alias=alias).all()
    if not profiles:
        raise NotFoundError('User ID or Social ID not found')

    for p in profiles:
        if provider == p.provider:
            raise ConflictError(
                'User has linked with another social profile for this provider'
            )
    log = AssociateLogs(provider=provider,
                        app_id=app_id,
                        social_id=profiles[0].alias,
                        nonce=gen_random_token(nbytes=16, format='hex'))
    db.session.add(log)
    db.session.flush()

    associate_token = log.generate_associate_token()
    db.session.commit()
    return {'token': associate_token, 'target_provider': provider}
Пример #5
0
    def _handle_authentication(
            self,
            params: OAuthCallbackParams) -> Tuple[SocialProfiles, Tokens]:
        """
        Handle authentication, return authenticated profile + token info
        :param params:
        :return:
        """
        if self._is_mobile():
            access_token = params.access_token
            id_token = params.id_token
            token_pack = self._debug_token(access_token=access_token,
                                           id_token=id_token)
        else:
            code = params.code
            token_pack: OAuth2TokenPack = self._get_token(code=code)
        user_id, attrs = self._get_profile(token_pack=token_pack)

        profile, existed = SocialProfiles.add_or_update(app_id=self.log.app_id,
                                                        provider=self.provider,
                                                        scope_id=user_id,
                                                        attrs=attrs)
        self.log.set_authorized(social_id=profile._id,
                                is_login=existed,
                                nonce=gen_random_token(nbytes=32))
        token = Tokens(provider=self.provider,
                       access_token=token_pack.access_token,
                       token_type=token_pack.token_type,
                       expires_at=datetime.utcnow() +
                       timedelta(seconds=token_pack.expires_in),
                       refresh_token=token_pack.refresh_token,
                       id_token=token_pack.id_token,
                       social_id=profile._id)
        db.session.add(token)
        return profile, token
Пример #6
0
def delete_user(app_id: str, body: Dict[str, Any]):
    user_pk, alias = _parse_and_validate_identifiers(body)
    num_affected = SocialProfiles.delete_profile(app_id=app_id,
                                                 alias=alias,
                                                 user_pk=user_pk)

    db.session.commit()
    return num_affected
Пример #7
0
def get_authorized_profile(auth_token: str,
                           params: Dict[str, Any]) -> Dict[str, Any]:
    log, args = _verify_auth_request(auth_token=auth_token, params=params)
    app = Apps.query.filter_by(_id=log.app_id).one_or_none()

    if log.is_login:
        log.status = AuthLogs.STATUS_SUCCEEDED
    elif app.option_enabled(key='reg_page'):
        log.status = AuthLogs.STATUS_WAIT_REGISTER
    else:
        SocialProfiles.activate(profile_id=log.social_id)
        log.status = AuthLogs.STATUS_SUCCEEDED

    profile = SocialProfiles.query.filter_by(_id=log.social_id).first_or_404()
    # TODO: What is fetch_user=True
    body = profile.as_dict(fetch_user=True)
    db.session.commit()

    return body
Пример #8
0
def merge_user(app_id: str, body: Dict[str, Any]):
    src_user_pk = body.get('src_user_id')
    src_alias = smart_str2int(body.get('src_social_id', '0'))
    dst_user_pk = body.get('dst_user_id')
    dst_alias = smart_str2int(body.get('dst_social_id', '0'))

    if not src_user_pk and src_alias <= 0:
        raise BadRequestError(
            'At least one valid parameter src_user_id or src_social_id must be provided'
        )
    if not dst_user_pk and dst_alias <= 0:
        raise BadRequestError(
            'At least one valid parameter dst_user_id or dst_social_id must be provided'
        )

    SocialProfiles.merge_profiles(app_id=app_id,
                                  src_user_pk=src_user_pk,
                                  src_alias=src_alias,
                                  dst_user_pk=dst_user_pk,
                                  dst_alias=dst_alias)
    db.session.commit()
Пример #9
0
def unlink_user(app_id: str, body: Dict[str, Any]):
    user_pk = body['user_id']
    alias = int(body['social_id'])
    if alias <= 0:
        raise BadRequestError('Invalid social_id: ' +
                              str(body.get('social_id')))

    num_affected = SocialProfiles.unlink_from_user(app_id=app_id,
                                                   alias=alias,
                                                   user_pk=user_pk)
    db.session.commit()
    return num_affected
Пример #10
0
def convert_social_id(body):
    sub, _ = _validate_access_token(access_token=body['access_token'])
    app_id = body['app_id']
    owner_id = db.session.query(Apps.owner_id).filter_by(_id=app_id).scalar()
    if not owner_id or owner_id != sub:
        raise NotFoundError('App ID not found')

    social_ids = body['ids'].split(',')
    if len(social_ids) > 150:
        raise BadRequestError('Number of IDs cannot be larger than 150')

    scope_ids = SocialProfiles.social_id_to_scope_id(app_id=app_id, social_ids=social_ids)
    return [e[0] for e in scope_ids]
Пример #11
0
def disassociate(app_id: str, body: Dict[str, Any]):
    providers = body['providers'].split(',')
    for provider in providers:
        if not is_valid_provider(provider):
            raise BadRequestError('Invalid provider ' + provider)
    user_pk, alias = _parse_and_validate_identifiers(body)

    num_affected = SocialProfiles.disassociate_provider(app_id=app_id,
                                                        providers=providers,
                                                        user_pk=user_pk,
                                                        alias=alias)

    db.session.commit()
    return num_affected
Пример #12
0
def activate_profile(auth_token: str, params: Dict[str, Any]):
    log, args = _verify_auth_request(auth_token=auth_token, params=params)
    log.status = AuthLogs.STATUS_SUCCEEDED

    SocialProfiles.activate(profile_id=log.social_id)
    db.session.commit()