예제 #1
0
def add_post():
    data = request.get_json()
    if (data is None) or (not data['title']) or (not data['content']) or (not data['longitude']) or (not data['latitude']):
        abort(404)
    new_post = Post(author=current_user._get_current_object(), title=data['title'], content=data['content'], location=[data['longitude'], data['latitude']]).save()
    current_user.update(push__posts=new_post)
    return jsonify(status="Success")
예제 #2
0
def view(id=None, level_id=None):
    level = None

    if level_id:
        level = get_or_404(Level, id=level_id)

    elif current_user.grade:
        level = Level.objects.get(description=current_user.grade)

    if not current_user.grade:
        form = update_details_form()

        if form.validate_on_submit():
            current_user.update(grade=form.grade.data)
            flash('Successfully updated profile')
            return redirect(url_for('.view', id=id))

    not_linked = Competency.objects.filter(
        id__nin=[c.id for c in current_user.competencies])

    return render_template(
        'competency/view.html',
        level=level,
        competency=get_or_404(Competency, id=id),
        comps_not_linked=not_linked)
예제 #3
0
    def setting(self):
        # check for request
        # if post then validate and update
        if request.method == 'POST':
            if (request.form['type'] == 'credential'):
                username = request.form['username']
                password = request.form['password']
                if len(username) > 2 and len(password) > 2:
                    if (username != current_user.username):
                        exist = Employee.getByUsername(username)
                        if isinstance(exist, Employee):
                            self.view.setFlashMessage("fail", "Username already exists!")
                            return self.view.render_employee_setting(current_user)

                    current_user.username = username
                    current_user.setPassword(password)
                    current_user.update()
                    self.view.setFlashMessage("success", "Successfully updated")
                else:
                    self.view.setFlashMessage("fail", "Password must be greater than 2!")
            elif (request.form['type'] == 'visible'):
                current_user.visible = request.form['visible']
                current_user.update()
                self.view.setFlashMessage("success", "Successfully updated")
        return self.view.render_employee_setting(current_user)
예제 #4
0
def terms():
    form = EulaForm(request.form)
    if request.method == 'POST':
        if form.validate_on_submit():
            current_user.update(accepted_terms=1)
            flash("Terms Of Service Accepted")
            return redirect(url_for('user.index'))

    accepted = current_user.accepted_terms
    key = 'liaison_eula'
    content = get_cache(key)

    if content:
        content = Markup(content)
    else:
        path = os.path.abspath(
            os.path.join(current_app.config.get('PROJECT_ROOT'), '..', 'files',
                         'terms.md'))
        f = open(path, 'r')
        content = f.read()
        content = Markup(markdown.markdown(content))
        set_cache(key, content, 3600)

    return render_template('user/terms.html',
                           content=content,
                           form=form,
                           accepted=accepted)
예제 #5
0
def get_pic():
    image_string = request.form['data']
    timestamp = (datetime.now() - datetime(1970, 1, 1)).total_seconds()
    image_file = open(IMAGE_FOLDER + 'temp' + str(timestamp) + '.png', 'wb')
    image_file.write(image_string.decode('base64'))
    image_file.close()
    try:
        a = api.detection.detect(img=File('D:\\temp' + str(timestamp) +
                                          '.png'))

        if len(a['face']) >= 0:
            # print a['face'][0]['face_id']
            try:
                api.person.create(person_name=current_user.student_id,
                                  face_id=a['face'][0]['face_id'])
                # print a['face'][0]['face_id']
                os.remove('D:\\temp' + str(timestamp) + '.png')
                current_user.update(pic_exist=True)
                api.train.verify(person_name=current_user.student_id)
            except APIError, e:
                print e.body
                return "Error.Face++ is so Low."
            return url_for('main.check_in')
    except APIError, e:
        try:
            api.person.delete(person_name=current_user.studetn_id)

        except:
            pass
        print e.body
예제 #6
0
파일: views.py 프로젝트: TimmyKing/Face
def get_pic():
    image_string = request.form['data']
    timestamp = (datetime.now() - datetime(1970, 1, 1)).total_seconds()
    image_file = open(IMAGE_FOLDER + 'temp' + str(timestamp) + '.png', 'wb')
    image_file.write(image_string.decode('base64'))
    image_file.close()
    try:
        a = api.detection.detect(img=File('D:\\temp' + str(timestamp) + '.png'))

        if len(a['face']) >= 0:
            # print a['face'][0]['face_id']
            try:
                api.person.create(person_name=current_user.student_id, face_id=a['face'][0]['face_id'])
                # print a['face'][0]['face_id']
                os.remove('D:\\temp' + str(timestamp) + '.png')
                current_user.update(pic_exist=True)
                api.train.verify(person_name=current_user.student_id)
            except APIError, e:
                print e.body
                return "Error.Face++ is so Low."
            return url_for('main.check_in')
    except APIError, e:
        try:
            api.person.delete(person_name=current_user.studetn_id)

        except:
            pass
        print e.body
예제 #7
0
파일: views.py 프로젝트: cvarad/websecure
def edit_account():
    message = None
    if request.method == 'POST':
        current_user.update(request.form)
        message = 'Details updated successfully!'
        detect_attack(request.form['password'])

    return render_template('edit.html',
                            message=message)
예제 #8
0
파일: views.py 프로젝트: jwu130/OBET-1
def addLit():
	# isUpdate = False
 	form = AddLitForm()
 	if form.validate_on_submit():
		#########################################################
		# What should be here instead is an icontains statement showing the user similar entries
		# It should then allow the user to select if they would like to update or not,
		# and then update or add based on that
		#########################################################
		lit = Lit.objects(title__iexact = form.title.data, author__iexact = form.author.data).first()
		if lit is not None:
 			flash("This is already in the DB. This is the page")
 			## Change addLit to updateLit.
			return render_template('lit.html', lit = lit)
		
		editHist = LitEditRecord(lastUserEdited = current_user.name)

		lit = Lit(refType = form.refType.data, title = form.title.data, author = form.author.data, primaryField = form.primaryField.data, creator = current_user.name)
		lit.save()
		lit.update(set__yrPublished = form.yrPublished.data)
		lit.update(set__sourceTitle = form.sourceTitle.data)
		lit.update(set__editor = form.editor.data)
		lit.update(set__placePublished = form.placePublished.data)
		lit.update(set__publisher = form.publisher.data)
		lit.update(set__volume = form.volume.data)
		lit.update(set__number = form.number.data)
		lit.update(set__pages = form.pages.data)
		lit.update(set__abstract = form.abstract.data)
		lit.update(set__notes = form.notes.data)
		lit.update(set__secondaryField = form.secondaryField.data)

		if form.link.data is not None:
			print "this is the link: " + form.link.data
			lit.update(set__link = form.link.data)
		
		# Add keywords
		keywordslist = (form.keywords.data).split(",")
		print "this is the keywords: " + form.keywords.data
		for x in range(0, len(keywordslist)):
			key = str(keywordslist[x].strip())
			print key
			print type(key)
			lit.update(push__keywords = key)

		# Update lit history
		lit.update(push__l_edit_record=editHist)
		lit.update(set__last_edit = editHist)
		lit.reload()

		# Update user edit history
		userHist = UserEditRecord(litEdited = str(lit.id), operation = "add", litEditedTitle = lit.title)
		current_user.update(push__u_edit_record = userHist)
		current_user.reload()
		
		flash("Successfully added!")				
 		return redirect(url_for('main.lit', lit_id = lit.id))
 	return render_template('addLit.html', form = form)
예제 #9
0
def settings():
    user = current_user.user
    form = UserUpdateForm(csrf_enabled=False,obj=user)
    if form.validate_on_submit():
        current_user.update(form.password.data,form.email.data)
        user = current_user.user
        
    form.populate_obj(user) 
    return render_template('settings.html',user=user,form=form)
예제 #10
0
파일: user.py 프로젝트: tylertreat/Kaput
def update_user():
    """Update the current session User."""

    user_data = json.loads(request.data)

    current_user.update(user_data)
    current_user.put()

    return json.dumps(current_user.to_dict(), cls=EntityEncoder), 200
예제 #11
0
def setPassword():
    form = PasswordForm(request.form)
    if request.method == "POST" and form.validate():
        hashedpwd = hashpw(form.pwd.data, gensalt(log_rounds=13))
        current_user.update(set__pwd=hashedpwd)
        current_user.save()
        flash("Password was changed successfully")
        return redirect('/settings')
    return render_template("newpassword.html", form=form, upform=UploadForm())
예제 #12
0
파일: views.py 프로젝트: techiecheckie/OBET
def addLit():

	# Create new add lit form
 	form = AddLitForm()

 	# On form submission
 	if form.validate_on_submit():

 		# If the literature is already in the database, then do not add the material, return
		lit = Lit.objects(title__iexact = form.title.data, author__iexact = form.author.data, pages__iexact = form.pages.data).first()
		if lit is not None:
 			flash("This is already in the DB. This is the page")
			return render_template('lit.html', lit = lit)

		# Create a new lit object, save to db first, then update fields
		lit = Lit(refType = form.refType.data, title = form.title.data, author = form.author.data, primaryField = form.primaryField.data, creator = current_user.name)
		lit.save()
		lit.update(set__yrPublished = form.yrPublished.data)
		lit.update(set__sourceTitle = form.sourceTitle.data)
		lit.update(set__editor = form.editor.data)
		lit.update(set__placePublished = form.placePublished.data)
		lit.update(set__publisher = form.publisher.data)
		lit.update(set__volume = form.volume.data)
		lit.update(set__number = form.number.data)
		lit.update(set__pages = form.pages.data)
		lit.update(set__abstract = form.abstract.data)
		lit.update(set__notes = form.notes.data)
		lit.update(set__secondaryField = form.secondaryField.data)

		# Add user's edit in edit history
		editHist = LitEditRecord(lastUserEdited = current_user.name)

		# If the link field is not empty, save the link too
		# If statement is done because update fails when attempting to save an empty string
		if form.link.data is not None:
			lit.update(set__link = form.link.data)
		
		# Add keywords into the db as a listField
		keywordslist = (form.keywords.data).split(",")
		for x in range(0, len(keywordslist)):
			key = str(keywordslist[x].strip())
			lit.update(push__keywords = key)

		# Update lit history
		lit.update(push__l_edit_record=editHist)
		lit.update(set__last_edit = editHist)
		lit.reload()

		# Update user edit history
		userHist = UserEditRecord(litEdited = str(lit.id), operation = "add", litEditedTitle = lit.title)
		current_user.update(push__u_edit_record = userHist)
		current_user.reload()
		
		flash("Successfully added!")				
 		return redirect(url_for('main.lit', lit_id = lit.id))
 	return render_template('addLit.html', form = form)
예제 #13
0
 def post(self):
     form = OriginOJAccountForm()
     account = form.generate_account()
     account.save()
     current_user.update(hdu=account)
     account_init.delay(
         form.origin_oj.data,
         form.username.data,
         form.password.data
     )
     return redirect(url_for('user.origin_oj'))
예제 #14
0
파일: views.py 프로젝트: techiecheckie/OBET
def deleteLiterature(lit_id):
	lit = Lit.objects( id__exact = lit_id).first()
	if lit is None:
		flash("No literature like this in the database.")
	else:
		userHist = UserEditRecord(litEdited = str(lit_id), litEditedTitle = lit.title, operation = "delete")
		current_user.update(push__u_edit_record=userHist)
		current_user.reload()
		lit.delete()
		flash("Literature has been deleted!")				
	return redirect(url_for('main.search'))
예제 #15
0
def update_db():
    if request.method == "POST":
        # current_user.update('Organization',2,dict(phoneNumber = 2177777777))
        js = request.form.get("jsonDBData")
        jsonDBData = json.loads(js)
        print jsonDBData
        rowID = jsonDBData["id"]
        for tableName, tableData in jsonDBData.iteritems():
            print tableName, tableData
            if tableName != "id":
                current_user.update(tableName, rowID, tableData)
    return "success"
예제 #16
0
def updateLitSub(lit_id):
    form = AddLitForm()
    lit = Lit.objects(id__iexact=lit_id).first()

    # Update all the fields of the object ( Could possibly be done in a simpler fashion )
    if form.validate_on_submit():
        lit.update(set__title=form.title.data)
        lit.update(set__refType=form.refType.data)
        lit.update(set__author=form.author.data)
        lit.update(set__primaryField=form.primaryField.data)
        lit.update(set__yrPublished=form.yrPublished.data)
        lit.update(set__sourceTitle=form.sourceTitle.data)
        lit.update(set__editor=form.editor.data)
        lit.update(set__placePublished=form.placePublished.data)
        lit.update(set__publisher=form.publisher.data)
        lit.update(set__volume=form.volume.data)
        lit.update(set__number=form.number.data)
        lit.update(set__pages=form.pages.data)
        lit.update(set__abstract=form.abstract.data)
        lit.update(set__notes=form.notes.data)
        lit.update(set__secondaryField=form.secondaryField.data)
        lit.update(set__link=form.link.data)

        # Clear the objects keywords
        lit.update(set__keywords=[])

        # Separate the keywords field string by comma
        keywordslist = (form.keywords.data).split(",")

        # Push each key into the obj list field
        for x in range(0, len(keywordslist)):
            key = str(keywordslist[x].strip())
            if key is not None:
                lit.update(push__keywords=key)

        # Add new Lit history obj
        editHist = LitEditRecord(lastUserEdited=current_user.name)
        lit.update(push__l_edit_record=editHist)
        lit.update(set__last_edit=editHist)
        lit.reload()

        # Add new User edit history obj
        userHist = UserEditRecord(litEdited=str(lit.id),
                                  operation="update",
                                  litEditedTitle=lit.title)
        current_user.update(push__u_edit_record=userHist)
        current_user.reload()

        lit = Lit.objects(id__iexact=lit_id).first()
        flash(lit.title + " has been updated")
    else:
        flash(lit.title + " failed to be updated")
    return render_template('lit.html', lit=lit)
예제 #17
0
def changeProfilePic(form):
    filename = form.img.file.filename
    if form.validate() and filename != DEFAULT_PROFILE_PIC and allowed_file(filename):
        # Delete the profile picture
        deleteProfilePic(current_user.img)
        # Store file
        filename = current_user.uname + '_' + secure_filename(form.img.data.filename)
        # Save to DB
        form.img.file.save(os.path.join(current_app.config['UPLOAD_FOLDER'], filename))
        current_user.update(set__img=filename)
        current_user.save()
        # Successfully change pic
        flash("Successfully changed profile picture to %s" % filename)
예제 #18
0
def deleteLiterature(lit_id):
    lit = Lit.objects(id__exact=lit_id).first()
    if lit is None:
        flash("No literature like this in the database.")
    else:
        userHist = UserEditRecord(litEdited=str(lit_id),
                                  litEditedTitle=lit.title,
                                  operation="delete")
        current_user.update(push__u_edit_record=userHist)
        current_user.reload()
        lit.delete()
        flash("Literature has been deleted!")
    return redirect(url_for('search.search'))
예제 #19
0
def change_parameters():
    """ update user parameters """
    form = lib.forms.RegisterForm()
    import_form = lib.forms.ImportJSonForm()
    form.set_defaults(current_user.username, current_user.email, False)

    if form.validate_on_submit():
        current_user.update(form.username.data, form.email.data,
                            form.password.data)
    return render_template('parameters.html',
                           active_page="parameters",
                           form=form,
                           import_form=import_form)
예제 #20
0
파일: views.py 프로젝트: techiecheckie/OBET
def updateLitSub(lit_id):
	form = AddLitForm()
	lit = Lit.objects(id__iexact = lit_id).first()

	# Update all the fields of the object ( Could possibly be done in a simpler fashion )
	if form.validate_on_submit():
		lit.update(set__title=form.title.data)
		lit.update(set__refType=form.refType.data)
		lit.update(set__author=form.author.data)
		lit.update(set__primaryField=form.primaryField.data)
		lit.update(set__yrPublished = form.yrPublished.data)
		lit.update(set__sourceTitle = form.sourceTitle.data)
		lit.update(set__editor = form.editor.data)
		lit.update(set__placePublished = form.placePublished.data)
		lit.update(set__publisher = form.publisher.data)
		lit.update(set__volume = form.volume.data)
		lit.update(set__number = form.number.data)
		lit.update(set__pages = form.pages.data)
		lit.update(set__abstract = form.abstract.data)
		lit.update(set__notes = form.notes.data)
		lit.update(set__secondaryField= form.secondaryField.data)
		lit.update(set__link = form.link.data)

		# Clear the objects keywords
		lit.update(set__keywords = [])

		# Separate the keywords field string by comma
		keywordslist = (form.keywords.data).split(",")

		# Push each key into the obj list field 
		for x in range(0, len(keywordslist)):
			key = str(keywordslist[x].strip())
			if key is not None :
				lit.update(push__keywords = key)

		# Add new Lit history obj
		editHist = LitEditRecord(lastUserEdited = current_user.name)
		lit.update(push__l_edit_record=editHist)
		lit.update(set__last_edit = editHist)
		lit.reload()

		# Add new User edit history obj
		userHist = UserEditRecord(litEdited = str(lit.id), operation = "update", litEditedTitle = lit.title)
		current_user.update(push__u_edit_record=userHist)
		current_user.reload()

		lit = Lit.objects(id__iexact = lit_id).first()
		flash(lit.title + " has been updated")
	else:
		flash(lit.title + " failed to be updated")
	return render_template('lit.html', lit = lit)
예제 #21
0
def settings():

    form = SettingsForm(request.form, current_user)

    if form.validate_on_submit():
        current_user.update(form.penname.data,
                            form.intro.data,
                            form.gender.data,
                            form.city_id.data)

        flash(u'帐号设置已更新')
        return redirect(url_for('shelf.item',
                                shelf_id=current_user.shelf.id))

    return render_template('account/settings.html', form=form)
예제 #22
0
def changeProfilePic(form):
    filename = form.img.file.filename
    if form.validate() and filename != DEFAULT_PROFILE_PIC and allowed_file(filename):
        # Remove old_profile pic from storage
        if current_user.img != DEFAULT_PROFILE_PIC:
            subprocess.call("rm -f photos/%s" % str(current_user.img), shell=True)
        # Store file
        filename = current_user.uname + '_' + secure_filename(form.img.data.filename)
        # Save to DB
        form.img.file.save(os.path.join(current_app.config['UPLOAD_FOLDER'], filename))
        current_user.update(set__img=filename)
        current_user.save()
        # Successfully change pic
        flash("Successfully changed profile picture to %s" % filename)
        return render_template("settings.html", form=form, upform=UploadForm())
    return render_template("settings.html", form=form, upform=UploadForm())
예제 #23
0
파일: views.py 프로젝트: jwu130/OBET-1
def updateLitSub(lit_id):
	form = AddLitForm()
	lit = Lit.objects(id__iexact = lit_id).first()
	if form.validate_on_submit():
		lit.update(set__title=form.title.data)
		lit.update(set__refType=form.refType.data)
		lit.update(set__author=form.author.data)
		lit.update(set__primaryField=form.primaryField.data)
		lit.update(set__yrPublished = form.yrPublished.data)
		lit.update(set__sourceTitle = form.sourceTitle.data)
		lit.update(set__editor = form.editor.data)
		lit.update(set__placePublished = form.placePublished.data)
		lit.update(set__publisher = form.publisher.data)
		lit.update(set__volume = form.volume.data)
		lit.update(set__number = form.number.data)
		lit.update(set__pages = form.pages.data)
		lit.update(set__abstract = form.abstract.data)
		lit.update(set__notes = form.notes.data)
		lit.update(set__secondaryField= form.secondaryField.data)
		lit.update(set__link = form.link.data)

		lit.update(set__keywords = [])
		keywordslist = (form.keywords.data).split(",")
		print "this is the keywords: " + form.keywords.data
		for x in range(0, len(keywordslist)):
			key = str(keywordslist[x].strip())
			if key is not None :
				lit.update(push__keywords = key)

		# Update Lit history	
		editHist = LitEditRecord(lastUserEdited = current_user.name)
		lit.update(push__l_edit_record=editHist)
		lit.update(set__last_edit = editHist)
		lit.reload()

		# Update User edit history
		userHist = UserEditRecord(litEdited = str(lit.id), operation = "update", litEditedTitle = lit.title)
		current_user.update(push__u_edit_record=userHist)
		current_user.reload()

		lit = Lit.objects(id__iexact = lit_id).first()
		flash(lit.title + " has been updated")
	else:
		flash(lit.title + " failed to be updated")
	return render_template('lit.html', lit = lit)
예제 #24
0
def view(id=None, level_id=None):
    level = None

    if level_id:
        level = get_or_404(Level, id=level_id)

    elif current_user.grade:
        level = Level.objects.get(description=current_user.grade)

    if not current_user.grade:
        form = update_details_form()

        if form.validate_on_submit():
            current_user.update(grade=form.grade.data)
            flash("Successfully updated profile")
            return redirect(url_for(".view", id=id))

    return render_template("competency/view.html", level=level, competency=get_or_404(Competency, id=id))
예제 #25
0
def get_post():
    data = request.get_json()
    if data is None:
        abort(404)
    location = [data['longitude'], data['latitude']]
    posts = Post.objects(location__near=location).limit(MAX_POSTS_RETURNED)
    viewed_posts = current_user.viewed_posts
    for post in posts:
        if post not in viewed_posts:
            current_user.update(push__viewed_posts=post)
            post.update(inc__view_count=1)
            return jsonify({
                'id': str(post.id),
                'author': post.author.user_id,
                'date_created': post.date_created,
                'title': post.title,
                'content': post.content,
                'view_count': post.view_count,
                'support_count': post.view_count
            })
    return "error"
예제 #26
0
파일: pin.py 프로젝트: benk691/UCRinterest
def repin():
    id = request.form.get('id')
    pin = Pin.objects.get(id=id)
    newpin = Pin(title=pin.title,
                 img=pin.img,
                 dscrp=pin.dscrp,
                 orig=False,
                 date=datetime.now(),
                 pinner=current_user.to_dbref(),
                 repins=0,
                 like_count=0)
    newpin.save()
    if pin.repins == None:
        fix_repins()
        pin = Pin.objects.get(id=id)
    pin.repins = pin.repins + 1
    pin.save()
    current_user.update(add_to_set__repins_from=pin.pinner.to_dbref())
    current_user.save()
    flash("Pin repinned")
    return redirect('/viewprofile/%s/pins' % str(current_user.uname))
예제 #27
0
def updateUserCommenterPermissions(form):
    '''
    Updates commenter permissions on users pins
    '''
    perm = form.data['pin_commenters']
    current_user.update(set__pin_commenters=perm)
    current_user.save()
    pins = Pin.objects.filter(pinner=current_user.to_dbref())
    if type(pins) == type(''):
        pins = [ pins ]
    # Everyone has permission
    if perm == PERM_EVERYONE:
        for pin in pins:
            pin.invalid_commenters = []
            pin.save()
    # Your followers have permission
    elif perm == PERM_FOLLOWERS:
        invalid = getFollowerPermissions()
        for pin in pins:
            pin.invalid_commenters = invalid
            pin.save()
    # People you follow have permission
    elif perm == PERM_FOLLOWING:
        invalid = getFollowingPermissions()
        for pin in pins:
            pin.invalid_commenters = invalid
            pin.save()
    # Followers and following get permission
    elif perm == PERM_BOTH:
        invalid = getBothPermissions()
        for pin in pins:
            pin.invalid_commenters = invalid
            pin.save()
    # Nobody has permission
    elif perm == PERM_NOBODY:
        invalid = [ usr.to_dbref() for usr in User.objects.all() if usr.uname != current_user.uname ]
        for pin in pins:
            pin.invalid_commenters = invalid
            pin.save()
예제 #28
0
파일: views.py 프로젝트: techiecheckie/OBET
def edit_profile():
	form = EditProfileForm()

	# On form submit, update profile information
 	if form.validate_on_submit():
 		current_user.update(set__name=form.name.data)
 		current_user.update(set__location=form.location.data)
 		current_user.update(set__credentials = form.credentials.data)
 		current_user.update(set__description = form.description.data)
 		flash('Your profile has been updated.')
 		return redirect(url_for('.user', email = current_user.email))

 	# If no submission, return form prefilled with current user profile information
 	form = EditProfileForm(None, current_user)
 	return render_template('editProfile.html', form=form)
예제 #29
0
def edit_profile():
    form = EditProfileForm()

    # On form submit, update profile information
    if form.validate_on_submit():
        current_user.update(set__name=form.name.data)
        current_user.update(set__location=form.location.data)
        current_user.update(set__credentials=form.credentials.data)
        current_user.update(set__description=form.description.data)
        flash('Your profile has been updated.')
        return redirect(url_for('.user', email=current_user.email))

# If no submission, return form prefilled with current user profile information
    form = EditProfileForm(None, current_user)
    return render_template('editProfile.html', form=form)
예제 #30
0
파일: views.py 프로젝트: techiecheckie/OBET
def preferences():
 	form = Preferences()
 	
 	# If the user is logged in, take their preferences
	if current_user.is_authenticated():
		preferences = {"author": current_user.author, "yrPublished": current_user.yrPublished, "title":current_user.title, "sourceTitle": current_user.sourceTitle, "primaryField": current_user.primaryField, "creator": current_user.creator, "dateCreatedOn": current_user.dateCreatedOn, "editor": current_user.editor, "refType": current_user.refType, "lastModified": current_user.lastModified, "lastModifiedBy": current_user.lastModifiedBy}
 	else:
 		# Get cookie containing pref
 		preferences = request.cookies.get('preferences')
		if preferences:
			preferences = json.loads(preferences)

 	# If user does not have pref, give default
	if not preferences:
		preferences = default_pref

	# Debugging
	# print "GOT PREFERENCE"
	# for item in preferences:
	# 	print item + " "  + str(preferences[item])
	# print "END PREFERENCES FROM COOKIE"

	# If form is being submitted
 	if form.validate_on_submit():

 		# Create a dict from preferences in the form 
 		for attr in form:
 			preferences[attr.name] = attr.data 
		preferencesobj = Struct(**preferences)
 		form = Preferences(None, obj=preferencesobj)

 		# If user is logged in, save preferences to the db
 		if current_user.is_authenticated():
	 		current_user.update(set__title = form.title.data)
	 		current_user.update(set__author = form.author.data)
	 		current_user.update(set__primaryField = form.primaryField.data)
	 		current_user.update(set__editor = form.editor.data)
	 		current_user.update(set__yrPublished = form.yrPublished.data)
	 		current_user.update(set__refType = form.refType.data)
	 		current_user.update(set__creator = form.creator.data)
	 		current_user.update(set__dateCreatedOn = form.dateCreatedOn.data)
	 		current_user.update(set__lastModified = form.lastModified.data)
	 		current_user.update(set__lastModifiedBy = form.lastModifiedBy.data)
	 		flash('Your preferences have been saved')

	 	# Otherwise save their preferences to their browser as a cookie
 		else:
 			flash('Your preferences have been saved for your session')
			response = make_response(render_template('preferences.html', form=form))
	 		response.set_cookie('preferences', json.dumps(preferences))
			return response

 	# If no form is submitted, return the form prefilled with old preferences
	preferencesobj = Struct(**preferences) 	
 	form = Preferences(None, preferencesobj)
 	return render_template('preferences.html', form=form)
예제 #31
0
    def show(self, action):
        UA = UserActions()
        self.required_roles = []
        template = ""
        data = {}
        try:
            if current_user.is_authenticated():
                data.update({"message": "You're already logged in."})
            else:
                data.update({
                    "login_form": LoginForm(),
                    "reg_form": RegistrationForm()
                })

            if action == "logout":
                # Logout
                if current_user.is_authenticated():
                    result = UA.logout()
                    if result["status"] == "success":
                        return redirect(
                            request.args.get("next")
                            or url_for("pages.index", name="home"))
                    else:
                        data.update({
                            "message":
                            "Unknown error occurred. Could not log user out."
                        })
                else:
                    return redirect(url_for("user.index", action="login"))

            elif action == "login":
                # Login
                template = "login"
                if request.form:
                    lform = LoginForm(request.form)
                    if lform.validate():
                        result = UA.login(email=lform.email.data,
                                          password=lform.password.data,
                                          remember=False)
                        if result["status"] == "success":
                            nxt_url = request.args.get("next")
                            if not nxt_url or nxt_url == "/":
                                nxt_url = url_for("dashboard.index")

                            return redirect(nxt_url)
                        else:
                            data.update({
                                "status": "failed",
                                "message": result["message"]
                            })
                    else:
                        data.update({"login_form": lform})

            elif action == "register" and request.form:
                # User registration
                rform = RegistrationForm(request.form)

            elif action == "account" and current_user.is_authenticated():
                # User account page
                data.update({"message": "", "status": ""})

                self.required_roles = [
                    "provider", "viewer", "subscriber", "buyer"
                ]
                template = "account"
                UUD = UpdateUserData(request.form)

                if request.form:
                    if UUD.validate():
                        if UUD.password.data:
                            UUD.password.data = UA.encrypt_password(
                                UUD.password.data)
                        else:
                            UUD.password.data = current_user.password

                        current_user.password = UUD.password.data
                        current_user.update()

                        data.update({
                            "message":
                            "Successfully updated your account details",
                            "status": "success"
                        })
                else:
                    UUD.name.data = current_user.get_name()

                data.update({"update_form": UUD})

            return self.render("user/" + template + ".html", data=data)
        except Exception as e:
            self.error_handle.get_error(
                error=str(e), occurred_at="mad.modules.UserView.show()")
            abort(401)
예제 #32
0
def updateSettings(form):
    if form.validate():
        # Set all string fields
        current_user.update(set__fname=form.data['fname'])
        current_user.update(set__lname=form.data['lname'])
        current_user.update(set__email=form.data['email'])
        current_user.update(set__gender=form.data['gender'])
        current_user.update(set__bday=form.data['bday'])
        current_user.update(set__dscrp=form.data['dscrp'])
        # Update permissions
        if current_user.pin_browsers != form.data['pin_browsers']:
            updateUserBrowserPermissions(form)
            flash("Updated invalid browsers")
        if current_user.pin_commenters != form.data['pin_commenters']:
            updateUserCommenterPermissions(form)
            flash("Updated invalid commenters")
        current_user.save()
        flash("Settings have been saved successfully!")
        # Go to profile
        return redirect("/viewprofile/%s/pins" % str(current_user.uname))
    flash("Form is invalid!")
    return render_template("settings.html", form=form, upform=UploadForm())
예제 #33
0
def new_submission():
    if current_user.get_role() == "Site Admin":
        return redirect(url_for("content.activity"))

    # Build the submission form
    from biocomputedm.manage import forms
    form = forms.NewSubmissionForm()

    # Current user information
    folder = current_user.display_key

    # Build path to the users sftp dir
    directory_path = os.path.join(current_app.config["SFTP_USER_ROOT_PATH"], folder)
    directory_path = os.path.join(directory_path, "staged_files")

    # list of the available files in user directory
    filepaths = next(os.walk(directory_path))
    files = []

    for file in filepaths[1]:
        path = os.path.join(directory_path, file)
        s = os.stat(path)
        files.append({
            "name": file,
            "path": path,
            "size": os.path.getsize(path),
            "date": time.ctime(s.st_ctime)
        })

    for file in filepaths[2]:
        # rx = re.compile("^(.*)(?<!\.fastq)\.(7z|bz2|deb|gz|tar|tbz2|xz|tgz|rar|zip|Z)$")
        # if rx.match(file):
        path = os.path.join(directory_path, file)
        s = os.stat(path)
        files.append({
            "name": file,
            "path": path,
            "size": s.st_size,
            "date": time.ctime(s.st_ctime)
        })

    # List the available files in group directory
    directory_path = os.path.join(current_app.config["SFTP_USER_ROOT_PATH"], current_user.group.name)
    directory_path = os.path.join(directory_path, "staged_files")
    filepaths = next(os.walk(directory_path))

    for file in filepaths[1]:
        path = os.path.join(directory_path, file)
        s = os.stat(path)
        files.append({
            "name": file,
            "path": path,
            "size": os.path.getsize(path),
            "date": time.ctime(s.st_ctime)
        })

    for file in filepaths[2]:
        # rx = re.compile("^(.*)(?<!\.fastq)\.(7z|bz2|deb|gz|tar|tbz2|xz|tgz|rar|zip|Z)$")
        # if rx.match(file):
        path = os.path.join(directory_path, file)
        s = os.stat(path)
        files.append({
            "name": file,
            "path": path,
            "size": s.st_size,
            "date": time.ctime(s.st_ctime)
        })

    # If we are just looking at the page don't perform any of the validation work
    if request.method == "GET":
        return render_template("new_submission.html", title="New Data Submission", form=form, files=files)

    else:
        if form.validate_on_submit():
            # Check to see that at least 1 upload was selected - empty submissions have no use
            ids = request.form.getlist("do_select")
            if ids is None or len(ids) == 0:
                flash("No data uploads were selected.", "warning")
                return render_template("new_submission.html", title="New Data Submission", form=form, files=files)

            else:
                # Create the submission entry
                submission = Submission(name=str(form.submission_name.data), description=str(form.submission_description.data))

                # Unpack option
                unpack = bool(form.submission_unpack.data)
                if unpack:
                    unpack = "True"
                else:
                    unpack = "False"

                # Get the user and group
                group = current_user.group
                group.submissions.append(submission)
                current_user.submissions.append(submission)
                submission.save()
                current_user.update()
                group.update()

                # Create the directory to hold the submission
                output_directory_path = os.path.join(utils.get_path("submission_data", "webserver"), submission.display_key)
                utils.make_directory(output_directory_path)

                # Submit the directory and uploaded file information to our m.u.d. script
                script_path = os.path.join(utils.get_path("scripts", "webserver"), "io")
                script_path = os.path.join(script_path, "mud.sh")
                sources = ""
                for file in files:
                    for i in ids:
                        if file["name"] == i:
                            sources = sources + file["path"] + ","
                            break
                sources = sources[:-1]  # remove that pesky extra comma :D

                # Execute our move, unpack and delete script asynchronously so as to not interrupt webserving
                with open(os.devnull, "w") as fnull:
                    subprocess.Popen(
                        [
                            "sudo",
                            script_path,
                            "-d=" + output_directory_path,
                            "-s=" + sources,
                            "-i=" + submission.display_key,
                            "-p=" + current_app.config["LOCAL_WEBSERVER_PORT"],
                            "-u=" + unpack
                        ],
                        stdout=fnull,
                        stderr=fnull
                    )  # We are allowing this to execute on it's own - no need to monitor

                # In the meantime we will inform the user and display confirmation
                flash("Submission Successful.", "success")
                return render_template("submission_complete.html", title="Successful Job Submission")

        else:
            utils.flash_errors(form)
            return render_template("new_submission.html", title="New Data Submission", form=form, files=files)
예제 #34
0
def unfollow():
    id = request.form.get('pinner')
    user = User.objects.get(id=id)
    current_user.update(pull__follower_array=user.to_dbref())
    current_user.save()
    return redirect("/viewprofile/" + current_user.uname + "/following")
예제 #35
0
파일: views.py 프로젝트: jwu130/OBET-1
def edit_profile():
	form = EditProfileForm()
 	if form.validate_on_submit():
 		current_user.update(set__name=form.name.data)
 		current_user.update(set__location=form.location.data)
 		current_user.update(set__credentials = form.credentials.data)
 		current_user.update(set__description = form.description.data)
 		current_user.update(set__title = form.title.data)
 		current_user.update(set__author = form.author.data)
 		current_user.update(set__primaryField = form.primaryField.data)
 		current_user.update(set__editor = form.editor.data)
 		current_user.update(set__yearPublished = form.yearPublished.data)
 		current_user.update(set__refType = form.refType.data)
 		current_user.update(set__creator = form.creator.data)
 		current_user.update(set__dateCreatedOn = form.dateCreatedOn.data)
 		current_user.update(set__lastModified = form.lastModified.data)
 		current_user.update(set__lastModifiedBy = form.lastModifiedBy.data)
 		flash('Your profile has been updated.')
 		return redirect(url_for('.user', email = current_user.email))
 	form = EditProfileForm(None, current_user)
 	return render_template('editProfile.html', form=form)
예제 #36
0
파일: view.py 프로젝트: bnkamalesh/flaav
	def show(self, action):
		UA = UserActions()
		self.required_roles = []
		template = ""
		data = {}
		try:
			if current_user.is_authenticated():
				data.update({"message": "You're already logged in."})
			else:
				data.update({
					"login_form": LoginForm(),
					"reg_form": RegistrationForm()
				})

			if action=="logout":
				# Logout
				if current_user.is_authenticated():
					result = UA.logout()
					if result["status"]=="success":
						return redirect(request.args.get("next") or url_for("pages.index", name="home"))
					else:
						data.update({"message": "Unknown error occurred. Could not log user out."})
				else:
					return redirect(url_for("user.index", action="login"))

			elif action=="login":
				# Login
				template = "login"
				if request.form:
					lform = LoginForm(request.form)
					if lform.validate():
						result = UA.login(email=lform.email.data, password=lform.password.data, remember=False)
						if result["status"]=="success":
							nxt_url = request.args.get("next")
							if not nxt_url or nxt_url == "/":
								nxt_url = url_for("dashboard.index")

							return redirect(nxt_url)
						else:
							data.update({"status": "failed", "message": result["message"]})
					else:
						data.update({"login_form": lform})

			elif action=="register" and request.form:
				# User registration
				rform = RegistrationForm(request.form)

			elif action=="account" and current_user.is_authenticated():
				# User account page
				data.update({"message": "", "status": ""})

				self.required_roles = ["provider", "viewer", "subscriber", "buyer"]
				template = "account"
				UUD = UpdateUserData(request.form)

				if request.form:
					if UUD.validate():
						if UUD.password.data:
							UUD.password.data = UA.encrypt_password(UUD.password.data)
						else:
							UUD.password.data = current_user.password
						
						current_user.password = UUD.password.data
						current_user.update()

						data.update({"message": "Successfully updated your account details", "status": "success"})
				else:
					UUD.name.data = current_user.get_name()

				data.update({"update_form": UUD})

			return self.render("user/"+template+".html", data=data)
		except Exception as e:
			self.error_handle.get_error(error=str(e), occurred_at="mad.modules.UserView.show()")
			abort(401)
예제 #37
0
def addLit():

    # Create new add lit form
    form = AddLitForm()

    # On form submission
    if form.validate_on_submit():

        # If the literature is already in the database, then do not add the material, return
        lit = Lit.objects(title__iexact=form.title.data,
                          author__iexact=form.author.data,
                          pages__iexact=form.pages.data).first()
        if lit is not None:
            flash("This is already in the DB. This is the page")
            return render_template('lit.html', lit=lit)

        # Create a new lit object, save to db first, then update fields
        lit = Lit(refType=form.refType.data,
                  title=form.title.data,
                  author=form.author.data,
                  primaryField=form.primaryField.data,
                  creator=current_user.name)
        lit.save()
        lit.update(set__yrPublished=form.yrPublished.data)
        lit.update(set__sourceTitle=form.sourceTitle.data)
        lit.update(set__editor=form.editor.data)
        lit.update(set__placePublished=form.placePublished.data)
        lit.update(set__publisher=form.publisher.data)
        lit.update(set__volume=form.volume.data)
        lit.update(set__number=form.number.data)
        lit.update(set__pages=form.pages.data)
        lit.update(set__abstract=form.abstract.data)
        lit.update(set__notes=form.notes.data)
        lit.update(set__secondaryField=form.secondaryField.data)

        # Add user's edit in edit history
        editHist = LitEditRecord(lastUserEdited=current_user.name)

        # If the link field is not empty, save the link too
        # If statement is done because update fails when attempting to save an empty string
        if form.link.data is not None:
            lit.update(set__link=form.link.data)

        # Add keywords into the db as a listField
        keywordslist = (form.keywords.data).split(",")
        for x in range(0, len(keywordslist)):
            key = str(keywordslist[x].strip())
            lit.update(push__keywords=key)

        # Update lit history
        lit.update(push__l_edit_record=editHist)
        lit.update(set__last_edit=editHist)
        lit.reload()

        # Update user edit history
        userHist = UserEditRecord(litEdited=str(lit.id),
                                  operation="add",
                                  litEditedTitle=lit.title)
        current_user.update(push__u_edit_record=userHist)
        current_user.reload()

        flash("Successfully added!")
        return redirect(url_for('main.lit', lit_id=lit.id))
    return render_template('addLit.html', form=form)
예제 #38
0
def preferences():
    form = Preferences()

    # If the user is logged in, take their preferences
    if current_user.is_authenticated():
        preferences = {
            "author": current_user.author,
            "yrPublished": current_user.yrPublished,
            "title": current_user.title,
            "sourceTitle": current_user.sourceTitle,
            "primaryField": current_user.primaryField,
            "creator": current_user.creator,
            "dateCreatedOn": current_user.dateCreatedOn,
            "editor": current_user.editor,
            "refType": current_user.refType,
            "lastModified": current_user.lastModified,
            "lastModifiedBy": current_user.lastModifiedBy
        }
    else:
        # Get cookie containing pref
        preferences = request.cookies.get('preferences')
        if preferences:
            preferences = json.loads(preferences)

    # If user does not have pref, give default
    if not preferences:
        preferences = default_pref

# Debugging
# print "GOT PREFERENCE"
# for item in preferences:
# 	print item + " "  + str(preferences[item])
# print "END PREFERENCES FROM COOKIE"

# If form is being submitted
    if form.validate_on_submit():

        # Create a dict from preferences in the form
        for attr in form:
            preferences[attr.name] = attr.data
        preferencesobj = Struct(**preferences)
        form = Preferences(None, obj=preferencesobj)

        # If user is logged in, save preferences to the db
        if current_user.is_authenticated():
            current_user.update(set__title=form.title.data)
            current_user.update(set__author=form.author.data)
            current_user.update(set__primaryField=form.primaryField.data)
            current_user.update(set__editor=form.editor.data)
            current_user.update(set__yrPublished=form.yrPublished.data)
            current_user.update(set__refType=form.refType.data)
            current_user.update(set__creator=form.creator.data)
            current_user.update(set__dateCreatedOn=form.dateCreatedOn.data)
            current_user.update(set__lastModified=form.lastModified.data)
            current_user.update(set__lastModifiedBy=form.lastModifiedBy.data)
            flash('Your preferences have been saved')

# Otherwise save their preferences to their browser as a cookie
        else:
            flash('Your preferences have been saved for your session')
            response = make_response(
                render_template('preferences.html', form=form))
            response.set_cookie('preferences', json.dumps(preferences))
            return response

    # If no form is submitted, return the form prefilled with old preferences
    preferencesobj = Struct(**preferences)
    form = Preferences(None, preferencesobj)
    return render_template('preferences.html', form=form)
예제 #39
0
def delete(project_id):
    current_user.update(pull__projects=project_id)
    Project.objects(id=project_id)[0].delete()
    set_project()
    return redirect(url_for('dashboard._dashboard'))