Esempio n. 1
0
def get_template(template_file):
    if hasattr(get_current_user(), 'template'):
        template = get_current_user().template
    else:
        template = config.get('default_template')

    return template + '/' + template_file
Esempio n. 2
0
def authorized(response):
    if response is None:
        #flash(u'Facebook-Access denied: reason=%s, error=%s' \
        #      %(request.args['error_reason'],
        #        request.args['error_description']),
        #      'error')
        flash(messages.fb_access_denied, 'error')

    else:
        oauth_token = response['access_token']
        expires = int(response['expires']) + time()

        if get_current_user():
            user_id = get_current_user().id
            db_obj = DBFacebook.query.filter_by(user_id=user_id).first()
            if db_obj:
                db_obj.access_token = oauth_token
                db_obj.expire_time = datetime.utcfromtimestamp(expires)
            else:
                db_obj = DBFacebook(
                            user_id=get_current_user().id,
                            access_token=oauth_token,
                            expire_time=datetime.utcfromtimestamp(expires)
                        )

            db.session.add(db_obj)
            db.session.commit()

    return redirect(request.args.get('next') or url_for('index'))
Esempio n. 3
0
 def get_current_user(self):
     """Get the current user"""
     try:
         getattr(self, "_current_user")
     except AttributeError:
         self._current_user = user.get_current_user(self)
     return self._current_user
Esempio n. 4
0
    def __init__(self, form):
        try:
            comment_form = ValidateCommentForm(form)
        except exceptions.CantValidateForm:
            raise exceptions.CantCreateNewComment

        self.content = comment_form.content
        self.related_post = comment_form.related_post
        self.time = datetime.now()

        if not post.check_if_post_exists(self.related_post):
            raise exceptions.CantCreateNewComment

        if not get_current_user():
            raise exceptions.CantCreateNewComment

        self.user_id = get_current_user().id
Esempio n. 5
0
def user_settings():
    if request.method == 'POST':
        setting = UserSettings()
        setting.change()

    user = get_current_user()
    return render_template(get_template('user_settings.html'), user=user,
                           templates=config.get('templates', list))
Esempio n. 6
0
def index():
    if not get_current_user():
        return redirect(url_for('public_index'))

    posts = Posts()
    posts = posts.get_posts()
    page = calc_page_links(len(posts), 1)

    return render_template(get_template('page.html'), posts=posts,
                           page_links=page)
Esempio n. 7
0
def edit_post(post_id):
    old_post = Post(post_id=post_id)
    if not old_post.id:
        abort(404)
    if old_post.user_id != get_current_user().id or \
       not get_current_user().is_admin():
        abort(403)

    if request.method == 'GET':
        return render_template(get_template('edit_preview.html'),
                               action='edit', post=old_post)
    else:
        try:
            new_post = NewPost(request.form)
            old_post.edit(new_post)
        except exceptions.CantCreateNewPost:
            flash(messages.post_edit_error, 'error')
            return render_template(get_template('edit_preview'), action='edit',
                                   post=request.form)
        flash(messages.post_edited, 'message')
        return redirect(url_for('get_post', post_id=old_post.id))
Esempio n. 8
0
def get_facebook_oauth_token():

    user = get_current_user()
    if not user:
        return None

    db_obj = DBFacebook.query.filter_by(user_id=user.id).first()

    if not db_obj:
        return None

    if not db_obj.access_token:
        return None

    if db_obj.expire_time < datetime.utcnow():
        return None

    return db_obj.access_token, ''
Esempio n. 9
0
def add_post():
    try:
        post = NewPost(request.form)
        post.save()

        flash(messages.post_created, 'message')

    except exceptions.CantCreateNewPost:
        flash(messages.post_error, 'error')
        return redirect(url_for('new_post'))

    # push this post to facebook?
    if config.get('facebook_integration', bool):
        if get_current_user().facebook_integration and post.is_public:
            return redirect(url_for('facebook_authorize_and_post',
                            post_id=post.id))

    return redirect(url_for('index'))
Esempio n. 10
0
    def __init__(self, form):
        try:
            post_form = inputvalidation.ValidatePostForm(form)
        except exceptions.CantValidateForm:
            raise exceptions.CantCreateNewPost

        self.title = post_form.title
        self.content = post_form.content
        self.content_type = post_form.category
        self.is_public = post_form.is_public

        self.time = datetime.now()
        self.user = user.get_current_user()

        # generate public id
        if self.is_public:
            self.public_id = generate_public_id(self.time, self.user.id)
        else:
            self.is_public = False
            self.public_id = None
Esempio n. 11
0
    def __init__(self):

        self.setting = request.form.get('setting')
        self.value = request.form.get('value')
        self.old_value = request.form.get('old_value')
        self.user = get_current_user()

        if not self.setting or not self.value:
            abort(400)

        if self.setting == 'password':
            self.change = self.change_password
        elif self.setting == 'email':
            self.change = self.change_email
        elif self.setting == 'posts_per_page':
            self.change = self.change_posts_per_page
        elif self.setting == 'email_notification':
            self.change = self.change_email_notification
        elif self.setting == 'template':
            self.change = self.change_template
        elif self.setting == 'facebook_integration':
            self.change = self.change_facebook_integration
        else:
            abort(400)
Esempio n. 12
0
def logout():
    if get_current_user():
        get_current_user().logout()
        flash(messages.logged_out, 'message')

    return redirect(url_for('public_index'))
Esempio n. 13
0
def prepare():
    """Open the database connection and get the current user."""
    flask.g.dbclient = utils.get_dbclient(flask.current_app.config)
    flask.g.db = utils.get_db(flask.g.dbclient, flask.current_app.config)
    if apikey := flask.request.headers.get("X-API-Key"):
        if not (
            apiuser := flask.request.headers.get("X-API-User")
        ):  # pylint: disable=superfluous-parens
            flask.abort(status=400)
        utils.verify_api_key(apiuser, apikey)
        flask.g.current_user = flask.g.db["users"].find_one({"auth_ids": apiuser})
        flask.g.permissions = flask.g.current_user["permissions"]
    else:
        if flask.request.method != "GET":
            utils.verify_csrf_token()
        flask.g.current_user = user.get_current_user()
        flask.g.permissions = flask.g.current_user["permissions"] if flask.g.current_user else None


@app.after_request
def finalize(response):
    """Finalize the response and clean up."""
    # close db connection
    if hasattr(flask.g, "dbserver"):
        flask.g.dbserver.close()
    # set csrf cookie if not set
    if not flask.request.cookies.get("_csrf_token"):
        response.set_cookie("_csrf_token", utils.gen_csrf_token(), samesite="Lax")
    # add some headers for protection
    response.headers["X-Frame-Options"] = "SAMEORIGIN"
    response.headers["X-XSS-Protection"] = "1; mode=block"
Esempio n. 14
0
def lambda_handler(event, context):
    ret = {}
    ret['statusCode'] = 200
    ret['headers'] = {'Content-Type': 'text/html'}

    #  logger.info(event['headers']['cookie'])
    user.get_current_user(event)
    #  logger.info(user.login)
    #actually that's mapping
    q_string = event["queryStringParameters"]

    if q_string is None:
        ret['body'] = html_tags.main_menu()
        return ret
    elif q_params.get_login_page in q_string:
        ret['body'] = html_tags.login_page
        return ret
    elif q_params.get_google_login_page in q_string:
        ret['body'] = html_tags.google_login_page
        return ret
    elif q_params.logout in q_string:
        ret['headers']['Set-Cookie'] = ''
        user.login = db_queries.anon
        ret['body'] = html_tags.main_menu()
        return ret
    elif q_params.get_signup_page in q_string:
        ret['body'] = html_tags.signup_page
        return ret
    elif q_params.do_login in q_string:
        login_status = do_login(q_string[q_params.login],
                                q_string[q_params.password])
        if (login_status[ok_login]):
            ret['headers']['Set-Cookie'] = login_status[cookie]
            user.get_current_user(None, login_status[cookie])
            ret['body'] = html_tags.main_menu()
            return ret
        else:
            ret['body'] = html_tags.fail_login()
            return ret
    elif q_params.do_login_google in q_string:  #copypaste from above
        login_status = do_login_google(q_string[q_params.google_token])
        if (login_status[ok_login]):
            ret['headers']['Set-Cookie'] = login_status[cookie]
            user.get_current_user(None, login_status[cookie])
            ret['body'] = html_tags.main_menu()
            return ret
        else:
            ret['body'] = html_tags.fail_login()
            return ret
    elif q_params.do_signup in q_string:
        signup_status = do_signup(q_string[q_params.login],
                                  q_string[q_params.password])
        ret['body'] = html_tags.signup_res(q_string[q_params.login],
                                           signup_status)
        return ret
    elif q_params.create_survey in q_string:
        ret['body'] = html_tags.create_survey()
        #  ret['body'] = str(type(event)) + "<br>" + str(event) + "<br>" + "keke"
        return ret
    elif q_params.create_by_yaml in q_string:
        ret['body'] = create_by_yaml(q_string[q_params.create_by_yaml])
        return ret
    elif q_params.get_survey in q_string:
        ret['body'] = get_survey(q_string[q_params.get_survey])
        return ret
    elif q_params.submit_survey in q_string:
        ret['body'] = submit_survey(q_string)
        return ret
    elif q_params.get_survey_res in q_string:
        ret['body'] = get_survey_res(q_string[q_params.get_survey_res])
        return ret
    elif q_params.get_user_surveys in q_string:
        ret['body'] = get_user_surveys(q_string[q_params.login])
        return ret
    elif q_params.get_user_info in q_string:
        ret['body'] = html_tags.get_user_info(q_string[q_params.login])
        return ret