Example #1
0
class ArticleTest(TestCase):
    def setUp(self):
        # create the objects needed
        self.client = Client()
        self.article = Article()

        self.user = User(username='admin')
        self.user.set_password('google')
        self.user.is_active = True
        self.user.save()

    def tearDown(self):
        self.client = None
        self.article = None
        self.user = None

    def test_save(self):
        self.article.headline = 'Unit Testing'
        self.article.summary = 'Unit Testing'

        # required fields
        self.article.creator = self.user
        self.article.creator_username = self.user.username
        self.article.owner = self.user
        self.article.owner_username = self.user.username
        self.article.status = True
        self.article.status_detail = 'active'
        self.article.enclosure_length = 0
        self.article.timezone = 'America/Chicago'

        self.article.save()

        self.assertTrue(isinstance(self.article.id, int))
def import_user(u):
    user_info = u["u"]
    up_info = u["up"]

    # HACK to handle dates
    user_info["last_login"] = dateutil.parser.parse(user_info["last_login"])
    user_info["date_joined"] = dateutil.parser.parse(user_info["date_joined"])

    user_keys = [
        "id",
        "username",
        "email",
        "password",
        "is_staff",
        "is_active",
        "is_superuser",
        "last_login",
        "date_joined",
        "password",
    ]
    up_keys = ["language", "location", "meta", "name", "id", "user_id"]

    u = User()
    for key in user_keys:
        u.__setattr__(key, user_info[key])
    u.save()

    up = UserProfile()
    up.user = u
    for key in up_keys:
        up.__setattr__(key, up_info[key])
    up.save()
Example #3
0
def initial_setup(request):
    if User.objects.all().exists():
        return redirect('/comic/')
    if request.POST:
        form = InitialSetupForm(request.POST)
        if form.is_valid():
            user = User(
                username=form.cleaned_data['username'],
                email=form.cleaned_data['email'],
                is_staff=True,
                is_superuser=True,
            )
            user.set_password(form.cleaned_data['password'])
            user.save()
            base_dir, _ = Setting.objects.get_or_create(name='BASE_DIR')
            base_dir.value = form.cleaned_data['base_dir']
            base_dir.save()
            user = authenticate(username=form.cleaned_data['username'],
                                password=form.cleaned_data['password'])
            login(request, user)
            return redirect('/comic/')
    else:
        form = InitialSetupForm()
    context = {
        'form': form,
        'title': 'CBWebReader - Setup',
        'error_message': form.errors,
    }
    return render(request, 'comic/settings_page.html', context)
Example #4
0
 def test_no_data_submission(self):
     """
     Form submission should add a submission with no data,
     which shouldn't generate any errors to the user.
     """
     user = User(
         username='das66',
         email='eeqdev+das66@psu.edu'
         )
     user.save()
     locker = Locker(
         form_url='http://equity.psu.edu/contact-form',
         form_identifier='contact-form',
         name='Contact Us',
         owner=user,
         create_timestamp='2015-01-14 15:00:00+05:00',
         archive_timestamp='2014-04-19 12:00:00+05:00',
         )
     response = self.client.post(
         reverse('datalocker:form_submission'),
         {
             'form-id': 'contact-form',
             'url': 'http://equity.psu.edu/contact-form',
             'owner': 'das66',
             'name': 'Contact Us',
         })
     self.assertEqual(response.status_code, 201)
     try:
         submission = Submission.objects.all()[0]
     except IndexError:
         self.assertTrue(False)
     else:
         self.assertDictEqual(submission.data_dict(), {})
    def setUpAuth(self):
        self.user_ctype = ContentType.objects.get_for_model(User)
        self.group_ctype = ContentType.objects.get_for_model(Group)

        User.objects.all().delete()
        self.abe = User(username='Abe', email='sales@example.com')
        self.jack = User(username='Jack', email='jack@example.com')
        self.james = User(username='James', email='sales@example.com')
        self.john = User(username='John', email='sales@example.com')
        self.elton = User(username='Elton', email='elton@example.com', pk=10)

        self.abe.save()
        self.jack.save()
        self.james.save()
        self.john.save()

        Group.objects.all().delete()
        self.rockers = Group(name='rockers')
        self.bluesmen = Group(name='bluesmen')
        self.jazzmen = Group(name='jazzmen')
        self.emos = Group(name='emos', pk=10)

        self.rockers.save()
        self.bluesmen.save()
        self.jazzmen.save()
        self.emos.save()
class MonitorUpdateTestCase(ResourceTestCase):
    def setUp(self):
        super(MonitorUpdateTestCase, self).setUp()
        self.user = User(username='user', password='password', email='1@2.com')
        self.user.save()
        fixture = AutoFixture(MonitorUpdate)
        fixture.create(10)

        try:
            self.api_key = ApiKey.objects.get(user=self.user)
        except ApiKey.DoesNotExist:
            self.api_key = ApiKey.objects.create(user=self.user)
        self.auth_string = '&username={0}&api_key={1}'.format(
            self.user.username, self.api_key.key)

    def tearDown(self):
        MonitorUpdate.objects.all().delete()

    def test_source_get(self):
        url = '/api/v1/monitorUpdate/1/?format=json{}'.format(self.auth_string)
        response = self.api_client.get(url)
        self.assertEqual(response.status_code, 200)
        unauth_url = '/api/v1/source/?format=json'
        response = self.api_client.get(unauth_url)
        self.assertEqual(response.status_code, 401)
Example #7
0
	def save(self):
		"Creates the User and Member records with the field data and returns the user"
		if not self.is_valid(): raise Exception('The form must be valid in order to save')
		user = User(username=self.cleaned_data['username'], first_name=self.cleaned_data['first_name'], last_name=self.cleaned_data['last_name'], email=self.cleaned_data['email'])
		user.save()
		member = user.get_profile()
		member.email2 = self.cleaned_data['email2']
		member.phone = self.cleaned_data['phone']
		member.phone = self.cleaned_data['phone2']
		member.address1 = self.cleaned_data['address1']
		member.address2 = self.cleaned_data['address2']
		member.city = self.cleaned_data['city']
		member.state = self.cleaned_data['state']
		member.zipcode = self.cleaned_data['zipcode']
		member.url_personal = self.cleaned_data['url_personal']
		member.url_professional = self.cleaned_data['url_professional']
		member.url_facebook = self.cleaned_data['url_facebook']
		member.url_twitter = self.cleaned_data['url_twitter']
		member.url_linkedin = self.cleaned_data['url_linkedin']
		member.url_biznik = self.cleaned_data['url_biznik']
		member.url_github = self.cleaned_data['url_github']
		member.url_aboutme = self.cleaned_data['url_aboutme']
		member.gender = self.cleaned_data['gender']
		member.howHeard = self.cleaned_data['howHeard']
		member.industry = self.cleaned_data['industry']
		member.neighborhood = self.cleaned_data['neighborhood']
		member.has_kids = self.cleaned_data['has_kids']
		member.self_emplyed = self.cleaned_data['self_employed']
		member.company_name = self.cleaned_data['company_name']
		member.notes = self.cleaned_data['notes']
		member.photo = self.cleaned_data['photo']
		member.save()
		return user
Example #8
0
    def setUp(self):
        user = User()
        user.is_superuser = 1
        user.username = 'admin'
        user.set_password('password2')
        user.email = 'admin@cc.com'
        user.first_name = 'aa'
        user.is_active = 1
        user.save()
        self.user = user

        c = Client()
        self.c = c
        self.c.login( username='admin', password='password2')

        product = Products()
        product.name = '123123'
        product.price = 123
        product.price_type = 1
        product.total_price = 1*2
        product.order_time = datetime.datetime.strptime('2014-03-20','%Y-%m-%d')
        product.trip_start_time = datetime.datetime.strptime('2014-06-20','%Y-%m-%d')
        product.trip_end_time = datetime.datetime.strptime('2014-09-09','%Y-%m-%d')
        product.key_desc = '123'
        product.start_city = '123'
        product.end_city = '123'
        product.pics = ''
        product.trips = ''
        product.date_count = 4
        product.user = self.user
        product.save()

        self.product = product
Example #9
0
class LocationLocationTest(TestCase):
    def setUp(self):
        # create the objects needed
        self.client = Client()
        self.location = Location()

        self.user = User(username='admin')
        self.user.set_password('google')
        self.user.is_active = True
        self.user.save()

    def tearDown(self):
        self.client = None
        self.location = None
        self.user = None

    def test_save(self):
        self.location.location_name = 'Unit Testing'
        self.location.description = 'Unit Testing'

        # required fields
        self.location.creator = self.user
        self.location.creator_username = self.user.username
        self.location.owner = self.user
        self.location.owner_username = self.user.username
        self.location.status = True
        self.location.status_detail = 'active'
        self.location.enclosure_length = 0
        self.location.timezone = 'America/Chicago'

        self.location.save()

        self.assertTrue(isinstance(self.location.id, int))
Example #10
0
def site_signup(request):
	if request.method == 'POST':
		form = PatientRegistrationForm(request.POST)
		if form.is_valid():
			cd = form.cleaned_data
			uname = cd['username']
			pword = cd['password']
			firstname = cd['firstname']
			lastname = cd['lastname']
			email = cd['emailid']
			mobNum = cd['mobNum']
			locality = cd['locality']
			user = User(username=uname,password=make_password(pword),first_name=firstname,last_name=lastname,email=email)
			user.backend='django.contrib.auth.backends.ModelBackend'
			user.save()
			usr = User.objects.get(username=uname)

			if usr:
				pat = Patient(phone_number=mobNum,locality=locality,user=usr)
				pat.save()
				usr.groups.add(Group.objects.get(name='Patient'))
				#usr = authenticate(username=uname,password=pword)
				login(request,user)
				request.session['new_un'] = uname
				#return HttpResponseRedirect("/signupsuccess/")
				return HttpResponseRedirect("/home/")
	else:
		form = PatientRegistrationForm(error_class=DivErrorList)
	return render(request,"signup_patient.html",{'form':form})
Example #11
0
    def update_user(self, existing_user=None, save=True, **kwargs):
        is_update_successful = False

        # From what I can tell, everything that invokes this method invokes it
        # with a value for existing_user. It also looks like the code below is
        # not behaving properly for mobile workers when existing_user is None.
        # If the soft asserts confirm this isn't ever being passed existing_user=None,
        # I propose making existing_user a required arg and removing the code below
        # that creates the user.
        _assert = soft_assert('@'.join(['gcapalbo', 'dimagi.com']), exponential_backoff=False)
        _assert(existing_user is not None, "existing_user is None")

        if not existing_user and 'email' in self.cleaned_data:
            from django.contrib.auth.models import User
            django_user = User()
            django_user.username = self.cleaned_data['email']
            django_user.save()
            existing_user = CouchUser.from_django_user(django_user)
            existing_user.save()
            is_update_successful = True

        for prop in self.direct_properties:
            setattr(existing_user, prop, self.cleaned_data[prop])
            is_update_successful = True

        if is_update_successful and save:
            existing_user.save()
        return is_update_successful
Example #12
0
def new_random_profile(year):
    sn = random_student_number(year)
    while TutorProfile.objects.filter(studentnumber__exact=sn).exists():
        sn = random_student_number(year)

    first_name = random_first_name()
    last_name = random_last_name()
    email = random_email(sn)

    tp = TutorProfile(
            studentnumber=sn,
            name=first_name+' '+last_name,
            email=email,
            street=random_street(),
            city=random_city(),
            phone=random_phone_number(),
            study=random_study(),
            )

    u = User(
            username=sn,
            email=email,
            first_name=first_name,
            last_name=last_name,
            )
    u.save()
    tp.user = u
    tp.save()

    return tp
Example #13
0
class TokenCreationTest(TestCase):
    def setUp(self):
        self.user = User(username='test_user')
        self.user.save()

    def test_create_token_string(self):
        from auth_remember.utils import create_token_string

        value = create_token_string(self.user)
        self.assertTrue(value.startswith('%d:' % self.user.id))

    def test_get_by_token_string(self):
        from auth_remember.models import RememberToken
        from auth_remember.utils import create_token_string

        value = create_token_string(self.user)
        token = RememberToken.objects.get_by_string(value)

        self.assertEqual(token.user, self.user)

    def test_create_token_string_token_arg(self):
        from auth_remember.models import RememberToken
        from auth_remember.utils import create_token_string

        value = create_token_string(self.user)
        token = RememberToken.objects.get_by_string(value)

        time.sleep(0.1)
        new_value = create_token_string(self.user, token)
        new_token = RememberToken.objects.get_by_string(new_value)
        self.assertEqual(new_token.created_initial, token.created)
        self.assertTrue(new_token.created > token.created)
Example #14
0
class CheckTokenTestCase(TestCase):

    def setUp(self):
        super(CheckTokenTestCase, self).setUp()

        self.alice = User(username="alice", email="alice@example.org")
        self.alice.set_password("password")
        self.alice.save()

        self.profile = Profile(user=self.alice)
        self.profile.token = make_password("secret-token")
        self.profile.save()

    def test_it_redirects(self):
        r = self.client.get("/accounts/check_token/alice/secret-token/")
        self.assertRedirects(r, "/checks/")

        # After login, token should be blank
        self.profile.refresh_from_db()
        self.assertEqual(self.profile.token, "")

    def test_it_redirects_already_logged_in(self):
        # Login
        self.client.login(username="alice@example.org", password="password")

        # Login again, when already authenticated
        r = self.client.get("/accounts/check_token/alice/secret-token/")
        self.assertRedirects(r, "/checks/")

    def test_it_redirects_bad_login(self):
        # Login with a bad token
        url = "/accounts/check_token/alice/invalid-token/"
        r = self.client.get(url, follow=True)
        self.assertRedirects(r, "/accounts/login/")
        self.assertContains(r, "incorrect or expired")
Example #15
0
 def delete(self, using=None):
     '''
     also delete from user table
     '''
     user = User.objects.get_by_natural_key(self.ma_so)
     User.delete(user, using)
     models.Model.delete(self, using=using)
Example #16
0
    def handle(self, *args, **options):
        reader = csv.DictReader(open(args[0], 'rb'), fields)
        
        csvfile = open('new_' + args[0], 'wb')
        writer = csv.writer(csvfile)

        for row in reader:
            for key in row:
                if isinstance(row[key], str):
                    row[key] = unicode(row[key], 'UTF-8').strip()
                if isinstance(row[key], basestring):
                    row[key] = row[key].strip()

            login = ''.join(random.choice(string.ascii_lowercase + string.digits) for x in range(6))
            password = ''.join(random.choice(string.ascii_lowercase + string.digits) for x in range(6))

            user = User(
                username=login,
                first_name=row['first_name'],
                last_name=row['last_name'],
                email=row['email']
            )
            user.set_password(password)
            user.save()

            new_row = [row['last_name'], row['first_name'], row['second_name'], row['email'], row['phone'], login, password]

            new_row = [s.encode('UTF-8') for s in new_row]

            writer.writerow(new_row)
            
        csvfile.close()
            
Example #17
0
 def setUp(self):
     self.super_user = User(username="test", is_staff = True, is_active = True, is_superuser = True)
     self.super_user.set_password("test")
     self.super_user.save()
     
     self.slave = User(username="slave", is_staff=True, is_active=True, is_superuser=False)
     self.slave.set_password("slave")
     self.slave.save()
     
     self.login_user(self.super_user)
     
     # create 3 sections
     self.sections = []
     self.section_pks = []
     for i in range(3):
         section = Section.objects.create(name="section %s" %i)
         self.sections.append(section)
         self.section_pks.append(section.pk)
     self.section_count = len(self.sections)
     # create 10 articles by section
     for section in self.sections:
         for j in range(10):
             Article.objects.create(
                 title="article %s" % j,
                 section=section
             )
     self.FIRST_LANG = settings.LANGUAGES[0][0]
     self.SECOND_LANG = settings.LANGUAGES[1][0]
 def authenticate(self, **kwargs):
     result = None
     tenantKey = kwargs.get('tenant')
     userId = kwargs.get('userId')
     if tenantKey != None and userId != None:
         tenantPackages = get_subpackages(tenant)
         logger.warn(str(tenantPackages))
         if tenantKey in tenantPackages:
             result = self.get_user(userId)
             logger.warn(str(tenantKey))
             if result == None:
                 if 'emailAddress'in kwargs.keys():
                     # 'Long' call has been issued
                     userId = kwargs['userId']
                     emailAddress = kwargs['emailAddress']
                     firstname = kwargs['firstname']
                     lastname = kwargs['lastname']
                     role = kwargs['role']
                     raw_password = userId[::-1]
                     user = User(username=userId, email=emailAddress, first_name=firstname,
                                 last_name=lastname)
                     user.set_password(raw_password)
                     user.save()
                     result = user
     return result
     
     
Example #19
0
def user_signup(request):
	context = RequestContext(request)
	registered = False
	user = User(username = '')
	next_link = ""
	if request.GET:
		next_link = request.GET['next']	
	
	if request.method == 'POST':
		next_link = request.POST['signup_next']
		user.first_name = request.POST['user[full_name]']
		user.last_name = request.POST['user[sur_name]']
		user.username = request.POST['user[email]']
		user.email = request.POST['user[email]']
		user.password = request.POST['user[password]']
		user.set_password(user.password)
		user.save()
		patron = Patron(user = user)
		account = PatronAccount(balance = 0,  frozen = False, valid = True )
		account.save()
		patron.account = account
		patron.save()
		user = authenticate(username = request.POST['user[email]'], password = request.POST['user[password]'])
                if user is not None:
                        if user.is_active:
                                login(request, user)

		if next_link == "":
			return HttpResponseRedirect('/giftcards')
		else:
			return HttpResponseRedirect(next_link)
	
	else:
		return render_to_response('login.html', {'next':next_link}, context)		
	return 
    def authenticate(request=None):
        _module_name, _function_name = settings.USER_DATA_FN.rsplit('.', 1)
        _module = __import__(_module_name, fromlist=[None])  # We need a non-empty fromlist
        USER_DATA_FN = getattr(_module, _function_name)

        if not request.is_secure():
            logger.debug("insecure request")
            return None
        authentication_status = request.META.get('HTTP_X_SSL_AUTHENTICATED',
                                                 None)
        if (authentication_status != "SUCCESS" or
                    'HTTP_X_SSL_USER_DN' not in request.META):
            logger.warn(
                "HTTP_X_SSL_AUTHENTICATED marked failed or "
                "HTTP_X_SSL_USER_DN "
                "header missing")
            return None
        dn = request.META.get('HTTP_X_SSL_USER_DN')
        user_data = USER_DATA_FN(dn)
        username = user_data['username']
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            logger.info("user {0} not found".format(username))
            if settings.AUTOCREATE_VALID_SSL_USERS:
                user = User(**user_data)
                user.save()
            else:
                return None
        if not user.is_active:
            logger.warning("user {0} inactive".format(username))
            return None
        logger.info("user {0} authenticated using a certificate issued to "
                    "{1}".format(username, dn))
        return user
Example #21
0
 def test_new_form_entry(self):
     """
     Form submission should create a new locker and save the submission.
     """
     user = User(
         username='das66',
         email='eeqdev+das66@psu.edu'
         )
     user.save()
     response = self.client.post(
         reverse('datalocker:form_submission'),
         {
             'form-id': 'contact-form',
             'url': 'http://equity.psu.edu/contact-form',
             'owner': 'das66',
             'name': 'Contact Us',
             'data': json.dumps({
                 'Your E-mail Address': 'eeqdev+das66@psu.edu',
                 'Subject': 'New Form Entry Test',
                 'Comments': 'Testing locker creation from initial form submission',
                 }),
         })
     self.assertEqual(response.status_code, 201)
     try:
         locker = Locker.objects.get(form_identifier='contact-form')
     except Locker.DoesNotExist:
         self.assertTrue(False)
     else:
         self.assertEqual(len(locker.submissions.all()), 1)
    def authenticate(self, linkedin_access_token, user=None):
        linkedin = LinkedIn(LINKEDIN_CONSUMER_KEY, LINKEDIN_CONSUMER_SECRET)
        # get their profile

        profile = ProfileApi(linkedin).getMyProfile(access_token=linkedin_access_token)

        try:
            user_profile = LinkedInUserProfile.objects.get(linkedin_uid=profile.id)
            user = user_profile.user
            return user
        except LinkedInUserProfile.DoesNotExist:
            # Create a new user
            username = "LI:%s" % profile.id

            if not user:
                user = User(username=username)
                user.first_name, user.last_name = (profile.firstname, profile.lastname)
                user.email = "%s@socialauth" % (username)
                user.save()

            userprofile = LinkedInUserProfile(user=user, linkedin_uid=profile.id)
            userprofile.save()

            auth_meta = AuthMeta(user=user, provider="LinkedIn").save()
            return user
Example #23
0
def seed_users():
    for num in range(0, 10):
        username = fake.name()
        email = fake.free_email()
        new_user = User(username=username, email=email)
        new_user.set_password('password')
        new_user.save()
Example #24
0
    def setUp(self):
        "Initial Setup"

        if not self.prepared:
            Object.objects.all().delete()

            # Create objects

            try:
                self.group = Group.objects.get(name='test')
            except Group.DoesNotExist:
                Group.objects.all().delete()
                self.group = Group(name='test')
                self.group.save()

            try:
                self.user = DjangoUser.objects.get(username=self.username)
                self.user.set_password(self.password)
                try:
                    self.profile = self.user.get_profile()
                except Exception:
                    User.objects.all().delete()
                    self.user = DjangoUser(username=self.username, password='')
                    self.user.set_password(self.password)
                    self.user.save()
            except DjangoUser.DoesNotExist:
                User.objects.all().delete()
                self.user = DjangoUser(username=self.username, password='')
                self.user.set_password(self.password)
                self.user.save()

            try:
                perspective = Perspective.objects.get(name='default')
            except Perspective.DoesNotExist:
                Perspective.objects.all().delete()
                perspective = Perspective(name='default')
                perspective.set_default_user()
                perspective.save()

            ModuleSetting.set('default_perspective', perspective.id)

            self.folder = Folder(name='test')
            self.folder.set_default_user()
            self.folder.save()

            self.document = Document(title='test_document', folder=self.folder)
            self.document.set_default_user()
            self.document.save()

            self.file = File(name='test_file', folder=self.folder)
            self.file.set_default_user()
            self.file.save()

            self.link = WebLink(title='test', folder=self.folder, url='test')
            self.link.set_default_user()
            self.link.save()

            self.client = Client()

            self.prepared = True
Example #25
0
def passet(request):
    """ Set credentials for new users registered with social auth. """
    ctx = {
        'title': _("Set your password"),
    }
    if request.method == 'POST':
        f = SocialAuthPassetForm(request.POST)
        if f.is_valid():
            user = User(request.user.id)
            user.username = f.cleaned_data['username']
            user.set_password(f.cleaned_data['password'])
            # Re-fetch user object from DB
            user = User.objects.get(pk=request.user.id)
            # Create user profile if not exists
            try:
                prof = UserProfile.objects.get(user=request.user.id)
            except:
                prof = UserProfile()
                prof.user = user
                prof.save()
            return redirect('user:index')
        ctx['form'] = SocialAuthPassetForm(request.POST)
        return render(request, 'userspace/pass.html', ctx)
    ctx['form'] = SocialAuthPassetForm()
    return render(request, 'userspace/pass.html', ctx)
Example #26
0
 def setUp(self):
     self.user = User(username="admin", email="admin@localhost", is_staff=True, is_superuser=True)
     self.user.set_password('admin')
     self.user.save()
     self.user2 = User(username="member", email="member@localhost")
     self.user2.set_password('member')
     self.user2.save()
     self.user3 = User(username="nobody", email="nobody@localhost")
     self.user3.set_password('nobody')
     self.user3.save()
     self.user4 = User(username="owner", email="owner@localhost")
     self.user4.set_password('owner')
     self.user4.save()
     self.team = Team.objects.create(owner=self.user4, name='foo', slug='foo')
     self.project = Project.objects.get(id=1)
     self.project.update(public=False, team=self.team)
     self.tm = TeamMember.objects.get_or_create(
         user=self.user2,
         team=self.team,
         type=MEMBER_USER,
     )[0]
     TeamMember.objects.get_or_create(
         user=self.user4,
         team=self.team,
         type=MEMBER_OWNER,
     )[0]
Example #27
0
def user_add_page(request):
    success_message = ''
    if request.POST:
        form = AddUserForm(request.POST)
        if form.is_valid():
            user = User(
                username=form.cleaned_data['username'],
                email=form.cleaned_data['email'],
            )
            user.set_password(form.cleaned_data['password'])
            user.save()
            UserMisc.objects.create(user=user)
            success_message = 'User {} created.'.format(user.username)

    else:
        form = AddUserForm()
    crumbs = [
        ('Users', '/comic/settings/users/'),
        ('Add', '/comic/settings/users/add/'),
    ]
    context = {
        'form': form,
        'menu': Menu(request.user, 'Users'),
        'breadcrumbs': generate_breadcrumbs_from_menu(crumbs),
        'error_message': form.errors,
        'success_message': success_message,
        'title': 'CBWebReader - Add User',
    }
    return render(request, 'comic/settings_page.html', context)
Example #28
0
def create_new_user_from_current_session(session):
    """
    This function creates a user from the session after shib validates
    """
    now = timezone.now()

    new_user = User(username=session.get(SESSION_VARS['gatorlink']),
                    email=session.get(SESSION_VARS['email']),
                    last_login=now,
                    last_name=session.get(SESSION_VARS['last_name']),
                    first_name=session.get(SESSION_VARS['first_name']))

    new_user.save()

    new_person = Person(user=new_user,
                        gatorlink=new_user.username,
                        first_name=new_user.first_name,
                        last_name=new_user.last_name,
                        email_address=new_user.email,
                        last_login_time=now,
                        account_expiration_time=utils.get_account_expiration_date(now))

    new_person.save(last_modified_by=new_user)

    return new_user
Example #29
0
def tester_registraion(request):
    if request.method == 'POST':
        form = TesterForm(request.POST)
        if form.is_valid():
            tester = Tester()
            user = User()
            user.username = user.email = form.cleaned_data['email']
            user.set_password(form.cleaned_data['password'])
            user.save()
            tester.user = user
            tester.surname = form.cleaned_data['last_name']
            tester.first_name = form.cleaned_data['first_name']
            tester.second_name = form.cleaned_data['second_name']
            tester.email = form.cleaned_data['email']
            tester.description = form.cleaned_data['description']
            tester.save()
            tester.osystems = form.cleaned_data['os']
            tester.program_languages = form.cleaned_data['program_languages']
            tester.testing_types = form.cleaned_data['testing_types']
            tester.browsers = form.cleaned_data['browsers']
            tester.save()
            return HttpResponseRedirect('/thanks')
    else:
        form = TesterForm()
    return render_to_response('tester_registraion.html',{'form': form})
Example #30
0
    def test_user_info(self):
        user = User(username="admin", email="admin@example.com")
        user.set_password("admin")
        user.save()

        self.assertRaises(Exception, self.client.get, reverse("sentry-raise-exc"))

        self.assertEquals(len(self.raven.events), 1)
        event = self.raven.events.pop(0)
        self.assertTrue("sentry.interfaces.User" in event)
        user_info = event["sentry.interfaces.User"]
        self.assertTrue("is_authenticated" in user_info)
        self.assertFalse(user_info["is_authenticated"])
        self.assertFalse("username" in user_info)
        self.assertFalse("email" in user_info)

        self.assertTrue(self.client.login(username="admin", password="admin"))

        self.assertRaises(Exception, self.client.get, reverse("sentry-raise-exc"))

        self.assertEquals(len(self.raven.events), 1)
        event = self.raven.events.pop(0)
        self.assertTrue("sentry.interfaces.User" in event)
        user_info = event["sentry.interfaces.User"]
        self.assertTrue("is_authenticated" in user_info)
        self.assertTrue(user_info["is_authenticated"])
        self.assertTrue("username" in user_info)
        self.assertEquals(user_info["username"], "admin")
        self.assertTrue("email" in user_info)
        self.assertEquals(user_info["email"], "admin@example.com")