def manage_thumbnail_get_(request): form = request.web_input(submitid="", charid="", auto="") submitid = define.get_int(form.submitid) charid = define.get_int(form.charid) if submitid and request.userid not in staff.ADMINS and request.userid != define.get_ownerid(submitid=submitid): return Response(define.errorpage(request.userid, errorcode.permissions)) elif charid and request.userid not in staff.ADMINS and request.userid != define.get_ownerid(charid=charid): return Response(define.errorpage(request.userid, errorcode.permissions)) elif not submitid and not charid: return Response(define.errorpage(request.userid)) if charid: source_path = define.url_make(charid, "char/.thumb", root=True) if os.path.exists(source_path): source = define.url_make(charid, "char/.thumb") else: source = define.url_make(charid, "char/cover") else: try: source = thumbnail.thumbnail_source(submitid)['display_url'] except WeasylError: source = None return Response(define.webpage(request.userid, "manage/thumbnail.html", [ # Feature "submit" if submitid else "char", # Targetid define.get_targetid(submitid, charid), # Thumbnail source, # Exists bool(source), ], options=['imageselect'], title="Select Thumbnail"))
def signin_post_(request): form = request.web_input(username="", password="", referer="", sfwmode="nsfw") form.referer = form.referer or '/' logid, logerror = login.authenticate_bcrypt(form.username, form.password) if logid and logerror == 'unicode-failure': raise HTTPSeeOther(location='/signin/unicode-failure') elif logid and logerror is None: if form.sfwmode == "sfw": request.set_cookie_on_response("sfwmode", "sfw", 31536000) # Invalidate cached versions of the frontpage to respect the possibly changed SFW settings. index.template_fields.invalidate(logid) raise HTTPSeeOther(location=form.referer) elif logerror == "invalid": return Response(define.webpage(request.userid, "etc/signin.html", [True, form.referer])) elif logerror == "banned": reason = moderation.get_ban_reason(logid) return Response(define.errorpage( request.userid, "Your account has been permanently banned and you are no longer allowed " "to sign in.\n\n%s\n\nIf you believe this ban is in error, please " "contact [email protected] for assistance." % (reason,))) elif logerror == "suspended": suspension = moderation.get_suspension(logid) return Response(define.errorpage( request.userid, "Your account has been temporarily suspended and you are not allowed to " "be logged in at this time.\n\n%s\n\nThis suspension will be lifted on " "%s.\n\nIf you believe this suspension is in error, please contact " "[email protected] for assistance." % (suspension.reason, define.convert_date(suspension.release)))) elif logerror == "address": return Response("IP ADDRESS TEMPORARILY BLOCKED") return Response(define.errorpage(request.userid))
def signup_post_(request): form = request.web_input(username="", password="", passcheck="", email="", emailcheck="", day="", month="", year="") if 'g-recaptcha-response' not in form or not define.captcha_verify( form['g-recaptcha-response']): return Response( define.errorpage( request.userid, "There was an error validating the CAPTCHA response; you should go back and try again." )) login.create(form) return Response( define.errorpage( request.userid, "**Success!** Your username has been reserved and a message " "has been sent to the email address you provided with " "information on how to complete the registration process. You " "should receive this email within the next hour.", [["Return to the Home Page", "/"]]))
def POST(self): form = web.input(username="", password="", referer="", sfwmode="nsfw") form.referer = form.referer or '/index' logid, logerror = login.authenticate_bcrypt(form.username, form.password) if logid and logerror == 'unicode-failure': raise web.seeother('/signin/unicode-failure') elif logid and logerror is None: if form.sfwmode == "sfw": web.setcookie("sfwmode", "sfw", 31536000) raise web.seeother(form.referer) elif logerror == "invalid": return define.webpage(self.user_id, template.etc_signin, [True, form.referer]) elif logerror == "banned": reason = moderation.get_ban_reason(logid) return define.errorpage( self.user_id, "Your account has been permanently banned and you are no longer allowed " "to sign in.\n\n%s\n\nIf you believe this ban is in error, please " "contact [email protected] for assistance." % (reason,)) elif logerror == "suspended": suspension = moderation.get_suspension(logid) return define.errorpage( self.user_id, "Your account has been temporarily suspended and you are not allowed to " "be logged in at this time.\n\n%s\n\nThis suspension will be lifted on " "%s.\n\nIf you believe this suspension is in error, please contact " "[email protected] for assistance." % (suspension.reason, define.convert_date(suspension.release))) elif logerror == "address": return "IP ADDRESS TEMPORARILY BLOCKED" return define.errorpage(self.user_id)
def POST(self): form = web.input( username="", password="", passcheck="", email="", emailcheck="", day="", month="", year="", recaptcha_challenge_field="", g_recaptcha_response=web.input("g-recaptcha-response")) if not define.captcha_verify(form): return define.errorpage( self.user_id, "There was an error validating the CAPTCHA response; you should go back and try again." ) login.create(form) return define.errorpage( self.user_id, "**Success!** Your username has been reserved and a " "message has been sent to the email address you specified with " "information on how to complete the registration process. You " "should receive this email within the next hour.", [["Return to the Home Page", "/index"]])
def signin_2fa_auth_get_(request): sess = define.get_weasyl_session() # Only render page if the password has been authenticated (we have a UserID stored in the session) if '2fa_pwd_auth_userid' not in sess.additional_data: return Response(define.errorpage(request.userid, errorcode.permission)) tfa_userid = sess.additional_data['2fa_pwd_auth_userid'] # Maximum secondary authentication time: 5 minutes session_life = arrow.now( ).timestamp - sess.additional_data['2fa_pwd_auth_timestamp'] if session_life > 300: _cleanup_2fa_session() return Response( define.errorpage( request.userid, errorcode. error_messages['TwoFactorAuthenticationAuthenticationTimeout'], [["Sign In", "/signin"], ["Return to the Home Page", "/"]])) else: ref = request.params["referer"] if "referer" in request.params else "/" return Response( define.webpage( request.userid, "etc/signin_2fa_auth.html", [ define.get_display_name(tfa_userid), ref, two_factor_auth.get_number_of_recovery_codes(tfa_userid), None ], title="Sign In - 2FA"))
def POST(self): form = web.input(ch_username="", ch_full_name="", ch_catchphrase="", ch_email="", ch_birthday="", ch_gender="", ch_country="") userid = d.get_int(form.userid) if self.user_id != userid and userid in staff.ADMINS and self.user_id not in staff.TECHNICAL: return d.errorpage(self.user_id, errorcode.permission) if form.get('impersonate'): if self.user_id not in staff.TECHNICAL: return d.errorpage(self.user_id, errorcode.permission) sess = web.ctx.weasyl_session sess.additional_data.setdefault('user-stack', []).append(sess.userid) sess.additional_data.changed() sess.userid = userid sess.save = True d.append_to_log( 'staff.actions', userid=self.user_id, action='impersonate', target=userid) raise web.seeother('/') else: profile.do_manage(self.user_id, userid, username=form.username.strip() if form.ch_username else None, full_name=form.full_name.strip() if form.ch_full_name else None, catchphrase=form.catchphrase.strip() if form.ch_catchphrase else None, birthday=form.birthday if form.ch_birthday else None, gender=form.gender if form.ch_gender else None, country=form.country if form.ch_country else None) raise web.seeother("/admincontrol")
def control_username_post_(request): if request.POST['do'] == 'change': login.change_username( acting_user=request.userid, target_user=request.userid, bypass_limit=False, new_username=request.POST['new_username'], ) return Response( define.errorpage( request.userid, "Your username has been changed.", [["Go Back", "/control/username"], ["Return Home", "/"]], )) elif request.POST['do'] == 'release': login.release_username( define.engine, acting_user=request.userid, target_user=request.userid, ) return Response( define.errorpage( request.userid, "Your old username has been released.", [["Go Back", "/control/username"], ["Return Home", "/"]], )) else: raise WeasylError("Unexpected")
def weasyl_exception_processor(): web.ctx.log_exc = web.ctx.env.get( 'raven.captureException', lambda **kw: traceback.print_exc()) try: return _handle() except ClientGoneAway: if 'raven.captureMessage' in web.ctx.env: web.ctx.env['raven.captureMessage']('HTTP client went away', level=logging.INFO) return '' except web.HTTPError: raise except Exception as e: userid = d.get_userid() errorpage_kwargs = {} if isinstance(e, WeasylError): if e.render_as_json: return json.dumps({'error': {'name': e.value}}) errorpage_kwargs = e.errorpage_kwargs if e.value in errorcode.error_messages: web.ctx.status = errorcode.error_status_code.get(e.value, '200 OK') message = '%s %s' % (errorcode.error_messages[e.value], e.error_suffix) return d.errorpage(userid, message, **errorpage_kwargs) web.ctx.status = '500 Internal Server Error' request_id = None if 'raven.captureException' in web.ctx.env: request_id = base64.b64encode(os.urandom(6), '+-') event_id, = web.ctx.env['raven.captureException'](request_id=request_id) request_id = '%s-%s' % (event_id, request_id) print 'unhandled error (request id %s) in %r' % (request_id, web.ctx.env) traceback.print_exc() if getattr(e, '__render_as_json', False): return json.dumps({'error': {}}) return d.errorpage(userid, request_id=request_id, **errorpage_kwargs)
def signin_post_(request): form = request.web_input(username="", password="", referer="", sfwmode="nsfw") form.referer = form.referer or '/' logid, logerror = login.authenticate_bcrypt(form.username, form.password, request=request, ip_address=request.client_addr, user_agent=request.user_agent) if logid and logerror is None: if form.sfwmode == "sfw": request.set_cookie_on_response("sfwmode", "sfw", 31536000) # Invalidate cached versions of the frontpage to respect the possibly changed SFW settings. index.template_fields.invalidate(logid) raise HTTPSeeOther(location=form.referer) elif logid and logerror == "2fa": # Password authentication passed, but user has 2FA set, so verify second factor (Also set SFW mode now) if form.sfwmode == "sfw": request.set_cookie_on_response("sfwmode", "sfw", 31536000) index.template_fields.invalidate(logid) # Check if out of recovery codes; this should *never* execute normally, save for crafted # webtests. However, check for it and log an error to Sentry if it happens. remaining_recovery_codes = two_factor_auth.get_number_of_recovery_codes(logid) if remaining_recovery_codes == 0: raise RuntimeError("Two-factor Authentication: Count of recovery codes for userid " + str(logid) + " was zero upon password authentication succeeding, " + "which should be impossible.") # Store the authenticated userid & password auth time to the session sess = define.get_weasyl_session() # The timestamp at which password authentication succeeded sess.additional_data['2fa_pwd_auth_timestamp'] = arrow.now().timestamp # The userid of the user attempting authentication sess.additional_data['2fa_pwd_auth_userid'] = logid # The number of times the user has attempted to authenticate via 2FA sess.additional_data['2fa_pwd_auth_attempts'] = 0 sess.save = True return Response(define.webpage( request.userid, "etc/signin_2fa_auth.html", [define.get_display_name(logid), form.referer, remaining_recovery_codes, None], title="Sign In - 2FA" )) elif logerror == "invalid": return Response(define.webpage(request.userid, "etc/signin.html", [True, form.referer])) elif logerror == "banned": reason = moderation.get_ban_reason(logid) return Response(define.errorpage( request.userid, "Your account has been permanently banned and you are no longer allowed " "to sign in.\n\n%s\n\nIf you believe this ban is in error, please " "contact %s for assistance." % (reason, MACRO_SUPPORT_ADDRESS))) elif logerror == "suspended": suspension = moderation.get_suspension(logid) return Response(define.errorpage( request.userid, "Your account has been temporarily suspended and you are not allowed to " "be logged in at this time.\n\n%s\n\nThis suspension will be lifted on " "%s.\n\nIf you believe this suspension is in error, please contact " "%s for assistance." % (suspension.reason, define.convert_date(suspension.release), MACRO_SUPPORT_ADDRESS))) raise WeasylError("Unexpected") # pragma: no cover
def submit_tags_(request): if not define.is_vouched_for(request.userid): raise WeasylError("vouchRequired") form = request.web_input(submitid="", charid="", journalid="", preferred_tags_userid="", optout_tags_userid="", tags="") tags = searchtag.parse_tags(form.tags) submitid = define.get_int(form.submitid) charid = define.get_int(form.charid) journalid = define.get_int(form.journalid) preferred_tags_userid = define.get_int(form.preferred_tags_userid) optout_tags_userid = define.get_int(form.optout_tags_userid) result = searchtag.associate(request.userid, tags, submitid, charid, journalid, preferred_tags_userid, optout_tags_userid) if result: failed_tag_message = "" if result["add_failure_restricted_tags"] is not None: failed_tag_message += "The following tags have been restricted from being added to this item by the content owner, or Weasyl staff: **" + result[ "add_failure_restricted_tags"] + "**. \n" if result["remove_failure_owner_set_tags"] is not None: failed_tag_message += "The following tags were not removed from this item as the tag was added by the owner: **" + result[ "remove_failure_owner_set_tags"] + "**.\n" failed_tag_message += "Any other changes to this item's tags were completed." if submitid: location = "/submission/%i" % (submitid, ) if not result: raise HTTPSeeOther(location=location) else: return Response( define.errorpage(request.userid, failed_tag_message, [["Return to Content", location]])) elif charid: location = "/character/%i" % (charid, ) if not result: raise HTTPSeeOther(location=location) else: return Response( define.errorpage(request.userid, failed_tag_message, [["Return to Content", location]])) elif journalid: location = "/journal/%i" % (journalid, ) if not result: raise HTTPSeeOther(location=location) else: return Response( define.errorpage(request.userid, failed_tag_message, [["Return to Content", location]])) else: raise HTTPSeeOther(location="/control/editcommissionsettings")
def signin_2fa_auth_post_(request): sess = define.get_weasyl_session() # Only render page if the password has been authenticated (we have a UserID stored in the session) if '2fa_pwd_auth_userid' not in sess.additional_data: return Response(define.errorpage(request.userid, errorcode.permission)) tfa_userid = sess.additional_data['2fa_pwd_auth_userid'] session_life = arrow.now( ).timestamp - sess.additional_data['2fa_pwd_auth_timestamp'] if session_life > 300: # Maximum secondary authentication time: 5 minutes _cleanup_2fa_session() return Response( define.errorpage( request.userid, errorcode. error_messages['TwoFactorAuthenticationAuthenticationTimeout'], [["Sign In", "/signin"], ["Return to the Home Page", "/"]])) elif two_factor_auth.verify(tfa_userid, request.params["tfaresponse"]): # 2FA passed, so login and cleanup. _cleanup_2fa_session() login.signin(tfa_userid) ref = request.params["referer"] or "/" # User is out of recovery codes, so force-deactivate 2FA if two_factor_auth.get_number_of_recovery_codes(tfa_userid) == 0: two_factor_auth.force_deactivate(tfa_userid) return Response( define.errorpage( tfa_userid, errorcode.error_messages[ 'TwoFactorAuthenticationZeroRecoveryCodesRemaining'], [["2FA Dashboard", "/control/2fa/status"], ["Return to the Home Page", "/"]])) # Return to the target page, restricting to the path portion of 'ref' per urlparse. raise HTTPSeeOther(location=urlparse.urlparse(ref).path) elif sess.additional_data['2fa_pwd_auth_attempts'] >= 5: # Hinder brute-forcing the 2FA token or recovery code by enforcing an upper-bound on 2FA auth attempts. _cleanup_2fa_session() return Response( define.errorpage( request.userid, errorcode.error_messages[ 'TwoFactorAuthenticationAuthenticationAttemptsExceeded'], [["Sign In", "/signin"], ["Return to the Home Page", "/"]])) else: # Log the failed authentication attempt to the session and save sess.additional_data['2fa_pwd_auth_attempts'] += 1 sess.save = True # 2FA failed; redirect to 2FA input page & inform user that authentication failed. return Response( define.webpage( request.userid, "etc/signin_2fa_auth.html", [ define.get_display_name(tfa_userid), request.params["referer"], two_factor_auth.get_number_of_recovery_codes(tfa_userid), "2fa" ], title="Sign In - 2FA"))
def signin_2fa_auth_post_(request): sess = define.get_weasyl_session() # Only render page if the session exists //and// the password has # been authenticated (we have a UserID stored in the session) if not sess.additional_data or '2fa_pwd_auth_userid' not in sess.additional_data: return Response(define.errorpage(request.userid, errorcode.permission)) tfa_userid = sess.additional_data['2fa_pwd_auth_userid'] session_life = arrow.now().timestamp - sess.additional_data['2fa_pwd_auth_timestamp'] if session_life > 300: # Maximum secondary authentication time: 5 minutes _cleanup_2fa_session() return Response(define.errorpage( request.userid, errorcode.error_messages['TwoFactorAuthenticationAuthenticationTimeout'], [["Sign In", "/signin"], ["Return to the Home Page", "/"]] )) elif two_factor_auth.verify(tfa_userid, request.params["tfaresponse"]): # 2FA passed, so login and cleanup. _cleanup_2fa_session() login.signin(request, tfa_userid, ip_address=request.client_addr, user_agent=request.user_agent) ref = request.params["referer"] or "/" # User is out of recovery codes, so force-deactivate 2FA if two_factor_auth.get_number_of_recovery_codes(tfa_userid) == 0: two_factor_auth.force_deactivate(tfa_userid) return Response(define.errorpage( tfa_userid, errorcode.error_messages['TwoFactorAuthenticationZeroRecoveryCodesRemaining'], [["2FA Dashboard", "/control/2fa/status"], ["Return to the Home Page", "/"]] )) # Return to the target page, restricting to the path portion of 'ref' per urlparse. raise HTTPSeeOther(location=urlparse.urlparse(ref).path) elif sess.additional_data['2fa_pwd_auth_attempts'] >= 5: # Hinder brute-forcing the 2FA token or recovery code by enforcing an upper-bound on 2FA auth attempts. _cleanup_2fa_session() return Response(define.errorpage( request.userid, errorcode.error_messages['TwoFactorAuthenticationAuthenticationAttemptsExceeded'], [["Sign In", "/signin"], ["Return to the Home Page", "/"]] )) else: # Log the failed authentication attempt to the session and save sess.additional_data['2fa_pwd_auth_attempts'] += 1 sess.save = True # 2FA failed; redirect to 2FA input page & inform user that authentication failed. return Response(define.webpage( request.userid, "etc/signin_2fa_auth.html", [define.get_display_name(tfa_userid), request.params["referer"], two_factor_auth.get_number_of_recovery_codes(tfa_userid), "2fa"], title="Sign In - 2FA"))
def weasyl_exception_view(exc, request): """ A view for general exceptions thrown by weasyl code. """ if isinstance(exc, ClientGoneAway): if 'raven.captureMessage' in request.environ: request.environ['raven.captureMessage']('HTTP client went away', level=logging.INFO) return request.response else: # Avoid using the reified request.userid property here. It might not be set and it might # have changed due to signin/out. if hasattr(request, 'weasyl_session'): userid = request.weasyl_session.userid else: userid = 0 request.userid = 0 # To keep templates happy. errorpage_kwargs = {} if isinstance(exc, WeasylError): status_code = errorcode.error_status_code.get(exc.value, 422) if exc.render_as_json: return Response(json={'error': { 'name': exc.value }}, status_code=status_code) errorpage_kwargs = exc.errorpage_kwargs if exc.value in errorcode.error_messages: message = errorcode.error_messages[exc.value] if exc.error_suffix: message = '%s %s' % (message, exc.error_suffix) return Response(d.errorpage(userid, message, **errorpage_kwargs), status_code=status_code) request_id = None if 'raven.captureException' in request.environ: request_id = base64.b64encode(os.urandom(6), b'+-').decode('ascii') event_id = request.environ['raven.captureException']( request_id=request_id) request_id = '%s-%s' % (event_id, request_id) print("unhandled error (request id %s) in %r" % (request_id, request.environ)) traceback.print_exc() if getattr(exc, "__render_as_json", False): return Response(json={'error': {}}, status_code=500) else: return Response(d.errorpage(userid, request_id=request_id, **errorpage_kwargs), status_code=500)
def GET(self): premiumpurchase.verify(self.user_id, web.input(token="").token) return define.errorpage( self.user_id, "**Success!** Your purchased premium terms have " "been applied to your account.", [["Go to Premium " "Settings", "/control"], ["Return to the Home Page", "/index"]])
def GET(self): login.verify(web.input(token="").token) return define.errorpage( self.user_id, "**Success!** Your email address has been verified " "and you may now sign in to your account.", [["Sign In", "/signin"], ["Return to the Home Page", "/index"]])
def forgetpassword_post_(request): resetpassword.request(email=request.POST['email']) return Response( define.errorpage( request.userid, "**Success!** Information on how to reset your password has been sent to your email address.", [["Return to the Home Page", "/"]]))
def signout_(request): if request.web_input(token="").token != define.get_token()[:8]: return Response(define.errorpage(request.userid, errorcode.token)) login.signout(request) raise HTTPSeeOther(location="/", headers=request.response.headers)
def shouts_(request): form = request.web_input(userid="", name="", backid=None, nextid=None) form.name = request.matchdict.get('name', form.name) form.userid = define.get_int(form.userid) otherid = profile.resolve(request.userid, form.userid, form.name) if not otherid: raise WeasylError("userRecordMissing") elif not request.userid and "h" in define.get_config(otherid): return Response(define.errorpage(request.userid, errorcode.no_guest_access)) userprofile = profile.select_profile(otherid, images=True, viewer=request.userid) has_fullname = userprofile['full_name'] is not None and userprofile['full_name'].strip() != '' page_title = u"%s's shouts" % (userprofile['full_name'] if has_fullname else userprofile['username'],) page = define.common_page_start(request.userid, title=page_title) page.append(define.render('user/shouts.html', [ # Profile information userprofile, # User information profile.select_userinfo(otherid, config=userprofile['config']), # Relationship profile.select_relation(request.userid, otherid), # Myself profile.select_myself(request.userid), # Comments shout.select(request.userid, ownerid=otherid), # Feature "shouts", ])) return Response(define.common_page_end(request.userid, page))
def verify_account_(request): login.verify(request.web_input(token="").token) return Response(define.errorpage( request.userid, "**Success!** Your email address has been verified " "and you may now sign in to your account.", [["Sign In", "/signin"], ["Return to the Home Page", "/"]]))
def verify_premium_(request): premiumpurchase.verify(request.userid, request.web_input(token="").token) return Response(define.errorpage( request.userid, "**Success!** Your purchased premium terms have " "been applied to your account.", [["Go to Premium " "Settings", "/control"], ["Return to the Home Page", "/"]]))
def GET(self, name=""): cachename = "user/followed.html" form = web.input(userid="", name="", backid=None, nextid=None) form.name = name if name else form.name form.userid = define.get_int(form.userid) otherid = profile.resolve(self.user_id, form.userid, form.name) if not otherid: raise WeasylError("userRecordMissing") elif not self.user_id and "h" in define.get_config(otherid): return define.errorpage(self.user_id, errorcode.no_guest_access) userprofile = profile.select_profile(otherid, images=True, viewer=self.user_id) return define.webpage(self.user_id, cachename, [ # Profile information userprofile, # User information profile.select_userinfo(otherid, config=userprofile['config']), # Relationship profile.select_relation(self.user_id, otherid), # Followed followuser.select_followed(self.user_id, otherid, limit=44, backid=define.get_int(form.backid), nextid=define.get_int(form.nextid)), ])
def GET(self, name=""): form = web.input(userid="", name="", backid=None, nextid=None) form.name = name if name else form.name form.userid = define.get_int(form.userid) config = define.get_config(self.user_id) rating = define.get_rating(self.user_id) otherid = profile.resolve(self.user_id, form.userid, form.name) if not otherid: raise WeasylError("userRecordMissing") elif not self.user_id and "h" in define.get_config(otherid): return define.errorpage(self.user_id, errorcode.no_guest_access) userprofile = profile.select_profile(otherid, images=True, viewer=self.user_id) has_fullname = userprofile['full_name'] is not None and userprofile['full_name'].strip() != '' page_title = u"%s's journals" % (userprofile['full_name'] if has_fullname else userprofile['username'],) page = define.common_page_start(self.user_id, title=page_title) page.append(define.render(template.user_journals, [ # Profile information userprofile, # User information profile.select_userinfo(otherid, config=userprofile['config']), # Relationship profile.select_relation(self.user_id, otherid), # Journals list # TODO(weykent): use select_user_list journal.select_list(self.user_id, rating, 250, otherid=otherid, config=config), # Latest journal journal.select_latest(self.user_id, rating, otherid=otherid), ])) return define.common_page_end(self.user_id, page)
def GET(self, name=""): cachename = "user/followed.html" form = web.input(userid="", name="", backid=None, nextid=None) form.name = name if name else form.name form.userid = define.get_int(form.userid) otherid = profile.resolve(self.user_id, form.userid, form.name) if not otherid: raise WeasylError("userRecordMissing") elif not self.user_id and "h" in define.get_config(otherid): return define.errorpage(self.user_id, errorcode.no_guest_access) userprofile = profile.select_profile(otherid, images=True, viewer=self.user_id) return define.webpage( self.user_id, cachename, [ # Profile information userprofile, # User information profile.select_userinfo(otherid, config=userprofile['config']), # Relationship profile.select_relation(self.user_id, otherid), # Followed followuser.select_followed(self.user_id, otherid, limit=44, backid=define.get_int(form.backid), nextid=define.get_int(form.nextid)), ])
def followed_(request): cachename = "user/followed.html" form = request.web_input(userid="", name="", backid=None, nextid=None) form.name = request.matchdict.get('name', form.name) form.userid = define.get_int(form.userid) otherid = profile.resolve(request.userid, form.userid, form.name) if not otherid: raise WeasylError("userRecordMissing") elif not request.userid and "h" in define.get_config(otherid): return Response(define.errorpage(request.userid, errorcode.no_guest_access)) userprofile = profile.select_profile(otherid, images=True, viewer=request.userid) return Response(define.webpage(request.userid, cachename, [ # Profile information userprofile, # User information profile.select_userinfo(otherid, config=userprofile['config']), # Relationship profile.select_relation(request.userid, otherid), # Followed followuser.select_followed(request.userid, otherid, limit=44, backid=define.get_int(form.backid), nextid=define.get_int(form.nextid)), ]))
def admincontrol_manageuser_post_(request): form = request.web_input(ch_username="", ch_full_name="", ch_catchphrase="", ch_email="", ch_birthday="", ch_gender="", ch_country="", remove_social=[]) userid = d.get_int(form.userid) if request.userid != userid and userid in staff.ADMINS and request.userid not in staff.TECHNICAL: return d.errorpage(request.userid, errorcode.permission) profile.do_manage( request.userid, userid, username=form.username.strip() if form.ch_username else None, full_name=form.full_name.strip() if form.ch_full_name else None, catchphrase=form.catchphrase.strip() if form.ch_catchphrase else None, birthday=form.birthday if form.ch_birthday else None, gender=form.gender if form.ch_gender else None, country=form.country if form.ch_country else None, remove_social=form.remove_social, permission_tag='permission-tag' in form) raise HTTPSeeOther(location="/admincontrol")
def resetpassword_get_(request): token = request.GET.get('token', "") reset_target = resetpassword.prepare(token=token) if reset_target is None: return Response(define.errorpage( request.userid, "This link does not appear to be valid. If you followed this link from your email, it may have expired.")) if isinstance(reset_target, resetpassword.Unregistered): return Response(define.errorpage( request.userid, "The e-mail address **%s** is not associated with a Weasyl account." % (reset_target.email,), [["Sign Up", "/signup"], ["Return to the Home Page", "/"]])) return Response(define.webpage(request.userid, "etc/resetpassword.html", [token, reset_target], title="Reset Forgotten Password"))
def journals_(request): form = request.web_input(userid="", name="", backid=None, nextid=None) form.name = request.matchdict.get('name', form.name) form.userid = define.get_int(form.userid) config = define.get_config(request.userid) rating = define.get_rating(request.userid) otherid = profile.resolve(request.userid, form.userid, form.name) if not otherid: raise WeasylError("userRecordMissing") elif not request.userid and "h" in define.get_config(otherid): return Response(define.errorpage(request.userid, errorcode.no_guest_access)) userprofile = profile.select_profile(otherid, images=True, viewer=request.userid) has_fullname = userprofile['full_name'] is not None and userprofile['full_name'].strip() != '' page_title = u"%s's journals" % (userprofile['full_name'] if has_fullname else userprofile['username'],) page = define.common_page_start(request.userid, title=page_title) page.append(define.render('user/journals.html', [ # Profile information userprofile, # User information profile.select_userinfo(otherid, config=userprofile['config']), # Relationship profile.select_relation(request.userid, otherid), # Journals list # TODO(weykent): use select_user_list journal.select_list(request.userid, rating, 250, otherid=otherid, config=config), # Latest journal journal.select_latest(request.userid, rating, otherid=otherid), ])) return Response(define.common_page_end(request.userid, page))
def GET(self, name=""): now = time.time() form = web.input(userid="", name="", backid=None, nextid=None) form.name = name if name else form.name form.userid = define.get_int(form.userid) otherid = profile.resolve(self.user_id, form.userid, form.name) if not otherid: raise WeasylError("userRecordMissing") elif not self.user_id and "h" in define.get_config(otherid): return define.errorpage(self.user_id, errorcode.no_guest_access) userprofile = profile.select_profile(otherid, images=True, viewer=self.user_id) has_fullname = userprofile['full_name'] is not None and userprofile['full_name'].strip() != '' page_title = u"%s's shouts" % (userprofile['full_name'] if has_fullname else userprofile['username'],) page = define.common_page_start(self.user_id, title=page_title) page.append(define.render(template.user_shouts, [ # Profile information userprofile, # User information profile.select_userinfo(otherid, config=userprofile['config']), # Relationship profile.select_relation(self.user_id, otherid), # Myself profile.select_myself(self.user_id), # Comments shout.select(self.user_id, ownerid=otherid), # Feature "shouts", ])) return define.common_page_end(self.user_id, page, now=now)
def inner(request): if weasyl.api.is_api_user(): raise HTTPForbidden if request.userid not in staff.DIRECTORS: return Response( define.errorpage(request.userid, errorcode.permission)) return view_callable(request)
def frienduser_(request): form = request.web_input(userid="") otherid = define.get_int(form.userid) if request.userid == otherid: return Response( define.errorpage(request.userid, "You cannot friend yourself.")) if form.action == "sendfriendrequest": if not frienduser.check(request.userid, otherid) and not frienduser.already_pending( request.userid, otherid): frienduser.request(request.userid, otherid) elif form.action == "withdrawfriendrequest": if frienduser.already_pending(request.userid, otherid): frienduser.remove_request(request.userid, otherid) elif form.action == "unfriend": frienduser.remove(request.userid, otherid) if form.feature == "pending": raise HTTPSeeOther(location="/manage/friends?feature=pending") else: # typical value will be user raise HTTPSeeOther( location="/~%s" % (define.get_sysname(define.get_display_name(otherid))))
def POST(self): form = web.input(target="", set_stream="", stream_length="", stream_url="", stream_text="") if form.target and self.user_id not in staff.MODS: return define.errorpage(self.user_id, errorcode.permission) if form.target: target = int(form.target) else: target = self.user_id stream_length = define.clamp(define.get_int(form.stream_length), 0, 360) p = orm.Profile() p.stream_text = form.stream_text p.stream_url = define.text_fix_url(form.stream_url.strip()) set_stream = form.set_stream profile.edit_streaming_settings(self.user_id, target, p, set_stream=set_stream, stream_length=stream_length) raise web.seeother("/control")
def control_streaming_post_(request): form = request.web_input(target="", set_stream="", stream_length="", stream_url="", stream_text="") if form.target and request.userid not in staff.MODS: return Response(define.errorpage(request.userid, errorcode.permission)) if form.target: target = int(form.target) else: target = request.userid stream_length = define.clamp(define.get_int(form.stream_length), 0, 360) p = orm.Profile() p.stream_text = form.stream_text p.stream_url = define.text_fix_url(form.stream_url.strip()) set_stream = form.set_stream profile.edit_streaming_settings(request.userid, target, p, set_stream=set_stream, stream_length=stream_length) if form.target: target_username = define.get_sysname(define.get_display_name(target)) raise HTTPSeeOther(location="/modcontrol/manageuser?name=" + target_username) else: raise HTTPSeeOther(location="/control")
def verify_account_(request): login.verify(token=request.web_input(token="").token, ip_address=request.client_addr) return Response(define.errorpage( request.userid, "**Success!** Your email address has been verified " "and you may now sign in to your account.", [["Sign In", "/signin"], ["Return to the Home Page", "/"]]))
def GET(self): form = web.input(submitid="", anyway="") form.submitid = define.get_int(form.submitid) detail = submission.select_view(self.user_id, form.submitid, ratings.EXPLICIT.code, False, anyway=form.anyway) if self.user_id != detail['userid'] and self.user_id not in staff.MODS: return define.errorpage(self.user_id, errorcode.permission) submission_category = detail['subtype'] // 1000 * 1000 return define.webpage( self.user_id, "edit/submission.html", [ # Submission detail detail, # Folders folder.select_list(detail['userid'], "drop/all"), # Subtypes [ i for i in macro.MACRO_SUBCAT_LIST if submission_category <= i[0] < submission_category + 1000 ], profile.get_user_ratings(detail['userid']), ])
def signout_(request): if request.web_input(token="").token != define.get_token()[:8]: return Response(define.errorpage(request.userid, errorcode.token), status=403) login.signout(request) raise HTTPSeeOther(location="/", headers=request.response.headers)
def control_editemailpassword_post_(request): form = request.web_input(newemail="", newemailcheck="", newpassword="", newpasscheck="", password="") newemail = emailer.normalize_address(form.newemail) newemailcheck = emailer.normalize_address(form.newemailcheck) # Check if the email was invalid; Both fields must be valid (not None), and have the form fields set if not newemail and not newemailcheck and form.newemail != "" and form.newemailcheck != "": raise WeasylError("emailInvalid") return_message = profile.edit_email_password(request.userid, form.username, form.password, newemail, newemailcheck, form.newpassword, form.newpasscheck) if not return_message: # No changes were made message = "No changes were made to your account." else: # Changes were made, so inform the user of this message = "**Success!** " + return_message # Finally return the message about what (if anything) changed to the user return Response( define.errorpage(request.userid, message, [["Go Back", "/control"], ["Return Home", "/"]]))
def GET(self): form = web.input(submitid="") form.submitid = define.get_int(form.submitid) if self.user_id != define.get_ownerid(submitid=form.submitid): return define.errorpage(self.user_id, errorcode.permission) return define.webpage(self.user_id, "submit/reupload_cover.html", [form.submitid])
def verify_emailchange_get_(request): token = request.web_input(token="").token email = login.verify_email_change(request.userid, token) return Response(define.errorpage( request.userid, "**Success!** Your email address was successfully updated to **" + email + "**.", [["Return to the Home Page", "/"]] ))
def POST(self, folderid): folderid = int(folderid) if not folder.check(self.user_id, folderid): return define.errorpage(self.user_id, errorcode.permission) form = web.input(settings=[]) folder.update_settings(folderid, form.settings) raise web.seeother('/manage/folders')
def reupload_cover_get_(request): form = request.web_input(submitid="") form.submitid = define.get_int(form.submitid) if request.userid != define.get_ownerid(submitid=form.submitid): return Response(define.errorpage(request.userid, errorcode.permission)) return Response(define.webpage(request.userid, "submit/reupload_cover.html", [form.submitid]))
def resetpassword_post_(request): form = request.web_input(token="", username="", email="", day="", month="", year="", password="", passcheck="") resetpassword.reset(form) return Response(define.errorpage( request.userid, "**Success!** Your password has been reset and you may now sign in to your account.", [["Sign In", "/signin"], ["Return to the Home Page", "/"]]))
def control_editfolder_post_(request): folderid = int(request.matchdict['folderid']) if not folder.check(request.userid, folderid): return Response(define.errorpage(request.userid, errorcode.permission)) form = request.web_input(settings=[]) folder.update_settings(folderid, form.settings) raise HTTPSeeOther(location='/manage/folders')
def control_editfolder_get_(request): folderid = int(request.matchdict['folderid']) if not folder.check(request.userid, folderid): return Response(define.errorpage(request.userid, errorcode.permission)) return Response(define.webpage(request.userid, "manage/folder_options.html", [ folder.select_info(folderid), ], title="Edit Folder Options"))
def verify_emailchange_get_(request): token = request.web_input(token="").token email = login.verify_email_change(request.userid, token) return Response( define.errorpage( request.userid, "**Success!** Your email address was successfully updated to **" + email + "**.", [["Return to the Home Page", "/"]]))
def force_resetpassword_(request): if define.common_status_check(request.userid) != "resetpassword": return Response(define.errorpage(request.userid, errorcode.permission)) form = request.web_input(password="", passcheck="") resetpassword.force(request.userid, form) raise HTTPSeeOther(location="/", headers=request.response.headers)
def POST(self): form = web.input(token="", username="", email="", day="", month="", year="", password="", passcheck="") resetpassword.reset(form) return define.errorpage( self.user_id, "**Success!** Your password has been reset and you may now sign in to your account.", [["Sign In", "/signin"], ["Return to the Home Page", "/index"]])
def POST(self): if define.common_status_check(self.user_id) != "resetpassword": return define.errorpage(self.user_id, errorcode.permission) form = web.input(password="", passcheck="") resetpassword.force(self.user_id, form) raise web.seeother("/index")
def GET(self, folderid): folderid = int(folderid) if not folder.check(self.user_id, folderid): return define.errorpage(self.user_id, errorcode.permission) return define.webpage(self.user_id, "manage/folder_options.html", [ folder.select_info(folderid), ])
def control_editfolder_get_(request): folderid = int(request.matchdict['folderid']) if not folder.check(request.userid, folderid): return Response(define.errorpage(request.userid, errorcode.permission)) return Response(define.webpage(request.userid, "manage/folder_options.html", [ folder.select_info(folderid), ]))
def force_resetbirthday_(request): if define.common_status_check(request.userid) != "resetbirthday": return define.errorpage(request.userid, errorcode.permission) form = request.web_input(birthday="") birthday = define.convert_inputdate(form.birthday) profile.force_resetbirthday(request.userid, birthday) raise HTTPSeeOther(location="/", headers=request.response.headers)
def unfollowuser_(request): form = request.web_input(userid="") form.otherid = define.get_int(form.userid) followuser.remove(request.userid, form.otherid) return Response(define.errorpage( request.userid, "**Success!** You are no longer following this user.", [["Go Back", "/manage/following"], ["Return Home", "/"]]))