def testAccount(self): Doc.objects(name=DOC_NAME)[0].delete( ) #strange bug happens when full collection from db is deleted :| logger.debug('Start TestUI::testAccount.') USER_NAME = 'testLogin' driver = self.driver driver.get(self.base_url) time.sleep(1) driver.find_element_by_css_selector("i.fa.fa-sign-in").click() time.sleep(1) driver.find_element_by_id("id_username").clear() driver.find_element_by_id("id_username").send_keys(USER_NAME) driver.find_element_by_id("id_password").clear() driver.find_element_by_id("id_password").send_keys(USER_NAME) driver.find_element_by_css_selector("input[type=\"submit\"]").click() time.sleep(1) self.assertEqual( "Your username and password didn't match. Please try again.", driver.find_element_by_css_selector("p").text) User.create_user(USER_NAME, USER_NAME) time.sleep(1) driver.get(self.base_url) time.sleep(1) driver.find_element_by_css_selector("i.fa.fa-sign-in").click() time.sleep(1) driver.find_element_by_id("id_username").clear() driver.find_element_by_id("id_username").send_keys(USER_NAME) driver.find_element_by_id("id_password").clear() driver.find_element_by_id("id_password").send_keys(USER_NAME) driver.find_element_by_css_selector("input[type=\"submit\"]").click() time.sleep(1) self.assertEqual("Welcome, " + USER_NAME + ".", driver.find_element_by_css_selector("p").text) PRIVATE_DOC_NAME = "prywatny" driver.find_element_by_class_name("has-menu").click() driver.find_element_by_id("newDocumentMenu").click() time.sleep(1) driver.find_element_by_id("documentNameAtStart").clear() driver.find_element_by_id("documentNameAtStart").send_keys( PRIVATE_DOC_NAME) driver.find_element_by_id("privateFlagAtStart").click() driver.find_element_by_id("saveDocumentButtonAtStart").click() time.sleep(10) logger.debug('Critical point of TestUI::testAccount.') doc = Doc.objects(name=PRIVATE_DOC_NAME)[0] self.assertEqual(doc.name, PRIVATE_DOC_NAME) self.assertTrue(doc.priv) driver.get(self.base_url) time.sleep(1) driver.find_element_by_class_name("has-menu").click() driver.find_element_by_id("documentListButton").click() time.sleep(1) self.assertEqual(PRIVATE_DOC_NAME, driver.find_element_by_css_selector("td").text) driver.find_element_by_id('accounts').click() driver.find_element_by_id("logout").click() time.sleep(1) with self.assertRaises(NoSuchElementException): driver.find_element_by_css_selector("td") logger.debug('End TestUI::testAccount.')
def authenticate(self, username=None, password=None): payload = {'username': username, 'password': password} url = '%s/auth/login/' % (settings.API_BASE_URL,) r = requests.post(url, data=json.dumps(payload)) if r.status_code == requests.codes.ok: token = r.headers.get('x-auth-token') if not token: return None try: user = User.objects.get(username=username) user.password = token user.save() except User.DoesNotExist: # Create a new user. Note that we can set password # to anything, because it won't be checked; the password # from settings.py will. user = User(username=username, password=token) user.is_staff = True user.is_superuser = True user.save() return user elif r.status_code >= requests.codes.internal_server_error: raise Exception('Server error. ' + str(r.status_code)) return None
def register(request): # errors = [] # if(request.POST.get('password','1') != request.POST.get('confirm_password','1')): # errors.append('wrong_password') # if(request.POST.get('username', "field is empty") == "" or request.POST.get('email', "field is empty") == "" or request.POST.get('password',"field is empty") == ""): # errors.append('empty_field') # if(len(errors) != 0): # return render_to_response('profile/register.html', {'errors': errors}, RequestContext(request)) # else: if request.user.is_authenticated(): my_user = MyUser.objects.get(user=User.objects.get(id=request.user.id)) return render_to_response('profile/profile.html', {'my_user': my_user}, RequestContext(request)) users_from_database = User.objects.all() if request.POST: User.create_user(username=request.POST['username'], email=request.POST['email'], password=request.POST['password']) user = authenticate(username=request.POST['username'], password=request.POST['password']) my_user = MyUser(point=0.0,comment_count=0,disease_added_count=0,article_added_count=0,discussion_added_count=0,forum_present_count=0) my_user.user = user my_user.save() login(request, user) return render_to_response('profile/account.html',{'users': users_from_database}, RequestContext(request)) else: return render_to_response('profile/register.html',{'users': users_from_database}, RequestContext(request))
def index(request): firstname = ""; lastname = ""; username = ""; password = ""; email = ""; if request.method == 'GET': return render(request, 'myapp/signup.html', {'rangerDay':range(1,32),'rangerYear':range(2014,1905,-1),}) elif request.method == 'POST': firstname = request.POST['txtFirstName'] lastname = request.POST['txtLastName'] username = request.POST['txtUserName'] password = request.POST['txtPassWord'] email= request.POST['txtEmail'] try: user = User() user.username = username user.first_name = firstname user.last_name = lastname user.email = email user.set_password(password); user.save() _profile = UserProfile() _profile.user_id = user _profile.save() user.backend = 'mongoengine.django.auth.MongoEngineBackend' logout(request) login(request, user) return HttpResponseRedirect('/mainscreen') except mongoengine.errors.NotUniqueError as e: return getSignupError(request,'Đã tồn tại trong hệ thống',firstname,lastname,username,password,email)
def patientinfo(request): message = "" if request.method == 'POST': if request.POST['requestType'] == 'newPatient': firstName = request.POST['firstName'] lastName = request.POST['lastName'] birthDate = request.POST['birthDate'] if(helper.validate(birthDate)): username = firstName + lastName userNum = len(User.objects(__raw__={'username':{'$regex': '^' + username, '$options' : 'i'}})) user = User.create_user(username + str(userNum), 'password') user.first_name = firstName user.last_name = lastName user.save() ion_user = IonUser(user=user, group='patient', birthdate=birthDate) ion_user.save() newPatient = patient(firstName=firstName, lastName=lastName, activeMeds = [], user=ion_user) newPatient.save() else: message = "Invalid birth date format. (should be mm-dd-yyyy)" if request.POST['requestType'] == 'deletePatient': id = request.POST['id'] patient.objects(id=id)[0].delete() # don't know if we actually want to give people the ability to delete medical records... return render_to_response('patientinfo.html', {'Patients': patient.objects, 'message': message}, context_instance=RequestContext(request))
def register(req): if req.method == 'GET': return render(req, 'user/register.html') elif req.method == 'POST': form = req.POST User.create_user(username=form['username'], password=form['password']) return redirect('index')
def setUp(self): if PY3: raise SkipTest('django does not have Python 3 support') if not DJ15: raise SkipTest('mongo_auth requires Django 1.5') connect(db='mongoenginetest') User.drop_collection() super(MongoAuthTest, self).setUp()
def setUp(self): User.drop_collection() self.display = Display(visible=0, size=(800, 600)) self.display.start() self.driver = webdriver.Firefox() self.driver.implicitly_wait(30) self.base_url = "http://localhost:8000" self.verificationErrors = [] self.accept_next_alert = True
def _fixture_setup(self): c=Category(name='Musica') c.save() c=Category(name='Restauracion') c.save() user=User.create_user('john','john') request = HttpRequest() user=User.objects(username='******') self.client.login(username='******',password='******')
def register_page(request): if request.method=='POST': form = RegistrationForm(request.POST) if form.is_valid(): User.create_user(username=form.cleaned_data['username'],password=form.cleaned_data['password1'],email=form.cleaned_data['email']) return HttpResponseRedirect("/register/success") else: form = RegistrationForm() variables = RequestContext(request, {'form': form}) return render_to_response('registration/register.html',variables)
def create_user(user_name, password, email): user = User() try: # print user_name, password, email user.create_user(user_name, password, email) print "User Created!" new_user = User.objects.get(username=user_name) print "User Access Key", new_user.id except Exception, e: print "Error", e
def register(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] User_save = User(username=username, password=password) User_save.set_password(password) User_save.save() return render(request,'index.html') else: return render(request,'register.html')
def create_user(user_name, password, email): user = User() try: # print user_name, password, email user.create_user(user_name, password, email) print "User Created!" new_user = User.objects.get(username=user_name) print "User Access Key", new_user.id except Exception,e: print "Error", e
def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): User.create_user(form.cleaned_data['username'],form.cleaned_data['password1']) messages.success(request, form.cleaned_data['username'] + ' you have been successfully registered') return HttpResponseRedirect("/") else: form = RegistrationForm() return render(request, "eventslist/register.html", { 'form': form, })
def test_should_create_default_superuser(self): FakeCommand().handle() self.assertEqual(1, User.objects().count()) user = User.objects().first() user_profile = UserProfile.objects().first() self.assertEqual('admin', user.username) self.assertTrue(check_password('password', user.password)) self.assertNotEqual('password', user.password) self.assertEqual('*****@*****.**', user_profile.email) self.assertEqual(self.kampala, user_profile.location) self.assertEqual('N/A', user_profile.phone) self.assertEqual('Admin', user_profile.name) self.assertEqual('Administrator', user_profile.user.group.name)
def signup(request): if request.method == 'POST': name = request.POST.get('name','') pw = request.POST.get('password','') email = request.POST.get('email','') if not verifyCaptcha(request.POST.get('g-recaptcha-response','')): messages.error(request, "Captcha could not be validated") return redirect('website:index') #check if either is only whitespace if isNoneOrEmptyOrBlankString(name) or isNoneOrEmptyOrBlankString(pw) or isNoneOrEmptyOrBlankString(email): return HttpResponseBadRequest('username and/or password is empty') if len(User.objects(username=name)) != 0: messages.error(request, "Username" + name + "already taken") return redirect('website:index') if len(User.objects(email=email)) != 0: messages.error(request, "Email" + email + "already taken") return redirect('website:index') maxLength = len("IraklisDimitriadis") #this should be a good maxLength if len(name) > maxLength: messages.error(request, "Your name is too long. Use less than "+maxLength+" letters.") return redirect('website:index') user = User.create_user(name,pw,email) user.save() UserExtension(user=user,karma=0).save() #log user in after registrartion user = authenticate(username=name,password=pw) if user is not None: if user.is_active: login(request, user) messages.success(request, 'Your account was created. Click OK to begin using Lemur.') return redirect('website:catalogue') elif request.method == 'GET': return redirect('website:index') messages.error(request, "The server let's you know, that something unexpected happened.") return redirect('website:index')
def setup(request, template='socialregistration/setup.html', form_class=UserForm, extra_context=dict()): """ Setup view to create a username & set email address after authentication """ try: social_user = request.session['socialregistration_user'] social_profile = request.session['socialregistration_profile'] except KeyError: return render_to_response( template, dict(error=True), context_instance=RequestContext(request)) if not GENERATE_USERNAME: # User can pick own username if not request.method == "POST": form = form_class(social_user, social_profile) else: form = form_class(social_user, social_profile, request.POST) if form.is_valid(): form.save(request=request) user = form.profile.authenticate() login(request, user) del request.session['socialregistration_user'] del request.session['socialregistration_profile'] return HttpResponseRedirect(_get_next(request)) extra_context.update(dict(form=form)) return render_to_response(template, extra_context, context_instance=RequestContext(request)) else: # Generate user and profile #social_user.username = str(uuid.uuid4())[:30] #social_user.save() #social_profile.user = social_user #social_profile.save() # Authenticate and login #user = social_profile.authenticate() User.create_user(user_data['username'], user_data['password'], user_data['email']) login(request, user) # Clear & Redirect del request.session['socialregistration_user'] del request.session['socialregistration_profile'] return HttpResponseRedirect(_get_next(request))
def __init__(self, bootstrap=False): self.db = settings._MONGODB if bootstrap: # load bootstrap data self.db.user.remove() User.create_user(username='******', email='*****@*****.**', password='******') self.db.menus.remove() self.db.menus.insert(menus) self.db.items.remove() self.db.items.insert(items) self.db.clients.remove() self.db.clients.insert(clients) self.db.orders.remove() self.db.django_session.remove()
def test_should_handle_existing_profile(self): UserProfile(phone='N/A', name='Admin', location=self.kampala, email='*****@*****.**').save() FakeCommand().handle() self.assertEqual(1, User.objects().count()) user = User.objects().first() user_profile = UserProfile.objects().first() self.assertEqual('admin', user.username) self.assertTrue(check_password('password', user.password)) self.assertNotEqual('password', user.password) self.assertEqual('*****@*****.**', user_profile.email) self.assertEqual(self.kampala, user_profile.location) self.assertEqual('N/A', user_profile.phone) self.assertEqual('Admin', user_profile.name) self.assertEqual('Administrator', user_profile.user.group.name)
def test_should_create_super_user_from_args(self): FakeCommand().handle('new_admin', 'new_password', '*****@*****.**', 'NewAdmin', 'Kampala', '1234567890') self.assertEqual(1, User.objects().count()) user = User.objects().first() user_profile = UserProfile.objects().first() self.assertEqual('new_admin', user.username) self.assertTrue(check_password('new_password', user.password)) self.assertNotEqual('new_password', user.password) self.assertEqual('*****@*****.**', user_profile.email) self.assertEqual(self.kampala, user_profile.location) self.assertEqual('1234567890', user_profile.phone) self.assertEqual('NewAdmin', user_profile.name) self.assertEqual('Administrator', user_profile.user.group.name)
def hybrid_authentication(username=None,password=None): try: if email_re.search(username): user = User.objects(email=username).first() else: user = User.objects(username=username).first() if len(user) != 0: if password and user.check_password(password): return user else: return None else: return None except: return None
def index(request): firstname = ""; lastname = ""; username = ""; password = ""; email = ""; if request.method == 'GET': return render(request, 'myapp/signup.html', {'rangerDay':range(1,32),'rangerYear':range(2014,1905,-1),}) elif request.method == 'POST': try: #parameter firstname = request.POST['txtFirstName'] lastname = request.POST['txtLastName'] username = request.POST['txtUserName'] password = request.POST['txtPassWord'] email= request.POST['txtEmail'] if str(firstname).strip() == "": return getSignupError(request,'First name can not be empty!',firstname,lastname,username,password,email) elif str(lastname).strip() == "": return getSignupError(request,'Last name can not be empty!',firstname,lastname,username,password,email) elif str(username).strip() == "": return getSignupError(request,'User name can not be empty!',firstname,lastname,username,password,email) elif str(password).strip() == "": return getSignupError(request,'Pass word can not be empty!',firstname,lastname,username,password,email) elif str(email).strip() == "": return getSignupError(request,'Email can not be empty!',firstname,lastname,username,email) #insert new user user = User() user.username = username user.first_name = firstname user.last_name = lastname user.email = email user.set_password(password); user.save() user.backend = 'mongoengine.django.auth.MongoEngineBackend' logout(request) login(request, user) #create new profile _profile = UserProfile() _profile.user_id = request.user _profile.save() return HttpResponseRedirect('/home') except mongoengine.errors.ValidationError as ex: return getSignupError(request,str(ex.errors['email']),firstname,lastname,username,password,email) except mongoengine.errors.NotUniqueError as e: return getSignupError(request,'User has already exists!',firstname,lastname,username,password,email) except Exception as e: return getSignupError(request,str(e),firstname,lastname,username,password,email)
def employee_department(request, employee_id): # @todo: respect DRY with employee method employee = Employee.objects(id=employee_id).first() if not employee: user = User.objects(id=employee_id).first() if user: employee = Employee.from_user(user) else: raise Http404 if request.method == 'POST' and 'department' in request.POST: department_id = request.POST['department'] if department_id: department = Department.objects(id=department_id).first() else: department = None employee.department = department employee.save() success(request, _('Department for employee changed')) return redirect('picket-admin-employees') else: return HttpResponseBadRequest()
def index(request): lisUserProfile = UserProfile.objects # print('begin') # for user in lisUserProfile: # print(user.images) # print('finish') c = {'lisUserProfile':lisUserProfile,} if request.method == 'GET': return render(request, 'myapp/people-directory.html', c) elif request.method == 'POST': try: keyword = request.POST['keyword'] users = User.objects(first_name__icontains=keyword)#search data lisUserProfile = UserProfile.objects(user_id__in=users) c = {'lisUserProfile':lisUserProfile,'keyword':keyword} # profile = Profile() # profile.name = 'Nusja Nawancali' # profile.image_url='images/user3.png' # profile.address='Phuket, Thailand' # profile.location='Product Manager' # profile.company='SomeCompany, Inc.' # profile.save() #get data from mongodb c.update(csrf(request)) c.update(context_processors.user(request)) return render_to_response("myapp/people-directory.html", c) except Exception: c.update(csrf(request)) c.update(context_processors.user(request)) return render_to_response("myapp/people-directory.html", c) return render(request, 'myapp/test.html', c)
def test_search_form_return_correct_event(self): user=User.create_user('john','john') request = HttpRequest() user=User.objects(username='******') self.client.login(username='******',password='******') response = self.client.post('/eventslist/addevent',data={'title': 'Concierto','description': 'Es un concierto','category': 'Musica','lat':'49.8','lng':'4.7'}) self.assertEqual(Event.objects(title='Concierto').count(),1) self.assertEqual(str(Event.objects(title='Concierto')),'[<Event: Concierto-49.84.7-Es un concierto-Musica>]') response = self.client.post('/',data={'title': 'Concierto','category': 'Musica','lat':'49.8','lng':'4.7','distance':'4'}) self.assertContains(response,'<td>Concierto</td>') self.assertContains(response,'<td>Es un concierto</td>') self.assertContains(response,'<td>Musica</td>') User.objects(username='******').delete()
def handle(self, **kwargs): username = self._get_string('Username') email = self._get_string('Email', required=False) password = self._get_string('Password', getpass.getpass) first_name = self._get_string('First name') last_name = self._get_string('Last name') user = User(username=username) user.first_name = first_name user.last_name = last_name user.email = email user.set_password(password) user.is_staff = True user.save() print 'User "%s %s" successfully added' % (first_name, last_name)
def user_register(request): if request.method == 'POST': uemail = request.POST.get('email', None) upassword = request.POST.get('password', None) if (not uemail) or (not upassword): return { 'error': 'All fields are required', 'email': uemail } try: user = User.create_user(uemail, upassword, request.POST['email']) user.backend = 'mongoengine.django.auth.MongoEngineBackend' login(request, user) request.session.set_expiry(60 * 60 * 10) # 10 hour timeout return redirect('project_list') except NotUniqueError: return { 'error': 'User with this email already exist', 'email': uemail } except ValidationError: return { 'error': 'Incorrect email', 'email': uemail } else: return {}
def get_or_create(cls, loginza_response): identity_qs = cls.objects.filter(identity=loginza_response['identity']) if identity_qs.count(): identity = identity_qs.get() else: user_qs = User.objects.filter( username=loginza_response['identity']) if user_qs.count(): user = user_qs.get() else: user = User.create_user( username=loginza_response['identity'], password=UNUSABLE_PASSWORD, email=loginza_response.get('email')) identity = Identity(identity=loginza_response['identity'], user=user) del loginza_response['identity'] identity.info = loginza_response identity.save() return identity
def clean_email(self): email = self.cleaned_data['email'] user = User.objects(email=email) if len(user) == 0: return email else: raise forms.ValidationError(self.error_messages['email_exists'])
def create(request): user = User.create_user('dispenser', 'password', '*****@*****.**') #user.groups = ['patient'] user.save() ion_user = IonUser(user=user, group='dispenser', birthdate=datetime.datetime.now()) ion_user.save() return HttpResponse("Account create successful")
def index(request): lisUserProfile = {} # print('begin') # for user in lisUserProfile: # print(user.company) # print('finish') c = {'lisUserProfile':lisUserProfile,} if request.method == 'GET': return render(request, 'myapp/search-mentor.html', c) elif request.method == 'POST': try: keyword = request.POST['search'] users = User.objects(Q(first_name__icontains=keyword) | Q(last_name__icontains=keyword)) #search data # lisUserProfile = UserProfile.objects(user_id__in=users,is_mentor=True) lisUserProfile = UserProfile.objects(user_id__in=users) listAllCurriculumn = Curriculumn.objects() listCurriculumn =Curriculumn.objects(name__icontains=keyword) c = {'lisUserProfile':lisUserProfile,'listCurriculumn':listCurriculumn,'listAllCurriculumn':listAllCurriculumn,'search':keyword} #get data from mongodb c.update(csrf(request)) c.update(context_processors.user(request)) return render_to_response("myapp/search-mentor.html", c) except Exception: c.update(csrf(request)) c.update(context_processors.user(request)) return render_to_response("myapp/search-mentor.html", c) return render(request, 'myapp/search-mentor.html', c)
def user(request): """A context processor that adds the user to template context""" profile = {} is_mentor = False if (request.user.is_authenticated()==True) and(request.user is not None): try: user_images = request.session['user_images'] except Exception as e: user_images = "" if (request.user.is_authenticated()==True) and(request.user is not None): try: isMentor = Mentor.objects.get(user=request.user) if len(isMentor): is_mentor = True except Exception as e: is_mentor = False if (request.user.is_authenticated()==True) and(request.user is not None): loggedUser = User.objects(username=str(request.user)) return { 'user': request.user, 'profile':profile, 'is_mentor':is_mentor, 'loggedUser':loggedUser[0], 'user_images':user_images } else: return { 'user': request.user, 'profile':profile, 'is_mentor':is_mentor, 'loggedUser':[], 'user_images':"" }
def create(request): form = NewAccountForm(request.POST or None) if form.is_valid(): # also attach the contact information to the anonymous request.user new_user.first_name = request.POST['first_name'] new_user.last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password = request.POST['password2'] new_user = User.create_user(username=username, email=email, password=password) new_user.save() # create the account instance new_account = Account() new_account.company = request.POST['company_name'] new_account.admin = new_user new_account.save() messages.success(request, new_account) # now authenticate and login user auth_user = authenticate(username=username, password=password) login(request=request, user=auth_user) messages.success(request, 'Successfully logged in as %s' % \ auth_user.username) return HttpResponseRedirect('/welcome/') data = {'title': 'Kolabria - Create a new Account ', 'form': form, } return render_to_response('account/create.html', data, context_instance=RequestContext(request))
def google_login_success(request): if request.method == 'GET': params = request.GET elif request.method == 'POST': params = request.POST values = { p.split('.')[-1]: params[p] for p in params.keys() if 'value' in p } mode = params['openid.mode'] if mode != 'id_res': # The user declined to sign in at Google return _fail_login(request, 'could not verify your credentials') email = values['email'] firstname = values['firstname'] lastname = values['lastname'] handle = params['openid.claimed_id'] # Break apart the handle to find the user's ID # Assumes there are no other parameters attached to URL in 'openid.claimed_id' userid = handle.split("?")[-1].split("=")[-1] association = params['openid.assoc_handle'] # Use the information from Google to retrieve this user's profile, # or create a new user and profile. # 1) Try to retrieve this user's profile by openid handle try: profile = UserProfile.objects.get(openid_auth_stub__claimed_id=userid) except UserProfile.DoesNotExist: # 2) Try to retrieve the user's profile by email address (username) try: user = User.objects.get(username=email) profile = UserProfile.objects.get(user=user) except User.DoesNotExist: # 3) This person has never logged in before user = User.create_user(email, random_string()) user.first_name = firstname user.last_name = lastname user.save() profile = UserProfile(user=user) # Save openid information when this user has never used openid before # This should happen even if the user's profile already exists profile.openid_auth_stub = OpenidAuthStub(association=association, claimed_id=userid) profile.save() # Store the profile in the session request.session['profile'] = profile # Get the user's phone number if they do not have one already registered if not profile.phone_number: return HttpResponseRedirect(reverse('google_register')) profile.user.backend = 'mongoengine.django.auth.MongoEngineBackend' login(request, profile.user) return HttpResponseRedirect(reverse('user_landing'))
def handle(self, **kwargs): username = self._get_string('Username') user = User.objects(username=username).first() if user: user.delete() print 'User "%s" successfully removed' % (username) else: print 'Error! Could not find user with username "%s"' % username
def createuser(request): result = {} try: if request.data['is_admin'] is True or request.data[ 'is_admin'] == "true" or request.data['is_admin'] == "True": User.create_user(request.data['username'], request.data['password'], request.data['email']) user = User.objects.get(username=request.data['username']) user.is_superuser = True user.save() else: User.create_user(request.data['username'], request.data['password'], request.data['email']) result = {'result': True, 'message': "Register completed."} return Response(result) except Exception as e: return Response(str(e), status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def clean_username(self): username = self.cleaned_data.get('username') try: user = User.objects(username=username) except User.DoesNotExist: return username else: raise forms.ValidationError(_('This username is already in use.'))
def is_valid(self): if len(User.objects(username = self.username)) != 0: self.error = 'User exists' return False elif len(self.username) == 0 or len(self.password) == 0: self.error = 'Invalid username or password, can not be empty' return False else: return True
def create_user(user_tup): '''Boilerplate for making a new user with a profile''' user = User.create_user(user_tup[2], "password") user.first_name = user_tup[0] user.last_name = user_tup[1] user.is_active = True user.save() profile = models.UserProfile.objects.create(phone_number=user_tup[3], user=user) return user, profile
def handle(self, **kwargs): username = self._get_string('Username') user = User.objects(username=username).first() if user: user.delete() print 'User "%s %s" successfully removed' % (user.first_name, user.last_name) else: print 'Error! Could not find user with username "%s"' % username
def create_user(data): """ Add new User Keyword arguments: @param data: data whose user details need to be extracted """ user = User.create_user(data["username"], data["password"], data["email"]) profile = Profile(user=user) profile.save() return user
def register(request): error = False if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') email = request.POST.get('email') user = User.objects(username=username) if not username or not password or not email or not len(user) == 0: error = True return render_to_response("registration/register.html", {'error': error}, context_instance=RequestContext(request)) else: User.create_user(username=username, password=password, email=email) newuser = auth.authenticate(username=username, password=password) auth.login(request, newuser) return HttpResponseRedirect("/") else: return render_to_response("registration/register.html", {'error': error}, context_instance=RequestContext(request))
def authenticate(self, username=None, password=None): payload = {'username': username, 'password': password} url = '%s/auth/login/' % (settings.API_BASE_URL, ) r = requests.post(url, data=json.dumps(payload)) if r.status_code == requests.codes.ok: token = r.headers.get('x-auth-token') if not token: return None try: user = User.objects.get(username=username) user.password = token user.save() except User.DoesNotExist: # Create a new user. Note that we can set password # to anything, because it won't be checked; the password # from settings.py will. user = User(username=username, password=token) user.is_staff = True user.is_superuser = True user.save() return user elif r.status_code >= requests.codes.internal_server_error: raise Exception('Server error. ' + str(r.status_code)) return None
def register(request): # Cannot register if logged in already if request.user.is_authenticated(): return HttpResponseRedirect(reverse('login')) # The registration form form = None # Form has been submitted if request.method == 'POST': form = RegisterForm(request.POST) # Validate the registration form if form.is_valid(): user = User.create_user(form.cleaned_data['username'], form.cleaned_data['password1']) user.first_name = form.cleaned_data['first_name'] user.last_name = form.cleaned_data['last_name'] user.is_active = False user.save() profile = UserProfile.objects.create( phone_number=form.cleaned_data['phone'], user=user) stub = RegistrationStub.objects.create(user=user) # Send confirmation email hostname = _hostname(protocol="") activate_uri = reverse('activate') activate_link = '{}{}?key={}'.format(hostname, activate_uri, stub.activationCode) email_subject = "Welcome to Obietaxi!" email_to = [form.cleaned_data['username']] msg_body = "Welcome to Obietaxi! Your account has already been created with this email address, now all you need to do is confirm your accout by clicking on the link below. If there is no link, you should copy & paste the address into your browser's address bar and navigate there.\n\n{}".format( activate_link) send_email(email_to=email_to, email_subject=email_subject, email_body=msg_body) messages.add_message( request, messages.SUCCESS, "Your account has been created. Check your email for a confirmation link to complete the registration process." ) return HttpResponseRedirect(reverse('login')) # Form needs to be rendered else: form = RegisterForm() # Render the form (possibly with errors if form did not validate) return render_to_response('register.html', locals(), context_instance=RequestContext(request))
def register(request): # errors = [] # if(request.POST.get('password','1') != request.POST.get('confirm_password','1')): # errors.append('wrong_password') # if(request.POST.get('username', "field is empty") == "" or request.POST.get('email', "field is empty") == "" or request.POST.get('password',"field is empty") == ""): # errors.append('empty_field') # if(len(errors) != 0): # return render_to_response('profile/register.html', {'errors': errors}, RequestContext(request)) # else: if request.user.is_authenticated(): my_user = MyUser.objects.get(user=User.objects.get(id=request.user.id)) return render_to_response('profile/profile.html', {'my_user': my_user}, RequestContext(request)) users_from_database = User.objects.all() if request.POST: User.create_user(username=request.POST['username'], email=request.POST['email'], password=request.POST['password']) user = authenticate(username=request.POST['username'], password=request.POST['password']) my_user = MyUser(point=0.0, comment_count=0, disease_added_count=0, article_added_count=0, discussion_added_count=0, forum_present_count=0) my_user.user = user my_user.save() login(request, user) return render_to_response('profile/account.html', {'users': users_from_database}, RequestContext(request)) else: return render_to_response('profile/register.html', {'users': users_from_database}, RequestContext(request))
def RegView(request): if request.method == 'GET': return render(request, 'reg.html') if request.method == 'POST': try: username = request.POST['username'] password = request.POST['password'] passwordrepeat = request.POST['password-repeat'] if User.objects(username=username).first(): messages.error(request, "user exists") return redirect("reg.html") elif password != passwordrepeat: messages.error(request, "please enter same password") return redirect("reg.html") else: user = User.create_user(username=username, password=password) messages.success(request, "user register successfully") return render(reqeuest, 'user.html') except: messages.error(request, "Error, please try again") return redirect("reg.html")
def clean_email(self): """ Validates that an active user exists with the given email address. """ email = self.cleaned_data["email"] self.users_cache = User.objects(email__iexact=email, is_active=True) if not len(self.users_cache): raise forms.ValidationError(self.error_messages['unknown']) if self.users_cache.filter(password=UNUSABLE_PASSWORD).count(): raise forms.ValidationError(self.error_messages['unusable']) return email
def clean(self): cleaned_data = super(RegisterForm, self).clean() pw1 = cleaned_data.get('password1') pw2 = cleaned_data.get('password2') usr = cleaned_data.get('username') # Passwords must match if pw1 and pw2: if cleaned_data['password1'] != cleaned_data['password2']: raise forms.ValidationError("Passwords must match.") # Unique usernames if usr: if User.objects(username=usr).count() > 0: raise forms.ValidationError("That username is already taken.") return cleaned_data
def createUser(request): logger.debug(request.POST) if request.method == "POST": form = UserForm(request.POST) if form.is_valid(): new_user = User.create_user(form.username, form.password) return HttpResponseRedirect('/') else: return render(request, 'registration/createUser.html', { 'form': UserForm(), 'error': form.error }) else: form = UserForm() return render(request, 'registration/createUser.html', {'form': form})
def testCreateUser(self): logger.debug('Start TestUI::testCreateUser.') USER_NAME = 'test12' driver = self.driver url = self.base_url + '/createUser/' logger.debug('TestUI::testCreateUser try to open browser at ' + url) driver.get(url) logger.debug('TestUI::testCreateUser opened browser at ' + url) time.sleep(2) driver.find_element_by_id("id_username").clear() driver.find_element_by_id("id_username").send_keys(USER_NAME) driver.find_element_by_id("id_password").clear() driver.find_element_by_id("id_password").send_keys(USER_NAME) driver.find_element_by_css_selector("input[type=\"submit\"]").click() time.sleep(5) self.assertEqual(User.objects().count(), 1) logger.debug('End TestUI::testCreateUser.')
def setUp(self): # Create a test user self.user_data = { 'username': '******', 'password': '******', } self.user = User.create_user(*self.user_data.values()) # Create a test entry self.text_entry = TextEntry(title='Test-Entry', slug='test-entry') self.text_entry.tags = ['tests'] self.text_entry.published = True self.text_entry.content = 'some-test-content' self.text_entry.rendered_content = '<p>some test content</p>' # Create test comment self.comment = HtmlComment( author='Mr Test', body='test comment', rendered_content='<p>test comment</p>', ) self.text_entry.comments = [self.comment] self.text_entry.save()
def tearDown(self): self.driver.quit() self.assertEqual([], self.verificationErrors) self.display.stop() Doc.objects.delete() User.drop_collection()
def tearDown(self): User.drop_collection()
def return_user(name): return use.objects(username=name)
def createuser(request): User.create_user(request.POST['username'], request.POST['password']) return HttpResponseRedirect('/login/')
def setUp(self): if not DJ15: raise SkipTest('mongo_auth requires Django 1.5') connect(db='mongoenginetest') User.drop_collection() super(MongoAuthTest, self).setUp()