예제 #1
0
    def __init__(self,
                 request_token: str = None,
                 callback_uri: str = None,
                 app_key: str = None,
                 app_secret: str = None):
        """Init.
        """
        self._app_key = app_key or _api.get_app_key()
        self._app_secret = app_secret or _api.get_app_secret()
        self._request_token = None
        self._request_secret = None
        self._oauth_session = None
        self._callback_uri = callback_uri if callback_uri else _router.current_url(
        )

        if request_token:
            if _request_tokens.has(request_token):
                self._request_token = request_token
                self._request_secret = _request_tokens.get(request_token)
                self._oauth_session = _OAuthSession(self._app_key,
                                                    self._app_secret,
                                                    self._request_token,
                                                    self._request_secret,
                                                    self._callback_uri)
            else:
                raise RuntimeError(
                    'Cannot find token secret corresponding to the specified token.'
                )
예제 #2
0
    def sign_in(self, data: dict) -> AbstractUser:
        """Authenticate an existing user
        """
        oauth_code = data.get('code')
        if not oauth_code:
            raise auth.error.AuthenticationError('No oAuth code')

        oauth_token = _api.get_access_token(oauth_code, current_url(True),
                                            data.get('state'))
        info = _api.get_user_info(oauth_token['access_token'],
                                  oauth_token['user_id'])

        email = info['email'].lower()
        if not email:
            raise auth.error.AuthenticationError('Service returned no email')

        user = auth.get_user(email)
        if not user:
            user = auth.create_user(email)

        opts = dict(user.options)
        opts.update({
            'id_gov_ua': info,
        })
        user.set_field('options', opts)

        user.set_field('first_name', info['givenname'].title())
        user.set_field('middle_name', info['middlename'].title())
        user.set_field('last_name', info['lastname'].title())
        user.set_field('phone', info['phone'])

        return user.save()
예제 #3
0
def reset():
    """Reset links
    """
    _links[_threading.get_id()] = {}

    for lng in _lang.langs(False):
        put(lng, _router.current_url(lang=lng))
예제 #4
0
def sign_up_url(driver_name: str = None, add_query: dict = None, add_fragment: str = '') -> str:
    """Get sign up URL
    """
    return router.rule_url('auth_ui@sign_up', {
        'driver': get_driver(driver_name).name,
        '__redirect': router.current_url(query=add_query, fragment=add_fragment)
    })
예제 #5
0
    def __init__(self,
                 state: str = None,
                 redirect_uri: str = None,
                 app_id: str = None,
                 app_secret: str = None):
        """Init.
        """
        self._app_id = app_id or _api.get_app_id()
        self._app_secret = app_secret or _api.get_app_secret()

        if state:
            self._state = state
            self._final_redirect_uri = _states.get(state,
                                                   _router.current_url())
        else:
            self._state = _util.random_str(64)
            self._final_redirect_uri = redirect_uri if redirect_uri else _router.current_url(
            )
            _states[self._state] = self._final_redirect_uri
예제 #6
0
def sign_in_url(driver_name: str = None, redirect: str = 'CURRENT_URL', add_query: dict = None,
                add_fragment: str = '') -> str:
    """Get sign in URL
    """
    rule_args = {
        'driver': get_driver(driver_name).name,
    }

    if redirect:
        rule_args['__redirect'] = redirect.replace('CURRENT_URL', router.current_url())

    return router.rule_url('auth_ui@sign_in', rule_args, query=add_query, fragment=add_fragment)
예제 #7
0
    def before(self) -> Optional[http.RedirectResponse]:
        if not auth.get_current_user().is_anonymous:
            return

        # Redirecting to the authorization endpoint
        inp = self.request.inp.copy()
        inp.update({
            'driver': _api.get_driver().name,
            '__redirect': util.escape_html(router.current_url(True)),
        })

        return self.redirect(router.rule_url('auth_ui@sign_in', inp))
예제 #8
0
def prepare_request_uri(state: str = None,
                        redirect_uri: str = None,
                        auth_type: str = 'dig_sign,bank_id,mobile_id'):
    """Prepare oAuth2 request URI
    """
    state = state or util.random_str()
    redirect_uri = redirect_uri or router.current_url()

    return get_client().prepare_request_uri(REQUEST_URI,
                                            redirect_uri,
                                            state=state,
                                            auth_type=auth_type)
예제 #9
0
    def __init__(self, uid: str, **kwargs):
        """Init.
        """
        super().__init__(uid, **kwargs)

        self._oauth_token = kwargs.get('oauth_token', '')
        self._oauth_token_secret = kwargs.get('oauth_token_secret', '')
        self._screen_name = kwargs.get('screen_name', '')
        self._user_blogs = []
        self._user_blog = kwargs.get('user_blog', '')
        self._callback_uri = kwargs.get('callback_uri', _router.current_url())

        self._css += ' widget-tumblr-oauth'
예제 #10
0
    def __init__(self, uid: str, **kwargs):
        """Init.
        """
        super().__init__(uid, **kwargs)

        self._app_id = _facebook.get_app_id()
        self._href = kwargs.get('href', _router.current_url())

        js_sdk_args = {
            'app_id': self._app_id,
            'language': _lang.ietf_tag(sep='_')
        }
        _assetman.add_inline_js(_tpl.render('facebook@fb-js-sdk', js_sdk_args))
예제 #11
0
    def render(self) -> str:
        # 'Create' toolbar button
        if self._model_class.odm_ui_creation_allowed(
        ) and odm_auth.check_model_permissions(self._model, PERM_CREATE):
            create_form_url = router.rule_url(
                self._m_form_rule, {
                    'model': self._model,
                    'eid': 0,
                    '__redirect': router.current_url(),
                })
            title = lang.t('odm_ui@create')
            btn = htmler.A(href=create_form_url,
                           css='btn btn-default btn-light add-button',
                           title=title)
            btn.append_child(htmler.I(css='fa fas fa-fw fa-plus'))
            self._widget.toolbar.append_child(btn)
            self._widget.toolbar.append_child(htmler.Span(' '))

        # 'Delete' toolbar button
        if self._model_class.odm_ui_deletion_allowed():
            delete_form_url = router.rule_url(self._d_form_rule,
                                              {'model': self._model})
            title = lang.t('odm_ui@delete_selected')
            btn = htmler.A(
                href=delete_form_url,
                css='hidden btn btn-danger mass-action-button sr-only',
                title=title)
            btn.append_child(htmler.I(css='fa fas fa-fw fa-remove fa-times'))
            self._widget.toolbar.append_child(btn)
            self._widget.toolbar.append_child(htmler.Span(' '))

        # Additional toolbar buttons
        for btn_data in self._model_class.odm_ui_browser_mass_action_buttons():
            ep = btn_data.get('ep')
            url = router.rule_url(ep) if ep else '#'
            css = 'btn btn-{} mass-action-button'.format(
                btn_data.get('color', 'default btn-light'))
            icon = 'fa fas fa-fw fa-' + btn_data.get('icon', 'question')
            button = htmler.A(href=url, css=css, title=btn_data.get('title'))
            if icon:
                button.append_child(htmler.I(css=icon))
            self._widget.toolbar.append_child(button)
            self._widget.toolbar.append_child(htmler.Span(' '))

        frm = htmler.Form(self._widget.render(),
                          action='#',
                          method='post',
                          css='table-responsive odm-ui-browser')

        return frm.render()
예제 #12
0
파일: _api.py 프로젝트: pytsite/pytsite
def nav_link(url: str, anchor: str = '', icon: str = None, **kwargs) -> str:
    """Generate Bootstrap compatible navigation item link
    """
    from pytsite import html, router

    li = html.Li(css=kwargs.pop('li_css', 'nav-item'))

    if not url.startswith('#') and router.url(url, strip_query=True) == router.current_url(strip_query=True):
        li.add_css('active')

    a = html.A(escape_html(anchor), href=url, css=kwargs.pop('a_css', 'nav-link'), **kwargs)
    if icon:
        a.append(html.I(css=icon))

    li.append(a)

    return str(li)
예제 #13
0
    def __init__(self, uid: str, **kwargs):
        """Init.
        """
        super().__init__(uid, **kwargs)

        self._app_id = kwargs.get('app_id') or _api.get_app_id()
        self._app_secret = kwargs.get('app_secret') or _api.get_app_secret()
        self._scope = kwargs.get('scope', 'public_profile,email,user_friends')
        self._access_token = kwargs.get('access_token', '')
        self._access_token_type = kwargs.get('access_token_type', '')
        self._access_token_expires = kwargs.get('access_token_expires', 0)
        self._user_id = kwargs.get('user_id', '')
        self._pages = []
        self._page_id = kwargs.get('page_id', '')
        self._screen_name = kwargs.get('screen_name', '')
        self._redirect_url = kwargs.get('redirect_url', _router.current_url())

        self._css += ' widget-facebook-oauth'
예제 #14
0
def render(
        content: Union[str,
                       htmler.Element]) -> Union[str, http.RedirectResponse]:
    """Render admin page with content.
    """
    if not _themes:
        raise _error.NoThemesRegistered()

    if auth.get_current_user().is_anonymous:
        return http.response.Redirect(
            auth_ui.sign_in_url(redirect=router.current_url()))

    theme_name = reg.get('admin.theme', _fallback_theme_name)
    try:
        theme = _themes[theme_name]
    except KeyError:
        raise _error.ThemeNotRegistered(theme_name)

    return theme.render(navbar, sidebar, content)
예제 #15
0
    def get_authorization_url(self, callback_uri: str = None) -> str:
        """Get authorization URL.
        """
        callback_uri = callback_uri or _router.current_url()

        self._init_session(callback_uri)

        state = self._get_state()
        if state['stage'] != 'request_token':
            raise _error.SessionError("Cannot generate authorization URL.")

        oauth = OAuth1Session(self._app_key,
                              self._app_secret,
                              state['oauth_token'],
                              state['oauth_token_secret'],
                              callback_uri=callback_uri)

        return oauth.authorization_url(
            'https://api.twitter.com/oauth/authorize')
예제 #16
0
    def exec(self):
        # Check for error from Google
        error = self.arg('error')
        if error == 'access_denied':
            raise self.forbidden(
                lang.t('auth_ui_google@user_declined_authorization'))

        # Check for code from Google
        code = self.arg('code')
        if code:
            # Restore flow from session
            flow = router.session().get(
                'google_oauth2_flow')  # type: OAuth2WebServerFlow
            if not flow:
                raise self.forbidden('Cannot retrieve stored OAuth2 flow')

            # Exchange code to credentials
            credentials = flow.step2_exchange(code)
            user = auth.get_current_user()
            user.set_option('google_oauth2_credentials', credentials.to_json())
            user.save()

            final_redirect = router.session().get(
                'google_oauth2_final_redirect', router.base_url())

            router.session().pop('google_oauth2_flow')
            router.session().pop('google_oauth2_final_redirect')

            return self.redirect(final_redirect)

        else:
            # Request new code from Google
            scope = self.args.pop('scope')  # type: str
            if scope and ',' in scope:
                scope = scope.split(',')
            flow = auth_google.create_oauth2_flow(
                scope, router.current_url(True, query=dict(self.args)))
            router.session()['google_oauth2_flow'] = flow
            router.session()['google_oauth2_final_redirect'] = self.args.pop(
                '__redirect', router.base_url())

            return self.redirect(flow.step1_get_authorize_url())
예제 #17
0
    def _init_session(self, callback_uri: str = None):
        callback_uri = callback_uri or _router.current_url()

        if self._get_state()['stage'] == 'new':
            # Need to fetch request token
            oauth = OAuth1Session(self._app_key,
                                  self._app_secret,
                                  callback_uri=callback_uri)
            r_token_resp = oauth.fetch_request_token(
                'https://api.twitter.com/oauth/request_token')
            self._set_state({
                'stage':
                'request_token',
                'time':
                _dt.now(),
                'oauth_token':
                r_token_resp.get('oauth_token'),
                'oauth_token_secret':
                r_token_resp.get('oauth_token_secret')
            })
예제 #18
0
 def _is_item_active(self, entity: _model.Menu):
     return self._item_url(entity) == router.current_url(True)
예제 #19
0
def sign_out_url(redirect: str = 'CURRENT_URL') -> str:
    """Get sign out URL
    """
    rule_args = {'__redirect': redirect.replace('CURRENT_URL', router.current_url())} if redirect else {}

    return router.rule_url('auth_ui@sign_out', rule_args)