コード例 #1
0
    def login(self):
        logger.info("My special login...")
        if g.user is not None and g.user.is_authenticated():
            return redirect(self.appbuilder.get_url_for_index)

        form = MyLoginForm()

        if form.validate_on_submit():
            logger.info("going to auth MY user: %s" % form.email.data)
            my_user = remote_server_api.authenticate(form.email.data,
                                                     form.password.data)
            # if my_user is authenticated
            if my_user:
                user = self.appbuilder.sm.auth_user_remote_user(
                    my_user.get('username'))
                if user is None:
                    flash(as_unicode(self.invalid_login_message), 'warning')
                else:
                    login_user(user)
                    return redirect(self.appbuilder.get_url_for_index)
            else:
                flash(as_unicode(self.invalid_login_message), 'warning')
        else:
            if form.errors.get('email') is not None:
                flash(as_unicode(" ".join(form.errors.get('email'))),
                      'warning')

        return self.render_template(self.login_template,
                                    title=self.title,
                                    form=form,
                                    appbuilder=self.appbuilder)
コード例 #2
0
ファイル: views.py プロジェクト: CLRN/flask-test-mongo
    def __call__(self, **kwargs):
        label_columns = {}
        form_fields = {}
        search_filters = {}
        dict_filters = self.filters.get_search_filters()
        dict_filters.append('extra')
        for col in self.template_args['include_cols']:
            label_columns[col] = as_unicode(
                self.template_args['form'][col].label.text)
            form_fields[col] = self.template_args['form'][col]()
            if col in dict_filters:
                search_filters[col] = [
                    as_unicode(flt.name) for flt in dict_filters[col]
                ]
        '''
        form = MyForm()

        label_columns['extra'] = u'extra'
        form_fields['extra'] = form['extra']()
        search_filters['extra'] = search_filters['sequence']
        '''

        kwargs['label_columns'] = label_columns
        kwargs['form_fields'] = form_fields
        kwargs['search_filters'] = search_filters
        kwargs['active_filters'] = self.filters.get_filters_values_tojson()
        return super(MySearchWidget, self).__call__(**kwargs)
コード例 #3
0
def dict_to_json(xcol, ycols, labels, value_columns):
    """
        Converts a list of dicts from datamodel query results
        to google chart json data.

        :param xcol:
            The name of a string column to be used has X axis on chart
        :param ycols:
            A list with the names of series cols, that can be used as numeric
        :param labels:
            A dict with the columns labels.
        :param value_columns:
            A list of dicts with the values to convert
    """
    json_data = dict()
    json_data['cols'] = [{'id': xcol,
                          'label': as_unicode(labels[xcol]),
                          'type': 'string'}]
    for ycol in ycols:
        json_data['cols'].append({'id': ycol,
                                  'label': as_unicode(labels[ycol]),
                                  'type': 'number'})
    json_data['rows'] = []
    for value in value_columns:
        row = {'c': []}
        for ycol in ycols:
            row['c'].append({'v': (value[xcol])})
            if value[ycol]:
                row['c'].append({'v': int(value[ycol])})
            else:
                row['c'].append({'v': 0})
        json_data['rows'].append(row)
    return json_data
コード例 #4
0
    def login(self):
        # headers
        username = request.headers.get('HTTP_PROXY_REMOTE_USER')
        if g.user is not None and g.user.is_authenticated():
            return redirect(self.appbuilder.get_url_for_index)

        sm = self.appbuilder.sm
        session = sm.get_session
        user = session.query(
            sm.user_model).filter_by(username=username).first()
        if user is None and username:
            msg = ("User not allowed, {}".format(username))
            flash(as_unicode(msg), 'error')
            return redirect(self.appbuilder.get_url_for_login)

        if username:
            user = self.appbuilder.sm.auth_user_remote_user(username)
            if user is None:
                flash(as_unicode(self.invalid_login_message), 'warning')
            else:
                login_user(user)
        else:
            flash(as_unicode(self.invalid_login_message), 'warning')

        return redirect(self.appbuilder.get_url_for_index)
コード例 #5
0
    def autologin(self):
        # import pdb; pdb.set_trace()
        if g.user is not None and g.user.is_authenticated:
            log.info("User is already authenticated: %s" % (g.user))
            return redirect(self.appbuilder.get_url_for_index)
        form = LoginForm_db()

        auth_header = request.headers.get("Authorization", None)
        log.info("Authorization header is %s" % (auth_header))
        if not auth_header:
            return self.render_template(self.login_template,
                                        title=self.title,
                                        form=form,
                                        appbuilder=self.appbuilder)
        else:
            u, p = self._get_basic_credentials(auth_header)
            form.username.data = u
            form.password.data = p
        if not form.validate_on_submit():
            flash(as_unicode(self.invalid_login_message), 'warning')
            return redirect(self.appbuilder.get_url_for_login)
        user = self.appbuilder.sm.auth_user_ldap(u, p)
        log.info("User is %s" % user)
        if not user:
            flash(as_unicode(self.invalid_login_message), 'warning')
            return redirect(self.appbuilder.get_url_for_login)
        remember_me = False
        if 'remember_me' in session:
            remember_me = session['remember_me']
            session.pop('remember_me', None)

        self.appbuilder.sm.update_user_auth_stat(user, success=True)
        login_user(user, remember=True)

        return redirect(self.appbuilder.get_url_for_index)
コード例 #6
0
ファイル: group.py プロジェクト: gkmbinh/Flask-AppBuilder
 def to_json(self, data, labels=None):
     labels = labels or dict()
     json_data = dict()
     json_data['cols'] = []
     for group_col in self.group_bys_cols:
         label = '' or as_unicode(labels[group_col])
         json_data['cols'].append({'id': group_col,
                                   'label': label,
                                   'type': 'string'})
     for aggr_col in self.aggr_by_cols:
         if isinstance(aggr_col, tuple):
             label_key = aggr_col[0].__name__ + aggr_col[1]
             aggr_col = aggr_col[1]
         else:
             label_key = aggr_col
         label = '' or as_unicode(labels[label_key])
         json_data['cols'].append({'id': aggr_col,
                                   'label': label,
                                   'type': 'number'})
     json_data['rows'] = []
     for item in data:
         row = {'c': []}
         if not isinstance(item[0], tuple):
             row['c'].append({'v': str(item[0])})
         else:
             for group_col_data in item[0]:
                 row['c'].append({'v': str(group_col_data)})
         for col_data in item[1:]:
             if isinstance(col_data, datetime.date):
                 row['c'].append({'v': (str(col_data))})
             else:
                 row['c'].append({'v': col_data})
         json_data['rows'].append(row)
     return json_data
コード例 #7
0
ファイル: group.py プロジェクト: bklynate/Flask-AppBuilder
 def to_json(self, data, labels=None):
     labels = labels or dict()
     json_data = dict()
     json_data['cols'] = []
     for group_col in self.group_bys_cols:
         label = '' or as_unicode(labels[group_col])
         json_data['cols'].append({'id': group_col,
                                   'label': label,
                                   'type': 'string'})
     for aggr_col in self.aggr_by_cols:
         if isinstance(aggr_col, tuple):
             label_key = aggr_col[0].__name__ + aggr_col[1]
             aggr_col = aggr_col[1]
         else:
             label_key = aggr_col
         label = '' or as_unicode(labels[label_key])
         json_data['cols'].append({'id': aggr_col,
                                   'label': label,
                                   'type': 'number'})
     json_data['rows'] = []
     for item in data:
         row = {'c': []}
         if not isinstance(item[0], tuple):
             row['c'].append({'v': str(item[0])})
         else:
             for group_col_data in item[0]:
                 row['c'].append({'v': str(group_col_data)})
         for col_data in item[1:]:
             if isinstance(col_data, datetime.date):
                 row['c'].append({'v': (str(col_data))})
             else:
                 row['c'].append({'v': col_data})
         json_data['rows'].append(row)
     return json_data
コード例 #8
0
 def activation(self, activation_hash):
     """
         Endpoint to expose an activation url, this url
         is sent to the user by email, when accessed the user is inserted
         and activated
     """
     reg = self.appbuilder.sm.find_register_user(activation_hash)
     if not reg:
         flash(as_unicode(self.false_error_message), 'danger')
         return redirect(self.appbuilder.get_url_for_index)
     if not self.appbuilder.sm.add_user(
             username=reg.username,
             email=reg.email,
             first_name=reg.first_name,
             last_name=reg.last_name,
             role=self.appbuilder.sm.find_role(
                 self.appbuilder.sm.auth_user_registration_role),
             hashed_password=reg.password):
         flash(as_unicode(self.error_message), 'danger')
         return redirect(self.appbuilder.get_url_for_index)
     else:
         self.appbuilder.sm.del_register_user(reg)
         return self.render_template(self.activation_template,
                                     username=reg.username,
                                     appbuilder=self.appbuilder)
コード例 #9
0
ファイル: group.py プロジェクト: zhounanshu/Flask-AppBuilder
    def to_json(self, data, labels=None):
        """
            Will return a dict with Google JSON structure for charts

            The Google structure::

                {
                    cols: [{id:<COL_NAME>, label:<LABEL FOR COL>, type: <COL TYPE>}, ...]
                    rows: [{c: [{v: <COL VALUE}, ...], ... ]
                }

            :param data:
            :param labels: dict with labels to include on Google JSON strcut
            :return: dict with Google JSON structure
        """
        labels = labels or dict()
        json_data = dict()
        json_data['cols'] = []
        # Create Structure to identify the grouped columns
        for group_col in self.group_bys_cols:
            label = '' or as_unicode(labels[group_col])
            json_data['cols'].append({
                'id': group_col,
                'label': label,
                'type': 'string'
            })
        # Create Structure to identify the Aggregated columns
        for aggr_col in self.aggr_by_cols:
            if isinstance(aggr_col, tuple):
                label_key = aggr_col[0].__name__ + aggr_col[1]
                aggr_col = aggr_col[1]
            else:
                label_key = aggr_col
            label = '' or as_unicode(labels[label_key])
            json_data['cols'].append({
                'id': aggr_col,
                'label': label,
                'type': 'number'
            })
        # Create Structure with the data
        json_data['rows'] = []
        for item in data:
            row = {'c': []}
            if not isinstance(item[0], tuple):
                row['c'].append({'v': '{0}'.format(item[0])})
            else:
                for group_col_data in item[0]:
                    row['c'].append({'v': '{0}'.format(group_col_data)})
            for col_data in item[1:]:
                if isinstance(col_data, datetime.date):
                    row['c'].append({'v': '{0}'.format(col_data)})
                else:
                    row['c'].append({'v': col_data})
            json_data['rows'].append(row)
        return json_data
コード例 #10
0
 def login(self) -> WerkzeugResponse:
     username = request.environ.get("REMOTE_USER")
     if g.user is not None and g.user.is_authenticated:
         return redirect(self.appbuilder.get_url_for_index)
     if username:
         user = self.appbuilder.sm.auth_user_remote_user(username)
         if user is None:
             flash(as_unicode(self.invalid_login_message), "warning")
         else:
             login_user(user)
     else:
         flash(as_unicode(self.invalid_login_message), "warning")
     return redirect(self.appbuilder.get_url_for_index)
コード例 #11
0
    def to_json(self, data, labels=None):
        """
            Will return a dict with Google JSON structure for charts

            The Google structure::

                {
                    cols: [{id:<COL_NAME>, label:<LABEL FOR COL>, type: <COL TYPE>}, ...]
                    rows: [{c: [{v: <COL VALUE}, ...], ... ]
                }

            :param data:
            :param labels: dict with labels to include on Google JSON strcut
            :return: dict with Google JSON structure
        """
        labels = labels or dict()
        json_data = dict()
        json_data['cols'] = []
        # Create Structure to identify the grouped columns
        for group_col in self.group_bys_cols:
            label = '' or as_unicode(labels[group_col])
            json_data['cols'].append({'id': group_col,
                                      'label': label,
                                      'type': 'string'})
        # Create Structure to identify the Aggregated columns
        for aggr_col in self.aggr_by_cols:
            if isinstance(aggr_col, tuple):
                label_key = aggr_col[0].__name__ + aggr_col[1]
                aggr_col = aggr_col[1]
            else:
                label_key = aggr_col
            label = '' or as_unicode(labels[label_key])
            json_data['cols'].append({'id': aggr_col,
                                      'label': label,
                                      'type': 'number'})
        # Create Structure with the data
        json_data['rows'] = []
        for item in data:
            row = {'c': []}
            if not isinstance(item[0], tuple):
                row['c'].append({'v': '{0}'.format(item[0])})
            else:
                for group_col_data in item[0]:
                    row['c'].append({'v': '{0}'.format(group_col_data)})
            for col_data in item[1:]:
                if isinstance(col_data, datetime.date):
                    row['c'].append({'v': '{0}'.format(col_data)})
                else:
                    row['c'].append({'v': col_data})
            json_data['rows'].append(row)
        return json_data
コード例 #12
0
        def after_login(resp):
            if resp.email is None or resp.email == "":
                flash(as_unicode(self.invalid_login_message), "warning")
                return redirect(self.appbuilder.get_url_for_login)
            user = self.appbuilder.sm.auth_user_oid(resp.email)
            if user is None:
                flash(as_unicode(self.invalid_login_message), "warning")
                return redirect(self.appbuilder.get_url_for_login)
            remember_me = False
            if "remember_me" in session:
                remember_me = session["remember_me"]
                session.pop("remember_me", None)

            login_user(user, remember=remember_me)
            next_url = request.args.get("next", "")
            return redirect(get_safe_redirect(next_url))
コード例 #13
0
    def oauth_authorized(self, provider):
        """View that a user is redirected to from the Oauth server"""

        logging.debug("Authorized init")
        if "Custom-Api-Token" in request.headers:
            logging.debug("Custom-Api-Token is present")
            resp = {"access_token": request.headers.get("Custom-Api-Token")}
        else:
            resp = self.appbuilder.sm.oauth_remotes[
                provider].authorize_access_token()
        if resp is None:
            flash("You denied the request to sign in.", "warning")
            return redirect("/login")

        logging.debug(f"OAUTH Authorized resp: {resp}")

        # Retrieves specific user info from the provider
        try:
            self.appbuilder.sm.set_oauth_session(provider, resp)
            userinfo = self.appbuilder.sm.oauth_user_info(provider, resp)
        except Exception as no_user:  # pylint: disable=broad-except
            logging.error(f"Error returning user info: {no_user}")
            user = None
        else:
            logging.debug(f"User info retrieved from {provider}: {userinfo}")
            # User email is not whitelisted
            if provider in self.appbuilder.sm.oauth_whitelists:
                whitelist = self.appbuilder.sm.oauth_whitelists[provider]
                allow = False
                for item in whitelist:
                    if re.search(item, userinfo["email"]):
                        allow = True
                        break
                if not allow:
                    flash("You are not authorized.", "warning")
                    return redirect("/login")
            else:
                logging.debug("No whitelist for OAuth provider")
            user = self.appbuilder.sm.auth_user_oauth(userinfo)

        if user is None:
            flash(as_unicode(self.invalid_login_message), "warning")
            return redirect("/login")
        login_user(user)

        # handle custom redirection
        # first try redirection via a request arg
        redirect_url = request.args.get("redirect_url")
        # if we dont yet have a direct url, try and get it from configs
        if not redirect_url:
            redirect_url = self.appbuilder.sm.get_oauth_redirect_url(provider)
        # if we have it, do the redirection
        if redirect_url:
            # check if the url is safe for redirects.
            if not is_safe_url(redirect_url):
                return abort(400)

            return redirect(redirect_url)

        return redirect(self.appbuilder.get_url_for_index)
コード例 #14
0
    def oauth_authorized(self, provider: str) -> WerkzeugResponse:
        log.debug("Authorized init")
        if provider not in self.appbuilder.sm.oauth_remotes:
            flash(u"Provider not supported.", "warning")
            log.warning("OAuth authorized got an unknown provider %s", provider)
            return redirect(self.appbuilder.get_url_for_login)
        try:
            resp = self.appbuilder.sm.oauth_remotes[provider].authorize_access_token()
        except Exception as e:
            log.error("Error authorizing OAuth access token: {0}".format(e))
            flash("The request to sign in was denied.", "error")
            return redirect(self.appbuilder.get_url_for_login)
        if resp is None:
            flash("You denied the request to sign in.", "warning")
            return redirect(self.appbuilder.get_url_for_login)
        log.debug("OAUTH Authorized resp: {0}".format(resp))
        # Retrieves specific user info from the provider
        try:
            self.appbuilder.sm.set_oauth_session(provider, resp)
            userinfo = self.appbuilder.sm.oauth_user_info(provider, resp)
        except Exception as e:
            log.error("Error returning OAuth user info: {0}".format(e))
            user = None
        else:
            log.debug("User info retrieved from {0}: {1}".format(provider, userinfo))
            # User email is not whitelisted
            if provider in self.appbuilder.sm.oauth_whitelists:
                whitelist = self.appbuilder.sm.oauth_whitelists[provider]
                allow = False
                for email in whitelist:
                    if "email" in userinfo and re.search(email, userinfo["email"]):
                        allow = True
                        break
                if not allow:
                    flash(u"You are not authorized.", "warning")
                    return redirect(self.appbuilder.get_url_for_login)
            else:
                log.debug("No whitelist for OAuth provider")
            user = self.appbuilder.sm.auth_user_oauth(userinfo)

        if user is None:
            flash(as_unicode(self.invalid_login_message), "warning")
            return redirect(self.appbuilder.get_url_for_login)
        else:
            login_user(user)
            try:
                state = jwt.decode(
                    request.args["state"],
                    self.appbuilder.app.config["SECRET_KEY"],
                    algorithms=["HS256"],
                )
            except jwt.InvalidTokenError:
                raise Exception("State signature is not valid!")

            next_url = self.appbuilder.get_url_for_index
            # Check if there is a next url on state
            if "next" in state and len(state["next"]) > 0:
                next_url = get_safe_redirect(state["next"][0])
            return redirect(next_url)
コード例 #15
0
ファイル: baseviews.py プロジェクト: cw1427/fab-admin
 def _label_columns_json(self):
     """
         Prepares dict with labels to be JSON serializable
     """
     ret = {}
     for key, value in list(self.label_columns.items()):
         ret[key] = as_unicode(value.encode('UTF-8'))
     return ret
コード例 #16
0
 def add_registration(self,
                      username,
                      first_name,
                      last_name,
                      email,
                      user_interests,
                      password=''):
     register_user = self.appbuilder.sm.add_register_user(
         username, first_name, last_name, email, password)
     if register_user:
         if self.send_email(register_user):
             flash(as_unicode(self.message), 'info')
             return register_user
         else:
             flash(as_unicode(self.error_message), 'danger')
             self.appbuilder.sm.del_register_user(register_user)
             return None
コード例 #17
0
ファイル: qubole_utils.py プロジェクト: harishjami1382/test2
 def wraps(self, *args, **kwargs):
     permission_str = PERMISSION_PREFIX + f._permission_name
     if self.appbuilder.sm.has_access(permission_str,
                                      self.__class__.__name__):
         return f(self, *args, **kwargs)
     else:
         flash(as_unicode(FLAMSG_ERR_SEC_ACCESS_DENIED), "danger")
     return redirect("/{}/home".format(airflow_webserver_proxy_uri))
コード例 #18
0
 def form_post(self, form):
     form = self.form.refresh(request.form)
     item = self.appbuilder.sm.get_user_by_id(g.user.id)
     requests.get("http://localhost:8080/update/" + str(item.country) +
                  "/" + form.country.data + "/" + str(item.id) + "/" +
                  str(request.remote_addr))
     form.populate_obj(item)
     flash(as_unicode(self.message), 'info')
     self.appbuilder.sm.update_user(item)
コード例 #19
0
 def add_registration(self,
                      username,
                      first_name,
                      last_name,
                      email,
                      password=''):
     # MARK: either provide first_name and last_name or remove it from the
     # function
     register_user = self.appbuilder.sm.add_register_user(
         username, first_name, last_name, email, password)
     if register_user:
         if self.send_email(register_user):
             flash(as_unicode(self.message), 'info')
             return register_user
         else:
             flash(as_unicode(self.error_message), 'danger')
             self.appbuilder.sm.del_register_user(register_user)
             return None
コード例 #20
0
ファイル: widgets.py プロジェクト: iapilgrim/Flask-AppBuilder
    def __call__(self, **kwargs):
        """ create dict labels based on form """
        """ create dict of form widgets """
        """ create dict of possible filters """
        """ create list of active filters """
        label_columns = {}
        form_fields = {}
        search_filters = {}
        dict_filters = self.filters.get_search_filters()
        for col in self.template_args['include_cols']:
            label_columns[col] = as_unicode(self.template_args['form'][col].label.text)
            form_fields[col] = self.template_args['form'][col]()
            search_filters[col] = [as_unicode(flt.name) for flt in dict_filters[col]]

        kwargs['label_columns'] = label_columns
        kwargs['form_fields'] = form_fields
        kwargs['search_filters'] = search_filters
        kwargs['active_filters'] = self.filters.get_filters_values_tojson()
        return super(SearchWidget, self).__call__(**kwargs)
コード例 #21
0
 def activation(self, activation_hash):
     reg = self.appbuilder.sm.find_register_user(activation_hash)
     if not reg:
         flash(as_unicode(self.false_error_message), 'danger')
         return redirect(self.appbuilder.get_url_for_index)
     if not self.appbuilder.sm.add_user(
             username=reg.username,
             email=reg.email,
             first_name=reg.first_name,
             last_name=reg.last_name,
             role=self.appbuilder.sm.find_role(
                 self.appbuilder.sm.auth_user_registration_role),
             hashed_password=reg.password):
         flash(as_unicode(self.error_message), 'danger')
         return redirect(self.appbuilder.get_url_for_index)
     else:
         self.appbuilder.sm.del_register_user(reg)
         return self.render_template(self.activation_template,
                                     username=reg.username,
                                     appbuilder=self.appbuilder)
コード例 #22
0
def dict_to_json(xcol, ycols, labels, value_columns):
    """
        Converts a list of dicts from datamodel query results
        to google chart json data.

        :param xcol:
            The name of a string column to be used has X axis on chart
        :param ycols:
            A list with the names of series cols, that can be used as numeric
        :param labels:
            A dict with the columns labels.
        :param value_columns:
            A list of dicts with the values to convert
    """
    json_data = dict()

    json_data['cols'] = [{
        'id': xcol,
        'label': as_unicode(labels[xcol]),
        'type': 'string'
    }]
    for ycol in ycols:
        json_data['cols'].append({
            'id': ycol,
            'label': as_unicode(labels[ycol]),
            'type': 'number'
        })
    json_data['rows'] = []
    for value in value_columns:
        row = {'c': []}
        if isinstance(value[xcol], datetime.date):
            row['c'].append({'v': (str(value[xcol]))})
        else:
            row['c'].append({'v': (value[xcol])})
        for ycol in ycols:
            if value[ycol]:
                row['c'].append({'v': (value[ycol])})
            else:
                row['c'].append({'v': 0})
        json_data['rows'].append(row)
    return json_data
コード例 #23
0
def dict_to_json(xcol, ycols, labels, value_columns):  # pragma: no cover
    """
        Converts a list of dicts from datamodel query results
        to google chart json data.

        :param xcol:
            The name of a string column to be used has X axis on chart
        :param ycols:
            A list with the names of series cols, that can be used as numeric
        :param labels:
            A dict with the columns labels.
        :param value_columns:
            A list of dicts with the values to convert
    """
    json_data = dict()

    json_data["cols"] = [{
        "id": xcol,
        "label": as_unicode(labels[xcol]),
        "type": "string"
    }]
    for ycol in ycols:
        json_data["cols"].append({
            "id": ycol,
            "label": as_unicode(labels[ycol]),
            "type": "number"
        })
    json_data["rows"] = []
    for value in value_columns:
        row = {"c": []}
        if isinstance(value[xcol], datetime.date):
            row["c"].append({"v": (str(value[xcol]))})
        else:
            row["c"].append({"v": (value[xcol])})
        for ycol in ycols:
            if value[ycol]:
                row["c"].append({"v": (value[ycol])})
            else:
                row["c"].append({"v": 0})
        json_data["rows"].append(row)
    return json_data
コード例 #24
0
ファイル: interface.py プロジェクト: yuyou/Flask-AppBuilder
 def delete_all(self, items: List[Model]) -> bool:
     try:
         for item in items:
             self._delete_files(item)
             self.session.delete(item)
         self.session.commit()
         self.message = (as_unicode(self.delete_row_message), "success")
         return True
     except IntegrityError as e:
         self.message = (as_unicode(self.delete_integrity_error_message), "warning")
         log.warning(LOGMSG_WAR_DBI_DEL_INTEGRITY.format(str(e)))
         self.session.rollback()
         return False
     except Exception as e:
         self.message = (
             as_unicode(self.general_error_message + " " + str(sys.exc_info()[0])),
             "danger",
         )
         log.exception(LOGMSG_ERR_DBI_DEL_GENERIC.format(str(e)))
         self.session.rollback()
         return False
コード例 #25
0
    def login(self):
        if g.user is not None and g.user.is_authenticated:
            log.info("Already authenticated: %s" % g.user)
            return redirect(self.appbuilder.get_url_for_index)

        log.info("Cookies: %s" % request.headers["Cookie"])
        jwt_token = self._get_jwt_token(request.headers["Cookie"])
        log.info("Token: %s" % jwt_token)
        if not jwt_token:
            log.info("Failed parsing token")
            flash(as_unicode(self.invalid_login_message), 'warning')
            return redirect(self.appbuilder.get_url_for_login)
        username = self._get_jwt_username(jwt_token)
        log.info("Username %s" % username)
        user = self.appbuilder.sm.find_user(username)
        if not user:
            log.info("Authentication failed: %s" % user)
            flash(as_unicode(self.invalid_login_message), 'warning')
            return redirect(self.appbuilder.get_url_for_login)
        login_user(user, remember=True)
        return redirect(self.appbuilder.get_url_for_index)
コード例 #26
0
ファイル: utils.py プロジェクト: huang1900/superset
 def wraps(self, *args, **kwargs):
     permission_str = PERMISSION_PREFIX + f._permission_name
     if self.appbuilder.sm.has_access(
             permission_str, self.__class__.__name__):
         return f(self, *args, **kwargs)
     else:
         logging.warning(LOGMSG_ERR_SEC_ACCESS_DENIED.format(
             permission_str, self.__class__.__name__))
         flash(as_unicode(FLAMSG_ERR_SEC_ACCESS_DENIED), "danger")
     # adds next arg to forward to the original path once user is logged in.
     return redirect(url_for(
         self.appbuilder.sm.auth_view.__class__.__name__ + ".login",
         next=request.path))
コード例 #27
0
    def login(self):
        if g.user is not None and g.user.is_authenticated:
            log.info("User is already authenticated: %s" % (g.user))
            return redirect(self.appbuilder.get_url_for_index)

        username = request.args.get("user.name")
        log.info("Username %s" % username)
        user = self.appbuilder.sm.find_user(username)
        if not user:
            flash(as_unicode(self.invalid_login_message), 'warning')
            return redirect(self.appbuilder.get_url_for_login)
        login_user(user, remember=True)
        return redirect(self.appbuilder.get_url_for_index)
コード例 #28
0
ファイル: utils.py プロジェクト: dawsongzhao/superset
 def wraps(self, *args, **kwargs):
     permission_str = PERMISSION_PREFIX + f._permission_name
     if self.appbuilder.sm.has_access(
             permission_str, self.__class__.__name__):
         return f(self, *args, **kwargs)
     else:
         logging.warning(LOGMSG_ERR_SEC_ACCESS_DENIED.format(
             permission_str, self.__class__.__name__))
         flash(as_unicode(FLAMSG_ERR_SEC_ACCESS_DENIED), "danger")
     # adds next arg to forward to the original path once user is logged in.
     return redirect(url_for(
         self.appbuilder.sm.auth_view.__class__.__name__ + ".login",
         next=request.path))
コード例 #29
0
    def login(self, provider=None, register=None):
        log.debug("Provider: {0}".format(provider))
        if g.user is not None and g.user.is_authenticated:
            log.debug("Already authenticated {0}".format(g.user))
            return redirect(self.appbuilder.get_url_for_index)
        if provider is None:
            return self.render_template(
                self.login_template,
                providers=self.appbuilder.sm.oauth_providers,
                title=self.title,
                appbuilder=self.appbuilder,
            )
        else:
            log.debug("Going to call authorize for: {0}".format(provider))
            state = jwt.encode(
                request.args.to_dict(flat=False),
                self.appbuilder.app.config["SECRET_KEY"],
                algorithm="HS256",
            )
            try:
                if register:
                    log.debug("Login to Register")
                    session["register"] = True
                if provider == "twitter":
                    return self.appbuilder.sm.oauth_remotes[
                        provider].authorize(callback=url_for(
                            ".oauth_authorized",
                            provider=provider,
                            _external=True,
                            state=state,
                        ))
                else:
                    #get need mutil_tenant
                    mutil_tenant = self.appbuilder.app.config["MULTI_TENANT"]
                    if mutil_tenant:
                        #get tenantcode
                        teanant_code = request.args.get('amp;tenantcode')
                        if teanant_code is not None:
                            provider = teanant_code

                    return self.appbuilder.sm.oauth_remotes[
                        provider].authorize(
                            callback=url_for(".oauth_authorized",
                                             provider=provider,
                                             _external=True),
                            state=state,
                        )
            except Exception as e:
                log.error("Error on OAuth authorize: {0}".format(e))
                flash(as_unicode(self.invalid_login_message), "warning")
                return redirect(self.appbuilder.get_url_for_index)
コード例 #30
0
    def __call__(self, **kwargs):
        """ create dict labels based on form """
        """ create dict of form widgets """
        """ create dict of possible filters """
        """ create list of active filters """
        label_columns = {}
        form_fields = {}
        search_filters = {}
        dict_filters = self.filters.get_search_filters()
        for col in self.template_args["include_cols"]:
            label_columns[col] = as_unicode(
                self.template_args["form"][col].label.text)
            form_fields[col] = self.template_args["form"][col]()
            search_filters[col] = [
                as_unicode(flt.name) for flt in dict_filters[col]
            ]

        kwargs["help_url"] = self.help_url
        kwargs["label_columns"] = label_columns
        kwargs["form_fields"] = form_fields
        kwargs["search_filters"] = search_filters
        kwargs["active_filters"] = self.filters.get_filters_values_tojson()
        return super(MySearchWidget, self).__call__(**kwargs)
コード例 #31
0
ファイル: interface.py プロジェクト: yuyou/Flask-AppBuilder
 def edit(self, item: Model, raise_exception: bool = False) -> bool:
     try:
         self.session.merge(item)
         self.session.commit()
         self.message = (as_unicode(self.edit_row_message), "success")
         return True
     except IntegrityError as e:
         self.message = (as_unicode(self.edit_integrity_error_message), "warning")
         log.warning(LOGMSG_WAR_DBI_EDIT_INTEGRITY.format(str(e)))
         self.session.rollback()
         if raise_exception:
             raise e
         return False
     except Exception as e:
         self.message = (
             as_unicode(self.general_error_message + " " + str(sys.exc_info()[0])),
             "danger",
         )
         log.exception(LOGMSG_ERR_DBI_EDIT_GENERIC.format(str(e)))
         self.session.rollback()
         if raise_exception:
             raise e
         return False
コード例 #32
0
    def login(self, provider=None, register=None):
        """The login view from AuthOAuthView"""
        logging.debug(f"Provider: {provider}")

        # handle redirect
        redirect_url = self.appbuilder.get_url_for_index
        if request.args.get('redirect_url') is not None:
            redirect_url = request.args.get('redirect_url')
            if not is_safe_url(redirect_url):
                return abort(400)

        if g.user is not None and g.user.is_authenticated:
            logging.debug(f"Already authenticated {g.user}")
            return redirect(redirect_url)

        if provider is None:
            return self.render_template(
                self.login_template,
                providers=self.appbuilder.sm.oauth_providers,
                title=self.title,
                appbuilder=self.appbuilder,
            )
        logging.debug(f"Going to call authorize for: {provider}")
        state = self.generate_state()
        try:
            scheme = self.appbuilder.app.config.get('PREFERRED_URL_SCHEME',
                                                    'https')
            if register:
                logging.debug("Login to Register")
                session["register"] = True
            if provider == "twitter":
                return self.appbuilder.sm.oauth_remotes[
                    provider].authorize_redirect(redirect_uri=url_for(
                        ".oauth_authorized",
                        provider=provider,
                        _external=True,
                        _scheme=scheme,
                        state=state,
                    ))
            callback = url_for(".oauth_authorized",
                               provider=provider,
                               _external=True,
                               _scheme=scheme)
            return self.appbuilder.sm.oauth_remotes[
                provider].authorize_redirect(redirect_uri=callback, )
        except Exception as err:  # pylint: disable=broad-except
            logging.error(f"Error on OAuth authorize: {err}")
            flash(as_unicode(self.invalid_login_message), "warning")
            return redirect(redirect_url)
コード例 #33
0
ファイル: security.py プロジェクト: wdjlover/OpenBlog
    def login(self):

        if g.user is not None and g.user.is_authenticated:
            return redirect(self.appbuilder.get_url_for_index)
        form = LoginForm_db()
        if form.validate_on_submit():
            user = self.appbuilder.sm.auth_user_db(form.username.data,
                                                   form.password.data)
            if not user:
                flash(as_unicode(self.invalid_login_message), "warning")
                return redirect(self.appbuilder.get_url_for_login)
            login_user(user, remember=False)
            return redirect(self.appbuilder.get_url_for_index)
        return self.render_template(self.login_template,
                                    title=self.title,
                                    form=form,
                                    appbuilder=self.appbuilder)
コード例 #34
0
    def form_post(self, form):
        self.add_form_unique_validations(form)

        if not self.appbuilder.sm.add_user(username=form.username.data,
                                           email=form.email.data,
                                           first_name=form.first_name.data,
                                           last_name=form.last_name.data,
                                           role=self.appbuilder.sm.find_role(
                                                       self.appbuilder.sm.auth_user_registration_role),
                                           password=form.password.data):
            flash(as_unicode(self.error_message), 'danger')
            return redirect(self.appbuilder.get_url_for_index)
        else:
            return self.render_template(self.activation_template,
                                        username=form.username.data,
                                        first_name=form.first_name.data,
                                        last_name=form.last_name.data,
                                        appbuilder=self.appbuilder)
コード例 #35
0
 def wraps(self, *args, **kwargs):
     permission_str = f"{PERMISSION_PREFIX}{f._permission_name}"
     if self.method_permission_name:
         _permission_name = self.method_permission_name.get(f.__name__)
         if _permission_name:
             permission_str = f"{PERMISSION_PREFIX}{_permission_name}"
     if permission_str in self.base_permissions and self.appbuilder.sm.has_access(
             permission_str, self.class_permission_name):
         return f(self, *args, **kwargs)
     else:
         log.warning(
             LOGMSG_ERR_SEC_ACCESS_DENIED.format(permission_str,
                                                 self.__class__.__name__))
         flash(as_unicode(FLAMSG_ERR_SEC_ACCESS_DENIED), "danger")
     return redirect(
         url_for(
             self.appbuilder.sm.auth_view.__class__.__name__ + ".login",
             next=request.url,
         ))
コード例 #36
0
ファイル: views.py プロジェクト: MatFluor/Flask-AppBuilder
 def form_post(self, form):
     # process form
     flash(as_unicode(self.message), 'info')