Exemple #1
0
def product(id):
    product = Product.query.get_or_404(id)
    comment = None
    form = None
    if current_user.is_authenticated():
        form = CommentForm()
        if form.validate_on_submit():
            comment = Comment(body=form.body.data, product=product, author=current_user)
    if comment:
        db.session.add(comment)
        db.session.commit()
        flash(gettext(u'Your comment has been published.'))
        return redirect(url_for('.product', id=product.id) + '#top')

    page = request.args.get('page', 1, type=int)
    per_page = current_app.config['COMMENTS_PER_PAGE']
    total = product.comments.count()
    comments = product.comments.order_by(Comment.timestamp.asc()).paginate(page, per_page, False).items
    pagination = Pagination(page=page, total=total, record_name='comments', per_page=per_page)
    stations = {}
    headers = {}
    if current_user.is_authenticated():
        headers['X-XSS-Protection'] = '0'
        
    return render_template('products/product.html', product=product, form=form, comments=comments, pagination=pagination, Status=Status, Operation=Operation), 200, headers
Exemple #2
0
def global_template_context():
    if current_user.is_authenticated():
        if (current_user.email_addr == current_user.name or
                current_user.email_addr == "None"):
            flash(lazy_gettext("Please update your e-mail address in your profile page,"
                  " right now it is empty!"), 'error')

    # Announcement sections
    if app.config.get('ANNOUNCEMENT'):
        announcement = app.config['ANNOUNCEMENT']
        if current_user.is_authenticated():
            for key in announcement.keys():
                if key == 'admin' and current_user.admin:
                    flash(announcement[key], 'info')
                if key == 'owner' and len(current_user.apps) != 0:
                    flash(announcement[key], 'info')
                if key == 'user':
                    flash(announcement[key], 'info')

    return dict(
        brand=app.config['BRAND'],
        title=app.config['TITLE'],
        logo=app.config['LOGO'],
        copyright=app.config['COPYRIGHT'],
        description=app.config['DESCRIPTION'],
        terms_of_use=app.config['TERMSOFUSE'],
        data_use=app.config['DATAUSE'],
        enforce_privacy=app.config['ENFORCE_PRIVACY'],
        version=pybossa.__version__,
        current_user=current_user)
def test_category_get_forums(forum, user):
    category = forum.category

    with current_app.test_request_context():
        # Test with logged in user
        login_user(user)
        assert current_user.is_authenticated()
        cat, forums = Category.get_forums(category.id, current_user)

        # Check if it is a list because in a category there are normally more
        # than one forum in it (not in these tests)
        assert isinstance(forums, list) is True

        assert forums == [(forum, None)]
        assert cat == category

        # Test the same thing with a logged out user
        logout_user()
        assert not current_user.is_authenticated()
        cat, forums = Category.get_forums(category.id, current_user)

        # Check if it is a list because in a category there are normally more
        # than one forum in it (not in these tests)
        assert isinstance(forums, list) is True

        assert forums == [(forum, None)]
        assert cat == category
def test_topic_update_read(database, user, topic):
    """Tests the update read method if the topic is unread/read."""
    forumsread = ForumsRead.query.\
        filter(ForumsRead.user_id == user.id,
               ForumsRead.forum_id == topic.forum_id).first()

    with current_app.test_request_context():
        # Test with logged in user
        login_user(user)
        assert current_user.is_authenticated()

        # Update the tracker
        assert topic.update_read(current_user, topic.forum, forumsread)
        # Because the tracker is already up-to-date, it shouldn't update it
        # again.
        assert not topic.update_read(current_user, topic.forum, forumsread)

        # Adding a new post - now the tracker shouldn't be up-to-date anymore.
        post = Post(content="Test Content")
        post.save(topic=topic, user=user)

        forumsread = ForumsRead.query.\
            filter(ForumsRead.user_id == user.id,
                   ForumsRead.forum_id == topic.forum_id).first()

        # Test tracker length
        flaskbb_config["TRACKER_LENGTH"] = 0
        assert not topic.update_read(current_user, topic.forum, forumsread)
        flaskbb_config["TRACKER_LENGTH"] = 1
        assert topic.update_read(current_user, topic.forum, forumsread)

        # Test with logged out user
        logout_user()
        assert not current_user.is_authenticated()
        assert not topic.update_read(current_user, topic.forum, forumsread)
    def test_user_gets_logged_out(self, client, user):
        with client:
            login_user(user, remember=True)
            assert current_user.is_authenticated()

            client.get(url_for('auth.logout'))
            assert not current_user.is_authenticated()
def test_category_get_all(forum, user):
    category = forum.category

    with current_app.test_request_context():
        # Test with logged in user
        login_user(user)
        assert current_user.is_authenticated()
        categories = Category.get_all(current_user)

        # All categories are stored in a list
        assert isinstance(categories, list)
        # The forums for a category are also stored in a list
        assert isinstance(categories[0][1], list)

        assert categories == [(category, [(forum, None)])]

        # Test with logged out user
        logout_user()
        assert not current_user.is_authenticated()
        categories = Category.get_all(current_user)

        # All categories are stored in a list
        assert isinstance(categories, list)
        # The forums for a category are also stored in a list
        assert isinstance(categories[0][1], list)

        assert categories == [(category, [(forum, None)])]
def profile():
    if current_user.is_authenticated():
        user = current_user
    else:
        user = None
    
    form = ProfileForm(obj=user)

    if not form.password or form.password == '':
        del form.password
    
    if form.validate_on_submit():
        if user:
            flash('Successfully updated your profile.')
        else:
            user = User()
            user.role = 1
            flash('Congratulations, you just created an account!')

        form.populate_obj(user)
        db.session.add(user)
        db.session.commit()

        if not current_user.is_authenticated():
            login_user(user)

        return redirect('/')

    return render_template('demographic.html', form=form)
Exemple #8
0
def authenticate(project):
    print "authenticate"
    print current_user, current_user.is_authenticated()

    if not current_user.is_authenticated():
        print "logging in user"
        user = User()
        db.session.add(user)
        db.session.commit()
        login_user(user)

    if project in current_user.projects:
        print "p:", project
        current_user.current_project = project
        db.session.commit()
        return redirect(url_for('.project', project=project))

    form = LoginForm()
    if form.validate_on_submit():
        print "p:", project
        current_user.current_project = project
        current_user.projects.append(project)
        db.session.commit()
        return redirect(url_for('.project', project=project))

    return render_template('authenticate.html',
                           project=project,
                           form=form)
Exemple #9
0
def talk(id):
    talk = Talk.query.get_or_404(id)
    comment = None
    if current_user.is_authenticated():
        form = PresenterCommentForm()
        if form.validate_on_submit():
            comment = Comment(body=form.body.data, talk=talk, author=current_user, notify=False, approved=True)
    else:
        form = CommentForm()
        if form.validate_on_submit():
            comment = Comment(body=form.body.data, talk=talk, author_name=form.name.data, author_email=form.email.data, notify=form.notify.data, approved=False)
    if comment:
        db.session.add(comment)
        db.session.commit()
        if comment.approved:
            send_comment_notification(comment)
            flash('Your comment has been published.')
        else:
            send_author_notification(talk)
            flash('Your comment will be published after it is reviewed by the presenter.')
        return redirect(url_for('.talk', id=talk.id) + '#top')
    if talk.author == current_user or (current_user.is_authenticated() and current_user.is_admin):
        comments_query = talk.comments
    else:
        comments_query = talk.approved_comments()
    page = request.args.get('page', 1, type=int)
    pagination = comments_query.order_by(Comment.timestamp.asc()).paginate(page, per_page=current_app.config['COMMENTS_PER_PAGE'], error_out=False)
    comments = pagination.items
    headers = {}
    if current_user.is_authenticated():
        headers['X-XSS-Protection'] = '0'
    return render_template('talks/talk.html', talk=talk, form=form, comments=comments, pagination=pagination), 200, headers
def view_form_history(word=None):
    page = flask.g.database.get_page(get_url(word))
    access_edit = False
    if page is not None:
        # Проверка на права пользователя вносить правки в статью
        if current_user.is_authenticated():
            access_edit = access_f(page['access'], current_user)
    if current_user.is_authenticated():
        if current_user.is_admin():
             access_edit = True

    if current_user.is_authenticated() is False or access_edit is False:
        return render_template('page.html',
                               page=None,
                               message=u"Вы не имеете прав на просмотр истории изменения страницы",
                               navigation=True,
                               word=get_url(word),
                               history = True
                               )

    pages = flask.g.database.get_pages_history(get_url(word))
#    if pages is None:
#        return 'error!'
#    else:
    return render_template('history.html', pages=pages, word=get_url(word), navigation=True, history = True)
Exemple #11
0
    def _global_template_context():
        notify_admin = False
        if current_user and current_user.is_authenticated():
            if current_user.email_addr == current_user.name:
                flash(gettext("Please update your e-mail address in your"
                      " profile page, right now it is empty!"), 'error')
        if (current_user and current_user.is_authenticated()
            and current_user.admin):
            key = NEWS_FEED_KEY + str(current_user.id)
            if sentinel.slave.get(key):
                notify_admin = True
            news = get_news()
        else:
            news = None

        # Cookies warning
        cookie_name = app.config['BRAND'] + "_accept_cookies"
        show_cookies_warning = False
        if request and (not request.cookies.get(cookie_name)):
            show_cookies_warning = True

        # Announcement sections
        if app.config.get('ANNOUNCEMENT'):
            announcement = app.config['ANNOUNCEMENT']
            if current_user and current_user.is_authenticated():
                for key in announcement.keys():
                    if key == 'admin' and current_user.admin:
                        flash(announcement[key], 'info')
                    if key == 'owner' and len(current_user.projects) != 0:
                        flash(announcement[key], 'info')
                    if key == 'user':
                        flash(announcement[key], 'info')

        if app.config.get('CONTACT_EMAIL'):  # pragma: no cover
            contact_email = app.config.get('CONTACT_EMAIL')
        else:
            contact_email = '*****@*****.**'

        if app.config.get('CONTACT_TWITTER'):  # pragma: no cover
            contact_twitter = app.config.get('CONTACT_TWITTER')
        else:
            contact_twitter = 'PyBossa'

        return dict(
            brand=app.config['BRAND'],
            title=app.config['TITLE'],
            logo=app.config['LOGO'],
            copyright=app.config['COPYRIGHT'],
            description=app.config['DESCRIPTION'],
            terms_of_use=app.config['TERMSOFUSE'],
            data_use=app.config['DATAUSE'],
            enforce_privacy=app.config['ENFORCE_PRIVACY'],
            # version=pybossa.__version__,
            current_user=current_user,
            show_cookies_warning=show_cookies_warning,
            contact_email=contact_email,
            contact_twitter=contact_twitter,
            upload_method=app.config['UPLOAD_METHOD'],
            news=news,
            notify_admin=notify_admin)
Exemple #12
0
    def before_request():

        if current_user.is_authenticated() and current_user.is_user() and not current_user.active:
            logout_user()
            error(msg=Item.data('active_alert_text', '你的帐号已被封号处理!', name='封号提示'))

        if current_user.is_authenticated() \
                and request.endpoint not in current_app.user_manager.config.allow_oauth_urls \
                and not request.path.startswith('/admin'):

            um = current_app.user_manager
            model = um.config.oauth_model
            remember = um.config.oauth_remember

            um.models.User.heart()
            if not current_user.is_user():
                if model == 'auto':
                    user = um.models.User.from_oauth(current_user)
                    login_user(user, remember=remember)
                    return
            elif current_user.phone or current_user.email or model == 'auto':
                return

            if is_json():
                abort(NEED_BIND)

            query = urlencode(dict(next=request.url))
            return redirect('%s?%s' % (current_app.user_manager.config.bind_url, query))
Exemple #13
0
 def test_logout_when_loggedin(self):
     with app.test_client() as c, authenticated_user(c):
         rv = c.get('/')
         self.assertTrue(current_user.is_authenticated())
         rv = c.get('/logout')
         self.assertEquals(rv.status_code, 302)
         self.assertFalse(current_user.is_authenticated())
def before_request():
    if current_user.is_authenticated()\
        and not current_user/.confirmed \
        and request.endpoint[:5] !='auth.':
    return redirect(url_for('auth.unconfirmed'))

@auth.route('/unconfirmed')
Exemple #15
0
def product_post_review(id):
    product_id = id
    reviewform = AddReview()

    if not current_user.is_authenticated():
        abort(401)

    if current_user.is_authenticated():
        author_id = current_user.id
        pub_date = datetime.datetime.now()

        if reviewform.validate_on_submit():
            review_text = unicode(reviewform.review_text.data)
            review = Review(product_id=product_id, author_id=author_id, pub_date=pub_date, review_text=review_text)
            db.session.add(review)
            db.session.commit()
            if review.product.review_count is None:
                review.product.review_count = 1
            else:
                review.product.review_count += 1
            db.session.commit()
            resp = {'user': current_user.nickname, 'review': escape(review_text), 'reviewid': review.id}
            return jsonify(resp)
            # return redirect(url_for('product', id=product_id)) #            +'#'+unicode(review.id))
        else:
            return "Something went wrong", 406
Exemple #16
0
    def before_request():
        if current_user.is_authenticated() and "channel" in str(current_user.get_id()):
            return

        if current_user.is_authenticated() and current_user.is_user() and not current_user.active:
            logout_user()
            error(msg=Item.data("active_alert_text", "你的帐号已被封号处理!", name="封号提示"))

        if (
            current_user.is_authenticated()
            and request.endpoint not in current_app.user_manager.config.allow_oauth_urls
            and not request.path.startswith("/admin")
        ):

            um = current_app.user_manager
            model = um.config.oauth_model
            remember = um.config.oauth_remember

            um.models.User.heart()
            if not current_user.is_user():
                if model == "auto":
                    user = um.models.User.from_oauth(current_user)
                    login_user(user, remember=remember)
                    return
            elif current_user.phone or current_user.email or model == "auto":
                return

            if is_json():
                abort(NEED_BIND)

            query = urlencode(dict(next=request.url))
            return redirect("%s?%s" % (current_app.user_manager.config.bind_url, query))
Exemple #17
0
def add_viewed():
    print current_user.is_authenticated()
    school_name = request.form['school_name']
    is_Favorite = request.form['is_Favorite']
    # user_id = current_user.get_id()
    school = School.query.filter_by(name=school_name).first_or_404()
    user_id = '*****@*****.**'
    student = Student.query.filter_by(email=user_id).first_or_404()
    message = ""
    if len(student.viewed_schools) == 0:
        student.viewed_schools.append(school)
    else:
        for item in student.viewed_schools:
            if item.id == school.id:
                message = "Viewed"
                break
            else:
                student.viewed_schools.append(school)
    if is_Favorite:
        if len(student.favorite_schools) == 0:
            student.favorite_schools.append(school)
        else:
            for item in student.favorite_schools:
                if item.id == school.id:
                    message = message + " Favorited"
                    return message
                else:
                    student.favorite_schools.append(school)
    db.session.commit()
    return "complete"
def index():
	error=''
	k=sqlite3.connect('test.db')
	c=sqlite3.connect('test.db')
        form=PostForm()
	if request.form.get('comment'):
		if current_user.is_authenticated():
			username=current_user.username
		else:
			username="******"
		postid=request.form.get('postid')
		comment=request.form.get('commentbox')
		c.execute('INSERT INTO comments(username,postid,comment)VALUES(?,?,?)',[username,postid,comment])
                c.commit()
        if current_user.is_authenticated() and request.form.get('submit'):
                title=form.title.data
                body=form.body.data
                username=current_user.username
		if body!=None and title!='':
                	k.execute('INSERT INTO posts(username,title,body,date)VALUES(?,?,?,?)',[username,title,body,datetime.utcnow()])
                	k.commit()
	try:
                k=k.execute('select * from posts')
		c=c.execute('select * from comments')
		posts=[]
		comments=[]
		for x in k:
			posts.append([x[0],x[1],x[2],x[3],x[4]])
		for x in c:
			comments.append([x[0],x[1],x[2],x[3]])
		posts.sort(key=lambda x:x[4],reverse=True)
        except:
                posts=None
    	return render_template("index.html",title='Home',posts=posts,form=form,error=error,comments=comments)
Exemple #19
0
    def test_login_new_user(self):
        """
        Register a new user, log them in, view the profile
        """
        username = "******"
        password = "******"
        email = "*****@*****.**"

        profile_url = url_for("users.profile")

        resp = self.client.get(profile_url)
        self.assert_redirects(resp, url_for("users.login", next=url_for("users.profile")))

        response = self.register_new_user(username, email, password)

        self.assert_successful_registration(response)

        resp = self.client.get(profile_url)
        self.assert200(resp)

        self.logout_user()

        with self.client:
            self.assertRaises(AttributeError, lambda: current_user.is_authenticated())
            self.login_user(email, password)
            self.assertTrue(current_user.is_authenticated())

        self.logout_user()

        resp = self.client.get(profile_url)
        self.assert_redirects(resp, url_for("users.login", next=url_for("users.profile")))
Exemple #20
0
def index():
    if current_user.is_authenticated():
        form = PostForm()
        if current_user.can(Permission.WRITE_ARTICLES) and \
           form.validate_on_submit():
            post = Post(body=form.body.data,
                        author=current_user._get_current_object())
            db.session.add(post)
            return redirect(url_for('.index'))
        page = request.args.get('page', 1, type=int)
        show_followed = False
        if current_user.is_authenticated():
            show_followed = bool(request.cookies.get('show_followed', ''))
        if show_followed:
            query = current_user.followed_posts
        else:
            query = Post.query
        pagination = query.order_by(Post.timestamp.desc()).paginate(
            page, per_page=current_app.config['NETWORK_POSTS_PER_PAGE'],
            error_out=False)
        posts = pagination.items
        return render_template('main/index.html', user=user, form=form, posts=posts,
                           show_followed=show_followed, pagination=pagination)
    else:
        return redirect(url_for('auth.login'))
Exemple #21
0
    def _deny_hook(self, resource=None):
        app = self.get_app()
        if current_user.is_authenticated():
            status = 403
        else:
            status = 401
        #abort(status)

        if app.config.get('FRONTED_BY_NGINX'):
                url = "https://{}:{}{}".format(app.config.get('FQDN'), app.config.get('NGINX_PORT'), '/login')
        else:
                url = "http://{}:{}{}".format(app.config.get('FQDN'), app.config.get('API_PORT'), '/login')
        if current_user.is_authenticated():
            auth_dict = {
                "authenticated": True,
                "user": current_user.email,
                "roles": current_user.role,
            }
        else:
            auth_dict = {
                "authenticated": False,
                "user": None,
                "url": url
            }

        return Response(response=json.dumps({"auth": auth_dict}), status=status, mimetype="application/json")
Exemple #22
0
 def logged_in(cls, **kwargs):
     user_logged_in = False
     if not current_user.is_authenticated():
         raise ProcessingException(description='Not Authorized. Please log in first.', code=401)
     elif current_user.is_authenticated():
         user_logged_in = True
     return user_logged_in
def index():
	error=''
	k=sqlite3.connect('test.db')
        form=PostForm()
	if request.form.get('delete') and current_user.is_authenticated():
		id=request.form.get('idid')
		k.execute('DELETE FROM posts WHERE id=(?)',[id,])
		k.commit()
	if request.form.get('edit') and current_user.is_authenticated():
		id=request.form.get('idid')
		tname=request.form.get('tname'+id)
		tmark=request.form.get('tmark'+id)
		tsubject=request.form.get('tsubject'+id)
		if len(tname)>0 and len(tmark)>0:
			k.execute('UPDATE posts SET name=(?),subject=(?),mark=(?) WHERE id=(?)',[tname,tsubject,tmark,id])
			k.commit()
		else:
			error="All field required"
	elif request.form.get('edit'):error="sign in required/"
        if current_user.is_authenticated() and request.form.get('submit'):
                name=form.name.data
                mark=form.mark.data
		subject=form.subject.data
                username=current_user.username
		if mark!=None and name!='':
                	k.execute('INSERT INTO posts(username,name,subject,mark)VALUES(?,?,?,?)',[username,name,subject,mark])
                	k.commit()
	try:
                k=k.execute('select id,name,subject,mark from posts')
        except:
                k=None
    	return render_template("index.html",
                           title='Home',posts=k,form=form,error=error)
Exemple #24
0
def session():
    data = {
        'logged_in': current_user.is_authenticated(),
        'user': None
    }
    if current_user.is_authenticated():
        data['user'] = current_user
    return jsonify(data)
Exemple #25
0
    def decorated_view(*args, **kwargs):
        if not current_user.is_authenticated() or not session.get('user_id'):
            return redirect(url_for('home.index'))

        if current_user.is_authenticated() and not current_user.is_active():
            flash('Votre compte est desactive. Contactez votre administrateur', 'danger')
            return redirect(url_for('user.logout'))

        return func(*args, **kwargs)
Exemple #26
0
def home():
    """ Render home page with the cached apps and users"""
    d = {'featured': cached_apps.get_featured_front_page(),
         'top_apps': cached_apps.get_top(),
         'top_users': None,
         'categories': None,
         'apps': None,
         'n_apps_per_category': None}

    if app.config['ENFORCE_PRIVACY'] and current_user.is_authenticated():
        if current_user.admin:
            d['top_users'] = cached_users.get_top()
    if not app.config['ENFORCE_PRIVACY']:
        d['top_users'] = cached_users.get_top()
    # @FC
    categories = cached_cat.get_all()
    n_apps_per_category = dict()
    apps = dict()
    for c in categories:
        n_apps_per_category[c.short_name] = cached_apps.n_count(c.short_name)
        apps[c.short_name],count = cached_apps.get(c.short_name,1,1)
    d['categories'] = categories
    d['n_apps_per_category'] = n_apps_per_category
    d['apps'] = apps
    # Current user Survey System
    if current_user.is_authenticated():
        sql = text('''SELECT COUNT(task_run.id) AS task_run FROM task_run WHERE :cur_user_id=task_run.user_id''')
        results = db.engine.execute(sql,cur_user_id=current_user.id)
        for row in results:
            num_run_task=row.task_run
    if current_user.is_authenticated() and current_user.survey_check!= "None" and current_user.survey_check == "2":
        if num_run_task>=30:
			d['survey_three'] = True
			new_profile = model.User(id=current_user.id, survey_check="3")
			db.session.query(model.User).filter(model.User.id == current_user.id).first()
			db.session.merge(new_profile)
			db.session.commit()
			cached_users.delete_user_summary(current_user.name)
    elif current_user.is_authenticated() and current_user.survey_check!= "None" and current_user.survey_check == "1":
        if num_run_task>=1:
			d['survey_two'] = True
			new_profile = model.User(id=current_user.id, survey_check="2")
			db.session.query(model.User).filter(model.User.id == current_user.id).first()
			db.session.merge(new_profile)
			db.session.commit()
			cached_users.delete_user_summary(current_user.name)
    elif current_user.is_authenticated() and current_user.survey_check!= "None" and current_user.survey_check == "0":
        d['survey_one'] = True
        new_profile = model.User(id=current_user.id, survey_check="1")
        db.session.query(model.User).filter(model.User.id == current_user.id).first()
        db.session.merge(new_profile)
        db.session.commit()
        cached_users.delete_user_summary(current_user.name)
    else:
        d['survey_one'] = False
	# @FC
    return render_template('/home/index.html', **d)
Exemple #27
0
    def decorated_view(*args, **kwargs):
        if not current_user.is_authenticated() or not session.get('user_id'):
            return redirect(url_for('Home'))

        if current_user.is_authenticated() and not current_user.is_active():
            flash('Your account is disabled. Contact Administrator', 'danger')
            return redirect(url_for('logout_user'))

        return func(*args, **kwargs)
Exemple #28
0
def index():
	s = settings()
	loggedUsername = s.get(["cloudSlicer", "loggedUser"])

	if (s.getBoolean(["server", "firstRun"])):
		# we need to get the user to sign into their AstroPrint account
		return render_template(
			"setup.jinja2",
			debug= debug,
			uiApiKey= UI_API_KEY,
			version= VERSION,
			variantData= variantManager().data,
			astroboxName= networkManager.getHostname(),
			settings=s
		)

	elif softwareManager.updatingRelease or softwareManager.forceUpdateInfo:
		return render_template(
			"updating.jinja2",
			uiApiKey= UI_API_KEY,
			showForceUpdate=  softwareManager.forceUpdateInfo != None,
			releaseInfo= softwareManager.updatingRelease or softwareManager.forceUpdateInfo,
			variantData= variantManager().data,
			astroboxName= networkManager.getHostname()
		)

	elif loggedUsername and (current_user is None or not current_user.is_authenticated() or current_user.get_id() != loggedUsername):
		if current_user.is_authenticated():
			logout_user()

		return render_template(
			"locked.jinja2",
			username= loggedUsername,
			uiApiKey= UI_API_KEY,
			astroboxName= networkManager.getHostname(),
			variantData= variantManager().data
		)

	else:
		paused = printer.isPaused()
		printing = printer.isPrinting()
		online = networkManager.isOnline()
		
		return render_template(
			"app.jinja2",
			user_email= loggedUsername,
			version= VERSION,
			printing= printing,
			paused= paused,
			online= online,
			print_capture= cameraManager().timelapseInfo if printing or paused else None,
			printer_profile= printerProfileManager().data,
			uiApiKey= UI_API_KEY,
			astroboxName= networkManager.getHostname(),
			variantData= variantManager().data
		)
Exemple #29
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)
Exemple #30
0
def stats():
    if current_user.is_authenticated():
        return json.dumps(dict(online=True,
                               logged_in=True,
                               is_authenticated=current_user.is_authenticated(),
                               username=current_user.login,
                               type=current_user.type,
                               user_id=current_user.id))
    else:
        return json.dumps(dict(online=True,
                               logged_in=False))
Exemple #31
0
 def _is_requester_admin(self):
     return current_user.is_authenticated() and current_user.admin
 def connect_handler_notif_page():
     if current_user.is_authenticated():
         user_room = 'user_{}'.format(session['user_id'])
         join_room(user_room)
         emit('notifpage-response', {'meta': 'WS notifpage connected'},
              namespace='/notifpage')
Exemple #33
0
 def _auth_by_cookie(self):
     if not current_user.is_authenticated():
         raise Unauthorized()
Exemple #34
0
 def authorized(self):
     if request.method in self.auth_methods:
         return current_user.is_authenticated()
     return True
Exemple #35
0
def hello():
    if current_user.is_authenticated():
        return " User " + str(current_user.myemail()) + " is logged in "

    return "Hello World!"
Exemple #36
0
def design_download(print_file_id):
    if current_user is None or not current_user.is_authenticated(
    ) or not current_user.publicKey:
        abort(401)

    em = eventManager()

    def progressCb(progress):
        em.fire(Events.CLOUD_DOWNLOAD, {
            "type": "progress",
            "id": print_file_id,
            "progress": progress
        })

    def successCb(destFile, fileInfo):
        if fileInfo is True:
            #This means the files was already on the device
            em.fire(Events.CLOUD_DOWNLOAD, {
                "type": "success",
                "id": print_file_id
            })

        else:
            if printerManager().fileManager.saveCloudPrintFile(
                    destFile, fileInfo, FileDestinations.LOCAL):
                em.fire(
                    Events.CLOUD_DOWNLOAD, {
                        "type":
                        "success",
                        "id":
                        print_file_id,
                        "filename":
                        printerManager().fileManager._getBasicFilename(
                            destFile),
                        "info":
                        fileInfo["info"]
                    })

            else:
                errorCb(destFile, "Couldn't save the file")

    def errorCb(destFile, error):
        if error == 'cancelled':
            em.fire(Events.CLOUD_DOWNLOAD, {
                "type": "cancelled",
                "id": print_file_id
            })
        else:
            em.fire(Events.CLOUD_DOWNLOAD, {
                "type": "error",
                "id": print_file_id,
                "reason": error
            })

        if destFile and os.path.exists(destFile):
            os.remove(destFile)

    if astroprintCloud().download_print_file(print_file_id, progressCb,
                                             successCb, errorCb):
        return jsonify(SUCCESS)

    return abort(400)
Exemple #37
0
def ws_drink(drink):
    drink_mixer = app.mixer
    if app.options.must_login_to_dispense and not current_user.is_authenticated():
        return "login required"

    return ws_make_drink(drink)
Exemple #38
0
 def is_accessible(self):
     if current_app.config.get('DEBUG'):
         return True
     return current_user.is_authenticated()
Exemple #39
0
def before_request():
    if current_user.is_authenticated() \
            and not current_user.confirmed \
            and request.endpoint[:5] != 'auth.':
        return redirect(url_for('auth.unconfirmed'))
Exemple #40
0
def poll_vote(slug):
    poll = get_poll(slug)
    poll.check_expiry()

    # Check if user needs to log in
    if (poll.require_login
            or poll.require_invitation) and current_user.is_anonymous():
        flash(gettext("You need to login to vote on this poll."), "error")
        return redirect(
            url_for("login", next=url_for("poll_vote", slug=poll.slug)))

    # Check if user voted already
    if poll.one_vote_per_user and not current_user.is_anonymous(
    ) and poll.get_user_votes(current_user):
        flash(
            gettext(
                "You can only vote once on this poll. Please edit your choices by clicking the edit button on the right."
            ), "error")
        return redirect(poll.get_url())

    # Check if user was invited
    if poll.require_invitation and not current_user.is_invited(poll):
        flash(gettext("You need an invitation to vote on this poll."), "error")
        return redirect(poll.get_url())

    groups = poll.get_choice_groups()
    if not groups:
        flash(
            gettext(
                "The poll owner has not yet created any choices. You cannot vote on the poll yet."
            ), "warning")
        return redirect(poll.get_url())

    form = CreateVoteForm()

    if request.method == "POST":
        for subform in form.vote_choices:
            subform.value.choices = [(v.id, v.title)
                                     for v in poll.get_choice_values()]

        if form.validate_on_submit():
            vote = Vote()
            if current_user.is_anonymous():
                vote.name = form.name.data
            else:
                vote.user = current_user

            vote.anonymous = poll.anonymous_allowed and form.anonymous.data
            if vote.anonymous and not vote.user:
                vote.name = "anonymous"

            vote.comment = form.comment.data

            poll.votes.append(vote)

            for subform in form.vote_choices:
                choice = Choice.query.filter_by(
                    id=subform.choice_id.data).first()
                value = ChoiceValue.query.filter_by(
                    id=subform.value.data).first()
                if not choice or choice.poll != poll: abort(404)
                if value and value.poll != poll: abort(404)

                vote_choice = VoteChoice()
                vote_choice.value = value
                vote_choice.comment = subform.comment.data
                vote_choice.amount = subform.amount.data
                vote_choice.vote = vote
                vote_choice.choice = choice
                db.session.add(vote_choice)

            if current_user.is_authenticated():
                invitation = Invitation.query.filter_by(
                    user_id=current_user.id, poll_id=poll.id).first()
                if invitation:
                    invitation.vote = vote

            flash(gettext("You have voted."), "success")

            poll.send_watchers("[Dudel] New vote: " + poll.title,
                               "email/poll_voted.txt",
                               voter=vote.displayname)

            db.session.commit()

            if current_user.is_authenticated() and current_user.autowatch:
                return redirect(
                    url_for("poll_watch",
                            slug=poll.slug,
                            watch="yes",
                            next=poll.get_url()))
            else:
                return redirect(poll.get_url())

    if not request.method == "POST":
        poll.fill_vote_form(form)

        for subform in form.vote_choices:
            min_ = poll.amount_minimum or 0
            max_ = poll.amount_maximum or 0
            avg = min_ + (max_ - min_) / 2 if min_ != max_ else 0
            subform.amount.data = avg

    return render_template("poll/vote/edit.html", poll=poll, form=form)
Exemple #41
0
    def _global_template_context():
        notify_admin = False
        if current_user and current_user.is_authenticated():
            if current_user.email_addr == current_user.name:
                flash(
                    gettext("Please update your e-mail address in your"
                            " profile page, right now it is empty!"), 'error')
        if (current_user and current_user.is_authenticated()
                and current_user.admin):
            key = NEWS_FEED_KEY + str(current_user.id)
            if sentinel.slave.get(key):
                notify_admin = True
            news = get_news()
        else:
            news = None

        # Cookies warning
        cookie_name = app.config['BRAND'] + "_accept_cookies"
        show_cookies_warning = False
        if request and (not request.cookies.get(cookie_name)):
            show_cookies_warning = True

        # Announcement sections
        if app.config.get('ANNOUNCEMENT'):
            announcement = app.config['ANNOUNCEMENT']
            if current_user and current_user.is_authenticated():
                for key in announcement.keys():
                    if key == 'admin' and current_user.admin:
                        flash(announcement[key], 'info')
                    if key == 'owner' and len(current_user.projects) != 0:
                        flash(announcement[key], 'info')
                    if key == 'user':
                        flash(announcement[key], 'info')

        if app.config.get('CONTACT_EMAIL'):  # pragma: no cover
            contact_email = app.config.get('CONTACT_EMAIL')
        else:
            contact_email = '*****@*****.**'

        if app.config.get('CONTACT_TWITTER'):  # pragma: no cover
            contact_twitter = app.config.get('CONTACT_TWITTER')
        else:
            contact_twitter = 'PyBossa'

        # Available plugins
        plugins = plugin_manager.plugins

        return dict(
            brand=app.config['BRAND'],
            title=app.config['TITLE'],
            logo=app.config['LOGO'],
            copyright=app.config['COPYRIGHT'],
            description=app.config['DESCRIPTION'],
            terms_of_use=app.config['TERMSOFUSE'],
            data_use=app.config['DATAUSE'],
            enforce_privacy=app.config['ENFORCE_PRIVACY'],
            # version=pybossa.__version__,
            current_user=current_user,
            show_cookies_warning=show_cookies_warning,
            contact_email=contact_email,
            contact_twitter=contact_twitter,
            upload_method=app.config['UPLOAD_METHOD'],
            news=news,
            notify_admin=notify_admin,
            plugins=plugins)
Exemple #42
0
def ws_custom_drink():
    if app.options.must_login_to_dispense and not current_user.is_authenticated():
        return "login required"

    return ws_make_drink(0)
Exemple #43
0
def index():
    if current_user.is_authenticated():
        return redirect('/crowd/dashboard/')
    return render_template("/crowd/index.html", login_form=LoginForm())
Exemple #44
0
def manage_user_no_login(access_token, next_url):
    if current_user.is_authenticated():
        user = user_repo.get(current_user.id)
        user.info['twitter_token'] = access_token
        user_repo.save(user)
    return redirect(next_url)
Exemple #45
0
def restrict_access():
    if current_app.config.get('ENV') != 'test':
        if not current_user.is_authenticated() or current_user.is_anonymous():
            return redirect(url_for('users.login'))
def check_api_auth(**kw):
    if not current_user.is_authenticated():
        raise ProcessingException(description='Not authenticated!', code=401)
    return True
Exemple #47
0
def render_admin():
    if current_user.is_authenticated() is False:
        return redirect("/login", code=302)
    return app.send_static_file('admin.html')
Exemple #48
0
def before_request():
    if current_user.is_authenticated():
        current_user.ping()
Exemple #49
0
 def is_accessible(self):
     return (current_user.is_authenticated()
             and current_user.is_administrator())
Exemple #50
0
def login():
    if current_user.is_authenticated():
        flash('Already Logged in as %s' % current_user, category='success')
        return redirect(url_for('frontend.index'))

    return render_template('frontend/login.html')
Exemple #51
0
 def authorized(self):
     return current_user.is_authenticated()
            {{ message }}
          </div>
          {% endfor %}
        </div>
    {% endif %}
    {% endwith %}

    <div class="container">
      <div class="row">
        <div class="u-full-width">
          <nav class="menu">
          <!-- menu goes here -->
            <a href="{{ url_for('login') }}">Log in</a>
            <a href="{{ url_for('logout') }}">Log out</a>
            <a href="{{ url_for('register') }}">Sign up</a>
            {% if current_user.is_authenticated() %}
              <a href="{{ url_for('taco') }}">Add a New Taco</a>
              <a href="{{ url_for('logout') }}">Log Out</a>
            {% endif %}
          </nav>
          {% block content %}{% endblock %}
        </div>
      </div>
      <footer>
        <p>An MVP web app made with Flask on <a href="http://teamtreehouse.com">Treehouse</a>.</p>
      </footer>
    </div>
  </body>
</html>

Exemple #53
0
def get_astroprint_info():
    if current_user and current_user.is_authenticated(
    ) and current_user.privateKey:
        return jsonify(user=current_user.get_id())
    else:
        return jsonify(user=None)
Exemple #54
0
 def is_accessible(self):
     if current_user.get_role() == '0':
         return current_user.is_authenticated()
Exemple #55
0
 def get():
     if current_user.is_authenticated() and current_user.debug \
             or hasattr(current_app, 'enable_debug') and current_app.enable_debug():
         return [Enable.ENABLED, Enable.DEBUG]
     return [Enable.ENABLED]
Exemple #56
0
    def signin(self):
        if request.method == 'POST':
            if os.environ['CONFIG_VARIABLE'] == "config.DevelopmentConfig":
                if current_user is not None and current_user.is_authenticated:
                    return redirect(url_for('mypage.index'))
            if os.environ['CONFIG_VARIABLE'] == "config.ProductionConfig":
                if current_user is not None and current_user.is_authenticated(
                ):
                    return redirect(url_for('mypage.index'))

            form = SigninForm(request.form)
            if form.validate():
                user = Users.query.filter_by(
                    username=form.username.data).first()

                if user is None:
                    # username not found in db
                    form.username.errors.append('Username not found')
                    return render_template('signin.html',
                                           signin_form=form,
                                           page_title='Sign In | Crowdkast',
                                           signinpage_form=SigninForm())
                if user.password != hash_string(form.password.data):
                    # username found but password not the same as in db
                    form.password.errors.append(
                        'Passwords did not match. Try again!')
                    return render_template('signin.html',
                                           signin_form=form,
                                           page_title='Sign In | Crowdkast',
                                           signinpage_form=SigninForm())

                ## add the check to see if the user is confirmed or not
                ## else return to the flash a message saying
                ## confirm the email
                if not user.confirmed:
                    flash(
                        "Please click on the confirmation link sent to your email"
                    )
                    return render_template('signin.html',
                                           signin_form=form,
                                           page_title='Sign In | Crowdkast',
                                           signinpage_form=SigninForm())

## if the user is found and password is correct, login
                login_user(user, remember=form.remember_me.data)
                # store the following values in the session dictionary
                session['signed'] = True
                session['username'] = user.username

                ## if the user was looking for page which needs login, proceed to the page after login
                if session.get('next'):
                    next_page = session.get('next')
                    session.pop('next')
                    return redirect(next_page)
                else:
                    return redirect(
                        url_for('mypage.index', username=user.username))
            return render_template('signin.html',
                                   signin_form=form,
                                   page_title='Sign In | Linkedup',
                                   signinpage_form=SigninForm())
        else:
            session['next'] = request.args.get('next')
            return render_template('signin.html',
                                   signin_form=SigninForm(),
                                   signinpage_form=SigninForm(),
                                   page_title='Sign In | Linkedup')
Exemple #57
0
 def username():
     if current_user.is_authenticated():
         return current_user.name
     return u'Anonymous'
Exemple #58
0
def auth_func(**kw):
    if not current_user.is_authenticated():
        raise ProcessingException(description='Not Authorized', code=401)
Exemple #59
0
 def index(self):
     if not current_user.is_authenticated():
         return redirect(url_for('.login'))
     return super(MyIndexView, self).index()
Exemple #60
0
 def is_accessible(self):
     return current_user.is_authenticated()