예제 #1
0
    def create_by_webapp(self):
        submission = Submission()
        submission.submission_id = time.time() * 1000
        submission.number_of_points = 1
        submission.user_id = current_user.get_id()
        submission.revised = False
        submission.approved = False
        db.session.add(submission)
        db.session.flush()
        new_point = Point()
        new_point.geom = "POINT({} {})".format(request.form['latitude'], request.form['longitude'])
        new_point.properties = json.loads(request.form['properties'])
        new_point.revised = False
        new_point.approved = False
        new_point.submission_id = submission.id
        db.session.add(new_point)
        db.session.flush()
        if 'images[]' in request.files:
            image = request.files['images[]']
            new_picture = self.__make_picture(submission.id, new_point.id, submission.user_id)
            directory = "app/static/uploads/submissions/" + str(submission.id)
            if not os.path.exists(directory):
                os.makedirs(directory)
            image.save(directory + "/" + str(new_point.id) + ".jpg")
            new_picture.filepath = "static/uploads/submissions/" + str(submission.id) + "/" + str(new_point.id) + ".jpg"
            db.session.add(new_picture)

        db.session.query(User).filter(User.id == current_user.get_id()) \
            .update({User.activity_points: User.activity_points + 1,
                     User.activity_points_total: User.activity_points_total + 1},
                    synchronize_session=False)
        db.session.commit()
        resp = Response(json.dumps({"status": "ok", "point": str(new_point)}))
        resp.headers['Content-Type'] = "application/json"
        return resp
예제 #2
0
def upload_documents():
    data = request.json.get('data', None)
    if not data:
        return jsonify(status=400, message='No file content passed')

    data = data.decode("base64")
    upload_handler = get_upload_handler()

    # force is a flag that signals to upload the current file even if it was uploaded before
    force = request.json.get('force', None)
    if force is None or force.lower() != "true":
        if upload_handler.is_file_already_uploaded(data, current_user.get_id()):
            return jsonify(status=400, message='File content was already uploaded. Force upload by adding the force boolean')

    blob_service = BlobService(account_name=BLOB_ACCOUNT_NAME, account_key=BLOB_ACCOUNT_KEY)
    filename = uuid.uuid4().hex
    # put the data in the container using a random filename
    blob_service.put_block_blob_from_bytes(BLOB_CONTAINER_NAME, filename, data)

    task_collection = get_db().task_collection
    
    # update the task db with the new task (which is parsing the new data file)
    task_id = upload_handler.update_uploaded_file(filename, data, current_user.get_id())

    return jsonify(status=200, message='Task created successfully', task_id=task_id)
예제 #3
0
def create_project():
    # with lock:
    # form = CreateProjectForm(request.form)
    # if request.method == 'POST' and form.validate_on_submit():
    debug_set = current_app.config["DEBUG"]
    if debug_set == True:
        print "\n\n\n==========> account->views.py -> create_project() "
        # print "=====> is_private() :", form.is_private.data

    form = CreateProjectForm()
    if form.validate_on_submit():
        new_proj = Project(
            prj_name=form.name.data,
            prj_desc=form.desc.data,
            is_private=form.is_private.data,
            owner=current_user.get_id(),
        )
        prj_id = new_proj.save()
        # Add a user as an owner of a project
        proj = Project.get_project_for_projectid(prj_id)
        print "project.is_private 2:", proj.is_private
        owner_name = current_user.firstname + " " + current_user.lastname
        proj.add_member(name=owner_name, email=current_user.get_id(), role=Project.ROLE_OWNER)
        flash("New project has been created.", category="index_page")
        # Generate a project owner's appkey & save it to ProjectMemberKey coll.
        # keygen = KeyGenerator()
        # key = keygen.getkey(settings.APPKEY_LENGTH)
        key = utils.generate_key()
        prjmemkey = ProjectMemberKey(prj_id=proj.prj_id, appkey=key, member_email=proj.owner)
        prjmemkey.save()
        return redirect(url_for(".list_projects"))

    return render_template("create_project.html", form=form)
예제 #4
0
def set_user_cookie_id():
    """
    Sets the user id in the global object if nothing is there 
    before each request
    This function works together with set_user_cookie in the after requests
    """
    #new fresh user
    if not request.cookies.get(config.COOKIE_ADSABS2_NAME):
        if current_user.is_anonymous():
            g.user_cookie_id = unicode(uuid.uuid4())
        else:
            g.user_cookie_id = current_user.get_id()
    #the user has already visited the web site
    else:
        if current_user.is_anonymous():
            #if the cookie is a valid UUID it's ok
            curr_cookie = request.cookies.get(config.COOKIE_ADSABS2_NAME)
            try:
                uuid.UUID(curr_cookie)
                g.user_cookie_id = curr_cookie
            #otherwise the app generates a new one
            except ValueError:
                g.user_cookie_id = unicode(uuid.uuid4())
        else:
            g.user_cookie_id = current_user.get_id()
예제 #5
0
def settings():
    # change preferred genres
    # update balance

    # get permissions from db
    db.execute(
        'SELECT fave_perm, rank_perm, watched_perm, balance FROM users WHERE user_id = %s',
        (current_user.get_id()))
    results = db.fetchall()[0]
    perms = {}
    perms['fave'] = results[0]
    perms['rank'] = results[1]
    perms['watch'] = results[2]

    balance = results[3]

    # get preferred genres from db
    db.execute(
        'SELECT genre_name FROM prefers, genre WHERE prefers.user_id = %s AND prefers.genre_id = genre.genre_id',
        (current_user.get_id()))
    results = db.fetchall()
    genres = [genre[0] for genre in results]
    genre_string = ', '.join(genres)

    return flask.render_template('settings.html',
                                 perms=perms,
                                 genres=genre_string,
                                 balance=balance)
예제 #6
0
def recommendations():

    user_id = current_user.get_id()

    if not user_id:
        flash('Recommendations are only available if you have an account.') 
        return render_template('/main/recommendations.html', recommendations=[])

    else:
        rated_movies = Rating.get_ratings(current_user.get_id())

        # the user needs to have rated some movies to be able to receive recommendations
        if len(rated_movies.keys()) == 0 and current_user.get_id():
            flash('No Recommendations found, please rate some movies.') 
            return render_template('/main/recommendations.html', recommendations=[], timestamp=None)

        try:
            timestamp = Recommendation.get_latest_recommendation_timestamp()
            (recommendation_type, recommendations) = \
                    Recommendation.get_recommendations(current_user.get_id())

        except RecommendationsNotGeneratedException:
            flash('No recommendations available - the Recommendation process has not run yet.') 
            return render_template('/main/recommendations.html', recommendations=[])
        except RecommendationsNotGeneratedForUserException:
            flash('No Recommendations found, please rate some movies.') 
            return render_template('/main/recommendations.html', recommendations=[], timestamp=timestamp)

        if recommendation_type:
            flash("Recommendation type: " + recommendation_type)

        return render_template('/main/recommendations.html', recommendations=recommendations, timestamp=timestamp)
예제 #7
0
def handle_game_submit(game):
    COOP = 1
    DEF = 0
    if game == 1:
        group_name = request.form['group_name']
        value = request.form['bid']
        if int(value) == 50:
            return redirect('/gameone?error=50')
        game1.set_bid(db, group_name, value)
        return redirect('/gameone')
    elif game == 2:
        try:
            value = float(request.form['bid'])
        except ValueError:
            return 'Invalid value'
        game2.set_value(db, current_user.get_id(), value)
        return redirect('/game2')
    elif game == 3:
        action = int(request.form['action'])
        group_name = request.form['group_name']
        game3.set_action(db, group_name, current_user.get_id(), action)
        return redirect('/thirdgame')
    elif game == 4:
        action = int(request.form['action'])
        group_name = request.form['group_name']
        action = int(request.form['action'])
        game4.set_choice(db, group_name, current_user.get_id(), action)
        return redirect('/4')
    return 'idk'
def membership_signup(provider):
    web.template.create('Maidstone Hackspace')
    header('Maidstone Hackspace Member registration')

    provider = payment(provider=provider, style='payment')

    payment_details = provider.subscribe_confirm(request.args)
    try:
        web.page.create('Thanks for becoming a member.')
        web.paragraph.create(
            """Your membership request has been recieved and will be active shortly.""")
    except:
        # TODO log what actually has gone wrong
        web.page.create('Something went wrong')
        web.paragraph.create(
            """We could not confirm the payment something may have gone terribly wrong.""")

    if payment_details is None:
        return redirect('/profile/membership/failure')

    update_membership_status().execute({'user_id': current_user.get_id(), 'status': '1'})
    #update_membership().execute({'user_id': str(current_user.get_id()), 'status': '1', 'join_date': details.get('start_date'), 'amount': details.get('amount'), 'subscription_reference': details.get('reference')})

    #update_membership_status().execute({'user_id': user_id, 'status': '1'})
    create_membership().execute({
        'user_id': current_user.get_id(), 
        'status': '1', 
        'join_date': payment_details.get('start_date'), 
        'amount': payment_details.get('amount'), 
        'subscription_reference': payment_details.get('reference')})

    web.page.section(web.paragraph.render())
    web.template.body.append(web.page.render())
    return footer()
예제 #9
0
파일: views.py 프로젝트: AsmNoob/Villo
def logout():
	if current_user.get_id() in User.users:
		del User.users[current_user.get_id()]
		logout_user()
		return redirect(url_for("index"))
	else:
		return redirect(url_for("login"))
예제 #10
0
def create_project():
    #with lock:
    form = CreateProjectForm(request.form)
    if request.method == 'POST' and form.validate():
        new_proj = Project(prj_name=form.name.data, prj_desc=form.desc.data,
            is_private=form.is_private.data, owner=current_user.get_id())
        print 'project.is_private:', new_proj.is_private
        prj_id = new_proj.save()
        # Add a user as an owner of a project
        proj = Project.get_project_for_projectid(prj_id)
        print 'project.is_private 2:', proj.is_private
        owner_name = current_user.firstname + ' ' + current_user.lastname
        proj.add_member(name=owner_name, email=current_user.get_id(), 
            role=Project.ROLE_OWNER)
        flash("New project has been created.", category='index_page')
        # Generate a project owner's appkey & save it to ProjectMemberKey coll.
        #keygen = KeyGenerator()
        #key = keygen.getkey(APPKEY_LENGTH)
        key = utils.generate_key()
        prjmemkey = ProjectMemberKey(prj_id=proj.prj_id, appkey=key, 
            member_email=proj.owner)
        prjmemkey.save()
        return redirect(url_for('.list_projects'))

    return render_template('create_project.html', form=form)
예제 #11
0
def share():
    data = request.get_json()
    user_email = data["email"]
    file_id = data["file"]
    target_user = models.User.query.filter_by(email=user_email).first()
    response = None
    if target_user:
        try:
            target_file = models.File.query.filter_by(id=file_id).first()
            target_file.share_file(target_user)
            db.session.commit()
            flash(
                "You successfully shared your file with {}".format(user_email),
                "positive")
            logger.info("File shared by {} to {}".format(
                current_user.get_id(), target_user.get_id()),
                        user=current_user.get_id())
            return jsonify(dict(success=True, message='File shared!'))
        except Exception as e:
            flash(
                "Error encountered while sharing file, contact an admin or try again",
                "negative")
            logger.error("Exception encountered {}".format(e),
                         user=current_user.get_id())
            response = {"message": "error"}
            pass
    if response is None:
        response = {"status": 200}
    return jsonify(result=response)
예제 #12
0
def apiAdmin():
    if not current_user.is_admin():
        return 'Not Authorized', 500
    if request.args.get('req') == 'submissions':
        dic = {}
        regex = r'(?:.*?/)+(.*?)_(.*?)'+OUTPUT
        for filename in glob.glob(os.path.join(OUTPUT_DIR, '*')):
            username = re.search(regex, filename).group(2)
            dataset = re.search(regex, filename).group(1)
            if username not in dic:
                dic[username] = {}
            if dataset not in dic[username]:
                dic[username][dataset] = {}
            with codecs.open(filename, 'r', 'utf-8') as f:
                dic[username][dataset] = [json.loads(line) for line in f.readlines()]
        return render_template('viewSubmissions.html', displayDict=dic, 
                           username=current_user.get_id())
    elif request.args.get('req') == 'assignments':
        dic = {}
        regex = r'(?:.*?/)+data/(.*?)\.json'
        for filename in glob.glob(os.path.join(DATA_DIR, '*.json')):
            dataset = re.search(regex, filename).group(1)
            with codecs.open(filename, 'r', 'utf-8') as f:
                dic[dataset] = [json.loads(line) for line in f.readlines()]
        return render_template('viewAssignments.html', dic=dic, 
                           username=current_user.get_id())
예제 #13
0
파일: api.py 프로젝트: HEPData/hepdata3
def determine_user_privileges(recid, ctx):
    # show_review_area = not show_upload_area
    ctx['show_review_widget'] = False
    ctx['show_upload_widget'] = False
    ctx['is_submission_coordinator_or_admin'] = False

    if current_user.is_authenticated:
        user_id = current_user.get_id()
        participant_records = SubmissionParticipant.query.filter_by(
            user_account=user_id, publication_recid=recid).all()

        for participant_record in participant_records:
            if participant_record is not None:
                if participant_record.role == 'reviewer':
                    ctx['show_review_widget'] = True

                if participant_record.role == 'uploader':
                    ctx['show_upload_widget'] = True

        user = User.query.get(current_user.get_id())
        if has_role(user, 'admin'):
            ctx['is_submission_coordinator_or_admin'] = True
        else:
            matching_records = HEPSubmission.query.filter_by(
                publication_recid=recid,
                coordinator=current_user.get_id()).count()

            if matching_records > 0:
                ctx['is_submission_coordinator_or_admin'] = True

        ctx['show_upload_widget'] = (
            ctx['show_upload_widget'] or ctx[
                'is_submission_coordinator_or_admin'])
예제 #14
0
파일: app.py 프로젝트: MBloom/JukeBerry
def add() :
    form = SongForm(request.form)
    if form.validate():
        songData = form.data['song'].split(" - ")
        notTitle = songData[1].split(" (")
        artist = notTitle[0]
        album = notTitle[1].split(")")[0]
        song = models.get_song(songData[0], artist, album)
        user = models.get_user(current_user.get_id())
        print song.id
        print song.artist
        print song.album
        print song.pi_owner
        if song != None and user != None:
            uname = current_user.get_id()
            all_songs = g.db.query(Song).all()
            your_songs = g.db.query(Queue).filter_by(owner=uname).all()
            queue = g.db.query(Queue).all()
            nextSong = Queue(id=song.id, album = song.album, artist = song.artist, title = song.title, pi_owner = song.pi_owner, owner=user.name)
            qsong = models.get_qsong(songData[0], artist, album)
            if qsong == None:
                g.db.add(nextSong)
                g.db.flush()
                return redirect(url_for("home"))
                #render_template('home.html', your_songs=your_songs, uname=uname, songs=all_songs)
            else:
                return render_template('home.html', your_songs=your_songs, uname=uname, songs=all_songs, error="You've already added that song to the list!", queue=queue)
                #return render_template("home.html", ) 
            #return redirect(url_for("home"))
        return render_template("home.html", error="Song not in available list.")
    return render_template("home.html", error="Uhoh. Looks like you forgot to enter a song!")
예제 #15
0
def login():
    """For GET requests, display the login form. For POSTS, login the current user
    by processing the form."""
    if current_user.is_authenticated():
        redirect_url = request.args.get('redirect_url')
        if redirect_url:
            return redirect('http://' + redirect_url, 302)
        else:
            return redirect(
                "http://" + IP + "/view_posts?email=" + current_user.get_id(),
                302)
    form = LoginForm()
    if form.validate_on_submit():
        user = models.User.query.get(form.email.data)
        if user:
            m = md5.new()
            m.update(form.password.data)
            if user.password == buffer(m.hexdigest()):
                user.authenticated = True
                db.session.add(user)
                db.session.commit()
                login_user(user, remember=True)
                print "now will be redirect!"
                return redirect(
                    "http://" + IP + "/view_posts?email=" +
                    current_user.get_id(), 302)
    return render_template("login.html", form=form)
예제 #16
0
파일: views.py 프로젝트: nandinikg/app
def search_plant_profiles(cur=1, first=1, shift="no change"):
	search = True
	num_profiles = db.plant_profiles.find().count()
	skip = (int(cur)-1) * 8
	lim = 8
	if num_profiles%lim == 0:
		pages = (num_profiles/lim)
	else:
		pages = (num_profiles/lim)+1
	device_list = []
	grows_list = []
	plant_list =[]
	username = current_user.get_id()
	devices = db.devices.find({'username': current_user.get_id()})
	for device in devices:
		device_list.append((device['device_name'], device['type'], \
				device['sensors'], device['actuators'], device['kit'], device['device_id']))
	grows = db.grows.find({'username' : current_user.get_id()})
	for grow in grows:
		grows_list.append((grow['grow_name'], grow['device_name']))
	plants = db.plant_profiles.find({"common_name": request.args.get('search')})
	for plant in plants:
		plant_list.append(plant)
	return render_template('plant_profiles/plant_profiles.html', username=username, my_devices=device_list,\
		 my_grows=grows_list, my_plants=plant_list, pages=pages, cur=int(cur), first=int(first), search=search)
예제 #17
0
def send_presence(username):

    if ( current_user.is_authenticated() ):
        logging.info("You are already authenticated")
        if ( current_user.get_id() != username ):
            logging.info("But you are "+current_user.get_id()+", not "+username)
            response = make_response(json.dumps({'server':'presence fail (you are someone else)', 'code':'error'}), 200)
        else:
            logging.info("Presence sent ok")
            response = make_response(json.dumps({'server':'presence sent (already authenticated)', 'code':'ok'}), 200)
    else:

        User(username)
        u = User.get_stored(username)
        if ( u.taken ):
            logging.info("Cannot use this username now, it is currently taken")
            response = make_response(json.dumps({'server':'presence fail (this username is taken)', 'code':'error'}), 200)
        else:
            if ( login_user(User.get(username), remember=True) ):
                u.taken = True
                database.session.add(u)
                database.session.commit()
                logging.info("Presence sent ok (by logging)")
                response = make_response(json.dumps({'server':'presence sent (just authenticated)', 'code':'ok'}), 200)
            else:
                logging.info("Presence sent not ok (login failed)")
                response = make_response(json.dumps({'server':'presence fail (login fail)', 'code':'error'}), 200)

    response.headers["content-type"] = "application/json"
    return response
예제 #18
0
def index():
    clients = OAuthClient.query.filter_by(
        user_id=current_user.get_id(),
        is_internal=False,
    ).all()

    tokens = OAuthToken.query.options(db.joinedload('client')).filter(
        OAuthToken.user_id == current_user.get_id(),
        OAuthToken.is_personal == True,
        OAuthToken.is_internal == False,
        OAuthClient.is_internal == True,
    ).all()

    authorized_apps = OAuthToken.query.options(db.joinedload('client')).filter(
        OAuthToken.user_id == current_user.get_id(),
        OAuthToken.is_personal == False,
        OAuthToken.is_internal == False,
        OAuthClient.is_internal == False,
    ).all()

    return render_template(
        "oauth2server/settings/index.html",
        clients=clients,
        tokens=tokens,
        authorized_apps=authorized_apps,
    )
예제 #19
0
파일: models.py 프로젝트: kasioumis/invenio
    def leave(self, user):
        """Remove user from group.

        :param user: User to remove from the group.
        """
        # if I want to remove another user from the group
        if(user.id != current_user.get_id()
           # I need to be an admin of the group
           and not self.is_admin(current_user.get_id())):
            raise AccountSecurityError(
                'Not enough right to '
                'remove user "{0}" from group "{1}"'
                .format(user.nickname, self.name))

        # check that I'm not the last admin before leaving the group.
        if self.is_admin(user.id) and self.admins.count() == 1:
            raise IntegrityUsergroupError(
                'User can leave the group '
                'without admins, please delete the '
                'group if you want to leave.')

        # leave the group
        UserUsergroup.query.filter_by(
            id_usergroup=self.id,
            id_user=user.id,
        ).delete()
        try:
            db.session.commit()
        except:
            db.session.rollback()
            raise
예제 #20
0
def import_bookmarks():
    form = ImportForm()

    if request.method == 'POST' and form.validate_on_submit():
        feed = feedparser.parse(form.atom_file.data.read())
        for mark in feed.entries:
            published = datetime.datetime.strptime(mark.published, "%Y-%m-%dT%H:%M:%SZ")
            referrers = filter(lambda link: 'via' == link['rel'], mark['links']) or [{'href': ''}]

            mongo.db.bookmarks.update({'url': mark.link, 'user._id': ObjectId(current_user.get_id())},
                                      {'$set': {
                                          'user': {
                                              '_id': ObjectId(current_user.get_id()),
                                              'nickname': current_user.nickname,
                                              'email': current_user.email
                                          },
                                          'published': published,
                                          'title': mark.title,
                                          'url': mark.link,
                                          'description': mark.get('summary', ''),
                                          'referrer': referrers[0]['href'],
                                          'public': not mark.get('bm_isprivate', False),
                                          'tags': [tag.label for tag in mark.get('tags', [])]
                                      }}, upsert=True)
        flash(u'Fichier importé avec succès !')

    return render_template('tools/import.html', form=form)
예제 #21
0
파일: models.py 프로젝트: kasioumis/invenio
    def join(self, user, status=None):
        """Join user to group.

        :param user: User to add into the group.
        :param status: status of user
        """
        # if I want to join another user from the group
        if(user.id != current_user.get_id()
           # I need to be an admin of the group
           and not self.is_admin(current_user.get_id())):
            raise AccountSecurityError(
                'Not enough right to '
                'add user "{0}" from group "{1}"'
                .format(user.nickname, self.name))

        # join group
        self.users.append(
            UserUsergroup(
                id_user=user.id,
                user_status=status or self.new_user_status,
            )
        )
        try:
            db.session.commit()
        except:
            db.session.rollback()
            raise
예제 #22
0
def cve(cveid):
    cveid = cveid.upper()
    cvesp = cves.last(rankinglookup=True,
                      namelookup=True,
                      vfeedlookup=True,
                      capeclookup=True,
                      subscorelookup=True,
                      misplookup=True)
    cve = cvesp.getcve(cveid=cveid)
    if cve is None:
        return render_template('error.html',
                               status={
                                   'except': 'cve-not-found',
                                   'info': {
                                       'cve': cveid
                                   }
                               })
    cve = markCPEs(cve)
    if current_user.is_authenticated():
        db.addSeenCVEs(current_user.get_id(), cveid)
        bookmarked = "yes" if cveid in db.bookmarks(
            current_user.get_id()) else "no"
    else:
        bookmarked = None
    return render_template('cve.html', cve=cve, bookmarked=bookmarked)
예제 #23
0
    def get(self):
        """
        This endpoint returns the ADS API client token, which
        is effectively a personal access token
        """
        client = OAuthClient.query.filter_by(
            user_id=current_user.get_id(),
            name=u'ADS API client',
        ).first()
        if not client:
            return {'message': 'no ADS API client found'}, 200

        token = OAuthToken.query.filter_by(
            client_id=client.client_id,
            user_id=current_user.get_id(),
        ).first()

        if not token:
            current_app.logger.error(
                'no ADS API client token '
                'found for {email}. This should not happen!'.format(
                    email=current_user.email))
            return {'message': 'no ADS API token found'}, 500

        output = print_token(token)
        output['client_id'] = client.client_id
        output['user_id'] = current_user.get_id()
        return output
예제 #24
0
def request_view():
    if current_user.user_role == 'customer':
        return redirect(url_for('index'))
    from models import RequestList
    lastNumber = False
    lastDate = False
    lastStatus = False
    print(current_user.get_name())
    queryA = RequestList.query.filter_by(
        user_id=current_user.get_id()).order_by(
            RequestList.table_id.desc()).limit(1)
    lastNumber = 0
    for row in queryA:
        lastDate = row.request_date
        lastNumber = row.number
        lastStatus = row.status
    pNumber = lastNumber + 1
    if request.method == 'POST':
        if request.form['cust_name']:
            rl = RequestList(custname=request.form['cust_name'].upper(),
                             request_type=request.form['request_type'].upper(),
                             status=0,
                             number=pNumber,
                             user_id=current_user.get_id())
            db.session.add(rl)
            db.session.commit()
            return jsonify({'data': [{'number': str(pNumber)}]})
    return render_template('request.html')
예제 #25
0
def index():
    clients = Client.query.filter_by(
        user_id=current_user.get_id(),
        is_internal=False,
    ).all()

    tokens = Token.query.options(db.joinedload('client')).filter(
        Token.user_id == current_user.get_id(),
        Token.is_personal == True,  # noqa
        Token.is_internal == False,
        Client.is_internal == True,
    ).all()

    authorized_apps = Token.query.options(db.joinedload('client')).filter(
        Token.user_id == current_user.get_id(),
        Token.is_personal == False,  # noqa
        Token.is_internal == False,
        Client.is_internal == False,
    ).all()

    return render_template(
        "oauth2server/settings/index.html",
        clients=clients,
        tokens=tokens,
        authorized_apps=authorized_apps,
    )
예제 #26
0
파일: DSApp.py 프로젝트: bobsavage/DSApp
def index():
    """Each user gets a custom landing page.
    There is no part of the site intended to be used by the public."""
    u = User.query.filter_by(id=current_user.get_id()).first()
    # ToDo query for all entities associated with user
    e_list = Entity.query.filter_by(user_id=current_user.get_id()).all()
    return render_template('index.html', username=u.login_id, entities=e_list)
예제 #27
0
파일: main.py 프로젝트: anneschilling/lmfdb
def save_form():
    ID = request.form["id"]
    if not ID:
        raise Exception("no id")

    if not allowed_knowl_id.match(ID):
        flask.flash(
            """Oops, knowl id '%s' is not allowed.
                  It must consist of lower/uppercase characters,
                  no spaces, numbers or '.', '_' and '-'."""
            % ID,
            "error",
        )
        return flask.redirect(url_for(".index"))

    k = Knowl(ID)
    k.title = request.form["title"]
    k.content = request.form["content"]
    k.quality = request.form["quality"]
    k.timestamp = datetime.now()
    k.save(who=current_user.get_id())
    from knowl import save_history

    save_history(k, current_user.get_id())
    return flask.redirect(url_for(".show", ID=ID))
예제 #28
0
파일: recipes.py 프로젝트: Mascarpone/Re7
def recipe(id):
    recipe = model.getRecipe(id)
    if recipe is not None:
        form = CommentForm()
        if form.validate_on_submit():
            if current_user.is_authenticated:
                comment = model.getCommentsByRecipeIDAndUserID(id, current_user.get_id())
                if comment is None:
                    model.insertComment(form.comment.data, form.tasteScore.data,
                        form.priceScore.data, form.instructionScore.data,
                         current_user.get_id(), id)
                else:
                    flash(u"Vous avez déjà commenté cette recette")

                return redirect(url_for('recipe', id=id))
            else :
                flash(u"Connectez-vous pour pouvoir commenter les recettes")
                return redirect(url_for('login'))

        steps = model.getStepsByRecipeID(id)
        image = gallery.url(recipe['image'])
        ingredients = model.getContainsByRecipeID(id)
        comments = model.getCommentsByRecipeID(id)
        averages = model.getAverageByRecipeID(id)

        if not recipe['image']:
            image += 'recipe.png'

        return render_template('recipe.html', recipe=recipe, steps=steps, image=image,
            ingredients=ingredients, form=form, comments=comments, averages=averages)

    return abort(404)
예제 #29
0
파일: main.py 프로젝트: nilsskoruppa/lmfdb
def edit(ID):
    if not allowed_knowl_id.match(ID):
        flask.flash("""Oops, knowl id '%s' is not allowed.
                  It must consist of lowercase characters,
                  no spaces, numbers or '.', '_' and '-'.""" % ID, "error")
        return flask.redirect(url_for(".index"))
    knowl = Knowl(ID)

    from knowl import is_locked, set_locked
    lock = False
    if request.args.get("lock", "") != 'ignore':
        lock = is_locked(knowl.id)
    # lock, if either lock is false or (lock is active), current user is editing again
    author_edits = lock and lock['who'] == current_user.get_id()
    logger.debug(author_edits)
    if not lock or author_edits:
        set_locked(knowl, current_user.get_id())
    if author_edits:
        lock = False

    b = get_bread([("Edit '%s'" % ID, url_for('.edit', ID=ID))])
    return render_template("knowl-edit.html",
                           title="Edit Knowl '%s'" % ID,
                           k=knowl,
                           bread=b,
                           lock=lock)
예제 #30
0
파일: owe.py 프로젝트: karlb/zerosum
def respond_to_request():
    request_id = int(request.form['request_id'])
    action = request.form['action']
    assert action in ('confirm', 'reject')
    if action == 'confirm':
        assert db.exec("""
            WITH new_owe AS (
                INSERT INTO owe(debitor_id, creditor_id, amount, subject)
                SELECT debitor_id, creditor_id, amount, subject
                FROM owe_request
                WHERE owe_request_id = %(request_id)s
                  AND debitor_id = %(debitor_id)s
                  AND status = 'open'
                RETURNING owe_id
            )
            UPDATE owe_request
            SET status = 'accepted',
                responded_at = now(),
                owe_id = new_owe.owe_id
            FROM new_owe
            WHERE owe_request_id = %(request_id)s
        """, dict(request_id=request_id, debitor_id=current_user.get_id())) == 1
    else:
        assert db.exec("""
            UPDATE owe_request
            SET status = 'rejected',
                responded_at = now()
            WHERE owe_request_id = %s
              AND debitor_id = %s
              AND status = 'open'
        """, [request_id, current_user.get_id()]) == 1
    return redirect(url_for('home'))
예제 #31
0
파일: views.py 프로젝트: romanchyla/adsws
    def get(self):
        """
        This endpoint returns the ADS API client token, which
        is effectively a personal access token
        """
        client = OAuthClient.query.filter_by(
            user_id=current_user.get_id(),
            name=u'ADS API client',
        ).first()
        if not client:
            return {'message': 'no ADS API client found'}, 200

        token = OAuthToken.query.filter_by(
            client_id=client.client_id,
            user_id=current_user.get_id(),
        ).first()

        if not token:
            current_app.logger.error(
                'no ADS API client token '
                'found for {email}. This should not happen!'.format(
                    email=current_user.email
                )
            )
            return {'message': 'no ADS API token found'}, 500

        output = print_token(token)
        output['client_id'] = client.client_id
        output['user_id'] = current_user.get_id()
        return output
예제 #32
0
def edit(post_id):
    if current_user.get_id() == app.config['POSTS_COLLECTION'].find_one({"_id": ObjectId(post_id) })['user']:

        post_body = app.config['POSTS_COLLECTION'].find_one({"_id": ObjectId(post_id) })['entry']
        post_title = app.config['POSTS_COLLECTION'].find_one({"_id": ObjectId(post_id) })['title']
        post_tags = app.config['POSTS_COLLECTION'].find_one({"_id": ObjectId(post_id) })['tags']
        form = EditForm()
        if request.method == 'POST':
            
            post = form.post.data
            title = form.post_title.data
            tags = form.tags.data.split(',')
            

            try:
                app.config['POSTS_COLLECTION'].update_one({"_id": ObjectId(post_id)}, {"$set":{"entry": post, "title": title, "tags": tags, "updated_on": datetime.datetime.now()}})
                flash("Post Updated", category='success')
                return redirect(url_for('user', nickname=current_user.get_id()))
            except:
                flash("Something went bad....", category='error')
        form.post.data = post_body
        form.post_title.data = post_title
        form.tags.data = post_tags
        return render_template('edit.html', post_id=post_id, form=form)
    else:
         flash("This is not your post...why would you want to edit it????", category='error')
         return redirect(url_for("posts"))


   

    return render_template('edit.html', post=post_body, form=form)
예제 #33
0
def determine_user_privileges(recid, ctx):
    # show_review_area = not show_upload_area
    ctx['show_review_widget'] = False
    ctx['show_upload_widget'] = False
    ctx['is_submission_coordinator_or_admin'] = False
    ctx['is_admin'] = False

    if current_user.is_authenticated:
        user_id = current_user.get_id()
        participant_records = SubmissionParticipant.query.filter_by(
            user_account=user_id, publication_recid=recid).all()

        for participant_record in participant_records:
            if participant_record is not None:
                if participant_record.role == 'reviewer' and participant_record.status == 'primary':
                    ctx['show_review_widget'] = True

                if participant_record.role == 'uploader' and participant_record.status == 'primary':
                    ctx['show_upload_widget'] = True

        user = User.query.get(current_user.get_id())
        if has_role(user, 'admin'):
            ctx['is_submission_coordinator_or_admin'] = True
            ctx['is_admin'] = True
        else:
            matching_records = HEPSubmission.query.filter_by(
                publication_recid=recid,
                coordinator=current_user.get_id()).count()

            if matching_records > 0:
                ctx['is_submission_coordinator_or_admin'] = True

        ctx['show_upload_widget'] = (ctx['show_upload_widget'] or
                                     ctx['is_submission_coordinator_or_admin'])
예제 #34
0
파일: beef.py 프로젝트: ghl3/IveGotBeef
def get_beef(_id):
    """ Get the sigle beef entry with the supplied id

    Return the beef as as dict, and return also a 
    dict representing the keyword arguments for the
    template generation:

    return (beef, kw_args)
    """

    # Be sure to fetch these parameters:
    to_fetch = ["_id", "BeefTitle", "BeefDescription", 
                "CreatedByName", "CreatedById", "BeefOpponent", "BeefOpponentId", 
                "TimeCreated", "ArgumentLeft", "ArgumentRight", 
                "VotesFor", "VotesAgainst", "CommentList"]
    
    beef_collection = getCollection("beef")
    beef_entry = beef_collection.find_one({"_id" : bson.objectid.ObjectId(_id)})
    
    if beef_entry==None:
        print "get_beef(): Failed to find entry with _id %s:" % _id
        raise InvalidBeef("Beef with Id Not Found")
    else:
        print "Successfully found entry: %s" % _id

    beef_dict = format_dict(beef_entry, to_fetch)

    # Now, get the parameters for the template generation
    kwargs = {}
    kwargs['argument_left'] = beef_dict.pop("ArgumentLeft")
    kwargs['argument_right'] = beef_dict.pop("ArgumentRight")
    kwargs['VotesFor'] = beef_dict.pop("VotesFor")
    kwargs['VotesAgainst'] = beef_dict.pop("VotesAgainst")

    # Determie who started the beef
    if current_user.get_id() == beef_dict["CreatedById"].__str__():
        kwargs['beef_owner']=True
    else:
        kwargs['beef_owner']=False

    # Determie who the beef is against
    if current_user.get_id() == beef_dict["BeefOpponentId"].__str__():
        kwargs['beef_against']=True
    else:
        kwargs['beef_against']=False

    # Now, fetch the comments
    # Comments are stored as ObjectId's
    comments_collection = getCollection("comments")
    comment_id_list = beef_dict.pop("CommentList")

    # Fetch all comments using a single query (sweet)
    comment_list = list(comments_collection.find({"_id" : {'$in':comment_id_list} }))    
    comment_list = map(lambda x: format_dict(x, ["username", "user_id",  "TimeCreated", "comment"]), comment_list)

    print beef_dict
    print comment_list
    print kwargs
    return (beef_dict, comment_list, kwargs)
예제 #35
0
def account_createtable():
    form = CreateTableForm(request.form)
    if form.validate():
        tableid=DB.add_table(form.tablenumber.data,current_user.get_id())
        new_url=BH.shorten_url(config.base_url + "newrequest/"+str(tableid))
        DB.update_table(tableid,new_url)
        return redirect(url_for('account'))
    return render_template("account.html",createtableform=form,tables=DB.get_tables(current_user.get_id()))
예제 #36
0
파일: views.py 프로젝트: binnie869/app
def documentation():
	username = current_user.get_id()
	grows_list = []
	grows = db.grows.find({'username' : current_user.get_id()})
	for grow in grows:
		grows_list.append((grow['grow_name'], grow['device_name'], grow['sensors'], grow['actuators']))
	
	return render_template('documentation/documentation.html', username=username, my_grows=grows_list)
예제 #37
0
def account():
    form_create_table = CreateTableForm()
    form_delete_table = DeleteTableForm()
    return render_template("account.html",
                           user=current_user.get_id(),
                           createtableform=form_create_table,
                           deletetableform=form_delete_table,
                           table=DB.get_tables(current_user.get_id()))
예제 #38
0
def account_createtable():
    form = CreateTableForm(request.form)
    if form.validate():
        tableid = DB.add_table(form.tablenumber.data,current_user.get_id())
        new_url = BH.shorten_url(config.base_url+"newrequest/"+tableid)
        DB.update_table(tableid,new_url)
        return redirect(url_for('account'))
    return render_template("account.html",createtableform=form,tables=DB.get_tables(current_user.get_id()))
예제 #39
0
def get_group(id):
    if current_user.get_id():
        user_grp = get_user(current_user.get_id())[4]
        user_name = get_user(current_user.get_id())[1]
    else:
        user_grp = None
        user_name = 'Login'
    return user_name, user_grp
예제 #40
0
def metadata(recid, of='hd'):
    from invenio.legacy.bibrank.downloads_similarity import register_page_view_event
    from invenio.modules.formatter import get_output_format_content_type
    register_page_view_event(recid, current_user.get_id(), str(request.remote_addr))
    if get_output_format_content_type(of) != 'text/html':
        from invenio.modules.search.views.search import response_formated_records
        return response_formated_records([recid], g.collection, of, qid=None)


    # Send the signal 'document viewed'
    record_viewed.send(
        current_app._get_current_object(),
        recid=recid,
        id_user=current_user.get_id(),
        request=request)


    def get_record_name(recid):
        tmp_rec = get_record(recid)
        if tmp_rec is None:
            return 'Can\'t link to record ( WRONG recid )'

        if 'title_additional' in tmp_rec :
            return tmp_rec.get('title_additional', '').get('title', '')
        elif tmp_rec.get('title',{}).get('title',''):
            return tmp_rec.get('title',{}).get('title','')

    def get_record_author_list(recid):
        tmp_rec = get_record(recid)
        if tmp_rec is None:
            return None

        return tmp_rec.get('authors','')


    current_app.jinja_env.filters['splitthem'] = splitting
    current_app.jinja_env.filters['get_record_name'] = get_record_name
    current_app.jinja_env.filters['get_record_author_list'] = get_record_author_list
    current_app.jinja_env.filters['get_download_time'] = calculate_download_time


    record_collection = get_record(recid)['collections'][0]['primary']
    rec_col = Collection.query.filter(Collection.name == record_collection).first_or_404()
    parent_collection = rec_col.most_specific_dad \
                        if (rec_col.most_specific_dad and \
                            rec_col.most_specific_dad.id != 1) else None

    breadcrumbs = [{}]

    if parent_collection:
        breadcrumbs.append({ "url":".collection", "text": parent_collection.name_ln, "param":"name", "value": parent_collection.name })

    breadcrumbs.append({"url":".collection", "text": rec_col.name_ln, "param":"name", "value":rec_col.name })

    try:
        return render_template(['records/'+record_collection+'_base.html','records/base_base.html'], breadcrumbs = breadcrumbs )
    except TemplateNotFound:
        return abort(404)  # FIX
예제 #41
0
def metadata(recid, of='hd'):
    from invenio.legacy.bibrank.downloads_similarity import register_page_view_event
    from invenio.modules.formatter import get_output_format_content_type
    register_page_view_event(recid, current_user.get_id(), str(request.remote_addr))
    if get_output_format_content_type(of) != 'text/html':
        from invenio.modules.search.views.search import response_formated_records
        return response_formated_records([recid], g.collection, of, qid=None)


    # Send the signal 'document viewed'
    record_viewed.send(
        current_app._get_current_object(),
        recid=recid,
        id_user=current_user.get_id(),
        request=request)

    def splitting(value, delimiter='/', maxsplit=0):
        return value.split(delimiter, maxsplit)

    def get_record_name(recid):
        tmp_rec = get_record(recid)
        if tmp_rec is None:
            return 'Can\'t link to record ( WRONG recid )'

        if 'title_additional' in tmp_rec :
            return tmp_rec.get('title_additional', '').get('title', '')
        elif tmp_rec.get('title',{}).get('title',''):
            return tmp_rec.get('title',{}).get('title','')

    def get_record_author_list(recid):
        tmp_rec = get_record(recid)
        if tmp_rec is None:
            return None

        return tmp_rec.get('authors','')


    current_app.jinja_env.filters['splitthem'] = splitting
    current_app.jinja_env.filters['get_record_name'] = get_record_name
    current_app.jinja_env.filters['get_record_author_list'] = get_record_author_list
    current_app.jinja_env.filters['get_download_time'] = calculate_download_time


    record_collection = get_record(recid)['collections'][0]['primary']
    rec_col = Collection.query.filter(Collection.name == record_collection).first_or_404()
    parent_collection = rec_col.most_specific_dad if ( rec_col.most_specific_dad.id != 1 ) else None

    breadcrumbs = [{}]

    if parent_collection:
        breadcrumbs.append({ "url":".collection", "text": parent_collection.name_ln, "param":"name", "value": parent_collection.name })

    breadcrumbs.append({"url":".collection", "text": rec_col.name_ln, "param":"name", "value":rec_col.name })

    try:
        return render_template('records/base_base.html', breadcrumbs = breadcrumbs )
    except TemplateNotFound:
        return abort(404)  # FIX
예제 #42
0
    def get(self):
        """Returns a list of servers (agents) with basic stats

        **GET** method provided by the webservice.

        The *JSON* returned is:
        ::

            [
              {
                'alive': true,
                'clients': 2,
                'name': 'burp1',
              },
              {
                'alive': false,
                'clients': 0,
                'name': 'burp2',
              },


        :returns: The *JSON* described above.
        """

        r = []
        if hasattr(api.bui.cli, 'servers'):  # pragma: no cover
            check = False
            allowed = []
            if (api.bui.acl and not
                    api.bui.acl.is_admin(current_user.get_id())):
                check = True
                allowed = api.bui.acl.servers(current_user.get_id())

            def get_servers_info(serv, output):
                try:
                    if check:
                        if serv in allowed:
                            output.put({
                                'name': serv,
                                'clients': len(api.bui.acl.clients(current_user.get_id(), serv)),
                                'alive': api.bui.cli.servers[serv].ping()
                            })
                            return
                    else:
                        output.put({
                            'name': serv,
                            'clients': len(api.bui.cli.servers[serv].get_all_clients(serv)),
                            'alive': api.bui.cli.servers[serv].ping()
                        })
                        return
                    output.put(None)
                except BUIserverException as e:
                    output.put(str(e))

            r = parallel_loop(get_servers_info, api.bui.cli.servers)

        return r
예제 #43
0
def edit_entry_get(id):
    entry = session.query(Entry).get(id)
    current_user_id = current_user.get_id()
    if current_user_id is None:
        raise Forbidden('Only entry author can delete it.')
    else:
        if int(entry.author_id) != int(current_user.get_id()):
            raise Forbidden('Only the entry author can delete it.')
    return render_template("edit_entry.html", entry=entry)
def edit_profile():
    user_details = get_user_details({'id': current_user.get_id()}).get() or {}
    if not user_details:
        print('create')
        create_description().execute({'user_id': current_user.get_id()})
    web.form.create('Update your details', '/profile/update')
    web.form.append(name='description', label='Description', placeholder='This is me i am great', value=user_details.get('description') or '')
    web.form.append(name='skills', label='skills', placeholder='python, arduino, knitting', value=user_details.get('skills') or '')
    return web.form.render()
예제 #45
0
def editor(post_id):
    blogging_engine = _get_blogging_engine(current_app)
    cache = blogging_engine.cache
    if cache:
        _clear_cache(cache)
    try:
        with blogging_engine.blogger_permission.require():
            post_processor = blogging_engine.post_processor
            config = blogging_engine.config
            storage = blogging_engine.storage
            if request.method == 'POST':
                form = BlogEditor(request.form)
                if form.validate():
                    post = storage.get_post_by_id(post_id)
                    if (post is not None) and \
                            (current_user.get_id() == post["user_id"]) and \
                            (post["post_id"] == post_id):
                        pass
                    else:
                        post = {}
                    pid = _store_form_data(form, storage, current_user, post)
                    flash("Blog posted successfully!", "info")
                    slug = post_processor.create_slug(form.title.data)
                    return redirect(url_for("blogging.page_by_id", post_id=pid,
                                            slug=slug))

                    return redirect(url_for("blogging.page_by_id", post_id=pid,slug=slug))
                else:
                    flash("There were errors in blog submission", "warning")
                    return render_template("blogging/editor.html", form=form,
                                           post_id=post_id, config=config)
            else:
                if post_id is not None:
                    post = storage.get_post_by_id(post_id)
                    if (post is not None) and \
                            (current_user.get_id() == post["user_id"]):
                        tags = ", ".join(post["tags"])
                        form = BlogEditor(title=post["title"],
                                          title_image=post['title_image'],
                                          summary_text=post['summary_text'],
                                          text=post["text"], tags=tags)
                        return render_template("blogging/editor.html",
                                               form=form, post_id=post_id,
                                               config=config)
                    else:
                        flash("You do not have the rights to edit this post",
                              "warning")
                        return redirect(url_for("blogging.index",
                                                post_id=None))

            form = BlogEditor()
            return render_template("blogging/editor.html", form=form,
                                   post_id=post_id, config=config)
    except PermissionDenied:
        flash("You do not have permissions to create or edit posts", "warning")
        return redirect(url_for("blogging.index", post_id=None))
예제 #46
0
def index():
    form = UserForm(nickname=current_user.nickname, email=current_user.email)
    if request.method == 'POST' and form.validate():
        mongo.db.users.update({'_id': ObjectId(current_user.get_id())}, {'$set': {'email': form.email.data, 'nickname': form.nickname.data}})
        mongo.db.bookmarks.update({'user._id': ObjectId(current_user.get_id())}, {'$set': {'user.email': form.email.data, 'user.nickname': form.nickname.data}}, multi=True)
        if form.new_password.data:
            mongo.db.users.update({'_id': ObjectId(current_user.get_id())}, {'$set': {'password': bcrypt.generate_password_hash(form.new_password.data, rounds=12)}})
        flash(u'Les modifications ont été correctement enregistrées.')

    return render_template('profil/index.html', form=form)
예제 #47
0
def __authenticated_delete_request(uri):
    from orcaweb.routes_base import session__get_hostname

    response = requests.delete(
        "%s/%s&token=%s" %
        (session__get_hostname(), uri, current_user.get_id()))
    print "%s/%s&token=%s" % (session__get_hostname(), uri,
                              current_user.get_id())
    if response.status_code == 403:
        raise NoSession("Invalid or no session")
    return json.loads(response.text)
예제 #48
0
파일: app.py 프로젝트: hybridkris/GoldStar
def oauth_authorized(resp):
    if resp is None:
        flash(u'You denied the request to sign in.')
    elif resp is not None:
        user = User.query.get(current_user.get_id())
        user.oauth_token = resp['oauth_token']
        user.oauth_secret = resp['oauth_token_secret']
        user.twitterUser = resp['screen_name']
        db.session.commit()
        session['user_id'] = current_user.get_id()
    return redirect('/mobileview.html')
예제 #49
0
def analyze(): 
    sent = request.args.get('sentence')
    annotation = request.args.get('anno')
    preproc = u'% TEXT\n{0}\n% ANNO\n{1}'.format(sent, annotation)
    with codecs.open(os.path.join(TEMP_DIR, current_user.get_id()+'.txt'), 'w', 'utf-8') as f:
        f.write(preproc)
    try: 
        view.main([os.path.join(TEMP_DIR, current_user.get_id()+'.txt')])
        return send_file(os.path.join(TEMP_DIR, current_user.get_id()+'.0.png'), mimetype='image/png')
    except Exception as ex:
        return str(ex), 500 
예제 #50
0
def get_data():
    concatenated_data = {}
    username = current_user.get_id()
    grows = db.grows.find({'username': current_user.get_id()})
    for grow in grows:
        data_points = db.data.find({'grow_name': grow['grow_name']})
        for data_point in data_points:
            data_point.pop('_id', None)
            concatenated_data.setdefault(grow['grow_name'],
                                         []).append(data_point)

    return flask.jsonify(**concatenated_data)
예제 #51
0
def change_password():
    if request.args.get('new_pass'): new_pass = request.args.get('new_pass')
    else: new_pass = request.form["new_pass"]
    print "new pass is ", new_pass
    user_id = current_user.get_id()
    m = md5.new()
    m.update(new_pass)
    user = models.User.query.get(user_id)
    user.password = buffer(m.hexdigest())
    db.session.commit()
    return render_template('success.html',
                           admin=is_admin(current_user.get_id()))
예제 #52
0
def delete_file():
    data = request.get_json()
    file_id = data["file"]
    target_file = models.File.query.filter_by(id=file_id).first()
    for item in current_user.files:
        if item.file is target_file:
            db.session.delete(item)
            db.session.commit()
            logger.info("User {} no longer can access file {}".format(
                current_user.get_id(), file_id),
                        user=current_user.get_id())
            return jsonify(dict(success=True, message="File deleted"))
    return jsonify(dict(success=False, message="Unable to delete file"))
예제 #53
0
def list_devices():
	device_list = []
	grows_list = []
	UUID = str(uuid.uuid4())
	username = current_user.get_id()
	devices = db.devices.find({'username': current_user.get_id()})
	for device in devices:
		device_list.append((device['device_name'], device['type'], \
				device['sensors'], device['actuators'], device['kit'], device['device_id'], device['emergency_stop']))
	grows = db.grows.find({'username' : current_user.get_id()})
	for grow in grows:
		grows_list.append((grow['grow_name'], grow['device_name']))
	return render_template('devices/devices.html' , my_devices=device_list, my_grows=grows_list, username=username, uuid=UUID)
예제 #54
0
def account_createtable():
    form = CreateTableForm(request.form)
    if form.validate_on_submit():
        tablename = form.tablenumber.data
        tableid = DB.add_table(tablename, current_user.get_id())
        new_url = config.base_url + "newrequest/" + str(tableid)
        DB.update_table(tableid, BH.shorten_url(new_url))
        return redirect(url_for('account'))
    else:
        return render_template("account.html",
                               user=current_user.get_id(),
                               createtableform=form,
                               deletetableform=DeleteTableForm(),
                               table=DB.get_tables(current_user.get_id()))
예제 #55
0
파일: app.py 프로젝트: hybridkris/GoldStar
def mobileview_route():
    if current_user.is_authenticated():
        p = page.Page("Gold Star!", False)
        userID = current_user.get_id()
        u = User.query.filter_by(id=userID).one()
        thisUser = userPageUser.userPageUser(u.firstName, u.lastName,
                                             current_user.get_id())
        if u.twitterUser is not None:
            thisUser.twitterUser = "******"
        else:
            thisUser.twitterUser = "******"
        return render_template('mobileview.html', page=p, user=thisUser)
    else:
        return redirect('login')
def reservations():
    user = User.query.get(current_user.get_id())

    reservations_as_host = Reservation.query \
        .filter(VacationProperty.host_id == current_user.get_id() and len(VacationProperty.reservations) > 0) \
        .join(VacationProperty) \
        .filter(Reservation.vacation_property_id == VacationProperty.id) \
        .all()

    reservations_as_guest = user.reservations

    return view_with_params('reservations',
                            reservations_as_guest=reservations_as_guest,
                            reservations_as_host=reservations_as_host)
예제 #57
0
def cart():
    model = ShoppingCart(current_user.get_id())
    videos = model.get_items()

    if videos:
        db.execute("SELECT title,dvd_price FROM video WHERE video_id IN (%s)" %
                   (",".join(str(i) for i in videos), ))
        videos_info = db.fetchall()
    else:
        videos_info = []

    items = []
    for video_id, video_info in zip(videos, videos_info):
        items.append({
            "video_id": video_id,
            "title": video_info[0],
            "dvd_price": video_info[1]
        })

    app.logger.debug("Query returned\n%s", repr(items))

    if flask.request.method == "POST":
        action = flask.request.form.get("action")

        app.logger.info("Cart action %s triggered.", action)

        if action == "checkout":
            db.execute("SELECT balance FROM users WHERE user_id=%s",
                       (current_user.get_id(), ))
            balance = int(db.fetchone()[0])

            price_sum = sum(i["dvd_price"] for i in items)

            if price_sum > balance:
                flask.flash("You don't have enough money in your account.",
                            category="error")
            else:
                db.execute(
                    'UPDATE users SET balance = balance - %s WHERE user_id = %s',
                    (price_sum, current_user.get_id()))
                model.complete_order()
                flask.flash("Your order has been placed!", category="message")

            return flask.redirect(flask.url_for("cart"))
        elif action == "clear":
            model.clear_cart()
            flask.flash("Cart has been cleared.", category="message")
            return flask.redirect(flask.url_for("cart"))

    return flask.render_template("cart.html", items=items)