def test_bcrypt_gen_password_hash(): pw = "youwillneverguessthis" # Normal password hash generation, and check on that hash hashed_pw = auth_lib.bcrypt_gen_password_hash(pw) assert auth_lib.bcrypt_check_password(pw, hashed_pw) assert not auth_lib.bcrypt_check_password("notthepassword", hashed_pw) # Same thing, extra salt. hashed_pw = auth_lib.bcrypt_gen_password_hash(pw, "3><7R45417") assert auth_lib.bcrypt_check_password(pw, hashed_pw, "3><7R45417") assert not auth_lib.bcrypt_check_password("notthepassword", hashed_pw, "3><7R45417")
def test_bcrypt_gen_password_hash(): pw = 'youwillneverguessthis' # Normal password hash generation, and check on that hash hashed_pw = auth_lib.bcrypt_gen_password_hash(pw) assert auth_lib.bcrypt_check_password(pw, hashed_pw) assert not auth_lib.bcrypt_check_password('notthepassword', hashed_pw) # Same thing, extra salt. hashed_pw = auth_lib.bcrypt_gen_password_hash(pw, '3><7R45417') assert auth_lib.bcrypt_check_password(pw, hashed_pw, '3><7R45417') assert not auth_lib.bcrypt_check_password('notthepassword', hashed_pw, '3><7R45417')
def edit_account(request): user = request.user form = forms.EditAccountForm(request.form, wants_comment_notification=user.get("wants_comment_notification")) if request.method == "POST": form_validated = form.validate() # if the user has not filled in the new or old password fields if not form.new_password.data and not form.old_password.data: if form.wants_comment_notification.validate(form): user.wants_comment_notification = form.wants_comment_notification.data user.save() messages.add_message(request, messages.SUCCESS, _("Account settings saved")) return redirect(request, "mediagoblin.user_pages.user_home", user=user.username) # so the user has filled in one or both of the password fields else: if form_validated: password_matches = auth_lib.bcrypt_check_password(form.old_password.data, user.pw_hash) if password_matches: # the entire form validates and the password matches user.pw_hash = auth_lib.bcrypt_gen_password_hash(form.new_password.data) user.wants_comment_notification = form.wants_comment_notification.data user.save() messages.add_message(request, messages.SUCCESS, _("Account settings saved")) return redirect(request, "mediagoblin.user_pages.user_home", user=user.username) else: form.old_password.errors.append(_("Wrong password")) return render_to_response(request, "mediagoblin/edit/edit_account.html", {"user": user, "form": form})
def register(request): """The registration view. Note that usernames will always be lowercased. Email domains are lowercased while the first part remains case-sensitive. """ # Redirects to indexpage if registrations are disabled if not mg_globals.app_config["allow_registration"]: messages.add_message( request, messages.WARNING, _('Sorry, registration is disabled on this instance.')) return redirect(request, "index") register_form = auth_forms.RegistrationForm(request.form) if request.method == 'POST' and register_form.validate(): # TODO: Make sure the user doesn't exist already users_with_username = User.query.filter_by(username=register_form.data['username']).count() users_with_email = User.query.filter_by(email=register_form.data['email']).count() extra_validation_passes = True if users_with_username: register_form.username.errors.append( _(u'Sorry, a user with that name already exists.')) extra_validation_passes = False if users_with_email: register_form.email.errors.append( _(u'Sorry, a user with that email address already exists.')) extra_validation_passes = False if extra_validation_passes: # Create the user user = User() user.username = register_form.data['username'] user.email = register_form.data['email'] user.pw_hash = auth_lib.bcrypt_gen_password_hash( register_form.password.data) user.verification_key = unicode(uuid.uuid4()) user.save() # log the user in request.session['user_id'] = unicode(user.id) request.session.save() # send verification email email_debug_message(request) send_verification_email(user, request) # redirect the user to their homepage... there will be a # message waiting for them to verify their email return redirect( request, 'mediagoblin.user_pages.user_home', user=user.username) return render_to_response( request, 'mediagoblin/auth/register.html', {'register_form': register_form})
def edit_account(request): user = request.user form = forms.EditAccountForm( request.form, wants_comment_notification=user.wants_comment_notification, license_preference=user.license_preference, ) if request.method == "POST": form_validated = form.validate() if form_validated and form.wants_comment_notification.validate(form): user.wants_comment_notification = form.wants_comment_notification.data if form_validated and form.new_password.data or form.old_password.data: password_matches = auth_lib.bcrypt_check_password(form.old_password.data, user.pw_hash) if password_matches: # the entire form validates and the password matches user.pw_hash = auth_lib.bcrypt_gen_password_hash(form.new_password.data) else: form.old_password.errors.append(_("Wrong password")) if form_validated and form.license_preference.validate(form): user.license_preference = form.license_preference.data if form_validated and not form.errors: user.save() messages.add_message(request, messages.SUCCESS, _("Account settings saved")) return redirect(request, "mediagoblin.user_pages.user_home", user=user.username) return render_to_response(request, "mediagoblin/edit/edit_account.html", {"user": user, "form": form})
def register(request): """ Your classic registration view! """ register_form = auth_forms.RegistrationForm(request.POST) if request.method == "POST" and register_form.validate(): # TODO: Make sure the user doesn't exist already users_with_username = request.db.User.find({"username": request.POST["username"]}).count() if users_with_username: register_form.username.errors.append(u"Sorry, a user with that name already exists.") else: # Create the user entry = request.db.User() entry["username"] = request.POST["username"] entry["email"] = request.POST["email"] entry["pw_hash"] = auth_lib.bcrypt_gen_password_hash(request.POST["password"]) entry.save(validate=True) # TODO: Send email authentication request # Redirect to register_success return exc.HTTPFound(location=request.urlgen("mediagoblin.auth.register_success")) # render template = request.template_env.get_template("mediagoblin/auth/register.html") return Response(template.render({"request": request, "register_form": register_form}))
def adduser(args): #TODO: Lets trust admins this do not validate Emails :) commands_util.setup_app(args) args.username = commands_util.prompt_if_not_set(args.username, "Username:"******"Password:"******"Email:") db = mg_globals.database users_with_username = \ db.User.find({ 'username': args.username.lower(), }).count() if users_with_username: print u'Sorry, a user with that name already exists.' else: # Create the user entry = db.User() entry.username = unicode(args.username.lower()) entry.email = unicode(args.email) entry.pw_hash = auth_lib.bcrypt_gen_password_hash(args.password) entry.status = u'active' entry.email_verified = True entry.save(validate=True) print "User created (and email marked as verified)"
def register(request): """ Your classic registration view! """ register_form = auth_forms.RegistrationForm(request.POST) if request.method == 'POST' and register_form.validate(): # TODO: Make sure the user doesn't exist already users_with_username = \ request.db.User.find({ 'username': request.POST['username'].lower() }).count() if users_with_username: register_form.username.errors.append( u'Sorry, a user with that name already exists.') else: # Create the user entry = request.db.User() entry['username'] = request.POST['username'].lower() entry['email'] = request.POST['email'] entry['pw_hash'] = auth_lib.bcrypt_gen_password_hash( request.POST['password']) entry.save(validate=True) send_verification_email(entry, request) return redirect(request, "mediagoblin.auth.register_success") return render_to_response(request, 'mediagoblin/auth/register.html', {'register_form': register_form})
def changepw(args): commands_util.setup_app(args) db = mg_globals.database user = db.User.one({'username':unicode(args.username.lower())}) if user: user['pw_hash'] = auth_lib.bcrypt_gen_password_hash(args.password) user.save() print 'Password successfully changed' else: print 'The user doesn\'t exist'
def verify_forgot_password(request): """ Check the forgot-password verification and possibly let the user change their password because of it. """ # get form data variables, and specifically check for presence of token formdata = _process_for_token(request) if not formdata['has_userid_and_token']: return render_404(request) formdata_token = formdata['vars']['token'] formdata_userid = formdata['vars']['userid'] formdata_vars = formdata['vars'] # check if it's a valid Id try: user = request.db.User.find_one( {'_id': ObjectId(unicode(formdata_userid))}) except InvalidId: return render_404(request) # check if we have a real user and correct token if ((user and user.fp_verification_key and user.fp_verification_key == unicode(formdata_token) and datetime.datetime.now() < user.fp_token_expire and user.email_verified and user.status == 'active')): cp_form = auth_forms.ChangePassForm(formdata_vars) if request.method == 'POST' and cp_form.validate(): user.pw_hash = auth_lib.bcrypt_gen_password_hash( request.form['password']) user.fp_verification_key = None user.fp_token_expire = None user.save() messages.add_message( request, messages.INFO, _("You can now log in using your new password.")) return redirect(request, 'mediagoblin.auth.login') else: return render_to_response( request, 'mediagoblin/auth/change_fp.html', {'cp_form': cp_form}) # in case there is a valid id but no user whit that id in the db # or the token expired else: return render_404(request)
def fixture_add_user(username=u"chris", password="******", active_user=True): test_user = mg_globals.database.User() test_user.username = username test_user.email = username + u"@example.com" if password is not None: test_user.pw_hash = bcrypt_gen_password_hash(password) if active_user: test_user.email_verified = True test_user.status = u"active" test_user.save() # Reload test_user = mg_globals.database.User.find_one({"username": username}) # ... and detach from session: Session.expunge(test_user) return test_user
def fixture_add_user(username=u'chris', password='******', active_user=True): test_user = mg_globals.database.User() test_user.username = username test_user.email = username + u'@example.com' if password is not None: test_user.pw_hash = bcrypt_gen_password_hash(password) if active_user: test_user.email_verified = True test_user.status = u'active' test_user.save() # Reload test_user = mg_globals.database.User.find_one({'username': username}) # ... and detach from session: from mediagoblin.db.sql.base import Session Session.expunge(test_user) return test_user
def register(request): """ Your classic registration view! """ register_form = auth_forms.RegistrationForm(request.POST) if request.method == 'POST' and register_form.validate(): # TODO: Make sure the user doesn't exist already users_with_username = \ request.db.User.find({'username': request.POST['username']}).count() if users_with_username: register_form.username.errors.append( u'Sorry, a user with that name already exists.') else: # Create the user entry = request.db.User() entry['username'] = request.POST['username'] entry['email'] = request.POST['email'] entry['pw_hash'] = auth_lib.bcrypt_gen_password_hash( request.POST['password']) entry.save(validate=True) # TODO: Send email authentication request # Redirect to register_success return exc.HTTPFound( location=request.urlgen("mediagoblin.auth.register_success")) # render template = request.template_env.get_template( 'mediagoblin/auth/register.html') return Response( template.render({ 'request': request, 'register_form': register_form }))
def fixture_add_user(username=u'chris', password=u'toast', active_user=True): # Reuse existing user or create a new one test_user = User.query.filter_by(username=username).first() if test_user is None: test_user = User() test_user.username = username test_user.email = username + u'@example.com' if password is not None: test_user.pw_hash = bcrypt_gen_password_hash(password) if active_user: test_user.email_verified = True test_user.status = u'active' test_user.save() # Reload test_user = User.query.filter_by(username=username).first() # ... and detach from session: Session.expunge(test_user) return test_user
def adduser(args): #TODO: Lets trust admins this do not validate Emails :) commands_util.setup_app(args) db = mg_globals.database users_with_username = \ db.User.find({ 'username': args.username.lower() }).count() if users_with_username: print u'Sorry, a user with that name already exists.' else: # Create the user entry = db.User() entry['username'] = unicode(args.username.lower()) entry['email'] = unicode(args.email) entry['pw_hash'] = auth_lib.bcrypt_gen_password_hash(args.password) entry['status'] = u'active' entry['email_verified'] = True entry.save(validate=True) print "User created (and email marked as verified)"
def register(request): """ Your classic registration view! """ # Redirects to indexpage if registrations are disabled if not mg_globals.app_config["allow_registration"]: messages.add_message( request, messages.WARNING, _('Sorry, registration is disabled on this instance.')) return redirect(request, "index") register_form = auth_forms.RegistrationForm(request.form) if request.method == 'POST' and register_form.validate(): # TODO: Make sure the user doesn't exist already username = unicode(request.form['username'].lower()) em_user, em_dom = unicode(request.form['email']).split("@", 1) em_dom = em_dom.lower() email = em_user + "@" + em_dom users_with_username = request.db.User.find( {'username': username}).count() users_with_email = request.db.User.find( {'email': email}).count() extra_validation_passes = True if users_with_username: register_form.username.errors.append( _(u'Sorry, a user with that name already exists.')) extra_validation_passes = False if users_with_email: register_form.email.errors.append( _(u'Sorry, a user with that email address already exists.')) extra_validation_passes = False if extra_validation_passes: # Create the user user = request.db.User() user.username = username user.email = email user.pw_hash = auth_lib.bcrypt_gen_password_hash( request.form['password']) user.verification_key = unicode(uuid.uuid4()) user.save(validate=True) # log the user in request.session['user_id'] = unicode(user._id) request.session.save() # send verification email email_debug_message(request) send_verification_email(user, request) # redirect the user to their homepage... there will be a # message waiting for them to verify their email return redirect( request, 'mediagoblin.user_pages.user_home', user=user.username) return render_to_response( request, 'mediagoblin/auth/register.html', {'register_form': register_form})
def test_authentication_views(test_app): """ Test logging in and logging out """ # Make a new user test_user = mg_globals.database.User() test_user['username'] = u'chris' test_user['email'] = u'*****@*****.**' test_user['pw_hash'] = auth_lib.bcrypt_gen_password_hash('toast') test_user.save() # Get login # --------- test_app.get('/auth/login/') assert util.TEMPLATE_TEST_CONTEXT.has_key( 'mediagoblin/auth/login.html') # Failed login - blank form # ------------------------- util.clear_test_template_context() response = test_app.post('/auth/login/') context = util.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html'] form = context['login_form'] assert form.username.errors == [u'This field is required.'] assert form.password.errors == [u'This field is required.'] # Failed login - blank user # ------------------------- util.clear_test_template_context() response = test_app.post( '/auth/login/', { 'password': u'toast'}) context = util.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html'] form = context['login_form'] assert form.username.errors == [u'This field is required.'] # Failed login - blank password # ----------------------------- util.clear_test_template_context() response = test_app.post( '/auth/login/', { 'username': u'chris'}) context = util.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html'] form = context['login_form'] assert form.password.errors == [u'This field is required.'] # Failed login - bad user # ----------------------- util.clear_test_template_context() response = test_app.post( '/auth/login/', { 'username': u'steve', 'password': '******'}) context = util.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html'] assert context['login_failed'] # Failed login - bad password # --------------------------- util.clear_test_template_context() response = test_app.post( '/auth/login/', { 'username': u'chris', 'password': '******'}) context = util.TEMPLATE_TEST_CONTEXT['mediagoblin/auth/login.html'] assert context['login_failed'] # Successful login # ---------------- util.clear_test_template_context() response = test_app.post( '/auth/login/', { 'username': u'chris', 'password': '******'}) # User should be redirected response.follow() assert_equal( urlparse.urlsplit(response.location)[2], '/') assert util.TEMPLATE_TEST_CONTEXT.has_key( 'mediagoblin/root.html') # Make sure user is in the session context = util.TEMPLATE_TEST_CONTEXT['mediagoblin/root.html'] session = context['request'].session assert session['user_id'] == unicode(test_user['_id']) # Successful logout # ----------------- util.clear_test_template_context() response = test_app.get('/auth/logout/') # Should be redirected to index page response.follow() assert_equal( urlparse.urlsplit(response.location)[2], '/') assert util.TEMPLATE_TEST_CONTEXT.has_key( 'mediagoblin/root.html') # Make sure the user is not in the session context = util.TEMPLATE_TEST_CONTEXT['mediagoblin/root.html'] session = context['request'].session assert session.has_key('user_id') == False # User is redirected to custom URL if POST['next'] is set # ------------------------------------------------------- util.clear_test_template_context() response = test_app.post( '/auth/login/', { 'username': u'chris', 'password': '******', 'next' : '/u/chris/'}) assert_equal( urlparse.urlsplit(response.location)[2], '/u/chris/')