Example #1
0
    def test_needs_tougher_password(self, action_allowed_user):
        for source in amo.LOGIN_SOURCE_BROWSERIDS:
            u = UserProfile(password=self.utf, source=source)
            assert not u.needs_tougher_password

        u = UserProfile(password=self.utf, source=amo.LOGIN_SOURCE_UNKNOWN)
        assert u.needs_tougher_password
Example #2
0
class ToolModelTest(TestCase):
    user1 = User(username="******")
    profile1 = UserProfile(postal_code=14564, user=user1)
    user2 = User(username="******")
    profile2 = UserProfile(postal_code=14564, user=user2)
    user3 = User(username="******")
    profile3 = UserProfile(postal_code=14564, user=user3)

    def test_is_available_with_borrower(self):
        """
        Tool.is_available() should return false if it has a borrower.
        """
        tool = Tool(name="test", owner=self.profile1, borrower=self.profile2)
        self.assertEqual(tool.is_available(), False)

    def test_is_available_without_borrower(self):
        """
        Tool.is_available() should return true if it has no borrower.
        """
        tool = Tool(name="test", owner=self.profile1, borrower=None)
        self.assertEqual(tool.is_available(), True)

    def test_tool_borrow_with_existing_borrower(self):
        """
        borrow_tool should return false if the tool is already has a borrower
        """
        tool = Tool(name="test", owner=self.profile1, borrower=self.profile2)
        self.assertEqual(tool.borrow_tool(self.profile3), False)

    def test_tool_borrow_with_no_existing_borrower(self):
        """
        borrow_tool should return false if the tool is already has a borrower
        """
        tool = Tool(name="test", owner=self.profile1, borrower=None)
        self.assertEqual(tool.borrow_tool(self.profile2), True)
Example #3
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 #4
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()
Example #5
0
def test_users_list():
    u1 = UserProfile(username='******', display_name='John Connor', pk=1)
    u2 = UserProfile(username='******', display_name='Sarah Connor', pk=2)
    eq_(users_list([u1, u2]), ', '.join((user_link(u1), user_link(u2))))

    # handle None gracefully
    eq_(user_link(None), '')
Example #6
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 #7
0
    def test_activate_locale(self):
        eq_(translation.get_language(), 'en-us')
        with UserProfile(username='******').activate_lang():
            eq_(translation.get_language(), 'en-us')

        with UserProfile(username='******', lang='fr').activate_lang():
            eq_(translation.get_language(), 'fr')
Example #8
0
 def test_welcome_name(self):
     u1 = UserProfile(username='******')
     u2 = UserProfile(username='******', display_name="Sarah Connor")
     u3 = UserProfile()
     eq_(u1.welcome_name, 'sc')
     eq_(u2.welcome_name, 'Sarah Connor')
     eq_(u3.welcome_name, '')
Example #9
0
def test_short_users_list():
    """Test the option to shortened the users list to a certain size."""
    # short list with 'others'
    u1 = UserProfile(username='******', display_name='Oscar the Grouch', pk=1)
    u2 = UserProfile(username='******', display_name='Grover', pk=2)
    u3 = UserProfile(username='******', display_name='Cookie Monster', pk=3)
    shortlist = users_list([u1, u2, u3], size=2)
    eq_(shortlist, ', '.join((user_link(u1), user_link(u2))) + ', others')
Example #10
0
 def test_get_url_path(self):
     eq_(UserProfile(username='******').get_url_path(),
         '/en-US/firefox/user/yolo/')
     eq_(UserProfile(username='******', id=1).get_url_path(),
         '/en-US/firefox/user/yolo/')
     eq_(UserProfile(id=1).get_url_path(),
         '/en-US/firefox/user/1/')
     eq_(UserProfile(username='******', id=1).get_url_path(),
         '/en-US/firefox/user/1/')
Example #11
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>' % reverse('users.profile', args=[1]))

    u = UserProfile(username='******', pk=1)
    url = reverse('users.profile', args=[1])
    eq_(user_link(u), u'<a href="%s">%s</a>' % (url, u.username))
Example #12
0
 def test_empty_password(self):
     profile = UserProfile(password=None)
     assert profile.has_usable_password() is False
     assert not check_password(None, profile.password)
     assert not profile.check_password(None)
     profile = UserProfile(password='')
     assert profile.has_usable_password() is False
     assert not check_password('', profile.password)
     assert not profile.check_password('')
Example #13
0
    def addUsers(self):
        role = UserRole.objects.get(name='student')
        users_objs = []
        for i in range(50):
            print('.', )
            users_objs.append(
                UserProfile(first_name='student' + '_' + str(i),
                            last_name='student' + '_' + str(i),
                            email='student_' + str(i) + '@student.com',
                            user_role=role,
                            date_of_birth=date.fromordinal(
                                random.randint(start_date, end_date)),
                            gender=random.randrange(1, 3)))
        print('student set created', )
        role = UserRole.objects.get(name='teacher')
        for i in range(50):
            print('.', )
            users_objs.append(
                UserProfile(first_name='teacher' + '_' + str(i),
                            last_name='teacher' + '_' + str(i),
                            email='teacher' + str(i) + '@teacher.com',
                            user_role=role,
                            date_of_birth=date.fromordinal(
                                random.randint(start_date, end_date)),
                            gender=random.randrange(1, 3)))
        print('teacher set created', )
        role = UserRole.objects.get(name='principle')
        for i in range(50):
            print('.', )
            users_objs.append(
                UserProfile(first_name='principle' + '_' + str(i),
                            last_name='principle' + '_' + str(i),
                            email='principle' + str(i) + '@principle.com',
                            user_role=role,
                            date_of_birth=date.fromordinal(
                                random.randint(start_date, end_date)),
                            gender=random.randrange(1, 3)))
        print('principle set created', )
        role = UserRole.objects.get(name='other')
        for i in range(50):
            print('.', )
            users_objs.append(
                UserProfile(first_name='other' + '_' + str(i),
                            last_name='other' + '_' + str(i),
                            email='other' + str(i) + '@other.com',
                            user_role=role,
                            date_of_birth=date.fromordinal(
                                random.randint(start_date, end_date)),
                            gender=random.randrange(1, 3)))

        print('other set created', )
        UserProfile.objects.bulk_create(users_objs)
        print('user done', )
Example #14
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 #15
0
    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()
Example #16
0
    def test_create_user_profile_special_characters(self):
        # period in mnemonic
        user = UserProfile(user=self.user1,
                           mnemonic='user.1',
                           created_by=self.user1,
                           updated_by=self.user1)
        user.full_clean()
        user.save()
        self.assertTrue(UserProfile.objects.filter(mnemonic='user.1').exists())
        user.delete()

        # hyphen in mnemonic
        user = UserProfile(user=self.user1,
                           mnemonic='user-1',
                           created_by=self.user1,
                           updated_by=self.user1)
        user.full_clean()
        user.save()
        self.assertTrue(UserProfile.objects.filter(mnemonic='user-1').exists())
        user.delete()

        # underscore in mnemonic
        user = UserProfile(user=self.user1,
                           mnemonic='user_1',
                           created_by=self.user1,
                           updated_by=self.user1)
        user.full_clean()
        user.save()
        self.assertTrue(UserProfile.objects.filter(mnemonic='user_1').exists())
        user.delete()

        # all characters in mnemonic
        user = UserProfile(user=self.user1,
                           mnemonic='user.1_2-3',
                           created_by=self.user1,
                           updated_by=self.user1)
        user.full_clean()
        user.save()
        self.assertTrue(
            UserProfile.objects.filter(mnemonic='user.1_2-3').exists())
        user.delete()

        # test validation error
        with self.assertRaises(ValidationError):
            user = UserProfile(user=self.user1,
                               mnemonic='user@1',
                               created_by=self.user1,
                               updated_by=self.user1)
            user.full_clean()
            user.save()
Example #17
0
    def test_picture_url(self):
        """
        Test for a preview URL if image is set, or default image otherwise.
        """
        u = UserProfile(id=1234, picture_type='image/png',
                        modified=datetime.date.today())
        u.picture_url.index('/userpics/0/1/1234.png?modified=')

        u = UserProfile(id=1234567890, picture_type='image/png',
                        modified=datetime.date.today())
        u.picture_url.index('/userpics/1234/1234567/1234567890.png?modified=')

        u = UserProfile(id=1234, picture_type=None)
        assert u.picture_url.endswith('/anon_user.png')
Example #18
0
    def post(self, request):
        user_register_form = UserRegisterForm(request.POST)
        if user_register_form.is_valid():
            email = user_register_form.cleaned_data['email']
            password = user_register_form.cleaned_data['password']

            user_list = UserProfile.objects.filter(
                Q(username=email) | Q(email=email))
            if user_list:
                return render(request, 'users/register.html',
                              {'msg': '用户已经存在'})
            else:
                a = UserProfile()
                a.username = email
                a.set_password(password)
                a.email = email

                # 进行邮箱验证激活
                # 发送邮箱验证码
                if send_email_code(email, 1):
                    a.save()
                    return HttpResponse('情尽快前往邮箱激活账号')
                else:
                    return HttpResponse('注册失败')
                # return redirect('/users/user_login')
        else:
            return render(request, 'users/register.html',
                          {'user_register_form': user_register_form})
Example #19
0
    def post(self, request):
        register_form = MobileRegisterForm(request.POST)
        if register_form.is_valid():
            mobile = request.POST.get("mobile")
            code = request.POST.get("code")
            password = request.POST.get("password")
            record = MobileVerify.objects.filter(
                mobile=mobile, code=code,
                is_valid=True).order_by("-add_time").first()
            if record:
                diff_time = datetime.now() - record.add_time
                if diff_time.seconds < 10 * 60:
                    UserProfile(username=mobile,
                                mobile=mobile,
                                password=make_password(password),
                                is_active=True).save()
                    record.is_valid = False
                    record.save()
                    return redirect(reverse("login"))
                else:
                    messages.add_message(request, messages.ERROR,
                                         "验证码已失效, 请重新获取")
            else:
                messages.add_message(request, messages.ERROR, "验证码错误")
        else:
            pass

        return render(request,
                      "users/mobile-register.html",
                      context={
                          "register_form": register_form,
                      })
Example #20
0
 def setUp(self):
     org = Org.objects.create(
         name="Stanford University",
         located=Location.objects.create(
             name="San Francisco",
         )
     )
     Course.objects.create(
         name="Compiler",
         org=org,
         tag="cs"
     )
     Course.objects.create(
         name="Operating System",
         org=org,
         tag="engineer"
     )
     Course.objects.create(
         name="Network",
         org=org,
         tag="cs"
     )
     self.user = UserProfile(
         username="******",
         email="*****@*****.**",
     )
     self.user.set_password("123456")
     self.user.save()
Example #21
0
    def post(self, request):

        if request.is_ajax():

            title = request.POST.get('title', '')
            status = request.POST.get('state', '')

            # 修改时间格式
            time = request.POST.get('time', '')
            patten = '年|月'
            time = re.sub(patten, '-', time)
            time = re.sub('日', '', time)

            start_time = request.POST.get('start_time', '')
            end_time = request.POST.get('end_time', '')
            content = request.POST.get('content', '')
            remark = request.POST.get('remark', '')
            style = request.POST.getlist('style[]', [])
            media = request.POST.getlist('media[]', [])
            accept_user = request.POST.getlist('accept_user[]', [])

            message_draft = MessageDraft()
            message_draft.draft_user = request.user
            message_draft.title = title
            message_draft.status = status
            message_draft.add_time = time
            message_draft.start_time = start_time
            message_draft.end_time = end_time
            message_draft.content = content
            message_draft.remark = remark

            # 保存文件 !

            message_draft.save()

            lis = MessageDraft.objects.get(id=message_draft.id)
            # 保存类型
            for c in style:
                category = Category(name=c)
                if not category:
                    category.name = c
                    category.save()
                    lis.category.add(category)
            # 保存媒体对象
            for m in media:
                media = ObjMedia(name=m)
                if not media:
                    media.name = m
                    media.save()
                    lis.media.add(media)

            # 修改   保存接受人的id
            for a in accept_user:
                accept_user = UserProfile(id=a)
                if accept_user:
                   lis.accept_user.add(accept_user)

            return HttpResponse('{"status": "success"}', content_type="application/json")

        return HttpResponse('{"status": "fail"}', content_type="application/json")
Example #22
0
    def post(self, request):
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            user_name = request.POST.get('email', '')
            if UserProfile.objects.filter(email=user_name):
                return render(request, 'register.html', {
                    'register_form': register_form,
                    'msg': '用户已存在'
                })
            pass_word = request.POST.get('password', '')
            re_user = UserProfile()
            re_user.username = user_name
            re_user.email = user_name
            re_user.password = make_password(pass_word)
            re_user.is_active = False
            re_user.save()

            usermessage = UserMessage()
            usermessage.message = "欢迎注册慕学在线网"
            usermessage.user = re_user
            usermessage.save()

            send_email_code.delay(user_name)
            return render(request, 'login.html')
        else:
            return render(request, 'register.html',
                          {'register_form': register_form})
Example #23
0
    def post(self, request):
        register_form = RegisterForm(request.POST)
        # print(register_form,"*"*100)
        if register_form.is_valid():
            user_name = request.POST.get("email", "")
            if UserProfile.objects.filter(email=user_name):
                return render(request, 'register.html', {
                    "register_form": register_form,
                    "msg": "用户已经存在"
                })
            pass_word = request.POST.get("password", "")
            user_profile = UserProfile()
            user_profile.username = user_name
            user_profile.email = user_name
            user_profile.is_active = False
            user_profile.password = make_password(pass_word)
            user_profile.save()

            user_message = UserMessage()
            user_message.user = user_profile.id
            user_message.message = '欢迎注册慕学在线网'
            user_message.save()
            send_register_email(user_name, "register")

            return render(request, 'login.html')
        else:
            return render(request, 'register.html',
                          {"register_form": register_form})
Example #24
0
def user_register(request):
    if request.method == 'GET':
        # 此处实例化forms类,目的不是为了验证,而是为了使用验证码
        user_register_form = UserRegisterForm()
        return render(request, 'users/register.html',
                      {'user_register_form': user_register_form})
    else:
        # 获取form注册表单数据
        user_register_form = UserRegisterForm(request.POST)
        if user_register_form.is_valid():  # 验证注册的邮箱与密码数据
            # 提取提交的数据
            email = user_register_form.cleaned_data['email']
            password = user_register_form.cleaned_data['password']
            # 到数据库查询注册的账号是否存在
            user_list = UserProfile.objects.filter(
                Q(username=email) | Q(email=email))
            if user_list:  # 注册的账号存在
                return render(request, 'users/register.html',
                              {'mgs': '用户已经存在!!!'})
            else:  # 注册的账号不存在
                user = UserProfile()
                user.username = email
                user.set_password(password)
                user.email = email
                user.save()
                send_mail_code(email, 1)
                return HttpResponse("请尽快登陆你的邮件进行账号激活,否则无法登陆...")
                # return redirect(reverse('index'))
        else:  # 表单数据验证不合法
            return render(request, 'users/register.html',
                          {'user_register_form': user_register_form})
Example #25
0
def user_register(request):
    all_category = Category.objects.filter(is_tab=True).all()
    if request.method == 'GET':
        return render(request, 'user_register.html')
    else:
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            email = register_form.cleaned_data['email']
            pwd = register_form.cleaned_data['password']
            nick_name = register_form.cleaned_data['nick_name']
            user = UserProfile.objects.filter(username=email)
            if user:
                return render(request, 'user_register.html', {'msg': '用户名已存在'})
            else:
                # if pwd == pwd1:
                new = UserProfile()
                new.username = email
                new.email = email
                new.nick_name = nick_name
                new.set_password(pwd)
                new.save()
                send_email_code(email, '1')
                return render(request, 'wait_start.html', {
                    'all_category': all_category,
                })
        # else:
        # 	return render(request, 'user_register.html', {
        # 		'msg': '两次密码不一致'
        # 		})
        else:
            return render(request, 'user_register.html',
                          {'register_form': register_form})
Example #26
0
    def post(self, request):
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            user_name = request.POST.get("email", "")
            if UserProfile.objects.filter(email=user_name):
                return render(request, 'register.html', {
                    'register_form': register_form,
                    'msg': "用户已经存在"
                })
            pass_word = request.POST.get("password", "")
            user_profile = UserProfile()
            user_profile.username = user_name
            user_profile.email = user_name
            user_profile.password = make_password(pass_word)
            user_profile.is_active = False
            user_profile.save()

            #写入欢迎注册消息
            user_message = UserMessage()
            user_message.user = user_profile.id
            user_message.message = "欢迎注册哔哩哔哩弹幕网!"
            user_message.save()

            send_register_email(user_name, "register")
            return HttpResponse("激活邮件已经发送!")
        else:
            return render(request, "register.html",
                          {'register_form': register_form})
Example #27
0
def register(request):
    if request.method == 'POST':
        reg_form = RegForm(request.POST)
        if reg_form.is_valid():
            username = reg_form.cleaned_data['username']
            email = reg_form.cleaned_data['email']
            password = reg_form.cleaned_data['password']
            user_name = reg_form.cleaned_data['user_name']
            stu_id = reg_form.cleaned_data['stu_id']
            major = reg_form.cleaned_data['major']
            # 创建用户
            user = User.objects.create_user(username, email, password)
            user.save()
            user_profile = UserProfile(user=user,
                                       user_name=user_name,
                                       stu_id=stu_id,
                                       major=major)
            user_profile.save()
            # 登录用户
            user = auth.authenticate(username=username, password=password)
            auth.login(request, user)
            return redirect(request.GET.get('from', reverse('home')))
    else:
        reg_form = RegForm()

    context = {}
    context['reg_form'] = reg_form
    return render(request, 'register.html', context)
Example #28
0
 def post(self, request):
     """业务逻辑:
     首先实例化一个Form对象,从request.POST中绑定数据,判断其是否合法
     如果合法,获取email和password,然后判断email是否已经存在,如果存在,则返回注册页并渲染一个信息。
     如果email可用,实例化一个UserProfile对象,并将数据保存至数据库,然后发送注册邮件,并然后登录页。
     如果form不合法,返回register页
     """
     register_form = RegisterForm(request.POST)
     if register_form.is_valid():
         user_name = request.POST.get('email', None)
         pass_word = request.POST.get('password', None)
         if UserProfile.objects.filter(email=user_name):
             return render(request, 'register.html', {
                 'register_form': 'register_form',
                 'msg': '邮箱已存在'
             })
         else:
             user_profile = UserProfile()
             user_profile.email = user_name
             user_profile.username = user_name
             user_profile.password = make_password(pass_word)
             user_profile.is_active = False
             user_profile.save()
             # 发送邮箱验证码
             send_email.send_user_email(email=user_name,
                                        send_type='register')
             return render(request, 'login.html')
     else:
         return render(request, 'register.html',
                       {'register_form': register_form})
Example #29
0
 def post(self, request):
     register_form = RegisterForm(request.POST)
     '''表单验证通过'''
     if register_form.is_valid():
         user_name = request.POST.get('email', None)
         # 如果用户已存在,则提示错误信息
         if UserProfile.objects.filter(email=user_name):
             return render(request, 'register.html', {
                 'register_form': register_form,
                 'msg': '用户已存在'
             })
         pass_word = request.POST.get('password', None)
         # 实例化一个user_profile对象
         user_profile = UserProfile()
         user_profile.username = user_name
         user_profile.email = user_name
         user_profile.is_active = False
         # 对保存到数据库中的密码加密
         user_profile.password = make_password(pass_word)
         user_profile.save()
         send_register_eamil(user_name, 'register')
         return render(request, 'login.html')
     else:
         return render(request, 'register.html',
                       {'register_form': register_form})
Example #30
0
    def post(self, request):
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            user_name = request.POST.get("email", "")
            if UserProfile.objects.filter(email=user_name):
                return render(request, 'register.html', {
                    'msg': '用户已存在',
                    'register_form': register_form
                })

            pass_word = request.POST.get("password", "")
            user_profile = UserProfile()
            user_profile.username = user_name
            user_profile.email = user_name  #这样注册可以用邮箱也可以用用户名作为账户
            user_profile.password = make_password(pass_word)
            user_profile.is_active = False
            user_profile.save()

            #写入欢迎注册消息
            user_message = UserMessage()
            user_message.user = user_profile.id
            user_message.message = '注册成功,欢迎加入'
            user_message.save()

            send_register_email(user_name, 'register')
            return render(request, 'login.html')
        else:
            return render(request, 'register.html',
                          {'register_form': register_form})