def login(request):
session = DBSession()
message = request.params.get('message')
username = request.params.get('username')
if request.method == 'POST':
if username:
username = username.lower()
# Think now have steam accounts. can have different accounts but same name
userq = session.query(User).filter(User.username == username).all()
for user in userq:
if user.validate_password(request.params.get('password')):
headers = remember(request, user.id)
user.last_login = datetime.datetime.now()
return HTTPFound('/team', headers=headers)
else:
headers = forget(request)
message = "Password did not match stored value for %s" % user.username
if not userq:
message = "Username not recognised"
else:
message = 'Oops! SOmething went wrong'
headers = forget(request)
return_dict = {'message': message, "plus_id": request.registry.settings.get(
'SOCIAL_AUTH_STEAM_KEY'
)}
return add_other_games(session, request.game, return_dict)
python类HTTPFound()的实例源码
def logout(request):
headers = forget(request)
return HTTPFound(location='/login', headers=headers)
def change_password(request):
session = DBSession()
user_id = authenticated_userid(request)
new_password = request.params.get('new_password')
confirm_new_password = request.params.get('confirm_new_password')
old_password = request.params.get('old_password')
user = session.query(User).filter(User.id == user_id).first()
if not user:
params = {"message": "Your username could not be found",
"message_type": "change_password"}
return HTTPFound(location=request.route_url('account_settings', _query=params))
if not user.validate_password(old_password):
params = {"message": "Old password did not match",
"message_type": "change_password"}
return HTTPFound(location=request.route_url('account_settings', _query=params))
if old_password == "": # this is the case for steam accounts
params = {"message": "Change password does not apply to steam logins",
"message_type": "failure"}
return HTTPFound(location=request.route_url('account_settings', _query=params))
pword_invalid_check = check_invalid_password(new_password, confirm_new_password)
if pword_invalid_check:
return HTTPFound(location=request.route_url('account_settings', _query=pword_invalid_check))
session.query(User).filter(User.id == user_id).update({User.password: bcrypt.encrypt(new_password)})
params = {"message": "Congratulations! Password successfully changed",
"message_type": "success"}
return HTTPFound(location=request.route_url('account_settings', _query=params))
def reset_password(request):
session = DBSession()
guid = request.params.get('guid')
user_id = request.params.get('user_id')
new_password = request.params.get('new_password')
confirm_new_password = request.params.get('confirm_new_password')
if not session.query(PasswordReset).filter(PasswordReset.user_id == user_id).first().validate_guid(guid):
raise HTTPForbidden()
if confirm_new_password != new_password:
params = {"message": "Passwords did not match",
"message_type": "change_password"}
return HTTPFound(location=request.route_url('viewAccount', _query=params))
pword_invalid_check = check_invalid_password(new_password, confirm_new_password)
if pword_invalid_check:
return HTTPFound(location=request.route_url('login', _query=pword_invalid_check))
session.query(User).filter(User.id == user_id).update({User.password: bcrypt.encrypt(new_password)})
session.query(PasswordReset).filter(PasswordReset.user_id == user_id).delete()
params = {"message": "Congratulations! Password successfully changed",
"message_type": "success"}
return HTTPFound(location=request.route_url('login', _query=params))
def update_email_settings(request):
session = DBSession()
user_id = authenticated_userid(request)
if not user_id:
return HTTPFound('/login')
new_email = request.params.get('email')
contactable = True if request.params.get('emailContact') == "on" else False
session.query(User).filter(User.id == user_id).\
update({User.contactable: contactable, User.email: new_email})
params = {"message": "Congratulations! Email settings successfully updated",
"message_type": "success"}
return HTTPFound(location=request.route_url('account_settings', _query=params))
# @view_config(route_name='home', renderer='../templates/login.mako')
# def home(request):
# try:
# user = get_user(request)
# headers = remember(request, user.id)
# return HTTPFound("/team", headers=headers)
# except:
# return HTTPFound("/login")
# # return common_context(
# # request.registry.settings['SOCIAL_AUTH_AUTHENTICATION_BACKENDS'],
# # load_strategy(request),
# # user=get_user(request),
# # plus_id=request.registry.settings.get(
# # 'SOCIAL_AUTH_GOOGLE_PLUS_KEY'
# # ),
# # )
def done(request):
user = get_user(request)
headers = remember(request, user.id)
return HTTPFound('/team', headers=headers)
# return {"user": get_user(request),
# "plus_id": request.registry.settings.get(
# 'SOCIAL_AUTH_STEAM_KEY'
# ),
# }
# return common_context(
# request.registry.settings['SOCIAL_AUTH_AUTHENTICATION_BACKENDS'],
# load_strategy(request),
# user=get_user(request),
# plus_id=request.registry.settings['SOCIAL_AUTH_GOOGLE_PLUS_KEY'],
# )
# @view_config(route_name='email_required', renderer='common:templates/home.jinja2')
# def email_required(request):
# strategy = load_strategy(request)
# partial_token = request.GET.get('partial_token')
# partial = strategy.partial_load(partial_token)
# return common_context(
# request.registry.settings['SOCIAL_AUTH_AUTHENTICATION_BACKENDS'],
# strategy,
# user=get_user(request),
# plus_id=request.registry.settings['SOCIAL_AUTH_GOOGLE_PLUS_KEY'],
# email_required=True,
# partial_backend_name=partial.backend,
# partial_token=partial_token
# )
def start_setup_view(self):
if "properties" in self.request.root.__dict__ and (PROP.getProperty(self.request, PROP.SITE_SETUP) == True):
return HTTPFound(location=self.request.route_path("welcome"))
return {}
def setup_one_view(self):
if (PROP.getProperty(self.request, PROP.SITE_SETUP) == True):
return HTTPFound(location=self.request.route_path("welcome"))
setup = False
if (PROP.getProperty(self.request, PROP.VERSION) != None):
print "Database already setup!"
else:
# Setup the database
self.db_run_setup(self.request.root)
setup = True
return {
"setup": setup
}
def setup_two_view(self):
if (PROP.getProperty(self.request, PROP.SITE_SETUP) == True):
return HTTPFound(location=self.request.route_path("welcome"))
elif (PROP.getProperty(self.request, PROP.VERSION) == None):
return HTTPFound(location=self.request.route_path("setup_stageone"))
# Check if the password has already been changed, default is 'password'
admin_usr = self.request.root.users["admin"]
test_password = salt_password("password", admin_usr.password_salt)
if test_password != admin_usr.password:
self.request.session.flash("It looks like someone has already changed the default password on the account, if this wasn't you then contact support!", "info")
return HTTPFound(location=self.request.route_path("setup_stagethree"))
# Get password for admin user and double check
if "password_one" in self.request.POST and "password_two" in self.request.POST:
pwd_1 = self.request.POST["password_one"]
pwd_2 = self.request.POST["password_two"]
if len(pwd_1) < 5:
self.request.session.flash("The passwords entered are too short, they must be of 5 characters or longer.", "error")
return {}
elif pwd_1 != pwd_2:
self.request.session.flash("The passwords entered do not match.", "error")
return {}
# Set the administrator password
admin_usr.password_salt = Coding().generateUniqueCode()
admin_usr.password = salt_password(pwd_1, admin_usr.password_salt)
return HTTPFound(location=self.request.route_path("setup_stagethree"))
return {}
def setup_done_view(self):
if (PROP.getProperty(self.request, PROP.SITE_SETUP) == True):
return HTTPFound(location=self.request.route_path("welcome"))
elif (PROP.getProperty(self.request, PROP.VERSION) == None):
return HTTPFound(location=self.request.route_path("setup_stageone"))
self.request.root.properties[PROP.SITE_SETUP] = True
return {}
# -- Database Setup Functions -- #
def at_front_view(self):
if not self.request.root.properties[PROP_KEYS.QUEUE_ENABLED]:
return HTTPFound(location=self.request.route_path("welcome"))
# Find open slots
total_slots = self.request.root.properties[PROP_KEYS.CONCURRENT_NUM]
open_slots = total_slots - len(self.request.root.active)
# Continue
position = Queue(self.request).position(self.request.session["queue_id"])
if position < open_slots:
queue_id = self.request.session["queue_id"]
items = [x for x in self.request.root.queue if x.queue_id == queue_id]
if len(items) <= 0:
self.request.session.flash("You are not yet at the front of the queue, please wait.", "info")
return HTTPFound(location=self.request.route_path("queue"))
else:
# Check if there are too many people in "active" state
if open_slots <= 0:
return HTTPFound(location=self.request.route_path("queue"))
# Shift the person from being in queue to being active
item = items[0]
self.request.root.queue.remove(item)
self.request.root.active[item.__name__] = item
item.__parent__ = self.request.root.active
item.queue_exit_time = item.purchase_entry_time = datetime.now()
# Make active
self.request.session.pop("queue_id", None)
self.request.session["active_id"] = item.__name__
header = remember(self.request, str(item.__name__))
return HTTPFound(location=self.request.route_path('welcome'), headers=header)
else:
self.request.session.flash("You are not yet at the front of the queue, please wait.", "info")
return HTTPFound(location=self.request.route_path("queue"))
def welcome_view(self):
# Check whether the site is setup?
if not "properties" in self.request.root.__dict__:
print "Need to setup site!"
return HTTPFound(location=self.request.route_path("setup"))
# If queue enabled, deal with it
elif not self.has_queued:
return HTTPFound(location=self.request.route_path("queue"))
# Check queue/active status
elif Queue(self.request).timed_out():
return HTTPFound(self.request.route_path("purchase_timeout"))
elif "user_id" in self.request.session and self.request.session["user_id"] in self.context.users:
return HTTPFound(location=self.request.route_path("branch_flow"))
return {}
def welcome_view_do(self):
if not self.has_queued:
return HTTPFound(location=self.request.route_path("queue"))
# Get username and password
username = self.request.POST["username"].lower()
password = self.request.POST["password"]
# Check if user exists and is non-raven
if not username in self.request.root.users:
self.request.session.flash("Your username or password was incorrect", "error")
return HTTPFound(location=self.request.route_path("welcome"))
user = self.request.root.users[username]
if user.profile != None and user.profile.raven_user:
self.request.session.flash("Your account appears to be a Raven account, please use the Raven login instead.", "error");
return HTTPFound(location=self.request.route_path("welcome"))
# Check password
if user.password != salt_password(password, user.password_salt):
self.request.session.flash("Your username or password was incorrect", "error")
return HTTPFound(location=self.request.route_path("welcome"))
# Ok, this all looks ok - lets go!
header = remember(self.request, user.__name__)
self.request.session["user_id"] = user.__name__
if user.profile == None:
profile = UserProfile()
profile.raven_user = False
profile.__parent__ = user
profile.__name__ = user.__name__ + "-profile"
user.profile = profile
return HTTPFound(location=self.request.route_path('user_profile_edit'), headers=header)
elif None in [user.profile.dob, user.profile.fullname]:
return HTTPFound(location=self.request.route_path('user_profile_edit'), headers=header)
else:
return HTTPFound(location=self.request.route_path('user_profile'), headers=header)
def start_raven_view(self):
if not self.has_queued:
return HTTPFound(location=self.request.route_path("queue"))
self.request.session["raven_route"] = self.request.route_path("branch_raven_flow")
return HTTPFound(location=self.request.route_path("raven_first_stage"))
def branch_flow_view(self):
user = self.context.users[self.request.session["user_id"]]
if user.profile == None or None in [user.profile.dob, user.profile.fullname]:
return HTTPFound(location=self.request.route_path('user_profile_edit'))
else:
return HTTPFound(location=self.request.route_path('user_profile'))
def view_403(self):
# Get intended path
if not self.user:
self.request.session.flash("You will need to login before you can access other parts of the ticketing system.", "info")
return HTTPFound(location=self.request.route_path("welcome"))
return {}
def api_login_raven_view(self):
self.request.session["raven_route"] = self.request.route_path("api_login_raven_return")
return HTTPFound(location=self.request.route_path("raven_first_stage"))
def api_login_raven_return_view(self):
# Choose raven path, create a user if necessary
users = self.context.users.values()
raven_obj = self.request.session["raven"]
# Should select a single user
user = [x for x in users if x.profile != None and x.profile.crsid != None and x.profile.crsid.lower() == raven_obj.raven_crsid.lower()]
if len(user) == 0:
self.request.session.flash("No account exists for this Raven login", "error")
return HTTPFound(location=self.request.route_path("api_login"))
else:
user = user[0]
header = remember(self.request, user.__name__)
self.request.session["user_id"] = user.__name__
return HTTPFound(location=self.request.route_path('api_token_issue'), headers=header)
def single_payment_view(self):
payments = self.request.root.payments
# Get payment if possible
if not self.request.matchdict["ref_code"] in self.request.root.payments:
return HTTPFound(location=self.request.route_path("admin_payments"))
payment = payments[self.request.matchdict["ref_code"]]
if "action" in self.request.GET:
if self.request.GET["action"] == "recalculate":
if payment.method == "stripe":
payment.processing = int(payment.item_total * self.stripe_percentage)
payment.total = int(payment.item_total * (1 + self.stripe_percentage))
else:
payment.processing = 0
payment.total = payment.item_total
self.request.session.flash("Recalculated the payment total.", "info")
elif self.request.GET["action"] == "emailconfirm":
PurchaseConfirmationEmail(self.request).compose_and_send(payment.ref_code)
self.request.session.flash("A payment confirmation has been sent via email.", "info")
elif self.request.GET["action"] == "sendtickets":
emailer = GenericEmail(self.request)
emailer.compose_and_send(
"Event Tickets",
"""Please find the tickets you purchased in payment %s attached as a PDF to this email. Please download and print-out the tickets and bring them with you to the event.""" % (payment.ref_code),
payment.owner.__name__,
pdf_attachment=TicketDownload(self.request).payment_tickets_pdf(payment)
)
self.request.session.flash("The tickets in this payment have been sent via email.", "info")
return {
"payment": payment,
}