Пример #1
0
def process_vc_room_association(plugin, event, vc_room, form, event_vc_room=None, allow_same_room=False):
    # disable autoflush, so that the new event_vc_room does not influence the result
    with db.session.no_autoflush:
        if event_vc_room is None:
            event_vc_room = VCRoomEventAssociation()

        plugin.update_data_association(event, vc_room, event_vc_room, form.data)

        existing = set()
        if event_vc_room.link_object is not None:
            # check whether there is a room-event association already present
            # for the given event, room and plugin
            q = VCRoomEventAssociation.find(
                VCRoomEventAssociation.event_new == event,
                VCRoomEventAssociation.link_object == event_vc_room.link_object,
                _join=VCRoom
            )
            if allow_same_room:
                q = q.filter(VCRoom.id != vc_room.id)
            existing = {x.vc_room for x in q}

    if event_vc_room.link_type != VCRoomLinkType.event and existing:
        transaction.abort()
        flash(_("There is already a VC room attached to '{link_object_title}'.").format(
            link_object_title=resolve_title(event_vc_room.link_object)), 'error')
        return None
    elif event_vc_room.link_type == VCRoomLinkType.event and vc_room in existing:
        transaction.abort()
        flash(_("This {plugin_name} room is already attached to the event.").format(plugin_name=plugin.friendly_name),
              'error')
        return None
    else:
        return event_vc_room
Пример #2
0
 def deco(*args, **kwds):
     if not "user" in flask.session:
         flask.flash("Login required!", "error")
         return flask.redirect(flask.url_for("login.login") + "?next=" + flask.request.url)
     else:
         # TODO: Check that user has permission, else redirect
         return f(*args, **kwds)
Пример #3
0
def process_legal_flag(contact_info, copr):
    form = forms.CoprLegalFlagForm()
    legal_flag = models.LegalFlag(raise_message=form.comment.data,
                                  raised_on=int(time.time()),
                                  copr=copr,
                                  reporter=flask.g.user)
    db.session.add(legal_flag)
    db.session.commit()
    send_to = app.config["SEND_LEGAL_TO"] or ["root@localhost"]
    hostname = platform.node()
    navigate_to = "\nNavigate to http://{0}{1}".format(
        hostname, flask.url_for("admin_ns.legal_flag"))
    contact = "\nContact on owner is: {}".format(contact_info)
    reported_by = "\nReported by {0} <{1}>".format(flask.g.user.name,
                                                   flask.g.user.mail)
    try:
        msg = MIMEText(
            form.comment.data + navigate_to + contact + reported_by, "plain")
    except UnicodeEncodeError:
        msg = MIMEText(form.comment.data.encode(
            "utf-8") + navigate_to + contact + reported_by, "plain", "utf-8")
    msg["Subject"] = "Legal flag raised on {0}".format(copr.name)
    msg["From"] = "root@{0}".format(hostname)
    msg["To"] = ", ".join(send_to)
    s = smtplib.SMTP("localhost")
    s.sendmail("root@{0}".format(hostname), send_to, msg.as_string())
    s.quit()
    flask.flash("Admin has been noticed about your report"
                " and will investigate the project shortly.")
    return flask.redirect(url_for_copr_details(copr))
Пример #4
0
def view(orthanc_id):
    """ view details of orthanc study """
    study = Study.query.filter(Study.orthanc_id==orthanc_id).first()
    if study is None:
        flash('Study ID not found', category='danger')
        redirect(url_for('studies.list'))
    return render_template('studies.view.html',study=study)
Пример #5
0
def checkEpisode(id):
    episode = Episode.query.get_or_404(id)

    if request.method == 'GET':
        return redirect(url_for('showEpisode', id=episode.id))

    url = request.referrer

    if not validate_token():
        return redirect(url_for('checkEpisode', id=episode.id))

    add = request.form.get('add', None)
    if add:
        if episode not in current_user.watched_episodes:
            current_user.watched_episodes.append(episode)
            flash('Added to watched!', 'success')
    else:
        if episode in current_user.watched_episodes:
            current_user.watched_episodes.remove(episode)
            flash('Removed from watched!', 'success')

    fav = UserSerie.query.\
        filter_by(user=current_user, \
        serie=episode.serie).first()
    if fav is not None:
        fav.last_watched = datetime.now()
        db.session.add(fav)

    db.session.commit()

    if url is not None:
        return redirect(url)

    return redirect(url_for('showEpisode', id=episode.id))
Пример #6
0
 def _process(self):
     user, identity = register_user(self.request.email, self.request.extra_emails, self.request.user_data,
                                    self.request.identity_data, self.request.settings)
     tpl = get_template_module('users/emails/registration_request_accepted.txt', user=user)
     send_email(make_email(self.request.email, template=tpl))
     flash(_('The request has been approved.'), 'success')
     return jsonify_data()
Пример #7
0
def upload():
    if request.method == 'POST' and 'somefile' in request.files:
        file = request.files['somefile']
        if file and allowed_file(file.filename):
            filename = os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(file.filename))
            file.save(filename)
            filename
            print 'Filename Upload:' , filename
            adnet  =  request.form['adnet']
            method =  request.form['method']
            adnet = adnet.strip(' ')
            method = method.strip(' ')


            pipe = subprocess.Popen("python ../start.py  "  + filename + "  --extract=decompile  --mode=" + method + " --netad=" + adnet, stdout=subprocess.PIPE, stderr=None, shell=True)
            result = pipe.stdout.read()

            final = string.split(result, '\n')  # --> ['Line 1', 'Line 2', 'Line 3']

            d_filename = 'sign.patched.' + filename[10:]
            flash('Signed Apk started to download.Look your browser download folder')
            return send_from_directory(app.config['UPLOAD_FOLDER'],d_filename, as_attachment=True)
        else: flash ('Wrong FileType') 

    return render_template('upload.html')
Пример #8
0
def checkSeries(id):
    series = Serie.query.get_or_404(id)

    if request.method == 'GET':
        return redirect(url_for('showSeries', id=series.id))

    url = request.referrer

    if not validate_token():
        return redirect(url_for('checkSeries', id=series.id))

    add = request.form.get('add', None)
    if add:
        if series not in current_user.favorite_series:
            current_user.favorite_series.append(series)
            flash('Added to watchlist!', 'success')
    else:
        current_user.favorite_series.remove(series)
        flash('Removed from watchlist!', 'success')
    db.session.commit()

    if url is not None:
        return redirect(url)

    return redirect(url_for('showSeries', id=series.id))
Пример #9
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)
Пример #10
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)
Пример #11
0
def delete_entry(task_id):
	g.db = connect_db()
	g.db.execute('delete from tasks where task_id='+ str(task_id))
	g.db.commit()
	g.db.close()
	flash('The task was deleted.')
	return redirect(url_for('tasks'))
Пример #12
0
def recover():
    """recover"""
    if request.method == 'GET':
        return render_template('recover_password.html')
    username = request.form['username']
    registered_user = User.query.filter_by(username=username,).first()
    if registered_user is None:
        flash(gettext('Invalid username'), 'danger')
        return redirect(url_for('recover', lang=g.current_lang))

    fromaddr = '%s <%s>' % (APP.config['GHC_SITE_TITLE'],
                            APP.config['GHC_ADMIN_EMAIL'])
    toaddr = registered_user.email

    template_vars = {
        'config': APP.config,
        'password': registered_user.password
    }
    msg = render_template2('recover_password_email.txt', template_vars)

    send_email(APP.config['GHC_SMTP'], fromaddr, toaddr, msg)

    flash(gettext('Password sent via email'), 'success')

    if 'next' in request.args:
        return redirect(request.args.get('next'))
    return redirect(url_for('home', lang=g.current_lang))
Пример #13
0
def login():
  form = LoginForm()
  if form.validate_on_submit():
    login_user(form.user)
    flash("Logged in successfully, bro.")
    return redirect(request.args.get("next") or url_for("instances.index"))
  return render_template('users/login.html', form=form)
Пример #14
0
def client_sensor_edit(client_id, sensor_id):
    with app.db.session_scope():
        sensor = app.db.get_sensor(sensor_id)
        MyForm = model_form(Sensor, \
                        base_class=Form, \
                        db_session=app.db.get_session(),
                        exclude=['core_device', 'name', 'reference', 'incremental', 'formula', 'data_type', 'conversion', 'last_value', 'last_received', 'history_duplicate','value_min','value_max'])
        #MyForm.history_duplicate.kwargs['validators'] = []
        MyForm.history_store.kwargs['validators'] = []
        form = MyForm(request.form, sensor)

        if request.method == 'POST' and form.validate():
            if request.form['history_store'] == 'y':
                store = 1 
            else:
                store = 0
            app.db.update_sensor(sensor_id, \
                     history_round=request.form['history_round'], \
                     history_store=store, \
                     history_max=request.form['history_max'], \
                     history_expire=request.form['history_expire'],
                     timeout=request.form['timeout'])

            flash(gettext("Changes saved"), "success")
            return redirect("/client/{0}/dmg_devices/known".format(client_id))
            pass
        else:
                return render_template('client_sensor.html',
                form = form,
                clientid = client_id,
                mactive="clients",
                active = 'devices'
                )
Пример #15
0
def client_devices_edit(client_id, did):
    with app.db.session_scope():
        device = app.db.get_device_sql(did)
        MyForm = model_form(Device, \
                        base_class=Form, \
                        db_session=app.db.get_session(),
                        exclude=['params', 'commands', 'sensors', 'address', 'xpl_commands', 'xpl_stats', 'device_type_id', 'client_id', 'client_version'])
        form = MyForm(request.form, device)

        if request.method == 'POST' and form.validate():
            # save it
            app.db.update_device(did, \
                    d_name=request.form['name'], \
                    d_description=request.form['description'], \
                    d_reference=request.form['reference'])
            # message the suer
            flash(gettext("Device saved"), 'success')
            # reload stats
            req = MQSyncReq(app.zmq_context)
            msg = MQMessage()
            msg.set_action( 'reload' )
            resp = req.request('xplgw', msg.get(), 100)
            # redirect
            return redirect("/client/{0}/dmg_devices/known".format(client_id))
        else:
            return render_template('client_device_edit.html',
                form = form,
                clientid = client_id,
                mactive="clients",
                active = 'devices'
                )
Пример #16
0
def login():
    if current_user.is_authenticated:
        flash('You\'re already logged in.')
        return redirect(url_for('index'))
    else:
        return render_template('login.html',
                           title='Validate Credentials')
Пример #17
0
def event_withdraw(profile, event):
    user_id = g.user.id
    participant = Participant.query.filter_by(event_id=event.id, user_id=user_id).first()
    if participant:
        workflow = participant.workflow()
        if not workflow.can_withdraw():
            abort(403)
        withdraw_call = {
                         0: workflow.withdraw_pending,
                         1: workflow.withdraw_waiting_list,
                         2: workflow.withdraw_confirmed,
                         3: workflow.withdraw_rejected,
                         }

        form = ConfirmWithdrawForm()
        if form.validate_on_submit():
            if 'delete' in request.form:
                try:
                    withdraw_call[participant.status]()

                except KeyError:
                    pass

                db.session.commit()
                flash(u"Your request to withdraw from {0} is recorded".format(event.title), "success")
            values = {'profile': profile.name, 'event': event.name}
            return render_redirect(event.url_for(), code=303)
        return render_template('withdraw.html', form=form, title=u"Confirm withdraw",
            message=u"Withdraw from '%s' ? You can come back anytime." % (event.title))
    else:
        abort(404)
Пример #18
0
def tuchuang_index():
    github_user = _get_user()

    if not github_user:
        flash(u'请正确完成牛逼参数设置后上传图片!', category='warning')
        return redirect(url_for('.info'))

    if request.method == 'POST':
        access_key = str(github_user.get('access_key'))
        secret_key = str(github_user.get('secret_key'))
        bucket_name = str(github_user.get('bucket_name'))
        domain_name = str(github_user.get('domain_name'))
        q = Auth(access_key, secret_key)
        token = q.upload_token(bucket_name)

        upload_files = request.files.getlist('file')
        for upload_file in upload_files:
            key = '%s_%s' % (datetime.now().isoformat(), upload_file.filename)
            ret, info = put_data(up_token=token, key=key, data=upload_file)
            url = '%s/%s' % (domain_name, key)
            f = File()
            f.set('url', url)
            f.set('user', github_user)
            f.save()
        flash(u'成功上传%s张照片!' % len(upload_files), category='success')
        return redirect(url_for('.tuchuang_index'))

    image_id = request.args.get('image_id')
    image = Query(File).get(image_id) if image_id else None

    return render_template('tuchuang.html', image=image)
Пример #19
0
def delete_post(username, post_id, reply_id=None):
    """Deletes posts.

    """
    # The default redirect is different for a post/reply deletion
    # Reply deletion keeps you on the page and post deletion takes you to feed
    if reply_id is not None:
        redirect_url = handle_next(request, url_for('posts.view_post',
                                   username=username, post_id=post_id))
    else:
        redirect_url = handle_next(request, url_for('users.feed'))

    user_id = get_uid(username)
    if not check_post(user_id, post_id, reply_id):
        return abort(404)

    if reply_id is not None:
        _post = get_post(reply_id)

        if _post['user_id'] != current_user['_id'] and \
                user_id != current_user['_id']:
            return abort(403)
    else:
        if user_id != current_user['_id']:
            return abort(403)

    if reply_id is not None:
        be_delete_post(reply_id)
        flash('Post has been deleted', 'success')
    else:
        be_delete_post(post_id)
        flash('Post has been deleted along with all replies', 'success')

    return redirect(redirect_url)
Пример #20
0
def outage_create():
    checked = False
    if request.form.get('checked') is not None:
        checked = True

    flagged = False 
    if request.form.get('flagged') is not None:
        flagged = True

    start_datetime = None
    if request.form.get('start_datetime') is not None:
        try:
            start_datetime = datetime.datetime.strptime(request.form.get('start_datetime'),
                '%Y-%m-%d %H:%M:%S')
        except Exception as e:
            flash('Start Date/Time formatted incorrectly')
            return redirect(url_for('outage_new'))

    end_datetime = None
    if (request.form.get('end_datetime') is not None) and ('None' not in request.form.get('end_datetime')):
        try:
            end_datetime = datetime.datetime.strptime(request.form.get('end_datetime'),
                '%Y-%m-%d %H:%M:%S')
        except Exception as e:
            flash('End Date/Time formatted incorrectly')
            return redirect(url_for('outage_new'))

    return redirect(url_for('outage_detail', outage_id=outage_id))
Пример #21
0
    def create_model(self, form):
        """
            Create model from form.

            :param form:
                Form instance
        """
        try:
            model = self.model()
            form.populate_obj(model)
            self.session.add(model)
            self._on_model_change(form, model, True)
            self.session.commit()
        except Exception as ex:
            if not self.handle_view_exception(ex):
                flash(gettext('Failed to create record. %(error)s', error=str(ex)), 'error')
                log.exception('Failed to create record.')

            self.session.rollback()

            return False
        else:
            self.after_model_change(form, model, True)

        return model
Пример #22
0
def commitblog():
    if 'logged_in' in session:
        title = request.form['title'].strip()
        blogpost = request.form['blogpost'].strip()

        if 'Preview Blog' in request.form.values():
            return redirect(url_for('add_blog',preview=1,title=title,blogpost=blogpost,recover=1))

        error = 0
        if title == "":
            error = 1
            flash("You must make a title","error")
        if blogpost == "":
            error = 1
            flash("You must make the blogpost","error")

        if error:
            return redirect(url_for('add_blog',title=title,blogpost=blogpost,recover=1))
        time_var = unixtime()
        g.db.execute("""
INSERT INTO post (title, text, removed,unixtime,views) VALUES (?,?,0,?,0)
""",(title,blogpost,time_var))
        g.db.commit()
        blogid = query_db("""SELECT id FROM post WHERE unixtime=?""",[time_var],True)['id']
    else:
        return abort(403)
    return redirect(url_for('blogpost',blogid=blogid))
Пример #23
0
def m_events_update():
    id = _g("id")
    if not id :
        flash("No id supplied !", MESSAGE_ERROR)
        return redirect(url_for("m_events_list"))
    action_type = _g("action_type")
    if not action_type in ["m", "c", "p"]:
        flash("No such action !", MESSAGE_ERROR)
        return redirect(url_for("m_events_list"))

    e = DBSession.query(Events).get(id)
#    e = connection.Events.one({"id" : int(id)})

    if action_type == "m":
        return render_template("m_events_update.html", event = e)
    elif action_type == "c": #cancel       
        e.status = 2
        DBSession.add(Message(subject = u"Cancel Booking Event", user_id = e.user_id,
                              content = u"%s cancel the booking request." % session['user_profile']['name']))
        DBSession.commit()
        return jsonify({"success" : True, "message" : "Update successfully !"})
    elif action_type == "p": #confirmed
        e.status = 1
        DBSession.add(Message(subject = u"Confirm Booking Event", user_id = e.user_id,
                              content = u"%s confirm the booking request." % session['user_profile']['name']))
        DBSession.commit()
        return jsonify({"success" : True, "message" : "Update successfully !"})
Пример #24
0
    def delete(self):
        if request.method == 'GET':
            id_list = request.args.getlist('id')
        else:
            id_list = request.form.getlist('id')

        query = self.model.select().where(self.pk << id_list)

        if request.method == 'GET':
            collected = {}
            if self.delete_collect_objects:
                for obj in query:
                    collected[obj.get_id()] = self.collect_objects(obj)

        elif request.method == 'POST':
            count = query.count()
            for obj in query:
                obj.delete_instance(recursive=self.delete_recursive)

            flash('Successfully deleted %s %ss' % (count, self.get_display_name()), 'success')
            return redirect(url_for(self.get_url_name('index')))

        return render_template(self.templates['delete'], **dict(
            model_admin=self,
            query=query,
            collected=collected,
            **self.get_extra_context()
        ))
Пример #25
0
def update_account():
    form = AccountDataForm()
    user = g.user
    if request.method == 'GET':
        form.email.data = user.email
        form.language.data = user.language
        form.timezone.data = user.timezone
    elif request.method == 'POST' and form.validate_on_submit():
        if password_hash(form.old_password.data) != user.password:
            form.old_password.errors.append(_('Wrong password'))
            return render_template('update_account.html', form=form)
        if form.email.data != user.email:
            user.email = form.email.data
            user.confirmed = False
            user.confirmation_string = random_string(20)
            msg = message_confirmation(user.id, user.email, user.confirmation_string)
            mail.send(msg)
            flash(_('Confirmation message sent, check your e-mail'))
        if form.password.data:
            user.password = password_hash(form.password.data)
            flash(_('Password successfully changed'))
        user.language = form.language.data
        user.timezone = form.timezone.data
        db.session.commit()
        return redirect('update_account')

    return render_template('update_account.html', form=form)
Пример #26
0
def edit(id):
    book = Book.query.get_or_404(id)
    if not current_user.can(Permission.EDIT):
        abort('403')
    form = AddBookForm()
    if form.validate_on_submit():
        book.front_cover=form.front_cover.data
        book.bookname=form.bookname.data
        book.introduction=form.introduction.data
        book.press=form.press.data
        book.author=form.author.data
        book.book_type=form.book_type.data
        book.published_date=form.published_date.data
        book.amount_all=form.amount_all.data
        db.session.add(book)
        flash('The book has been updated.')
        return redirect(url_for('.book', id=book.id))
    form.front_cover.data=book.front_cover
    form.bookname.data=book.bookname
    form.introduction.data=book.introduction
    form.press.data=book.press
    form.author.data=book.author
    form.book_type.data=book.book_type
    form.published_date.data=book.published_date
    form.amount_all.data=book.amount_all
    return render_template('edit_book.html', form=form)
Пример #27
0
def server_add():
    form = AmazonServerForm()
    if form.validate_on_submit():
        amazon.add_server(form)
        flash(_('Amazon server added'))
        return redirect(url_for('deploy.deploy_list'))
    return render_template('amazon_server_add.html', form=form)
Пример #28
0
def provider_add():
    form = AmazonForm()
    if form.validate_on_submit():
        amazon.add_provider(form)
        flash(_('Amazon informations added'))
        return redirect(url_for("amazon.provider_list"))
    return render_template('amazon_provider_add.html', form=form)
Пример #29
0
def add_user():
    form = EditUser()

    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()

        if user is None:
            user = User(
                email=form.email.data,
                password=form.password.data,
                first_name=form.first_name.data,
                last_name=form.last_name.data,
                role=form.role.data,
                name="{} {}".format(form.first_name.data, form.last_name.data),
            )

            db.session.add(user)
            db.session.commit()
            flash("User sucessfully added.")

            return redirect(url_for(".all_users"))

        else:
            flash("That user already exists.")

    return render_template("form.html", form=form)
Пример #30
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)
Пример #31
0
 def _process(self):
     self.application.reset_client_secret()
     logger.info("Client secret of %s reset by %s", self.application, session.user)
     flash(_("New client secret generated for the application"), 'success')
     return redirect(url_for('.app_details', self.application))
Пример #32
0
 def _process(self):
     db.session.delete(self.token)
     logger.info("Token of application %s for user %s was revoked.", self.token.application, self.token.user)
     flash(_("Token for {} has been revoked successfully").format(self.token.application.name), 'success')
     return redirect(url_for('.user_profile'))
Пример #33
0
 def _process(self):
     db.session.delete(self.application)
     logger.info("Application %s deleted by %s", self.application, session.user)
     flash(_("Application deleted successfully"), 'success')
     return redirect(url_for('.apps'))
Пример #34
0
 def _process(self):
     self.application.tokens.delete()
     logger.info("All user tokens for %s revoked by %s", self.application, session.user)
     flash(_("All user tokens for this application were revoked successfully"), 'success')
     return redirect(url_for('.app_details', self.application))