Ejemplo n.º 1
0
    def form_valid(self, form):
        username = form.cleaned_data.get('username')
        first_name = form.cleaned_data.get('first_name')
        last_name = form.cleaned_data.get('last_name')
        password = form.cleaned_data.get('password')
        email = form.cleaned_data.get('email')
        address = form.cleaned_data.get('address')
        date_of_birth = form.cleaned_data.get('date_of_birth')

        user = User(username=username,
                    first_name=first_name,
                    last_name=last_name,
                    email=email,
                    address=address,
                    date_of_birth=date_of_birth)

        if User.objects.filter(username=user.username).exists():
            #check whether user is not already exist
            messages.error(self.request, 'Username already exist')
            return redirect('forum:sign-up')

        user.set_password(password)
        user.save()
        messages.success(self.request, 'User Register Successfully')
        return redirect(self.success_url)
Ejemplo n.º 2
0
 def create(self, validated_data):
     user = User(email=validated_data['email'],
                 first_name=validated_data['first_name'],
                 last_name=validated_data['last_name'])
     user.set_password(validated_data['password'])
     user.is_active = True
     user.save()
     return user
Ejemplo n.º 3
0
 def create(self, validated_data):
     profile_data = validated_data.pop('profile')
     password = validated_data.pop('password')
     user = User(**validated_data)
     user.set_password(password)
     user.save()
     UserProfile.objects.create(user=user, **profile_data)
     return user
Ejemplo n.º 4
0
 def create(self, validated_data):
     """
     Create and return user instance, given validate data
     """
     user = User()
     user.email = validated_data.get('email')
     user.set_password(validated_data.get('password'))
     user.phone_number = validated_data.get('phone_number')
     user.username = validated_data.get('username')
     user.is_active = False
     user.save()
     return user
Ejemplo n.º 5
0
    def setUp(self):
        self.client = APIClient()
        self.token = None
        mods.mock_query(self.client)

        user_noadmin = User(email='*****@*****.**')
        user_noadmin.set_password('qwerty')
        user_noadmin.save()

        user_admin = User(email='*****@*****.**', is_staff=True)
        user_admin.set_password('qwerty')
        user_admin.save()
Ejemplo n.º 6
0
class Login(BaseView, PhoneMixin):

    def get_sms_code(self, request):
        sms_code = request.POST.get('key')
        user_sms_code = redis.get('nedviga_user_sms_{}'.format(self.phone))
        if user_sms_code:
            if int(user_sms_code) == int(sms_code):
                if not User.objects.filter(phone=self.phone):
                    self.user = User()
                    self.user.phone = self.phone
                    self.user.set_password(DEFAULT_PASSWORD)
                    self.user.save()
            else:
                return self.render_internal_error('Invalid sms-code')
        else:
            return self.render_internal_error('Sms-code expired')

    def post(self, request):
        """
        :param request:
        :param phone: номер телефона
        :param sms_code: sms код проверки
        :return:
        Авторизует пользователя по номеру телефона и sms-коду
        Варианты ошибок:
        'User not registered' - пользователь с таким телефоном не зарегистрирован
        'User is blocked' - пользователь заблокирован
        'Invalid sms-code' - неверный sms-код авторизации
        """
        result = self.get_phone(request)
        if result:
            return result

        result = self.get_user(self.phone, False)
        if result:
            return result

        result = self.get_sms_code(request)
        if result:
            return result

        # еще раз вытаскиваем юзера, чтобы django его авторизировала, просто User передать нельзя
        self.user = authenticate(phone=self.phone, password=DEFAULT_PASSWORD)

        # удаляем все другие сессии этого пользователя, чтобы был залогинен всегда с одного устройства
        my_old_sessions = Session.objects.all()
        for row in my_old_sessions:
            if row.get_decoded().get("_auth_user_id") == self.user.id:
                row.delete()
        # теперь спокойно логиним
        login(request, self.user)
        return self.render_json_response(data={'sessionid': request.session.session_key})
Ejemplo n.º 7
0
    def create(self, validated_data):
        user = User(
            email=validated_data['email'],
            first_name=validated_data['first_name'],
            last_name=validated_data['last_name']
        )
        user.set_password(validated_data['password'])
        user.is_active = True
        hunter = PyHunter(settings.HUNTER_API_KEY)
        hunter.email_verifier(user.email)
        pp = pprint.PrettyPrinter(indent=4)
        pp.pprint(hunter.email_verifier(user.email))
        user.save()

        return user
Ejemplo n.º 8
0
    def create_user(cls, username: str, email: str, first_name: str,
                    last_name: str, password: str) -> User:
        if User.objects.filter(Q(username=username) | Q(email=email)).exists():
            raise UserAlreadyExistsException

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

        return user
Ejemplo n.º 9
0
    def create(self, validated_data):
        if (User.objects.filter(
                username=validated_data.get('email')).exists()):
            return {'status': 'failed', 'message': 'Email already registered'}

        profile_data = validated_data.pop('UserProfile')
        password = validated_data.pop('password')
        user = User(**validated_data)
        user.set_password(password)
        user.save()
        UserProfile.objects.create(user=user, **profile_data)

        Dashboard.objects.create(user=user)

        return user
Ejemplo n.º 10
0
def git_check(request):
    request_code = request.GET.get('code')
    oauth_git = OAuthGitHub(settings.GITHUB_APP_ID, settings.GITHUB_KEY,
                            settings.GITHUB_CALLBACK_URL)
    try:
        access_token = oauth_git.get_access_token(
            request_code)  # 获取access token
        time.sleep(0.1)  # 此处需要休息一下,避免发送urlopen的10060错误
    except Exception as e:  # 获取令牌失败,反馈失败信息
        print(e)
        return redirect('home')
    print('access_token: ', access_token)
    infos = oauth_git.get_user_info()  # 获取用户信息
    nickname = infos.get('login', '')
    image_url = infos.get('avatar_url', '')
    open_id = str(oauth_git.openid)
    signature = infos.get('bio', '')
    if not signature:
        signature = "无个性签名"
    githubs = OAuth.objects.filter(openid=open_id,
                                   type='1')  # 查询是否该第三方账户已绑定本网站账号
    if githubs:  # 若已绑定,直接登录
        auth_login(request, githubs[0].user)
        return redirect('home')
    else:  # 否则尝试获取用户邮箱用于绑定账号
        try:
            email = oauth_git.get_email()
        except Exception as e:  # 若获取失败,则跳转到绑定用户界面,让用户手动输入邮箱
            print(e)
            return redirect('home')
    users = User.objects.filter(email=email)  # 若获取到邮箱,则查询是否存在本站用户
    if users:  # 若存在,则直接绑定
        user = users[0]
    else:  # 若不存在,则新建本站用户
        while User.objects.filter(username=nickname):  # 防止用户名重复
            nickname = nickname + '*'
        user = User(username=nickname, email=email)
        pwd = str(uuid.uuid1())  # 随机设置用户密码
        user.set_password(pwd)
        user.save()
    oauth = OAuth(user=user, openid=open_id, type='1')
    oauth.save()  # 保存后登陆
    auth_login(request, user)
    return redirect('home')
Ejemplo n.º 11
0
 def test_errors(self):
     u = User(email=mock_user2["email"], username=mock_user2["username"])
     u.set_password(mock_user2["password"])
     u.save()
     response = self.client.post('/api/v1/auth/login/',
                                 data=json.dumps({
                                     "email":
                                     mock_user2["email"],
                                     "password":
                                     mock_user2["password"]
                                 }),
                                 content_type="application/json")
     self.assertEquals(response.status_code, 200)
     response = self.client.delete('/api/v1/posts/%s/' % self.post["id"])
     self.assertEquals(response.status_code, 403)
     response = self.client.put('/api/v1/posts/%s/' % self.post["id"],
                                data=json.dumps({"content": "new content"}),
                                content_type="application/json")
     self.assertEquals(response.status_code, 403)
Ejemplo n.º 12
0
    def post(self, request):
        form = RegisterForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            data = form.cleaned_data
            user = User()
            user.email = data['email']
            user.set_password(data['password1'])
            user.first_name = data['first_name']
            user.last_name = data['last_name']
            user.save()

            group = Group.objects.get(name='Users')
            user.groups.add(group)

            user.save()

            return redirect("index")

        return render_to_response(self.template_name, {'form': form}, context_instance=RequestContext(request))
Ejemplo n.º 13
0
    def mutate(cls, root, info, **kwargs):
        if not isinstance(info.context.user, User):
            raise UnauthorizedException()

        if not info.context.user.is_superuser:
            raise ForbiddenException()

        user = User()

        create_kwargs = dict(kwargs)

        del create_kwargs['password']

        for key, value in create_kwargs.items():
            setattr(user, key, value)

        user.set_password(kwargs.get('password'))

        user.is_staff = user.is_superuser

        user.save()

        return CreateUser(user=user)
Ejemplo n.º 14
0
 def setUp(self):
     self.product_source = Product(
         name="Coca-Cola Classic",
         code="5449000000996",
         nutriscore="e",
         url="https://fr.openfoodfacts.org/produit/5449000000996/coca-cola",
         popularity=2802)
     self.product_source.save()
     self.product_target = Product(
         name="Coca-Cola Zero",
         code="5449000133335",
         nutriscore="b",
         url=
         "https://fr.openfoodfacts.org/produit/5449000133335/coca-cola-zero",
         popularity=181)
     self.product_target.save()
     test_user = User(email='*****@*****.**',
                      password=None,
                      first_name='essai',
                      last_name='register')
     test_user.set_password('blabla75')
     test_user.save()
     self.target_user = User.objects.get(email='*****@*****.**')
Ejemplo n.º 15
0
 def create_user(email, password, **kwargs):
     user = User(email=email, **kwargs)
     user.set_password(password)
     user.save()
     return user
Ejemplo n.º 16
0
 def setUpClassData(cls):
     u = User(email=mock_user1["email"], username=mock_user1["username"])
     u.set_password(mock_user1["password"])
     u.save()
Ejemplo n.º 17
0
 def create(self, validated_data):
     user = User(email=validated_data['email'])
     user.set_password(validated_data['password'])
     user.save()
     return user
Ejemplo n.º 18
0
class VersionAdminTest(TestCase):

    urls = "reversion.tests"

    def setUp(self):
        self.user = User(
            username="******",
            is_staff=True,
            is_superuser=True,
        )
        self.user.set_password("bar")
        self.user.save()
        self.client.login(username="******", password="******")

    def testAutoRegisterWorks(self):
        self.assertTrue(reversion.is_registered(ChildTestAdminModel))
        self.assertTrue(reversion.is_registered(ParentTestAdminModel))

    def testRevisionSavedOnPost(self):
        self.assertEqual(ChildTestAdminModel.objects.count(), 0)
        # Create an instance via the admin.
        response = self.client.post(
            "/admin/auth/childtestadminmodel/add/", {
                "parent_name": "parent instance1 version1",
                "child_name": "child instance1 version1",
                "_continue": 1,
            })
        self.assertEqual(response.status_code, 302)
        obj_pk = response["Location"].split("/")[-2]
        obj = ChildTestAdminModel.objects.get(id=obj_pk)
        # Check that a version is created.
        versions = reversion.get_for_object(obj)
        self.assertEqual(versions.count(), 1)
        self.assertEqual(versions[0].field_dict["parent_name"],
                         "parent instance1 version1")
        self.assertEqual(versions[0].field_dict["child_name"],
                         "child instance1 version1")
        # Save a new version.
        response = self.client.post(
            "/admin/auth/childtestadminmodel/%s/" % obj_pk, {
                "parent_name": "parent instance1 version2",
                "child_name": "child instance1 version2",
                "_continue": 1,
            })
        self.assertEqual(response.status_code, 302)
        # Check that a version is created.
        versions = reversion.get_for_object(obj)
        self.assertEqual(versions.count(), 2)
        self.assertEqual(versions[0].field_dict["parent_name"],
                         "parent instance1 version2")
        self.assertEqual(versions[0].field_dict["child_name"],
                         "child instance1 version2")
        # Check that the versions can be listed.
        response = self.client.get(
            "/admin/auth/childtestadminmodel/%s/history/" % obj_pk)
        self.assertContains(response, "child instance1 version2")
        self.assertContains(response, "child instance1 version1")
        # Check that a version can be rolled back.
        response = self.client.post(
            "/admin/auth/childtestadminmodel/%s/history/%s/" %
            (obj_pk, versions[1].pk), {
                "parent_name": "parent instance1 version3",
                "child_name": "child instance1 version3",
            })
        self.assertEqual(response.status_code, 302)
        # Check that a version is created.
        versions = reversion.get_for_object(obj)
        self.assertEqual(versions.count(), 3)
        self.assertEqual(versions[0].field_dict["parent_name"],
                         "parent instance1 version3")
        self.assertEqual(versions[0].field_dict["child_name"],
                         "child instance1 version3")
        # Check that a deleted version can be viewed.
        obj.delete()
        response = self.client.get("/admin/auth/childtestadminmodel/recover/")
        self.assertContains(response, "child instance1 version3")
        # Check that a deleted version can be recovered.
        response = self.client.post(
            "/admin/auth/childtestadminmodel/recover/%s/" % versions[0].pk, {
                "parent_name": "parent instance1 version4",
                "child_name": "child instance1 version4",
            })
        obj = ChildTestAdminModel.objects.get(id=obj_pk)

    def tearDown(self):
        self.client.logout()
        self.user.delete()
        del self.user
        ChildTestAdminModel.objects.all().delete()
Ejemplo n.º 19
0
 def create(self, validated_data):
     user = User(**validated_data)
     user.set_password(validated_data.get('password'))
     user.save()
     return user
Ejemplo n.º 20
0
class VersionAdminTest(TestCase):

    urls = "reversion.tests"

    def setUp(self):
        self.user = User(
            username = "******",
            is_staff = True,
            is_superuser = True,
        )
        self.user.set_password("bar")
        self.user.save()
        self.client.login(username="******", password="******")

    def testAutoRegisterWorks(self):
        self.assertTrue(reversion.is_registered(ChildTestAdminModel))
        self.assertTrue(reversion.is_registered(ParentTestAdminModel))
        
    def testRevisionSavedOnPost(self):
        self.assertEqual(ChildTestAdminModel.objects.count(), 0)
        # Create an instance via the admin.
        response = self.client.post("/admin/auth/childtestadminmodel/add/", {
            "parent_name": "parent instance1 version1",
            "child_name": "child instance1 version1",
            "_continue": 1,
        })
        self.assertEqual(response.status_code, 302)
        obj_pk = response["Location"].split("/")[-2]
        obj = ChildTestAdminModel.objects.get(id=obj_pk)
        # Check that a version is created.
        versions = reversion.get_for_object(obj)
        self.assertEqual(versions.count(), 1)
        self.assertEqual(versions[0].field_dict["parent_name"], "parent instance1 version1")
        self.assertEqual(versions[0].field_dict["child_name"], "child instance1 version1")
        # Save a new version.
        response = self.client.post("/admin/auth/childtestadminmodel/%s/" % obj_pk, {
            "parent_name": "parent instance1 version2",
            "child_name": "child instance1 version2",
            "_continue": 1,
        })
        self.assertEqual(response.status_code, 302)
        # Check that a version is created.
        versions = reversion.get_for_object(obj)
        self.assertEqual(versions.count(), 2)
        self.assertEqual(versions[0].field_dict["parent_name"], "parent instance1 version2")
        self.assertEqual(versions[0].field_dict["child_name"], "child instance1 version2")
        # Check that the versions can be listed.
        response = self.client.get("/admin/auth/childtestadminmodel/%s/history/" % obj_pk)
        self.assertContains(response, "child instance1 version2")
        self.assertContains(response, "child instance1 version1")
        # Check that a version can be rolled back.
        response = self.client.post("/admin/auth/childtestadminmodel/%s/history/%s/" % (obj_pk, versions[1].pk), {
            "parent_name": "parent instance1 version3",
            "child_name": "child instance1 version3",
        })
        self.assertEqual(response.status_code, 302)
        # Check that a version is created.
        versions = reversion.get_for_object(obj)
        self.assertEqual(versions.count(), 3)
        self.assertEqual(versions[0].field_dict["parent_name"], "parent instance1 version3")
        self.assertEqual(versions[0].field_dict["child_name"], "child instance1 version3")
        # Check that a deleted version can be viewed.
        obj.delete()
        response = self.client.get("/admin/auth/childtestadminmodel/recover/")
        self.assertContains(response, "child instance1 version3")
        # Check that a deleted version can be recovered.
        response = self.client.post("/admin/auth/childtestadminmodel/recover/%s/" % versions[0].pk, {
            "parent_name": "parent instance1 version4",
            "child_name": "child instance1 version4",
        })
        obj = ChildTestAdminModel.objects.get(id=obj_pk)
        
    def tearDown(self):
        self.client.logout()
        self.user.delete()
        del self.user
        ChildTestAdminModel.objects.all().delete()