Ejemplo n.º 1
0
def login_handler(response, provider, query):
    """Shared method to handle the signin process"""

    connection = _datastore.find_connection(**query)

    if connection:
        after_this_request(_commit)
        user = connection.user
        login_user(user)
        key = _social.post_oauth_login_session_key
        redirect_url = session.pop(key, get_post_login_redirect())

        login_completed.send(current_app._get_current_object(),
                             provider=provider, user=user)

        return redirect(redirect_url)

    login_failed.send(current_app._get_current_object(),
                      provider=provider,
                      oauth_response=response)
    #_security.login_manager.login_view = "user.register"
    #next = get_url(_security.login_manager.login_view)
    next = url_for('user.register', provider_id=provider.id, login_failed=1)
    msg = '%s account not associated with an existing user' % provider.name
    #if session['login_attempt']:
    #    session['failed_login_connection'] = dict(dummy="dummy")
    do_flash(msg, 'danger' if session['login_attempt'] else 'info')
    return redirect(next)
Ejemplo n.º 2
0
def login_user(user, remember=False, force=False):
    """
    Logs a user in. You should pass the actual user object to this. If the
    user's `is_active` method returns `False`, they will not be logged in
    unless `force` is `True`.

    This will return `True` if the log in attempt succeeds, and `False` if
    it fails (i.e. because the user is inactive).

    :param user: The user object to log in.
    :param remember: Whether to remember the user after their session expires.
    :param force: If the user is inactive, setting this to `True` will log
                  them in regardless.
    """
    if (not force) and (not user.is_active()):
        return False
    user_id = user.get_id()
    session["user_id"] = user_id
    session["_fresh"] = True
    if remember:
        session["remember"] = "set"
    app = current_app._get_current_object()
    current_app.login_manager.reload_user()
    user_logged_in.send(current_app._get_current_object(), user=_get_user())
    return True
Ejemplo n.º 3
0
    def revert(self, revision_id):
        """Revert the record to a specific revision.

        #. Send a signal :data:`invenio_records.signals.before_record_revert`
           with the current record as parameter.

        #. Revert the record to the revision id passed as parameter.

        #. Send a signal :data:`invenio_records.signals.after_record_revert`
           with the reverted record as parameter.

        :param revision_id: Specify the record revision id
        :returns: The :class:`Record` instance corresponding to the revision id
        """
        if self.model is None:
            raise MissingModelError()

        revision = self.revisions[revision_id]

        with db.session.begin_nested():
            before_record_revert.send(
                current_app._get_current_object(),
                record=self
            )

            self.model.json = dict(revision)

            db.session.merge(self.model)

        after_record_revert.send(
            current_app._get_current_object(),
            record=self
        )
        return self.__class__(self.model.json, model=self.model)
Ejemplo n.º 4
0
def login_handler(response, provider, query):
    """Shared method to handle the signin process"""

    connection = _datastore.find_connection(**query)

    if connection:
        after_this_request(_commit)
        user = connection.user
        login_user(user)
        key = _social.post_oauth_login_session_key
        redirect_url = session.pop(key, get_post_login_redirect())

        login_completed.send(current_app._get_current_object(),
                             provider=provider, user=user)

        return redirect(redirect_url)

    login_failed.send(current_app._get_current_object(),
                      provider=provider,
                      oauth_response=response)

    next = get_url(_security.login_manager.login_view)
    msg = '%s account not associated with an existing user' % provider.name
    do_flash(msg, 'error')
    return redirect(next)
Ejemplo n.º 5
0
def items_status_update(order_id, step):
    order = Order.get(order_id)
    if not order:
        abort(404)
    item_ids = request.form.getlist('item_id')
    leaders = request.form.getlist('leader')
    if not item_ids:
        flash(u"请选择订单项")
    else:
        action = int(request.form.get('action'))
        if action in STATUS_APPLLY:
            if not leaders:
                flash(u"请选择Leader")
                return redirect(url_for('schedule.order_detail', order_id=order.id, step=step))
            else:
                apply = ChangeStateApply(step, action, [User.get(m).email for m in leaders], order)
                order_apply_signal.send(current_app._get_current_object(), change_state_apply=apply)
                flash(u"请在2个自然日内与审核Leaer联系")
        if action in ITEM_STATUS_LEADER_ACTIONS:
            apply = ChangeStateApply(
                step,
                action,
                [order.creator.email],
                order)
            reply_apply_signal.send(current_app._get_current_object(), change_state_apply=apply)
        items = AdItem.gets(item_ids)
        AdItem.update_items_with_action(items, action, g.user)
        msg = '\n\n'.join(['%s : %s' % (item.name, ITEM_STATUS_ACTION_CN[action]) for item in items])
        order.add_comment(g.user, msg)
        flash(u'%s个排期项%s。请将理由在留言板上留言说明' % (len(items), ITEM_STATUS_ACTION_CN[action]))
        step = AdItem.get_next_step(step, action)
    return redirect(url_for('schedule.order_detail', order_id=order.id, step=step))
Ejemplo n.º 6
0
def load_user_from_request(req):
    api_key = req.args.get('api_key')
    if api_key:
        user = get_user_by_api_key(api_key)
        if user:
            identity_changed.send(current_app._get_current_object(),
                                  identity=Identity(user.id))
            user.login_type = API_LOGIN
            return user

    api_key = req.headers.get('Authorization')
    if api_key:
        api_key = api_key.replace('Basic ', '', 1)
        try:
            api_key = base64.b64decode(api_key)
        except TypeError:
            pass
        user = get_user_by_api_key(api_key)
        if user:
            identity_changed.send(current_app._get_current_object(),
                                  identity=Identity(user.id))
            user.login_type = API_LOGIN
            return user

    return None
Ejemplo n.º 7
0
def post(board):
    "Add a post to the board"
    
    #Make Sure threads are enabled
    if "Threads" in board.Disable:
        flash("Thread creation not allowed.")
        abort(400)
    
    #Parse out the options
    meta = get_post_opts(request.form.get("subject", ""),
                         request.form.get("author", "Anonymous"))
    
    #Make the new thread Object
    meta["post"] = Thread(text = request.form["content"],
                          subject = meta["subject"],
                          author = meta["trip"],
                          board = board)
    
    #Run signals
    g.signals.execute_commands.send(current_app._get_current_object(), meta=meta)
    g.signals.new_post.send(current_app._get_current_object(), meta=meta)
        
    #Save the post
    meta["post"].save()
    
    #Singal After the post is saved
    g.signals.save_post.send(current_app._get_current_object(), meta=meta)
    
    #Prune the boards
    if board.PruneAt:
        Board(board).prune(to_thread_count=board.PruneAt)
    
    return redirect(url_for("board", board=board.short))
Ejemplo n.º 8
0
def connect_handler(cv, provider):
    """Shared method to handle the connection process

    :param connection_values: A dictionary containing the connection values
    :param provider_id: The provider ID the connection shoudl be made to
    """
    cv.setdefault('user_id', current_user.get_id())
    connection = _datastore.find_connection(**cv)

    if connection is None:
        after_this_request(_commit)
        connection = _datastore.create_connection(**cv)
        msg = ('Connection established to %s' % provider.name, 'success')
        connection_created.send(current_app._get_current_object(),
                                user=current_user._get_current_object(),
                                connection=connection)
    else:
        msg = ('A connection is already established with %s '
               'to your account' % provider.name, 'notice')
        connection_failed.send(current_app._get_current_object(),
                               user=current_user._get_current_object())

    redirect_url = session.pop(config_value('POST_OAUTH_CONNECT_SESSION_KEY'),
                               get_url(config_value('CONNECT_ALLOW_VIEW')))

    do_flash(*msg)
    return redirect(redirect_url)
Ejemplo n.º 9
0
def custom(webhook):
    if webhook not in custom_webhooks.webhooks:
        raise ApiError("Custom webhook '%s' not found." % webhook, 404)

    try:
        rv = custom_webhooks.webhooks[webhook].incoming(
            query_string=request.args,
            payload=request.get_json() or request.get_data(as_text=True) or request.form
        )
    except Exception as e:
        raise ApiError(str(e), 400)

    if isinstance(rv, Alert):
        rv = [rv]

    if isinstance(rv, list):
        alerts = []
        for alert in rv:
            alert.customer = assign_customer(wanted=alert.customer)

            def audit_trail_alert(event: str):
                write_audit_trail.send(current_app._get_current_object(), event=event, message=alert.text, user=g.login,
                                       customers=g.customers, scopes=g.scopes, resource_id=alert.id, type='alert',
                                       request=request)

            try:
                alert = process_alert(alert)
            except RejectException as e:
                audit_trail_alert(event='alert-rejected')
                raise ApiError(str(e), 403)
            except RateLimit as e:
                audit_trail_alert(event='alert-rate-limited')
                return jsonify(status='error', message=str(e), id=alert.id), 429
            except HeartbeatReceived as e:
                audit_trail_alert(event='alert-heartbeat')
                return jsonify(status='ok', message=str(e), id=alert.id), 202
            except BlackoutPeriod as e:
                audit_trail_alert(event='alert-blackout')
                return jsonify(status='ok', message=str(e), id=alert.id), 202
            except Exception as e:
                raise ApiError(str(e), 500)

            text = 'alert received via {} webhook'.format(webhook)
            write_audit_trail.send(current_app._get_current_object(), event='webhook-received', message=text,
                                   user=g.login, customers=g.customers, scopes=g.scopes, resource_id=alert.id,
                                   type='alert', request=request)
            alerts.append(alert)

        if len(alerts) == 1:
            return jsonify(status='ok', id=alerts[0].id, alert=alerts[0].serialize), 201
        else:
            return jsonify(status='ok', ids=[alert.id for alert in alerts]), 201

    else:
        text = 'request received via {} webhook'.format(webhook)
        write_audit_trail.send(current_app._get_current_object(), event='webhook-received', message=text,
                               user=g.login, customers=g.customers, scopes=g.scopes, resource_id=None,
                               type='user-defined', request=request)
        return rv
Ejemplo n.º 10
0
def login():
    """ Prompt for username/email and password and sign the user in."""
    user_manager =  current_app.user_manager
    db_adapter = user_manager.db_adapter

    next = request.args.get('next', _endpoint_url(user_manager.after_login_endpoint))
    reg_next = request.args.get('reg_next', _endpoint_url(user_manager.after_register_endpoint))

    # Immediately redirect already logged in users
    if _call_or_get(current_user.is_authenticated) and user_manager.auto_login_at_login:
        return redirect(next)

    # Initialize form
    login_form = user_manager.login_form(request.form)          # for login.html
    register_form = user_manager.register_form()                # for login_or_register.html
    if request.method!='POST':
        login_form.next.data     = register_form.next.data = next
        login_form.reg_next.data = register_form.reg_next.data = reg_next

    # Process valid POST
    if request.method=='POST' and login_form.validate():
        # Retrieve User
        user = None
        user_email = None
        if user_manager.enable_username:
            # Find user record by username
            user = user_manager.find_user_by_username(login_form.username.data)
            user_email = None
            # Find primary user_email record
            if user and db_adapter.UserEmailClass:
                user_email = db_adapter.find_first_object(db_adapter.UserEmailClass,
                        user_id=int(user.get_id()),
                        is_primary=True,
                        )
            # Find user record by email (with form.username)
            if not user and user_manager.enable_email:
                user, user_email = user_manager.find_user_by_email(login_form.username.data)
        else:
            # Find user by email (with form.email)
            user, user_email = user_manager.find_user_by_email(login_form.email.data)

        if user:
            # Log user in
            return _do_login_user(user, login_form.next.data, login_form.remember_me.data)
    
    if not user:
	# Send unsuccessful_login signal
	signals.unsuccessful_login.send(current_app._get_current_object(),email=login_form.username.data)
    
    if request.method=='POST' and login_form.validate()==False:
	# Send unsuccessful_login signal
	signals.unsuccessful_login.send(current_app._get_current_object(),email=login_form.username.data)    

    # Process GET or invalid POST
    return render_template(user_manager.login_template,
            form=login_form,
            login_form=login_form,
            register_form=register_form)
Ejemplo n.º 11
0
def update(user_id, lid):
    okr_old = Okr.query.get(lid)

    if request.method == 'POST':
        okr_json = request.values.get('okr_json')
        o_kr = json.loads(okr_json)
        quarter = int(o_kr['quarter'])
        status = int(o_kr['status'])
        year = int(o_kr['year'])
        okrtext = json.dumps(o_kr['okrs'])
        if quarter == okr_old.quarter and year == okr_old.year:
            okr_update = Okr.query.get(lid)
            okr_update.year = year
            okr_update.quarter = quarter
            okr_update.status = status
            okr_update.o_kr = okrtext
            okr_update.creator_id = user_id
            okr_update.save()
            if int(status) == OKR_STATUS_APPLY:
                flash(u'已发送申请', 'success')
                account_okr_apply_signal.send(
                    current_app._get_current_object(), okr=okr_update)
            else:
                flash(u'修改成功', 'success')
            return redirect(url_for('account_okr.index'))
        elif Okr.query.filter_by(quarter=quarter, year=year, creator=g.user).first():
            flash(u'您已经填写过该季度的OKR表了!', 'danger')
            return tpl('/account/okr/update_new.html',
                       okrlist=o_kr['okrs'],
                       year=year,
                       quarter=quarter,
                       year_list=YEAR_LIST,
                       quarters=OKR_QUARTER_CN,
                       priority_list=PRIORITY_LIST)
        okr_update = Okr.query.get(lid)
        okr_update.year = year
        okr_update.quarter = quarter
        okr_update.status = status
        okr_update.o_kr = okrtext
        okr_update.creator_id = user_id
        okr_update.save()
        if int(status) == OKR_STATUS_APPLY:
            flash(u'已发送申请', 'success')
            account_okr_apply_signal.send(
                current_app._get_current_object(), okr=okr_update)
        else:
            flash(u'修改成功', 'success')
        return redirect(url_for('account_okr.index'))
    okr = Okr.query.get(lid)
    okrlist = json.loads(okr.o_kr)
    return tpl('/account/okr/update_new.html',
               okr=okr,
               okrlist=okrlist,
               year=str(okr.year),
               quarter=okr.quarter,
               year_list=YEAR_LIST,
               quarters=OKR_QUARTER_CN,
               priority_list=PRIORITY_LIST)
Ejemplo n.º 12
0
    def test_on_login_with_method(self):
        # no login method provided
        on_login_with_method.send(
            current_app._get_current_object(),
            event_name=on_login_with_method.name,
            user=self.user
        )

        expected_caliper_event = {
            'action': 'LoggedIn',
            'actor': self.get_compair_caliper_actor(self.user),
            'object': self.expected_caliper_object,
            'session': self.get_caliper_session(self.get_compair_caliper_actor(self.user)),
            'type': 'SessionEvent'
        }

        events = self.get_and_clear_caliper_event_log()
        self.assertEqual(len(events), 1)
        self.assertEqual(events[0], expected_caliper_event)

        expected_xapi_statement = {
            "actor": self.get_compair_xapi_actor(self.user),
            "verb": {
                'id': 'https://brindlewaye.com/xAPITerms/verbs/loggedin/',
                'display': {'en-US': 'logged in'}
            },
            "object": self.expected_xapi_object,
            "context": {
                'extensions': {
                    'http://id.tincanapi.com/extension/browser-info': {},
                    'http://id.tincanapi.com/extension/session-info': self.get_xapi_session_info()
                }
            },
        }

        statements = self.get_and_clear_xapi_statement_log()
        self.assertEqual(len(statements), 1)
        self.assertEqual(statements[0], expected_xapi_statement)

        # test with login method
        sess['login_method'] = "SAML"
        on_login_with_method.send(
            current_app._get_current_object(),
            event_name=on_login_with_method.name,
            user=self.user
        )

        expected_caliper_event['session'] = self.get_caliper_session(self.get_compair_caliper_actor(self.user))

        events = self.get_and_clear_caliper_event_log()
        self.assertEqual(len(events), 1)
        self.assertEqual(events[0], expected_caliper_event)

        expected_xapi_statement['context']['extensions']['http://id.tincanapi.com/extension/session-info'] = self.get_xapi_session_info()
        statements = self.get_and_clear_xapi_statement_log()
        self.assertEqual(len(statements), 1)
        self.assertEqual(statements[0], expected_xapi_statement)
Ejemplo n.º 13
0
def get_identity(username):
    user = User.query.filter_by(username=username).first()
    if user is not None:
        identity_changed.send(current_app._get_current_object(), identity=Identity(user.username))
    else:
        user = User(username, username+'@case.edu', 'new')
        db.session.add(user)
        db.session.commit()
        identity_changed.send(current_app._get_current_object(), identity=Identity(user.username))
Ejemplo n.º 14
0
def get_app():
    try:
        from flask import current_app

        current_app._get_current_object()

        return current_app
    except RuntimeError:
        return make_app()
Ejemplo n.º 15
0
 def decorated_function(classview, **kwargs):
     if g.profile and request.method == 'GET':
         if g.profile.legacy and current_app._get_current_object() is app:
             with funnelapp.app_context(), funnelapp.test_request_context():
                 return redirect(classview.obj.url_for(classview.current_handler.name, _external=True), code=303)
         elif not g.profile.legacy and current_app._get_current_object() is funnelapp:
             with app.app_context(), app.test_request_context():
                 return redirect(classview.obj.url_for(classview.current_handler.name, _external=True), code=303)
     return f(classview, **kwargs)
Ejemplo n.º 16
0
def back_money(order_id):
    if not (g.user.is_contract() or g.user.is_finance()):
        abort(404)
    order = DoubanOrder.get(order_id)
    if not order:
        abort(404)
    if request.method == 'POST':
        money = float(request.values.get('money', 0))
        back_time = request.values.get(
            'back_time', datetime.date.today().strftime('%Y-%m-%d'))
        back_money_status = request.values.get('back_money_status', '')
        if back_money_status != '':
            if int(back_money_status) == 0:
                order.back_money_status = int(back_money_status)
                order.save()
                flash(u'完成所有回款!', 'success')
                order.add_comment(g.user, u"完成所有回款", msg_channel=4)
                apply_context = {
                    'order': order,
                    'num': 0,
                    'type': 'end',
                }
                back_money_apply_signal.send(
                    current_app._get_current_object(), apply_context=apply_context)
            elif int(back_money_status) == -1:
                order.back_money_status = int(back_money_status)
                order.save()
                flash(u'该项目为划账!', 'success')
                order.add_comment(g.user, u"坏账项目", msg_channel=4)
                apply_context = {
                    'order': order,
                    'num': -1,
                    'type': 'end',
                }
                back_money_apply_signal.send(
                    current_app._get_current_object(), apply_context=apply_context)
        else:
            bm = BackMoney.add(
                douban_order=order,
                money=money,
                back_time=back_time,
                create_time=datetime.date.today().strftime('%Y-%m-%d'))
            bm.save()
            apply_context = {
                'order': order,
                'num': money,
                'type': 'money',
            }
            back_money_apply_signal.send(
                current_app._get_current_object(), apply_context=apply_context)
            flash(u'回款信息保存成功!', 'success')
            order.add_comment(
                g.user, u"更新了回款信息,回款金额: %s; 回款时间: %s;" % (money, back_time), msg_channel=4)
        return redirect(url_for("saler_douban_order_back_money.back_money", order_id=order.id))
    return tpl('/saler/douban_order/back_money/index.html', order=order)
Ejemplo n.º 17
0
def index():
    if request.method == 'POST':
        if 'signIn' in request.form:
            passed, errors = validate_signin_form(request.form)
            if not passed:
                return render_template('index.html', signInErrors=errors, riverId=request.form.get('riverId'))
            identity_changed.send(current_app._get_current_object(), identity=Identity(request.form.get('riverId')))
            return redirect(url_for('gatewaymanager'))
        if 'signOut' in request.form:
            identity_changed.send(current_app._get_current_object(), identity=Identity('guest'))
    return render_template('index.html')
Ejemplo n.º 18
0
def login():
	if octoprint.server.userManager is not None and "user" in request.values.keys() and "pass" in request.values.keys():
		username = request.values["user"]
		password = request.values["pass"]

		if "remember" in request.values.keys() and request.values["remember"] == "true":
			remember = True
		else:
			remember = False

		if "usersession.id" in session:
			_logout(current_user)

		user = octoprint.server.userManager.findUser(username)
		if user is not None:
			if octoprint.server.userManager.checkPassword(username, password):
				if octoprint.server.userManager is not None:
					user = octoprint.server.userManager.login_user(user)
					session["usersession.id"] = user.get_session()
				login_user(user, remember=remember)
				identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
				return jsonify(user.asDict())
		return make_response(("User unknown or password incorrect", 401, []))

	elif "passive" in request.values.keys():
		if octoprint.server.userManager is not None:
			user = octoprint.server.userManager.login_user(current_user)
		else:
			user = current_user

		if user is not None and not user.is_anonymous():
			identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
			return jsonify(user.asDict())
		elif s().getBoolean(["accessControl", "autologinLocal"]) \
			and s().get(["accessControl", "autologinAs"]) is not None \
			and s().get(["accessControl", "localNetworks"]) is not None:

			autologinAs = s().get(["accessControl", "autologinAs"])
			localNetworks = netaddr.IPSet([])
			for ip in s().get(["accessControl", "localNetworks"]):
				localNetworks.add(ip)

			try:
				remoteAddr = util.getRemoteAddress(request)
				if netaddr.IPAddress(remoteAddr) in localNetworks:
					user = octoprint.server.userManager.findUser(autologinAs)
					if user is not None:
						login_user(user)
						identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
						return jsonify(user.asDict())
			except:
				logger = logging.getLogger(__name__)
				logger.exception("Could not autologin user %s for networks %r" % (autologinAs, localNetworks))
	return NO_CONTENT
Ejemplo n.º 19
0
def send_to_parent(kind, *args):
    '''similar to the behaviour of a ParentedLet'''
    if not hasattr(current_app, 'queue'):
        logging.debug('no parent queue; aborting send')
        return
    msg = {
        'emitter': current_app._get_current_object(),
        'class': current_app._get_current_object().__class__.__name__,
        'kind': kind,
        'args': args
    }
    current_app.queue.put(msg)
Ejemplo n.º 20
0
    def _send(self, command, *args):
        fn = getattr(self.client, command)

        if fn is not None:
            if not self._app.config.get('FLASK_CENT_SUPPRESS', False):
                err = fn(*args)

                if isinstance(err, Exception):
                    message_error.send(current_app._get_current_object(), command=command, params=args)
                else:
                    message_sent.send(current_app._get_current_object(), command=command, params=args)
            else:
                message_sent.send(current_app._get_current_object(), command=command, params=args)
Ejemplo n.º 21
0
 def pages():
     kwargs = dict(
         _external=True,
         _scheme=self.app.config.get('SITEMAP_URL_SCHEME')
     )
     kwargs['page'] = 1
     yield {'loc': url_for('flask_sitemap.page', **kwargs)}
     sitemap_page_needed.send(current_app._get_current_object(),
                              page=1, urlset=urlset)
     for urlset_ in run:
         kwargs['page'] += 1
         yield {'loc': url_for('flask_sitemap.page', **kwargs)}
         sitemap_page_needed.send(current_app._get_current_object(),
                                  page=kwargs['page'], urlset=urlset_)
Ejemplo n.º 22
0
    def create(cls, data, id_=None, **kwargs):
        r"""Create a new record instance and store it in the database.

        #. Send a signal :data:`invenio_records.signals.before_record_insert`
           with the new record as parameter.

        #. Validate the new record data.

        #. Add the new record in the database.

        #. Send a signal :data:`invenio_records.signals.after_record_insert`
           with the new created record as parameter.

        :Keyword Arguments:
          * **format_checker** --
            An instance of the class :class:`jsonschema.FormatChecker`, which
            contains validation rules for formats. See
            :func:`~invenio_records.api.RecordBase.validate` for more details.

          * **validator** --
            A :class:`jsonschema.IValidator` class that will be used to
            validate the record. See
            :func:`~invenio_records.api.RecordBase.validate` for more details.

        :param data: Dict with the record metadata.
        :param id_: Specify a UUID to use for the new record, instead of
                    automatically generated.
        :returns: A new :class:`Record` instance.
        """
        from .models import RecordMetadata
        with db.session.begin_nested():
            record = cls(data)

            before_record_insert.send(
                current_app._get_current_object(),
                record=record
            )

            record.validate(**kwargs)

            record.model = RecordMetadata(id=id_, json=record)

            db.session.add(record.model)

        after_record_insert.send(
            current_app._get_current_object(),
            record=record
        )
        return record
Ejemplo n.º 23
0
def contract_apply(order):
    if not order:
        abort(404)
    to_users = User.douban_contracts_by_order(order) + [order.creator, g.user]
    to_emails = [x.email for x in set(to_users)]
    douban_contract_apply_context = {"to": to_emails, "order": order}
    if order.__tablename__ == 'bra_framework_order':
        framework_douban_contract_apply_signal.send(current_app._get_current_object(),
                                                    apply_context=douban_contract_apply_context)
    else:
        douban_contract_apply_signal.send(current_app._get_current_object(),
                                          apply_context=douban_contract_apply_context)
    flash(u'[%s] 已向豆瓣发送合同号申请邮件 ' % (order.name), 'success')
    flash(u'[%s] 已发送邮件给 %s ' % (order.name, ', '.join(to_emails)), 'info')
    return redirect(order.info_path())
Ejemplo n.º 24
0
def login():
    # 已登录用户则返回首页
    if g.user.is_authenticated:
        return redirect(url_for('frontend.index'))

    login_form = LoginForm()
    if login_form.validate_on_submit():
        people = People.query.authenticate(
            login_form.login.data,
            login_form.password.data,
        )

        if people:
            login_user(people, remember=login_form.remember.data)
            # Flask-Principal 发送信号
            identity_changed.send(current_app._get_current_object(), identity=Identity(people.id))
            print 'sent by login'
            ip = get_client_ip()
            login_log = LoginLog(people.id, ip)
            db.session.add(login_log)
            db.session.commit()

            flash('登录成功', 'success')
            return redirect(url_for('frontend.index'))
        else:
            flash('登录失败', 'warning')

    return render_template('login.html', form=login_form)
Ejemplo n.º 25
0
    def send(self, message, envelope_from=None):
        """Verifies and sends message.

        :param message: Message instance.
        :param envelope_from: Email address to be used in MAIL FROM command.
        """
        assert message.recipients, "No recipients have been added"

        assert message.sender, (
                "The message does not specify a sender and a default sender "
                "has not been configured")

        if message.has_bad_headers():
            raise BadHeaderError

        if message.date is None:
            message.date = time.time()

        if self.host:
            self.host.sendmail(sanitize_address(envelope_from or message.sender),
                               sanitize_addresses(message.send_to),
                               message.as_string(),
                               message.mail_options,
                               message.rcpt_options)

        email_dispatched.send(message, app=current_app._get_current_object())

        self.num_emails += 1

        if self.num_emails == self.mail.max_emails:
            self.num_emails = 0
            if self.host:
                self.host.quit()
                self.host = self.configure_host()
Ejemplo n.º 26
0
def change_password():
    """ Prompt for old password and new password and change the user's password."""
    user_manager =  current_app.user_manager
    db_adapter = user_manager.db_adapter

    # Initialize form
    form = user_manager.change_password_form(request.form)
    form.next.data = request.args.get('next', _endpoint_url(user_manager.after_change_password_endpoint))  # Place ?next query param in next form field

    # Process valid POST
    if request.method=='POST' and form.validate():
        # Hash password
        hashed_password = user_manager.hash_password(form.new_password.data)

        # Change password
        user_manager.update_password(current_user, hashed_password)

        # Send 'password_changed' email
        if user_manager.enable_email and user_manager.send_password_changed_email:
            emails.send_password_changed_email(current_user)

        # Send password_changed signal
        signals.user_changed_password.send(current_app._get_current_object(), user=current_user)

        # Prepare one-time system message
        flash(_('Your password has been changed successfully.'), 'success')

        # Redirect to 'next' URL
        return redirect(form.next.data)

    # Process GET or invalid POST
    return render_template(user_manager.change_password_template, form=form)
Ejemplo n.º 27
0
def change_username():
    """ Prompt for new username and old password and change the user's username."""
    user_manager =  current_app.user_manager
    db_adapter = user_manager.db_adapter

    # Initialize form
    form = user_manager.change_username_form(request.form)
    form.next.data = request.args.get('next', _endpoint_url(user_manager.after_change_username_endpoint))  # Place ?next query param in next form field

    # Process valid POST
    if request.method=='POST' and form.validate():
        new_username = form.new_username.data

        # Change username
        user_auth = current_user.user_auth if db_adapter.UserAuthClass and hasattr(current_user, 'user_auth') else current_user
        db_adapter.update_object(user_auth, username=new_username)
        db_adapter.commit()

        # Send 'username_changed' email
        if user_manager.enable_email and user_manager.send_username_changed_email:
            emails.send_username_changed_email(current_user)

        # Send username_changed signal
        signals.user_changed_username.send(current_app._get_current_object(), user=current_user)

        # Prepare one-time system message
        flash(_("Your username has been changed to '%(username)s'.", username=new_username), 'success')

        # Redirect to 'next' URL
        return redirect(form.next.data)

    # Process GET or invalid POST
    return render_template(user_manager.change_username_template, form=form)
Ejemplo n.º 28
0
def signup():

    if 'openid' not in session:
        abort(403)

    form = OpenIdSignupForm(next=request.args.get("next"),
                            username=request.args.get("name"),
                            email=request.args.get("email"))

    if form.validate_on_submit():

        user = User(openid=session.pop('openid'))
        form.populate_obj(user)

        db.session.add(user)
        db.session.commit()

        session.permanent = True

        identity_changed.send(current_app._get_current_object(),
                              identity=Identity(user.id))

        flash(_("Welcome, %%s") % user.username, "success")

        next_url = form.next.data or \
            url_for("user.posts", username=user.username)

        return redirect(next_url)

    return render_template("openid_signup.html", form=form)
Ejemplo n.º 29
0
def login_user(user, remember=None):
    """Performs the login routine.

    :param user: The user to login
    :param remember: Flag specifying if the remember cookie should be set. Defaults to ``False``
    """

    if remember is None:
        remember = config_value('DEFAULT_REMEMBER_ME')

    if not _login_user(user, remember):  # pragma: no cover
        return False

    if _security.trackable:
        if 'X-Forwarded-For' not in request.headers:
            remote_addr = request.remote_addr or 'untrackable'
        else:
            remote_addr = request.headers.getlist("X-Forwarded-For")[0]

        old_current_login, new_current_login = user.current_login_at, datetime.utcnow()
        old_current_ip, new_current_ip = user.current_login_ip, remote_addr

        user.last_login_at = old_current_login or new_current_login
        user.current_login_at = new_current_login
        user.last_login_ip = old_current_ip or new_current_ip
        user.current_login_ip = new_current_ip
        user.login_count = user.login_count + 1 if user.login_count else 1

        _datastore.put(user)

    identity_changed.send(current_app._get_current_object(),
                          identity=Identity(user.id))
    return True
Ejemplo n.º 30
0
def _do_login_user(user, next, remember_me=False):
    # User must have been authenticated
    if not user: return unauthenticated()

    # Check if user account has been disabled
    if not _call_or_get(user.is_active):
        flash(_('Your account has not been enabled.'), 'error')
        return redirect(url_for('user.login'))

    # Check if user has a confirmed email address
    user_manager = current_app.user_manager
    if user_manager.enable_email and user_manager.enable_confirm_email \
            and not current_app.user_manager.enable_login_without_confirm_email \
            and not user.has_confirmed_email():
        url = url_for('user.resend_confirm_email')
        flash(_('Your email address has not yet been confirmed. Check your email Inbox and Spam folders for the confirmation email or <a href="%(url)s">Re-send confirmation email</a>.', url=url), 'error')
        return redirect(url_for('user.login'))

    # Use Flask-Login to sign in user
    #print('login_user: remember_me=', remember_me)
    login_user(user, remember=remember_me)

    # Send user_logged_in signal
    signals.user_logged_in.send(current_app._get_current_object(), user=user)

    # Prepare one-time system message
    flash(_('You have signed in successfully.'), 'success')

    # Redirect to 'next' URL
    return redirect(next)
Ejemplo n.º 31
0
def network():
    flask_app = current_app._get_current_object()
    user = get_request_user(
        request.args.get('api_key', flask_app.config.get('DEV_API_KEY')))

    if not user:
        raise Exception("Unable to find requested user")

    if request.method == 'GET':
        filter = request.args.get('provider')

        networks = Network.objects.filter(user=user,
                                          provider=filter,
                                          active=True)
        networks_data = json.loads(networks.to_json())
        return jsonify(networks_data)

    if request.method == 'POST':
        post_data = request.get_json().get('body', {})
        credentials = request.get_json().get('credentials', {})
        provider = post_data.get('provider', '')

        if provider == 'admob' or provider == 'play':
            # credentials = request_google_credentials(user.id, post_data.get('name'), provider)
            auth_url = authorize(user.id, post_data.get('name'), provider)

            return jsonify({'status': 'google', 'auth_url': auth_url})

        if provider == 'itunes':
            from app.utils.crypto import AESCipher
            aes = AESCipher('wixot')
            credentials['password'] = (aes.encrypt(
                credentials['password'])).decode('utf-8')

        if credentials:
            Network.objects.create(name=post_data.get('name'),
                                   user=user,
                                   provider=provider,
                                   credentials=credentials,
                                   active=True)

        return jsonify({'status': 'ok'})

    if request.method == 'PATCH':
        patch_data = request.get_json().get('body', {})
        credentials = request.get_json().get('credentials', {})
        network = Network.objects.filter(id=patch_data['_id']['$oid'])
        provider = patch_data.get('provider', '')

        if provider == 'admob':
            # credentials = request_google_credentials(user.id, post_data.get('name'), provider)
            try:
                os.remove(
                    os.path.abspath(
                        os.path.join(
                            os.curdir, 'media/adsense/{}_{}_{}.dat'.format(
                                user.id, patch_data.get('name'), 'adsense'))))
            except:
                print('File Not Found')

            auth_url = authorize(user.id, patch_data.get('name'), provider)

            return jsonify({'status': 'google', 'auth_url': auth_url})

        if provider == 'play':
            try:
                os.remove(
                    os.path.abspath(
                        os.path.join(
                            os.curdir,
                            'media/androidpublisher/{}_{}_{}.dat'.format(
                                user.id, patch_data.get('name'),
                                'androidpublisher'))))
            except:
                print('File Not Found')

            auth_url = authorize(user.id, patch_data.get('name'), provider)

            return jsonify({'status': 'google', 'auth_url': auth_url})

        if provider == 'itunes':
            from app.utils.crypto import AESCipher
            aes = AESCipher('wixot')
            credentials['password'] = (aes.encrypt(
                credentials['password'])).decode('utf-8')

        if credentials:
            network.update(name=patch_data['name'],
                           credentials=credentials,
                           active=True)

        return jsonify({'status': 'ok'})

    if request.method == 'DELETE':
        filter_id = request.args.get('id')
        Network.objects.filter(id=filter_id).update(active=False)
        Credentials.objects.filter(network__id=filter_id).update(active=False)

        return jsonify({'status': 'ok'})

    return jsonify({'status': 'error'})
Ejemplo n.º 32
0
    def post(self, slug=None, post_type='post', is_draft=False):
        article_model = article_models['post'] if request.form.get('publish') else article_models['draft']

        form = forms.PostForm(obj=request.form)
        if not form.validate():
            return self.get(slug, form)

        # if slug:
        #     post = article_model.objects.get_or_404(slug=slug)
        # else:
        #     post = article_model()
        #     post.author = get_current_user()

        try:
            post = article_model.objects.get_or_404(slug=slug)
        except:
            post = article_model()
            post.author = get_current_user()

        post.title = form.title.data.strip()
        post.slug = form.slug.data.strip()
        post.raw = form.raw.data.strip()
        abstract = form.abstract.data.strip()
        post.abstract = abstract if abstract else post.raw[:140]
        post.category = form.category.data.strip() if form.category.data.strip() else None
        post.tags = [tag.strip() for tag in form.tags_str.data.split(',')] if form.tags_str.data else None
        post.post_type = form.post_type.data if form.post_type.data else None

        post_urls = {
            'post': url_for('blog_admin.posts'),
            'page': url_for('blog_admin.pages'),
            'wechat': url_for('blog_admin.wechats'),
        }

        draft_urls = {
            'post': url_for('blog_admin.drafts'),
            'page': url_for('blog_admin.page_drafts'),
            'wechat': url_for('blog_admin.wechat_drafts'),
        }

        if request.form.get('publish'):
            post.is_draft = False
            msg = 'Succeed to publish the {0}'.format(post_type)
            # redirect_url = url_for('blog_admin.pages') if form.post_type.data == 'page' else url_for('blog_admin.posts')
            redirect_url = post_urls[form.post_type.data]
            post.save()

            signals.post_pubished.send(current_app._get_current_object(), post=post)

            try:
                draft = models.Draft.objects.get(slug=slug)
                draft.delete()
            except:
                pass

            try:
                post_statistic = models.PostStatistics.objects.get(post=post)
            except models.PostStatistics.DoesNotExist:
                post_statistic = models.PostStatistics()
                post_statistic.post = post
                post_statistic.verbose_count_base = random.randint(500, 5000)
                post_statistic.save()

        elif request.form.get('draft'):
            post.is_draft = True
            msg = 'Succeed to save the draft'
            # redirect_url = url_for('blog_admin.page_drafts') if form.post_type.data == 'page' else url_for('blog_admin.drafts')
            redirect_url = draft_urls[form.post_type.data]
            post.save()
        else:
            return self.get(slug, form, is_draft)

        flash(msg, 'success')
        return redirect(redirect_url)
Ejemplo n.º 33
0
 def audit_trail_alert(event: str):
     write_audit_trail.send(current_app._get_current_object(), event=event, message=alert.text, user=g.login,
                            customers=g.customers, scopes=g.scopes, resource_id=alert.id, type='alert', request=request)
Ejemplo n.º 34
0
def modify():
    """
	"""

    data = request.get_json()
    file_id = data.get('file_id')
    new_extension = data.get('extension').lower()  # None Type Error
    new_extension = File.sanitize_extension(new_extension)
    headers = data['headers']  # Key Error
    current_app.logger.debug(
        f"File ID- {file_id} \nExtension - {new_extension} \nHeader list- {headers} \n..."
    )
    position_dict = {}
    header_name_dict = {}
    for head, details in headers.items():
        header_name_dict[head] = details['header_name']
        position_dict[head] = details['position']
    new_header_list = [
        x[0] for x in sorted(position_dict.items(), key=lambda x: x[1])
    ]

    # Getting current file from DB.
    file_collection = mongo.db.uploaded_files
    current_file = file_collection.find_one({'_id': ObjectId(file_id)})

    ## TO-DO -
    # Put check to ensure same user is accessing the file
    # if current_user.public_id == current_file.user_id:
    # if session['user_id'] == current_user.public_id == current_file.user_id
    # abort (404) unauthorized error

    current_file_path = current_file.get('file_path')
    name, extension = os.path.splitext(os.path.basename(current_file_path))
    ext = extension.split('.')[-1].lower()
    ext = File.sanitize_extension(ext)
    update_file_obj = File(user_id=current_file['user_id'],
                           file_path=current_app.config['DOWNLOAD_FOLDER'] +
                           '123/')

    # Downloading the original file from the S3 bucket.
    # Creating the dataframe of the file

    aws = AWSBucket(current_app._get_current_object())
    df = aws.aws_to_dataframe(key=current_file_path, extension=ext)

    # Modifying the data frame Adding the new modified headers
    try:
        df = df[
            new_header_list]  # NoneType/AttributeError if Dataframe has not been formed

    except AttributeError:
        current_app.logger.debug(
            "Dataframe is not created. Extension provided incorrect.")
        raise Exception("Dataframe not created. The file uploaded is invalid.")

    # Modifying the data frame Renaming the headers
    df.rename(columns=header_name_dict, inplace=True)
    current_app.logger.debug("Dataframe modified")

    result = update_file_obj.generate_update_file_df(
        data_frame=df, current_file=current_file, new_extension=new_extension)
    new_file_document = result['file_document']
    s3_key = new_file_document['file_path']

    #### Uploading onto S3
    aws.put_file(body=result['file_object'].getvalue(), key=s3_key)
    current_app.logger.info(f"New file uploaded to S3\nKey - {s3_key}")

    #### Adding the Updated File document to the Database
    # Add file document to the database
    _id = file_collection.insert_one(new_file_document)
    # Append new files object id into the versions of the parent file
    parent_file = file_collection.find_one(
        {'_id': ObjectId(new_file_document['parent_file_oid'])})
    versions = parent_file.get('versions')
    versions.append(_id.inserted_id)
    file_collection.save(parent_file)
    current_app.logger.info(
        f"New file object added to the database\nID - {_id.inserted_id}")

    return {
        'key':
        s3_key,
        'attachment_name':
        f'{new_file_document["original_filename"]}.{new_extension}'
    }, 200
Ejemplo n.º 35
0
def send_mail(subject, to, template, **kwargs):
    app = current_app._get_current_object()
    message = Message(subject, recipients=[to])
    message.html = render_template(template, **kwargs)
    thr = Thread(target=_send_async_mail, args=[app, message])
    thr.start()
Ejemplo n.º 36
0
def set_identity(u):
    """Sets identity in flask.g to the user."""
    identity = Identity(u.id)
    identity_changed.send(current_app._get_current_object(), identity=identity)
    assert flask.g.identity.id == u.id
Ejemplo n.º 37
0
def send_email(subject, sender, recipients, text_body, html_body):
    msg = Message(subject, sender=sender, recipients=recipients)
    msg.body = text_body
    msg.html = html_body
    Thread(target=send_async_email,
           args=(current_app._get_current_object(), msg)).start()
Ejemplo n.º 38
0
def save_in_thread(filepath, obj):
    app = current_app._get_current_object()
    t = threading.Thread(target=save_object_in_app, args=[app, filepath, obj])
    t.start()
Ejemplo n.º 39
0
def reset_password(token):
    """ Verify the password reset token, Prompt for new password, and set the user's password."""
    # Verify token
    user_manager = current_app.user_manager
    db_adapter = user_manager.db_adapter

    if _call_or_get(current_user.is_authenticated):
        logout_user()

    is_valid, has_expired, user_id = user_manager.verify_token(
        token, user_manager.reset_password_expiration)

    if has_expired:
        flash(_('Your reset password token has expired.'), 'error')
        return redirect(_endpoint_url(user_manager.login_endpoint))

    if not is_valid:
        flash(_('Your reset password token is invalid.'), 'error')
        return redirect(_endpoint_url(user_manager.login_endpoint))

    user = user_manager.get_user_by_id(user_id)

    # Mark email as confirmed
    user_email = emails.get_primary_user_email(user)
    user_email.confirmed_at = datetime.utcnow()
    db_adapter.commit()

    # Initialize form
    form = user_manager.reset_password_form(request.form)

    # Process valid POST
    if request.method == 'POST' and form.validate():

        # Change password
        hashed_password = user_manager.hash_password(form.new_password.data)
        user_auth = user.user_auth if db_adapter.UserAuthClass and hasattr(
            user, 'user_auth') else user
        db_adapter.update_object(user_auth, password=hashed_password)
        db_adapter.commit()

        # Send 'password_changed' email
        if user_manager.enable_email and user_manager.send_password_changed_email:
            emails.send_password_changed_email(user)

        # Send user_reset_password signal
        signals.user_reset_password.send(current_app._get_current_object(),
                                         user=user)

        # Prepare one-time system message
        flash(_("Your password has been reset successfully."), 'success')

        # Auto-login after reset password or redirect to login page
        safe_next = _get_safe_next_param(
            'next', user_manager.after_reset_password_endpoint)
        if user_manager.auto_login_after_reset_password:
            return _do_login_user(user, safe_next)  # auto-login
        else:
            return redirect(
                url_for('user.login') + '?next=' +
                quote(safe_next))  # redirect to login page

    # Process GET or invalid POST
    return render(user_manager.reset_password_template, form=form)
Ejemplo n.º 40
0
def issueTask_deal():
    # 获取数据文件的存储位置时,需要使用当前应用实例 app 来创建
    # 应用上下文,所以需要获取 current_app 代理对象背后潜在的被代理的当前应用实例 app,
    # 可以用 _get_current_object() 方法获取 app。
    app = current_app._get_current_object()

    taskIds = request.values.get('taskIds')
    taskIds = taskIds.strip('[]')
    taskIds = taskIds.split(',')
    print(taskIds)
    issue_task_queue = []
    for taskId in taskIds:
        taskId = int(taskId)
        # 从 Task 模型中找到由 taskId 指定的任务
        task = Task.query.filter_by(task_id=taskId).first()
        if task is not None:
            # 如果当前任务的状态是可以执行 EXECUTABLE,表示确实需要执行,
            # 这里加上这个判断是由于先按下单个执行按钮再按下全部执行按钮之后,
            # 之前当个执行按钮已经下发执行的那个任务会再次被下发执行,而此时
            # 该任务的状态已经是正在执行而不是可执行了,所以通过判断这个任务状态,
            # 可以将这个已经提交的任务不再提交
            if task.task_status == Task_Status.EXECUTABLE:
                print('task_id: %s' % task.task_id)
                # 将其状态标记为正在执行
                task.task_status = Task_Status.RUNNING

                # 将每一个需要下发的任务解析并添加到下发任务队列
                # 获取任务数据文件的存储位置
                taskDataPath = ''
                if (task.data_file_name != ''):
                    taskDataPath = os.path.join(
                        app.config['UPLOADED_TASKDATAS_DEST'],
                        task.data_file_name)
                    print('taskDataPath: %s' % taskDataPath)
                    taskSize = os.path.getsize(
                        taskDataPath) >> 10  # 大小以 kb 为单位
                else:
                    taskSize = 0
                issue_task = {
                    'taskId': chr(task.task_id),
                    'taskSize': taskSize,
                    'taskDataPath': taskDataPath,
                }
                issue_task_queue.append(issue_task)

                try:
                    db.session.add(task)
                    db.session.commit()
                except Exception as err:
                    print('Modify task: %s status occurs error: %s' %
                          (taskId, err))
                    db.session.rollback()
                    return jsonify({'status': -1})
    print('issueTask_deal: %s' % issue_task_queue)
    # 调用处理函数改变 socket_client 中 cmd_search 中 parseIssueTaskData 对应的数据
    parseIssueTaskQueue(issue_task_queue)
    # 通过 socket 与主控板通信,进行任务下发及结果接收
    updateModel(parseIssueTaskData, user_email=current_user.email)

    alive_tasks_queue, executable_len, running_len = query_construct_aliveTasks(
        current_user)
    alive_tasks_info = {
        'alive_tasks_queue': alive_tasks_queue,
        'executable_len': executable_len,
        'running_len': running_len,
        'status': 0
    }

    return jsonify(alive_tasks_info)
Ejemplo n.º 41
0
def uploads_taskdatas(filename):
    # 获取用于保存数据文件的目录时,需要使用当前应用实例 app 来创建
    # 应用上下文,所以需要获取 current_app 代理对象背后潜在的被代理的当前应用实例 app,
    # 可以用 _get_current_object() 方法获取 app。
    app = current_app._get_current_object()
    return send_from_directory(app.config['UPLOADED_TASKDATAS_DEST'], filename)
Ejemplo n.º 42
0
    def get(self):

        app = current_app._get_current_object()

        return app.config["TRIGGER"].get_jobs()
Ejemplo n.º 43
0
 def create_topic(self, **kwargs):
     topic = self.create(**kwargs)
     topic_create_signal.send(current_app._get_current_object(),
                              topic=topic)
    def handle_error(self, e):
        '''
        Error handler for the API transforms a raised exception into a Flask response,
        with the appropriate HTTP status code and body.

        :param Exception e: the raised Exception object

        '''
        got_request_exception.send(current_app._get_current_object(),
                                   exception=e)

        if not isinstance(e,
                          HTTPException) and current_app.propagate_exceptions:
            exc_type, exc_value, tb = sys.exc_info()
            if exc_value is e:
                raise
            else:
                raise e

        include_message_in_response = current_app.config.get(
            "ERROR_INCLUDE_MESSAGE", True)
        default_data = {}

        headers = Headers()

        for typecheck, handler in six.iteritems(
                self._own_and_child_error_handlers):
            if isinstance(e, typecheck):
                result = handler(e)
                default_data, code, headers = unpack(
                    result, HTTPStatus.INTERNAL_SERVER_ERROR)
                break
        else:
            if isinstance(e, HTTPException):
                code = HTTPStatus(e.code)
                if include_message_in_response:
                    default_data = {
                        'message': getattr(e, 'description', code.phrase)
                    }
                headers = e.get_response().headers
            elif self._default_error_handler:
                result = self._default_error_handler(e)
                default_data, code, headers = unpack(
                    result, HTTPStatus.INTERNAL_SERVER_ERROR)
            else:
                code = HTTPStatus.INTERNAL_SERVER_ERROR
                if include_message_in_response:
                    default_data = {
                        'message': code.phrase,
                    }

        if include_message_in_response:
            default_data['message'] = default_data.get('message', str(e))

        data = getattr(e, 'data', default_data)
        fallback_mediatype = None

        if code >= HTTPStatus.INTERNAL_SERVER_ERROR:
            exc_info = sys.exc_info()
            if exc_info[1] is None:
                exc_info = None
            current_app.log_exception(exc_info)

        elif code == HTTPStatus.NOT_FOUND and current_app.config.get("ERROR_404_HELP", True) \
                and include_message_in_response:
            data['message'] = self._help_on_404(data.get('message', None))

        elif code == HTTPStatus.NOT_ACCEPTABLE and self.default_mediatype is None:
            # if we are handling NotAcceptable (406), make sure that
            # make_response uses a representation we support as the
            # default mediatype (so that make_response doesn't throw
            # another NotAcceptable error).
            supported_mediatypes = list(self.representations.keys())
            fallback_mediatype = supported_mediatypes[
                0] if supported_mediatypes else "text/plain"

        # Remove blacklisted headers
        for header in HEADERS_BLACKLIST:
            headers.pop(header, None)

        resp = self.make_response(data,
                                  code,
                                  headers,
                                  fallback_mediatype=fallback_mediatype)

        if code == HTTPStatus.UNAUTHORIZED:
            resp = self.unauthorized(resp)
        return resp
Ejemplo n.º 45
0
    def post(self):
        """
        .. http:post:: /auth/login

           Login with username:password

           **Example request**:

           .. sourcecode:: http

              POST /auth/login HTTP/1.1
              Host: example.com
              Accept: application/json, text/javascript

              {
                "username": "******",
                "password": "******"
              }

           **Example response**:

           .. sourcecode:: http

              HTTP/1.1 200 OK
              Vary: Accept
              Content-Type: text/javascript

              {
                "token": "12343243243"
              }

           :arg username: username
           :arg password: password
           :statuscode 401: invalid credentials
           :statuscode 200: no error
        """
        self.reqparse.add_argument('username',
                                   type=str,
                                   required=True,
                                   location='json')
        self.reqparse.add_argument('password',
                                   type=str,
                                   required=True,
                                   location='json')

        args = self.reqparse.parse_args()

        if '@' in args['username']:
            user = user_service.get_by_email(args['username'])
        else:
            user = user_service.get_by_username(args['username'])

        if user and user.check_password(args['password']):
            # Tell Flask-Principal the identity changed
            identity_changed.send(current_app._get_current_object(),
                                  identity=Identity(user.id))

            metrics.send('successful_login', 'counter', 1)
            return dict(token=create_token(user))

        metrics.send('invalid_login', 'counter', 1)
        return dict(message='The supplied credentials are invalid'), 401
Ejemplo n.º 46
0
def remove_identity():
    identity_changed.send(current_app._get_current_object(),
                          identity=AnonymousIdentity())
Ejemplo n.º 47
0
    def post(self):
        self.reqparse.add_argument('clientId',
                                   type=str,
                                   required=True,
                                   location='json')
        self.reqparse.add_argument('redirectUri',
                                   type=str,
                                   required=True,
                                   location='json')
        self.reqparse.add_argument('code',
                                   type=str,
                                   required=True,
                                   location='json')

        args = self.reqparse.parse_args()

        # take the information we have received from the provider to create a new request
        params = {
            'client_id': args['clientId'],
            'grant_type': 'authorization_code',
            'scope': 'openid email profile address',
            'redirect_uri': args['redirectUri'],
            'code': args['code']
        }

        # you can either discover these dynamically or simply configure them
        access_token_url = current_app.config.get('PING_ACCESS_TOKEN_URL')
        user_api_url = current_app.config.get('PING_USER_API_URL')

        # the secret and cliendId will be given to you when you signup for the provider
        token = '{0}:{1}'.format(args['clientId'],
                                 current_app.config.get("PING_SECRET"))

        basic = base64.b64encode(bytes(token, 'utf-8'))
        headers = {'authorization': 'basic {0}'.format(basic.decode('utf-8'))}

        # exchange authorization code for access token.

        r = requests.post(access_token_url, headers=headers, params=params)
        id_token = r.json()['id_token']
        access_token = r.json()['access_token']

        # fetch token public key
        header_data = fetch_token_header(id_token)
        jwks_url = current_app.config.get('PING_JWKS_URL')

        # retrieve the key material as specified by the token header
        r = requests.get(jwks_url)
        for key in r.json()['keys']:
            if key['kid'] == header_data['kid']:
                secret = get_rsa_public_key(key['n'], key['e'])
                algo = header_data['alg']
                break
        else:
            return dict(message='Key not found'), 403

        # validate your token based on the key it was signed with
        try:
            jwt.decode(id_token,
                       secret.decode('utf-8'),
                       algorithms=[algo],
                       audience=args['clientId'])
        except jwt.DecodeError:
            return dict(message='Token is invalid'), 403
        except jwt.ExpiredSignatureError:
            return dict(message='Token has expired'), 403
        except jwt.InvalidTokenError:
            return dict(message='Token is invalid'), 403

        user_params = dict(access_token=access_token, schema='profile')

        # retrieve information about the current user.
        r = requests.get(user_api_url, params=user_params)
        profile = r.json()

        user = user_service.get_by_email(profile['email'])
        metrics.send('successful_login', 'counter', 1)

        # update their google 'roles'
        roles = []

        for group in profile['googleGroups']:
            role = role_service.get_by_name(group)
            if not role:
                role = role_service.create(
                    group,
                    description=
                    'This is a google group based role created by Lemur')
            roles.append(role)

        role = role_service.get_by_name(profile['email'])
        if not role:
            role = role_service.create(
                profile['email'], description='This is a user specific role')
        roles.append(role)

        # if we get an sso user create them an account
        if not user:
            # every user is an operator (tied to a default role)
            if current_app.config.get('LEMUR_DEFAULT_ROLE'):
                v = role_service.get_by_name(
                    current_app.config.get('LEMUR_DEFAULT_ROLE'))
                if v:
                    roles.append(v)

            user = user_service.create(profile['email'],
                                       get_psuedo_random_string(),
                                       profile['email'], True,
                                       profile.get('thumbnailPhotoUrl'), roles)

        else:
            # we add 'lemur' specific roles, so they do not get marked as removed
            for ur in user.roles:
                if ur.authority_id:
                    roles.append(ur)

            # update any changes to the user
            user_service.update(
                user.id,
                profile['email'],
                profile['email'],
                True,
                profile.get('thumbnailPhotoUrl'
                            ),  # incase profile isn't google+ enabled
                roles)

        # Tell Flask-Principal the identity changed
        identity_changed.send(current_app._get_current_object(),
                              identity=Identity(user.id))

        return dict(token=create_token(user))
Ejemplo n.º 48
0
def create_stats_fixtures(metadata,
                          n_records,
                          n_versions,
                          n_files,
                          event_data,
                          start_date,
                          end_date,
                          interval,
                          do_process_events=True,
                          do_aggregate_events=True,
                          do_update_record_statistics=True):
    """Generate configurable statistics fixtures.

    :param dict metadata: Base metadata for the created records.
    :param int n_records: Number of records that will be created.
    :param int n_versions: Number of versions for each record.
    :param int n_files: Number of files for each record version.
    :param dict event_data: Base event metadata (e.g. user, user agent, etc).
    :param datetime start_date: Start date for the generated events.
    :param datetime end_date: End date for the generated events.
    :param timedelta interval: Interval between each group of events.
    :param bool do_process_events: ``True`` will run the ``process_events``
        task.
    :param bool do_aggregate_events: ``True`` will run the ``aggregate_events``
        task.
    :param bool do_update_record_statistics: ``True`` will run the
        ``update_record_statistics`` task.
    """
    records = _create_records(metadata,
                              total=n_records,
                              versions=n_versions,
                              files=n_files)

    @contextmanager
    def _patch_stats_publish():
        original_publish = current_stats.publish

        event_batches = defaultdict(list)

        def _patched_publish(self, event_type, events):
            events[0].update(event_data)
            event_batches[event_type].append(events[0])

        current_stats.publish = MethodType(_patched_publish, current_stats)
        yield
        current_stats.publish = original_publish
        for event_type, events in event_batches.items():
            current_stats.publish(event_type, events)

    with _patch_stats_publish():
        for ts in _gen_date_range(start_date, end_date, interval):
            event_data['timestamp'] = ts.isoformat()
            for recid, record, file_objects in records:
                with current_app.test_request_context():
                    record_viewed.send(current_app._get_current_object(),
                                       pid=recid,
                                       record=record)
                    for obj in file_objects:
                        file_downloaded.send(current_app._get_current_object(),
                                             obj=obj,
                                             record=record)
    if do_process_events:
        process_events(['record-view', 'file-download'])
        current_search.flush_and_refresh(index='events-stats-*')

    if do_aggregate_events:
        with patch('invenio_stats.aggregations.datetime',
                   mock_date(*end_date.timetuple()[:3])):
            aggregate_events([
                'record-view-agg', 'record-view-all-versions-agg',
                'record-download-agg', 'record-download-all-versions-agg'
            ])
            current_search.flush_and_refresh(index='stats-*')

    if do_update_record_statistics:
        update_record_statistics(start_date=start_date.isoformat(),
                                 end_date=end_date.isoformat())
        RecordIndexer().process_bulk_queue()
        current_search.flush_and_refresh(index='records')

    return records
Ejemplo n.º 49
0
def send_mail(subject,to,tem,**kwargs):
    app = current_app._get_current_object()
    msg = Message(subject=subject, recipients=[to], sender=app.config['MAIL_USERNAME'])
    msg.html = render_template('email/'+tem+'.html',**kwargs)
    send = Thread(target=async_send_mail,args=(app,msg))
    send.start()
Ejemplo n.º 50
0
 def update_topic(self, topic, **kwargs):
     self.update(topic, **kwargs)
     topic_update_signal.send(current_app._get_current_object(),
                              topic=topic)
Ejemplo n.º 51
0
def logged_in_admin(session, app):
    with app.test_request_context():
        identity_changed.send(current_app._get_current_object(),
                              identity=Identity(2))
        yield
Ejemplo n.º 52
0
def web_async_signal_demo():
    """异步信息示例"""
    event_async_with_app_demo.send(current_app._get_current_object(),
                                   mydata='view.data')
    return render_template('base-msg.html', e={'content': '页面已返回, 5秒后查看控制台日志'})
Ejemplo n.º 53
0
def register():
    """ Display registration form and create new User."""

    user_manager = current_app.user_manager
    db_adapter = user_manager.db_adapter

    safe_next = _get_safe_next_param('next', user_manager.after_login_endpoint)
    safe_reg_next = _get_safe_next_param('reg_next',
                                         user_manager.after_register_endpoint)

    # Initialize form
    login_form = user_manager.login_form()  # for login_or_register.html
    register_form = user_manager.register_form(
        request.form)  # for register.html

    # invite token used to determine validity of registeree
    invite_token = request.values.get("token")

    # require invite without a token should disallow the user from registering
    if user_manager.require_invitation and not invite_token:
        flash("Registration is invite only", "error")
        return redirect(url_for('user.login'))

    user_invite = None
    if invite_token and db_adapter.UserInvitationClass:
        user_invite = db_adapter.find_first_object(
            db_adapter.UserInvitationClass, token=invite_token)
        if user_invite:
            register_form.invite_token.data = invite_token
        else:
            flash("Invalid invitation token", "error")
            return redirect(url_for('user.login'))

    if request.method != 'POST':
        login_form.next.data = register_form.next.data = safe_next
        login_form.reg_next.data = register_form.reg_next.data = safe_reg_next
        if user_invite:
            register_form.email.data = user_invite.email

    # Process valid POST
    if request.method == 'POST' and register_form.validate():
        # Create a User object using Form fields that have a corresponding User field
        User = db_adapter.UserClass
        user_class_fields = User.__dict__
        user_fields = {}

        # Create a UserEmail object using Form fields that have a corresponding UserEmail field
        if db_adapter.UserEmailClass:
            UserEmail = db_adapter.UserEmailClass
            user_email_class_fields = UserEmail.__dict__
            user_email_fields = {}

        # Create a UserAuth object using Form fields that have a corresponding UserAuth field
        if db_adapter.UserAuthClass:
            UserAuth = db_adapter.UserAuthClass
            user_auth_class_fields = UserAuth.__dict__
            user_auth_fields = {}

        # Enable user account
        if db_adapter.UserProfileClass:
            if hasattr(db_adapter.UserProfileClass, 'active'):
                user_auth_fields['active'] = True
            elif hasattr(db_adapter.UserProfileClass, 'is_enabled'):
                user_auth_fields['is_enabled'] = True
            else:
                user_auth_fields['is_active'] = True
        else:
            if hasattr(db_adapter.UserClass, 'active'):
                user_fields['active'] = True
            elif hasattr(db_adapter.UserClass, 'is_enabled'):
                user_fields['is_enabled'] = True
            else:
                user_fields['is_active'] = True

        # For all form fields
        for field_name, field_value in register_form.data.items():
            # Hash password field
            if field_name == 'password':
                hashed_password = user_manager.hash_password(field_value)
                if db_adapter.UserAuthClass:
                    user_auth_fields['password'] = hashed_password
                else:
                    user_fields['password'] = hashed_password
            # Store corresponding Form fields into the User object and/or UserProfile object
            else:
                if field_name in user_class_fields:
                    user_fields[field_name] = field_value
                if db_adapter.UserEmailClass:
                    if field_name in user_email_class_fields:
                        user_email_fields[field_name] = field_value
                if db_adapter.UserAuthClass:
                    if field_name in user_auth_class_fields:
                        user_auth_fields[field_name] = field_value

        # Add User record using named arguments 'user_fields'
        user = db_adapter.add_object(User, **user_fields)
        if db_adapter.UserProfileClass:
            user_profile = user

        # Add UserEmail record using named arguments 'user_email_fields'
        if db_adapter.UserEmailClass:
            user_email = db_adapter.add_object(UserEmail,
                                               user=user,
                                               is_primary=True,
                                               **user_email_fields)
        else:
            user_email = None

        # Add UserAuth record using named arguments 'user_auth_fields'
        if db_adapter.UserAuthClass:
            user_auth = db_adapter.add_object(UserAuth, **user_auth_fields)
            if db_adapter.UserProfileClass:
                user = user_auth
            else:
                user.user_auth = user_auth

        require_email_confirmation = True
        if user_invite:
            if user_invite.email == register_form.email.data:
                require_email_confirmation = False
                db_adapter.update_object(user, confirmed_at=datetime.utcnow())

        db_adapter.commit()

        # Send 'registered' email and delete new User object if send fails
        if user_manager.send_registered_email:
            try:
                # Send 'registered' email
                _send_registered_email(user, user_email,
                                       require_email_confirmation)
            except Exception as e:
                # delete new User object if send  fails
                db_adapter.delete_object(user)
                db_adapter.commit()
                raise

        # Send user_registered signal
        signals.user_registered.send(current_app._get_current_object(),
                                     user=user,
                                     user_invite=user_invite)

        # Redirect if USER_ENABLE_CONFIRM_EMAIL is set
        if user_manager.enable_confirm_email and require_email_confirmation:
            safe_reg_next = user_manager.make_safe_url_function(
                register_form.reg_next.data)
            return redirect(safe_reg_next)

        # Auto-login after register or redirect to login page
        if 'reg_next' in request.args:
            safe_reg_next = user_manager.make_safe_url_function(
                register_form.reg_next.data)
        else:
            safe_reg_next = _endpoint_url(user_manager.after_confirm_endpoint)
        if user_manager.auto_login_after_register:
            return _do_login_user(user, safe_reg_next)  # auto-login
        else:
            return redirect(
                url_for('user.login') + '?next=' +
                quote(safe_reg_next))  # redirect to login page

    # Process GET or invalid POST
    return render(user_manager.register_template,
                  form=register_form,
                  login_form=login_form,
                  register_form=register_form)
Ejemplo n.º 54
0
    def handle_error(self, e):
        """Error handler for the API transforms a raised exception into a Flask
        response, with the appropriate HTTP status code and body.

        :param e: the raised Exception object
        :type e: Exception

        """
        got_request_exception.send(current_app._get_current_object(),
                                   exception=e)

        if not isinstance(e,
                          HTTPException) and current_app.propagate_exceptions:
            exc_type, exc_value, tb = sys.exc_info()
            if exc_value is e:
                raise
            else:
                raise e

        headers = Headers()
        if isinstance(e, HTTPException):
            code = e.code
            default_data = {
                'message': getattr(e, 'description', http_status_message(code))
            }
            headers = e.get_response().headers
        else:
            code = 500
            default_data = {
                'message': http_status_message(code),
            }

        # Werkzeug exceptions generate a content-length header which is added
        # to the response in addition to the actual content-length header
        # https://github.com/flask-restful/flask-restful/issues/534
        remove_headers = ('Content-Length', )

        for header in remove_headers:
            headers.pop(header, None)

        data = getattr(e, 'data', default_data)

        if code and code >= 500:
            exc_info = sys.exc_info()
            if exc_info[1] is None:
                exc_info = None
            current_app.log_exception(exc_info)

        help_on_404 = current_app.config.get("ERROR_404_HELP", True)
        if code == 404 and help_on_404:
            rules = dict([(re.sub('(<.*>)', '', rule.rule), rule.rule)
                          for rule in current_app.url_map.iter_rules()])
            close_matches = difflib.get_close_matches(request.path,
                                                      rules.keys())
            if close_matches:
                # If we already have a message, add punctuation and continue it.
                if "message" in data:
                    data["message"] = data["message"].rstrip('.') + '. '
                else:
                    data["message"] = ""

                data['message'] += 'You have requested this URI [' + request.path + \
                                   '] but did you mean ' + \
                                   ' or '.join((
                                       rules[match] for match in close_matches)
                                   ) + ' ?'

        error_cls_name = type(e).__name__
        if error_cls_name in self.errors:
            custom_data = self.errors.get(error_cls_name, {})
            code = custom_data.get('status', 500)
            data.update(custom_data)

        if code == 406 and self.default_mediatype is None:
            # if we are handling NotAcceptable (406), make sure that
            # make_response uses a representation we support as the
            # default mediatype (so that make_response doesn't throw
            # another NotAcceptable error).
            supported_mediatypes = list(self.representations.keys())
            fallback_mediatype = supported_mediatypes[
                0] if supported_mediatypes else "text/plain"
            resp = self.make_response(data,
                                      code,
                                      headers,
                                      fallback_mediatype=fallback_mediatype)
        else:
            resp = self.make_response(data, code, headers)

        if code == 401:
            resp = self.unauthorized(resp)
        return resp
Ejemplo n.º 55
0
def set_identity(uid):
    identity_changed.send(current_app._get_current_object(),
                          identity=Identity(uid))
Ejemplo n.º 56
0
def logout():
    logout_user()
    identity_changed.send(current_app._get_current_object(),
                          identity=AnonymousIdentity())
    flash('注销成功', category='success')
    return redirect(url_for('.index'))
Ejemplo n.º 57
0
def openid():

    oidc_configuration, jwt_key_set = get_oidc_configuration(current_app)
    token_endpoint = oidc_configuration['token_endpoint']
    userinfo_endpoint = oidc_configuration['userinfo_endpoint']

    data = {
        'grant_type': 'authorization_code',
        'code': request.json['code'],
        'redirect_uri': request.json['redirectUri'],
        'client_id': request.json['clientId'],
        'client_secret': current_app.config['OAUTH2_CLIENT_SECRET'],
    }
    r = requests.post(token_endpoint, data)
    token = r.json()

    if 'error' in token:
        error_text = token.get('error_description') or token['error']
        raise ApiError(error_text)

    try:
        jwt_header = jwt.get_unverified_header(token['id_token'])
        if current_app.config['OIDC_VERIFY_TOKEN']:
            public_key = jwt_key_set[jwt_header['kid']]

            id_token = jwt.decode(
                token['id_token'],
                key=public_key,
                algorithms=jwt_header['alg']
            )
        else:
            id_token = jwt.decode(
                token['id_token'],
                algorithms=jwt_header['alg'],
                options={'verify_signature': False}
            )
    except Exception:
        current_app.logger.warning('No ID token in OpenID Connect token response.')
        id_token = {}

    try:
        headers = {'Authorization': '{} {}'.format(token.get('token_type', 'Bearer'), token['access_token'])}
        r = requests.get(userinfo_endpoint, headers=headers)
        userinfo = r.json()
    except Exception:
        raise ApiError('No access token in OpenID Connect token response.')

    subject = userinfo['sub']
    name = userinfo.get('name') or id_token.get('name')
    username = userinfo.get('preferred_username') or id_token.get('preferred_username')
    nickname = userinfo.get('nickname') or id_token.get('nickname')
    email = userinfo.get('email') or id_token.get('email')
    email_verified = userinfo.get('email_verified', id_token.get('email_verified', bool(email)))
    email_verified = True if email_verified == 'true' else email_verified  # Cognito returns string boolean
    picture = userinfo.get('picture') or id_token.get('picture')

    role_claim = current_app.config['OIDC_ROLE_CLAIM']
    group_claim = current_app.config['OIDC_GROUP_CLAIM']
    custom_claims = {
        role_claim: userinfo.get(role_claim) or id_token.get(role_claim, []),
        group_claim: userinfo.get(group_claim) or id_token.get(group_claim, []),
    }

    login = username or nickname or email
    if not login:
        raise ApiError("Must support one of the following OpenID claims: 'preferred_username', 'nickname' or 'email'", 400)

    if current_app.config['OIDC_LINK_USER_EMAIL'] and email and email_verified:
        user = User.find_by_email(email=email)
    else:
        user = User.find_by_id(id=subject)

    if not user:
        user = User(id=subject, name=name, login=login, password='', email=email,
                    roles=current_app.config['USER_ROLES'], text='', email_verified=email_verified)
        user.create()
    else:
        user.update(login=login, email=email, email_verified=email_verified)

    roles = custom_claims[role_claim] + user.roles
    groups = custom_claims[group_claim]

    if user.id != subject:
        custom_claims['oid'] = user.id  # if subject differs store the original subject as "oid" claim

    if user.status != 'active':
        raise ApiError('User {} is not active'.format(login), 403)

    if not_authorized('ALLOWED_OIDC_ROLES', roles) or not_authorized('ALLOWED_EMAIL_DOMAINS', groups=[user.domain]):
        raise ApiError('User {} is not authorized'.format(login), 403)
    user.update_last_login()

    scopes = Permission.lookup(login, roles=roles)
    customers = get_customers(login, groups=[user.domain] + groups)

    auth_audit_trail.send(current_app._get_current_object(), event='openid-login', message='user login via OpenID Connect',
                          user=login, customers=customers, scopes=scopes, **custom_claims,
                          resource_id=subject, type='user', request=request)

    token = create_token(user_id=subject, name=name, login=login, provider=current_app.config['AUTH_PROVIDER'],
                         customers=customers, scopes=scopes, **custom_claims,
                         email=email, email_verified=email_verified, picture=picture)
    return jsonify(token=token.tokenize)
Ejemplo n.º 58
0
def github():

    if current_app.config['GITHUB_URL'] == 'https://github.com':
        access_token_url = 'https://github.com/login/oauth/access_token'
        github_api_url = 'https://api.github.com'
    else:
        access_token_url = current_app.config['GITHUB_URL'] + '/login/oauth/access_token'
        github_api_url = current_app.config['GITHUB_URL'] + '/api/v3'

    client_lookup = dict(zip(
        current_app.config['OAUTH2_CLIENT_ID'].split(','),
        current_app.config['OAUTH2_CLIENT_SECRET'].split(',')
    ))
    client_secret = client_lookup.get(request.json['clientId'], None)
    data = {
        'grant_type': 'authorization_code',
        'code': request.json['code'],
        'redirect_uri': request.json['redirectUri'],
        'client_id': request.json['clientId'],
        'client_secret': client_secret,
    }
    r = requests.post(access_token_url, data, headers={'Accept': 'application/json'})
    token = r.json()

    headers = {'Authorization': 'token {}'.format(token['access_token'])}
    r = requests.get(github_api_url + '/user', headers=headers)
    profile = r.json()

    r = requests.get(github_api_url + '/user/orgs', headers=headers)  # list public and private Github orgs
    organizations = [o['login'] for o in r.json()]

    subject = str(profile['id'])
    name = profile['name']
    username = '******' + profile['login']
    email = profile['email']
    email_verified = True if email else False
    picture = profile['avatar_url']

    login = username or email
    if not login:
        raise ApiError("Must allow access to GitHub user profile information: 'login' or 'email'", 400)

    user = User.find_by_id(id=subject)
    if not user:
        user = User(id=subject, name=name, login=login, password='', email=email,
                    roles=current_app.config['USER_ROLES'], text='', email_verified=email_verified)
        user.create()
    else:
        user.update(login=login, email=email)

    if user.status != 'active':
        raise ApiError('User {} is not active'.format(login), 403)

    if not_authorized('ALLOWED_GITHUB_ORGS', organizations):
        raise ApiError('User {} is not authorized'.format(login), 403)
    user.update_last_login()

    scopes = Permission.lookup(login, roles=user.roles + organizations)
    customers = get_customers(login, groups=[user.domain] + organizations)

    auth_audit_trail.send(current_app._get_current_object(), event='github-login', message='user login via GitHub',
                          user=login, customers=customers, scopes=scopes, roles=user.roles, orgs=organizations,
                          resource_id=subject, type='user', request=request)

    token = create_token(user_id=subject, name=name, login=login, provider='github',
                         customers=customers, scopes=scopes, roles=user.roles, orgs=organizations,
                         email=email, email_verified=email_verified, picture=picture)
    return jsonify(token=token.tokenize)
Ejemplo n.º 59
0
def pitScouting(request):
    app = current_app._get_current_object()

    database = current_app._get_current_object().database
    if request.method == "GET":
        return flask.render_template('pitScouting.html')
    if request.method == "POST":
        fields = [k for k in request.form]
        values = [request.form[k] for k in request.form]
        data = dict(zip(fields, values))
        filename = ""
        if 'robotPicUpload' in request.files:
            file = request.files['robotPicUpload']
            # if user does not select file, browser also
            # submit a empty part without filename
            if file.filename and app.allowed_file(file.filename):
                with open("scouting/incrementUploads.txt",
                          "r") as incrementFile:

                    currentValue = incrementFile.read()
                    print("CURRENT VALUE IS " + currentValue + '.' +
                          file.filename.split('.')[-1])
                    filename = currentValue + '.' + file.filename.split(
                        '.')[-1]

                with open("scouting/incrementUploads.txt",
                          "w") as incrementFile:
                    incrementFile.write(str(int(currentValue) + 1))
                file.save(app.root_path + "/" + app.config['UPLOAD_FOLDER'] +
                          "/" + filename)

        badata = {
            'hatchLevelD': None,
            'hatchLevelC': None,
            'comments': None,
            'scoutname': None,
            'cargoLevelG': None,
            'robotPic64': None,
            'cycleTime': None,
            'hatchLevel3': None,
            'hatchLevel1': None,
            'hatchLevel2': None,
            'climbLevel': None,
            'cargoLevelC': None,
            'driveTrain': None,
            'hatchLevelG': None,
            'cargoComments': None,
            'cargoLevel2': None,
            'teamNumber': None,
            'hatchComments': None,
            'buddyClimb': None,
            'cargoLevel3': None,
            'cargoLevel1': None,
            'cargoLevelD': None,
            'robotPicURL': None,
            'ProgramLang': None,
            'weight': None,
            'scoutname': None
        }
        badata.update(data)
        cargoIntake = ('D' if badata['cargoLevelD'] == 'on' else '') + \
            ('G' if badata['cargoLevelG'] == 'on' else '')
        hatchIntake = ('D' if badata['hatchLevelD'] == 'on' else '') + \
            ('G' if badata['hatchLevelG'] == 'on' else '')
        cargoOutake = ('C' if badata['cargoLevelC'] == 'on' else
                       '') + ('1' if badata['cargoLevel1'] == 'on' else '') + (
                           '2' if badata['cargoLevel2'] == 'on' else
                           '') + ('3' if badata['cargoLevel3'] == 'on' else '')
        hatchOutake = ('C' if badata['hatchLevelC'] == 'on' else
                       '') + ('1' if badata['hatchLevel1'] == 'on' else '') + (
                           '2' if badata['hatchLevel2'] == 'on' else
                           '') + ('3' if badata['hatchLevel3'] == 'on' else '')

        newdata = {
            'TeamNumber': badata['teamNumber'],
            'HatchLevels': hatchOutake,
            'CargoLevels': cargoOutake,
            'HatchIntake': hatchIntake,
            'CargoComments': badata['cargoComments'],
            'CargoIntake': cargoIntake,
            'HatchComments': badata['hatchComments'],
            'DriveTrain': badata['driveTrain'],
            'ClimbLevels': badata['climbLevel'],
            'CycleTime': badata['cycleTime'],
            'Weight': badata['weight'],
            'ProgrammingLanguage': badata['ProgramLang'],
            'Comments': badata['comments'],
            "Picture": filename,
            "ScouterName": badata['scoutname'],
            'BuddyClimb': badata['buddyClimb']
        }
        newdata.update({'type': 'pit'})
        rq.post(
            "https://script.google.com/macros/s/AKfycbzJb8ch1pg5vSCx8dAoTHEQwwn5SjfcGsWa7GpP4mb4-C20tq0G/exec?key=1XfIrmB9tNzBckh3W689WZToBLRnU2kwWatePk_pawoc",
            params=newdata,
            data=newdata)

        print(badata)
        return render_template(
            'fullScreenBill.html',
            url=rq.get('https://yesno.wtf/api/').text.split('"')[-2])
Ejemplo n.º 60
0
def send_mail(subject, to, html):
    app = current_app._get_current_object()
    message = Message(subject, recipients=[to], html=html)
    thr = Thread(target=_send_async_mail, args=[app, message])
    thr.start()
    return thr