Beispiel #1
0
 def on_admin_toggle_pin(self, request):
     if request.cookies.get('cookie_name') is None:
         return redirect('/')
     img_id = request.args.get('id')
     if img_id is not None:
         cvtools.toggle_pinned(img_id)
     return redirect(request.referrer)
Beispiel #2
0
def login():
    form = UserLogin()

    if request.method == "POST":
        email = thwart(request.form["email"])
        password = thwart(request.form["password"])

        if re.match(r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]*$", email):
            if not check_new_user_email(email):
                user = get_user_id(email)

                check = comfirm_password(user[0], email, password)
                password = random.random()

                if check:
                    session["username"] = user[1]
                    session["userid"] = user[0]
                    session["logged_in"] = True
                    flash("Welcome back " + session["username"] + ".")
                    return redirect(url_for("index"))

                else:
                    flash("Please check your login details")
                    return redirect(url_for("login"))
            else:
                flash("Please check your login details")
                return redirect(url_for("login"))
        else:
            flash("Please check your login details")
            return redirect(url_for("login"))

    return render_template("users/login.html", form=form)
def create_new_account():
    if request.method == 'POST':
        first_name = request.form['first_name']
        last_name = request.form['last_name']
        email = request.form['email']
        password = request.form['password'].encode('utf-8')
        retype_password = request.form['retype_password'].encode('utf-8')
        # if the same email was used to log in
        if email == UserExternalLogin.query.filter_by(email=email).first():
            provider = UserExternalLogin.query.filter_by(email=email).join(ExternalAuthenticationProvider).first()
            flash('This email was already used to login with' + str(provider.name))
        if password == retype_password:
            password_salt = bcrypt.gensalt()  # generate salt
            password_hash = bcrypt.hashpw(password, password_salt)  # generate password hash

            user_details = UserDetails(first_name=first_name, last_name=last_name, email=email,
                                       password_hash=password_hash,
                                       password_salt=password_salt)
            db.session.add(user_details)
            db.session.commit()

            new_user = UserAccount(screen_user_name=first_name + ' ' + last_name, user_details_id=user_details.id)
            db.session.add(new_user)
            db.session.commit()
            login_user(new_user)
            return redirect(url_for('success'))
        else:
            flash('Passwords don\'t match')
            return redirect(url_for('/signup'))
    else:
        return render_template('signup-form.html')
Beispiel #4
0
def paymentSuccess():
    # Paypal redirects the user to this URL once the user has approved the payment.
    # Now we still need to execute the payment.

    try:
        payment, prt = pp1.execute_payment(request.args)

        # amount = payment["transactions"][0]["amount"]["total"]  # get total amount from the Paypal return message
        amount = prt.final_fee + prt.donation

        # send confirmation email
        body = render_template("application_confirmation.txt", amount=int(amount), prt=prt, eventname=event_name,
                               shortname=event_shortname, final_fee=int(prt.final_fee), currency_symbol=currency_symbol)
        print(body)
        ehbmail.send([prt.id], "Application confirmed", [body], "Application page")

        return render_template("payment_confirmation.html", title="Apply!", amount=int(amount), data=prt, name=event_name, shortname=event_shortname, application_fee=int(application_fee))

    except ParticipantNotFoundException as e:
        # print("pnfe " + e.token)
        return "Unable to resolve the Paypal token '%s' to a participant. Please try resubmitting your application, or contact the organizers." % e.token
    except PaymentNotFoundException as e:
        # print("pm nfe " + e.paymentId)
        flash("Unable to resolve the Paypal payment ID '%s' to a payment. Please try resubmitting your application, or contact the organizers." % e.paymentId)
        flask_session['sn_code'] = generate_confirmation_token(prt.email)
        return redirect("confirm.html")
    except DuplicatePaymentException as e:
        amount = application_fee + e.prt.donation
        return render_template("payment_confirmation.html", title="Apply!", amount=amount, data=e.prt, name=event_name, shortname=event_shortname, application_fee=("%.2f" % application_fee))
    except PaymentFailedException as e:
        flash("Something went wrong with your Paypal payment. Please contact the organizers.")
        flask_session['sn_code'] = generate_confirmation_token(prt.email)
        return redirect("confirm.html")
def hierarchy_update(id_):
    root = g.nodes[id_]
    if root.system:
        abort(403)
    form = build_form(HierarchyForm, 'hierarchy', root)
    form.forms.choices = NodeMapper.get_form_choices(root)
    if root.value_type:
        del form.multiple
    elif root.multiple:
        form.multiple.render_kw = {'disabled': 'disabled'}
    if form.validate_on_submit():
        if form.name.data != root.name and NodeMapper.get_nodes(form.name.data):
            flash(_('error name exists'), 'error')
            return redirect(url_for('node_index') + '#tab-' + str(root.id))
        save(form, root)
        flash(_('info update'), 'info')
        return redirect(url_for('node_index') + '#tab-' + str(root.id))
    form.multiple = root.multiple
    table = {'id': 'used_forms', 'show_pager': False, 'data': [], 'sort': 'sortList: [[0, 0]]',
             'header': ['form', 'count']}
    for form_id, form_ in root.forms.items():
        url = url_for('hierarchy_remove_form', id_=root.id, remove_id=form_id)
        link = '<a href="' + url + '">' + uc_first(_('remove')) + '</a>'
        count = NodeMapper.get_form_count(root, form_id)
        table['data'].append([form_['name'], format_number(count) if count else link])
    return render_template('hierarchy/update.html', node=root, form=form, table=table,
                           forms=[form.id for form in form.forms])
def process_event_cfs_speaker(identifier, via_hash=False):
    if request.method == 'GET':
        event = get_published_event_or_abort(identifier)
        placeholder_images = DataGetter.get_event_default_images()
        if event.sub_topic:
            custom_placeholder = DataGetter.get_custom_placeholder_by_name(event.sub_topic)
        elif event.topic:
            custom_placeholder = DataGetter.get_custom_placeholder_by_name(event.topic)
        else:
            custom_placeholder = DataGetter.get_custom_placeholder_by_name('Other')
        if not event.has_session_speakers:
            abort(404)

        call_for_speakers = DataGetter.get_call_for_papers(event.id).first()

        if not call_for_speakers or (not via_hash and call_for_speakers.privacy == 'private'):
            abort(404)

        form_elems = DataGetter.get_custom_form_elements(event.id)
        speaker_form = json.loads(form_elems.speaker_form)
        session_form = json.loads(form_elems.session_form)

        now = datetime.now(pytz.timezone(event.timezone
                                                  if (event.timezone and event.timezone != '') else 'UTC'))
        start_date = pytz.timezone(event.timezone).localize(call_for_speakers.start_date)
        end_date = pytz.timezone(event.timezone).localize(call_for_speakers.end_date)
        state = "now"
        if end_date < now:
            state = "past"
        elif start_date > now:
            state = "future"
        speakers = DataGetter.get_speakers(event.id).all()
        accepted_sessions_count = get_count(DataGetter.get_sessions(event.id))
        return render_template('gentelella/guest/event/cfs_new_speaker.html',
                               event=event,
                               speaker_form=speaker_form,
                               accepted_sessions_count=accepted_sessions_count,
                               session_form=session_form,
                               call_for_speakers=call_for_speakers,
                               placeholder_images=placeholder_images,
                               state=state,
                               speakers=speakers,
                               via_hash=via_hash,
                               custom_placeholder=custom_placeholder,
                               from_path="cfs")

    if request.method == 'POST':
        email = request.form['email']
        event = DataGetter.get_event_by_identifier(identifier)
        if not event.has_session_speakers:
            abort(404)
        DataManager.add_speaker_to_event(request, event.id)
        if login.current_user.is_authenticated:
            flash("You have been registered as Speaker", "success")
            return redirect(url_for('event_detail.display_event_cfs', identifier=identifier))
        else:
            flash(Markup(
                "You have been registered as Speaker. Please login/register with <strong><u>" + email + "</u></strong> to manage it."),
                "success")
            return redirect(url_for('admin.login_view', next=url_for('my_sessions.display_my_sessions_view')))
def user_login():
    if request.method == 'GET':
        if UserSession.currentUser.userId != -1:
            return render_template('home.html', isAuthenticated = user_is_authenticated())
        else:
            return render_template('user_login.html', isAuthenticated = user_is_authenticated())
    
    if request.method == 'POST':
        filterParameter1 = FilterParameter("USERNAME", "=", request.form['login_username'])
        filterParameter2 = FilterParameter("USERPASSWORD", "=", request.form['login_password'])
        filterExpression = FilterExpression()
        filterExpression.AddParameter(filterParameter1)
        filterExpression.AddParameter(filterParameter2)
    
        users = []
        
        for user in userhandler.Get(filterExpression):
            users.append(user)
            
        if len(users) == 0:
            return redirect('/login')
            #return render_template('home.html', current_time=now.ctime())
        else:
            UserSession.currentUser = users[0]

            return redirect('/')
def user_account():
    if UserSession.currentUser is None:
        return redirect('/')
    
    if request.method == 'POST':
        if request.form['button'] == "delete":
            userhandler.Delete(UserSession.currentUser.userId)
            UserSession.currentUser.userId = -1
            
            return redirect('/')
        
        user = User()
        user.firstName = request.form['account_firstName']
        user.lastName = request.form['account_lastName']
        user.username = request.form['account_username']
        user.password = request.form['account_password']

        user.userId = UserSession.currentUser.userId
        
        if request.form['button'] == "update":
            userhandler.Update(user)
            UserSession.currentUser = user

        return redirect('/')
    
    elif request.method == 'GET':
        return render_template('user_account.html', currentUser=UserSession.currentUser, isAuthenticated = user_is_authenticated())
Beispiel #9
0
    def on_index(self, request):
        if request.cookies.get('cookie_name') is not None and request.cookies.get('cookie_name') != '':
            return redirect('/admin_list/')
        
        error = None
        sid = request.cookies.get('cookie_name')
        if sid is None:
            request.session = session_store.new()
        else:
            request.session = session_store.get(sid)
            
        action = request.args.get('action')
        user = request.cookies.get('cookie_user')
        
        if action == "Signout":
            response = redirect('/')
            response.set_cookie('cookie_name', '')
            return response

        username = request.form.get('username')
        password = request.form.get('password')
        logged_in, user_id = cvtools.admin_login(username, password)
        if logged_in:
            session_store.save(request.session)
            response = redirect('/admin_list')
            response.set_cookie('cookie_name', request.session.sid)
            response.set_cookie('cookie_user', username)
            return response
        return self.render_template('index.html', page="index", error=error, sid=sid, user=user)
Beispiel #10
0
def actionOnRecord():
    if request.method == "POST":
        if request.form['submit'] == 'Update':
            # updatation
            person_id = request.form.get('id')
            person_name = request.form.get('name')
            person_email = request.form.get('email')
            person_city = request.form.get("city")
            person_company = request.form.get("company")

            person_to_update = Person.query.filter_by(id=int(person_id))
            person_to_update.name = person_name
            person_to_update.email = person_email
            person_to_update.city = person_city
            person_to_update.company = person_company

            # Saving update
            db.session.commit()
            return redirect(url_for("index"))
        if request.form['submit'] == 'Delete':
            # deletion
            personid = request.form.get('id')
            print( "The Record to be deleted : ", personid)
            if not type(eval(personid)) == int:
                return
            Person.query.filter_by(id=int(personid)).delete()
            db.session.commit() # deletion Completed
            return redirect(url_for("index"))
    return redirect(url_for("index"))
Beispiel #11
0
    def out_note_delete(self):
        id = _g("id")
        if not id :
            flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR)
            return redirect(url_for(".view", action = "out_note"))
        try:
            note = DBSession.query(InventoryOutNote).get(id)
            note.active = 1
            for d in note.details:
                location_item = DBSession.query(InventoryLocationItem).filter(and_(InventoryLocationItem.active == 0,
                                                               InventoryLocationItem.location_id == d.location_id,
                                                               InventoryLocationItem.item_id == d.item_id)).with_lockmode("update").one()
                if note.status == 1 :  # the record is not approved
                    location_item.qty += d.qty
                    location_item.area += d.area
                    location_item.weight += d.weight
                location_item.exp_qty += d.qty
                location_item.exp_area += d.area
                location_item.exp_weight += d.weight

            DBSession.add(SystemLog(
                                    type = InventoryOutNote.__class__.__name__,
                                    ref_id = note.id,
                                    remark = u"%s 删除该记录。" % (session['user_profile']['name'])
                                    ))

            DBSession.commit()
            flash(MSG_DELETE_SUCC, MESSAGE_INFO)
        except:
            _error(traceback.print_exc())
            DBSession.rollback()
            flash(MSG_SERVER_ERROR, MESSAGE_ERROR)
        return redirect(url_for(".view", action = "out_note"))
Beispiel #12
0
def delete_user(user_id):
    """
    Delete a user.

    This page can be requested in both GET and POST methods:

    * If this page was requested with GET method, a form that confirms that this user should be removed is returned.
    * If this page was requested with POST method, the validation form is checked. If it is validated successfully.
        Later (even if the user was not deleted) the user is redirected to the management page (see
        :meth:`~edsudoku.server.manage_users.manage_users`).

    :param user_id: The user ID to be deleted.
    :type user_id: int
    :return: As explained above.
    :rtype: flask.Response
    """
    user_to_delete = User.get_by_id(user_id)
    if not user_to_delete:
        flash('User not found', 'danger')
        return redirect(url_for('manage_users'))

    if request.method == 'POST':
        user_id2 = int(request.form.get('user_id', -1))
        approved = bool(request.form.get('approved', False))

        if approved and user_id == user_id2:
            user_to_delete.delete()
            commit()
            flash('User %s has been deleted successfully' % user_to_delete.display, 'success')
        else:
            flash('User not deleted', 'warning')
        return redirect(url_for('manage_users'))

    user = User.get_by_id(session['user'])
    return render_template('delete_user.html', user=user, user_to_delete=user_to_delete)
Beispiel #13
0
def logout():
    form = LoginForm(csrf_enabled=False)
    if(current_user.is_authenticated):
        logout_user()
        return redirect('/auth/login')
    else:
        return redirect('/auth/login')
Beispiel #14
0
 def f(*args,**kwargs):
     if not 'user' in session:
         return redirect(url_for("login-required"))
     user = get_user_object()
     if 'user' in session and not user:
         return redirect(url_for('logout'))
     return func(*args, user=user,**kwargs)
Beispiel #15
0
    def post(self, entry_id):
        if entry_id is None:
            # Add a new entry
            form_class = self.create_form(config=current_app.config)
            form = form_class()
            if form.validate_on_submit():
                image = request.files['image']
                self.model.bl.save_image(
                    image=image,
                    img_category=form.data['img_category'],
                    title=form.data['title'],
                    description=form.data['description'],
                )
                return redirect(url_for("admin." + self.success_url))

        else:
            # Update an old entry
            instance = self.model.bl.get(entry_id)
            form_class = self.update_form(
                config=current_app.config,
                is_update=True,
            )
            form = form_class(obj=instance)
            if form.validate_on_submit():
                instance.bl.update(form.data)
                return redirect(url_for("admin." + self.success_url))

        return self.render_response(entry_form=form)
def reset_password():
    if current_user.is_authenticated:  # Prevent password reset if already logged in
        return redirect(url_for('index'))
    form = PasswordResetForm()
    if form.validate_on_submit() and session['settings']['mail']:  # pragma: no cover
        user = UserMapper.get_by_email(form.email.data)
        if not user:
            logger.log('info', 'password', 'Password reset for non existing ' + form.email.data)
            flash(_('error non existing email'), 'error')
        else:
            code = UserMapper.generate_password()
            user.password_reset_code = code
            user.password_reset_date = datetime.datetime.now()
            user.update()
            link = request.scheme + '://' + request.headers['Host']
            link += url_for('reset_confirm', code=code)
            subject = _('Password reset request for %(site_name)s',
                        site_name=session['settings']['site_name'])
            body = _('We received a password reset request for %(username)s',
                     username=user.username)
            body += ' ' + _('at') + ' '
            body += request.headers['Host'] + '\n\n' + _('reset password link') + ':\n\n'
            body += link + '\n\n' + _('The link is valid for') + ' '
            body += str(session['settings']['reset_confirm_hours']) + ' ' + _('hours') + '.'
            if send_mail(subject, body, form.email.data):
                flash(_('A password reset confirmation mail was send to %(email)s.',
                        email=form.email.data), 'info')
            else:
                flash(_('Failed to send password reset confirmation mail to %(email)s.',
                        email=form.email.data), 'error')
            return redirect(url_for('login'))
    return render_template('login/reset_password.html', form=form)
Beispiel #17
0
def publish(msg):


#    print msg
    #print url
    code_obj = Code.objects.first()
    client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
    try:
        if code_obj and code_obj.access_token and code_obj.expires_in:
            pass
        else:
            if not code_obj:
                return redirect(client.get_authorize_url())
            r = client.request_access_token(code_obj.code)
            code_obj.access_token = r.access_token # 新浪返回的token,类似abc123xyz456
            code_obj.expires_in = r.expires_in # token过期的UNIX时间:http://zh.wikipedia.org/wiki/UNIX%E6%97%B6%E9%97%B4
            code_obj.save()

        access_token = code_obj.access_token
        expires_in = code_obj.expires_in

        assert access_token
        print expires_in
        ### TODO: 在此可保存access token
        print "access_token", access_token
        print 'expires_in', expires_in
        client.set_access_token(access_token, expires_in)
        #
        print client.get.statuses__user_timeline()
        print client.post.statuses__update(status=msg)
    except:
        return redirect(client.get_authorize_url())
Beispiel #18
0
def login():
    if session.get("usid"):
        return redirect("/user_home")
    
    if request.method == "POST":
        email = request.form.get("email")
        password = request.form["password"]
        
        cnx = db_connect()
        cur = cnx.cursor()
        
        stmt_select = "select uid, firstname, pwdhash from users where email = %s;"
        names = [email]
        
        cur.execute(stmt_select, names)
        row = cur.fetchone()
     
        if row:
            data = {
                "uid":row[0],
                "firstname":row[1],
                "pwdhash":row[2],
            }
            
            if password == data["pwdhash"]:
                session["usid"] = data["uid"]
                session["firstname"] = data["firstname"]
                return redirect("/user_home")
            else:
                return render_template("login.html", pwdwrong = True)
        else:
            return render_template("login.html", emailwrong = True) 
          
    elif request.method == "GET":
        return render_template("login.html")
Beispiel #19
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())
 def on_cell(self, request, image_id, cell_id):
     auto = int(request.args.get('auto','0'))
 
     new_label = request.args.get('label',None)
     if 'key' in request.args:
         new_label = chr(int(request.args['key']))
     if new_label and new_label not in self.labels:
         new_label = None
     
     if new_label is not None:
         labels = self.work.get_labels(image_id)
         if new_label == '':
             labels[cell_id] = None
         else:
             labels[cell_id] = new_label
         self.work.set_labels(image_id, labels)
         if auto:
             return redirect('/next')
         return redirect('/image/%d' % image_id)
         #return redirect('/cell/%d/%d' % (image_id, cell_id))
     
     image_name = self.work.index[image_id]
     current_label = self.work.get_labels(image_id)[cell_id]
     
     measure = self.work.get_measure(image_id)        
     
     if not self.work.has_classification(image_id):
         call = None
     else:
         c = self.work.get_classification(image_id)
         call = c.call[cell_id]
 
     return self._response('cell.html', locals())
Beispiel #21
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'))
Beispiel #22
0
    def save_update(self):
        id = _g('id', None)
        if not id :
            flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR)
            return redirect(url_for('.view'))
        obj = DBSession.query(Customer).get(id)
        if not obj :
            flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR)
            return redirect(url_for('.view'))
        try:
            fields = ['no', 'name', 'display_name', 'province_id', 'city_id',
                      'address', 'contact_person', 'mobile', 'phone', 'email', 'note_id', 'remark']
            old_info = obj.serialize(fields) # to used for the history log
            for f in fields:
                setattr(obj, f, _g(f))

            #handle the file upload
            old_attachment_ids = map(lambda (k, v) : v, _gp("old_attachment_"))
            old_attachment_ids.extend(multiupload())
            obj.attachment = old_attachment_ids

            DBSession.commit()
            flash(MSG_SAVE_SUCC, MESSAGE_INFO)
#            return redirect(url_for('.view',id=obj.id))
            new_info = obj.serialize(fields)
            change_result = obj.compare(old_info, new_info)
            obj.insert_system_logs(change_result)
        except:
            _error(traceback.print_exc())
            DBSession.rollback()
            flash(MSG_SERVER_ERROR, MESSAGE_ERROR)
        return redirect(url_for('.view', action = "view", id = obj.id))
Beispiel #23
0
 def permission(self):
     method = _g('m', 'LIST')
     if method not in ['LIST', 'NEW', 'UPDATE', 'DELETE', 'SAVE_NEW', 'SAVE_UPDATE']:
         flash(MSG_NO_SUCH_ACTION, MESSAGE_ERROR);
         return redirect(url_for('.view', action = 'index'))
     if method == 'LIST':
         page = _g('page') or 1
         objs = DBSession.query(Permission).filter(Permission.active == 0).order_by(Permission.name).all()
         def url_for_page(**params): return url_for('bpAdmin.view', action = 'permission', m = 'LIST', page = params['page'])
         records = paginate.Page(objs, page, show_if_single_page = True, items_per_page = PAGINATE_PER_PAGE, url = url_for_page)
         return render_template('admin/permission_index.html', records = records)
     elif method == 'NEW':
         groups = Group.all()
         return render_template('admin/permission_new.html', groups = groups)
     elif method == 'UPDATE':
         id = _g('id', None)
         if not id :
             flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR)
             return redirect(url_for('.view', action = 'permission'))
         obj = Permission.get(id)
         if not obj :
             flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR)
             return redirect(url_for('.view', action = 'permission'))
         gids = map(lambda v:v.id, obj.groups)
         all_groups = Group.all()
         return render_template('admin/permission_update.html', v = obj.populate(), gids = gids, all_groups = all_groups)
     elif method == 'DELETE':
         id = _g('id', None)
         if not id :
             flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR)
             return redirect(url_for('.view', action = 'permission'))
         obj = Permission.get(id)
         if not obj :
             flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR)
             return redirect(url_for('.view', action = 'permission'))
         obj.active = 1
         obj.groups = []
         DBSession.commit()
         flash(MSG_DELETE_SUCC, MESSAGE_INFO)
         return redirect(url_for('.view', action = 'permission'))
     elif method == 'SAVE_NEW':
         obj = Permission.saveAsNew(request.values)
         obj.groups = DBSession.query(Group).filter(Group.id.in_(_gl("gids"))).all()
         DBSession.commit()
         flash(MSG_SAVE_SUCC, MESSAGE_INFO)
         return redirect(url_for('.view', action = 'permission'))
     elif method == 'SAVE_UPDATE':
         id = _g('id', None)
         if not id :
             flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR)
             return redirect(url_for('.view', action = 'permission'))
         obj = Permission.get(id)
         if not obj :
             flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR)
             return redirect(url_for('.view', action = 'permission'))
         obj.saveAsUpdate(request.values)
         obj.groups = DBSession.query(Group).filter(Group.id.in_(_gl('gids'))).all()
         obj.commit()
         flash(MSG_UPDATE_SUCC, MESSAGE_INFO)
         return redirect(url_for('.view', action = 'permission'))
Beispiel #24
0
def login():
    """
    Show the login page and handle login requests.

    :return: The login page.
    :rtype: flask.Response
    """
    if request.method == 'POST':
        try:
            username = request.form.get('username', None)
            password = request.form.get('password', None)

            if username is None or password is None:
                flash('Invalid data', 'danger')
                return redirect(url_for('login'))

            user = User.query().filter_by(username=username).first()
            if user is None or not user.check_password(password):
                flash('Invalid login credentials', 'danger')
            else:
                flash('You were logged in successfully!', 'success')
                session['logged_in'] = True
                session['user'] = user.id

                if request.args.get('next', None):
                    return redirect(request.args['next'])
                return redirect(url_for('main_page'))
        except KeyError:
            flash('Missing username or password', 'info')
    return render_template('login.html')
Beispiel #25
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)
Beispiel #26
0
def test_redirect_xss():
    location = 'http://example.com/?xss="><script>alert(1)</script>'
    resp = utils.redirect(location)
    assert b'<script>alert(1)</script>' not in resp.get_data()

    location = 'http://example.com/?xss="onmouseover="alert(1)'
    resp = utils.redirect(location)
    assert b'href="http://example.com/?xss="onmouseover="alert(1)"' not in resp.get_data()
Beispiel #27
0
def upload():
    file = request.files['file']
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return redirect(url_for('index'))
    else:
        return redirect(url_for('admin'))
 def on_next(self, request):
     if not self.interesting:
         self.interesting = select_interesting(self.work, 10)
     if not self.interesting:
         self.message = 'No more cells to classify.'
         return redirect('/')
     image_id, cell_id = self.interesting.pop(0)
     return redirect('/cell/%d/%d?auto=1' % (image_id,cell_id))
Beispiel #29
0
    def test_redirect_xss(self):
        location = 'http://example.com/?xss="><script>alert(1)</script>'
        resp = utils.redirect(location)
        self.assert_not_in(b'<script>alert(1)</script>', resp.get_data())

        location = 'http://example.com/?xss="onmouseover="alert(1)'
        resp = utils.redirect(location)
        self.assert_not_in(b'href="http://example.com/?xss="onmouseover="alert(1)"', resp.get_data())
Beispiel #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"))
Beispiel #31
0
def show_product_page(item_name):
    form = AddToBuy()
    review_form = CreateReviewForm()
    _item_name = item_name
    db_sess = db_session.create_session()
    product_page_content = sqlite3.connect('db/store.sqlite3').cursor(
    ).execute(
        f'''SELECT * FROM items WHERE title == "{item_name}"''').fetchone()

    item_id = db_sess.query(Items).filter_by(title=_item_name).first().id

    reviews = db_sess.query(Review).filter_by(item_id=item_id).all()[::-1]
    reviews_amount = len(reviews)

    if review_form.validate_on_submit():
        db_sess = db_session.create_session()
        review = Review(title=review_form.title.data,
                        review=review_form.review.data,
                        rating=review_form.rating.data,
                        item_id=item_id,
                        username=db_sess.query(User).filter_by(
                            id=current_user.id).first().name)

        db_sess.add(review)
        db_sess.commit()

        mess_sym = emoji.emojize(':thumbs_up:')

        return render_template(
            'product_page.html',
            title='Отзыв оставлен (он появится после обновления страницы)',
            form=form,
            review_form=review_form,
            reviews=reviews,
            reviews_amount=reviews_amount,
            item_name=product_page_content[2],
            item_price=product_page_content[5],
            item_description=product_page_content[3],
            image_name=product_page_content[4][7::],
            review_message=f"Спасибо за отзыв {mess_sym}")

    if form.validate_on_submit():
        db_sess = db_session.create_session()
        if str(item_id) in db_sess.query(Basket).filter_by(
                user_id=current_user.id).first().items_id:
            return render_template(
                'product_page.html',
                title='Вы уже добавили данный товар в корзину',
                form=form,
                review_form=review_form,
                reviews=reviews,
                reviews_amount=reviews_amount,
                item_name=product_page_content[2],
                item_price=product_page_content[5],
                item_description=product_page_content[3],
                image_name=product_page_content[4][7::],
                message="Такой товар уже есть")

        db_sess.query(Basket).filter_by(
            user_id=current_user.id).first().items_id += f',{item_id}'
        db_sess.commit()

        return redirect('/')

    return render_template('product_page.html',
                           form=form,
                           review_form=review_form,
                           reviews=reviews,
                           reviews_amount=reviews_amount,
                           item_category=product_page_content[1],
                           item_name=product_page_content[2],
                           item_price=product_page_content[5],
                           item_description=product_page_content[3],
                           image_name=product_page_content[4][7::])
Beispiel #32
0
def edit_switch(switch_id):
    form = SwitchForm()
    session = db_session.create_session()
    # заполнение вариантов для выпадающих чекбоксов
    all_users = [(user.id, user.name) for user in session.query(User).filter(
        User.house_id == current_user.house_id).all()]
    form.editors.choices = all_users
    form.users.choices = all_users
    switch = session.query(Switch).filter(Switch.id == switch_id).first()
    if switch:  # проверка существования
        if current_user in switch.editors or switch.public_edit:  # проверка прав
            if request.method == 'GET':
                form.title.data = switch.title
                form.personal_name.data = switch.personal_name
                form.editors.data = [user.id for user in switch.editors]
                form.users.data = [user.id for user in switch.users]
                return render_template('switch.html',
                                       title='Редактирование модуля',
                                       form=form,
                                       item=switch)

            elif form.validate_on_submit():
                # проверка ункальности названия
                if session.query(Switch).filter(
                        Switch.title == form.title.data,
                        Switch.id != switch_id,
                        Switch.house_id == switch.house_id).first():
                    return render_template('switch.html',
                                           title='Редактирования модуля',
                                           form=form,
                                           message='Имя модуля уже занято',
                                           item=switch)
                # проверка уникальности порта
                elif session.query(Switch).filter(
                        Switch.personal_name == form.personal_name.data,
                        Switch.id != switch_id,
                        Switch.house_id == switch.house_id).first():
                    return render_template(
                        'switch.html',
                        title='Редактирования модуля',
                        form=form,
                        message='"Этот порт уже используется"',
                        item=switch)
                switch.title = form.title.data
                switch.personal_name = form.personal_name.data
                # изменение списка пользователей:
                for user in switch.users:  # удаление лишних
                    if user.id not in form.users.data:
                        switch.users.remove(user)
                for user_id in form.users.data:  # добавление новых
                    user = session.query(User).filter(
                        User.id == user_id).first()
                    if user not in switch.users:
                        switch.users.append(user)

                # изменение списка редакторов:
                for user in switch.editors:  # удаление лишних
                    if user.id not in form.editors.data:
                        switch.editors.remove(user)
                for user_id in form.editors.data:  # добавление новых
                    user = session.query(User).filter(
                        User.id == user_id).first()
                    if user not in switch.editors:
                        switch.editors.append(user)

                switch.public_edit = not bool(switch.editors)
                switch.public_use = not bool(switch.users)
                session.merge(switch)
                session.commit()
                return redirect('/')
        else:
            abort(403)
    else:
        abort(404)
Beispiel #33
0
def logout():
    session.pop('admin', None)
    return redirect(url_for('admin.login'))
Beispiel #34
0
 def sort_down():
     manager.sort(down=True)
     return redirect(url_for('index'))
Beispiel #35
0
def edit_group(group_id):
    form = GroupForm()
    session = db_session.create_session()
    user = session.query(User).filter(User.id == current_user.id).first()
    # добавление вариантов выпадающих чекбоксов
    all_users = [(user.id, user.name) for user in session.query(User).filter(
        User.house_id == current_user.house_id).all()]
    form.editors.choices = all_users
    form.users.choices = all_users
    usable_switches = user.usable_switches + session.query(Switch).filter(
        Switch.public_use == 1, Switch.house_id == user.house_id).all()
    form.switches.choices = [(s.id, s.title) for s in usable_switches]
    group = session.query(Group).filter(Group.id == group_id).first()
    if group:  # проверка существования
        if current_user in group.editors or group.public_edit:  # проверка прав
            if request.method == 'GET':
                form.title.data = group.title
                form.editors.data = [user.id for user in group.editors]
                form.users.data = [user.id for user in group.users]
                form.switches.data = [switch.id for switch in group.switches]
                return render_template('group.html',
                                       title='Редактирование группы',
                                       form=form,
                                       item=group)

            elif form.validate_on_submit():
                # проверка уникальности названия
                if session.query(Group).filter(
                        Group.title == form.title.data, Group.id != group_id,
                        Group.house_id == group.house_id).first():
                    return render_template('group.html',
                                           title='Редактирования группы',
                                           form=form,
                                           message='Имя группы уже занято',
                                           item=group)
                # проверка что группа не пустая
                elif not form.switches.data:
                    return render_template(
                        'group.html',
                        title='Редактирования группы',
                        form=form,
                        message='В группе нет ни одного модуля',
                        item=group)
                group.title = form.title.data
                # изменение списка пользователей:
                for user in group.users:  # удаление лишних
                    if user.id not in form.users.data:
                        group.users.remove(user)
                for user_id in form.users.data:  # добавление новых
                    user = session.query(User).filter(
                        User.id == user_id).first()
                    if user not in group.users:
                        group.users.append(user)

                # изменение списка редакторов:
                for user in group.editors:  # удаление лишних
                    if user.id not in form.editors.data:
                        group.editors.remove(user)
                for user_id in form.editors.data:  # добавление новых
                    user = session.query(User).filter(
                        User.id == user_id).first()
                    if user not in group.editors:
                        group.editors.append(user)

                # изменение списка модулей:
                for switch in group.switches:  # удаление старых
                    if switch.id not in form.switches.data:
                        group.switches.remove(switch)
                for switch_id in form.switches.data:  # добавление новых
                    switch = session.query(Switch).filter(
                        Switch.id == switch_id).first()
                    if switch not in group.switches:
                        group.switches.append(switch)

                group.public_edit = not bool(group.editors)
                group.public_use = not bool(group.users)
                session.merge(group)
                session.commit()
                return redirect('/groups_list')
        else:
            abort(403)
    else:
        abort(404)
Beispiel #36
0
 def authorize_s2s_create(self, **post):
     acquirer_id = int(post.get('acquirer_id'))
     acquirer = request.env['payment.acquirer'].browse(acquirer_id)
     acquirer.s2s_process(post)
     return utils.redirect("/payment/process")
Beispiel #37
0
 def decorated_function(*args, **kwargs):
     if current_user is None or current_user.is_authenticated() is False:
         return redirect(url_for('Login.login', next=request.url))
     return f(*args, **kwargs)
Beispiel #38
0
    def wrapped_view(*args, **kwargs):
        if "admin" not in session:
            return redirect(url_for("admin.login"))

        return view(*args, **kwargs)
Beispiel #39
0
 def good_remove(good_id):
     manager.good_remove(good_id)
     return redirect(url_for('index'))
Beispiel #40
0
 def decorated_function(*args, **kwargs):
     if current_user.is_admin():
         return f(*args, **kwargs)
     return redirect(url_for('Common.unauthorized'))
Beispiel #41
0
def departure_board_index_html():
    return redirect("ui//departure-board/index.html", code=302)
Beispiel #42
0
def logout():
    logout_user()
    return redirect("/")
Beispiel #43
0
def logout():
    session.pop('user')
    return redirect('/dashboard')
Beispiel #44
0
def external_subdomain_redirect_demo_app(environ, start_response):
    if 'test.example.com' in environ['HTTP_HOST']:
        response = Response('redirected successfully to subdomain')
    else:
        response = redirect('http://test.example.com/login')
    return response(environ, start_response)
Beispiel #45
0
def external_redirect_demo_app(environ, start_response):
    response = redirect('http://example.com/')
    return response(environ, start_response)
Beispiel #46
0
def delete(sno):
    if ('user' in session and session['user'] == params['admin_user']):
        post = Posts.query.filter_by(sno=sno).first()
        db.session.delete(post)
        db.session.commit()
    return redirect('/dashboard')
Beispiel #47
0
 def decorated_function(*args, **kwargs):
     if 'email' not in session.keys() or session['email'] is None:
         return redirect(url_for('users.login_user', next=request.path))
     return func(*args, **kwargs)
Beispiel #48
0
 def wrapped_view(**kwargs):
     if g.user is None:
         return redirect(url_for('auth.login'))
     return view(**kwargs)
Beispiel #49
0
 def decorated_function(*args, **kwargs):
     if 'email' not in session.keys() or session['email'] is None:
         return redirect(url_for('users.login_user', next=request.path))
     if session['email'] not in config.ADMINS:
         return redirect(url_for('users.login_user', message="Not logged in as admin!"))
     return func(*args, **kwargs)
Beispiel #50
0
def logout():
    logout_user()
    flash('You\'ve been successfully logged out', category='success')
    return redirect(url_for('auth.login'))
Beispiel #51
0
def save_form_1():
    email = session['email']
    if request.method == 'POST':
        current_address_line_1 = request.form.get('current_address_line_1')
        current_address_line_2 = request.form.get('current_address_line_2')
        current_address = current_address_line_1 + " " + current_address_line_2
        permanent_address_line_1 = request.form.get('permanent_address_line_1')
        permanent_address_line_2 = request.form.get('permanent_address_line_2')
        permanent_address = permanent_address_line_1 + " " + permanent_address_line_2
        tel_no = request.form.get('tel_no')
        email = session['email']
        # email = request.form.get('email')
        nationality = request.form.get('nationality')
        disability = request.form.get('disability')

        education = {}
        course_list = ['tenth', 'twelfth', 'graduate', 'postgraduate']
        for i in course_list:
            if request.form.get(i):
                education[i if request.form.get(i) is not None else None] = {
                    'from': request.form.get('from_' + str(i)),
                    'till': request.form.get('till_' + str(i)),
                    'school': request.form.get('school_' + str(i)),
                    'board': request.form.get('board_' + str(i)),
                }
            else:
                pass

        languages = {
            'hindi': {
                'understand':
                'yes'
                if request.form.get('hindi_understand') is not None else 'no',
                'speak':
                'yes' if request.form.get('hindi_speak') is not None else 'no',
                'read_write':
                'yes'
                if request.form.get('hindi_read_write') is not None else 'no'
            },
            'english': {
                'understand':
                'yes' if request.form.get('english_understand') is not None
                else 'no',
                'speak':
                'yes'
                if request.form.get('english_speak') is not None else 'no',
                'read_write':
                'yes'
                if request.form.get('english_read_write') is not None else 'no'
            }
        }

        references = {
            'first': {
                'full_name': request.form.get('first_name'),
                'address': request.form.get('first_address'),
                'tel_no': request.form.get('first_tel_no'),
                'email': request.form.get('first_email'),
                'occupation': request.form.get('first_occupation'),
                'relation': request.form.get('first_relation')
            },
            'second': {
                'full_name': request.form.get('second_name'),
                'address': request.form.get('second_address'),
                'tel_no': request.form.get('second_tel_no'),
                'email': request.form.get('second_email'),
                'occupation': request.form.get('second_occupation'),
                'relation': request.form.get('second_relation')
            }
        }

        about_you = request.form.get('about_you')
        why_volunteer = request.form.get('why_volunteer')
        communities_associated = request.form.get('communities_associated')
        motivation = request.form.get('motivation')
        file = request.files.get('file')
        new_file_name = None

        # form 1 status is saved by default.
        # If the form is final, then add the last parameter to Form constructor as 'submit'
        try:
            if file and file.filename == '':
                return 'The uploaded file has no filename.'
            if file and Utils.allowed_file(file.filename):
                filename = secure_filename(file.filename)
                email = session['email']
                user = User.get_user_object(email=email)
                filename_list = filename.split('.')
                new_file_name = os.path.normpath(
                    os.path.join(
                        UPLOAD_FOLDER_PROFILE_PICTURES_PATH, user._id + "." +
                        filename_list[len(filename_list) - 1]))
                user.photo_path = new_file_name
                if os.path.exists(new_file_name):
                    os.remove(new_file_name)
                file.save(new_file_name)
            form_1 = Form1(current_address=current_address,
                           permanent_address=permanent_address,
                           tel_no=tel_no,
                           email=email,
                           nationality=nationality,
                           disability=disability,
                           languages=languages,
                           education=education,
                           about_you=about_you,
                           why_volunteer=why_volunteer,
                           communities_associated=communities_associated,
                           motivation=motivation,
                           references=references,
                           photo_path=new_file_name)
            form_1.save_form_to_db()
            return 'form 1 has been saved successfully'
        except Form1Errors.Form1Error as e:
            return e.message
    else:
        session['email'] = email
        return redirect(url_for('users.user_dashboard'))
Beispiel #52
0
def logout():
    logout_user()
    return redirect(url_for('main.home'))
Beispiel #53
0
 def _redirect_to_index(self, unused_request):
     return utils.redirect('/')
Beispiel #54
0
def logout():
    session.clear()
    flash("Vous avez été déconnecté")
    return redirect(url_for("root"))
Beispiel #55
0
def logout():
    session.clear()
    return redirect(url_for('main.index'))
Beispiel #56
0
 def sort_up():
     manager.sort(down=False)
     return redirect(url_for('index'))
Beispiel #57
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        return redirect('/')
    return render_template('login.html', title='Авторизация', form=form)
Beispiel #58
0
def route_map_index_html():
    return redirect("ui/route-map/index.html", code=302)
Beispiel #59
0
def redirect_loop_app(environ, start_response):
    response = redirect('http://localhost/some/redirect/')
    return response(environ, start_response)
Beispiel #60
0
def mkdir(folder: str):
    os.makedirs(cfg.CLOUD_PATH / folder)

    log("User %r made dir %r", get_user(), folder)
    return redirect("/cloud")