Example #1
0
def view_profile(request, user_id, **kwargs):
	query_set = User.objects.filter(id=user_id)
	if not query_set.exists():
		return view_profile(request, request.user.id, error_messages=['User with user_id='+str(user_id)+' could not be found.'])
	user = query_set[0]

	profile = None
	query_set = UserProfile.objects.filter(user=user)
	if not query_set.exists():
		profile = UserProfile()
		profile.user = user
		profile.save()
	else:
		profile = query_set[0]

	context_dict = {}

	if int(user_id) == int(request.user.id):
		context_dict = {
			'user_form': EditUserForm(initial=model_to_dict(user)),
			'profile_form': UserProfileForm(initial=model_to_dict(profile)),
			'available_backends': load_backends(settings.AUTHENTICATION_BACKENDS),
			'editing': 'editing' in kwargs and kwargs['editing'] == 'editing',
		}
	context_dict['disp_user'] = user
	context_dict['disp_user_is_sm'] = (user.is_superuser) or (Permission.objects.get(codename='site_manager') in user.user_permissions.all()) #user.has_perm('users.site_manager')

	if 'error_messages' in kwargs:
		context_dict['error_messages'] = kwargs['error_messages']

	return render(request, 'profile.html', context_dict)
Example #2
0
 def test_persona_sha512_md5_base64(self):
     md5 = hashlib.md5('password').hexdigest()
     hsh = hashlib.sha512(self.bytes_ + md5).hexdigest()
     u = UserProfile(password='******' %
                     (encodestring(self.bytes_), hsh))
     assert u.check_password('password') is True
     assert u.has_usable_password() is True
Example #3
0
def send_activation_email(request, user):
    username = user.username
    email = user.email
    salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
    activation_key = hashlib.sha1(salt + email).hexdigest()

    # Create and save user profile
    new_profile = UserProfile(user=user, activation_key=activation_key)
    new_profile.save()

    # Send email with activation key
    activation_link = request.META['HTTP_HOST'] + \
        reverse('users:confirm', kwargs={'activation_key': activation_key})
    email_subject = 'Account confirmation'
    email_body = render_to_string('index/activation_email.html',
                    {'username': username, 'activation_link': activation_link,
                    'active_time': new_profile.active_time})

    msg = EmailMultiAlternatives(email_subject, email_body, EMAIL_HOST_USER, [email])
    msg.attach_alternative(email_body, "text/html")

    try:
        Thread(target=msg.send, args=()).start()
    except:
        logger.warning("There is an error when sending email to %s's mailbox" % username)
Example #4
0
def create_user(request):
    #If the user is trying to add info to the server,
    if request.method == 'POST':
        #Feed as arguments to RegisterForm the inputs from the user.
        create_user_form = RegisterForm(request.POST)
        #If username and password are of the right length and email is of the valid form,
        #And password and confirm password identical, 
        if create_user_form.is_valid():
            #Don't save the user in creation as a new user yet. 
            new_user = create_user_form.save()
            pw = create_user_form.cleaned_data.get('password')
            new_user.set_password( pw )
            new_user.save()
 
            #Then create UserProfile object from User object.
            new_UserProfile = UserProfile(user=new_user)
            #new_UserProfile.user = new_user
            new_UserProfile.save() #Then save. 
 
            #Render a Welcome to GroupFit page if the input info is valid. 
            #No need to customize welcome page unless we want to just switch the name: Welcome, username!
            return render(request, 'welcome.html')
 
            #Send an email as well.
    else:
        #If the user didn't plug in anything, create_user_form will be an empty shell?
        create_user_form = RegisterForm()
    return render(request, 'register.html', {'create_user_form': create_user_form})
Example #5
0
def register(request):

	if request.method == 'GET':
		form = UserForm()
		greeting = 'Please register an account'

		context = {
			'form': form,
			'greeting': greeting
		}
		
		return render(request, 'users/register.html', context)

	else:
		form = UserForm(request.POST)
		
		if form.is_valid():
			user = User(username=form.cleaned_data['username'],
				email=form.cleaned_data['email'], 
				first_name=form.cleaned_data['first_name'], 
				last_name=form.cleaned_data['last_name'])
			user.set_password(form.cleaned_data['password'])
			user.save()
			profile = UserProfile(user=user)
			profile.save()
			return redirect('/login/')
		else:
			context = {
				'form': form,
				'greeting': 'Invalid fields, please check errors.'
			}
			return render(request, 'users/register.html', context)
Example #6
0
    def test_browserid_password(self):
        for source in amo.LOGIN_SOURCE_BROWSERIDS:
            u = UserProfile(password=self.utf, source=source)
            assert u.check_password('foo')

        u = UserProfile(password=self.utf, source=amo.LOGIN_SOURCE_UNKNOWN)
        assert not u.check_password('foo')
Example #7
0
 def test_persona_sha512_base64_maybe_not_latin1(self):
     passwd = u'fo\xf3'
     hsh = hashlib.sha512(self.bytes_ + passwd.encode('latin1')).hexdigest()
     u = UserProfile(password='******' %
                     (encodestring(self.bytes_), hsh))
     assert u.check_password(self.utf) is False
     assert u.has_usable_password() is True
Example #8
0
 def post(self, request, *args, **kwargs):
     user_form = UserForm(request.POST)
     user_profile_form = SignUpProfileForm(request.POST)
     if user_form.is_valid() and user_profile_form.is_valid():
         user = user_form.save()
         user_profile = UserProfile(
             user = user,
             city = user_profile_form.data['city'],
             country = user_profile_form.data['country']
         )
         try:
             user_profile.save()
             user = authenticate(
                 username=user_form.data.get('username'),
                 password=user_form.data.get('password1')
             )
             login(self.request, user)
         except:
             transaction.rollback()
         return HttpResponseRedirect(self.success_url)
     else:
         context = {}
         context['user_form'] = user_form
         context['user_profile_form'] = user_profile_form
         context['cities'] = City.objects.all()
         context['countries'] = Country.objects.all()
         return self.render_to_response(context)
Example #9
0
    def authenticate(self, **kwargs):
        """Authenticate the user based on an OpenID response."""
        # Require that the OpenID response be passed in as a keyword
        # argument, to make sure we don't match the username/password
        # calling conventions of authenticate.

        openid_response = kwargs.get('openid_response')
        if openid_response is None:
            return None

        if openid_response.status != SUCCESS:
            return None

        user = None
        try:
            user_openid = UserOpenID.objects.get(
                claimed_id__exact=openid_response.identity_url)
            log.debug("Drupal openid user resgistered already: %s" % (openid_response.identity_url,))
            return None
        except UserOpenID.DoesNotExist:
            drupal_user = drupal.get_openid_user(openid_response.identity_url)
            if drupal_user:
                user_data = drupal.get_user_data(drupal_user)
                profile = UserProfile(**user_data)
                profile.save()
                if profile.user is None:
                    profile.create_django_user()
                self.associate_openid(profile.user, openid_response)
                return profile.user
Example #10
0
 def test_is_subscribed(self):
     c = Collection.objects.get(pk=512)
     u = UserProfile()
     u.nickname = "unique"
     u.save()
     c.subscriptions.create(user=u)
     assert c.is_subscribed(u), "User isn't subscribed to collection."
def add_edit_core(request,form="",id=0):
    """
    This function calls the AddCoreForm from forms.py
    If a new core is being created, a blank form is displayed and the super user can fill in necessary details.
    If an existing core's details is being edited, the same form is displayed populated with current core details for all fields

    """
    dajax = Dajax()
    if id:
        core_form = AddCoreForm(form, instance=User.objects.get(id=id))
        if core_form.is_valid():
            core_form.save()
            dajax.script("updateSummary();")
        else:
            template = loader.get_template('ajax/admin/editcore.html')
            html=template.render(RequestContext(request,locals()))
            dajax.assign(".bbq-item",'innerHTML',html)
    else:
        core_form = AddCoreForm(form)
        if core_form.is_valid():
            core=core_form.save()
            core.set_password("default")
            core.save()
            core_profile = UserProfile( user=core, is_core=True)
            core_profile.save()
            dajax.script("updateSummary();")
        else:
            template = loader.get_template('ajax/admin/addcore.html')
            html=template.render(RequestContext(request,locals()))
            dajax.assign(".bbq-item",'innerHTML',html)
    return dajax.json()
Example #12
0
 def test_is_publisher(self):
     c = Collection()
     u = UserProfile(nickname='f')
     c.save()
     u.save()
     CollectionUser(collection=c, user=u).save()
     eq_(c.is_publisher(u), True)
Example #13
0
 def newUserProfile(self):
     """
         This method or function creates the new user along with the profile
         that is initially disabled, returns the number of the Franchisee
         which referenced where applicable.
     """
     # when the user registers with Code
     if self._validFranchiseeCode['flag'] == True and self._validFranchiseeCode['id'] >0:
         
         franchisee = UserProfile.objects.get(identification=self._validFranchiseeCode['id'])
         
         newProfile = UserProfile(
                     identification=self._user, activationKey=self._activationKey,
                     keyExpires=self._keyExpires, refFranchiseeCode=self._franchiseeCode,
                     refFranchisee=franchisee)
         #update Code in list for user; assigning values ​​necessary to use the code and date of use
         CreateCodes.objects.filter(code=self._data['franchiseeCode']).update(useFlagCode=True, dateUseFlag=datetime.datetime.now())
         
     # when the user is logged without Code
     else:
         newProfile = UserProfile(
                     identification=self._user, activationKey=self._activationKey,
                     keyExpires=self._keyExpires, refFranchiseeCode=None)
     
     # Save the profile
     newProfile.save()
def register_post_fb(request):
    """
        This is the user registration view for fb
    """
    form = FacebookUserForm(request.POST)
    facebook_id = request.POST['facebook_id']
    access_token = request.POST['access_token']
    if form.is_valid():
        data = form.cleaned_data
        new_user = User(first_name = data['first_name'], last_name=data['last_name'], username= data['username'], email = data['email'])
        new_user.set_password('default')
        new_user.save()
        userprofile = UserProfile(
                user = new_user,
                gender     = data['gender'],
                age = data['age'],
                branch = data['branch'],
                mobile_number = data['mobile_number'],
                college = data['college'],
                college_roll = data['college_roll'],
                facebook_id = facebook_id,
                access_token = access_token,
                )
        userprofile.save()
        new_user = authenticate(username = data['username'], password = "******")
        auth_login(request, new_user)
        return HttpResponseRedirect(settings.SITE_URL)
    return render_to_response('users/register.html', locals(), context_instance = RequestContext(request))
Example #15
0
def test_users_list_truncate_display_name():
    u = UserProfile(username='******',
                    display_name='Some Very Long Display Name', pk=1)
    truncated_list = users_list([u], None, 10)
    eq_(truncated_list,
        u'<a href="%s" title="%s">Some Very...</a>' % (u.get_url_path(),
                                                       u.name))
Example #16
0
def send_forget_password_email(request, user):
    username = user.username
    email = user.email
    salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
    activation_key = hashlib.sha1(salt + email).hexdigest()
    # Create and save user profile
    UserProfile.objects.filter(user=user).delete()
    new_profile = UserProfile(user=user, activation_key=activation_key)
    new_profile.save()

    # Send email with activation key
    profile_link = request.META["HTTP_HOST"] + reverse(
        "users:forget_password_confirm", kwargs={"activation_key": activation_key}
    )
    email_subject = "Password Reset"
    email_body = render_to_string(
        "index/forget_password_email.html",
        {"username": username, "profile_link": profile_link, "active_time": new_profile.active_time},
    )
    msg = EmailMultiAlternatives(email_subject, email_body, EMAIL_HOST_USER, [email])
    msg.attach_alternative(email_body, "text/html")

    try:
        Thread(target=msg.send, args=()).start()
    except:
        logger.warning("There is an error when sending email to %s's mailbox" % username)
Example #17
0
def send_forget_password_email(request, user):
    username = user.username
    email = user.email
    salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
    activation_key = hashlib.sha1(salt+email).hexdigest()
    
    #Create and save user profile
    UserProfile.objects.filter(account=user).delete()
    new_profile = UserProfile(account=user, activation_key=activation_key)
    new_profile.save()

    # Send email with activation key
    profile_link = request.META['HTTP_HOST'] + \
        reverse('users:forget_password_confirm', kwargs={'activation_key': activation_key})
    email_subject = 'Password Reset'
    email_body = render_to_string('index/forget_password_email.html',
                    {'username': username, 'profile_link': profile_link,
                    'active_time': new_profile.active_time})
    msg = EmailMultiAlternatives(email_subject, email_body, settings.EMAIL_HOST_USER, [email])
    msg.attach_alternative(email_body, "text/html")

    try:
        Thread(target=msg.send, args=()).start()
    except:
        print ("There is an error when sending email to %s's mailbox" % username)
Example #18
0
def test_user_link_unicode():
    """make sure helper won't choke on unicode input"""
    u = UserProfile(username=u'jmüller', display_name=u'Jürgen Müller', pk=1)
    eq_(user_link(u), u'<a href="%s">Jürgen Müller</a>' % u.get_url_path())

    u = UserProfile(username='******', pk=1)
    eq_(user_link(u),
        u'<a href="%s">%s</a>' % (u.get_url_path(), u.username))
Example #19
0
 def test_valid_old_password(self):
     hsh = hashlib.md5('sekrit').hexdigest()
     u = UserProfile(password=hsh)
     assert u.check_password('sekrit') is True
     # Make sure we updated the old password.
     algo, salt, hsh = u.password.split('$')
     eq_(algo, 'sha512')
     eq_(hsh, get_hexdigest(algo, salt, 'sekrit'))
Example #20
0
def test_user_link():
    u = UserProfile(username='******', display_name='John Connor', pk=1)
    eq_(user_link(u),
        '<a href="%s" title="%s">John Connor</a>' % (u.get_url_path(),
                                                     u.name))

    # handle None gracefully
    eq_(user_link(None), '')
Example #21
0
 def test_valid_old_password(self):
     hsh = hashlib.md5(encoding.smart_str(self.utf)).hexdigest()
     u = UserProfile(password=hsh)
     assert u.check_password(self.utf) is True
     # Make sure we updated the old password.
     algo, salt, hsh = u.password.split('$')
     eq_(algo, 'sha512')
     eq_(hsh, get_hexdigest(algo, salt, self.utf))
Example #22
0
 def _make_admin_user(self, email):
     """
     Create a user with at least one admin privilege.
     """
     p = UserProfile(username="******", email=email, password="******", created=datetime.now(), pk=998)
     p.create_django_user()
     admingroup = Group.objects.create(rules="Users:Edit")
     GroupUser.objects.create(group=admingroup, user=p)
Example #23
0
def create_profile(backend, user, response, *args, **kwargs):
    if UserProfile.objects.filter(user=user).exists():
        profile = UserProfile.objects.get(user=user)
        return
    else:
        profile = UserProfile(user=user, city='', country='')
        profile.save()
        return
Example #24
0
 def setUp(self):
     u = UserProfile(username='******')
     u.save()
     t = Tag(tag_text='donkeybuttrhino')
     t.save()
     a = Addon.objects.all()[0]
     at = AddonTag(tag=t, user=u, addon=a)
     at.save()
     super(TagTest, self).setUp()
Example #25
0
def register_api(request):
	staffID = request.POST['id']
	username = request.POST['username']
	password = request.POST['password']
	role = request.POST['role']
	user = User.objects.create_user(username, '*****@*****.**', password)
	user.save()
	u_p = UserProfile(user = user, staff_id=staffID, role=role)
	u_p.save()
	return redirect('/')
Example #26
0
    def test_user_orgs(self):
        user = UserProfile(user=self.user1, mnemonic='user1', created_by=self.user1, updated_by=self.user1)
        user.full_clean()
        user.save()

        self.assertEquals(0, user.orgs)
        user.organizations.append(1)
        self.assertEquals(1, user.orgs)
        user.organizations.remove(1)
        self.assertEquals(0, user.orgs)
Example #27
0
    def test_resetcode_expires(self):
        """
        For some reason resetcode is required, and we default it to
        '0000-00-00 00:00' in mysql, but that doesn't fly in Django since it's
        an invalid date.  If Django reads this from the db, it interprets this
        as resetcode_expires as None
        """

        u = UserProfile(username="******", pk=2, resetcode_expires=None, email="*****@*****.**")
        u.save()
        assert u.resetcode_expires
Example #28
0
def test_user_link_xss():
    u = UserProfile(username='******',
                    display_name='<script>alert(1)</script>', pk=1)
    html = "&lt;script&gt;alert(1)&lt;/script&gt;"
    eq_(user_link(u), '<a href="%s" title="%s">%s</a>' % (u.get_url_path(),
                                                          html, html))

    u = UserProfile(username='******',
                    display_name="""xss"'><iframe onload=alert(3)>""", pk=1)
    html = """xss&#34;&#39;&gt;&lt;iframe onload=alert(3)&gt;"""
    eq_(user_link(u), '<a href="%s" title="%s">%s</a>' % (u.get_url_path(),
                                                          html, html))
Example #29
0
 def post(self,request):
     submitted_username = request.POST['username']
     submitted_password = request.POST['password']
     new_user = User.objects.create_user(username = submitted_username, password = submitted_password)
     if new_user:
         new_user_profile = UserProfile(user=new_user)
         new_user_profile.save()
         authenticated_user = authenticate(username=submitted_username,password=submitted_password)
         login(request,authenticated_user)
         active_user_dict = User.objects.filter(id = int(authenticated_user.id))[0].to_json()
         return JsonResponse({'Success':True})
     return JsonResponse({'Success':False})
Example #30
0
 def test_user_log_as_argument(self):
     """
     Tests that a user that has something done to them gets into the user
     log.
     """
     u = UserProfile(username='******')
     u.save()
     amo.log(amo.LOG['ADD_USER_WITH_ROLE'],
             u, 'developer', Addon.objects.get())
     entries = ActivityLog.objects.for_user(self.request.amo_user)
     eq_(len(entries), 1)
     entries = ActivityLog.objects.for_user(u)
     eq_(len(entries), 1)
Example #31
0
 def test_invalid_old_password(self):
     u = UserProfile(password=self.utf)
     assert u.check_password(self.utf) is False
Example #32
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')))
Example #33
0
 def test_persona_sha512_base64_maybe_not_latin1(self):
     passwd = u'fo\xf3'
     hsh = hashlib.sha512(self.bytes_ + passwd.encode('latin1')).hexdigest()
     u = UserProfile(password='******' %
                     (encodestring(self.bytes_), hsh))
     assert u.check_password(self.utf) is False
Example #34
0
 def setUp(self):
     user = UserProfile()
     user.username = '******'
     user.nick_name = 'hyh'
     user.password = '******'
     user.is_superuser = 0
     user.first_name = 'huo'
     user.last_name = 'yinghui'
     user.email = '*****@*****.**'
     print(user)
     user.save()
Example #35
0
def test_user_link_xss():
    u = UserProfile(username='******',
                    display_name='<script>alert(1)</script>',
                    pk=1)
    html = "&lt;script&gt;alert(1)&lt;/script&gt;"
    eq_(user_link(u), '<a href="%s">%s</a>' % (u.get_url_path(), html))
Example #36
0
    def post(self, request):
        if request.user.is_authenticated():
            cursor = connection.cursor()
            if len(request.FILES) == 0:
                return render(request, "student_manage.html",
                              {"msg": u"请上传一个文件。"})

            excel = request.FILES['excel']
            data = []
            # 处理Excel
            wb = xlrd.open_workbook(filename=None, file_contents=excel.read())
            ws = wb.sheets()[0]
            nrows = ws.nrows
            for i in range(1, nrows):
                data.append(ws.row_values(i))

            success = 0
            repeat = 0
            invalid = 0
            for xm, xh, bj in data:
                if xm == '' or xh == '' or bj == '':
                    invalid += 1
                    continue
                first_name = xm[0]
                last_name = xm[1:]
                xh = str(int(xh))
                bj = str(int(bj))
                sql = "select count(1) from users_userprofile where username = '******'"
                cursor.execute(sql)
                count = cursor.fetchone()
                if count[0] == 0:
                    # 注册用户
                    user_profile = UserProfile()
                    user_profile.username = str(xh)
                    user_profile.nick_name = xm
                    user_profile.first_name = first_name
                    user_profile.last_name = last_name
                    user_profile.email = ""
                    user_profile.user_class = bj
                    user_profile.is_active = True
                    user_profile.role = 1
                    user_profile.password = make_password(xh)
                    user_profile.save()
                    success += 1
                else:
                    repeat += 1
            repeat_msg = ''
            if repeat > 0:
                repeat_msg = '另' + str(repeat) + '条已存在。'
            if invalid > 0:
                repeat_msg += str(invalid) + '条数据因缺失项无效。'
            return render(request, "student_manage_ok.html", {
                "insert_total": success,
                "repeat_msg": repeat_msg
            })
        else:
            return render(request, "login.html", {"msg": u'请先登录。'})
 def authenticate(self, token):
     firebase_user = verify_token(token)
     if not firebase_user:
         return None
     try:
         profile = UserProfile.objects.get(
             firebase_uid=firebase_user['uid'])
         if firebase_user.get('email'):
             profile.email = firebase_user.get('email')
             profile.username = firebase_user.get('email')
         if firebase_user.get('phone_number'):
             profile.phone = firebase_user.get('phone_number')
             profile.username = firebase_user.get('phone_number')
         if firebase_user.get('name') and not profile.first_name:
             profile.first_name = firebase_user.get('name').split(' ')[0]
             profile.last_name = ' '.join(
                 firebase_user.get('name').split(' ')[1:])
         profile.signedup_on = timezone.now()
         profile.anonymous = False
         profile.firebase_signin_provider = firebase_user['firebase'][
             'sign_in_provider']
         profile.save()
     except UserProfile.DoesNotExist:
         try:
             if firebase_user.get('phone_number'):
                 profile = UserProfile.objects.get(
                     phone=firebase_user.get('phone_number'),
                     firebase_uid__isnull=True)
                 if firebase_user.get('email'):
                     profile.email = firebase_user.get('email')
                 if firebase_user.get('name') and not profile.first_name:
                     profile.first_name = firebase_user.get('name').split(
                         ' ')[0]
                     profile.last_name = ' '.join(
                         firebase_user.get('name').split(' ')[1:])
             elif firebase_user.get('email'):
                 profile = UserProfile.objects.get(
                     email=firebase_user.get('email'),
                     firebase_uid__isnull=True)
                 if firebase_user.get('phone_number'):
                     profile.phone = firebase_user.get('phone_number')
             else:
                 raise UserProfile.DoesNotExist
             profile.firebase_uid = firebase_user['uid']
         except UserProfile.DoesNotExist:
             # username = firebase_user.get('phone_number') or firebase_user.get('email') or firebase_user['uid']
             profile = UserProfile(firebase_uid=firebase_user['uid'],
                                   phone=firebase_user.get('phone_number'))
             if firebase_user.get('email'):
                 profile.email = firebase_user.get('email')
             if firebase_user.get('name') and not profile.first_name:
                 profile.first_name = firebase_user.get('name').split(
                     ' ')[0]
                 profile.last_name = ' '.join(
                     firebase_user.get('name').split(' ')[1:])
         profile.firebase_signin_provider = firebase_user['firebase'][
             'sign_in_provider']
         try:
             profile.save()
         except IntegrityError:
             profile = UserProfile.objects.get(
                 firebase_uid=firebase_user['uid'])
     return profile
Example #38
0
 def test_persona_sha512_base64_maybe_utf8(self):
     hsh = hashlib.sha512(self.bytes_ + self.utf.encode('utf8')).hexdigest()
     u = UserProfile(password='******' %
                     (encodestring(self.bytes_), hsh))
     assert u.check_password(self.utf) is True
     assert u.has_usable_password() is True
Example #39
0
 def test_persona_sha512_base64(self):
     hsh = hashlib.sha512(self.bytes_ + 'password').hexdigest()
     u = UserProfile(password='******' %
                     (encodestring(self.bytes_), hsh))
     assert u.check_password('password') is True
     assert u.has_usable_password() is True
Example #40
0
def patient_csv_export_view(request, queryset):
    response = HttpResponse(content_type='text/csv')
    now = datetime.now()

    response[
        'Content-Disposition'] = 'attachment; filename="test-report-%s.csv"' % now.timestamp(
        )
    writer = csv.writer(response)
    # Create the HttpResponse object with the appropriate CSV header.
    writer.writerow(patient_csv_header)

    for test in queryset.all():
        date_of_birth, gender, street_address, city, state, zip_code = '', '', '', '', '', ''
        county, contact_number, last_name, first_name, patient_race, patient_ethnicity = '', '', '', '', '', ''
        user = test.acuity_appointment.user if test.acuity_appointment else User(
        )
        user_profile = user.user_profile if hasattr(
            user, 'user_profile') else UserProfile()

        if test.acuity_appointment:
            appointment = test.acuity_appointment
            date_of_birth = get_form_value(
                appointment.appointment_data.get("forms", {}))
            gender = get_form_value(
                appointment.appointment_data.get("forms", {}), 8666022)
            zip_code = get_form_value(
                appointment.appointment_data.get("forms", {}), 8666034)
            contact_number = appointment.appointment_data.get('phone')
            street_address = get_form_value(
                appointment.appointment_data.get("forms", {}), 8911198)
            city = get_form_value(
                appointment.appointment_data.get("forms", {}), 8974651)
            state = get_form_value(
                appointment.appointment_data.get("forms", {}), 8974657)
            first_name = appointment.appointment_data.get('firstName')
            last_name = appointment.appointment_data.get('lastName')
            patient_race = get_form_value(
                appointment.appointment_data.get("forms", {}), 9257182)
            patient_ethnicity = get_form_value(
                appointment.appointment_data.get("forms", {}), 9257184)

        data = {
            18: first_name or user.first_name,
            19: last_name or user.last_name,
            21: gender or user_profile.gender,  # Sex at Birth
            22: date_of_birth or user_profile.date_of_birth,  # Date of Birth
            25: street_address
            or user_profile.street_address,  # Patient Street Address
            26: city,  # Patient City
            27: state,  # Patent State
            28: zip_code or user_profile.zip_code,  # Patient Zip code
            29: county,  # Patient County of Residence
            30: contact_number
            or user_profile.contact_number,  # Patient Phone Number
            35: patient_race,  # 'Patient Race'
            37: patient_ethnicity,  # 'Patient Ethnicity'
            41: test.test_type.first().type_name,  # Test Name
            43: test.get_specimen_type_display(),  # Specimen Type
            44: test.get_result_display(),  # Test Result
            45: test.collection_date,  # Specimen Collection date
        }
        row_data = get_csv_row(data)
        writer.writerow(row_data)

    return response
Example #41
0
 def test_browserid_password(self):
     u = UserProfile(password=self.utf, source=amo.LOGIN_SOURCE_UNKNOWN)
     assert not u.check_password('foo')
     assert u.has_usable_password() is True
Example #42
0
def patient_csv_export_pcr_view(request, queryset):
    response = HttpResponse(content_type='text/csv')
    now = datetime.now()

    response[
        'Content-Disposition'] = 'attachment; filename="test-report-%s.csv"' % now.timestamp(
        )
    writer = csv.writer(response)
    # Create the HttpResponse object with the appropriate CSV header.
    writer.writerow(patient_csv_header_pcr)

    for test in queryset.all():
        date_of_birth, gender, street_address, city, state, zip_code = '', '', '', '', '', ''
        county, contact_number, last_name, first_name, patient_race, patient_ethnicity = '', '', '', '', '', ''
        test_result = test.get_result_display()
        collection_date = test.collection_date
        received_date = test.processed_date.strftime(
            "%Y-%m-%d") if test.processed_date else ''
        result_date = test.processed_date.strftime(
            "%Y-%m-%d") if test.processed_date else ''
        collection_location = test.location
        user = test.acuity_appointment.user if test.acuity_appointment else User(
        )
        user_profile = user.user_profile if hasattr(
            user, 'user_profile') else UserProfile()
        acuity_appointment_id = ''
        if test.acuity_appointment:
            appointment = test.acuity_appointment
            acuity_appointment_id = appointment.acuity_appointment_id
            date_of_birth = get_form_value(
                appointment.appointment_data.get("forms", {}))
            gender = get_form_value(
                appointment.appointment_data.get("forms", {}), 8666022)
            zip_code = get_form_value(
                appointment.appointment_data.get("forms", {}), 8666034)
            contact_number = appointment.appointment_data.get('phone')
            street_address = get_form_value(
                appointment.appointment_data.get("forms", {}), 8911198)
            city = get_form_value(
                appointment.appointment_data.get("forms", {}), 8974651)
            state = get_form_value(
                appointment.appointment_data.get("forms", {}), 8974657)
            first_name = appointment.appointment_data.get('firstName')
            last_name = appointment.appointment_data.get('lastName')
            patient_race = get_form_value(
                appointment.appointment_data.get("forms", {}), 9257182)
            patient_ethnicity = get_form_value(
                appointment.appointment_data.get("forms", {}), 9257184)

        data = {
            1: acuity_appointment_id,
            2: first_name or user.first_name,
            3: last_name or user.last_name,
            4: date_of_birth or user_profile.date_of_birth,  # Date of Birth
            5: gender or user_profile.gender,  # Sex at Birth
            6: street_address,  # Street Address
            7: city,  # City
            8: state,  # State # Todo: fetch state from acuity data
            9: zip_code,  # zip code
            10: patient_race,  # Race
            11: patient_ethnicity,  # Patient Ethnicity
            12: collection_date,  # Collection date
            13: received_date,  # Received date
            14: result_date,  # Result date
            15: test_result,  # Test result
            16: collection_location,  # Collection location
            17: contact_number,  # Patient Telephone
            18: county
        }
        row_data = get_csv_row_pcr(data)
        writer.writerow(row_data)

    return response
Example #43
0
 def test_empty_password(self):
     profile = UserProfile(password=None)
     assert profile.has_usable_password() is False
     profile = UserProfile(password='')
     assert profile.has_usable_password() is False
Example #44
0
 def setUp(self):
     self.user = UserProfile()
Example #45
0
def auth_receive(request):
    if 's' in request.GET and request.GET['s'] == "logout":
        # This was a logout request
        return HttpResponseRedirect('/')

    if 'i' not in request.GET:
        return HttpResponse("Missing IV in url!", status=400)
    if 'd' not in request.GET:
        return HttpResponse("Missing data in url!", status=400)

    # Set up an AES object and decrypt the data we received
    decryptor = AES.new(base64.b64decode(settings.PGAUTH_KEY), AES.MODE_CBC,
                        base64.b64decode(str(request.GET['i']), "-_"))
    s = decryptor.decrypt(base64.b64decode(str(request.GET['d']),
                                           "-_")).rstrip(' ')

    # Now un-urlencode it
    try:
        data = urlparse.parse_qs(s, strict_parsing=True)
    except ValueError:
        return HttpResponse("Invalid encrypted data received.", status=400)

    # Check the timestamp in the authentication
    if (int(data['t'][0]) < time.time() - 10):
        return HttpResponse("Authentication token too old.", status=400)

    # Update the user record (if any)
    try:
        user = User.objects.get(username=data['u'][0])
        # User found, let's see if any important fields have changed
        changed = False
        if user.first_name != data['f'][0]:
            user.first_name = data['f'][0]
            changed = True
        if user.last_name != data['l'][0]:
            user.last_name = data['l'][0]
            changed = True
        if user.email != data['e'][0]:
            user.email = data['e'][0]
            changed = True
        if changed:
            user.save()
    except User.DoesNotExist:
        # User not found, create it!

        # NOTE! We have some legacy users where there is a user in
        # the database with a different userid. Instead of trying to
        # somehow fix that live, give a proper error message and
        # have somebody look at it manually.
        if User.objects.filter(email=data['e'][0]).exists():
            return HttpResponse(
                """A user with email %s already exists, but with
a different username than %s.

This is almost certainly caused by some legacy data in our database.
Please send an email to [email protected], indicating the username
and email address from above, and we'll manually merge the two accounts
for you.

We apologize for the inconvenience.
""" % (data['e'][0], data['u'][0]),
                content_type='text/plain')

        user = User(
            username=data['u'][0],
            first_name=data['f'][0],
            last_name=data['l'][0],
            email=data['e'][0],
            password='******',
        )
        user.save()

    # Ok, we have a proper user record. Now tell django that
    # we're authenticated so it persists it in the session. Before
    # we do that, we have to annotate it with the backend information.
    user.backend = "%s.%s" % (AuthBackend.__module__, AuthBackend.__name__)
    django_login(request, user)

    # Finally, check of we have a data package that tells us where to
    # redirect the user.
    if 'd' in data:
        (ivs, datas) = data['d'][0].split('$')
        decryptor = AES.new(
            SHA.new(settings.SECRET_KEY).digest()[:16], AES.MODE_CBC,
            base64.b64decode(ivs, "-_"))
        s = decryptor.decrypt(base64.b64decode(datas, "-_")).rstrip(' ')
        try:
            rdata = urlparse.parse_qs(s, strict_parsing=True)
        except ValueError:
            return HttpResponse("Invalid encrypted data received.", status=400)
        if 'r' in rdata:
            # Redirect address
            return HttpResponseRedirect(rdata['r'][0])
    # No redirect specified, see if we have it in our settings
    if hasattr(settings, 'PGAUTH_REDIRECT_SUCCESS'):
        return HttpResponseRedirect(settings.PGAUTH_REDIRECT_SUCCESS)
    return HttpResponse(
        "Authentication successful, but don't know where to "
        "redirect!",
        status=500)
Example #46
0
 def test_persona_sha512_md5(self):
     md5 = hashlib.md5('password').hexdigest()
     hsh = hashlib.sha512(self.bytes_ + md5).hexdigest()
     u = UserProfile(password='******' % (self.bytes_, hsh))
     assert u.check_password('password') is True
     assert u.has_usable_password() is True
Example #47
0
class TestDrumbeatMail(test_utils.TestCase):

    test_username = '******'
    test_password = '******'
    test_email = '*****@*****.**'

    def setUp(self):
        self.locale = 'en-US'
        self.user = UserProfile(username=self.test_username,
                                email=self.test_email)
        self.user.set_password(self.test_password)
        self.user.save()
        self.user.create_django_user()

        self.user_two = UserProfile(username='******',
                                    email='*****@*****.**')
        self.user_two.set_password('testpassword')
        self.user_two.save()
        self.user_two.create_django_user()

    def test_messaging_user_following(self):
        print "From test: %s" % (self.user.user, )
        print "From test: %s" % (self.user_two.user, )
        Relationship(source=self.user_two, target_user=self.user).save()
        form = ComposeForm(data={
            'recipient': self.user_two,
            'subject': 'Foo',
            'body': 'Bar',
        },
                           sender=self.user)
        self.assertTrue(form.is_bound)
        self.assertTrue(form.is_valid())

    def test_messaging_user_following_project(self):
        project = Project(name='test project',
                          short_description='abcd',
                          long_description='edfgh',
                          created_by=self.user)
        project.save()
        Relationship(source=self.user_two, target_project=project).save()
        form = ComposeForm(data={
            'recipient': self.user_two,
            'subject': 'Foo',
            'body': 'Bar',
        },
                           sender=self.user)
        self.assertTrue(form.is_bound)
        self.assertTrue(form.is_valid())

    def test_view_message(self):
        """Test user can view message in inbox."""
        Relationship(source=self.user, target_user=self.user_two).save()
        message = Message(sender=self.user_two.user,
                          recipient=self.user.user,
                          subject='test message subject',
                          body='test message body')
        message.save()
        self.client.login(username=self.test_username,
                          password=self.test_password)
        response = self.client.get("/%s/messages/inbox/" % (self.locale, ))
        self.assertContains(response, 'test message body')
Example #48
0
 def test_valid_new_password(self):
     u = UserProfile()
     u.set_password(self.utf)
     assert u.check_password(self.utf) is True
     assert u.has_usable_password() is True
Example #49
0
    def post(self, request, *args, **kwargs):
        UserProfile.create_or_update(user=request.user,
                                     avatar=request.FILES.get("avatar"))

        return JsonResponse({"message": "Avatar set"},
                            status=status.HTTP_200_OK)
Example #50
0
 def test_invalid_new_password(self):
     u = UserProfile()
     u.set_password(self.utf)
     assert u.check_password('wrong') is False
     assert u.has_usable_password() is True
Example #51
0
    def post(self, request):
        # data = json.load(request.body) # postman에서 raw로 받을 때 사용...
        data = request.data
        user_type = "GENERAL"
        email = data['email']
        password = data['password']
        nickname = data['nickname']

        try:

            if email == "" or password == "" or nickname == "":
                return Response({"message": "빈 칸 없이 모두 입력해 주시기 바랍니다."},
                                status=status.HTTP_400_BAD_REQUEST)

            if len(password) >= 6:
                password = bcrypt.hashpw(password.encode('utf-8'),
                                         bcrypt.gensalt())
            else:
                return Response({"message": "password는 최소 6글자 이상이어야 합니다."},
                                status=status.HTTP_400_BAD_REQUEST)

            validate_email(email)

            user_create = User(user_type=user_type,
                               email=email,
                               password=password,
                               nickname=nickname)
            print("여기")
            user_create.save()

        except ValidationError as e:
            print(e)
            return Response({"message": "유효하지 않은 email입니다."},
                            status=status.HTTP_400_BAD_REQUEST)

        except IntegrityError as e:
            if 'UNIQUE OF USER' in e.args[1]:
                return Response({"message": "이미 존재하는 email입니다."},
                                status=status.HTTP_400_BAD_REQUEST)
            if 'nickname' in e.args[1]:
                return Response({"message": "이미 존재하는 nickname입니다."},
                                status=status.HTTP_400_BAD_REQUEST)

        # 새로운 계정이 생성됨과 동시에 해당 계정의 프로필도 생성한다.
        new_user = User.objects.get(nickname=nickname)
        new_user_id = new_user.id
        new_profile = UserProfile(
            user_id=new_user_id,
            name=randstr(45))  # 추후 이메일 인증을 위해 유저 프로필 이름에 랜덤값 삽입
        new_profile.save()

        # 이메일 인증 준비
        current_site = get_current_site(request)  # localhost:8000
        message = render_to_string(
            'users/user_active_email.html', {
                'domain': current_site.domain,
                'activate_token': new_user.profile.name,
            })

        # 가입 인증 이메일 전송
        mail_subject = "[90Insta] 회원가입 인증 E-mail 입니다."
        user_email = new_user.email
        email = EmailMessage(mail_subject, message, to=[user_email])
        email.send()

        return Response({"message": "회원 가입 완료"},
                        status=status.HTTP_201_CREATED)
Example #52
0
 def test_invalid_old_password(self):
     u = UserProfile(password=self.utf)
     assert u.check_password(self.utf) is False
     assert u.has_usable_password() is True
Example #53
0
def test_user_data():
    u = user_data(UserProfile(username='******', pk=1))
    eq_(u['anonymous'], False)
Example #54
0
 def test_persona_sha512_md5_base64(self):
     md5 = hashlib.md5('password').hexdigest()
     hsh = hashlib.sha512(self.bytes_ + md5).hexdigest()
     u = UserProfile(password='******' %
                     (encodestring(self.bytes_), hsh))
     assert u.check_password('password') is True
Example #55
0
 def test_get_unfiltered_manager(self):
     Addon.get_unfiltered_manager() == Addon.unfiltered
     UserProfile.get_unfiltered_manager() == UserProfile.objects
Example #56
0
def test_user_link():
    u = UserProfile(username='******', display_name='John Connor', pk=1)
    eq_(user_link(u), '<a href="%s">John Connor</a>' % u.get_url_path())

    # handle None gracefully
    eq_(user_link(None), '')
Example #57
0
def test_user_link_xss():
    u = UserProfile(username='******',
                    display_name='<script>alert(1)</script>', pk=1)
    url = reverse('users.profile', args=[1])
    html = "&lt;script&gt;alert(1)&lt;/script&gt;"
    eq_(user_link(u), '<a href="%s">%s</a>' % (url, html))
Example #58
0
def process(request):
    '''
	Processes the form submitted in registration.
	'''
    # Get request's context
    context = RequestContext(request)

    if request.method == 'POST':
        # Initialize an error list to send back to the registration page if needed
        errors = []

        # Pull all of the post variables submitted in the form
        username = request.POST.get('username')
        first = request.POST.get('first')
        last = request.POST.get('last')
        phone = request.POST.get('phone')
        password1 = request.POST.get('password1')
        password2 = request.POST.get('password2')
        school = request.POST.get('school')
        print "School" + str(school)

        # Make sure passwords match
        match = passwords_match(password1, password2)

        # Make sure user object w/ submitted username does not already exist
        user_exists = False

        for u in User.objects.all():
            if u.username == username:
                user_exists = True

        # Make the phone, first, and last variables clean
        clean_user = clean_email(username)
        clean_first = clean(first)
        clean_last = clean(last)
        clean_num = clean_phone(phone)

        if (match == True) and (user_exists == False) and (
                clean_num != False) and (clean_first != False) and (
                    clean_last != False) and (clean_email != False):
            # Construct the new object
            user_to_add = User(username=clean_user,
                               first_name=clean_first,
                               last_name=clean_last)

            # And the password
            user_to_add.set_password(password1)

            # Save the new user into the database
            user_to_add.save()

            # Now add the new user profile
            user_profile_to_add = UserProfile(
                user=user_to_add,
                phone=clean_num,
                school=School.objects.get(id=school))

            # Save the user profile
            user_profile_to_add.save()

            # Send user profile's ID to the add payment view
            user_to_add = user_to_add.id

            return render_to_response('add_payment.html',
                                      {'user_to_add': user_to_add}, context)

        else:

            # Get list of all schools to pass through to the view
            schools = School.objects.all()

            # Check to see what errors are being thrown
            if (match == False):
                errors.append("Your passwords do not match.")
            if (clean_user == False):
                errors.append("Please enter a valid email.")
            if (user_exists == True):
                errors.append("This user already exists.")
            if (clean_num == False):
                errors.append("Please enter a valid phone number.")
            if (clean_first == False) or (clean_last == False):
                errors.append("Please enter a first and last name.")

            # Return original register template, with errors listed
            return render_to_response("register.html", {
                'schools': schools,
                'errors': errors
            }, context)

    return register(request)
Example #59
0
 def setUp(self):
     u = UserProfile(username='******')
     u.save()
     self.request = Mock()
     self.request.amo_user = self.user = u
     amo.set_user(u)
Example #60
0
 def test_empty_query_search(self):
     """Make sure the search method works with an empty query"""
     assert UserProfile.search('').count()