def post(self, request): form = SignupForm(request.POST, request.FILES) if form.is_valid(): # Creating user and profile try: with transaction.atomic(): new_user = User.objects.create( username=form.cleaned_data['login'], password=make_password(form.cleaned_data['password']), email=form.cleaned_data['email'], avatar=form.cleaned_data['avatar'], reg_date=datetime.datetime.now()) if new_user: MailSender().send(new_user.email, 'sign_up', context={"login": new_user.username}) return HttpResponseRedirect('/signup/done/') except Exception as error: message = 'Error while adding new user: '******'Error while adding new user, check fields ' return render(request, "index/signup.html", { "form": form, "message": message, "trends": Trend.get_trends() })
def signup(request): form = SignupForm(data=request.POST) if form.is_valid(): form.save(request=request) return redirect('/auth/sent') else: return render(request, 'user/signup.html', {'form': form})
def test_validate_success_register_form(self): # Ensure correct data validates. form = SignupForm(email='*****@*****.**', company="test", contact="test", password='******', confirm='signupformtest') self.assertTrue(form.validate())
def test_validate_invalid_password_format(self): # Ensure incorrect data does not validate. form = SignupForm(email='*****@*****.**', company="test", contact="test", password='******', confirm='signupformtest') self.assertFalse(form.validate())
def test_validate_email_already_registered(self): # Ensure user can't register when a duplicate email is used form = SignupForm(email='*****@*****.**', company="test", contact="test", password='******', confirm='signupformtest') self.assertFalse(form.validate())
def test_validate_invalid_password_format(self): # Ensure incorrect data does not validate. form = SignupForm( email='*****@*****.**', company="test", contact="test", password='******', confirm='signupformtest') self.assertFalse(form.validate())
def test_validate_email_already_registered(self): # Ensure user can't register when a duplicate email is used form = SignupForm( email='*****@*****.**', company="test", contact="test", password='******', confirm='signupformtest') self.assertFalse(form.validate())
def test_validate_success_register_form(self): # Ensure correct data validates. form = SignupForm( email='*****@*****.**', company="test", contact="test", password='******', confirm='signupformtest') self.assertTrue(form.validate())
def test_form_validation_for_password_mismatch(self): form = SignupForm( data={ 'email': '*****@*****.**', 'password1': 'abcdef123', 'password2': 'badcfe321' }) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['password2'], ['Les deux mots de passe ne correspondent pas.'])
def signup(): """ User Sign up page: Very basic email + password sign up form that will also login users. """ # Data is used throughout for the jinja2 templates data = {"active": "signup", "loggedin": False} # Sets the current page # Don't show the logout link # Define the SignupForm form = SignupForm(request.form) # Validate and then create userdata if request.method == "POST": if form.validate(): # Take form data email = form.email.data password = form.password.data company = form.company.data contact = form.contact.data userdata = {"username": email, "email": email, "password": password, "company": company, "contact": contact} # Create user user = User() user.config = app.config result = user.createUser(userdata, g.rdb_conn) # Check results for success or failure if result == "exists": flash("User already exists.", "danger") elif result is not False: try: stathat.ez_count(app.config["STATHAT_EZ_KEY"], app.config["ENVNAME"] + " User Signup", 1) except: pass print("/signup - New user created") cdata = cookies.genCdata(result, app.config["SECRET_KEY"]) data["loggedin"] = True flash("You are signed up.", "success") # Generate confirmation token generate_confirmation_token(email, result, time.time()) # Build response resp = make_response(redirect(url_for("member.dashboard_page"))) timeout = int(time.time()) + int(app.config["COOKIE_TIMEOUT"]) # Set the cookie secure as best as possible resp.set_cookie("loggedin", cdata, expires=timeout, httponly=True) return resp else: stathat.ez_count(app.config["STATHAT_EZ_KEY"], app.config["ENVNAME"] + " False User Signup", 1) print("/signup - False user creation") flash("Form is not valid.", "danger") # Return Signup Page return render_template("user/signup.html", data=data, form=form)
def test_valid_form_send_mail(self, mock_get_current_site): form = SignupForm( data={ 'email': '*****@*****.**', 'password1': 'GoodPassword1234', 'password2': 'GoodPassword1234' }) self.assertTrue(form.is_valid()) form.save(self.request) self.assertEqual(len(mail.outbox), 1) sent_mail = mail.outbox[0] self.assertIn('*****@*****.**', sent_mail.body)
def test_user_valid_signupform(self): """ Tests if the user tries to create an account with valid values. """ data = { 'email': self.signup_email, 'password': self.password, 'pwd_confirm': self.password } form = SignupForm(data=data) self.assertTrue(form.is_valid()) self.assertEqual(self.signup_email, form.clean_email()) self.assertEqual(self.password, form.clean_pwd_confirm())
def test_valid_form_create_user(self, mock_get_current_site): form = SignupForm( data={ 'email': '*****@*****.**', 'password1': 'GoodPassword1234', 'password2': 'GoodPassword1234' }) self.assertTrue(form.is_valid()) form.save(self.request) self.assertEqual(Profile.objects.count(), 1) new_profile = Profile.objects.first() self.assertEqual(new_profile.email, '*****@*****.**') self.assertFalse(new_profile.is_active)
def test_form_validation_for_duplicate_active_user(self): self.user1 = baker.make( Profile, username='******', email='*****@*****.**', is_active=True, ) form = SignupForm( data={ 'email': self.user1.email, 'password1': 'GoodPassword1234', 'password2': 'GoodPassword1234' }) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['email'], [DUPLICATE_USER_ERROR])
def test_form_validation_for_duplicate_inactive_user(self): self.user1 = baker.make( Profile, username='******', email='*****@*****.**', is_active=False, ) form = SignupForm( data={ 'email': self.user1.email, 'password1': 'GoodPassword1234', 'password2': 'GoodPassword1234' }) self.assertTrue(form.is_valid()) self.assertEqual(len(form.errors), 0)
def get(self, request): form = SignupForm() return render(request, "index/signup.html", { "form": form, "trends": Trend.get_trends() })
def signup_page(request): if request.method == "POST": form = SignupForm(request.POST) if form.is_valid(): user_id = form.cleaned_data["ID"] if User.objects.filter(username=user_id).exists(): messages.info(request, "이미 존재하는 유저이름입니다.") elif form.cleaned_data["PW"] != form.cleaned_data["PW_C"]: messages.info(request, "비밀번호가 서로 일치하지 않습니다.") else: user_pw = form.cleaned_data["PW"] first_name = form.cleaned_data["first_name"] add_list = User(username=user_id, first_name=first_name) add_list.set_password(user_pw) add_list.save() messages.info(request, "회원가입이 정상적으로 완료되었습니다.") return HttpResponseRedirect(reverse("post:index")) form = SignupForm() return render(request, "user/signup.html", {"form": form})
def test_user_signupform_same_email(self): """ Tests if the user tries to create an account with an already used username. """ data = { 'email': self.email, 'password': self.password, 'pwd_confirm': self.password } form = SignupForm(data=data) self.assertRaises(ValidationError, form.clean_email)
def test_user_signupform_wrong_confirm_pwd(self): """ Tests if the confirmation password is different from the first password. """ data = { 'email': self.email, 'password': self.password, 'pwd_confirm': self.pwd_confirm } form = SignupForm(data=data) self.assertRaises(ValidationError, form.clean_pwd_confirm)
def signup(request): try: args={} form = SignupForm() if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): cd = form.cleaned_data s_first_name = cd['first_name'] s_last_name = cd['last_name'] s_username = cd['username'] s_password = '******' p_first_name = cd['p_first_name'] p_last_name = cd['p_last_name'] p_username = cd['p_username'] p_email = cd['p_email'] p_password = '******' result = User.objects.create_user(password=s_password, username=s_username, first_name=s_first_name, last_name=s_last_name, email = '*****@*****.**') rslt = User.objects.create_user(password=p_password, username=p_username, first_name=p_first_name, last_name=p_last_name, email =p_email) if rslt: stud_parent = StudentParent.objects.create(parent_id=rslt.id, student_id=result.id) messages.add_message(request, messages.INFO, "Welcome, You are Registered Successfully.") return HttpResponseRedirect('/test/') else: messages.add_message(request, messages.ERROR, "Error occured during registration. Please Try Again.") return render(request, 'user/signup.html') else: args['form'] = form return render(request, 'user/signup.html', args) else: return render(request, 'user/signup.html', {'form':form}) except: messages.add_message(request, messages.ERROR, sys.exc_info()[1]) return render(request, 'user/signup.html', {'form':form})
def Signup(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') first_name = form.cleaned_data.get('first_name') last_name = form.cleaned_data.get('last_name') password = form.cleaned_data.get('password') User.objects.create_user(username=username, email=email, first_name=first_name, last_name=last_name, password=password) return redirect('login') else: form = SignupForm() context = { 'form': form, } return render(request, 'auth/signup.html', context)
def signup(): form = SignupForm() error = "" if form.validate_on_submit(): newUser = User( form.fullname.data, form.email.data, form.username.data, form.password.data ) db.session.add(newUser) # Similar to triggers. Runs all actions in session. Builds new records & can return new id fields, but data is temporary until commit() # db.session.flush() # print "Trigger ID: ", newUser.id db.session.commit() app.logger.info('%s: New User Signup:%s ', datetime.datetime.utcnow(), form.username.data) return redirect(url_for('welcome')) return render_template('user/signup.html', form=form, username=form.username.data)
def signup(): """Creating a view/route for the registration form""" form = SignupForm() # Validating the signup form unique_error = "" if form.validate_on_submit(): # Checking if the username is already taken if not Signup.query.filter_by(username=form.username.data).first(): user = Signup(form.username.data, form.email.data, generate_password_hash(form.password.data), date.today().strftime('%d %B, %Y')) db.session.add(user) db.session.commit() # Creating an instance of user profile info profile = Profile(user.id) db.session.add(profile) db.session.commit() return redirect(url_for('login')) else: # Error is username is already taken unique_error = 'Username is already taken.' return render_template('user/signup.html', form=form, unique_error=unique_error)
def user_signup(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') fname = form.cleaned_data.get('fname') lname = form.cleaned_data.get('lname') password = form.cleaned_data.get('password').encode("utf-8") conf_password = form.cleaned_data.get('confirm_password').encode( "utf-8") #checking if two passwords from form are matching or not if password == conf_password: #checking if any user exists with same username if User.objects.filter(username=username).exists(): messages.info(request, f'Username exists') return redirect('user_signup') #else we go with hashing password else: #Password Hashing hashed_password = bcrypt.hashpw(password, bcrypt.gensalt()) #create user with create and assigning form values to model u = User.objects.create(username=username, fname=fname, lname=lname, password=hashed_password) #saving the data to database and committing it u.save() #after save we redirect user to home and render books favourited by user return redirect('user_home') messages.success(request, f'Account created for { username}!') else: messages.error(request, f'passwords mismatch', 'warning') else: form = SignupForm() return render(request, 'user/user_signup.html', {'form': form})
def signup_view(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email') username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(email=email, password=raw_password) user_try_login = login(request, user) return redirect('accounts:index') else: messages.error(request, "Please check the fields.") else: form = SignupForm() context = {'form': form} return render(request, 'user/signup.html', context)
def register(request): if request.method == "POST": form = SignupForm(data=request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) messages.info(request, 'Registration successful!') messages.info(request, 'You can now login.') return redirect('home') else: messages.error(request, 'Registration failed!') messages.error(request, form.errors) context = {'form': SignupForm(), 'style': 'user.css'} return render(request, 'user/register.html', context)
def signup(request): if request.user.is_authenticated: return redirect('/') if request.method == 'POST': form = SignupForm(request.POST, request.FILES) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() verify_email(request, user) return HttpResponse( '<h1 align="center">Verify Your Email. Check Your Mailbox</h1>' ) else: form = SignupForm() context = {'form': form} return render(request, 'user/auth/signup.html', context)
def signup(): ''' User Sign up page: Very basic email + password sign up form that will also login users. ''' # Data is used throughout for the jinja2 templates data = { 'active': "signup", # Sets the current page 'loggedin': False # Don't show the logout link } # Define the SignupForm form = SignupForm(request.form) # Validate and then create userdata if request.method == "POST": if form.validate(): # Take form data email = form.email.data password = form.password.data company = form.company.data contact = form.contact.data userdata = { 'username': email, 'email': email, 'password': password, 'company': company, 'contact': contact } # Create user user = User() result = user.createUser(userdata, g.rdb_conn) # Check results for success or failure if result == "exists": data['error'] = True data['msg'] = 'User already exists' elif result is not False: stathat.ez_count( app.config['STATHAT_EZ_KEY'], app.config['ENVNAME'] + ' User Signup', 1) print("/signup - New user created") cdata = cookies.genCdata(result, app.config['SECRET_KEY']) data['loggedin'] = True data['msg'] = 'You are signed up' data['error'] = False # Build response resp = make_response(redirect(url_for('member.dashboard_page'))) timeout = int(time.time()) + int(app.config['COOKIE_TIMEOUT']) # Set the cookie secure as best as possible resp.set_cookie( 'loggedin', cdata, expires=timeout, httponly=True) return resp else: stathat.ez_count( app.config['STATHAT_EZ_KEY'], app.config['ENVNAME'] + ' Failed User Signup', 1) print("/signup - Failed user creation") data['msg'] = 'Form is not valid' data['error'] = True # Return Signup Page return render_template('user/signup.html', data=data, form=form)
def auth(request): context = {'signup_form': SignupForm()} return render(request, 'user/signup.html', context)
def test_form_renders_email_input(self): form = SignupForm() self.assertIn('placeholder="*****@*****.**"', form.as_p()) self.assertIn('class="form-control input-lg"', form.as_p())
def test_form_renders_password1_and_password2_inputs(self): form = SignupForm() self.assertIn('placeholder="********"', form.as_p()) self.assertIn('id="id_password1', form.as_p()) self.assertIn('id="id_password2"', form.as_p())
def test_form_validation_for_blank_email(self): form = SignupForm(data={'email': ''}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['email'], [EMPTY_EMAIL_ERROR])
def signup(): ''' User Sign up page: Very basic email + password sign up form that will also login users. ''' # Data is used throughout for the jinja2 templates data = { 'active': "signup", # Sets the current page 'loggedin': False # Don't show the logout link } # Define the SignupForm form = SignupForm(request.form) # Validate and then create userdata if request.method == "POST": if form.validate(): # Take form data email = form.email.data password = form.password.data company = form.company.data contact = form.contact.data userdata = { 'username': email, 'email': email, 'password': password, 'company': company, 'contact': contact } # Create user user = User() user.config = app.config result = user.createUser(userdata, g.rdb_conn) # Check results for success or failure if result == "exists": flash('User already exists.', 'danger') elif result is not False: try: stathat.ez_count( app.config['STATHAT_EZ_KEY'], app.config['ENVNAME'] + ' User Signup', 1) except: pass print("/signup - New user created") cdata = cookies.genCdata(result, app.config['SECRET_KEY']) data['loggedin'] = True flash('You are signed up.', 'success') # Generate confirmation token generate_confirmation_token(email, result, time.time()) # Build response resp = make_response(redirect(url_for('member.dashboard_page'))) timeout = int(time.time()) + int(app.config['COOKIE_TIMEOUT']) # Set the cookie secure as best as possible resp.set_cookie( 'loggedin', cdata, expires=timeout, httponly=True) return resp else: stathat.ez_count( app.config['STATHAT_EZ_KEY'], app.config['ENVNAME'] + ' False User Signup', 1) print("/signup - False user creation") flash('Form is not valid.', 'danger') # Return Signup Page return render_template('user/signup.html', data=data, form=form)