def pm(username): pd = PageData() try: pd.recipient = SiteUser.create(username) except (NoItem, NoUser): return page_not_found(404) if 'username' in session: if request.method == 'POST': message = request.form['body'] subject = request.form['subject'] if 'parent' in request.form: parent = deobfuscate(request.form['parent']) else: parent = None if message and subject: messageid = send_pm(pd.authuser.uid, pd.recipient.uid, subject, message, messagestatus['unread_pm'], parent) if messageid: flash('Message sent!') if parent: return redirect_back('/user/' + username + '/pm') else: return redirect('/user/' + pd.authuser.username + '/pm/' + obfuscate((messageid))) else: # TODO re-fill form flash('No message or subject') return redirect_back('/user/' + username + '/pm') return render_template('sendpm.html', pd=pd)
def emailupdate(): pd = PageData() if 'username' in session: if request.method == 'POST': try: user = SiteUser.create(session['username']) except NoUser: return render_template('error.html', pd=pd) try: user.authenticate(request.form['password']) except AuthFail: flash("Please check your current password and try again") return redirect('/user/' + user.username) email = request.form['email'] if not re.match("[^@]+@[^@]+\.[^@]+", request.form['email']): flash("Invalid email address") return redirect('/user/' + user.username) user.newemail(email) flash("Your email address has been changed.") return redirect('/user/' + user.username) return redirect(url_for('index'))
def new_facebook_user(): pd = PageData(); logger.info('Started Facebook new user for {}, referrer was {}'.format(request.remote_addr, request.referrer)) if not check_new_user(request, nopass=True): pd.username = request.form['username'] pd.email = request.form['email'] return redirect_back(url_for('index')) password = ''.join(random.choice(string.printable) for _ in range(100)) if not new_user(request.form['username'], password, request.form['email'], request.remote_addr): return render_template('error.html', pd=pd) user_key = 'oauth-facebook-{}'.format(session['facebook_id']) new_key(user_key, request.form['username']) try: user = SiteUser.create(request.form['username']) session['username'] = user.username profile = user.profile() profile.profile['facebook_id'] = session['facebook_id'] profile.update() except (NoUser, AuthFail): return render_template('error.html', pd=pd) logger.info('New Facebook user {} ID {} ip {}'.format(user.username, session['facebook_id'], request.remote_addr)) flash('Welcome ' + request.form['username']) return redirect(url_for('index'))
def updateprefs(username): pd = PageData() if 'username' in session: ret = False if request.method == 'POST': try: user = SiteUser.create(session['username']) profile = user.profile() except NoUser: return render_template('error.html', pd=pd) if request.form['timezone'] in pytz.common_timezones: logger.info('timezone updated for for {}'.format(username)) profile.profile['timezone'] = request.form['timezone'] profile.profile['summary'] = request.form['summary'] profile.profile['gameday'] = request.form['gameday'] profile.profile['whitewhale'] = request.form['whitewhale'] profile.update() flash("Your profile has been updated.") logger.info('profile updated for for {}'.format(username)) return redirect('/user/' + user.username) return redirect(url_for('index'))
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)
def link_facebook_account(username): pd = PageData() logger.info('Started Facebook auth for {} ({}), referrer was {}'.format( username, request.remote_addr, request.referrer)) if 'username' in session: try: user = SiteUser.create(session['username']) user.authenticate(request.form['password']) except (NoUser, AuthFail): flash( 'Authentication failed, please check your password and try again.' ) logger.info( 'Facebook auth link failed for username {} ip {}'.format( user.username, request.remote_addr)) return redirect_back(url_for('index')) user_key = 'oauth-facebook-{}'.format(session['facebook_id']) new_key(user_key, session['username']) profile = user.profile() profile.profile['facebook_id'] = session['facebook_id'] profile.update() flash('Your account is now linked to Facebook.') logger.info('Facebook auth linked for username {} ID {} ip {}'.format( user.username, session['facebook_id'], request.remote_addr)) return redirect(url_for('index')) return redirect_back(url_for('index'))
def new_facebook_user(): pd = PageData() logger.info('Started Facebook new user for {}, referrer was {}'.format( request.remote_addr, request.referrer)) if not check_new_user(request, nopass=True): pd.username = request.form['username'] pd.email = request.form['email'] return redirect_back(url_for('index')) password = ''.join(random.choice(string.printable) for _ in range(100)) if not new_user(request.form['username'], password, request.form['email'], request.remote_addr): return render_template('error.html', pd=pd) user_key = 'oauth-facebook-{}'.format(session['facebook_id']) new_key(user_key, request.form['username']) try: user = SiteUser.create(request.form['username']) session['username'] = user.username profile = user.profile() profile.profile['facebook_id'] = session['facebook_id'] profile.update() except (NoUser, AuthFail): return render_template('error.html', pd=pd) logger.info('New Facebook user {} ID {} ip {}'.format( user.username, session['facebook_id'], request.remote_addr)) flash('Welcome ' + request.form['username']) return redirect(url_for('index'))
def newavatar(username): pd = PageData() if 'username' in session: ret = False if request.method == 'POST': try: user = SiteUser.create(session['username']) profile = user.profile() except NoUser: return render_template('error.html', pd=pd) raw = request.files['img'].read() size = len(raw) if size > 2097152: logger.info('rejected avatar for {}, raw size is {}'.format(username, size)) flash("Please resize your avatar to be smaller than 2MB. The image you uploaded was {:.1f}MB".format(size / 1000000.0)) return redirect('/user/' + user.username) if not imghdr.what(None, raw): flash("There was a problem updating your avatar.") logger.info('failed to update avatar for {} '.format(username)) return redirect('/user/' + user.username) image = base64.b64encode(raw) profile.profile['avatar'] = image profile.update() flash("Your avatar has been updated.") logger.info('avatar updated for for {}, raw size is {}'.format(username, size)) return redirect('/user/' + user.username) return redirect(url_for('index'))
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')
def link_facebook_account(username): pd = PageData(); logger.info('Started Facebook auth for {} ({}), referrer was {}'.format(username, request.remote_addr, request.referrer)) if 'username' in session: try: user = SiteUser.create(session['username']) user.authenticate(request.form['password']) except (NoUser, AuthFail): flash('Authentication failed, please check your password and try again.') logger.info('Facebook auth link failed for username {} ip {}'.format(user.username, request.remote_addr)) return redirect_back(url_for('index')) user_key = 'oauth-facebook-{}'.format(session['facebook_id']) new_key(user_key, session['username']) profile = user.profile() profile.profile['facebook_id'] = session['facebook_id'] profile.update() flash('Your account is now linked to Facebook.') logger.info('Facebook auth linked for username {} ID {} ip {}'.format(user.username, session['facebook_id'], request.remote_addr)) return redirect(url_for('index')) return redirect_back(url_for('index'))
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)
def login(): if request.method == 'POST': try: user = SiteUser.create(request.form['username']) except NoUser as e: flash('Login unsuccessful.') return redirect_back(url_for('index')) try: user.authenticate(request.form['password']) except (NoUser, AuthFail) as e: if user.accesslevel is 0: flash('Your account has been banned') session.pop('username', None) else: flash('Login unsuccessful.') return redirect_back(url_for('index')) user.seen() session['username'] = user.username session.permanent = True flash('You were successfully logged in') if not request.args.get('index'): return redirect_back(url_for('index')) else: return redirect(url_for('index')) return redirect(url_for('error'))
def check_new_user(request): ret = True try: user = SiteUser.create(request.form['username']) flash("User already exists!") ret = False except NoUser: if check_email(request.form['email']): flash("You may not create multiple users with the same email address.") return False valid = string.ascii_letters + string.digits for c in request.form['username']: if c not in valid: flash("Invalid character in username: "******"The passwords entered don't match.") ret = False else: if len(pass1) < 6: flash("Your password is too short, it must be at least 6 characters") ret = False if not re.match("[^@]+@[^@]+\.[^@]+", request.form['email']): flash("Invalid email address") ret = False return ret
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)
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)
def itemaction(item_id, action): """ :URL: /item/<item_id>/<action> :Methods: GET, POST Update or query the logged in user's record for an item. If a POST request is received then the current record is returned instead of a redirect back to the previous page. Setting the accept:application/json header will always return JSON regardless of request type. :Allowed actions: * 'status' - Return the item's current status * 'have' - Mark an item as part of the user's collection * 'donthave' - Remove the item from the user's collection * 'show' - If the item is in the user's collection mark it as visible to others * 'hide' - If the item is in the user's collection hide it from others * 'willtrade' - Mark the item as available for trade * 'wonttrade' - Don't show this item as available for trade * 'want' - Add this item to the user's want list * 'dontwant ' - Remove this item from the user's want list :Sample record: .. code-block:: javascript {"hidden": 1, "want": 0, "have": 1, "willtrade": 0} """ try: user = SiteUser.create(session['username']) except (NoUser, KeyError): user = None def get_record(): return json.dumps(user.query_collection(item_id).values()) if action == 'status': if not user: return '{}' else: return get_record() if user: try: ownwant(item_id, user.uid, actions[action]) except (NoItem, KeyError, ValueError): return page_not_found() if request.method == 'POST' or request_wants_json(): return get_record() else: if request_wants_json(): return '{}', 400 flash('You must be logged in to have a collection') return redirect_back('/item/' + item_id)
def itemaction(item_id, action): """ :URL: /item/<item_id>/<action> :Methods: GET, POST Update or query the logged in user's record for an item. If a POST request is received then the current record is returned instead of a redirect back to the previous page. Setting the accept:application/json header will always return JSON regardless of request type. :Allowed actions: * 'status' - Return the item's current status * 'have' - Mark an item as part of the user's collection * 'donthave' - Remove the item from the user's collection * 'show' - If the item is in the user's collection mark it as visible to others * 'hide' - If the item is in the user's collection hide it from others * 'willtrade' - Mark the item as available for trade * 'wonttrade' - Don't show this item as available for trade * 'want' - Add this item to the user's want list * 'dontwant ' - Remove this item from the user's want list :Sample record: .. code-block:: javascript {"hidden": 1, "want": 0, "have": 1, "willtrade": 0} """ try: user = SiteUser.create(session['username']) except (NoUser, KeyError): user = None def get_record(): return json.dumps(user.query_collection(item_id).values()) if action == 'status': if not user: return '{}' else: return get_record() if user: try: ownwant(item_id, user.uid, actions[action]) except (NoItem, KeyError): return page_not_found() if request.method == 'POST' or request_wants_json(): return get_record() else: if request_wants_json(): return '{}', 400 flash('You must be logged in to have a collection') return redirect_back('/item/' + item_id)
def serve_avatar(username): try: user = SiteUser.create(username) avatar = user.profile().profile['avatar'] resp = make_response(base64.b64decode(avatar)) resp.content_type = "image/png" return resp except (IOError, NoUser): return page_not_found(404)
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)
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)
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)
def admin_reset_pw(user): pd = PageData() try: user = SiteUser.create(user) user.forgot_pw_reset(ip='0.0.0.0', admin=True) except NoUser: return page_not_found(404) flash('A new password has been e-mailed to ' + user.username + '.') return redirect_back('/admin')
def ownwant(item_id, values): try: moditem = SiteItem(item_id) except NoItem: return page_not_found(404) try: user = SiteUser.create(session['username']) except (NoUser, KeyError): flash('You must be logged in to add items to a collection') return redirect('newuser') OwnWant(item_id, user.uid).update(values)
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)
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)
def userupdate(): pd = PageData() if request.method == 'POST': try: user = SiteUser.create(request.form['username']) user.forgot_pw_reset(request.remote_addr) except NoUser: email_user = check_email(request.form['email']) if email_user: email_user.forgot_pw_reset(request.remote_addr) flash('A new password has been e-mailed. Please remember to change it when you log in.') return redirect(url_for('index')) return render_template('forgotpw.html', pd=pd)
def userupdate(): pd = PageData() if request.method == 'POST': try: user = SiteUser.create(request.form['username']) user.forgot_pw_reset(request.remote_addr) except NoUser: email_user = check_email(request.form['email']) if email_user: email_user.forgot_pw_reset(request.remote_addr) flash( 'A new password has been e-mailed. Please remember to change it when you log in.' ) return redirect(url_for('index')) return render_template('forgotpw.html', pd=pd)
def admin_reset_pw(user): """ :URL: /admin/users/<user>/resetpw Reset the password for a user. Must be an admin. """ pd = PageData() try: user = SiteUser.create(user) user.forgot_pw_reset(ip='0.0.0.0', admin=True) except NoUser: return page_not_found() flash('A new password has been e-mailed to ' + user.username + '.') return redirect_back('/admin')
def pm(username): pd = PageData() try: pmuser = SiteUser.create(username) except (NoItem, NoUser): return page_not_found() if 'username' in session: if session['username'] == username: pd.profileuser = pmuser return render_template('profile/messages.html', pd=pd) else: pd.recipient = pmuser if request.method == 'POST': message = request.form['body'] subject = request.form['subject'] if 'parent' in request.form: parent = deobfuscate(request.form['parent']) else: parent = None if message and subject: messageid = send_pm(pd.authuser.uid, pd.recipient.uid, subject, message, None, parent) if messageid: flash('Message sent!') if parent: return redirect_back('/user/' + username + '/pm') else: return redirect('/user/' + pd.authuser.username + '/pm/' + obfuscate((messageid))) else: # TODO re-fill form flash('No message or subject') return redirect_back('/user/' + username + '/pm') return render_template('sendpm.html', pd=pd)
def check_new_user(request, nopass=False): ret = True try: user = SiteUser.create(request.form['username']) flash("User already exists!") ret = False except NoUser: if check_email(request.form['email']): flash("You may not create multiple users with the same email address.") return False valid = string.ascii_letters + string.digits + ' ' for c in request.form['username']: if c not in valid: flash("Invalid character in username: "******"The passwords entered don't match.") ret = False else: if len(pass1) < 6: flash("Your password is too short, it must be at least 6 characters") ret = False for regex in BANNED: if re.match(regex, request.form['email']): flash("This domain has been banned.") logger.info('Banned email address rejected: {}'.format(request.form['email'])) ret = False if not re.match("[^@]+@[^@]+\.[^@]+", request.form['email']): flash("Invalid email address") ret = False return ret
def newavatar(username): pd = PageData() if 'username' in session: ret = False if request.method == 'POST': try: user = SiteUser.create(session['username']) profile = user.profile() except NoUser: return render_template('error.html', pd=pd) raw = request.files['img'].read() size = len(raw) if size > 2097152: logger.info('rejected avatar for {}, raw size is {}'.format( username, size)) flash( "Please resize your avatar to be smaller than 2MB. The image you uploaded was {:.1f}MB" .format(size / 1000000.0)) return redirect('/user/' + user.username) if not imghdr.what(None, raw): flash("There was a problem updating your avatar.") logger.info('failed to update avatar for {} '.format(username)) return redirect('/user/' + user.username) image = base64.b64encode(raw) profile.profile['avatar'] = image profile.update() flash("Your avatar has been updated.") logger.info('avatar updated for for {}, raw size is {}'.format( username, size)) return redirect('/user/' + user.username) return redirect(url_for('index'))
def pwreset(): pd = PageData() if 'username' in session: ret = False if request.method == 'POST': try: user = SiteUser.create(session['username']) except NoUser: return render_template('error.html', pd=pd) try: user.authenticate(request.form['password']) except AuthFail: flash("Please check your current password and try again") return redirect('/user/' + user.username) pass1 = request.form['newpassword'] pass2 = request.form['newpassword2'] if pass1 != pass2: flash("The passwords entered don't match.") ret = True if len(pass1) < 6: flash( "Your new password is too short, it must be at least 6 characters" ) ret = True if ret: return redirect('/user/' + user.username) user.newpassword(request.form['newpassword']) flash("Your password has been reset.") return redirect('/user/' + user.username) return redirect(url_for('index'))
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)
def pwreset(): pd = PageData() if 'username' in session: ret = False if request.method == 'POST': try: user = SiteUser.create(session['username']) except NoUser: return render_template('error.html', pd=pd) try: user.authenticate(request.form['password']) except AuthFail: flash("Please check your current password and try again") return redirect('/user/' + user.username) pass1 = request.form['newpassword'] pass2 = request.form['newpassword2'] if pass1 != pass2: flash("The passwords entered don't match.") ret = True if len(pass1) < 6: flash("Your new password is too short, it must be at least 6 characters") ret = True if ret: return redirect('/user/' + user.username) user.newpassword(request.form['newpassword']) flash("Your password has been reset.") return redirect('/user/' + user.username) return redirect(url_for('index'))
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)
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'))
def show_user_collection(username): """ :URL: /user/<username>/collection Query a user's collection and return JSON. Hidden items are not returned unless the user is requesting their own collection.. :Sample response: .. code-block:: javascript [ [ { "added": "2016-05-21 04:05:01", "body": "Original Cascadia", "description": 472, "images": [ 191 ], "modified": "2016-05-25 00:06:31", "name": "Cascadia GBW Fringe 2010" }, { "have": 1, "hidden": 0, "want": 0, "willtrade": 0 } ], [ { "added": "2016-05-22 17:02:15", "body": "", "description": 317, "images": [ 364, 365 ], "modified": "2016-05-22 17:02:15", "name": "Cascadia" }, { "have": 1, "hidden": 0, "want": 0, "willtrade": 0 } ] ] """ pd = PageData() try: user = SiteUser.create(username) except NoUser: return page_not_found() collection = list() for item in user.collection(): ownwant = user.query_collection(item.uid).values() if ownwant['hidden'] == 1: if not hasattr(pd, 'authuser') or pd.authuser.username != username: continue collection.append((item.values(), ownwant)) return json.dumps(collection)
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'))