def setUp(self):
        cache.clear()
        user1 = self.user_model.objects.create(password=make_password('user1'), email='*****@*****.**',
                                               first_name='1', last_name='User', is_active=True)
        user2 = self.user_model.objects.create(password=make_password('user2'), email='*****@*****.**',
                                               first_name='2', last_name='User', is_active=False)
        user3 = self.user_model.objects.create(password=make_password('user3'), email='*****@*****.**',
                                               first_name='3', last_name='User', is_active=True)
        user4 = self.user_model.objects.create(password=make_password('user4'), email='*****@*****.**',
                                               first_name='4', last_name='User', is_active=True)

        prt1 = PasswordRecovery.objects.create(user=user1, token=core.utils.gen_temporary_token(),
                                               ip_address='192.168.0.1')
        prt2 = PasswordRecovery.objects.create(user=user2, token=core.utils.gen_temporary_token(),
                                               ip_address='192.168.0.2')
        prt3 = PasswordRecovery.objects.create(user=user3, token=core.utils.gen_temporary_token(),
                                               ip_address='192.168.0.3')
        prt4 = PasswordRecovery.objects.create(user=user4, token=core.utils.gen_temporary_token(),
                                               ip_address='192.168.0.4')

        prt1.request_datetime = timezone.now() - datetime.timedelta(hours=settings.PRT_VALIDITY, minutes=1)
        prt2.request_datetime = timezone.now() - datetime.timedelta(hours=settings.PRT_VALIDITY, minutes=40)
        prt3.request_datetime = timezone.now() - datetime.timedelta(hours=settings.PRT_VALIDITY-1, minutes=59)
        prt1.save()
        prt2.save()
        prt3.save()
    def handle_noargs(self, **options):

        TOTAL_USERS = 10

        # Clean tables
        User.objects.all().delete()

        # Generate users
        users = {}
        fake_emails = generate_fake_list(fake.email, TOTAL_USERS)
        fake_usernames = generate_fake_list(fake.user_name, TOTAL_USERS)
        for i in range(TOTAL_USERS - 2):

            generated_user = user.make(
                first_name=fake.first_name(), last_name=fake.last_name(),
                email=fake_emails[i], username=fake_usernames[i],
                password=make_password(fake_usernames[i])
            )

            users[i] = generated_user

        # Generate static users
        admin_user = user.make(
            first_name=fake.first_name(), last_name=fake.last_name(),
            email='*****@*****.**', username='******',
            password=make_password('admin'), is_superuser=True, is_staff=True
        )
        users[TOTAL_USERS - 2] = admin_user

        demo_user = user.make(
            first_name=fake.first_name(), last_name=fake.last_name(),
            email='*****@*****.**', username='******',
            password=make_password('demo')
        )
        users[TOTAL_USERS - 1] = demo_user
    def test_initial_password_hash(self):
        """
        Ensure that a user's password hash is set correctly when the user is created,
        and that it isn't touched for existing users.
        """
        initial_hash = make_password('hunter2')

        # Make sure the command aborts if the provided hash isn't a valid Django password hash
        with self.assertRaises(CommandError) as exc_context:
            call_command('manage_user', TEST_USERNAME, TEST_EMAIL, '--initial-password-hash', 'invalid_hash')
        self.assertIn('password hash', str(exc_context.exception).lower())

        # Make sure the hash gets set correctly for a new user
        call_command('manage_user', TEST_USERNAME, TEST_EMAIL, '--initial-password-hash', initial_hash)
        user = User.objects.get(username=TEST_USERNAME)
        self.assertEqual(user.password, initial_hash)

        # Change the password
        new_hash = make_password('correct horse battery staple')
        user.password = new_hash
        user.save()

        # Verify that calling manage_user again leaves the password untouched
        call_command('manage_user', TEST_USERNAME, TEST_EMAIL, '--initial-password-hash', initial_hash)
        user = User.objects.get(username=TEST_USERNAME)
        self.assertEqual(user.password, new_hash)
Beispiel #4
0
def changeResestPassword(request):
    token = request.POST['token']
    if token:
        signer = Signer()
        try:
            original = signer.unsign(token)
        except BadSignature:
            print("Tampering detected!")
            return JsonResponse({'error' : 'token expired'})

        user = User.objects.filter(username=original).get()
        newPass = request.POST['password']
        user.password = make_password(newPass)
        user.save()
        user = authenticate(username=original, password=newPass)
        login(request, user)
        request.session['member_id'] = user.id
        request.session['username'] = user.username
        return JsonResponse({'success' : 'password changed for ' + user.username})
    else:
        if request.user.is_authenticated():
            me = request.user
            if check_password(request.POST['password0'], me.password):
                newPass = request.POST['password']
                me.password = make_password(newPass)
                me.save()
                me = authenticate(username=me.username, password=newPass)
                login(request, me)
                return JsonResponse({'success' : 'password changed for ' + me.username})
            else:
                return JsonResponse({'error' : 'current password doesn\'t match'})

    return JsonResponse({'error' : 'password not changed'})
Beispiel #5
0
    def setUp(self):
        super(TestHelpdeskWithClient, self).setUp()

        # create a manager user
        User.objects.create(
            user_type="password",
            user_id="test_manager",
            info={"password": make_password("test_manager")},
            admin_p=True,
            management_p=True,
            institution=self.institution,
            )
        self.manager_creds = {
            'username': '******',
            'password': '******'
            }

        # create superadmin
        User.objects.create(
            user_type="password",
            user_id="test_superadmin",
            info={"password": make_password("test_superadmin")},
            superadmin_p=True,
            institution=self.institution,
            )
        self.superadmin_creds = {
            'username': '******',
            'password': '******',
            }
def accountManager_changeUserpassword(request):
	if 'member_id' in request.session:
		if 'oldpass' in request.POST:
			user = SurveyUser.objects.get(id=request.session['member_id'])
			oldpass=make_password(password=request.POST['oldpass'],salt=None,hasher='unsalted_md5')
			if oldpass != user.hash_of_password :
				return render(request, 'account_management.html', {
					'website_type':'changeUserpassword',
					'hideLoginPanel': True,
					'swap_LoginPanel_to_accountmanager_menu' : True,
					'error_token':'Podane niewłaściwe hasło',})
			if request.POST['pass'] != request.POST['rpass']:
				return render(request, 'account_management.html', {
					'website_type':'changeUserpassword',
					'hideLoginPanel': True,
					'swap_LoginPanel_to_accountmanager_menu' : True,
					'error_token':'Podane nowe hasła się nie zgadzają',})
			user.hash_of_password=make_password(password=request.POST['pass'],salt=None,hasher='unsalted_md5')
			user.save()
			return render(request, 'account_management.html', {
					'website_type':'changeUserpassword',
					'hideLoginPanel': True,
					'swap_LoginPanel_to_accountmanager_menu' : True,
					'success_token':'Hasło zostało zmienione pomyślnie'})
		else:
			return render(request, 'account_management.html', {
					'website_type':'changeUserpassword',
					'hideLoginPanel': True,
					'swap_LoginPanel_to_accountmanager_menu' : True,})
Beispiel #7
0
def signup_view(request):
	if request.method == "POST":
		first_name = request.POST['first_name']
		last_name = request.POST['last_name']
		email = request.POST['email']
		username = request.POST['username']
		password = request.POST['password']
		confirm_password = request.POST['password2']
		profile_picture = request.FILES.get('profile_picture')

		try:
			if password == confirm_password:
				password = make_password(password)
				confirm_password = make_password(confirm_password)

				user = User(username=username, first_name=first_name, last_name=last_name, email=email,
					password=password)
				user.save()

				profile = Profile(user=user, profile_picture=profile_picture)
				profile.save()

				return redirect('index')
			else:
				return render(request, '500.html', {'error': "Las contraseñas no coinciden"})
		except:
			return render(request, '500.html', {'error': "El username ya existe"})
def create_users(apps, schema_editor):
    Group = apps.get_model("auth","Group")
    User = apps.get_model("auth", "User")
    Profile = apps.get_model("Users", "Profile")



    # Add 100 users: first 95 users are players, while last 5 are devs
    for i in range(1,95):
        username = "******" % i
        us1 = User(username=username, password=hashers.make_password("00000000"), email=("*****@*****.**" % username))
        us1.is_active=True
        us1.save()

        user1 = Profile(user=us1, activationToken=uuid.uuid4())
        user1.save()

        players = Group.objects.get(name='players')
        us1.groups.add(players)

    for i in range(96, 100):
        username = "******" % i
        us1 = User(username=username,  password=hashers.make_password("00000000"), email=("*****@*****.**" % username))
        us1.is_active=True
        us1.save()

        user1 = Profile(user=us1, activationToken=uuid.uuid4())
        user1.save()

        developers = Group.objects.get(name='developers')
        us1.groups.add(developers)
Beispiel #9
0
    def test_bcrypt_sha256(self):
        encoded = make_password('lètmein', hasher='bcrypt_sha256')
        self.assertTrue(is_password_usable(encoded))
        self.assertTrue(encoded.startswith('bcrypt_sha256$'))
        self.assertTrue(check_password('lètmein', encoded))
        self.assertFalse(check_password('lètmeinz', encoded))
        self.assertEqual(identify_hasher(encoded).algorithm, "bcrypt_sha256")

        # Verify that password truncation no longer works
        password = ('VSK0UYV6FFQVZ0KG88DYN9WADAADZO1CTSIVDJUNZSUML6IBX7LN7ZS3R5'
                    'JGB3RGZ7VI7G7DJQ9NI8BQFSRPTG6UWTTVESA5ZPUN')
        encoded = make_password(password, hasher='bcrypt_sha256')
        self.assertTrue(check_password(password, encoded))
        self.assertFalse(check_password(password[:72], encoded))
        # Blank passwords
        blank_encoded = make_password('', hasher='bcrypt_sha256')
        self.assertTrue(blank_encoded.startswith('bcrypt_sha256$'))
        self.assertTrue(is_password_usable(blank_encoded))
        self.assertTrue(check_password('', blank_encoded))
        self.assertFalse(check_password(' ', blank_encoded))
        # Long password
        self.assertRaises(
            ValueError,
            make_password,
            b"1" * (MAXIMUM_PASSWORD_LENGTH + 1),
            hasher="bcrypt_sha256",
        )
Beispiel #10
0
def get_ecounting_user(username, password):
  from heliosauth.models import User

  is_valid, user_data = check_ecounting_credentials(username, password)
  user = None
  if not is_valid:
    return user

  try:
    user = User.get_by_type_and_id('password', username)
    user.institution = get_institution(user_data)
    user.info['name'] = username
    user.info['password'] = make_password(password)
    user.ecounting_account = True
    user.save()
  except User.DoesNotExist:
    if is_valid:
      user = create_user(username, password)
      user.admin_p = True
      user.info['name'] = user.user_id
      user.info['password'] = make_password(password)
      user.ecounting_account = True
      user.institution = get_institution(user_data)
      user.save()

  return user
Beispiel #11
0
    def setUp(self):
        """
        Make a user for authenticating and
        testing community actions
        """
        owner = self.user_model.objects.create(password=make_password('user1'), email='*****@*****.**',
                                               first_name='1', last_name='User', is_active=True)
        moderator = self.user_model.objects.create(password=make_password('user2'), email='*****@*****.**',
                                               first_name='2', last_name='User', is_active=True)
        member = self.user_model.objects.create(password=make_password('user3'), email='*****@*****.**',
                                               first_name='3', last_name='User', is_active=True)
        other = self.user_model.objects.create(password=make_password('user4'), email='*****@*****.**',
                                               first_name='4', last_name='User', is_active=True)

        com = LocalCommunity.objects.create(name='com', description='com_desc', city='Paris', country='France',
                                            gps_x=0, gps_y=0,
                                            auto_accept_member=True)

        own_mbr = Member.objects.create(user=owner, community=com, role='0', status='1')
        mod_mbr = Member.objects.create(user=moderator, community=com, role='1', status='1')
        spl_mbr = Member.objects.create(user=member, community=com, role='2', status='1')

        loc1 = Location.objects.create(community=com, name='Gare de Lyon', description='Pour le train',
                                       gps_x=0, gps_y=0)
        loc2 = Location.objects.create(community=com, name='Gare Montparnasse', description='Pour le train',
                                       gps_x=0, gps_y=0)
        loc3 = Location.objects.create(community=com, name='Aéroport d\'Orly', description='Pour l\'avion',
                                       gps_x=0, gps_y=0)
        loc4 = Location.objects.create(community=com, name='Opéra', description='Pour le métro',
                                       gps_x=0, gps_y=0)
        loc5 = Location.objects.create(community=com, name='Saint Lazare', description='Pour le métro, pas le train',
                                       gps_x=0, gps_y=0)
Beispiel #12
0
 def test_unsalted_md5(self):
     encoded = make_password('lètmein', '', 'unsalted_md5')
     self.assertEqual(encoded, '88a434c88cca4e900f7874cd98123f43')
     self.assertTrue(is_password_usable(encoded))
     self.assertTrue(check_password('lètmein', encoded))
     self.assertFalse(check_password('lètmeinz', encoded))
     self.assertEqual(identify_hasher(encoded).algorithm, "unsalted_md5")
     # Alternate unsalted syntax
     alt_encoded = "md5$$%s" % encoded
     self.assertTrue(is_password_usable(alt_encoded))
     self.assertTrue(check_password('lètmein', alt_encoded))
     self.assertFalse(check_password('lètmeinz', alt_encoded))
     # Blank passwords
     blank_encoded = make_password('', '', 'unsalted_md5')
     self.assertTrue(is_password_usable(blank_encoded))
     self.assertTrue(check_password('', blank_encoded))
     self.assertFalse(check_password(' ', blank_encoded))
     # Long password
     self.assertRaises(
         ValueError,
         make_password,
         b"1" * (MAXIMUM_PASSWORD_LENGTH + 1),
         "",
         "unsalted_md5",
     )
Beispiel #13
0
def reg_User(req):
    if req.method == 'POST':
        m = regUser(req.POST)
        if m.is_valid():
            username = m.cleaned_data['username']
            email = m.cleaned_data['Email']
            password = m.cleaned_data['password']
            confirm_password = m.cleaned_data['confirm_password']
            print username,email,password,confirm_password
            sha256 =make_password(password,'Dzer0','pbkdf2_sha256')
            md5_pwd = make_password(sha256,None,'unsalted_md5')
            print sha256
            print md5_pwd
            #reg_date = datetime.datetime.now()
            #print reg_date
            #OneEmail = Members.objects.get(email= email)
            #print OneEmail
            if password == confirm_password:

                #print OneEmail

                #if OneEmail:
                #    xxerror = '该邮箱已注册请更改邮箱并重新注册!!!'
                #    render_to_response('reg.html',locals(),context_instance=RequestContext(req))
                Members.objects.create(username=username,passwd=md5_pwd,email=email)
                return HttpResponseRedirect('/login/')
    else:
        m = regUser()
        return render_to_response('reg.html',locals(),context_instance=RequestContext(req))
Beispiel #14
0
def login_User(req):
    if req.method =='POST':
        m = loginUser(req.POST)
        if m.is_valid():
            username = m.cleaned_data['username']
            password = m.cleaned_data['password']
            #print username,password
            sha256 =make_password(password,'Dzer0','pbkdf2_sha256')
            md5_pwd = make_password(sha256,None,'unsalted_md5')
            login_static = Members.objects.filter(username=username,passwd=md5_pwd)
            print login_static
            if login_static:
                sessusername = req.session['username'] =username
                print sessusername
                web = models.WebIntroduction.objects.all()
                lanmu = models.Column.objects.all()
                return HttpResponseRedirect('/User/')
                #return render_to_response('user.html',locals(),context_instance=RequestContext(req))
            else:
                return HttpResponse('<script>alert("密码或用户名错误");top.location="/login/";</script>')

            #return HttpResponse('test')
    else:
        web = models.WebIntroduction.objects.all()
        lanmu = models.Column.objects.all()
        m = loginUser()     #将m指向登陆表单
        print m
    #if req.method =='POST':
        #userlogin =
        #error = '<script>alert"sldjflksd";</script>'
        return render_to_response('user.html',locals(),context_instance= RequestContext(req))
    def setUp(self):
        """

        """
        owner = self.user_model.objects.create(password=make_password('user1'), email='*****@*****.**',
                                               first_name='1', last_name='User', is_active=True)
        moderator = self.user_model.objects.create(password=make_password('user2'), email='*****@*****.**',
                                               first_name='2', last_name='User', is_active=True)
        member = self.user_model.objects.create(password=make_password('user3'), email='*****@*****.**',
                                               first_name='3', last_name='User', is_active=True)
        other = self.user_model.objects.create(password=make_password('user4'), email='*****@*****.**',
                                               first_name='4', last_name='User', is_active=True)


        com1 = LocalCommunity.objects.create(name='com1', description='desc1', city='Paris', country='FR',
                                             gps_x=0, gps_y=0)
        com2 = LocalCommunity.objects.create(name='loc1', description='desc2', city='Paris', country='FR',
                                             gps_x=1, gps_y=1, auto_accept_member=True)
        com3 = LocalCommunity.objects.create(name='loccom1', description='desc3', city='Paris', country='FR',
                                             gps_x=2, gps_y=1)
        com4 = LocalCommunity.objects.create(name='con2', description='desc4', city='Paris', country='FR',
                                             gps_x=3, gps_y=2)
        com5 = LocalCommunity.objects.create(name='loc2', description='des5', city='Paris', country='FR',
                                             gps_x=2, gps_y=3)

        own_mbr = Member.objects.create(user=owner, community=com1, role='0', status='1')
        mod_mbr = Member.objects.create(user=moderator, community=com1, role='1', status='1')
        spl_mbr = Member.objects.create(user=member, community=com1, role='2', status='1')

        own_mbr = Member.objects.create(user=owner, community=com2, role='0', status='1')
        mod_mbr = Member.objects.create(user=moderator, community=com2, role='1', status='1')
        spl_mbr = Member.objects.create(user=member, community=com2, role='2', status='1')
Beispiel #16
0
def do_reg(request):
    try:
        if request.method == 'POST':
            reg_form = RegForm(request.POST)
            if reg_form.is_valid():
                print("有效 *************************")
                print(reg_form.cleaned_data['username'],make_password(reg_form.cleaned_data['password']),reg_form.cleaned_data['email'],reg_form.cleaned_data['url'])
                user = User.objects.create(
                    username=reg_form.cleaned_data['username'],
                    password=make_password(reg_form.cleaned_data['password']),
                    email=reg_form.cleaned_data['email'],
                    url=reg_form.cleaned_data['url'],
                )
                user.save()
                user.backend = 'django.contrib.auth.backends.ModelBackend'
                login(request, user)
                print(request.POST.get('source_url'))
                return redirect(request.POST.get('source_url'))
            else:
                return render(request, 'failure.html', locals())
        else:
            reg_form = RegForm()
    except Exception as e:
        print(e)
        logger.error(e)
    return render(request, 'reg.html', locals())
Beispiel #17
0
    def clean_password(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        if username and password:
            mail = checkldap(username,password)
            if not mail:
                raise forms.ValidationError(u'LDAP账户不正确')
            else:
                try:
                    c = User(username=username, password=make_password(password,None, 'pbkdf2_sha256'),email=mail,is_active=1)
                    c.save()
                except Exception:
                    pass
                try:
                    u = Example.objects.get(username=username)
                    u.password = make_password(password,None, 'pbkdf2_sha256')
                    u.save()
                except Exception:
                    pass
              
            self.user_cache = auth.authenticate(username=username,password=password)
            if self.user_cache is None:
                raise forms.ValidationError(u'账号密码不匹配')
            elif not self.user_cache.is_active:
                raise forms.ValidationError(u'此账号已被禁用')
        return self.cleaned_data
Beispiel #18
0
def cambiarPass(request):
    """
    Metodo en el que el usuario cambia su pass
    """
    us = request.user
    if request.method == 'POST':
        #user = User.objects.filter(username=request.POST['un'])

        #if user:

        passVieja = request.POST['passVieja']
        viejoConHash = make_password(passVieja)
        #valor=user.password
        #valor=us.password
        passNueva = request.POST['passNueva']
        confirmacion = request.POST['passNueva2']
        if passNueva == confirmacion:

            nuevo = make_password(confirmacion)
            us.password = nuevo
            us.save()
            messages.info(request, 'Contrasenha cambiada con exito')
        else:
            messages.error(request, 'Las contrasenhas no coinciden')
            return render(request, 'cambiarPass.html')
            #else:
            #   messages.error(request,'El usuario no existe' )
            #  return render(request, 'cambiarPass.html')
    else:
        return render(request, 'cambiarPass.html')
    return HttpResponseRedirect('/ss/inicio/')
def add_user_data(apps, schema_editor):
    Profile = apps.get_model('user', 'Profile')
    User = apps.get_model('user', 'User')
    andrew_user = User.objects.create(
        email='*****@*****.**',
        password=make_password('hunter2'),
        is_active=True,
        is_staff=True,
        is_superuser=True)
    andrew_profile = Profile.objects.create(
        user=andrew_user,
        name='Andrew',
        slug='andrew',
        about='The author of this site!')
    ada_user = User.objects.create(
        email='*****@*****.**',
        password=make_password('algorhythm'),
        is_active=True,
        is_staff=True,
        is_superuser=False)
    ada_profile = Profile.objects.create(
        user=ada_user,
        name='Ada Lovelace',
        slug='the_countess',
        about=(
            'Django Girls is a non-profit'
            'organization that empowers and helps'
            'women to organize free, one-day'
            'programming workshops by providing'
            'tools, resources and support. It was'
            'born in Berlin and started by two'
            'Polish girls: Ola Sitarska and Ola'
            'Sendecka.'))
Beispiel #20
0
 def setUp(self):
   self.user1 = User(first_name='Aslan', password=make_password('old_magic'), username="******", email="*****@*****.**")
   self.user2 = User(first_name='White', last_name='Witch', password=make_password('new_magic'), username="******", email="*****@*****.**")
   self.user1.save()
   self.user2.save()
   self.users = [self.user1, self.user2]
   self.formData = {'title':'CreationTest', 'address':'war drobe', 'email':'*****@*****.**', 'accessCode':'turkishdelight'}
Beispiel #21
0
	def save(self, *args, **kwargs):
		if self.pk:
			orig = SkvallraUser.objects.get(pk=self.pk)
			if orig.password != self.password:
				self.password = make_password(self.password)
		else:
			self.password = make_password(self.password)
		super(SkvallraUser, self).save(*args, **kwargs)
Beispiel #22
0
 def setUp(self):
     """
     Set data
     """
     user1 = self.user_model.objects.create(password=make_password('user1'), email='*****@*****.**',
                                            first_name='1', last_name='User', is_active=True)
     user2 = self.user_model.objects.create(password=make_password('user2'), email='*****@*****.**',
                                            first_name='2', last_name='User', is_active=True)
Beispiel #23
0
 def test_bad_algorithm(self):
     msg = (
         "Unknown password hashing algorithm '%s'. Did you specify it in "
         "the PASSWORD_HASHERS setting?"
     )
     with self.assertRaisesMessage(ValueError, msg % 'lolcat'):
         make_password('lètmein', hasher='lolcat')
     with self.assertRaisesMessage(ValueError, msg % 'lolcat'):
         identify_hasher('lolcat$salt$hash')
Beispiel #24
0
    def setUp(self):
        """
        Make a user for authenticating and
        testing community actions
        """
        owner = self.user_model.objects.create(password=make_password('user1'), email='*****@*****.**',
                                               first_name='1', last_name='User', is_active=True)
        moderator = self.user_model.objects.create(password=make_password('user2'), email='*****@*****.**',
                                               first_name='2', last_name='User', is_active=True)
        member = self.user_model.objects.create(password=make_password('user3'), email='*****@*****.**',
                                               first_name='3', last_name='User', is_active=True)
        other = self.user_model.objects.create(password=make_password('user4'), email='*****@*****.**',
                                               first_name='4', last_name='User', is_active=True)

        Profile.objects.create(user=owner)
        Profile.objects.create(user=moderator)
        Profile.objects.create(user=member)
        Profile.objects.create(user=other)

        lcom1 = LocalCommunity.objects.create(name='lcom1', description='descl1', city='Paris', country='FR',
                                              gps_x=0, gps_y=0)
        lcom2 = LocalCommunity.objects.create(name='lcom2', description='descl2', city='Paris', country='FR',
                                              gps_x=0, gps_y=0,
                                              auto_accept_member=True)
        lcom3 = LocalCommunity.objects.create(name='lcom3', description='descl3', city='Paris', country='FR',
                                              gps_x=0, gps_y=0)
        lcom4 = LocalCommunity.objects.create(name='lcom4', description='descl4', city='Paris', country='FR',
                                              gps_x=0, gps_y=0,
                                              auto_accept_member=True)
        lcom5 = LocalCommunity.objects.create(name='lcom5', description='descl5', city='Paris', country='FR',
                                              gps_x=0, gps_y=0)
        tcom1 = TransportCommunity.objects.create(name='tcom1', description='desct1', departure='dep1', arrival='arr1',
                                                  auto_accept_member=True)
        tcom2 = TransportCommunity.objects.create(name='tcom2', description='desct2', departure='dep2', arrival='arr2')
        tcom3 = TransportCommunity.objects.create(name='tcom3', description='desct3', departure='dep3', arrival='arr3')
        tcom4 = TransportCommunity.objects.create(name='tcom4', description='desct4', departure='dep4', arrival='arr4')
        tcom5 = TransportCommunity.objects.create(name='tcom5', description='desct5', departure='dep4', arrival='arr5')

        own_mbr = Member.objects.create(user=owner, community=lcom1, role='0', status='1')
        own_mbr = Member.objects.create(user=owner, community=lcom2, role='0', status='1')

        own_mbr = Member.objects.create(user=owner, community=lcom3, role='0', status='1')
        mod_mbr = Member.objects.create(user=moderator, community=lcom3, role='1', status='0')
        spl_mbr = Member.objects.create(user=member, community=lcom3, role='2', status='0')

        own_mbr = Member.objects.create(user=owner, community=lcom4, role='0', status='1')
        mod_mbr = Member.objects.create(user=moderator, community=lcom4, role='1', status='1')
        spl_mbr = Member.objects.create(user=member, community=lcom4, role='2', status='1')

        own_mbr = Member.objects.create(user=owner, community=lcom5, role='0', status='1')
        spl_mbr = Member.objects.create(user=member, community=lcom5, role='2', status='2')

        own_mbr = Member.objects.create(user=owner, community=tcom1, role='0', status='1')
        own_mbr = Member.objects.create(user=owner, community=tcom2, role='0', status='1')
        own_mbr = Member.objects.create(user=owner, community=tcom3, role='0', status='1')
        own_mbr = Member.objects.create(user=owner, community=tcom4, role='0', status='1')
        own_mbr = Member.objects.create(user=owner, community=tcom5, role='0', status='1')
Beispiel #25
0
 def setUp(self):
     """
     Make a user for authenticating and
     testing skill actions
     """
     user = self.user_model.objects.create(password=make_password('user1'), email='*****@*****.**',
                                           first_name='1', last_name='User', is_active=True)
     other = self.user_model.objects.create(password=make_password('user2'), email='*****@*****.**',
                                            first_name='2', last_name='User', is_active=True)
Beispiel #26
0
 def setUp(self):
     self.user1 = mommy.make(User, password=make_password('password'))
     self.user2 = mommy.make(User, password=make_password('password'))
     self.dataset = mommy.make(Dataset, owner=self.user1)
     self.choropleth = mommy.make(
         Choropleth,
         dataset=self.dataset,
         owner=self.user1,
         published=0
     )
def add_user_data(apps, schema_editor):
    Group = apps.get_model('auth', 'Group')
    Permission = apps.get_model(
        'auth', 'Permission')
    Profile = apps.get_model('user', 'Profile')
    User = apps.get_model('user', 'User')
    andrew_user = User.objects.create(
        email='*****@*****.**',
        password=make_password('hunter2'),
        is_active=True,
        is_staff=True,
        is_superuser=True)
    andrew_profile = Profile.objects.create(
        user=andrew_user,
        name='Andrew',
        slug='andrew',
        about='The author of this site!')
    # Django Girls is a real and very cool
    # organization but they are not affiliated
    # with this book and the email above is *not*
    # a real one.  Use of their name is for
    # illustrative purposes only.
    ada_user = User.objects.create(
        email='*****@*****.**',
        password=make_password('algorhythm'),
        is_active=True,
        is_staff=True,
        is_superuser=False)
    ada_profile = Profile.objects.create(
        user=ada_user,
        name='Ada Lovelace',
        slug='the_countess',
        about=(
            'Django Girls is a non-profit '
            'organization that empowers and '
            'helps women to organize free, '
            'one-day programming workshops by '
            'providing tools, resources and '
            'support. It was born in Berlin and '
            'started by two Polish girls: Ola '
            'Sitarska and Ola Sendecka.'))
    contributors = Group.objects.create(
        name='contributors')
    ada_user.groups.add(contributors)
    permissions = [
        'add_post',
        'change_post',
    ]
    for perm in permissions:
        contributors.permissions.add(
            Permission.objects.get(
                codename=perm,
                content_type__app_label='blog'))
Beispiel #28
0
 def test_simple(self):
     encoded = make_password('lètmein')
     self.assertTrue(encoded.startswith('pbkdf2_sha256$'))
     self.assertTrue(is_password_usable(encoded))
     self.assertTrue(check_password('lètmein', encoded))
     self.assertFalse(check_password('lètmeinz', encoded))
     # Blank passwords
     blank_encoded = make_password('')
     self.assertTrue(blank_encoded.startswith('pbkdf2_sha256$'))
     self.assertTrue(is_password_usable(blank_encoded))
     self.assertTrue(check_password('', blank_encoded))
     self.assertFalse(check_password(' ', blank_encoded))
Beispiel #29
0
 def test_simple(self):
     encoded = make_password("lètmein")
     self.assertTrue(encoded.startswith("pbkdf2_sha256$"))
     self.assertTrue(is_password_usable(encoded))
     self.assertTrue(check_password("lètmein", encoded))
     self.assertFalse(check_password("lètmeinz", encoded))
     # Blank passwords
     blank_encoded = make_password("")
     self.assertTrue(blank_encoded.startswith("pbkdf2_sha256$"))
     self.assertTrue(is_password_usable(blank_encoded))
     self.assertTrue(check_password("", blank_encoded))
     self.assertFalse(check_password(" ", blank_encoded))
Beispiel #30
0
 def test_md5(self):
     encoded = make_password('lètmein', 'seasalt', 'md5')
     self.assertEqual(encoded, 'md5$seasalt$3f86d0d3d465b7b458c231bf3555c0e3')
     self.assertTrue(is_password_usable(encoded))
     self.assertTrue(check_password('lètmein', encoded))
     self.assertFalse(check_password('lètmeinz', encoded))
     self.assertEqual(identify_hasher(encoded).algorithm, "md5")
     # Blank passwords
     blank_encoded = make_password('', 'seasalt', 'md5')
     self.assertTrue(blank_encoded.startswith('md5$'))
     self.assertTrue(is_password_usable(blank_encoded))
     self.assertTrue(check_password('', blank_encoded))
     self.assertFalse(check_password(' ', blank_encoded))
Beispiel #31
0
    def post(self,request):
        dict_root = {'是': '1', '否': '0'}
        dict_status = {'空闲': '0', '占用': '1', '损坏': '-1','':'0'}
        form = UploadExcelForm(request.POST,request.FILES)
        if form.is_valid():
            wb = xlrd.open_workbook(filename=None,file_contents=request.FILES['excel'].read())
            table = wb.sheets()[0]
            row  =table.nrows
            for i in range(1,row):

                col = table.row_values(i)
                device_type = str(col[1])
                device_id = str(col[3])
                device_root = dict_root[str(col[4])]
                department_name = str(col[5])
                device_user = str(col[6])

                device_status = dict_status[str(col[8])]


                #borrow_date = xlrd.xldate_as_datetime(col[7], 0).strftime('%Y-%m-%d') if device_status=='1' else None


                comment = str(col[9])
                device_sys = str(col[10])
                device_cpu = str(col[11])
                device_men = str(col[12])
                device_res = str(col[13])
                device_mac = str(col[14])
                try:
                    buy_time = xlrd.xldate_as_datetime(col[15],0).strftime('%Y-%m-%d')
                except:
                    buy_time=datetime.datetime.now()


                dev = Device.objects.filter(device_id=device_id)
                if not dev:

                    devicetype = DeviceType.objects.filter(device_type=device_type).first()

                    if devicetype:
                    #device_type = DeviceType.objects.filter(device_type=device_type).first()
                        pass
                    else:
                        devicetype = DeviceType(device_type=device_type,device_cpu=device_cpu,device_res=device_res)
                        devicetype.save()


                    if device_status == '1':
                        department = Department.objects.filter(department_name=department_name).first()
                        if department:
                            pass
                        else:
                            department = Department(department_name = department_name)
                            department.save()

                        user = UserProfile.objects.filter(username=device_user).first()
                        if user:
                            pass
                        else:
                            user = UserProfile(username=device_user,department=department,password=make_password(pwd),isadmin='0',is_staff='1')
                            user.save()

                        device = Device(device_id=device_id,device_type=devicetype,buy_time=buy_time,
                                    device_mac=device_mac,device_sys=device_sys,device_root=device_root,device_men=device_men,
                                    device_status=device_status,device_user=user,comment=comment)
                        device.save()

                        deviceLog(device, '0', device_status, 0, device.device_user)
                    else:
                        admin_user = UserProfile.objects.filter(isadmin='1').first()
                        device = Device(device_type=devicetype, device_id=device_id, buy_time=buy_time,
                               device_mac=device_mac, device_root=device_root,device_sys=device_sys,device_men=device_men,
                               device_status=device_status, device_user=admin_user,comment=comment)
                        device.save()
                else:
                    pass

        return HttpResponseRedirect((reverse('devices:device_list')))
Beispiel #32
0
 def set_password(self, password):
     self.password = make_password(password)
Beispiel #33
0
 def perform_create(self, serializer):
     serializer.save(password=make_password(self.request.data['password']))
Beispiel #34
0
 def perform_create(self, serializer):
     user = serializer.save()
     user.password = make_password(serializer.validated_data['password'])
     user.save()
     return Response(serializer.data)
 def create_test_user(username, password):
     testuser = User()
     testuser.username = username
     testuser.password = make_password(password)
     testuser.save()
Beispiel #36
0
def sign_up(request):
    sign_up_form = SignUpForm(request.POST or None)
    # next_url = request.GET.get('next_url')
    context = {
        # 'next_url': next_url,
    }
    if request.method == 'POST':
        # return HttpResponse(request.POST)
        if sign_up_form.is_valid():
            # return HttpResponse('he')
            clean_data = sign_up_form.cleaned_data
            first_name = clean_data.get('first_name')
            last_name = clean_data.get('last_name')
            username = clean_data.get('username')
            email = clean_data.get('email')
            password = clean_data.get('password')
            type = clean_data.get('type')
            # status = clean_data.get('status')
            status = 'user'
            voen = clean_data.get('voen')
            bank_account = clean_data.get('bank_account')
            region = clean_data.get('region')
            address = clean_data.get('address')
            businnes_types = clean_data.get('businnes_types')
            businnes_types_parent = clean_data.get('businnes_types_parent')
            practices = clean_data.get('practices')
            region_o = Region.objects.filter(id=region).first()
            random_string = str(random.random()).encode('utf8')
            # return HttpResponse(businnes_types_o.count())
            businness_types_o = Businnes.objects.filter(id__in=businnes_types)
            businnes_types_parents_o = Businnes.objects.filter(
                id__in=businnes_types_parent)
            if businnes_types_parents_o:
                for businnes_types_parent_o in businnes_types_parents_o:
                    if businnes_types_parent_o.parent_id:
                        businness_types_o = businness_types_o.exclude(
                            id=businnes_types_parent_o.parent_id)
            # print('--------------------------')
            # print(businness_types_o.count())
            # # print('--------------------------')
            # print(businnes_types_parents_o.count())
            # return HttpResponse('----------')
            salt = hashlib.sha1(random_string).hexdigest()[:5]

            salted = (salt + email).encode('utf8')

            # activation_key = hashlib.sha1(salted).hexdigest()
            #
            # key_expires = datetime.datetime.today() + datetime.timedelta(1)
            password = make_password(password, salt=salt)
            user = User(first_name=first_name,
                        last_name=last_name,
                        email=email,
                        username=username,
                        password=password,
                        is_active=False,
                        is_staff=False,
                        is_superuser=False)
            user.save()
            if type != 'ordinary-person':
                profile_o = Profile(user=user,
                                    type=type,
                                    status=status,
                                    voen=voen,
                                    bank_account=bank_account,
                                    region=region_o,
                                    address=address,
                                    practices=practices)
            else:
                profile_o = Profile(user=user,
                                    type=type,
                                    status=status,
                                    region=region_o)
            for businnes_types_parent_o in businnes_types_parents_o:
                profile_o.businnes_type.add(businnes_types_parent_o)
            for businnes_type_o in businness_types_o:
                profile_o.businnes_type.add(businnes_type_o)
            profile_o.save()
            message_code = 1
            sign_up_form = SignUpForm()
            message = 'succesfully_registered_please_login_to_site'
            context.update({
                'message': message,
                'message_code': message_code,
                'sign_up_form': sign_up_form,
            })
            return render(request,
                          'registration/sign_up.html',
                          context=context)
        # else:
        #     return HttpResponse('asas')
    context.update({
        'sign_up_form': sign_up_form,
    })
    return render(request, 'registration/sign_up.html', context=context)
Beispiel #37
0
def update(request, name):

    sta_mac = request.META.get('HTTP_X_ESP8266_STA_MAC')
    ap_mac = request.META.get('HTTP_X_ESP8266_AP_MAC')
    free_space = request.META.get('HTTP_X_ESP8266_FREE_SPACE')
    sketch_size = request.META.get('HTTP_X_ESP8266_SKETCH_SIZE')
    sketch_md5 = request.META.get('HTTP_X_ESP8266_SKETCH_MD5')
    chip_size = request.META.get('HTTP_X_ESP8266_CHIP_SIZE')
    sdk_version = request.META.get('HTTP_X_ESP8266_SDK_VERSION')

    print "sta_mac,ap_mac,free_space,sketch_size,sketch_md5,chip_size,sdk_version"
    print sta_mac, ap_mac, free_space, sketch_size, sketch_md5, chip_size, sdk_version

    if sta_mac is None\
       or ap_mac is None\
       or free_space is None\
       or sketch_size is None\
       or chip_size is None\
       or sdk_version is None :
        #       or sketch_md5 is None\

        return HttpResponse("403 Forbidden only for ESP8266 updater! (header)",
                            status=403)

    if request.META.get('HTTP_USER_AGENT') != 'ESP8266-http-Update':
        print "403 Forbidden only for ESP8266 updater!"
        return HttpResponse("403 Forbidden only for ESP8266 updater!",
                            status=403)

    try:
        firmware = Firmware.objects.filter(
            firmware__name=name,
            active=True,
        ).order_by('date').reverse()[0]
    except:
        print ' 500 no version for ESP firmware name'
        return HttpResponse(' 500 no version for ESP firmware name',
                            status=500)

    try:
        #check date (version)
        swversion = json.loads(request.META.get('HTTP_X_ESP8266_VERSION'))
        swdate = dateutil.parser.parse(swversion["ver"])
    except:
        print ' 300 No valid version!'
        return HttpResponse(' 300 No valid version!', status=300)

    try:
        print "user: "******"user"]
    except:
        print "no user in version"
    try:
        print "slug: ", swversion["slug"]
    except:
        print "no slug in version"

    try:
        print "boardslug: ", swversion["bslug"]
    except:
        print "no board slug in version; set default"
        swversion["bslug"] = "default"

    try:
        myboard = Board.objects.get(
            slug=swversion["bslug"],
            stationmetadata__slug=swversion["slug"],
            stationmetadata__ident__username=swversion["user"])

        if hasattr(myboard, 'boardfirmwaremetadata'):
            if not myboard.boardfirmwaremetadata.mac:
                print "update missed mac in firmware updater"
                myboard.boardfirmwaremetadata.mac = make_password(sta_mac)
                myboard.boardfirmwaremetadata.save(update_fields=[
                    'mac',
                ])
        else:
            print "add firmware metadata to board"
            bfm = BoardFirmwareMetadata(board=myboard,
                                        mac=make_password(sta_mac))
            myboard.boardfirmwaremetadata = bfm
            myboard.save()
        if check_password(sta_mac, myboard.boardfirmwaremetadata.mac):
            print "update firmware metadata"
            myboard.boardfirmwaremetadata.swversion = swversion["ver"]
            myboard.boardfirmwaremetadata.swlastupdate = django.utils.timezone.now(
            )
            myboard.boardfirmwaremetadata.save()
        else:
            print "WARNING! mac mismach in firmware updater"

    except:
        print "user/station/board not present on DB; ignore it"
        traceback.print_exc()

    if swdate >= firmware.date.replace(tzinfo=None):
        print ' 304 No new firmware'
        return HttpResponse(' 304 No new firmware', status=304)

    mymd5 = md5(firmware.file.path)
    mysize = os.path.getsize(firmware.file.path)

    if sketch_md5 == mymd5:
        print ' 304 Not Modified'
        return HttpResponse(' 304 Not Modified', status=304)

    response = FileResponse(open(firmware.file.path, 'rb'))
    response['Content-Disposition'] = 'attachment; filename="firmware.bin"'
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Length'] = mysize
    #https://tools.ietf.org/html/rfc1864#section-2
    response['x-MD5'] = mymd5

    print "send new firmware"
    return response
Beispiel #38
0
 def validate_password(self, value):
     return make_password(value)
Beispiel #39
0
def get_random_password():
    password = User.objects.make_random_password(length=16)

    return make_password(password)
Beispiel #40
0
 def save(self, *args, **kwargs):
     self.password = make_password(self.password, None, 'pbkdf2_sha256')
     super().save(*args, **kwargs)
Beispiel #41
0
 def update_password(self, user, password):
     user.password = hashers.make_password(password)
Beispiel #42
0
def user_signup(request):
    try:

        #csrfContext = RequestContext(request)
        print "hey"
        if request.method == 'POST':
            #form = SignupForm(request.POST or None)
            #if form.is_valid():
            #password = form.cleaned_data['password']
            password = request.POST['password']
            print password
            #form.password = make_password(password)
            #pswd = form.password
            #print pswd
            #user = form.save(commit=False)
            #user.is_active = False
            #user.save()
            #userobj = form.cleaned_data
            #username = userobj['username']
            #email = userobj['email']
            #raw_password = userobj['password']
            user = register_model()
            username = request.POST['username']
            email = request.POST['email']
            user.firstname = request.POST['first_name']
            user.lastname = request.POST['last_name']
            user.username = username
            user.password = make_password(password)
            user.email = email
            user.contact_no = request.POST['contact_no']
            if not (register_model.objects.filter(username=username).exists()
                    or register_model.objects.filter(email=email).exists()):
                #user.password = make_password(password)
                pd = user.password
                print "encrpted passwd is"
                print pd
                user.save()
                current_site = get_current_site(request)
                subject = 'Activate your account.'
                message = render_to_string(
                    'user_model/acc_active_email.html', {
                        'user': user,
                        'domain': current_site.domain,
                        'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                        'token': account_activation_token.make_token(user),
                    })
                to_email = email
                email = EmailMessage(subject, message, to=[to_email])
                email.send()
                #return HttpResponse("Activation link is sent to an email, Please activate your account")
                #return render(request, 'S_W/confirmaton.html')
                context = {
                    "message":
                    "Activation link is sent to an email, Please activate your account"
                }
                return render(request, 'user_model/register.html', context)
            else:
                context = {
                    'message':
                    "Username or email exist please try something different"
                }
                return render(request, 'user_model/register.html', context)
        else:
            return render(request, 'user_model/register.html')
    except:
        #return render(request, 'user_model/error.html')
        return render(request, 'user_model/register.html')
Beispiel #43
0
 def form_valid(self, form):
     sr = form.instance
     sr.password = make_password(sr.password)  # hash password
     form.save()
     return redirect('accounts:thanks')
Beispiel #44
0
 def create(self, validated_data):
     user = CustomUser.objects.create(username=validated_data['username'],
                                      password=make_password(
                                          validated_data['password']))
     return user
 def create(self, validated_data):
     user = CustomUser(**validated_data)
     # send_email(validated_data['email'], 'Registration', 'Hi 123')
     user.password = make_password(validated_data['password'])
     user.save()
     return user.id
Beispiel #46
0
 def create_password_history(self, form, user):
     if settings.ACCOUNT_PASSWORD_USE_HISTORY:
         password = form.cleaned_data[self.form_password_field]
         PasswordHistory.objects.create(user=user,
                                        password=make_password(password))
Beispiel #47
0
 def perform_create(self, serializer):
     serializer.save(password=make_password(None))
 def set_password(self, raw_password):
     self.password = make_password(raw_password)
     self._password = raw_password
Beispiel #49
0
 def validate(self, attrs):
     attrs['password'] = make_password(attrs['password'])
     del attrs['checkpass']
     return attrs
 def set_unusable_password(self):
     # Set a value that will never be a valid hash
     self.password = make_password(None)
Beispiel #51
0
 def password(self, value):
     self.password_hash = make_password(value)
Beispiel #52
0
def password_reset_new(request):

    new_id = request.session['user_id']
    print new_id
    if new_id is not None:
        print new_id
        if request.method == 'POST':
            try:
                user = register_model.objects.get(id=new_id)
                print "User is"
                print user
            except:
                user = None
            if user is not None:
                print new_id
                old_password = request.POST['old_password']
                new_password = request.POST['new_password']
                print old_password
                print user.password
                confirm_password = make_password(old_password)
                #print password

                if (old_password == new_password):
                    print "passwords are same"
                    user.password = confirm_password
                    print user.password
                    user.is_active = True
                    user.email_confirmed = True
                    user.save()

                    context = {
                        "message": "your password is changed successfully",
                        "conn": True
                    }

                    # now redirect a page on user_login and set a sleep time of 5 sec to redirect it automaticaly
                    # ye dekhna hai apan ko kal kii kesse
                    # ki back jaaane pr session expire ho jaaaye
                    # fir wapas login page pr redirect ho and new sessions bane
                    #

                else:
                    print "passswords are not same"

                    context = {
                        "message":
                        "your password is not changed, both passwords are not same",
                    }

            else:
                print "user is none"
                # print user
                # print user.firstname
                # print user.password
                # user.password = make_password(password)
                # user.save()

                # print user.password

                # print "hey"

                context = {"message": "your password is changed successfully"}

        else:
            print "you are on secand path"

            context = {"message": "you are on wrong path"}

    else:
        context = {"message": "Please reset your password"}

    return render(request, 'user_model/reset_pass.html', context)
 def setUp(self):
     super(CheckTokenTestCase, self).setUp()
     self.profile.token = make_password("secret-token")
     self.profile.save()
Beispiel #54
0
def register_page(request):
    try:
        if request.POST:
            register_data = request.POST.dict()

            # combine data into fullname
            fname = register_data.get("fname")
            mname = register_data.get("mname")
            lname = register_data.get("lname")
            fullname = str(fname) + " " + str(mname) + " " + str(lname)

            # Finding age
            bdate = register_data.get("bdate")
            today = date.today()
            age = ""
            dob = date(int(bdate[:4]), int(bdate[5:7]), int(bdate[8:10]))
            age = today.year - dob.year - ((today.month, today.day) <
                                           (dob.month, dob.day))

            # Generating patient id
            max_id = Patient.objects.all().aggregate(
                Max('patient_id'))['patient_id__max']
            max_id = int(max_id) if max_id is not None else 0
            max_id += 1
            max_id = str(max_id).zfill(10) if max_id is not None else 1

            # Adding record into Patient table
            record, _ = Patient.objects.update_or_create(
                name=fullname,
                patient_id=max_id,
                email_id=register_data.get("email_id"),
                birth_date=bdate,
                adhaar_number=register_data.get("adhaar"),
                gender=register_data.get("gender"),
                address_1=register_data.get("add"),
                city=register_data.get("city"),
                state=register_data.get("state"),
                country=register_data.get("country"),
                pincode=register_data.get("pincode"),
                age=age,
                password=make_password(register_data.get("password")),
                permission=1)

            # Adding record phone number in PhoneNumber table
            phone_id = PhoneNumber.objects.all().aggregate(
                Max('phone_number_id'))['phone_number_id__max']
            phone_id = int(phone_id) if phone_id is not None else 0
            phone_id += 1
            phone_id = str(phone_id).zfill(10) if phone_id is not None else 1
            phone_record = PhoneNumber.objects.update_or_create(
                phone_number_id=phone_id,
                patient_id=record,
                phone_number=register_data.get("phone"))

            # setting email id variable for login
            request.session['emailid'] = register_data.get("email_id")
            return redirect('/patient/', request=request)

    except Exception as e:
        print(e)

    return render(request, 'app/registration_page.html')
Beispiel #55
0
 def update(self, request, *args, **kwargs):
     request.data["password"] = make_password(request.data["password"])
     return super().update(request, *args, **kwargs)
Beispiel #56
0
 def generate_code(self):
     code = secure_string(16)
     self.code = make_password(code)
     return code
Beispiel #57
0
 def setUp(self):
     global user_id
     password = make_password("password123")
     user = User.objects.create(username="******", password=password)
     user_id = user.id
Beispiel #58
0
def register(request):
    if 'requestcode' in request.POST.keys():  # form is filled. if not spam, generate code and save in db, wait for email confirmation, return message
        print('form is filled')
        print(request.POST)
        # is this spam? check reCaptcha
        if not grecaptcha_verify(request):  # captcha was not correct
            print('captcha error')

            context = {
                'message': 'کپچای گوگل درست وارد نشده بود. شاید ربات هستید؟ کد یا کلیک یا تشخیص عکس زیر فرم را درست پر کنید. ببخشید که فرم به شکل اولیه برنگشته!'}  # TODO: forgot password
            return render(request, 'register.html', context)

        # duplicate email
        if User.objects.filter(email=request.POST.get('email')).exists():
            print('duplicate email')
            context = {
                'message': 'متاسفانه این ایمیل قبلا استفاده شده است. در صورتی که این ایمیل شما است، از صفحه ورود گزینه فراموشی پسورد رو انتخاب کنین. ببخشید که فرم ذخیره نشده. درست می شه'  # TODO: forgot password
            }

            #TODO: Keep the form data;
            return render(request, 'register.html', context)

        # if user does not exists
        if not User.objects.filter(username=request.POST.get('username')).exists():
            code = get_random_string(length=32)
            now = datetime.now()
            email = request.POST.get('email')
            password = make_password(request.POST.get('password'))
            username = request.POST.get('username')
            temporarycode = Passwordresetcodes(email=email, time=now, code=code, username=username, password=password)
            temporarycode.save()
            #message = PMMail(api_key=settings.POSTMARK_API_TOKEN,
            #                 subject="فعالسازی اکانت بستون",
            #                 sender="*****@*****.**",
            #                 to=email,
            #                 text_body=" برای فعال کردن اکانت بستون خود روی لینک روبرو کلیک کنید: {}?code={}".format(
            #                     request.build_absolute_uri('/accounts/register/'), code),
            #                 tag="account request")
            #message.send()
            message = 'ایمیلی حاوی لینک فعال سازی اکانت به شما فرستاده شده، لطفا پس از چک کردن ایمیل، روی لینک کلیک کنید.'
            message = 'قدیم ها ایمیل فعال سازی می فرستادیم ولی الان شرکتش ما رو تحریم کرده (: پس راحت و بی دردسر'
            body = " برای فعال کردن اکانت بستون خود روی لینک روبرو کلیک کنید: <a href=\"{}?code={}\">لینک رو به رو</a> ".format(request.build_absolute_uri('/accounts/register/'), code)
            message = message + body
            context = {
                'message': message }
            return render(request, 'index.html', context)

        else:
            context = {
                'message': 'متاسفانه این نام کاربری قبلا استفاده شده است. از نام کاربری دیگری استفاده کنید. ببخشید که فرم ذخیره نشده. درست می شه'}  # TODO: forgot password
            # TODO: keep the form data
            return render(request, 'register.html', context)

    elif request.GET.get('code'): # user clicked on code
        code = request.GET.get('code')
        if Passwordresetcodes.objects.filter(code=code).exists():  # if code is in temporary db, read the data and create the user
            new_temp_user = Passwordresetcodes.objects.get(code=code)
            newuser = User.objects.create(username=new_temp_user.username, password=new_temp_user.password, email=new_temp_user.email)
            this_token = get_random_string(length=48)
            token = Token.objects.create(user=newuser, token=this_token)
            # delete the temporary activation code from db
            Passwordresetcodes.objects.filter(code=code).delete()
            context = {
                'message': 'اکانت شما ساخته شد. توکن شما {} است. آن را ذخیره کنید چون دیگر نمایش داده نخواهد شد! جدی!'.format(
                    this_token)}
            return render(request, 'index.html', context)

        else:
            context = {
                'message': 'این کد فعال سازی معتبر نیست. در صورت نیاز دوباره تلاش کنید'}
            return render(request, 'register.html', context)

    else:
        context = {'message': ''}
        return render(request, 'register.html', context)
Beispiel #59
0
    def setUpTestData(cls):
        """
        Creates departments, courses, sections and schedules from
        `/tests/plan/course_recs_test_data/course_data_test.csv`
        and `/tests/plan/course_recs_test_data/course_descriptions_test.csv`.

        The contents of `/tests/plan/course_recs_test_data/course_data_test.csv` are 3 columns:
        - a `person_id` (used when creating schedules)
        - a course `full_code` column (ie "PSCI-498")
        - a semester column (ranging between 2016C and 2020A).

        Courses are created with approximately the following specification:
        - `department_id`: Corresponds to the department code embedded in the `full_code`
        - `full_code` : corresponds to the course code column in
           `/tests/plan/course_recs_test_data/course_data_test.csv`
        - `semester` : corresponds to the semester column in
           `/tests/plan/course_recs_test_data/course_data_test.csv`. Additionally, if the value of
           the semester column in `/tests/plan/course_recs_test_data/course_data_test.csv`
           for a course is not "2020A" or "2017A" and the course `full_code` is not "HIST-650"
           another course entry is created with `semester` equal to `TEST_SEMESTER` as defined
           at the top of this file (2021C at the time of writing.)
        - `description` : corresponds to the entry in
           `/tests/plan/course_recs_test_data/course_descriptions_test.csv`

        Sections corresponding to each created course are created with approximately this
        specification
        - `code` : "001"
        - `full_code` : the course's `full_code` + "-001"
        """

        course_data_path = (
            settings.BASE_DIR +
            "/tests/plan/course_recs_test_data/course_data_test.csv")

        # Setting up test courses in the db
        test_descriptions = dict()
        with open(
                settings.BASE_DIR +
                "/tests/plan/course_recs_test_data/course_descriptions_test.csv"
        ) as course_desc_file:
            desc_reader = csv.reader(course_desc_file)
            for course, description in desc_reader:
                test_descriptions[course] = description
        courses = set()
        with open(course_data_path) as course_data_file:
            course_data_reader = csv.reader(course_data_file)
            for _, course_code, semester in course_data_reader:
                courses.add((course_code, semester))

        departments_to_save = []
        department_obs = dict()
        courses_to_save = []
        course_obs = dict()
        sections_to_save = []

        def create_dont_save(course_code, semester, iter_num):
            dept_code = course_code.split("-")[0]
            if iter_num == 0:
                if dept_code not in department_obs:
                    dept = Department(code=dept_code, name=dept_code)
                    department_obs[dept_code] = dept
                    departments_to_save.append(dept)
            elif iter_num == 1:
                dept_id = department_obs[dept_code]
                course = Course(
                    code=course_code.split("-")[1],
                    semester=semester,
                    full_code=course_code,
                    description=test_descriptions[course_code],
                )
                course.department_id = dept_id
                courses_to_save.append(course)
            elif iter_num == 2:
                course_id = course_obs[course_code, semester]
                section = Section(
                    code="001",
                    full_code=course_code + "-001",
                    credits=1,
                    status="O",
                    activity="LEC",
                )
                section.course_id = course_id
                sections_to_save.append(section)

        curr_courses = set()
        for i in range(3):
            for course_code, semester in courses:
                assert semester != TEST_SEMESTER
                create_dont_save(course_code, semester, i)
            for course_code, semester in courses:
                curr_courses.add(course_code)
            for course_code, semester in courses:
                if semester in ["2017A", "2020A"
                                ] or course_code in ["HIST-650"]:
                    curr_courses.remove(course_code)
            for course_code in curr_courses:
                create_dont_save(course_code, TEST_SEMESTER, i)
            for extra_course_code in ["CIS-121", "CIS-262"]:
                create_dont_save(extra_course_code, TEST_SEMESTER, i)
            if i == 0:
                Department.objects.bulk_create(departments_to_save)
                department_obs = dict()
                for dept in Department.objects.all():
                    department_obs[dept.code] = dept.id
            elif i == 1:
                for course in courses_to_save:
                    course.save()
                    course_obs[course.full_code, course.semester] = course.id
            elif i == 2:
                Section.objects.bulk_create(sections_to_save)

        section_obs = dict()
        for section in Section.objects.all():
            section_obs[section.full_code,
                        section.course.semester] = section.id
        cls.section_obs = section_obs

        schedules = dict()
        with open(course_data_path) as course_data_file:
            course_data_reader = csv.reader(course_data_file)
            for person_id, course_code, semester in course_data_reader:
                if person_id not in schedules:
                    schedules[person_id] = dict()
                if semester not in schedules[person_id]:
                    schedules[person_id][semester] = set()
                schedules[person_id][semester].add(course_code)

        User.objects.bulk_create([
            User(
                username=person_id,
                email=person_id + "@example.com",
                password=make_password(person_id + "_password"),
                is_active=True,
            ) for person_id in schedules.keys()
        ] + [
            User(
                username=person_id,
                email=person_id + "@example.com",
                password=make_password(person_id + "_password"),
                is_active=True,
            ) for person_id in ["freshman", "gapsem", "noshow", "repeat"]
        ])

        user_obs = dict()
        for user in User.objects.all():
            user_obs[user.username] = user.id

        # Create past schedules
        schedules_list = []
        for username in schedules.keys():
            for semester in schedules[username].keys():
                schedule = Schedule(
                    semester=semester,
                    name=username + " main schedule",
                )
                schedule.person_id = user_obs[username]
                schedules_list.append(schedule)
        Schedule.objects.bulk_create(schedules_list)
        schedule_obs = dict()
        for schedule in Schedule.objects.all():
            schedule_obs[schedule.person_id, schedule.semester] = schedule
        for username in schedules.keys():
            for semester in schedules[username].keys():
                schedule = schedule_obs[user_obs[username], semester]
                for course_code in schedules[username][semester]:
                    if course_code in ["AFRC-437", "GRMN-180", "CIS-262"]:
                        continue
                    schedule.sections.add(section_obs[course_code + "-001",
                                                      semester])

        schedule = Schedule(
            person=get_user_model().objects.get(username="******"),
            semester=TEST_SEMESTER,
            name="My Test Schedule",
        )
        schedule.save()
        for course_code in ["AFRC-437", "GRMN-180", "CIS-262"]:
            schedule.sections.add(section_obs[course_code + "-001",
                                              TEST_SEMESTER])

        cls.course_clusters = train_recommender(
            course_data_path=course_data_path, output_path=os.devnull)

        cls.course_clusters_with_schedules = train_recommender(
            course_data_path=None, output_path=os.devnull)
Beispiel #60
0
 def change_user_password(old_password=None, password=None, user=None):
     if check_password(old_password, user.password):
         user.password = make_password(password)
         user.save()
         return True
     return False