def test_expired_confirmation_token(self): u = User(password='******') db.session.add(u) db.session.commit() token = u.generate_token(expiration=1) time.sleep(2) self.assertFalse(u.confirm_registration(token))
def test_valid_reset_token(self): u = User(password='******') db.session.add(u) db.session.commit() token = u.generate_token() self.assertTrue(u.confirm_reset(token, 'dog')) self.assertTrue(u.verify_password('dog'))
def test_valid_email_change_token(self): u = User(email='*****@*****.**', password='******') db.session.add(u) db.session.commit() token = u.generate_token(new_email='*****@*****.**') self.assertTrue(u.confirm_new_email(token)) self.assertTrue(u.email == '*****@*****.**')
def test_ping(self): u = User(password='******') db.session.add(u) db.session.commit() time.sleep(2) last_seen_before = u.last_seen u.ping() self.assertTrue(u.last_seen > last_seen_before)
def test_duplicate_email_change_token(self): u1 = User(email='*****@*****.**', password='******') u2 = User(email='*****@*****.**', password='******') db.session.add(u1) db.session.add(u2) db.session.commit() token = u2.generate_token(new_email='*****@*****.**') self.assertFalse(u2.confirm_new_email(token)) self.assertTrue(u2.email == '*****@*****.**')
def get_openid_user(cls, assoc_key): try: authmap = drupal.Authmap.objects.using(DRUPAL_DB).get(authname=assoc_key) drupal_user = drupal.Users.objects.using(DRUPAL_DB).get(uid=authmap.uid) try: user = User.objects.get(username=drupal_user.name) except User.DoesNotExist: user = User(username=drupal_user.name) cls.get_user_data(drupal_user, user) user.save() return user except drupal.Authmap.DoesNotExist, drupal.Users.DoesNotExist: return None
def get_openid_user(cls, assoc_key): try: user_openid = lernanta.UserOpenID.objects.using(LERNANTA_DB).get(display_id__exact=assoc_key) lernanta_user = lernanta.UserProfile.objects.using(LERNANTA_DB).get(user=user_openid.user) try: user = User.objects.get(username=lernanta_user.username) except User.DoesNotExist: user = User(username=lernanta_user.username) cls.get_user_data(lernanta_user, user) user.save() return user except lernanta.UserOpenID.DoesNotExist, lernanta.UserProfile.DoesNotExist: return None
def create_user(request): if request.POST: form = CreateUserForm(request.POST) if form.is_valid(): user_ = User(username=form.cleaned_data['username'], email=form.cleaned_data['email']) user_.set_password(form.cleaned_data['password1']) if not form.cleaned_data.get('validate_email', False): user_.email_isvalid = True user_.save() UserJoinsAction(user=user_).save() request.user.message_set.create( message=_("New user created sucessfully. %s.") % html.hyperlink(user_.get_profile_url(), _("See %s profile") % user_.username, target="_blank")) return HttpResponseRedirect( reverse("admin_tools", kwargs={'name': 'createuser'})) else: form = CreateUserForm() return ('osqaadmin/createuser.html', { 'form': form, })
def register(request): if request.method == 'POST': form = ClassicRegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password1'] email = form.cleaned_data['email'] user_ = User(username=username, email=email) user_.set_password(password) if User.objects.all().count() == 0: user_.is_superuser = True user_.is_staff = True user_.save() UserJoinsAction(user=user_, ip=request.META['REMOTE_ADDR']).save() return login_and_forward(request, user_, None, _("A welcome email has been sent to your email address. ")) else: form = ClassicRegisterForm(initial={'next':reverse('index')}) return render_to_response('auth/complete.html', { 'form1': form }, context_instance=RequestContext(request))
def register(request): if request.method == 'POST': form = ClassicRegisterForm(request.POST) email_feeds_form = SimpleEmailSubscribeForm(request.POST) if form.is_valid() and email_feeds_form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password1'] email = form.cleaned_data['email'] user_ = User(username=username, email=email) user_.set_password(password) if User.objects.all().count() == 0: user_.is_superuser = True user_.is_staff = True user_.save() UserJoinsAction(user=user_, ip=request.META['REMOTE_ADDR']).save() if email_feeds_form.cleaned_data['subscribe'] == 'n': user_.subscription_settings.enable_notifications = False user_.subscription_settings.save() return login_and_forward(request, user_, None, _("A welcome email has been sent to your email address. ")) else: form = ClassicRegisterForm(initial={'next':'/'}) email_feeds_form = SimpleEmailSubscribeForm() return render_to_response('auth/complete.html', { 'form1': form, 'email_feeds_form': email_feeds_form }, context_instance=RequestContext(request))
def get_openid_user(cls, assoc_key): try: authmap = drupal.Authmap.objects.using(DRUPAL_DB).get( authname=assoc_key) drupal_user = drupal.Users.objects.using(DRUPAL_DB).get( uid=authmap.uid) try: user = User.objects.get(username=drupal_user.name) except User.DoesNotExist: user = User(username=drupal_user.name) cls.get_user_data(drupal_user, user) user.save() return user except drupal.Authmap.DoesNotExist, drupal.Users.DoesNotExist: return None
def register(): if current_user.is_authenticated: return redirect(url_for('home')) if request.method == 'POST': username = request.form['username'] password = request.form['password'] repassword = request.form['repassword'] email = request.form['email'] user = User.query.filter_by(email=email).first() if user: print('User already exists') return make_response({'message': 'Email already exists!'}) elif password == repassword: hashed_password = bcrypt.generate_password_hash(password).decode( 'utf-8') user = User(password=hashed_password, username=username, type=3, email=email) db.session.add(user) db.session.commit() print('Creating User') flash("Account created successfully.. You can now login") return make_response({'message': 'redirect'}) else: print('Password does not match') return make_response({'message': 'Passwords does not match!'}) else: return render_template('register.html')
def global_variables(request): return { 'hot_nodes': Node.hot(), 'hot_topics': Topic.hot(), 'hot_users': User.hot(), 'latest_topics': Topic.objects.order_by('-id')[:10], 'central_banks': CentralBank.objects.all(), }
def register(request): if request.method == "POST": form = ClassicRegisterForm(request.POST) email_feeds_form = SimpleEmailSubscribeForm(request.POST) if form.is_valid() and email_feeds_form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password1"] email = form.cleaned_data["email"] user_ = User(username=username, email=email) user_.set_password(password) if User.objects.all().count() == 0: user_.is_superuser = True user_.is_staff = True user_.save() UserJoinsAction(user=user_, ip=request.META["REMOTE_ADDR"]).save() if email_feeds_form.cleaned_data["subscribe"] == "n": user_.subscription_settings.enable_notifications = False user_.subscription_settings.save() return login_and_forward(request, user_, None, _("A welcome email has been sent to your email address. ")) else: form = ClassicRegisterForm(initial={"next": "/"}) email_feeds_form = SimpleEmailSubscribeForm() return render_to_response( "auth/complete.html", {"form1": form, "email_feeds_form": email_feeds_form}, context_instance=RequestContext(request), )
def register(request): if request.method == 'POST': form = ClassicRegisterForm(request.POST.copy()) #form = ClassicRegisterForm(request.POST) logging.info(form) if form.is_valid(): logging.error(form.cleaned_data) username = form.cleaned_data['username'] password = form.cleaned_data['password1'] #email = form.cleaned_data['email'] #user_ = User(username=username, email=email) user_ = User(username=username) user_.set_password(password) if User.objects.all().count() == 0: user_.is_superuser = True user_.is_staff = True user_.save() #UserJoinsAction(user=user_, ip=request.META['REMOTE_ADDR']).save() return login_and_forward(request, user_, None, _("A welcome email has been sent to your email address. ")) else: #form = ClassicRegisterForm(initial={'next':'/'}) form = ClassicRegisterForm() return render_to_response('auth/complete.html', { 'form1': form }, context_instance=RequestContext(request))
def authenticate(self, username=None, password=None): try: drupal_user = drupal.Users.objects.using(DRUPAL_DB).get(name=username) except drupal.Users.DoesNotExist: return None if User.objects.filter(username=drupal_user.name): # Only authenticates users that have not being migrated to the django database. return None user = User(username=username) pwd_valid = self.check_password(drupal_user, user, password) if pwd_valid: DrupalAuthBackend.get_user_data(drupal_user, user) if User.objects.all().count() == 0: user.is_superuser = True user.is_staff = True user.save() return user else: return None
def test_invalid_reset_token(self): u1 = User(password='******') u2 = User(password='******') db.session.add(u1) db.session.add(u2) db.session.commit() token = u1.generate_token() self.assertFalse(u2.confirm_reset(token, 'horse')) self.assertTrue(u2.verify_password('dog'))
def register(request): email = request.POST['emailRegister'] if validateEmail(email): user = User(email=email, display_name=email) user.save() raw_password = randint(1000000, 9999999) user.set_password(str(raw_password)) user.save() send_mail('Welcome to Claremont Academia!','You temporary password is '+ str(raw_password) +'.', \ '*****@*****.**',[email],fail_silently=False) return redirect('/login/') else: return render(request, 'loginpage.html', {'invalid_email': True})
def update_forum_user(request): """ Create or Update Forum User model """ try: # Customise User Model # username = request.user.username.split('@')[0] user = User.objects.get(user_ptr_id=request.user.id) user.user_ptr = request.user user.save() except ObjectDoesNotExist: obj = User() obj.user_ptr = request.user obj.email_isvalid = True obj.last_seen = request.user.last_login obj.username = request.user.username if '@' not in request.user.username else request.user.username.split('@')[0] obj.real_name = "%s %s" % (request.user.first_name, request.user.last_name) # obj.is_active = request.user.is_active obj.email = request.user.email obj.profile_image_url = request.session['profile_image'] if 'profile_image' in request.session else '' obj.save()
def register(): form = RegistrationForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8') user = User(email=form.email.data, password=hashed_password) db.session.add(user) db.session.commit() message = 'Good Day! <p> Welcome to Pi Forum!</p>' send_email('Greetings, New User!', '*****@*****.**', [form.email.data], message, message) flash(f'Account created for {form.email.data}!', 'success') return redirect(url_for('login')) return render_template('register.html', title='Register', form=form)
def process_authentication_request(self, request): # Check for the Shibboleth session header. if 'HTTP_SHIB_SESSION_ID' in request.META and request.META['HTTP_SHIB_SESSION_ID']: # Fetch the username and email from Shibboleth headers. utf8_username = request.META['HTTP_SSONAME'].decode('utf-8') # Create an ASCII compatible version of the username, # because OSQA/Django have bugs handling UTF8 strings in usernames. username = unicodedata.normalize('NFKD', utf8_username).encode('ascii', 'ignore') email = request.META['HTTP_SSOCONTACTMAIL'] # Try to load the user from the database, by its email. user = None try: user = User.objects.get(email=email) except: pass if user is None: # The user was not found, so it must be a new user. # Let's create it on the database. user = User(username=username, email=email) user.email_isvalid = True user.set_unusable_password() user.save() UserJoinsAction(user=user, ip=request.META['REMOTE_ADDR']).save() # Return the User object of the authenticated user. return user else: raise InvalidAuthentication("Shibboleth Authentication Failure.")
def process_authentication_request(self, request): logout_request = request.POST.get('logoutRequest', None) if logout_request: if settings.CAS_LOGOUT_REQUESTS_ENABLED: handle_logout_request(request, logout_request) raise InvalidAuthentication('CAS logout request processed') else: raise InvalidAuthentication('CAS logout request ignored, disabled in configuration') ticket = request.GET.get('ticket', None) if not ticket: raise InvalidAuthentication(_('Login failed. CAS ticket is missing.')) service = service_url(request) username, attributes = validate(ticket, service) if not username: raise InvalidAuthentication(_('Login failed. CAS ticket is invalid.')) try: _user = User.objects.get(username=username) self._sync_user_attributes(_user, attributes) except User.DoesNotExist: _user = User(username=username) _user.set_unusable_password() self._sync_user_attributes(_user, attributes) _user.save() UserJoinsAction(user=_user, ip=request.META['REMOTE_ADDR']).save() request.session[CAS_TICKET_SESSION_ATTR] = ticket return _user
def register(request): banned_ips = cache.get(BANNED_IPS_KEY, set()) ip = get_client_ip(request) if ip in banned_ips: logging.warning("Spammer returned ip:%s" % ip) return HttpResponseRedirect("http://www.pudelek.pl/artykul/x/") if request.method == "POST": banned_emails = cache.get(BANNED_EMAILS_KEY, set()) if request.POST["email"] in banned_emails: logging.warning("Spammer returned:%s, ip:%s" % (request.POST["email"], ip)) return HttpResponseRedirect("http://www.pudelek.pl/artykul/x/") form = ClassicRegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password1"] email = form.cleaned_data["email"] # Honeypot checks if request.POST.get("age", None): logging.warning("Age honeypot filled, will not register for email:%s, ip:%s" % (email, ip)) ban(email, ip) return HttpResponseRedirect(reverse("index")) if request.POST.get("birthday", None): logging.warning("Birthday honeypot filled, will not register for email:%s, ip:%s" % (email, ip)) ban(email, ip) return HttpResponseRedirect(reverse("index")) if request.POST.get("website", None): logging.warning("Website honeypot filled, will not register for email:%s, ip:%s" % (email, ip)) ban(email, ip) return HttpResponseRedirect(reverse("index")) user_ = User(username=username, email=email) user_.set_password(password) if User.objects.all().count() == 0: user_.is_superuser = True user_.is_staff = True user_.save() UserJoinsAction(user=user_, ip=request.META["REMOTE_ADDR"]).save() logging.info("New user joined with email:%s from ip:%s" % (email, ip)) return login_and_forward(request, user_, None, _("A welcome email has been sent to your email address. ")) else: form = ClassicRegisterForm(initial={"next": "/"}) return render_to_response( "auth/register.html", {"form1": form, "bigicon_providers": _get_bigicon_providers(request)}, context_instance=RequestContext(request), )
def process_data(self, **data): processed_data = self.create_revision_data(True, **data) if 'added_at' in data: processed_data['added_at'] = data['added_at'] question = Question(author=self.user, **processed_data) question.save() if 'invites' in data: question.invites = data['invites'].strip() for inviter_name in question.invites.split(): try: inviter = User.objects.get(username=inviter_name) except User.DoesNotExist: if isidvalid(inviter_name): inviter = User(username=userid, email=(userid+ u'@synopsys.com'), real_name=userid, email_isvalid=True) inviter.save() else: continue question.whitelist.add(inviter) self.node = question messages.info(REQUEST_HOLDER.request, self.describe(self.user))
def test_invalid_confirmation_token(self): u1 = User(password='******') u2 = User(password='******') db.session.add(u1) db.session.add(u2) db.session.commit() token = u1.generate_token() self.assertFalse(u2.confirm_registration(token))
def register(request): email = request.POST['emailRegister'] if validateEmail(email): user = User(email = email,display_name = email) user.save(); raw_password = randint(1000000,9999999) user.set_password(str(raw_password)) user.save() send_mail('Welcome to Claremont Academia!','You temporary password is '+ str(raw_password) +'.', \ '*****@*****.**',[email],fail_silently=False) return redirect('/login/') else: return render(request,'loginpage.html',{'invalid_email':True})
def process_authentication_request(self, request): username = request.POST["username"].strip() password = request.POST["password"] uid = str(settings.LDAP_USER_MASK) % username # an empty password will cause ldap to try an anonymous bind. This is picked up here if not password: raise InvalidAuthentication( _("Login failed. Please enter valid username and password (both are case-sensitive)") ) ldapo = ldap.initialize(str(settings.LDAP_SERVER)) if settings.LDAP_USE_TLS: ldapo.start_tls_s() ldapo.set_option(ldap.OPT_PROTOCOL_VERSION, 3) try: ldapo.simple_bind_s(str(settings.LDAP_BIND_DN), str(settings.LDAP_BIND_SECRET)) search = ldapo.search_s(str(settings.LDAP_BASE_DN), ldap.SCOPE_SUBTREE, uid) except ldap.LDAPError: # could not bind using credentials specified in ldap config raise InvalidAuthentication(_("Login failed - LDAP bind error. Please contact your system administrator")) ldapo.unbind_s() if not search: # could not find user raise InvalidAuthentication( _("Login failed. Please enter valid username and password (both are case-sensitive)") ) # now try to bind as selected user; should raise exception if bind fails ldapo = ldap.initialize(str(settings.LDAP_SERVER)) if settings.LDAP_USE_TLS: ldapo.start_tls_s() ldapo.set_option(ldap.OPT_PROTOCOL_VERSION, 3) try: ldapo.simple_bind_s(search[0][1][str(settings.LDAP_DN)][0], password) except ldap.LDAPError: # could not bind as user - password is incorrect raise InvalidAuthentication( _("Login failed. Please enter valid username and password (both are case-sensitive)") ) ldapo.unbind_s() try: return User.objects.get(username=username) except User.DoesNotExist: userinfo = search[0][1] _user = User( username=userinfo[str(settings.LDAP_UID)][0], email=userinfo[str(settings.LDAP_MAIL)][0], real_name=userinfo[str(settings.LDAP_NAME)][0], ) _user.email_isvalid = True _user.set_unusable_password() _user.save() UserJoinsAction(user=_user, ip=request.META["REMOTE_ADDR"]).save() return _user
def authenticate(self, username=None, password=None): try: lernanta_user = lernanta.UserProfile.objects.using(LERNANTA_DB).get(username=username) except lernanta.UserProfile.DoesNotExist: return None try: user = User.objects.get(username=lernanta_user.username) user.is_active = lernanta_user.user.is_active user.save() except User.DoesNotExist: user = User(username=username) if not lernanta_user.user.is_active or not lernanta_user.password: return None pwd_valid = self.check_password(lernanta_user, user, password) if pwd_valid: LernantaAuthBackend.get_user_data(lernanta_user, user) if User.objects.all().count() == 0: user.is_superuser = True user.is_staff = True user.save() return user else: return None
def register(): if current_user.is_authenticated: return redirect("/") form = registration_form() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash( form.password.data).decode("utf-8") user = User(username=form.username.data, password=hashed_password) db.session.add(user) db.session.commit() return redirect("/") return render_template("register.html", form=form)
def oauth(request, provider): code = request.GET.get('code') if not code: # 认证返回的params中没有code,肯定出错了 # 重定向到某处,再做处理 raise social_sites = SocialSites(settings.SOCIALOAUTH_SITES) s = social_sites.get_site_object_by_name(provider) # 用code去换取认证的access_token s.get_access_token(code) u = User.from_oauth(s.name, s.uid, s.access_token, s.avatar) login_user(request, u) return redirect('index')
def test_gravatar(self): u = User(email='*****@*****.**', password='******') gravatar = u.gravatar() gravatar_256 = u.gravatar(size=256) gravatar_pg = u.gravatar(rating='pg') gravatar_retro = u.gravatar(default='retro') self.assertTrue(self.app.config['BASE_GRAVATAR_URL'] + '/d4c74594d841139328695756648b6bd6' in gravatar) self.assertTrue('s=256' in gravatar_256) self.assertTrue('r=pg' in gravatar_pg) self.assertTrue('d=retro' in gravatar_retro)
def generate_fake_users(count=100): seed() for i in range(count): user_name = forgery_py.internet.user_name(True)[:32] u = User(email=forgery_py.internet.email_address(), username=user_name, username_normalized=user_name.lower(), password=forgery_py.lorem_ipsum.word(), confirmed=True, name=forgery_py.name.full_name()[:64], homeland=forgery_py.address.city()[:64], about=forgery_py.lorem_ipsum.sentence(), created_at=forgery_py.date.date(True)) db.session.add(u) try: db.session.commit() except IntegrityError: db.session.rollback()
def register_page(): login = request.form.get('login') password = request.form.get('password') password2 = request.form.get('password2') if request.method == 'POST': if not (login or password or password2): flash('Please fill all fields!') elif password != password2: flash('Passwords are not equal!') else: hash_password = generate_password_hash(password) new_user = User(login=login, password=hash_password) db.session.add(new_user) db.session.commit() return redirect(url_for('login_page')) return render_template('register.html')
def register(request): if request.method == "POST": form_values = request.POST.dict() name = form_values['name']#nom names = form_values["names"]#prenom email = form_values['email'] username = form_values['username'] paswrd = form_values['paswrd'] confirm_paswrd = form_values['confirm_paswrd'] error = "Password don't match!" photo="https://img.icons8.com/cotton/64/000000/gender-neutral-user.png" try: myfile = request.FILES['resume'] except KeyError: print("key error") else: print("no key error") myfile = request.FILES['resume'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) print(uploaded_file_url) photo=uploaded_file_url if paswrd == confirm_paswrd: try: user = AuthUser.objects.create_user(username=username,email=email,password=paswrd,first_name=names,last_name=name) # user=User(username,first_name="names",last_name="name",email="email",password="******") except IntegrityError: error = f"Username{username} already exist" else: User(user=user, photo=photo).save() new_login(request,user) return redirect(home) return render(request, 'forum/register.html',{"error" : error} ) else: return render(request, 'forum/register.html') return render(request,'forum/register.html')
def create(self, request): #print(request.data, request.data['username'], request.data.get('username'), request.POST, request.POST.get('username')) serializer = self.serializer_class(data=request.data) if serializer.is_valid(): username = request.data.get('username') email = request.data.get('email') password = request.data.get('password') print(username, email, password) instance = User(username=username, email=email) instance.set_password(password) instance.save() return Response(serializer.validated_data) else: print("validate error") return Response({ 'status': 'Bad request', 'message': 'Account could not be created with received data.' }, status=status.HTTP_400_BAD_REQUEST)
def create_user(request): if request.method == 'POST' and request.POST['access_token'] == djsettings.BZ_QA_TOKEN: assoc_key = request.POST['url'] username = request.POST['name'] real_name = request.POST['name'] email = request.POST['email'] auth_provider = 'openidurl' user_ = User(username=username, email=email, real_name=real_name) user_.set_unusable_password() user_.email_isvalid = True user_.save() UserJoinsAction(user=user_, ip=request.META['REMOTE_ADDR']).save() uassoc = AuthKeyUserAssociation(user=user_, key=assoc_key, provider=auth_provider) uassoc.save() return HttpResponse('OK') else: raise Http404()
def authenticate(self, username=None, password=None): try: drupal_user = drupal.Users.objects.using(DRUPAL_DB).get( name=username) except drupal.Users.DoesNotExist: return None if User.objects.filter(username=drupal_user.name): # Only authenticates users that have not being migrated to the django database. return None user = User(username=username) pwd_valid = self.check_password(drupal_user, user, password) if pwd_valid: DrupalAuthBackend.get_user_data(drupal_user, user) if User.objects.all().count() == 0: user.is_superuser = True user.is_staff = True user.save() return user else: return None
def create_user(request): if request.POST: form = CreateUserForm(request.POST) if form.is_valid(): user_ = User(username=form.cleaned_data['username'], email=form.cleaned_data['email']) user_.set_password(form.cleaned_data['password1']) if not form.cleaned_data.get('validate_email', False): user_.email_isvalid = True user_.save() UserJoinsAction(user=user_).save() request.user.message_set.create(message=_("New user created sucessfully. %s.") % html.hyperlink( user_.get_profile_url(), _("See %s profile") % user_.username, target="_blank")) return HttpResponseRedirect(reverse("admin_tools", kwargs={'name': 'createuser'})) else: form = CreateUserForm() return ('osqaadmin/createuser.html', { 'form': form, })
def create_user(request): if request.POST: form = CreateUserForm(request.POST) if form.is_valid(): user_ = User(username=form.cleaned_data["username"], email=form.cleaned_data["email"]) user_.set_password(form.cleaned_data["password1"]) if not form.cleaned_data.get("validate_email", False): user_.email_isvalid = True user_.save() UserJoinsAction(user=user_).save() request.user.message_set.create( message=_("New user created sucessfully. %s.") % html.hyperlink(user_.get_profile_url(), _("See %s profile") % user_.username, target="_blank") ) return HttpResponseRedirect(reverse("admin_tools", kwargs={"name": "createuser"})) else: form = CreateUserForm() return ("podporaadmin/createuser.html", {"form": form})
def instantiate(request): # if request.META['REMOTE_ADDR'] not in ALLOWED_IPS: # return http.HttpResponseForbidden('Invalid REMOTE_ADDR') if request.method != 'GET': return http.HttpResponseBadRequest('Invalid request method') try: username = request.GET['username'] email = request.GET['email'] except datastructures.MultiValueDictKeyError, e: return http.HttpResponseBadRequest(str(e)) if(User.objects.filter(username=username)): return http.HttpResponseBadRequest('Username already in use') u = User(username=username, email=email) u.save() return http.HttpResponse('Created user #%d, %s <%s>' % (u.id, username, email)) def register(request): # disable registration return http.HttpResponseForbidden() if request.method == 'POST': form = ClassicRegisterForm(request.POST) email_feeds_form = SimpleEmailSubscribeForm(request.POST) if form.is_valid() and email_feeds_form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password1']
def test_password_salts_are_random(self): u = User(password='******') u2 = User(password='******') self.assertTrue(u.password_hash != u2.password_hash)
def external_register(request): if request.method == 'POST' and 'bnewaccount' in request.POST: form1 = SimpleRegistrationForm(request.POST) email_feeds_form = SimpleEmailSubscribeForm(request.POST) if (form1.is_valid() and email_feeds_form.is_valid()): user_ = User(username=form1.cleaned_data['username'], email=form1.cleaned_data['email']) user_.email_isvalid = request.session.get('auth_validated_email', '') == form1.cleaned_data['email'] user_.set_unusable_password() if User.objects.all().count() == 0: user_.is_superuser = True user_.save() if not user_.email_isvalid: send_validation_email(user_) try: assoc_key = request.session['assoc_key'] auth_provider = request.session['auth_provider'] except: request.session['auth_error'] = _("Oops, something went wrong in the middle of this process. Please try again.") return HttpResponseRedirect(request.session.get('on_signin_url', reverse('auth_signin'))) uassoc = AuthKeyUserAssociation(user=user_, key=request.session['assoc_key'], provider=request.session['auth_provider']) uassoc.save() if email_feeds_form.cleaned_data['subscribe'] == 'n': user_.subscription_settings.enable_notifications = False user_.subscription_settings.save() del request.session['assoc_key'] del request.session['auth_provider'] if user_.email_isvalid: return login_and_forward(request, user_) else: return HttpResponseRedirect(reverse('index')) else: provider_class = AUTH_PROVIDERS[request.session['auth_provider']].consumer user_data = provider_class.get_user_data(request.session['assoc_key']) username = user_data.get('username', '') email = user_data.get('email', '') if not email: email = request.session.get('auth_email_request', '') if email: request.session['auth_validated_email'] = email form1 = SimpleRegistrationForm(initial={ 'next': '/', 'username': username, 'email': email, }) email_feeds_form = SimpleEmailSubscribeForm() provider_context = AUTH_PROVIDERS[request.session['auth_provider']].context return render_to_response('auth/complete.html', { 'form1': form1, 'email_feeds_form': email_feeds_form, 'provider':mark_safe(provider_context.human_name), 'login_type':provider_context.id, 'gravatar_faq_url':reverse('faq') + '#gravatar', }, context_instance=RequestContext(request))
def test_no_password_getter(self): u = User(password='******') with self.assertRaises(AttributeError): u.password
def test_password_setter(self): u = User(password='******') self.assertTrue(u.password_hash is not None)
def external_register(request): if request.method == "POST" and "bnewaccount" in request.POST: form1 = SimpleRegistrationForm(request.POST) if form1.is_valid(): user_ = User( username=form1.cleaned_data["username"], email=form1.cleaned_data["email"], real_name=form1.cleaned_data["real_name"], ) user_.email_isvalid = request.session.get("auth_validated_email", "") == form1.cleaned_data["email"] user_.set_unusable_password() if User.objects.all().count() == 0: user_.is_superuser = True user_.is_staff = True user_.save() UserJoinsAction(user=user_, ip=request.META["REMOTE_ADDR"]).save() try: assoc_key = request.session["assoc_key"] auth_provider = request.session["auth_provider"] except: request.session["auth_error"] = _( "Oops, something went wrong in the middle of this process. Please try again. Note that you need to have cookies enabled for the authentication to work." ) logging.error( "Missing session data when trying to complete user registration: %s" % ", ".join(["%s: %s" % (k, v) for k, v in request.META.items()]) ) return HttpResponseRedirect(reverse("auth_signin")) uassoc = AuthKeyUserAssociation(user=user_, key=assoc_key, provider=auth_provider) uassoc.save() del request.session["assoc_key"] del request.session["auth_provider"] return login_and_forward(request, user_, message=_("A welcome email has been sent to your email address. ")) else: auth_provider = request.session.get("auth_provider", None) if not auth_provider: request.session["auth_error"] = _( "Oops, something went wrong in the middle of this process. Please try again." ) logging.error( "Missing session data when trying to complete user registration: %s" % ", ".join(["%s: %s" % (k, v) for k, v in request.META.items()]) ) return HttpResponseRedirect(reverse("auth_signin")) provider_class = AUTH_PROVIDERS[auth_provider].consumer if provider_class.__class__.__name__ == "FacebookAuthConsumer": user_data = provider_class.get_user_data(request.session["access_token"]) else: user_data = provider_class.get_user_data(request.session["assoc_key"]) if not user_data: user_data = request.session.get("auth_consumer_data", {}) username = user_data.get("username", "") email = user_data.get("email", "") real_name = user_data.get("real_name", "") if email: request.session["auth_validated_email"] = email form1 = SimpleRegistrationForm( initial={"next": "/", "username": username, "email": email, "real_name": real_name} ) provider_context = AUTH_PROVIDERS[request.session["auth_provider"]].context return render_to_response( "auth/complete.html", { "form1": form1, "provider": provider_context and mark_safe(provider_context.human_name) or _("unknown"), "login_type": provider_context.id, "gravatar_faq_url": reverse("faq") + "#gravatar", }, context_instance=RequestContext(request), )
def external_register(request): if request.method == 'POST' and 'bnewaccount' in request.POST: form1 = SimpleRegistrationForm(request.POST) if form1.is_valid(): message= u'' try: user_ = User(username=form1.cleaned_data['username'], email=form1.cleaned_data['email'], real_name=form1.cleaned_data.get('real_name', '')) user_.email_isvalid = request.session.get('auth_validated_email', '') == form1.cleaned_data['email'] user_.set_unusable_password() if User.objects.all().count() == 0: user_.is_superuser = True user_.is_staff = True assoc_key = request.session['assoc_key'] auth_provider = request.session['auth_provider'] user_.save() UserJoinsAction(user=user_, ip=request.META['REMOTE_ADDR']).save() if user_.email_isvalid: EmailValidationAction(user=user_, ip=request.META['REMOTE_ADDR']).save() message += _(u"A welcome email has been sent to Your email address.") else: message += _(u"A welcome email has been sent to You.<br />Remember to validate Your email address to be able to fully participate in %s community." % settings.APP_TITLE) uassoc = AuthKeyUserAssociation(user=user_, key=assoc_key, provider=auth_provider) uassoc.save() logging.info(u"User %s joined via %s" % (user_.username, auth_provider)) except: request.session['auth_error'] = _( "Oops, something went wrong in the middle of this process. Please try again. Note that you need to have cookies enabled for the authentication to work." ) logging.exception("Missing session data when trying to complete user registration: %s" % ", ".join( ["%s: %s" % (k, v) for k, v in request.META.items()])) return HttpResponseRedirect(reverse('auth_signin')) _cleanup_after_external_signin(request) return login_and_forward(request, user_, message=message) else: logging.info("Form not validated in external_register %s", str(form1.errors)) else: auth_provider = request.session.get('auth_provider', None) if not auth_provider: request.session['auth_error'] = _( "Oops, something went wrong in the middle of this process. Please try again.") logging.error("Missing session data when trying to complete user registration: %s" % ", ".join( ["%s: %s" % (k, v) for k, v in request.META.items()])) return HttpResponseRedirect(reverse('auth_signin')) provider_class = AUTH_PROVIDERS[auth_provider].consumer if provider_class.__class__.__name__ == 'FacebookAuthConsumer' or provider_class.__class__.__name__ == 'GoogleAuthConsumer': user_data = provider_class.get_user_data(request.session['access_token']) else: user_data = provider_class.get_user_data(request.session['assoc_key']) if not user_data: user_data = request.session.get('auth_consumer_data', {}) username = user_data.get('username', '') email = user_data.get('email', '') real_name = user_data.get('real_name', '') if email: try: old_user = User.objects.get(email=email) message=_("Welcome back %s! You can now login via %s.") % (old_user.username, auth_provider.capitalize()) if not old_user.email_isvalid: message += _("<br />Since this email was not previously validated we cleared your password.<br />Set new one to be able to login with it") old_user.set_unusable_password() old_user.email_isvalid = True old_user.save() logging.warning("Clearing password for user %s with unvalidated email after signing with %s" % (old_user.username, auth_provider)) EmailValidationAction(user=old_user, ip=request.META['REMOTE_ADDR']).save() uassoc = AuthKeyUserAssociation(user=old_user, key=request.session['assoc_key'], provider=auth_provider) uassoc.save() logging.info(u"User %s added %s sign in provider" % (old_user.username, auth_provider)) _cleanup_after_external_signin(request) return login_and_forward(request, old_user, message=mark_safe(message)) except: pass request.session['auth_validated_email'] = email form1 = SimpleRegistrationForm(initial={ 'next': '/', 'username': username, 'email': email, 'real_name': real_name, }) provider_context = AUTH_PROVIDERS[request.session['auth_provider']].context return render_to_response('auth/complete.html', { 'form1': form1, 'provider':provider_context and mark_safe(provider_context.human_name) or _('unknown'), 'login_type':provider_context.id, 'gravatar_faq_url':reverse('faq') + '#gravatar', }, context_instance=RequestContext(request))
def test_password_verification(self): u = User(password='******') self.assertTrue(u.verify_password('cat')) self.assertFalse(u.verify_password('dog'))
def external_register(request): if request.method == 'POST' and 'bnewaccount' in request.POST: form1 = SimpleRegistrationForm(request.POST) if form1.is_valid(): user_ = User(username=form1.cleaned_data['username'], email=form1.cleaned_data['email']) user_.email_isvalid = request.session.get('auth_validated_email', '') == form1.cleaned_data['email'] user_.set_unusable_password() if User.objects.all().count() == 0: user_.is_superuser = True user_.is_staff = True user_.save() try: assoc_key = request.session['assoc_key'] auth_provider = request.session['auth_provider'] if auth_provider == "weibo": token = ast.literal_eval(assoc_key) assoc_key = token["access_token"] weibo_uid = token["uid"] weibo_remind_in = token["remind_in"] weibo_expires_at = token["expires_at"] except: request.session['auth_error'] = _( "Oops, something went wrong in the middle of this process. Please try again. Note that you need to have cookies enabled for the authentication to work." ) logging.error("Missing session data when trying to complete user registration: %s" % ", ".join( ["%s: %s" % (k, v) for k, v in request.META.items()])) return HttpResponseRedirect(reverse('auth_signin')) if auth_provider == "weibo": uassoc = AuthKeyUserAssociation(user=user_, key=assoc_key, provider=auth_provider,weibo_uid=weibo_uid,weibo_remind_in=weibo_remind_in,weibo_expires_at=weibo_expires_at) else: uassoc = AuthKeyUserAssociation(user=user_, key=assoc_key, provider=auth_provider) uassoc.save() UserJoinsAction(user=user_, ip=request.META['REMOTE_ADDR']).save() del request.session['assoc_key'] del request.session['auth_provider'] return login_and_forward(request, user_, message=_("A welcome email has been sent to your email address. ")) else: auth_provider = request.session.get('auth_provider', None) if not auth_provider: request.session['auth_error'] = _( "Oops, something went wrong in the middle of this process. Please try again.") logging.error("Missing session data when trying to complete user registration: %s" % ", ".join( ["%s: %s" % (k, v) for k, v in request.META.items()])) return HttpResponseRedirect(reverse('auth_signin')) if auth_provider == 'weibo': assoc_key = request.session['assoc_key'] token = ast.literal_eval(assoc_key) client = weibo_client(str(settings.WEIBO_API_KEY), str(settings.WEIBO_API_SECRET),urlparse.urljoin(settings.APP_URL,'/weibo/signin/check'),token) user=client.get('users/show', uid=token["uid"]) username = user["name"] email = None provider_context = None else: # weibo user register provider_class = AUTH_PROVIDERS[auth_provider].consumer user_data = provider_class.get_user_data(request.session['assoc_key']) if not user_data: user_data = request.session.get('auth_consumer_data', {}) username = user_data.get('username', '') email = user_data.get('email', '') provider_context = AUTH_PROVIDERS[request.session['auth_provider']].context if email: request.session['auth_validated_email'] = email form1 = SimpleRegistrationForm(initial={ 'next': '/', 'username': username, 'email': email, }) return render_to_response('auth/complete.html', { 'form1': form1, #'provider':provider_context and mark_safe(provider_context.human_name) or _('unknown'), #'login_type':provider_context.id, 'gravatar_faq_url':reverse('faq') + '#gravatar', }, context_instance=RequestContext(request))
def process_authentication_request(self, request): username = request.POST['username'].strip() password = request.POST['password'] uid = str(settings.LDAP_USER_MASK) % username #an empty password will cause ldap to try an anonymous bind. This is picked up here if not password: raise InvalidAuthentication( _('Login failed. Please enter valid username and password (both are case-sensitive)' )) ldapo = ldap.initialize(str(settings.LDAP_SERVER)) if (settings.LDAP_USE_TLS): ldapo.start_tls_s() ldapo.set_option(ldap.OPT_PROTOCOL_VERSION, 3) try: ldapo.simple_bind_s(str(settings.LDAP_BIND_DN), str(settings.LDAP_BIND_SECRET)) search = ldapo.search_s(str(settings.LDAP_BASE_DN), ldap.SCOPE_SUBTREE, uid) except ldap.LDAPError: #could not bind using credentials specified in ldap config raise InvalidAuthentication( _('Login failed - LDAP bind error. Please contact your system administrator' )) ldapo.unbind_s() if not search: #could not find user raise InvalidAuthentication( _('Login failed. Please enter valid username and password (both are case-sensitive)' )) #now try to bind as selected user; should raise exception if bind fails ldapo = ldap.initialize(str(settings.LDAP_SERVER)) if (settings.LDAP_USE_TLS): ldapo.start_tls_s() ldapo.set_option(ldap.OPT_PROTOCOL_VERSION, 3) try: # F.CRESPEL: use search[0][0] as the DN, so that it works consistently across OpenLDAP/ActiveDirectory ###ldapo.simple_bind_s(search[0][1][str(settings.LDAP_DN)][0],password) ldapo.simple_bind_s(search[0][0], password) except ldap.LDAPError: #could not bind as user - password is incorrect raise InvalidAuthentication( _('Login failed. Please enter valid username and password (both are case-sensitive)' )) ldapo.unbind_s() try: return User.objects.get(username=username) except User.DoesNotExist: userinfo = search[0][1] _user = User(username=userinfo[str(settings.LDAP_UID)][0], email=userinfo[str(settings.LDAP_MAIL)][0], real_name=userinfo[str(settings.LDAP_NAME)][0]) _user.email_isvalid = True _user.set_unusable_password() _user.save() UserJoinsAction(user=_user, ip=request.META['REMOTE_ADDR']).save() return _user
def external_register(request): if request.method == 'POST' and 'bnewaccount' in request.POST: form1 = SimpleRegistrationForm(request.POST) if form1.is_valid(): user_ = User(username=form1.cleaned_data['username'], email=form1.cleaned_data['email']) user_.email_isvalid = request.session.get('auth_validated_email', '') == form1.cleaned_data['email'] user_.set_unusable_password() if User.objects.all().count() == 0: user_.is_superuser = True user_.is_staff = True user_.save() UserJoinsAction(user=user_, ip=request.META['REMOTE_ADDR']).save() try: assoc_key = request.session['assoc_key'] auth_provider = request.session['auth_provider'] except: request.session['auth_error'] = _( "Oops, something went wrong in the middle of this process. Please try again. Note that you need to have cookies enabled for the authentication to work." ) logging.error("Missing session data when trying to complete user registration: %s" % ", ".join( ["%s: %s" % (k, v) for k, v in request.META.items()])) return HttpResponseRedirect(reverse('auth_signin')) uassoc = AuthKeyUserAssociation(user=user_, key=assoc_key, provider=auth_provider) uassoc.save() del request.session['assoc_key'] del request.session['auth_provider'] return login_and_forward(request, user_, message=_("A welcome email has been sent to your email address. ")) else: auth_provider = request.session.get('auth_provider', None) if not auth_provider: request.session['auth_error'] = _( "Oops, something went wrong in the middle of this process. Please try again.") logging.error("Missing session data when trying to complete user registration: %s" % ", ".join( ["%s: %s" % (k, v) for k, v in request.META.items()])) return HttpResponseRedirect(reverse('auth_signin')) provider_class = AUTH_PROVIDERS[auth_provider].consumer user_data = provider_class.get_user_data(request.session['assoc_key']) if not user_data: user_data = request.session.get('auth_consumer_data', {}) username = user_data.get('username', '') email = user_data.get('email', '') if email: request.session['auth_validated_email'] = email form1 = SimpleRegistrationForm(initial={ 'next': '/', 'username': username, 'email': email, }) provider_context = AUTH_PROVIDERS[request.session['auth_provider']].context return render_to_response('auth/complete.html', { 'form1': form1, 'provider':provider_context and mark_safe(provider_context.human_name) or _('unknown'), 'login_type':provider_context.id, 'gravatar_faq_url':reverse('faq') + '#gravatar', }, context_instance=RequestContext(request))
def test_valid_confirmation_token(self): u = User(password='******') db.session.add(u) db.session.commit() token = u.generate_token() self.assertTrue(u.confirm_registration(token))
def external_register(request): if request.method == 'POST' and 'bnewaccount' in request.POST: form1 = SimpleRegistrationForm(request.POST) if form1.is_valid(): user_ = User(username=form1.cleaned_data['username'], email=form1.cleaned_data['email']) user_.email_isvalid = request.session.get('auth_validated_email', '') == form1.cleaned_data['email'] user_.set_unusable_password() if User.objects.all().count() == 0: user_.is_superuser = True user_.is_staff = True user_.save() UserJoinsAction(user=user_, ip=request.META['REMOTE_ADDR']).save() try: assoc_key = request.session['assoc_key'] auth_provider = request.session['auth_provider'] except: request.session['auth_error'] = _( "Oops, something went wrong in the middle of this process. Please try again. Note that you need to have cookies enabled for the authentication to work." ) logging.error("Missing session data when trying to complete user registration: %s" % ", ".join( ["%s: %s" % (k, v) for k, v in request.META.items()])) return HttpResponseRedirect(reverse('auth_signin')) uassoc = AuthKeyUserAssociation(user=user_, key=assoc_key, provider=auth_provider) uassoc.save() del request.session['assoc_key'] del request.session['auth_provider'] return login_and_forward(request, user_, message=_("A welcome email has been sent to your email address. ")) else: auth_provider = request.session.get('auth_provider', None) if not auth_provider: request.session['auth_error'] = _( "Oops, something went wrong in the middle of this process. Please try again.") logging.error("Missing session data when trying to complete user registration: %s" % ", ".join( ["%s: %s" % (k, v) for k, v in request.META.items()])) return HttpResponseRedirect(reverse('auth_signin')) provider_class = AUTH_PROVIDERS[auth_provider].consumer # Hack: Facebook auth expects an access token, not the assoc_key. identifier = request.session['assoc_key'] if auth_provider == 'facebook': identifier = request.session['access_token'] user_data = provider_class.get_user_data(identifier) if not user_data: user_data = request.session.get('auth_consumer_data', {}) username = user_data.get('username', '') email = user_data.get('email', '') if email: request.session['auth_validated_email'] = email form1 = SimpleRegistrationForm(initial={ 'next': '/', 'username': username, 'email': email, }) provider_context = AUTH_PROVIDERS[request.session['auth_provider']].context return render_to_response('auth/complete.html', { 'form1': form1, 'provider':provider_context and mark_safe(provider_context.human_name) or _('unknown'), 'login_type':provider_context.id, 'gravatar_faq_url':reverse('faq') + '#gravatar', }, context_instance=RequestContext(request))
def import_users(self, users): pkey_map = {} doc = dom.parse(users) rows = doc.getElementsByTagName('row') unknown_count = 0 added_names = [] for row in rows: values = self.row_to_dic(row) username = values.get('displayname', values.get('realname', values.get('email', None))) if username is None: unknown_count += 1 username = '******' % unknown_count if username in added_names: cnt = 1 new_username = "******" % (username, cnt) while new_username in added_names: cnt += 1 new_username = "******" % (username, cnt) username = new_username added_names.append(username) user = User(username=username, email=values.get('email', '')) user.reputation = values['reputation'] user.last_seen = self.from_sx_time(values['lastaccessdate']) user.real_name = values.get('realname', '') user.about = values.get('aboutme', '') user.website = values.get('websiteurl', '') user.date_of_birth = self.from_sx_time(values.get('birthday', None)) user.location = values.get('location', '') user.is_active = True user.email_isvalid = True if int(values['usertypeid']) == 5: user.is_superuser = True if int(values['usertypeid']) == 5: user.is_staff = True user.save() pkey_map[values['id']] = user return users