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 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
Exemple #3
0
def contact():

    form = ReportForm(request.form)

    if current_user.is_authenticated():
        form = ReportForm(request.form, obj=current_user)

    if form.validate_on_submit():
        user_id = None
        if current_user.is_authenticated():
            user_id = current_user.id

        report = UserReports(
            user_id=user_id,
            email=form.email.data,
            subject=form.subject.data,
            message=form.message.data
        )

        db.session.add(report)
        db.session.commit()

        flash(gettext(u'Message sent. Thank you for contact. \
                        We really appreciate it!'),
              'success')
        return redirect(url_for('simple_page.index'))

    return render_template(
        'contact.html',
        form=form
    )
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)
Exemple #5
0
    def question(category_id, eid, title):
        category = Category.query.get_or_404(category_id)

        selected_lang = request.args.get('lang', DEFAULT_LANG)
        selected_platform = request.args.get('platform', g.detected_platform)
        question = (Question.query
                    .filter_by(category_id=category_id, eid=eid,
                               lang=selected_lang)
                    .filter(Question.platform.in_([DEFAULT_PLATFORM,
                                                   selected_platform]))
                    .first())
        if not question:
            abort(404)

        if current_user.is_authenticated() and request.method == 'DELETE':
            db.session.delete(question)
            return jsonify(success=True)

        form = QuestionForm(prefix='paano-question', obj=question)
        form.category_id.choices = [(c.id, c.title) for c in
                                    Category.query.order_by(Category.title).all()]

        if current_user.is_authenticated():
            if request.args.get('edit'):
                return render_template('paano/question_form.html', form=form)
            if form.validate_on_submit():
                form.populate_obj(question)
                db.session.add(question)
                db.session.flush()
                flash("Question saved")
                return redirect(question.url(platform=question.platform))

        return render_template('paano/question.html', category=category,
                               question=question)
Exemple #6
0
def entity(id, rev=None):
    review = Review.query.get_or_404(str(id))
    # Not showing review if it isn't published yet and not viewed by author.
    if review.is_draft and not (current_user.is_authenticated()
                                and current_user == review.user):
        raise NotFound(gettext("Can't find a review with the specified ID."))
    if review.is_hidden:
        if not current_user.is_admin():
            raise Forbidden(gettext("Review has been hidden. "
                                    "You need to be an administrator to view it."))
        else:
            flash(gettext("Review has been hidden."), 'warning')

    spotify_mappings = None
    if review.entity_type == 'release_group':
        spotify_mappings = mbspotify.mappings(review.entity_id)

    revisions = Revision.query.filter_by(review=review).order_by(desc(Revision.timestamp))
    count = revisions.count()
    if not rev:
        rev = count
    if rev < count:
        flash(gettext('You are viewing an old revision, the review has been updated since then.'))
    elif rev > count:
        raise NotFound(gettext("The revision you are looking for does not exist."))

    revision = revisions.offset(count-rev).first()
    if not review.is_draft and current_user.is_authenticated():  # if user is logged in, get his vote for this review
        vote = Vote.query.filter_by(user=current_user, revision=revision).first()
    else:  # otherwise set vote to None, its value will not be used
        vote = None
    review.text_html = markdown(revision.text, safe_mode="escape")
    return render_template('review/entity/%s.html' % review.entity_type, review=review, spotify_mappings=spotify_mappings, vote=vote)
Exemple #7
0
def usertraffic():
    """For anonymous users with a valid IP
    """
    try:
        ip = request.remote_addr
        trafficdata = query_trafficdata(ip)

        if current_user.is_authenticated():
            if current_user.userid is user_id_from_ip(ip):
                flash(gettext(u"Ein anderer Nutzer als der für diesen Anschluss"
                              u" Eingetragene ist angemeldet!"), "warning")
                flash(gettext("Hier werden die Trafficdaten "
                              "dieses Anschlusses angezeigt"), "info")
    except ForeignIPAccessError:
        flash(gettext(u"Deine IP gehört nicht zum Wohnheim!"), "error")

        if current_user.is_authenticated():
            flash(gettext(u"Da du angemeldet bist, kannst du deinen Traffic "
                          u"hier in der Usersuite einsehen."), "info")
            return redirect(url_for('usersuite.usersuite'))
        else:
            flash(gettext(u"Um deinen Traffic von außerhalb einsehen zu können,"
                          u" musst du dich anmelden."), "info")
            return redirect(url_for('login'))

    # todo test if the template works if called from this position
    return render_template("usertraffic.html", usertraffic=trafficdata)
Exemple #8
0
def activity():
    '''
    View for the activity feed of recent events.

    Note that we want anonymous users to be able to get a "sneak peek" at
    this page, so we allow them in; however, if the user has
    logged in but hasn't yet completed the registration process,
    we want them to finish it first.
    '''

    if (current_user.is_authenticated()
        and not current_user.has_fully_registered):
        return redirect(get_best_registration_step_url(current_user))

    if not session.get('activity_route_visited'):
        # reset tutorials if repeat_tutorials flag is set
        num_tutorials = 3
        if ('DISCOURSE_ENABLED' in current_app.jinja_env.globals):
            if (current_app.jinja_env.globals['DISCOURSE_ENABLED']):
                num_tutorials = 4
        if hasattr(current_user, 'repeat_tutorials'):
            if current_user.repeat_tutorials and current_user.tutorial_step > num_tutorials:
                current_user.tutorial_step = 1
                db.session.add(current_user)
                db.session.commit()


    events = get_latest_events()
    shared_message_form = SharedMessageForm()


    if request.method == 'POST':
        if not current_user.is_authenticated():
            flash(gettext(u'You must log in to post a message.'), 'error')
        elif not current_user.display_in_search:
            flash(gettext(u'We need your name before you can post a message.'), 'error')
        elif shared_message_form.validate():
            data = shared_message_form.message.data
            msg = SharedMessageEvent.from_user(
                current_user,
                message=data
            )
            db.session.add(msg)
            db.session.commit()
            flash(gettext(u'Message posted!'))
            return redirect(url_for('views.activity'))

    session['activity_route_visited'] = True;

    return render_template('activity.html', **{
        'user': current_user,
        'events': events,
        'blog_posts': get_blog_posts(),
        'page_config_json': json_blob(
            LOADING_TEXT=gettext("Loading...")
        ),
        'most_complete_profiles': User.get_most_complete_profiles(limit=5),
        'most_connected_profiles': User.get_most_connected_profiles(limit=5)
    })
Exemple #9
0
def filter_logic(f, limit, skip):
    query = []
    # retrieving lists
    if current_user.is_authenticated():
        if f['blacklistSelect'] == "on":
            regexes = db.getRules('blacklist')
            if len(regexes) != 0:
                exp = "^(?!" + "|".join(regexes) + ")"
                query.append({'$or': [{'vulnerable_configuration': re.compile(exp)},
                                      {'vulnerable_configuration': {'$exists': False}},
                                      {'vulnerable_configuration': []} ]})
        if f['whitelistSelect'] == "hide":
            regexes = db.getRules('whitelist')
            if len(regexes) != 0:
                exp = "^(?!" + "|".join(regexes) + ")"
                query.append({'$or': [{'vulnerable_configuration': re.compile(exp)},
                                      {'vulnerable_configuration': {'$exists': False}},
                                      {'vulnerable_configuration': []} ]})
        if f['unlistedSelect'] == "hide":
            wlregexes = compile(db.getRules('whitelist'))
            blregexes = compile(db.getRules('blacklist'))
            query.append({'$or': [{'vulnerable_configuration': {'$in': wlregexes}},
                                  {'vulnerable_configuration': {'$in': blregexes}}]})
    if f['rejectedSelect'] == "hide":
        exp = "^(?!\*\* REJECT \*\*\s+DO NOT USE THIS CANDIDATE NUMBER.*)"
        query.append({'summary': re.compile(exp)})

    # plugin filters
    query.extend(plugManager.doFilter(f, **pluginArgs()))

    # cvss logic
    if f['cvssSelect'] == "above":    query.append({'cvss': {'$gt': float(f['cvss'])}})
    elif f['cvssSelect'] == "equals": query.append({'cvss': float(f['cvss'])})
    elif f['cvssSelect'] == "below":  query.append({'cvss': {'$lt': float(f['cvss'])}})

    # date logic
    if f['timeSelect'] != "all":
        if f['startDate']:
            startDate = parse_datetime(f['startDate'], ignoretz=True, dayfirst=True)
        if f['endDate']:
            endDate   = parse_datetime(f['endDate'],   ignoretz=True, dayfirst=True)

        if f['timeSelect'] == "from":
            query.append({f['timeTypeSelect']: {'$gt': startDate}})
        if f['timeSelect'] == "until":
            query.append({f['timeTypeSelect']: {'$lt': endDate}})
        if f['timeSelect'] == "between":
            query.append({f['timeTypeSelect']: {'$gt': startDate, '$lt': endDate}})
        if f['timeSelect'] == "outside":
            query.append({'$or': [{f['timeTypeSelect']: {'$lt': startDate}}, {f['timeTypeSelect']: {'$gt': endDate}}]})
    cve=db.getCVEs(limit=limit, skip=skip, query=query)
    # marking relevant records
    if current_user.is_authenticated():
        if f['whitelistSelect'] == "on":   cve = whitelist_mark(cve)
        if f['blacklistSelect'] == "mark": cve = blacklist_mark(cve)
    plugManager.mark(cve, **pluginArgs())
    cve = list(cve)
    return cve
Exemple #10
0
    def main():
        if current_user.is_authenticated():
            form = PasteForm(request.form)
        else:
            print 'test'
            form = PasteFormNoAuth(request.form)

        if form.validate_on_submit():

            times = {
                '0':None,
                '1':{'minutes':+15},
                '2':{'minutes':+30},
                '3':{'hours':+1},
                '4':{'hours':+6},
                '5':{'hours':+12},
                '6':{'days':+1},
                '7':{'weeks':+1},
                '8':{'months':+1}
            }
            paste = database.Paste()

            paste.paste = form.text.data
            paste.digest = sha1(paste.paste.encode('utf-8')).hexdigest()

            if (current_user.is_authenticated()):
                paste.user = current_user.to_dbref()
            #Create a name and make sure it doesn't exist
            paste.name = random_string()
            collision_check = database.Paste.objects(name__exact=paste.name).first()
            while collision_check is not None:
                paste.name = random_string()
                collision_check = database.Paste.objects(name__exact=paste.name).first()

            if form.language.data is not None:
                paste.language = form.language.data
            else:
                try:
                    paste.language = guess_lexer(form.text.data).name
                except:
                    paste.language = 'text'
            paste.time = datetime.utcnow()

            if times.get(form.expiration.data) is not None:
                paste.expire = arrow.utcnow().replace(**times.get(form.expiration.data)).datetime
            if times.get(form.expiration.data) is None and not current_user.is_authenticated():
                paste.expire = arrow.utcnow.replace(**times.get(7))

            paste.save()
            return redirect('/{id}'.format(id=paste.name))


        return render_template('new_paste.html', form=form)
Exemple #11
0
def get_gi_vars():
    """Gets gallery item variables."""

    gallery_limit = app.config['GALLERY_LIMIT']

    if app.config.get('USE_SESSIONSTORE_NOT_DB'):
        gallery_count = len(session.get('gallery_item', []))
    else:
        gallery_count = (
            GalleryItem.query
                       .filter_by(active=True)
                       .count())

    if not gallery_count:
        default_gallery_items = get_default_gallery_items()
        gallery_count = len(default_gallery_items)

    is_gallery_showmore = request.args.get('gallery_showmore', None) == '1'

    is_gallery_showlimited = (
        (not current_user.is_authenticated()) and
        (not is_gallery_showmore) and
        (gallery_count > gallery_limit))

    gallery_items = get_gallery_items()

    if is_gallery_showlimited:
        if app.config.get('USE_SESSIONSTORE_NOT_DB'):
            gallery_items = gallery_items[:gallery_limit]
        else:
            gallery_items = gallery_items.limit(gallery_limit)

    if not app.config.get('USE_SESSIONSTORE_NOT_DB'):
        gallery_items = gallery_items.all()

    gallery_forms = {}
    if current_user.is_authenticated():
        for gi in gallery_items:
            gallery_forms[gi.id] = {
                'title': TextEditForm(content=gi.title),
                'image': ImageEditForm(image=gi.image),
                'content': LongTextEditForm(content=gi.content),
                'date_taken': TextEditForm(content=gi.date_taken)}

            if current_user.is_authenticated():
                gallery_forms[gi.id]['delete'] = Form()

    return (
        gallery_items,
        is_gallery_showlimited,
        gallery_forms)
Exemple #12
0
def tabs_list(id):
    likeform   = LikeForm()
    artist     = Artist.query.filter_by(id=id).first_or_404()
    dic_codes  = dict([(code.id,code.code_name) for code in Dic_code.query.all()])
    tabs_kind  = Dic_code.query.filter_by(parent_id=4).all()

    big_cates = Dic_code.query.filter_by(parent_id=1).all()
    for big_cate in big_cates:
        big_cate.children = Dic_code.query.filter(Dic_code.parent_id == big_cate.type_id).order_by(Dic_code.id)

    if request.method == 'POST' and likeform.validate_on_submit() and current_user.is_authenticated():
        if likeform.op.data == 'c':
            like = Like()
            like.save(likeform, current_user.id, 2)
            artist.fans = artist.fans + 1
        elif likeform.op.data == 'd':
            like = Like.query.filter_by(like_id=likeform.like_id.data).filter_by(uid=current_user.id)\
                    .filter_by(like_type=2).first()
            like.delete()
            if artist.fans != 0:
                artist.fans = artist.fans - 1
        db.session.commit()

    artist.hot = artist.hot + 1
    db.session.commit()


    if current_user.is_authenticated():
        like_tabs = [ like.like_id for like in Like.query.filter_by(uid=current_user.id)\
                    .filter_by(like_type=1).all() ]
    else:
        like_tabs = []

    kind_id =  request.args.get("kind")
    tabs    =  Tab.query.filter_by(artist=id).all()
    if kind_id:
        if kind_id == "all_tab" :
            tabs = tabs
        else:
            kind_id = int(kind_id)
            tabs    = Tab.query.filter(Tab.artist == id).filter(Tab.tabs_type == kind_id).all() 
        return render_template('artists/tabs_filter_ajax.html', tabs=tabs, dic_codes=dic_codes,\
            form=likeform, like_tabs=like_tabs)

    is_like = None
    if current_user.is_authenticated():
        is_like = Like.query.filter_by(uid=current_user.id).filter_by(like_type=2)\
                    .filter_by(like_id=id).first()
    
    return render_template('artists/tabs_list.html', artist=artist, tabs=tabs, is_like=is_like,\
        dic_codes=dic_codes, tabs_kind=tabs_kind, form=likeform, like_tabs=like_tabs, big_cates=big_cates)
def login():
    if current_user.is_authenticated():
        return redirect(url_for('views.home'), code=302)

    if request.method == 'POST':
        login_form = request.form
        user.login(login_form.get('email'), login_form.get('password'))

        if current_user.is_authenticated():
            next_url = request.args.get('next',url_for('views.home'))
            return redirect(next_url, code=302)
        else:
            return render_template('login.html', failure=True, email=login_form.get('email'))

    return render_template('login.html', failure=False, email='')
Exemple #14
0
def dispatchApiCall(reqJson):

	forwarded_for = request.headers.get('X-Forwarded-For', None)

	# if forwarded_for == '108.28.56.67':
	# 	print("Bouncing possible abuse from %s" % (forwarded_for, ))
	# 	return getResponse("Hi there! Please contact me on github.com/fake-name/wlnupdates before doing bulk scraping, please!", error=True)

	if not "mode" in reqJson:
		print("API JSON Request without mode!")
		return getResponse("No mode in API Request!", error=True)

	mode = reqJson["mode"]
	if not mode in DISPATCH_TABLE:
		print("Invalid mode in request: '{mode}'".format(mode=mode))
		return getResponse("Invalid mode in API Request ({mode})!".format(mode=mode), error=True)

	dispatch_method, auth_required, csrf_required, rate_limited = DISPATCH_TABLE[mode]
	try:
		if csrf_required:
			csrf.protect()

		if auth_required and not current_user.is_authenticated():
			return getResponse(LOGIN_REQ, error=True)

		if rate_limited and not current_user.is_authenticated():
			limiter_key = forwarded_for + " " + mode
			if limiter_key in RATE_LIMITER:
				print("Anon User hit rate limiting. Bouncing.")
				return getResponse("API calls when not logged in are rate limited. Please either log in, or slow down. "
					"Complain at github.com/fake-name/wlnupdates/issues if this is a problem", error=True)

			print("Inserting anon requester into rate-limit cache.")
			RATE_LIMITER[limiter_key] = True

			ret = dispatch_method(reqJson)

		else:
			ret = dispatch_method(reqJson)

	except AssertionError as e:
		traceback.print_exc()
		print(reqJson)
		return getResponse("Error processing API request: '%s'!" % e, error=True)



	return ret
def login():
    print current_user
    if current_user.is_authenticated():
        return redirect('/')

    if len(request.data):
        # 表示这是前端通过ajax发送的post请求
        json_data = json.loads(request.data)

        user = UserEntity.query.filter_by(username=json_data['username']).first()

        if user is not None and user.password == hashlib.md5(json_data['password']).hexdigest():
            # 登录成功
            login_user(user)
            result = ResultModel(ResultModel.SUCCESS_CODE, ResultModel.SUCCESS_MSG, None)
        elif user is not None and user.password != json_data['password']:
            # 密码错误
            result = ResultModel(ResultModel.FAILED_CODE, '密码错误', None)
        else:
            # 用户不存在
            result = ResultModel(ResultModel.FAILED_CODE, '用户不存在', None)
        return jsonify(vars(result))
    else:
        # 表明这是通过get方式发送的请求,因此跳转到登录页面让用户进行登录
        return render_template('login.html')
Exemple #16
0
def login():
    """
    Attempt to log into the LDAP server with the authentication
    provided by a form.
    """
    try:
        if current_user.is_authenticated():
            if opt['VERBOSE']:
                print(current_user)
            return redirect(url_for('edit_data', lang='en')), 302

        form = request.form
        username = form['user']
        password = form['pass']

        if opt['VERBOSE']:
            print(username)

        User.try_login(username, password)
        user = User.get_by_uname(username)
        if not user:
            user = User(username)
            user.add_to_db()
        session['uid'] = user.id
        login_user(user)
        return redirect(url_for('edit_data', lang='en')), 302

    except Exception, ex:
        if opt['VERBOSE']:
            print(ex)
        return render_template('login_fail.html'), 401
Exemple #17
0
    def __init__(self, slug, name):
        assert current_user.is_authenticated()

        self.slug = slug
        self.name = name
        self.members.append(GroupMember(user_id=current_user.id,
                                        is_admin=True))
Exemple #18
0
 def is_accessible(self):
     return (
         not AUTHENTICATE or (
             not current_user.is_anonymous() and
             current_user.is_authenticated()
         )
     )
Exemple #19
0
def login(self, request, session=None):
    if current_user.is_authenticated():
        flash("You are already logged in")
        return redirect(url_for('admin.index'))

    username = None
    password = None

    form = LoginForm(request.form)

    if request.method == 'POST' and form.validate():
        username = request.form.get("username")
        password = request.form.get("password")

    try:
        user = authenticate(session, username, password)
        flask_login.login_user(user)

        return redirect(request.args.get("next") or url_for("admin.index"))
    except AuthenticationError:
        flash("Incorrect login details")
        return self.render('airflow/login.html',
                           title="Airflow - Login",
                           form=form)
    finally:
        session.commit()
        session.close()
Exemple #20
0
    def _handle_view(self, name, **kwargs):
        """The method will be executed before calling any view method."""
        if not current_user.is_authenticated():
            return current_app.login_manager.unauthorized()

        if not self.is_accessible():
            return abort(403)
Exemple #21
0
def login():
    if app.config["LOGADMIN"] == True:
        user_login(app.config["ADMIN_EMAIL"])
    if current_user.is_authenticated():
        flash("Already logged in")
        return redirect(url_for("showAllCourses"))
    return render_template("login.html")
Exemple #22
0
def login():
    if current_user.is_authenticated():
        return redirect(request.args.get('next') or '/')

    if not settings.PASSWORD_LOGIN_ENABLED:
        if settings.SAML_LOGIN_ENABLED:
            return redirect(url_for("saml_auth.sp_initiated", next=request.args.get('next')))
        else:
            return redirect(url_for("google_oauth.authorize", next=request.args.get('next')))


    if request.method == 'POST':
        user = models.User.select().where(models.User.email == request.form['username']).first()
        if user and user.verify_password(request.form['password']):
            remember = ('remember' in request.form)
            login_user(user, remember=remember)
            return redirect(request.args.get('next') or '/')

    return render_template("login.html",
                           name=settings.NAME,
                           analytics=settings.ANALYTICS,
                           next=request.args.get('next'),
                           username=request.form.get('username', ''),
                           show_google_openid=settings.GOOGLE_OAUTH_ENABLED,
                           show_saml_login=settings.SAML_LOGIN_ENABLED)
Exemple #23
0
def buscartipoItem2():
    """ Funcion para buscar registros de la tabla de Tipo de Item""" 
    if not current_user.is_authenticated():
        flash('Debe loguearse primeramente!!!!', 'loggin')
        return render_template('index.html')
    
    permission =UserPermission('LIDER PROYECTO', int(session['pry']))
    if permission.can()==False:
        flash('No posee los permisos suficientes para realizar la operacion', 'info')
        return render_template('index.html')  
    
    valor = request.args['patron']
    parametro = request.args['parametro']
    #init_db(db_session)
    if valor == "" : 
        administrartipoItem()
    if parametro == 'id_fase':
        ti = db_session.query(TipoItem).from_statement("SELECT * FROM tipo_item where "+parametro+" in (SELECT id FROM fase where nombre ilike '%"+valor+"%' )").all()
    else:
        ti = db_session.query(TipoItem).from_statement("SELECT * FROM tipo_item where "+parametro+" ilike '%"+valor+"%'").all()
    return render_template('tipoItem/listartipoItem.html', tipoItems2 = ti)    
    
    valor = request.args['patron']
    #init_db(db_session)
    r = db_session.query(TipoItem).filter_by(nombre=valor)
    if r == None:
        return 'no existe concordancia'
    return render_template('tipoItem/listartipoItem.html', tipoItems2 = r)
Exemple #24
0
def check_session_id():
    """
    Generate a UUID and store it in the session
    as well as in the WebSession table.
    """
    # TODO: Create UserAgentEntity and populate
    user_agent = get_user_agent()

    if 'uuid' not in session:
        session['uuid'] = str(uuid.uuid4())
        WebSessionEntity.create(session_id=session['uuid'],
                                user_id=current_user.get_id(),
                                ip=request.remote_addr,
                                date_time=datetime.datetime.now(),
                                user_agent=user_agent)
        return
    if current_user.is_authenticated():
        # update the user_id on the first request after login is completed
        session_id = session['uuid']
        web_session = WebSessionEntity.get_by_session_id(session_id)
        if web_session is not None:
            web_session = WebSessionEntity.update(
                web_session,
                user_id=current_user.get_id())
        else:
            app.logger.error("No row found for sess_id: {}".format(session_id))
Exemple #25
0
def access():
    """Access."""
    try:
        mail = mail_cookie_check_mail_activation(request.values['mailcookie'])

        u = User.query.filter(User.email == mail).one()
        u.note = 1
        try:
            db.session.commit()
        except SQLAlchemyError:
            db.session.rollback()
            flash(_('Authorization failled.'), 'error')
            redirect('/')

        if current_user.is_authenticated():
            current_user.reload()
            flash(_('Your email address has been validated'), 'success')
        else:
            UserInfo(u.id).reload()
            flash(
                _('Your email address has been validated, and you can '
                  'now proceed to sign-in.'),
                'success'
            )
    except Exception:
        current_app.logger.exception("Authorization failed.")
        flash(_('The authorization token is invalid.'), 'error')
    return redirect('/')
Exemple #26
0
def eliminartipoItem():
    """ Funcion para eliminar registros de la tabla de Tipo de Item"""
    if not current_user.is_authenticated():
        flash('Debe loguearse primeramente!!!!', 'loggin')
        return render_template('index.html')
    
    permission =UserPermission('LIDER PROYECTO', int(session['pry']))
    if permission.can()==False:
        flash('No posee los permisos suficientes para realizar la operacion', 'info')
        return render_template('index.html')  
    
    try:
        cod = request.args.get('cod')
        tipoItem = db_session.query(TipoItem).filter_by(codigo=cod).first()  
        items= db_session.query(Item).filter_by(id_tipo_item=tipoItem.id).first()
        cant = db_session.query(TItemAtributo).filter_by(id_tipo_item=tipoItem.id).count()
        cnt = 0
        #se verifica si el tipo de item esta siendo utilizado, en tal caso no podra ser eliminado 
        if items !=  None :
            flash('El Tipo de Item no puede ser eliminado, ya que esta siendo utilizado por algun Item!','info')
            return render_template('tipoItem/administrartipoItem.html')
        while cnt < cant :
            cnt = cnt + 1
            tt = db_session.query(TItemAtributo).filter_by(id_tipo_item=tipoItem.id).first()  
            db_session.delete(tt)
            db_session.commit()
        db_session.delete(tipoItem)
        db_session.commit()
        flash('El tipo item ha sido eliminado con exito','info')
        return redirect('/tipoItem/administrartipoItem')
    except DatabaseError, e:
            flash('Error en la Base de Datos' + e.args[0],'info')
            return render_template('tipoItem/administrartipoItem.html')
Exemple #27
0
def buscarsolicitudavotar():
    if not current_user.is_authenticated():
        flash('Debe loguearse primeramente!!!!', 'loggin')
        return render_template('index.html')
    
    idusuario = current_user.id
    idproyecto= session['pry']
    valor = request.args['patron']
    parametro = request.args['parametro']
    if valor=='' or valor == None:
        return administrarsolicitudavotar()
    else:
        if parametro == 'fecha':
            try:
                fecha = datetime.strptime(valor, '%Y-%m-%d')
                solicitudes = db_session.query(SolicitudCambio).join(MiembrosComite, MiembrosComite.id_proyecto == SolicitudCambio.id_proyecto).filter(MiembrosComite.id_usuario == idusuario).filter(SolicitudCambio.id_proyecto == idproyecto).filter(SolicitudCambio.estado == 'E').filter(SolicitudCambio.fecha == fecha).all()
            except ValueError:
                solicitudes =[]
        elif parametro == 'nombre':
            solicitudes = db_session.query(SolicitudCambio).join(MiembrosComite, MiembrosComite.id_proyecto == SolicitudCambio.id_proyecto).filter(MiembrosComite.id_usuario == idusuario).join(Usuario, SolicitudCambio.id_usuario == Usuario.id).filter(SolicitudCambio.id_proyecto == idproyecto).filter(SolicitudCambio.estado == 'E').filter(or_(Usuario.nombre.ilike('%'+valor+'%'),Usuario.apellido.ilike('%'+valor+'%'))).all()
        elif parametro == 'cant_votos':
            if valor.isdigit() :
                solicitudes = db_session.query(SolicitudCambio).join(MiembrosComite, MiembrosComite.id_proyecto == SolicitudCambio.id_proyecto).filter(MiembrosComite.id_usuario == idusuario).filter(SolicitudCambio.id_proyecto == idproyecto).filter(SolicitudCambio.estado == 'E').filter(SolicitudCambio.cant_votos == valor).all()
            else :
                solicitudes = []
        elif parametro == 'descripcion' :
            solicitudes = db_session.query(SolicitudCambio).join(MiembrosComite, MiembrosComite.id_proyecto == SolicitudCambio.id_proyecto).filter(MiembrosComite.id_usuario == idusuario).filter(SolicitudCambio.id_proyecto == idproyecto).filter(SolicitudCambio.estado == 'E').filter(SolicitudCambio.descripcion.ilike('%'+valor+'%')).all()
            #relaciones = db_session.query(Relacion).from_statement("SELECT * FROM relacion where to_char("+parametro+", '99999') ilike '%"+valor+"%'").all()
            #p = db_session.query(Relacion).from_statement("SELECT * FROM relacion where "+parametro+" = CAST("+valor+" AS Int)").all()
        else:
            return administrarsolicitudavotar()()
    #p = db_session.query(Relacion).filter(Relacion.codigo.like('%'+valor+ '%'))
        return render_template('solicitudavotar/administrarsolicitudavotar.html', solicitudes = solicitudes)
Exemple #28
0
def login():
    """Login page for users
    """
    form = LoginForm()

    if form.validate_on_submit():
        username = form.username.data
        password = form.password.data

        try:
            user = authenticate(username, password)
        except UserNotFound:
            flash(gettext(u"Nutzer nicht gefunden!"), "error")
        except PasswordInvalid:
            flash(gettext(u"Passwort war inkorrekt!"), "error")
        else:
            if isinstance(user, User):
                login_user(user)
    elif form.is_submitted():
        flash_formerrors(form)

    if current_user.is_authenticated():
        return redirect(url_for('usersuite.usersuite'))

    return render_template('login.html', form=form)
Exemple #29
0
def dispatchApiCall(reqJson):
	print("Json request:", reqJson)
	if not "mode" in reqJson:
		print("API JSON Request without mode!")
		return getResponse("No mode in API Request!", error=True)

	mode = reqJson["mode"]
	if not mode in DISPATCH_TABLE:
		print("Invalid mode in request: '{mode}'".format(mode=mode))
		return getResponse("Invalid mode in API Request ({mode})!".format(mode=mode), error=True)

	dispatch_method, auth_required, csrf_required = DISPATCH_TABLE[mode]
	try:
		if csrf_required:
			csrf.protect()

		if auth_required and not current_user.is_authenticated():
			return getResponse(LOGIN_REQ, error=True)

		else:
			ret = dispatch_method(reqJson)

	except AssertionError as e:
		traceback.print_exc()
		print(reqJson)
		return getResponse("Error processing API request: '%s'!" % e, error=True)



	return ret
Exemple #30
0
def entity(id):
    id = str(id)
    event = musicbrainz.get_event_by_id(id)
    if not event:
        raise NotFound(gettext("Sorry, we couldn't find a event with that MusicBrainz ID."))

    if 'artist-relation-list' in event and event['artist-relation-list']:
        artists_sorted = sorted(event['artist-relation-list'], key=itemgetter('type'))
        event['artists_grouped'] = groupby(artists_sorted, itemgetter('type'))

    if current_user.is_authenticated():
        my_reviews, my_count = Review.list(entity_id=id, entity_type='event', user_id=current_user.id)
        if my_count != 0:
            my_review = my_reviews[0]
        else:
            my_review = None
    else:
        my_review = None

    limit = int(request.args.get('limit', default=10))
    offset = int(request.args.get('offset', default=0))
    reviews, count = Review.list(entity_id=id, entity_type='event', sort='rating', limit=limit, offset=offset)

    return render_template('event/entity.html', id=id, event=event, reviews=reviews,
                           my_review=my_review, limit=limit, offset=offset, count=count)
Exemple #31
0
def logout():
    try:
        instagram_username = current_user.insta_username
        if current_user.is_authenticated():
            client.delete(instagram_username)
            session.clear()
        logout_user()
        client.delete(instagram_username)
        session.clear()
    except:
        pass
    return redirect(url_for('core.index'))
Exemple #32
0
 def decorated_view(*args, **kwargs):
     if not current_user.is_authenticated():
         return current_app.login_manager.unauthorized()
     try:
         if current_user.is_admin():
             return fn(*args, **kwargs)
     except AttributeError:
         pass
     user_unauthorized.send(current_app._get_current_object())
     flash("Admin login required for this page", "error")
     #return redirect(login_url(current_app.login_manager.login_view,request.url))
     return "Admin login required"
Exemple #33
0
def likePost(post_id):
    post = db.session.query(Posts).filter_by(id=post_id).first()
    if current_user.is_authenticated():
        id = current_user.id
        like = Likes(id, post_id)
        db.session.add(like)
        db.session.commit()
        return jsonify(message="Post Liked!", likes=len(post.likes)), 201

    #Flash message to indicate that an error occurred
    failure = "Failed to like post"
    return jsonify(error=failure)
def login():
    if current_user.is_authenticated():
        return redirect(url_for('authentication.dashboard'))
    form = LoginForm()
    if form.validate_on_submit():
        # login and validate user
        user = User.load_user(form.username.data, form.password.data)
        if user:
            login_user(user)
            return redirect(url_for('authentication.dashboard'))
        flash("Incorrect username or password")
    return render_template("login.html", form=form)
Exemple #35
0
def get_access_levels():
    open_for = 1
    visibility = 1

    if current_user.is_authenticated() and current_user.is_active():
        open_for = 2
        visibility = 2

        if current_user.has_role('ROLE_ADMIN'):
            open_for = 3
            visibility = 3
    return {'visibility':visibility, 'open_for':open_for}
Exemple #36
0
 def filter_logic(self, filters, skip, limit=None):
     query = self.generate_full_query(filters)
     limit = limit if limit else self.args['pageLength']
     cve = db.getCVEs(limit=limit, skip=skip, query=query)
     # marking relevant records
     if current_user.is_authenticated():
         if filters['whitelistSelect'] == "on":
             cve['results'] = self.list_mark('white', cve['results'])
         if filters['blacklistSelect'] == "mark":
             cve['results'] = self.list_mark('black', cve['results'])
     self.plugManager.mark(cve, **self.pluginArgs)
     return cve
Exemple #37
0
def render_login_local():
    """ Render the login page with username/pass

    @see #index()
    @see #render_login_shib()
    """
    if current_user.is_authenticated():
        return redirect(get_role_landing_page())

    uuid = session['uuid']
    form = LoginForm(request.form)

    if request.method == 'POST' and form.validate():
        email = form.email.data.strip(
        ) if form.email.data else "*****@*****.**"
        password = form.password.data.strip() if form.password.data else ""
        app.logger.debug("{} password: {}".format(email, password))

        app.logger.debug("Checking email: {}".format(email))
        user = UserEntity.query.filter_by(email=email).first()

        if user:
            app.logger.debug("Found user object: {}".format(user))
        else:
            utils.flash_error("No such email: {}".format(email))
            LogEntity.login(uuid, "No such email: {}".format(email))
            return redirect(url_for('index'))

        password_hash = user.password_hash

        # @TODO: enforce the `local password` policy
        if '' == password_hash or \
                utils.is_valid_auth(app.config['SECRET_KEY'],
                                    password_hash[0:16],
                                    password,
                                    password_hash[17:]):
            app.logger.info('Log login event for: {}'.format(user))
            LogEntity.login(uuid, 'Successful login via email/password')
            login_user(user, remember=False, force=False)

            # Tell Flask-Principal that the identity has changed
            identity_changed.send(current_app._get_current_object(),
                                  identity=Identity(user.get_id()))
            return redirect(get_role_landing_page())
        else:
            app.logger.info('Incorrect pass for: {}'.format(user))
            LogEntity.login_error(uuid, 'Incorrect pass for: {}'.format(user))
            utils.flash_error("Incorrect username/password.")

    # When sending a GET request render the login form
    return render_template('index.html',
                           form=form,
                           next_page=request.args.get('next'))
Exemple #38
0
def restless_api_auth(*args, **kwargs):
    """Restrict access to logged in user or valid admin api key
    Flask-Restless preprocessor"""
    if current_user.is_authenticated():
        return  # allow

    # check for system api key
    admin_key = current_app.config.get('ADMIN_API_KEY')
    if admin_key and request.args.get('api_key') == admin_key:
        return  # allow

    abort(401, 'Not Authenticated')
Exemple #39
0
def hallo():
    try:
        azerty = current_user
        print(current_user)
        if current_user.is_authenticated():
            #return render_template("main_for_user.html")
            return "Server is running"
        else:
            return '<a class="button" href="/login">Google Login</a>'
    except Exception as ex:
        logging.error(ex)
        return "ok"
Exemple #40
0
def servicesandroid():
    if current_user.is_authenticated():
        items=[]
        users=User_Organization_mapping.query.filter_by(id_user=g.user.id).all()
        for x in users:
            items = items + Service.query.filter_by(organization_id=x.id_organization).all()
        #org_id = User_Organization_mapping.query.filter_by(id_user=g.user.id).first()
        #items=db.session.query(Service).filter_by(organization_id=org_id.id_organization).all()

        return Response((json.dumps([o.dump() for o in items], default=json_util.default)), mimetype='application/json')
    else:
        return "Blad", 400
def profile(musicbrainz_id):
    if current_user.is_authenticated() and \
       current_user.musicbrainz_id == musicbrainz_id:
        user = current_user
    else:
        user = user_data.get_by_mb_id(musicbrainz_id)
        if user is None:
            raise NotFound("Can't find this user.")

    return render_template('user/profile.html',
                           user=user,
                           datasets=dataset.get_by_user_id(user.id))
Exemple #42
0
def login():
    if request.method == 'POST':
        user = User.get_and_check_user(request.form['username'],
                                       request.form['password'])
        if user:
            login_user(user)
            flash("Login as, %s" % user.get("user_name"), "success")
            return redirect(request.args.get("next") or url_for("home.index"))
        flash(u'Nombre de usuario y/o contraseña incorrecta.', "error")
    if current_user.is_authenticated():
        return redirect(url_for("home.index"))
    return render_template('login.html')
Exemple #43
0
def access_request(recid=None):
    """Create an access request."""
    record = get_record(recid)

    # Record must be in restricted access mode.
    if record.get('access_right') != 'restricted' or \
       not record.get('access_conditions'):
        abort(404)

    # Record must have an owner and owner must still exists.
    try:
        record_owner = User.query.get_or_404(record['owner']['id'])
    except KeyError:
        abort(404)

    sender = None
    initialdata = dict()

    # Prepare initial form data
    if current_user.is_authenticated():
        sender = current_user
        initialdata = dict(
            # FIXME: add full_name attribute to user accounts.
            full_name=" ".join([sender["family_name"], sender["given_names"]]),
            email=sender["email"],
        )

    # Normal form validation
    form = AccessRequestForm(formdata=request.form, **initialdata)

    if form.validate_on_submit():
        accreq = AccessRequest.create(recid=recid,
                                      receiver=record_owner,
                                      sender_full_name=form.data['full_name'],
                                      sender_email=form.data['email'],
                                      justification=form.data['justification'],
                                      sender=sender)

        if accreq.status == RequestStatus.EMAIL_VALIDATION:
            flash(_(
                "Email confirmation needed: We have sent you an email to "
                "verify your address. Please check the email and follow the "
                "instructions to complete the access request."),
                  category='info')
        else:
            flash(_("Access request submitted."), category='info')
        return redirect(url_for("record.metadata", recid=recid))

    return render_template(
        'accessrequests/access_request.html',
        record=record,
        form=form,
    )
Exemple #44
0
def login():

    if request.method == 'POST':
        instagram_username = request.form['userEmailID']
        instagram_password = request.form['userLoginPassword']

        session['insta_username'] = instagram_username
        session['insta_password'] = instagram_password

        insta_bot = InstagramBot(instagram_username, instagram_password)
        insta_login_response = insta_bot.login()
        insta_bot.closeBrowser()

        if instagram_username:
            user_obj = Users.query.filter_by(
                insta_username=instagram_username).first()
            if not user_obj:
                new_user = Users(insta_username=instagram_username)
                db.session.add(new_user)
                db.session.commit()

        user = Users.query.filter_by(insta_username=instagram_username).first()
        if insta_login_response and user is not None:

            if user.is_subscribed:
                if datetime.datetime.utcnow() < user.till_date:
                    ok = login_user(user)
                    print(ok)
                    print("subscribed")
                    print(current_user.is_authenticated())
                    next = request.args.get('next')

                    if next == None or not next[0] == '/':
                        next = url_for('users.accept_pending_requests')
                    return redirect(next)

            if user.is_subscribed == False:
                try:
                    if datetime.datetime.utcnow() > user.till_date:
                        user.till_date = None
                        user.from_date = None
                        user.is_subscribed = False
                        db.session.commit()
                except:
                    ok = login_user(user)
                    print(ok)
                    print("Not subscribed")
                    next = request.args.get('next')
                    if next == None or not next[0] == '/':
                        next = url_for('core.pricing')
                    return redirect(next)

    return render_template('index.html')
Exemple #45
0
def login_dashboard():
    #print('Entrei aqui')
    if request.path == '/dashboards/relogin':
        msg = 'Login Inválido!'
    else:
        msg = None

    if current_user.is_authenticated():
        return redirect('/dashboards/')

    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        ambient = request.form['ambient']
        cod_empresa = request.form['cod_empresa']
        cod_filial = request.form['cod_filial']

        #Autenticacao de Usuario
        username = username.lower()
        password = password.lower()
        cod_empresa = cod_empresa.lower()
        cod_filial = cod_filial.lower()
        ambient = ambient.lower()

        m = Manager(cod_empresa, cod_filial)
        r = m.load_user(username, password, ambient)

        if r is None:
            return redirect('/dashboards/relogin')

        #Valida Empresa e Filial
        if cod_empresa != '':
            if m.load_empresa(cod_empresa, ambient) is None:
                return redirect('/dashboards/relogin')

        if cod_filial != '':
            if m.load_filial(cod_empresa, cod_filial, ambient) is None:
                return redirect('/dashboards/relogin')

        #Cria sessão do login bem sucedido
        user = User(username + ':' + ambient + ':' + cod_empresa + ':' +
                    cod_filial)
        login_user(user)

        #Faz redirecionamento
        m.user = user
        m.id_db = 'softlog_' + user.id.split(':')[1]
        m.load_menu_dashboard()
        id_dash = m.dashboards[0]
        return redirect('/dashboards/%i' % (id_dash))
    else:
        return render_template('dashboards_v1/login.html', msg=msg)
Exemple #46
0
def deleteCandidateLinks():
    try:
        database = psycopg2.connect(
            user="******",
            password=
            "******",
            host=os.getenv('DATABASE_IP', "172.17.0.1"),
            port="5432",
            database="dauhmnvct04jp4")
        if database:
            cursor = database.cursor()
            response = dict()
            data = request.get_json()

            if current_user.is_authenticated():

                isDeleted1 = data['is_deleted_1']
                isDeleted2 = data['is_deleted_2']
                isDeleted3 = data['is_deleted_3']

                currentUserId = current_user.get_id()

                if currentUserId:
                    cursor.execute(
                        f"""SELECT link_id FROM public."Candidate Links" WHERE user_id = '{currentUserId}'"""
                    )
                    queryResult = cursor.fetchall()

                    cursor.execute(
                        f"""UPDATE public."Candidate Links" SET is_deleted='{isDeleted1}' WHERE link_id={queryResult[0][0]}"""
                    )
                    database.commit()
                    cursor.execute(
                        f"""UPDATE public."Candidate Links" SET is_deleted='{isDeleted2}' WHERE link_id={queryResult[1][0]}"""
                    )
                    database.commit()
                    cursor.execute(
                        f"""UPDATE public."Candidate Links" SET is_deleted='{isDeleted3}' WHERE link_id={queryResult[2][0]}"""
                    )
                    database.commit()
                    response['status'] = True
                    response[
                        'status_info'] = 'The Appropriate Candidate Links Were Deleted Successfully'

        else:
            error = "Connection To Database Failed!"
            response['error'] = error
            raise Exception(response)
    except Exception:
        return response, 400

    return response
def item_detail(item_id):
    item = Models.Item.objects(item_id=item_id).first_or_404()

    item_dict = Json.item_json(item)

    if current_user.is_authenticated():
        user = current_user._get_current_object()
    else:
        user = Models.GuestRecord.by_key(get_session_key())

    item_dict.update({'is_favored': item_id in user.favor_items})
    log_item_visit(user_id=user.id, item_id=item_id)
    return jsonify(message='OK', item=item_dict)
Exemple #48
0
def time_since(time):  # pragma: no cover
    """Returns a string representing time since e.g.
    3 days ago, 5 hours ago.

    :param time: A datetime object
    """
    delta = time - datetime.utcnow()

    locale = "en"
    if current_user.is_authenticated() and current_user.language is not None:
        locale = current_user.language

    return format_timedelta(delta, add_direction=True, locale=locale)
Exemple #49
0
def comments(slug):
    article_obj = Article()
    article = article_obj.get_article_by_slug(slug)
    form = CommentForm(request.form)
    if request.method == 'POST' and current_user.is_authenticated(
    ) and form.content.data:
        user = current_user.get_mongo_doc()
        comment = Comment(article=article,
                          content=form.content.data,
                          user=user,
                          vote=1)
        comment.save()
    return redirect(url_for('articles.get_article', slug=slug))
Exemple #50
0
def reset_password_request():
    if current_user.is_authenticated():
        return redirect(url_for('index'))
    form = ResetPasswordRequestForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user:
            send_email(user)
        flash('check your email for the instructions to reset your password')
        return redirect(url_for('login'))
    return render_template('reset_password_request',
                           title='Reset Password',
                           form=form)
Exemple #51
0
def reset_password():
    if current_user.is_authenticated():
        return redirect(url_for('index'))
    user = User.verify_reset_password_token(token)
    if not user:
        return redirect(url_for('index'))
    form = ResetPasswordForm()
    if form.validate_on_submit():
        user.set_password(form.password.data)
        db.session.commit()
        flash('Your Password has been reset.')
        return redirect(url_for('login'))
    return render_template('reset_password.html', form=form)
Exemple #52
0
 def test_correct_login(self):
     # Ensure login behaves correctly with correct credentials.
     with self.client:
         response = self.client.post(
             '/login',
             data=dict(email="*****@*****.**", password="******"),
             follow_redirects=True
         )
         self.assertTrue(response.status_code == 200)
         self.assertTrue(current_user.email == "*****@*****.**")
         self.assertTrue(current_user.is_active())
         self.assertTrue(current_user.is_authenticated())
         self.assertTemplateUsed('main/index.html')
Exemple #53
0
        def decorated_view(*args, **kwargs):

            if current_user.is_active() is False:
                flash('SVP confirmez votre compte!', 'warning')
                return redirect(url_for('user_param.unconfirmed'))

            if not current_user.is_authenticated() or not session.get(
                    'user_id'):
                flash('Connectez-vous SVP.', 'danger')
                return redirect(url_for('user.logout'))

            if not current_user.is_authenticated() and session.get('user_id'):
                flash('Connectez-vous SVP.', 'danger')
                return redirect(url_for('user.logout'))

            # User must have the required roles
            if not current_user.has_roles(required_roles, required_droits):
                # Redirect to the unauthorized page
                return redirect(url_for('server_Unauthorized'))

            # Call the actual view
            return func(*args, **kwargs)
 def before_request_gdpr_check():
     # skip certain pages, static content and the API
     if request.path == url_for('index.gdpr_notice') \
         or request.path == url_for('profile.delete') \
         or request.path == url_for('profile.export_data') \
         or request.path == url_for('login.logout') \
         or request.path.startswith('/static') \
         or request.path.startswith('/1'):
         return
     # otherwise if user is logged in and hasn't agreed to gdpr,
     # redirect them to agree to terms page.
     elif current_user.is_authenticated() and current_user.gdpr_agreed is None:
         return redirect(url_for('index.gdpr_notice', next=request.full_path))
Exemple #55
0
    def on_identity_loaded(sender, identity):
        identity.user = current_user

        if not current_user.is_authenticated():
            return
        if hasattr(current_user, 'login'):
            identity.provides.add(UserNeed(current_user.login))

        for role in session.get('provides', []):
            permissions = list(role)
            if len(permissions) == 3 and permissions[0] == ZONE_CONTEXT:
                current_user.add_zone(permissions)
            identity.provides.add(tuple(role))
Exemple #56
0
def login():
    success = False
    if current_user.is_authenticated():
        success = True
    elif query_is_photo_user(request.form) or query_is_photo_user(
            request.args):
        success = login_user(photo_user, remember=True)
    elif query_is_admin_user(request.form) or query_is_admin_user(
            request.args):
        success = login_user(admin_user, remember=True)
    if not success:
        abort(403)
    return ""
Exemple #57
0
def set_status(event_id, status):
    if current_user.is_authenticated():
        cu = User.query.get_or_404(current_user.id)
        if cu.is_admin or cu.is_promoter:
            event = Event.query.get_or_404(event_id)
            try:
                event.status = Status[status.upper()].value
            except KeyError:
                abort(400)

            db.session.add(event)
            db.session.commit()
    return redirect(url_for('events'))\
Exemple #58
0
    def test_reset_forgotten_password_valid_token_invalid_login(self):
        # Ensure user can confirm account with valid token.
        with self.client:
            self.client.post('/forgot', data=dict(
                email='*****@*****.**',
            ), follow_redirects=True)
            token = generate_confirmation_token('*****@*****.**')
            response = self.client.get('/forgot/new/'+token, follow_redirects=True)
            self.assertTemplateUsed('user/forgot_new.html')
            self.assertIn(
                b'You can now change your password.',
                response.data
            )
            response = self.client.post(
                '/forgot/new/'+token,
                data=dict(password="******", confirm="new-password"),
                follow_redirects=True
            )
            self.assertIn(
                b'Password successfully changed.',
                response.data
            )
            self.assertTemplateUsed('user/profile.html')
            self.assertTrue(current_user.is_authenticated())
            self.client.get('/logout')
            self.assertFalse(current_user.is_authenticated())

            response = self.client.post(
                '/login',
                data=dict(email="*****@*****.**", password="******"),
                follow_redirects=True
            )
            self.assertTrue(response.status_code == 200)
            self.assertFalse(current_user.is_authenticated())
            self.assertIn(
                b'Invalid email and/or password.',
                response.data
            )
            self.assertTemplateUsed('user/login.html')
Exemple #59
0
def forbidden(err):
    code = 403
    if not current_user.is_authenticated():
        target = get_redirect_target()
        if not target:
            target = request.url
        flash('You do not have access to this resource, please login.', 'error')
        return redirect(url_for('user.login', next=target), code=code)
    else:

        title = 'Access denied'
        message = "Sorry, but you don't have access to this resource."
        return render_template('errors/show.html', code=code, title=title, message=message), code
Exemple #60
0
 def test_incorrect_login(self):
     # Ensure login behaves correctly with incorrect credentials.
     with self.client:
         response = self.client.post(
             '/login',
             data=dict(email="*****@*****.**", password="******"),
             follow_redirects=True
         )
         self.assertTrue(response.status_code == 200)
         self.assertIn(b'Invalid email and/or password.', response.data)
         self.assertFalse(current_user.is_active())
         self.assertFalse(current_user.is_authenticated())
         self.assertTemplateUsed('user/login.html')