Пример #1
0
def login():
    '''This routine verifies that the user is an administrator and, if so,
    puts them in admin mode and redirects them to the admin resource they
    originally requested. It sends them back to the main page if their
    requested URL is unsafe. The username and password are stored in
    the database.
    '''
    if is_logged_in():
        return redirect(url_for('web.display_admin'))
    target_url = request.values.get('next') or url_for('web.display_admin')
    if not is_safe_url(target_url):
        return redirect(url_for('web.display_index'))
    form = Users()
    if form.is_submitted():
        # Check if the cancel button has been pressed; the form value will be
        # 'Cancel' but this doesn't need to be checked.
        if request.form.get('cancel'):
            return redirect(url_for('web.display_index'))
        if form.validate():
            user = Users.read_unit(form.nameField.data)
            if (user is not None) and \
                   (custom_app_context.verify(form.passwordField.data,
                                          user['password'])):
                session['logged_in'] = True
                return redirect(target_url)
        flash('invalid login...', 'error')
    return display_content(
        form=form,
        next=target_url,
        title='Login',
        breadcrumbs=get_breadcrumbs('login')
    )
Пример #2
0
 def out_note_review(self):
     id = _g('id')
     if not id :
         flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR)
         return redirect(self.default())
     obj = DBSession.query(InventoryOutNote).get(id)
     return {'obj' : obj}
Пример #3
0
def contact():
    '''Configure and display the contact us page, with its input form and
    email feature.
    '''
    form = Contacts()
    if form.is_submitted():
        if request.form.get('cancel'):
            return redirect(url_for('web.display_index'))
        if form.validate():
            Contacts.send_email(mail, form)
            return redirect(url_for('web.display_index'))
        flash('All fields are required.')
    department = Departments.read_unit('cs')
    return display_content(
        form=form,
        title='Contact Us',
        primary=department.get('contact'),
        sideTitle='Admissions at Calvin',
        sideContent='''<p>Interested in what Calvin has to offer?<br>
    <a href="http://www.calvin.edu/admissions/visit/">Schedule a visit</a>
    or <br><a href="http://www.calvin.edu/admissions/contact/request/">request
    more information</a>.</p>''',
        breadcrumbs=get_breadcrumbs('contact'),
        editable=True,
        editableUrl=url_for('web.update_department', name='cs')
    )
Пример #4
0
def home_page():
    """
    Generates the unauthenticated landing page. AKA the main or home page.
    """
    if not is_authenticated():
        return render_template('landing.html')
    screenname = g.user['name'].split()[0]
    api = API()
    req = LoginRequest(identity=g.user['identity'],  # @UndefinedVariable
                       email=g.user['email'],  # @UndefinedVariable
                       screenname=screenname)
    result = api.login(req)  # commit user to database and determine userid
    if isinstance(result, APIError):
        flash("Error registering user details.")
        logging.debug("login error: %s", result)
        return redirect(url_for('error_page'))
    else:
        session['screenname'] = result.screenname
        session['userid'] = result.userid
    api = API()
    userid = session['userid']
    screenname = session['screenname']
    identity = g.user['identity']
    personal_url = url_for("love", user=userid, _external=True)
    unsubscribe_url = notifications.make_unsubscribe_url(identity)
    return render_template('home.html', screenname=screenname,
        personal_url=personal_url, unsubscribe_url=unsubscribe_url)
Пример #5
0
    def review(self):
        id = _g('id') or None
        if not id :
            flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR)
            return redirect(self.default())

        try:
            header = DBSession.query(OrderHeader).get(id)

            logs = []
            logs.extend(header.get_logs())
            try:
                deliver_detail = DBSession.query(DeliverDetail).filter(and_(DeliverDetail.active == 0, DeliverDetail.order_header_id == header.id)).one()
                deliver_heaer = deliver_detail.header
    #            for f in deliver_heaer.get_logs() : _info(f.remark)
                logs.extend(deliver_heaer.get_logs())
            except:
                pass
            logs = sorted(logs, cmp = lambda x, y: cmp(x.transfer_date, y.transfer_date))

            return {
                    'header' : header ,
                    'transit_logs' : logs,
                    }
        except:
            _error(traceback.print_exc())
            flash(MSG_SERVER_ERROR, MESSAGE_ERROR)
            return  redirect(self.default())
Пример #6
0
def add_project():
    '''
    Add a project.  Default a tree structure and sections to go with them.
    '''
    session.pop('project_id', None)
    form = ProjectForm(request.form)
    form.template.choices = [(t.id, t.name) for t in Project.query.order_by('name').filter(Project.is_template)]
    form.template.choices.insert(0, (0, gettext('-- Choose a Template --')))
    if form.validate():
        project = Project(name=form.name.data, description=form.description.data, is_template=form.is_template.data)
        db.session.add(project)

        if form.template.data != 0:
            copy_from_template(project, form.template.data)
        else:
            create_node(project=project, title=form.name.data)

        db.session.commit()
        session['project_id'] = project.id

        flash('New Project Added')
        return redirect(url_for('show_content', project_id=project.id, structure_id=None))

    projects = Project.query.all()
    return render_template('index.html',
                           projects=projects,
                           form=form)
Пример #7
0
def bd(source=None):
    """
    绑定微信与门户账户
    :param source:
    :return:
    """

    if source:
        w = WechatUser.query.filter(and_(WechatUser.source == source, WechatUser.checked == 1)).first()
        if w:
            staff = portal_user.query.filter(portal_user.user_code == w.usercode).first()
            login_user(staff, remember=True)
            flash('您已经绑定了' + w.usercode)
            return redirect(url_for('index'))

    from  forms import WechatUserSendcode

    form = WechatUserSendcode()
    if form.validate_on_submit():
        usercode = form.usercode.data.replace('@chinaunicom.cn', '')
        sendcode(source=source, usercode=usercode)
        flash('验证码发送成功!')
        return redirect(url_for('bdchk', usercode=usercode, source=source))
    return render_template('WechatUserSendcode.html',
                           title='绑定',
                           form=form, source=source)
Пример #8
0
def index():
    ''' Our root/index route and corresponding templates. Notice the new codes here. 
    We are searching and getting all the entries from the DB and displaying them.
    One more thing to notice is that we are typecasting the default pymongo return to
    list before we pass it to the template.'''
    try:
        if session['name'] != '':
            user_name = session['name']
    except:
        user_name = 'default'
        session['name'] = 'default'
    entries = get_entries()
    if entries == None:
        entries = []
        flash("Opps! Somwthing went wrong!")
    init_entries = list(entries)
    final_entries = []
    for entry in init_entries:
        if entry['user'] == user_name: ## If it is our current user's entry
            final_entries.append(entry) ## The the entry whatever the private settings is
        else:
            if 'is_private' in entry and entry['is_private'] == False: ## Not our current user? Check for privacy settings
                final_entries.append(entry)
                
    return render_template('index.html',
                           entries=final_entries,
                           home_page=True) ## No need to typecast it again as a list. it is already a list
Пример #9
0
def save_register():
    cid = _g('customer_id' , None)
    user_params = {
                "name" : _g('name'),
                "password" : _g('password'),
                "email" : _g('email'),
                "first_name" : _g('first_name'),
                "last_name" : _g('last_name'),
                "phone" : _g('phone'),
                "mobile" : _g('mobile'),
                   }


    if cid and cid != 'OTHER':
        c = DBSession.query(Customer).get(cid)
        user_params['customer_profile_id'] = c.profile.id
    else:
        cname = _g('name').strip()
        cp = CustomerProfile(name = "PROFILE_%s" % cname.strip().upper().replace(' ', '_'))
        DBSession.add(cp)
        DBSession.flush()
        c = Customer(
                     name = cname,
                     address = _g('address'),
                     profile = cp
                     )
        user_params['customer_profile_id'] = cp.id
        DBSession.add(c)

    DBSession.add(User(**user_params))

    DBSession.commit()
    flash(MSG_SAVE_SUCC, MESSAGE_INFO)
    return redirect(url_for('bpAuth.login'))
Пример #10
0
 def view(self):
     id = _g('id')
     if not id :
         flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR)
         return redirect(url_for('.view'))
     obj = DBSession.query(Customer).get(id)
     return {'obj' : obj}
Пример #11
0
def register():
    '''
    Registers the user.
    :return:
    '''
    if g.user:
        return redirect(url_for('timeline'))
    error = None
    if request.method == 'POST':
        if not request.form['username']:
            error = 'You have to enter a username'
        elif not request.form['email'] or '@' not in request.form['email']:
            error = 'You have to enter a valid email address.'
        elif not request.form['password']:
            error = 'You have to enter a password'
        elif request.form['password'] != request.form['password2']:
            error = 'The two passwords do not match'
        elif get_user_id(request.form['username']) is not None:
            error = 'The username is alredy taken'
        else:
            g.db.execute('''insert into user (username, email, pw_hash) values (?, ?, ?)''',
                         [request.form['username'], request.form['email'],
                          generate_password_hash(request.form['password'])])
            g.db.commit()
            flash('You were successfully registered and can login now')
            return redirect(url_for('login'))
    return render_template('register.html', error=error)
Пример #12
0
 def machine(self, machine_name):
     show_stl = False
     fn, doc, inputs = self.machines_model.machine(machine_name)
     form = metaform('Form_%s' % str(machine_name), inputs)(request.form)
     file_name = ""
     if request.method == 'POST' and form.validate():
         try:
             values = {}
             for name, _type, _, _, _ in inputs:
                 value = getattr(form, name)
                 if types.get(_type, None):
                     values[name] = types[_type](value.data)
                 else:
                     values[name] = value.data
             flash('CREATING!', 'success')
             current_folder = os.getcwd()
             os.chdir(UPLOAD_FOLDER)
             file_name = fn(**values)
             os.chdir(current_folder)
             show_stl = True
         except Exception as e:
             flash('WARNING! %s' % e.message, 'warning')
     return render_template('machine/machine.html',
                            title=doc.title,
                            description=doc.description,
                            images=doc.images,
                            form=form,
                            show_stl=show_stl,
                            file_name=file_name,
                            machine_name=machine_name)
Пример #13
0
def template_edit(path):
    # http://127.0.0.1:5000/template/layout.html
    print path
    path = os.path.join(current_app.root_path, 'templates', "%s.html" % path)
    print path
    html = ""

    try:
        f = open(path)
        html = f.read()
        f.close()
    except Exception as ex:
        flash(_("Template file does not exists"), "error")

    print html

    form = TemplateForm(html=html.decode('utf8'))

    if form.validate_on_submit():
        f = open(path, 'w')
        f.write(form.html.data.encode('utf8'))
        f.close()

        flash(_("Saving success"), "success")

        return redirect(url_for("portal.index"))

    return render_template("misc/template_edit.html",
        form=form,
        path=path)
Пример #14
0
def profile(id):
    user = User.query.get(id)
    if user is None:
        flash(u'We can’t find this User %s :(' % id)
        return redirect(url_for('main.index'))

    return render_template('account/profile.html', user=user)
Пример #15
0
def edit(username):
    """
    编辑 users
    """
    user = UserService.get_by_username(username)

    if not user:
        abort(404)

    if request.method == 'GET':
        form = PeopleEditForm(next=request.args.get('next', None), id=id, obj=user)
    else:
        form = PeopleEditForm(next=request.args.get('next', None), id=id)
        if form.validate_on_submit():
            # 获取指定的表单数据
            form.populate_obj(user)

            # 保存数据
            UserService.update(user)

            flash(_("Modify success"), "success")

            next_url = form.next.data

            if not next_url or next_url == request.path:
                next_url = url_for('people.show', username=username)

            return redirect(next_url)
        elif form.errors:
            for error_name, error_value in form.errors.iteritems():
                print "error: %s %s" % (error_name, error_value)
            flash(_("Cause an error"), "failed")

    statistic = EntryService.get_statistic_by_author_id(user.id)
    return render_template("people/edit.html", form=form, people=user, statistic=statistic, form_id=user.id)
Пример #16
0
def love():
    """
    Main message-sending page.
    Note that you don't have to log in or have an account for this, you just
    have to be authenticated by Google.
    """
    userid = request.args.get('user', None)
    if userid is None:
        flash("That URL doesn't specify a valid user. I'm so sorry...")
        return render_template('base.html')
    api = API()
    response = api.get_user(userid)
    if isinstance(response, APIError):
        flash("That URL doesn't specify a valid user. I'm so sorry...")
        return render_template('base.html')
    target = response.screenname
    form = LoveForm()
    if not form.validate_on_submit():
        form = LoveForm()
        return render_template('love.html', form=form, userid=userid,
                               target=target)
    but = form.but.data
    message = "I love %s, but I wish %s" % (target, but)
    api.love(userid, message)
    return render_template('loved.html', message=message)
Пример #17
0
def submit(id):
    """
    similar to the test submission.
    The code is submitted by this method , it stores the code in the `upload` folder and then finds the score
    :param id:
    :return:
    """
    print(current_user.username)
    form = SubmitForm()
    if request.method == 'POST':
        file = request.files['code']
        print(os.path.abspath("static"))
        if file and allowed_file(file.filename):
            filename = "_".join([current_user.username, str(id), str(int(time.time()))])
            location = os.path.join(UPLOAD_LOCATION, filename)
            file.save(location)
            userid = int(current_user.id)
            code_process = Process(target=find_score, args=(location, id, userid))
            code_process.start()

            flash("your code has been uploaded")
            return redirect(url_for("questions.getquestion", id=id))
        else:
            flash("that file format is not allowed", category="warning")
            return redirect(url_for("questions.getquestion", id=id))
Пример #18
0
    def save_new(self):
        params = {
                   "name" : _g('name'),
                   "address" : _g('address'),
                   "manager" : _g('manager'),
                   "remark" : _g('remark'),
                   "parent_id" : _g('parent_id'),
                  }

        try:
            obj = InventoryLocation(**params)
            DBSession.add(obj)
            DBSession.flush()

            if params['parent_id']:
                parent = DBSession.query(InventoryLocation).get(obj.parent_id)
                obj.full_path = "%s%s" % (parent.full_path or '', params['name'])
                obj.full_path_ids = "%s|%s" % (parent.full_path_ids, obj.id)
            else:
                obj.full_path = params['name']
                obj.full_path_ids = obj.id

            DBSession.commit()
            flash(MSG_SAVE_SUCC, MESSAGE_INFO)
        except:
            DBSession.rollback()
            _error(traceback.print_exc())
        return redirect(self.default())
Пример #19
0
def bdchk(source=None, usercode=None):
    """
    验证绑定码是否匹配
    :param source:
    :param usercode:
    :return:
    """
    from forms import WechatChkCode

    source = request.args.get('source')
    usercode = request.args.get('usercode')
    form = WechatChkCode()
    if form.validate_on_submit():
        code = form.code.data
        if source and request:
            x = WechatUser.query.filter(and_(WechatUser.source == source,
                                             WechatUser.usercode == usercode,
                                             WechatUser.code == code))

            w = x.first()
            if w:
                x.update({
                    WechatUser.checked: 1
                })

                staff = portal_user.query.filter(portal_user.user_code == w.usercode).first()
                login_user(staff, remember=True)
                db.session.commit()
                flash('绑定成功')
                return redirect(url_for('index'))

    return render_template('checkcode.html', action='bdchk', opname='绑定账户', form=form, title='请输入验证码')
Пример #20
0
    def save_new(self):
        try:
            obj = Customer(
                            no = _g('no'),
                            name = _g('name'),
                            display_name = _g('display_name'),
                            province_id = _g('province_id'),
                            city_id = _g('city_id'),
                            address = _g('address'),
                            contact_person = _g('contact_person'),
                            mobile = _g('mobile'),
                            phone = _g('phone'),
                            email = _g('email'),
                            remark = _g('remark'),
                            note_id = _g('note_id'),
#                            payment_id = _g('payment_id'),
                                )
            DBSession.add(obj)
            obj.attachment = multiupload()
            DBSession.commit()
            flash(MSG_SAVE_SUCC, MESSAGE_INFO)
            return redirect(url_for('.view', action = 'view', id = obj.id))
        except:
            _error(traceback.print_exc())
            DBSession.rollback()
            flash(MSG_SERVER_ERROR, MESSAGE_ERROR)
            return redirect(url_for('.view'))
Пример #21
0
def save_image(store_key):
    return_to_edit = False
    image = image_dao.get(store_key)
    prop_config = config_dao.get_property_config()
    for prop in prop_config:
        key = prop['key']
        # need to iterate over array elements first because their actual key does not exist in the form
        # so it would collide with l171 where I set a property to None if the form doesn't contain the key/is empty
        if prop['type'] == 'array':
            image[key] = []
            for i in xrange(0, 100):
                arr_key = key + str(i)
                if arr_key in request.form:
                    image[key].append(request.form[arr_key].strip())
        else:
            if key not in request.form or request.form[key] == '':
                image[key] = None
            elif prop['type'] == 'integer':
                try:
                    image[key] = int(request.form[key])
                except ValueError:
                    flash('%s must be of type %s' % (prop['human_' + config['language']], prop['type']), 'alert-error')
                    return_to_edit = True
            else:
                image[key] = request.form[key].strip()
    if return_to_edit:
        view_props = create_view_props(image, prop_config)
        return render_template('edit.html', view_props=view_props, store_key=store_key)
    else:
        image_dao.put(store_key, image)
        return redirect(url_for('image_page', store_key=store_key))
Пример #22
0
def save(page):
    # pdb.set_trace()
    account_model = AccountModel(request.form)
    account_model.interests = request.form.getlist("interests")

    select_list = InterestsList(
        div_class="list_interests", model="interestsListModel", id_select="interests", options=account_model.interests
    )

    if account_model.validate() and len(account_model.interests) != 0:
        entity = Account.Account(
            author=account_model.author.data,
            birth=account_model.birth.data,
            about_me=account_model.about_me.data,
            sex=account_model.sex.data,
            occupation=account_model.occupation.data,
            interests=account_model.interests,
            username=account_model.username.data,
            password=account_model.password.data if len(account_model.password.data) > 0 else session["pass"],
        )

        entity.update(session["user"])
        flash("Seus dados foram atualizados com muito sucesso!")
    else:
        flash(u"O formulário não está válido, verifique erros ou incoerências")
        # flash(account.)

    return render_template("admin/%s.html" % page, accountForm=account, selectList=select_list)
Пример #23
0
def ensure_user():
    """
    Commit user to database and determine userid.

    May return a complete web response (e.g. in case of error).

    May flash messages.
    """
    # TODO: REVISIT: automagically hook this into OIDC.check
    api = API()
    if not is_authenticated():
        # user is not authenticated yet
        return
    if is_logged_in():
        # user is authenticated and authorised (logged in)
        api.resubscribe(session['userid'])
        return
    identity, email = get_oidc_token_details()
    req = LoginRequest(identity=identity,
                       email=email)
    result = api.login(req)
    if isinstance(result, APIError):
        flash("Error registering user details.")
        logging.debug("login error: %s", result)
        return redirect(url_for('error_page'))
    session['userid'] = result.userid
    session['screenname'] = result.screenname
    flash("You have logged in as '%s'" % (session['screenname'],))
Пример #24
0
def loop_list(page):
    if request.method == 'POST':
        if request.form.get('action') == 'add':
        #           try:
            spl = request.form.get('begin').split(':')
            begin = int(int(spl[0]) * 100 + (int(spl[1]) / 60.) * 100)
            spl = request.form.get('end').split(':')
            end = math.ceil(int(spl[0]) * 100 + (int(spl[1]) / 60.) * 100)
            if end == begin and end == 0:
                end = 2400
            loop = Loop(begin=begin, end=end, filename=request.form.get('filename'))
            rfk.database.session.add(loop)
            rfk.database.session.commit()
        #            except Exception as e:
        #                flash('error while inserting Loop')
        elif request.form.get('action') == 'delete':
            try:
                rfk.database.session.delete(Loop.query.get(request.form.get('loopid')))
                rfk.database.session.commit()
            except Exception as e:
                flash('error while deleting Loop')
    per_page = 25
    (result, total_count) = paginate_query(Loop.query, page=page)
    current_loop = Loop.get_current_loop()
    loops = []
    for loop in result:
        loops.append({'loop': loop.loop,
                      'begin': '%02d:%02d' % (int(loop.begin / 100), int(((loop.begin % 100) / 100.) * 60)),
                      'end': '%02d:%02d' % (int(loop.end / 100), int(((loop.end % 100) / 100.) * 60)),
                      'current': loop == current_loop,
                      'filename': loop.filename,
                      'file_missing': not (loop.file_exists)})
    pagination = Pagination(page, per_page, total_count)
    searchpath = get_path(rfk.CONFIG.get('liquidsoap', 'looppath'))
    return render_template('admin/loops/list.html', loops=loops, pagination=pagination, searchpath=searchpath)
Пример #25
0
def authenticated_game_page(gameid):
    """
    Game page when user is authenticated (i.e. the private view)
    """
    alternate_response = ensure_user()
    if alternate_response:
        return alternate_response
    userid = session['userid']

    api = API()
    response = api.get_private_game(gameid, userid)
    if isinstance(response, APIError):
        if response is api.ERR_NO_SUCH_GAME:
            msg = "Invalid game ID."
        else:
            msg = "An unknown error occurred retrieving game %d, sorry." %  \
                (gameid,)
        flash(msg)
        return redirect(url_for('error_page'))

    if response.is_finished():
        return _finished_game(response, gameid, userid)
    elif response.game_details.current_player == None:
        return _paused_game(response, gameid, userid)
    else:
        return _running_game(response, gameid, userid, api)
Пример #26
0
def save_config():

    flash(gettext('Configuration Save was a Complete Success!'))
    return redirect(url_for('show_config'))

#@crsf.error_handler
#def csrf_error(reason):
#    return render_template('csrf_error.html', reason=reason), 400
Пример #27
0
def quick_transaction_post(user=None, username=None, beer_id=None):
    selected_user = get_user_object(username)
    beer = Beer.query.filter_by(id=beer_id).first()
    transaction = Transaction(user=selected_user, registered_by=user, beer=beer)
    transaction.save()
    transaction.user.update_account_status()
    flash(u'Skráði %s á %s' % (beer.name, selected_user.name))
    return redirect(url_for('quick_transaction'))
Пример #28
0
 def get_cambiar_contrasena(self, token):
     usuario = UsuarioDao().get_usuario_por_token(
         Usuario(token_password=token))
     if usuario is None:
         flash(u"El token no es valido para el cambio de contraseña.",
               'error')
         return False
     return render_template('login/cambiar_contraseña.html', token=token)
Пример #29
0
    def print_barcode(self):
        header = OrderHeader.get(_g('id'))

        if not header :
            flash(MSG_RECORD_NOT_EXIST)
            return redirect(self.default())

        return {'header' : header}
Пример #30
0
 def revise_by_barcode(self):
     barcode = _g('no')
     try:
         header = DBSession.query(OrderHeader).filter(OrderHeader.no == barcode).one()
         return redirect(url_for('.view', action = 'revise', id = header.id))
     except:
         flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR)
         return redirect(url_for("bpRoot.view", action = "index"))
Пример #31
0
    def update_model(self, form, model):
        try:
            form.populate_obj(model)

            model.save()
            return True
        except Exception as ex:
            flash(_('Failed to update model. %(error)s', error=str(ex)), 'error')
            return False
Пример #32
0
 def __RegisterTheUser(self, registerForm):
     # Hashes the password 
     hashedPass = bcrypt.generate_password_hash(registerForm.password.data).decode('utf-8')
     # Adds user to database as a object 
     userToAdd = users(registerForm.username.data, hashedPass, 0)
     db.session.add(userToAdd)
     db.session.commit()
     flash("User created successfully", "Success")
     return redirect(url_for('UserControl.AdminPanel'))
Пример #33
0
def delete_post(post_id):
    post = Post.query.get_or_404(post_id)
    if post.author != current_user:
        abort(403)

    db.session.delete(post)
    db.session.commit()
    flash('Your post has been deleted', 'success')
    return redirect(url_for('home'))
    def edit(self) -> Response:
        isbn = request.args.get("isbn")
        visa = request.args.get("visa")
        if not isbn and not visa:
            flash("Veuillez renseigner un ISBN ou un visa d'exploitation",
                  "error")
            return redirect(url_for(".search"))

        if isbn:
            products = (Product.query.filter(
                Product.extraData["isbn"].astext == isbn).options(
                    joinedload(Product.offers).joinedload(
                        Offer.criteria)).all())

        if visa:
            products = (Product.query.filter(
                Product.extraData["visa"].astext == visa).options(
                    joinedload(Product.offers).joinedload(
                        Offer.criteria)).all())

        if not products:
            flash(
                "Aucun livre n'a été trouvé avec cet ISBN ou ce visa d'exploitation",
                "error")
            return redirect(url_for(".search"))

        offer_criteria_form = OfferCriteriaForm()

        offers = list(itertools.chain.from_iterable(p.offers
                                                    for p in products))
        active_offers_number = len(
            [offer for offer in offers if offer.isActive])
        inactive_offers_number = len(offers) - active_offers_number
        current_criteria_on_offers = _get_current_criteria_on_active_offers(
            offers)
        current_criteria_on_all_offers = []

        for _, value in current_criteria_on_offers.items():
            if value["count"] == active_offers_number:
                current_criteria_on_all_offers.append(value["criterion"])

        if len(current_criteria_on_all_offers) > 0:
            offer_criteria_form.criteria.data = current_criteria_on_all_offers

        context = {
            "name": products[0].name,
            "type": _get_product_type(products[0]),
            "active_offers_number": active_offers_number,
            "inactive_offers_number": inactive_offers_number,
            "isbn": isbn,
            "offer_criteria_form": offer_criteria_form,
            "current_criteria_on_offers": current_criteria_on_offers,
            "product_compatibility": _get_products_compatible_status(products),
            "visa": visa,
        }

        return self.render("admin/edit_many_offers.html", **context)
Пример #35
0
 def update_model(self, form, model):
     try:
         form.populate_obj(model)
         return model.save()
     except Exception as ex:
         self.session.rollback()
         flash(_('Failed to update model. %(error)s', error=str(ex)),
               'error')
         return False
Пример #36
0
def solicitar_sustentacion():
    if request.method == "GET":
        return EstudianteController().get_solicitar_sustentacion()
    file = request.files['documento']
    id = session['usuario']['id']
    if file.filename == '':
        flash('No selecciono el archivo', 'Error')
        return redirect(request.url)
    return EstudianteController().solicitar_sustentacion(file, id)
Пример #37
0
def check_import_errors(fileloc, session):
    # Check dag import errors
    import_errors = session.query(errors.ImportError).filter(
        errors.ImportError.filename == fileloc).all()
    if import_errors:
        for import_error in import_errors:
            flash(
                "Broken DAG: [{ie.filename}] {ie.stacktrace}".format(
                    ie=import_error), "dag_import_error")
Пример #38
0
    def update_model(self, form, model):
        try:
            form.populate_obj(model)

            EmailCheckService.add_or_update(model)
            return True
        except Exception as ex:
            flash(_('Failed to update model. %(error)s', error=str(ex)), 'error')
            return False
Пример #39
0
def remove(submission_id: str):
    submission = Submission.query.get_or_404(submission_id)
    if submission.mapper_id != current_user.osu_uid:
        flash("You are not allowed to do that.", "danger")
        return redirect(url_for("base.index"), code=400)

    delete_submission(submission)
    flash("Done!", "success")
    return redirect(url_for("submission.submit"))
Пример #40
0
def login():
    flash('You are logged in and redirected to index page')

    if request.method == 'POST':
        session['username'] = request.form['username']
        print(session['username'])
        print(id(session))
        return redirect(url_for('index'))

    return '''
Пример #41
0
def Results():
    searchString = request.form['searchString']
    if searchString == '':
        flash("Please Enter a Search String!!")
        return redirect(url_for('HomePage'))
    results = RunThis(searchString=searchString)
    return render_template('Results.html',
                           results=results[0],
                           searchStr=searchString,
                           Num=results[1])
Пример #42
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user is None or not user.verify(form.password.data):
            flash("Invalid email or password", category="warning")
            return redirect(url_for("auth.login"))
        login_user(user, form.remember_me.data)
        return redirect(url_for("questions.index"))
    return render_template("login.html", forms=form)
Пример #43
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        flash('Login requested for OpenID="%s", remember_me=%s' %
              (form.openid.data, str(form.remember_me.data)))
        return redirect('/index')
    return render_template('login.html', 
                           title='Sign In',
                           form=form,
                           providers=app.config['OPENID_PROVIDERS'])
Пример #44
0
def password_reset_request():
    form = PasswordResetRequestForm()
    if form.validate_on_submit():
        user = User().get_user(email=form.email.data)
        if user:
            AuthSupport().send_reset_password_email(user,
                                                    request.args.get('next'))
            flash('重置密码的邮件已经发送到你的注册邮箱')
            return redirect(url_for('auth.login'))
    return render_template('auth/reset_password.html', form=form)
Пример #45
0
    def create_model(self, form):
        try:
            model = GeneralFile()
            form.populate_obj(model)

            model.save()
            return True
        except Exception as ex:
            flash(_('Failed to create model. %(error)s', error=str(ex)), 'error')
            return False
 def after_model_change(self, form: Form, model: User,
                        is_created: bool) -> None:
     update_external_user(model)
     if is_created and not send_activation_email(model):
         token = create_reset_password_token(model)
         flash(
             f"L'envoi d'email a échoué. Le mot de passe peut être réinitialisé depuis le lien suivant : {build_pc_webapp_reset_password_link(token.value)}",
             "error",
         )
     super().after_model_change(form, model, is_created)
Пример #47
0
def register_unlock(key):
    user = User.unique(User.generated == key)
    if not user: flash(localize("administration", "client.no_account"))
    user.generated = ""
    user.role = Role.get(3)
    user.update()
    g.session.user_id = user.id
    g.session.update()
    flash(localize("administration", "client.unlock_success") % (user.name))
    return redirect("/")
Пример #48
0
def delete_user(username):
    '''remove user and feedback, then redirect to login'''
    if 'username' not in session or username != session['username']:
        raise Unauthorized()
    user = User.query.get(username)
    db.session.delete(user)
    db.session.commit()
    session.pop('username')
    flash('Your account has been deleted!', 'danger')
    return redirect('/')
Пример #49
0
def check_access():
    if not current_user.is_authenticated:
        return abort(401)

    if not current_user.has_access("admin"):
        if not current_user.has_access("judge"):
            return abort(403)
        if current_app.config["STATUS"] != "judging":
            flash("It is not judging phase.")
            return redirect(url_for("base.index"))
Пример #50
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        #         user = User.query.filter_by(email=form.email.data).first()
        user = User.query.filter_by(email=form.email.data).first()
        if user is not None and user.verify_password(form.password.data):
            login_user(user, form.remember_me.data)
            return redirect(request.args.get('next') or url_for('main.index'))
        flash('Invalid username or password')
    return render_template('login.html', form=form)
Пример #51
0
def quick_transaction_post(user=None, username=None, beer_id=None):
    selected_user = get_user_object(username)
    beer = Beer.query.filter_by(id=beer_id).first()
    transaction = Transaction(user=selected_user,
                              registered_by=user,
                              beer=beer)
    transaction.save()
    transaction.user.update_account_status()
    flash(u'Skráði %s á %s' % (beer.name, selected_user.name))
    return redirect(url_for('quick_transaction'))
Пример #52
0
    def create_model(self, form):
        try:
            model = Comment()
            form.populate_obj(model)

            Comment.add_or_update(model)
            return True
        except Exception as ex:
            flash(_('Failed to create model. %(error)s', error=str(ex)), 'error')
            return False
Пример #53
0
def change(type_):
    if type_ == "hq":
        motd = request.form.get('motd')
        sset_motd_hq(motd)
        flash(gettext("HQ MOTD Saved"), 'success')
    elif type_ == "vg":
        motd = request.form.get('motd')
        sset_motd_vg(motd)
        flash(gettext("VG MOTD Saved"), 'success')
    return redirect(url_for('settings_fmotds.index'))
Пример #54
0
    def editar_usuario(self, nombres, apellidos, cedula, email, tipo_usuario,
                       id):
        usuario_e = Usuario(nombres=nombres, apellidos=apellidos, cedula=cedula,
                            email=email, tipo_usuario=tipo_usuario, id=id)

        if UsuarioDao().editar_usuario(usuario_e):
            flash("El usuario se edito correctamente.", "success")
        else:
            flash("Error al editar el usuario.", "error")
        return redirect(url_for("usuarios.listar_usuarios"))
Пример #55
0
def store():
    notification = Notification(
        notification=(f"{session['user']['username']} Ask to be a store"),
        to=str(User.get_admin(User)))
    notification.save()
    flash(
        "You Resquest Send Successfully. We will contact you soon.\n Thank you to trust us."
    )
    # render the view
    return redirect(url_for('item.index'))
    def after_model_change(self, form: Form, model, is_created: bool) -> None:
        if is_created:
            token = users_api.create_reset_password_token(
                model, token_life_time=RESET_PASSWORD_TOKEN_LIFE_TIME_EXTENDED)
            send_admin_user_validation_email(model, token)
            flash(
                f"Lien de réinitialisation du mot de passe : {build_pc_webapp_reset_password_link(token.value)}"
            )

        super().after_model_change(form, model, is_created)
Пример #57
0
def api_logout():
    try:
        current_user.authenticated = False
        #tmp_id = str(current_user.id)
        logout_user()
        session.clear()
        flash("로그아웃 되었습니다.")
        return redirect(url_for("main_view.main"))
    except Exception as e:
        logger.info(str(e))
Пример #58
0
def logout():
    """Logout, a route but not a html page, requires user to be logged in. 
    Ends a users flask_login session and redirects to home."""
    logout_user()
    for user in users_lst:
        if user.get_id() == current_user.get_id():
            users_lst.remove(user)
            break
    flash("You have been logged out!")
    return redirect(url_for("home"))
Пример #59
0
def submitEmail():
    if not Email.validate_email(request.form):
        return redirect('/')

    data = {
        'email_address': (request.form['email_address']),
    }
    Email.saveToDB(data)
    flash('Thanks for entering a valid email address!')
    return redirect('/emailsMade')
Пример #60
0
def delete_feedback(feedback_id):
    '''delete a feedback post'''
    feedback = Feedback.query.get(feedback_id)
    if 'username' not in session or feedback.username != session['username']:
        raise Unauthorized()
    form = DeleteForm()
    if form.validate_on_submit():
        db.session.delete(feedback)
        db.session.commit()
        flash('Feedback removed!', 'danger')
    return redirect(f'/users/{feedback.username}')