コード例 #1
0
ファイル: items.py プロジェクト: cmazuc/scarfage
def edititem(item_id=None):
    pd = PageData()
    if request.method == 'POST':
        if 'username' in session:
            userid = pd.authuser.uid
        else:
            userid = 0 

        if 'desc' in request.form:
            if request.form['name'] == '':
                flash('No name for this item?')
                return redirect_back("/item/new")

            try:
                item = SiteItem.create(request.form['uid'])

                item_id = uid_by_item(request.form['name'])
                if not item_id or item_id == int(request.form['uid']):
                    uid = request.form['uid']
                    ip = request.remote_addr

                    if item.name != request.form['name']:
                        item.name = request.form['name']
                        item.update()

                    old = core.digest(item.body())
                    new = core.digest(request.form['desc'])

                    # silently discard null edits
                    if old != new:
                        new_edit(uid, request.form['desc'], userid, ip)
                        logger.info('item {} edited by user {} ({})'.format(uid, userid, ip))
                    else:
                        logger.info('null edit discarded for item {} by user {} ({})'.format(uid, userid, ip))

                    return redirect('/item/' + str(uid))
                else:
                    flash(item.name + " already exists!")
                    item_id = request.form['uid']
            except NoItem:
                if uid_by_item(request.form['name']):
                    flash(request.form['name'] + " already exists!")
                    return redirect_back("/item/new")

                uid = new_item(request.form['name'], request.form['desc'], userid, request.remote_addr)
                return redirect('/item/' + str(uid))

    if item_id:
        try:
            pd.item = SiteItem.create(item_id)
        except NoItem:
            return page_not_found()
     
        pd.title="Editing: %s" % pd.item.name
    else:
        pd.title="Editing: New Item"

    return render_template('edititem.html', pd=pd)
コード例 #2
0
def edititem(item_id=None):
    pd = PageData()
    if request.method == 'POST':
        if 'username' in session:
            userid = pd.authuser.uid
        else:
            userid = 0

        if 'desc' in request.form:
            if request.form['name'] == '':
                flash('No name for this item?')
                return redirect_back("/item/new")

            try:
                item = SiteItem.create(request.form['uid'])

                item_id = uid_by_item(request.form['name'])
                if not item_id or item_id == int(request.form['uid']):
                    item.name = request.form['name']
                    item.update()

                    # todo: check for null edits
                    new_edit(request.form['uid'], request.form['desc'], userid,
                             request.remote_addr)

                    uid = request.form['uid']
                    flash('Edited item!')
                    return redirect('/item/' + str(uid))
                else:
                    flash(item.name + " already exists!")
                    item_id = request.form['uid']
            except NoItem:
                if uid_by_item(request.form['name']):
                    flash(request.form['name'] + " already exists!")
                    return redirect_back("/item/new")

                uid = new_item(request.form['name'], request.form['desc'],
                               userid, request.remote_addr)
                return redirect('/item/' + str(uid))

    if item_id:
        try:
            pd.item = SiteItem.create(item_id)
        except NoItem:
            return page_not_found()

        pd.title = "Editing: %s" % pd.item.name
    else:
        pd.title = "Editing: New Item"

    return render_template('edititem.html', pd=pd)
コード例 #3
0
ファイル: user.py プロジェクト: cmazuc/scarfage
def newuser():
    pd = PageData();
    pd.title = "New User"

    if 'username' in session:
        flash('You are already logged in.')
        return redirect(url_for('index'))
    else:
        if request.method == 'POST':
            if not check_new_user(request):
                pd.username = request.form['username']
                pd.email = request.form['email']
                return render_template('new_user.html', pd=pd)

            if not new_user(request.form['username'], request.form['password'], request.form['email'], request.remote_addr):
                return render_template('error.html', pd=pd)

            try:
                user = SiteUser.create(request.form['username'])
                user.authenticate(request.form['password'])
                session['username'] = user.username
            except (NoUser, AuthFail):
                return render_template('error.html', pd=pd)

            flash('Welcome ' + request.form['username'])
            return redirect(url_for('index'))

        return render_template('new_user.html', pd=pd)
コード例 #4
0
ファイル: admin.py プロジェクト: oamike/scarfage
def admin_set_accesslevel(user, level):
    pd = PageData()

    if pd.authuser.accesslevel != 255 and pd.authuser.accesslevel <= int(
            level):
        app.logger.error('Accesslevel change was denied for user: '******'index')

    try:
        moduser = SiteUser.create(user)

        if pd.authuser.accesslevel != 255 and moduser.accesslevel >= pd.authuser.accesslevel:
            flash("Please contact an admin to modify this user's account.")
            return redirect_back('index')
    except NoUser:
        app.logger.error('Accesslevel change attempted for invalid user by: ' +
                         pd.authuser.username)
        pd.title = "User does not exist"
        pd.errortext = "The user does not exist"
        return render_template('error.html', pd=pd)

    moduser.newaccesslevel(level)
    flash('User ' + user + '\'s accesslevel has been set to ' + level)

    return redirect('/user/' + moduser.username)
コード例 #5
0
def show_item(item_id, edit=None):
    pd = PageData()

    if item_id is 'new':
        return redirect("/item/" + item_id + "/edit")

    try:
        showitem = SiteItem(item_id)

        if edit:
            showitem.old = True
            showitem.description = edit

        showitem.description_html = markdown.markdown(
            escape_html(str(showitem.body(edit))), md_extensions)
    except NoItem:
        return page_not_found(404)

    if 'username' in session:
        try:
            user = SiteUser.create(session['username'])
            pd.iteminfo = user.query_collection(showitem.uid)
        except (NoUser, NoItem):
            pass

    pd.title = showitem.name
    pd.item = showitem

    return render_template('item.html', pd=pd)
コード例 #6
0
ファイル: admin.py プロジェクト: CptPicard89/scarfage
def admin_set_accesslevel(user, level):
    """
    :URL: /admin/users/<user>/accesslevel/<level>

    Change a user's access level. The user requesting the access level change must be more privileged
    than the level they are setting. 

    Redirects back if there was an error, otherwise redirects to the user's profile.
    """
    pd = PageData()

    if pd.authuser.accesslevel != 255 and pd.authuser.accesslevel <= int(
            level):
        app.logger.error('Accesslevel change was denied for user: '******'index')

    try:
        moduser = SiteUser.create(user)

        if pd.authuser.accesslevel != 255 and moduser.accesslevel >= pd.authuser.accesslevel:
            flash("Please contact an admin to modify this user's account.")
            return redirect_back('index')
    except NoUser:
        app.logger.error('Accesslevel change attempted for invalid user by: ' +
                         pd.authuser.username)
        pd.title = "User does not exist"
        pd.errortext = "The user does not exist"
        return render_template('error.html', pd=pd)

    moduser.newaccesslevel(level)
    flash('User ' + user + '\'s accesslevel has been set to ' + level)

    return redirect('/user/' + moduser.username)
コード例 #7
0
ファイル: admin.py プロジェクト: cmazuc/scarfage
def admin_set_accesslevel(user, level):
    """
    :URL: /admin/users/<user>/accesslevel/<level>

    Change a user's access level. The user requesting the access level change must be more privileged
    than the level they are setting. 

    Redirects back if there was an error, otherwise redirects to the user's profile.
    """
    pd = PageData()

    if pd.authuser.accesslevel != 255 and pd.authuser.accesslevel <= int(level):
        app.logger.error('Accesslevel change was denied for user: '******'index')

    try:
        moduser = SiteUser.create(user)

        if pd.authuser.accesslevel != 255 and moduser.accesslevel >= pd.authuser.accesslevel:
            flash("Please contact an admin to modify this user's account.")
            return redirect_back('index')
    except NoUser:
        app.logger.error('Accesslevel change attempted for invalid user by: ' + pd.authuser.username)
        pd.title = "User does not exist"
        pd.errortext = "The user does not exist"
        return render_template('error.html', pd=pd)

    moduser.newaccesslevel(level)
    flash('User ' + user + '\'s accesslevel has been set to ' + level)

    return redirect_back('index')
コード例 #8
0
ファイル: moderation.py プロジェクト: macandcheese/scarfage
def moderate():
    pd = PageData()

    sql = read('imgmods')
    result = doquery(sql)

    pd.mods = []

    pd.tags = Tree('tags')

    for mod in result:
        try:
            imgid = mod[0]
            flag = mod[2]
            user = mod[3]

            if user is None:
                user = '******'
            else:
                user = user_by_uid(user)

            if mod[1] == 0 or flag == 1:
                sql = 'select tag from images where uid = %(uid)s;'
                img = doquery(sql, {"uid": imgid})

                class Mod:
                    pass

                mod = Mod()

                if img:
                    mod.uid = imgid
                    mod.tag = img[0][0]
                    mod.user = user
                    mod.flag = flag
                    pd.mods.append(mod)
                else:
                    flash('Error loading data for image ' + str(imgid))
        except IndexError as e:
            pd.title = "SQL error"
            pd.errortext = "SQL error"
            return render_template('error.html', pd=pd)

    pd.title = "Unmoderated images"

    return render_template('moderation.html', pd=pd)
コード例 #9
0
ファイル: moderation.py プロジェクト: cmazuc/scarfage
def moderate():
    pd = PageData()

    sql = read('imgmods')
    result = doquery(sql)

    pd.mods = []

    pd.tags = Tree('tags')

    for mod in result:
        try:
            imgid = mod[0]
            flag = mod[2]
            user = mod[3]

            if user is None:
                user = '******'
            else:
                user = user_by_uid(user)

            if mod[1] == 0 or flag == 1:
                sql = 'select tag from images where uid = %(uid)s;'
                img = doquery(sql, {"uid": imgid})
                
                class Mod:
                    pass
                mod = Mod()

                if img:
                    mod.uid = imgid
                    mod.tag = img[0][0]
                    mod.user = user
                    mod.flag = flag
                    pd.mods.append(mod)
                else:
                    flash('Error loading data for image ' + str(imgid))
        except IndexError as e:
            pd.title = "SQL error"
            pd.errortext = "SQL error"
            return render_template('error.html', pd=pd)

    pd.title = "Unmoderated images" 

    return render_template('moderation.html', pd=pd)
コード例 #10
0
ファイル: profile.py プロジェクト: subiki/scarfage
def show_user_profile(username):
    pd = PageData()
    pd.title = "Profile for " + username

    try:
        pd.profileuser = SiteUser.create(username)
    except NoUser:
        return page_not_found()

    return render_template('profile/main.html', pd=pd)
コード例 #11
0
ファイル: profile.py プロジェクト: macandcheese/scarfage
def show_user_profile(username):
    pd = PageData()
    pd.title = "Profile for " + username

    try:
        pd.profileuser = SiteUser.create(username)
    except NoUser:
        return page_not_found()

    return render_template('profile/main.html', pd=pd)
コード例 #12
0
ファイル: image.py プロジェクト: oamike/scarfage
def show_image(img_id):
    pd = PageData()

    try:
        pd.img = SiteImage.create(img_id)
        pd.title=pd.img.tag
    except NoImage:
        return page_not_found(404)

    return render_template('image.html', pd=pd)
コード例 #13
0
ファイル: image.py プロジェクト: oamike/scarfage
def show_image(img_id):
    pd = PageData()

    try:
        pd.img = SiteImage.create(img_id)
        pd.title = pd.img.tag
    except NoImage:
        return page_not_found(404)

    return render_template('image.html', pd=pd)
コード例 #14
0
ファイル: profile.py プロジェクト: oamike/scarfage
def show_user_profile(username):
    pd = PageData()
    pd.title = "Profile for " + username
    pd.timezones = get_timezones()

    try:
        pd.profileuser = SiteUser.create(username)
    except NoUser:
        return page_not_found(404)

    return render_template('profile.html', pd=pd)
コード例 #15
0
ファイル: profile.py プロジェクト: oamike/scarfage
def show_user_profile(username):
    pd = PageData()
    pd.title = "Profile for " + username
    pd.timezones = get_timezones()

    try:
        pd.profileuser = SiteUser.create(username)
    except NoUser:
        return page_not_found(404)

    return render_template('profile.html', pd=pd)
コード例 #16
0
ファイル: moderation.py プロジェクト: CptPicard89/scarfage
def mod_ban_user(user):
    pd = PageData()

    pd.title = "Banning user " + user

    pd.accessreq = 10
    pd.conftext = "Banning user " + user
    pd.conftarget = "/admin/users/" + user + "/accesslevel/0"
    pd.conflinktext = "Yup, I'm sure."

    return render_template('confirm.html', pd=pd)
コード例 #17
0
ファイル: profile.py プロジェクト: subiki/scarfage
def show_user_profile_collections(username):
    pd = PageData()
    pd.title = "Collections for " + username
    pd.timezones = get_timezones()

    try:
        pd.profileuser = SiteUser.create(username)
    except NoUser:
        return page_not_found()

    return render_template('profile/collections.html', pd=pd)
コード例 #18
0
ファイル: stats.py プロジェクト: oamike/scarfage
def stats():
    pd = PageData()

    pd.title = "Scarf Stats" 

    pd.topcollectors = get_whores_table()
    pd.topcontributors = get_contribs_table()
    pd.topneedy = get_needy_table()
    pd.topwilltrade = get_willtrade_table()

    return render_template('stats.html', pd=pd)
コード例 #19
0
def show_item_history(item_id):
    pd = PageData()

    try:
        showitem = SiteItem.create(item_id)
    except NoItem:
        return redirect("/item/" + item_id + "/edit")

    pd.title = showitem.name
    pd.item = showitem

    return render_template('itemhistory.html', pd=pd)
コード例 #20
0
ファイル: items.py プロジェクト: cmazuc/scarfage
def show_item_history(item_id):
    pd = PageData()

    try:
        showitem = SiteItem.create(item_id)
    except NoItem:
        return redirect("/item/" + item_id + "/edit")

    pd.title = showitem.name
    pd.item = showitem

    return render_template('itemhistory.html', pd=pd)
コード例 #21
0
ファイル: profile.py プロジェクト: macandcheese/scarfage
def show_user_profile_collections(username):
    pd = PageData()
    pd.title = "Collections for " + username
    pd.timezones = get_timezones()

    try:
        pd.profileuser = SiteUser.create(username)
    except NoUser:
        return page_not_found()

    if pd.profileuser.accesslevel == 0:
        return page_not_found()

    return render_template('profile/collections.html', pd=pd)
コード例 #22
0
ファイル: profile.py プロジェクト: subiki/scarfage
def show_user_profile_prefs(username):
    pd = PageData()
    pd.title = "Preferences for " + username
    pd.timezones = get_timezones()

    if not hasattr(pd, 'authuser') or pd.authuser.username != username:
        return page_not_found()

    try:
        pd.profileuser = SiteUser.create(username)
    except NoUser:
        return page_not_found()

    return render_template('profile/preferences.html', pd=pd)
コード例 #23
0
ファイル: profile.py プロジェクト: macandcheese/scarfage
def show_user_profile_prefs(username):
    pd = PageData()
    pd.title = "Preferences for " + username
    pd.timezones = get_timezones()

    if not hasattr(pd, 'authuser') or pd.authuser.username != username:
        return page_not_found()

    try:
        pd.profileuser = SiteUser.create(username)
    except NoUser:
        return page_not_found()

    return render_template('profile/preferences.html', pd=pd)
コード例 #24
0
ファイル: image.py プロジェクト: oamike/scarfage
def reallydelete_image(img_id):
    pd = PageData()

    try:
        delimg = SiteImage.create(img_id)
        delimg.delete()
    except NoImage:
        return page_not_found(404)

    pd.title = delimg.tag + " has been deleted"
    pd.accessreq = 10
    pd.conftext = delimg.tag + " has been deleted. I hope you meant to do that."
    pd.conftarget = ""
    pd.conflinktext = ""
    return render_template('confirm.html', pd=pd)
コード例 #25
0
ファイル: image.py プロジェクト: oamike/scarfage
def reallydelete_image(img_id):
    pd = PageData()

    try:
        delimg = SiteImage.create(img_id)
        delimg.delete()
    except NoImage:
        return page_not_found(404)

    pd.title = delimg.tag + " has been deleted"
    pd.accessreq = 10
    pd.conftext = delimg.tag + " has been deleted. I hope you meant to do that."
    pd.conftarget = ""
    pd.conflinktext = ""
    return render_template('confirm.html', pd=pd)
コード例 #26
0
def delete_item(item_id):
    try:
        delitem = SiteItem.create(item_id)
    except NoItem:
        return page_not_found()

    pd = PageData()

    pd.title = delitem.name

    pd.accessreq = 255
    pd.conftext = "Deleting item " + delitem.name + ". This will also delete all trades but not the associated PMs. If this item has open trades you are going to confuse people. Are you really sure you want to do this?"
    pd.conftarget = "/item/" + str(delitem.uid) + "/reallydelete"
    pd.conflinktext = "Yup, I'm sure"

    return render_template('confirm.html', pd=pd)
コード例 #27
0
def revert_item_edit(item_id, edit):
    pd = PageData()

    try:
        item = SiteItem.create(item_id)

        item.old = True
        item.edit = edit
    except NoItem:
        return page_not_found()

    pd.title = "Reverting: " + item.name
    pd.item_name = item.name
    pd.item = item

    return render_template('edititem.html', pd=pd)
コード例 #28
0
ファイル: image.py プロジェクト: oamike/scarfage
def delete_image(img_id):
    pd = PageData()

    try:
        delimg = SiteImage.create(img_id)
    except NoImage:
        return page_not_found(404)

    pd.title=delimg.tag

    pd.accessreq = 10
    pd.conftext = "Deleting image " + delimg.tag
    pd.conftarget = "/image/" + img_id + "/reallydelete"
    pd.conflinktext = "Yup, I'm sure"

    return render_template('confirm.html', pd=pd)
コード例 #29
0
ファイル: items.py プロジェクト: cmazuc/scarfage
def delete_item(item_id):
    try:
        delitem = SiteItem.create(item_id)
    except NoItem: 
        return page_not_found()

    pd = PageData()

    pd.title=delitem.name

    pd.accessreq = 255
    pd.conftext =  "Items may take some time to disappear from the indexes."
    pd.conftarget = "/item/" + str(delitem.uid) + "/reallydelete"
    pd.conflinktext = "I want to delete '{}' and accept the consequences of this action.".format(delitem.name)

    return render_template('confirm.html', pd=pd)
コード例 #30
0
ファイル: items.py プロジェクト: cmazuc/scarfage
def revert_item_edit(item_id, edit):
    pd = PageData()

    try:
        item = SiteItem.create(item_id)

        item.old = True
        item.edit = edit
    except NoItem:
        return page_not_found()

    pd.title="Reverting: " + item.name
    pd.item_name = item.name
    pd.item = item

    return render_template('edititem.html', pd=pd)
コード例 #31
0
ファイル: image.py プロジェクト: CptPicard89/scarfage
def show_image(img_id):
    """
    :URL: /image/<img_id>

    Render a template for viewing an image.
    """

    pd = PageData()

    try:
        pd.img = SiteImage.create(img_id)
        pd.title = pd.img.tag
    except NoImage:
        return page_not_found()

    return render_template('image.html', pd=pd)
コード例 #32
0
ファイル: image.py プロジェクト: oamike/scarfage
def delete_image(img_id):
    pd = PageData()

    try:
        delimg = SiteImage.create(img_id)
    except NoImage:
        return page_not_found(404)

    pd.title = delimg.tag

    pd.accessreq = 10
    pd.conftext = "Deleting image " + delimg.tag
    pd.conftarget = "/image/" + img_id + "/reallydelete"
    pd.conflinktext = "Yup, I'm sure"

    return render_template('confirm.html', pd=pd)
コード例 #33
0
ファイル: image.py プロジェクト: cmazuc/scarfage
def show_image(img_id):
    """
    :URL: /image/<img_id>

    Render a template for viewing an image.
    """

    pd = PageData()

    try:
        pd.img = SiteImage.create(img_id)
        pd.title=pd.img.tag
    except NoImage:
        return page_not_found()

    return render_template('image.html', pd=pd)
コード例 #34
0
def reallydelete_item(item_id):
    try:
        delitem = SiteItem(item_id)
    except NoItem:
        return page_not_found(404)

    pd = PageData()

    pd.title = delitem.name + " has been deleted"

    delitem.delete()

    pd.accessreq = 255
    pd.conftext = delitem.name + " has been deleted. I hope you meant to do that."
    pd.conftarget = ""
    pd.conflinktext = ""
    return render_template('confirm.html', pd=pd)
コード例 #35
0
ファイル: admin.py プロジェクト: oamike/scarfage
def admin_users():
    pd = PageData()
    pd.sf_conf = config

    pd.title = "Admin" 

    new_string('welcomebanner', 'Placeholder...')
    pd.welcomebanner = SiteString('welcomebanner').string

    pd.users = get_users()
    try:
        with open(config.DEPFILE, 'r') as depfile:
            frozen = depfile.read()
        pd.deployment = jsonpickle.decode(frozen)
        pd.mode = 'prod'
    except (OSError, IOError):
        pd.mode = "dev"

    return render_template('admin.html', pd=pd)
コード例 #36
0
ファイル: admin.py プロジェクト: oamike/scarfage
def admin_users():
    pd = PageData()
    pd.sf_conf = config

    pd.title = "Admin"

    new_string('welcomebanner', 'Placeholder...')
    pd.welcomebanner = SiteString('welcomebanner').string

    pd.users = get_users()
    try:
        with open(config.DEPFILE, 'r') as depfile:
            frozen = depfile.read()
        pd.deployment = jsonpickle.decode(frozen)
        pd.mode = 'prod'
    except (OSError, IOError):
        pd.mode = "dev"

    return render_template('admin.html', pd=pd)
コード例 #37
0
ファイル: pm.py プロジェクト: macandcheese/scarfage
def viewpm(username, messageid):
    pd = PageData()
    dmid = deobfuscate(messageid)

    if not 'username' in session or pd.authuser.username != username or dmid is None:
        return render_template('pm_error.html', pd=pd)

    if 'username' in session:
        pm = TradeMessage.create(dmid)

        if pm.delete_status(session['username']):
            return render_template('pm_error.html', pd=pd)

        if session['username'] is pm.to_user:
            pd.tradeuser = pm.from_user
            pm.read(pm.to_user)
        else:
            pd.tradeuser = pm.to_user

        pd.pm = pm
        pd.title = pm.subject

        return render_template('pm.html', pd=pd)
コード例 #38
0
ファイル: pm.py プロジェクト: oamike/scarfage
def viewpm(username, messageid):
    pd = PageData()
    dmid = deobfuscate(messageid)

    if not 'username' in session or pd.authuser.username != username or dmid is None:
        return render_template('pm_error.html', pd=pd)

    if 'username' in session:
        pm = TradeMessage.create(dmid)

        if pm.messagestatus < messagestatus['unread_pm']:
            pm = TradeMessage.create(messageid)

        if session['username'] is pm.to_user:
            pd.tradeuser = pm.from_user
            pm.read()
        else:
            pd.tradeuser = pm.to_user

        pd.pm = pm
        pd.title = pm.subject

        return render_template('pm.html', pd=pd)
コード例 #39
0
ファイル: admin.py プロジェクト: oamike/scarfage
def admin_set_accesslevel(user, level):
    pd = PageData()

    if pd.authuser.accesslevel != 255 and pd.authuser.accesslevel <= int(level):
        app.logger.error('Accesslevel change was denied for user: '******'index')

    try:
        moduser = SiteUser.create(user)

        if pd.authuser.accesslevel != 255 and moduser.accesslevel >= pd.authuser.accesslevel:
            flash("Please contact an admin to modify this user's account.")
            return redirect_back('index')
    except NoUser:
        app.logger.error('Accesslevel change attempted for invalid user by: ' + pd.authuser.username)
        pd.title = "User does not exist"
        pd.errortext = "The user does not exist"
        return render_template('error.html', pd=pd)

    moduser.newaccesslevel(level)
    flash('User ' + user + '\'s accesslevel has been set to ' + level)

    return redirect('/user/' + moduser.username)
コード例 #40
0
ファイル: image.py プロジェクト: CptPicard89/scarfage
def delete_image(img_id):
    """
    :URL: /image/<img_id>/delete

    Redirect to a confirmation page to make sure you want to delete an image.

    .. todo:: This should be re-done in javascript.
    """

    pd = PageData()

    try:
        delimg = SiteImage.create(img_id)
    except NoImage:
        return page_not_found()

    pd.title = delimg.tag

    pd.accessreq = 10
    pd.conftext = "Deleting image " + delimg.tag
    pd.conftarget = "/image/" + img_id + "/reallydelete"
    pd.conflinktext = "Yup, I'm sure"

    return render_template('confirm.html', pd=pd)
コード例 #41
0
ファイル: trade.py プロジェクト: oamike/scarfage
def trade(username, itemid=None, messageid=None):
    pd = PageData()

    status = messagestatus['unread_trade']

    try:
        pd.tradeuser = SiteUser.create(username)
    except NoUser:
        return page_not_found(404)

    if 'username' in session:
        if request.method == 'POST':
            authuseritems = request.form.getlist('authuseritem')
            tradeuseritems = request.form.getlist('tradeuseritem')
            message = request.form['body']
            subject = request.form['subject']

            if 'parent' in request.form:
                parent = request.form['parent']
            else:
                if messageid:
                    parent = core.deobfuscate(messageid)
                    messageid = parent
                    status = messagestatus['unread_pm']
                    flashmsg = 'Message sent!'
                else:
                    parent = None
                    messageid = None
                    flashmsg = 'Submitted trade request!'

            if message and subject:
                pmid = send_pm(pd.authuser.uid, pd.tradeuser.uid, subject, message, status, parent)

                if not messageid:
                    messageid = pmid
                elif tradeuseritems or authuseritems:
                    flashmsg = 'Trade updated'

                for item in authuseritems:
                    add_tradeitem(item, messageid, pd.authuser.uid, tradeitemstatus['accepted'])

                for item in tradeuseritems:
                    add_tradeitem(item, messageid, pd.tradeuser.uid, tradeitemstatus['unmarked'])

                flash(flashmsg)
                return redirect('/user/' + pd.authuser.username + '/pm/' + obfuscate(messageid))

            if message == '':
                flash('Please add a message')

            return redirect_back('/')

    pd.title = "Trading with {}".format(username)

    try:
        pd.authuser.ownwant = pd.authuser.query_collection(itemid)
    except AttributeError:
        pass

    try:
        pd.tradeuser.ownwant = pd.tradeuser.query_collection(itemid)
        pd.item = SiteItem(itemid)
    except NoItem:
        if messageid:
            try:
                pd.trademessage = TradeMessage.create(deobfuscate(messageid))
            except NoItem:
                return page_not_found(404)
        else:
            return page_not_found(404)

    return render_template('trade.html', pd=pd)
コード例 #42
0
ファイル: fbauth.py プロジェクト: cmazuc/scarfage
def fblogin():
    """
    :URL: /fbauth
    :Methods: GET

    Facebook auth callback URI
    """

    logger.info('Started Facebook auth for {}, referrer was {}'.format(request.remote_addr, request.referrer))

    try:
        facebook = OAuth2Session(FB_CLIENT_ID, redirect_uri=redirect_uri(), state=session['facebook_state'])
        facebook = facebook_compliance_fix(facebook)
    except KeyError:
        flash('Unable to log in via Facebook, do you have cookies enabled for this site?')
        logger.info('Failed to find Facebook state information for {}'.format(request.remote_addr))
        return redirect_back(url_for('index'))

    try:
        token = facebook.fetch_token(token_url, client_secret=FB_SECRET_ID, authorization_response=request.url)
        response = facebook.get('https://graph.facebook.com/v2.5/me?fields=id,name,email').content
    except (MismatchingStateError, MissingTokenError) as e:
        flash('Facebook was not able to provide us with the information we need to authenticate your account.')
        logger.info('Facebook auth exception for {}: {}'.format(request.remote_addr, e))
        return redirect_back(url_for('index'))

    decoded = json.loads(response)

    user_key = 'oauth-facebook-{}'.format(decoded['id'])

    try:
        username = SiteKey(user_key)
        user = SiteUser(username.value)

        if user.accesslevel is 0:
            flash('Your account has been banned')
            logger.info('Successful Facebook auth for {} but user is banned'.format(user.username))
            session.pop('username', None)
            session.pop('facebook_id', None)
            username.delete()
            return redirect_back(url_for('index'))

        user.seen()
        session['username'] = user.username
        session['facebook_token'] = token
        session['facebook_id'] = decoded['id']
        session['facebook_name'] = decoded['name']
        session['facebook_email'] = decoded['email']
        session.permanent = True

        # This profile update block won't be needed out of testing
        profile = user.profile()
        profile.profile['facebook_id'] = session['facebook_id']
        profile.update()
        # end block

        flash('You were successfully logged in')
        logger.info('Successful Facebook auth for {} (ID {})'.format(user.username, decoded['id']))
        return redirect_back(url_for('index'))
    except NoKey:
        session['facebook_token'] = token
        session['facebook_id'] = decoded['id']
        session['facebook_name'] = decoded['name']
        session['facebook_email'] = decoded['email']

        pd = PageData();
        pd.title = "Log in with Facebook"
        logger.info('Successful Facebook auth for ID {} but this person has no linked account'.format(decoded['id']))
        return render_template('new_facebook_user.html', pd=pd)

    flash('Facebook authentication failed :(')
    logger.info('Facebook auth error for {}'.format(request.remote_addr))
    return redirect_back(url_for('index'))
コード例 #43
0
def trade(username, itemid=None, messageid=None):
    pd = PageData()

    status = messagestatus['unread_trade']

    try:
        pd.tradeuser = SiteUser.create(username)
    except NoUser:
        return page_not_found(404)

    if 'username' in session:
        if request.method == 'POST':
            authuseritems = request.form.getlist('authuseritem')
            tradeuseritems = request.form.getlist('tradeuseritem')
            message = request.form['body']
            subject = request.form['subject']

            if 'parent' in request.form:
                parent = request.form['parent']
            else:
                if messageid:
                    parent = core.deobfuscate(messageid)
                    messageid = parent
                    status = messagestatus['unread_pm']
                    flashmsg = 'Message sent!'
                else:
                    parent = None
                    messageid = None
                    flashmsg = 'Submitted trade request!'

            if message and subject:
                pmid = send_pm(pd.authuser.uid, pd.tradeuser.uid, subject,
                               message, status, parent)

                if not messageid:
                    messageid = pmid
                elif tradeuseritems or authuseritems:
                    flashmsg = 'Trade updated'

                for item in authuseritems:
                    add_tradeitem(item, messageid, pd.authuser.uid,
                                  tradeitemstatus['accepted'])

                for item in tradeuseritems:
                    add_tradeitem(item, messageid, pd.tradeuser.uid,
                                  tradeitemstatus['unmarked'])

                flash(flashmsg)
                return redirect('/user/' + pd.authuser.username + '/pm/' +
                                obfuscate(messageid))

            if message == '':
                flash('Please add a message')

            return redirect_back('/')

    pd.title = "Trading with {}".format(username)

    try:
        pd.authuser.ownwant = pd.authuser.query_collection(itemid)
    except AttributeError:
        pass

    try:
        pd.tradeuser.ownwant = pd.tradeuser.query_collection(itemid)
        pd.item = SiteItem(itemid)
    except NoItem:
        if messageid:
            try:
                pd.trademessage = TradeMessage.create(deobfuscate(messageid))
            except NoItem:
                return page_not_found(404)
        else:
            return page_not_found(404)

    return render_template('trade.html', pd=pd)
コード例 #44
0
ファイル: items.py プロジェクト: cmazuc/scarfage
def show_item(item_id, edit=None):
    """
    :URLs:
        * /item/<item_id>/history/<edit>
        * /item/<item_id>

    :Methods: GET

    Setting the accept:application/json header will return JSON.

    :Sample response:

    .. code-block:: javascript
    {
        "added": "2016-05-23 20:52:12",
        "body": "",
        "body_rendered": "",
        "description": 384,
        "images": [
            443,
            444
        ],
        "modified": "2016-05-23 20:53:19",
        "name": "SSFC",
        "tags": {
            "FO": false,
            "Front Office": true,
            "MLS": true,
        },
        "uid": 388
    }

    * added         - Date added, always UTC
    * modified      - Late modified, also always UTC
    * name          - Item's name
    * body          - raw unrendered description body for the active edit
    * body_rendered - rendered content for the active edit
    * description   - edit identifier
    * images        - array of image ids associated with this item
    * tags          - dict of tags, keys are the tag title. the value is a bool which will be set to true if the tag was directly applied and false if inherited.
    """

    if item_id is 'new':
        return redirect("/item/" + item_id + "/edit")

    try:
        showitem = SiteItem.create(item_id)

        if showitem.deleted:
            return page_not_found()

        if edit:
            edit = int(edit)

        showitem.edit = edit

        if edit and edit not in [int(i.uid) for i in showitem.history()]:
            return page_not_found()
    except (NoItem, ValueError):
        return page_not_found()

    if request_wants_json():
        values = showitem.values(edit)
        values['body_rendered'] = render_markdown(values['body'])

        return json.dumps(values)
    else:
        pd = PageData()

        pd.title = showitem.name
        pd.item = showitem

        return render_template('item.html', pd=pd)
コード例 #45
0
ファイル: fbauth.py プロジェクト: macandcheese/scarfage
def fblogin():
    """
    :URL: /fbauth
    :Methods: GET

    Facebook auth callback URI
    """

    logger.info('Started Facebook auth for {}, referrer was {}'.format(
        request.remote_addr, request.referrer))

    try:
        facebook = OAuth2Session(FB_CLIENT_ID,
                                 redirect_uri=redirect_uri(),
                                 state=session['facebook_state'])
        facebook = facebook_compliance_fix(facebook)
    except KeyError:
        flash(
            'Unable to log in via Facebook, do you have cookies enabled for this site?'
        )
        logger.info('Failed to find Facebook state information for {}'.format(
            request.remote_addr))
        return redirect_back(url_for('index'))

    try:
        token = facebook.fetch_token(token_url,
                                     client_secret=FB_SECRET_ID,
                                     authorization_response=request.url)
        response = facebook.get(
            'https://graph.facebook.com/v2.5/me?fields=id,name,email').content
    except (MismatchingStateError, MissingTokenError) as e:
        flash(
            'Facebook was not able to provide us with the information we need to authenticate your account.'
        )
        logger.info('Facebook auth exception for {}: {}'.format(
            request.remote_addr, e))
        return redirect_back(url_for('index'))

    decoded = json.loads(response)

    user_key = 'oauth-facebook-{}'.format(decoded['id'])

    try:
        username = SiteKey(user_key)
        user = SiteUser(username.value)

        if user.accesslevel is 0:
            flash('Your account has been banned')
            logger.info(
                'Successful Facebook auth for {} but user is banned'.format(
                    user.username))
            session.pop('username', None)
            session.pop('facebook_id', None)
            username.delete()
            return redirect_back(url_for('index'))

        user.seen()
        session['username'] = user.username
        session['facebook_token'] = token
        session['facebook_id'] = decoded['id']
        session['facebook_name'] = decoded['name']
        session['facebook_email'] = decoded['email']
        session.permanent = True

        # This profile update block won't be needed out of testing
        profile = user.profile()
        profile.profile['facebook_id'] = session['facebook_id']
        profile.update()
        # end block

        flash('You were successfully logged in')
        logger.info('Successful Facebook auth for {} (ID {})'.format(
            user.username, decoded['id']))
        return redirect_back(url_for('index'))
    except NoKey:
        session['facebook_token'] = token
        session['facebook_id'] = decoded['id']
        session['facebook_name'] = decoded['name']
        session['facebook_email'] = decoded['email']

        pd = PageData()
        pd.title = "Log in with Facebook"
        logger.info(
            'Successful Facebook auth for ID {} but this person has no linked account'
            .format(decoded['id']))
        return render_template('new_facebook_user.html', pd=pd)

    flash('Facebook authentication failed :(')
    logger.info('Facebook auth error for {}'.format(request.remote_addr))
    return redirect_back(url_for('index'))
コード例 #46
0
def show_item(item_id, edit=None):
    """
    :URLs:
        * /item/<item_id>/history/<edit>
        * /item/<item_id>

    :Methods: GET

    Setting the accept:application/json header will return JSON.

    :Sample response:

    .. code-block:: javascript
    {
        "added": "2016-05-23 20:52:12",
        "body": "",
        "body_rendered": "",
        "description": 384,
        "images": [
            443,
            444
        ],
        "modified": "2016-05-23 20:53:19",
        "name": "SSFC",
        "tags": {
            "FO": false,
            "Front Office": true,
            "MLS": true,
        },
        "uid": 388
    }

    * added         - Date added, always UTC
    * modified      - Late modified, also always UTC
    * name          - Item's name
    * body          - raw unrendered description body
    * body_rendered - rendered content
    * description   - edit identifier
    * images        - array of image ids associated with this item
    * tags          - dict of tags, keys are the tag title. the value is a bool which will be set to true if the tag was directly applied and false if inherited.
    """

    if item_id is 'new':
        return redirect("/item/" + item_id + "/edit")

    try:
        showitem = SiteItem.create(item_id)

        if edit:
            showitem.old = True
            showitem.edit = edit
        else:
            showitem.old = False
            showitem.edit = None

        showitem.description_content = showitem.body(edit)
    except NoItem:
        return page_not_found()

    if request_wants_json():
        values = showitem.values()
        values['body_rendered'] = render_markdown(values['body'])
        return json.dumps(values)
    else:
        pd = PageData()

        pd.title = showitem.name
        pd.item = showitem

        return render_template('item.html', pd=pd)