Пример #1
0
def addUser(request):
    form = UserForm(request.POST)
    
    if form.is_valid():
        try:
            with transaction.atomic():
                enterprise = Enterprise()
                enterprise.save()
                request.session['idEnterprise'] = enterprise.id;
                
                location= Location(enterprise=enterprise, lat=0, lng=0, name='Main Office')
                location.save()
                
                user = User(location = location, email=form.cleaned_data['email'], 
                        password=form.cleaned_data['password'])
                user.save()
                request.session['idUser'] = user.id;
                
                profile = Profile(user = user, role="Administrator")
                profile.save()
                
                return render(request, 'users/dashboard.html')
                
        except Exception as e:
            print(e)
            messages.error(request, 'Sorry, Internal Error')
                
    else:
        messages.error(request, 'Please fill the form')
        return HttpResponseRedirect('/signup')
Пример #2
0
def saveNewUser(username, password):
    newuser = User(
            username = username,
            password = password,
        )
    newuser.save()
    return newuser
Пример #3
0
def generate_users(mask, info):
    for index, username in info:
        login = mask % index
        password = User.objects.make_random_password()
        user = User(login=login, username=username, rights=0x0)
        user.set_password(password)
        yield user, password
Пример #4
0
def delete_users():
    """
    delete all users from database

    """
    from users.models import User
    User.objects().delete()
Пример #5
0
class AdminAuthorizationRedirectMiddlewareTests(TestCase):
    def setUp(self):
        self.factory = RequestFactory()
        self.middleware = AdminAuthorizationRedirectMiddleware()

        self.user = User()
        self.user.username = "******"
        self.user.email = "*****@*****.**"
        self.user.first_name = "Bruce"
        self.user.last_name = "Wayne"
        self.user.save()

    def test_not_admin_url(self):
        request = RequestFactory().get("/something")
        result = self.middleware.process_request(request)

        self.assertIsNone(result)

    def test_admin_url_user_not_staff(self):
        request = RequestFactory().get(reverse("admin:index"))
        request.user = self.user
        result = self.middleware.process_request(request)

        self.assertEqual(settings.ADMIN_UNATHORIZED_REDIRECTION_URL, result.url)
        self.assertTrue(isinstance(result, HttpResponseRedirect))

    def test_admin_url_user_staff(self):
        adm = User.objects.create_superuser(username="******",
                                            email="*****@*****.**")
        request = RequestFactory().get(reverse("admin:index"))
        request.user = adm
        result = self.middleware.process_request(request)

        self.assertIsNone(result)
Пример #6
0
 def clean_email(self):
   email = self.cleaned_data["email"]
   try:
     User.get(email=email)
   except UserDoesNotExist:
     return email
   raise forms.ValidationError(_("A user with that email already exists."))
Пример #7
0
 def clean_username(self):
   username = self.cleaned_data["username"].lower()
   try:
     User.get(username=username)
   except UserDoesNotExist:
     return username.lower()
   raise forms.ValidationError(_("A user with that username already exists."))
class AdminBookViewTests(TestCase):
    def setUp(self):
        self.bookData = {'isbn': '85-359-0277-5', 'title': 'title', 'price': '10', 'author': 'author',
                    'image': 'test.jpg'}
        # We put user_id 2 as this would be the identifier of admin returned by TDA
        self.user = User(user_id=2, name='admin')
        self.user.save()
        self.book2 = Book(isbn='0-306-40615-2', title='title', price=10, author='author',
                    image='test.jpg')
        self.book2.save()

    def test_create_new_book_return_201(self):
        resp = self.client.post('/ebucxop/books/', data=self.bookData,
                HTTP_AUTHORIZATION='Basic ' + base64.b64encode('%s:%s' % ('admin', 'admin')))
        self.assertEqual(resp.status_code, 201)
        self.assertEquals('85-359-0277-5', resp.data['isbn'])

    def test_update_existing_book_return_200(self):
        resp = self.client.post('/ebucxop/books/0-306-40615-2/', data={'title': 'titleUpdated'},
                HTTP_AUTHORIZATION='Basic ' + base64.b64encode('%s:%s' % ('admin', 'admin')))
        self.assertEqual(resp.status_code, 200)
        self.assertEquals('titleUpdated', resp.data['title'])

    def test_create_new_book_without_credentials_return_403(self):
        resp = self.client.post('/ebucxop/books/', data=self.bookData,
                HTTP_AUTHORIZATION='Basic ' + base64.b64encode('%s:%s' % ('Aladdin', 'open sesame')))
        self.assertEqual(resp.status_code, 403)
class RateViewTests(TestCase):
    def setUp(self):
        self.book = Book(isbn='85-359-0277-5', title='title', price=10, author='author',
                    image='test.jpg')
        self.book.save()
        self.user = User(user_id=1, name='test')
        self.user.save()
        self.book2 = Book(isbn='0-306-40615-2', title='title', price=10, author='author',
                    image='test.jpg')
        self.book2.save()
        rate = Rate(rating=1, book_id=self.book2, user_id=self.user)
        rate.save()

    def test_put_new_rate_should_return_201(self):
        """
        When non existing rate, new one is added
        """
        resp = self.client.put('/ebucxop/books/85-359-0277-5/ratings/me?format=json', {'rating': 3},
                    HTTP_AUTHORIZATION='Basic ' + base64.b64encode('%s:%s' % ('Aladdin', 'open sesame')))
        response_content = json.loads(resp.content)
        self.assertEqual(resp.status_code, 201)
        self.assertEquals('3', response_content['rating'])

    def test_put_existing_rate_should_return_200(self):
        """
        When existing rate, old rate is updated and 200 returned
        """
        resp = self.client.put('/ebucxop/books/0-306-40615-2/ratings/me?format=json', {'rating': u'3'},
                    HTTP_AUTHORIZATION='Basic ' + base64.b64encode('%s:%s' % ('Aladdin', 'open sesame')))
        self.assertEqual(resp.status_code, 200)
        response_content = json.loads(resp.content)
        # Ensure that 1 is changed to 3
        self.assertEquals('3', response_content['rating'])
Пример #10
0
 def test_chg_pwd(self):
     self.assertIsNone(
         User.register(None, '*****@*****.**', 'abc', 'abc', 'first', 'last'),
         'About to test changing of passwords'
     )
     user = User.all().filter('email =', '*****@*****.**').get()
     self.assertIsNotNone(user)
     self.assertIsNotNone(
         user.chgpwd('wrong', 'good', 'good'),
         'Wrong original password'
     )
     self.assertIsNotNone(
         user.chgpwd('abc', 'blah', 'different'),
         'Passwords differ'
     )
     self.assertIsNone(
         User.authenticate(None, '*****@*****.**', 'abc'),
         'Password should not have changed'
     )
     self.assertIsNone(
         user.chgpwd('abc', 'newpwd', 'newpwd'),
         'Valid change of password'
     )
     self.assertIsNone(
         User.authenticate(None, '*****@*****.**', 'newpwd'),
         'Password should have changed'
     )
     self.assertIsNotNone(user.chgpwd(None, None, None))
Пример #11
0
    def test_update_password(self):
        user1 = User(username='******')
        user1.set_password('12345')
        user1.save()
        update_data = {
            'password': '******',
        }

        request = self.request_factory.patch(reverse('users:user-detail', kwargs={'pk': 1}), update_data, format='json')
        force_authenticate(request, user=user1)
        view = UserDetail.as_view()
        response = view(request, pk=1)
        response.render()

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        # We confirmed that the update response worked, so let's test the new password in authentication
        update_data = {
            'username': user1.username,
            'password': '******',
        }
        request = self.request_factory.post(reverse('auth:token'), update_data, format='json')
        view = ObtainJSONWebToken.as_view()
        response = view(request)
        response.render()

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertTrue(response.data.get('token'))
Пример #12
0
 def test_successful_login(self):
     """
     Tests the login method of the User class
     """
     User.add("xxxxxx", "xxxxxx")
     result = User.login("xxxxxx", "xxxxxx")
     self.assertEqual(result, 2)
Пример #13
0
	def test_refresh_token( self, token_delete, token_save ):
		user = User( pk=1, username='******' )
		user.token = Token_factory.build()
		token = user.refresh_token()
		user.token.delete.assert_not_called()
		token_save.assert_not_called()
		self.assertEqual( token.user.pk, user.pk )
Пример #14
0
def register(request):
    if request.method == 'POST':
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        password2 = request.POST.get('password2', '')
        if not re.match(r'^\w{5,}$', username):
            error = 'invalid_username'
        elif len(password) < 5:
            error = 'invalid_password'
        elif password != password2:
            error = 'password_mismatch'
        else:
            try:
                User.create(username, password)
            except IntegrityError:
                error = 'username_taken'
            else:
                return HttpResponseRedirect("/")
    else:
        error = ''
        username = ''

    return render(request, "register.html", {
        'error': error,
        'username': username
    })
Пример #15
0
class JWTAuthBackendTests(TestCase):
    def setUp(self):
        self.user = User()
        self.user.username = "******"
        self.user.email = "*****@*****.**"
        self.user.first_name = "Bruce"
        self.user.last_name = "Wayne"
        self.user.save()

        self.backend = JWTAuthBackend()

        self.jwt_ok = jwt_utils.create_jwt(self.user)
        self.jwt_wrong = jwt_utils.create_jwt(self.user, secret="wrong_key")

    def test_jwt_ok(self):
        request = RequestFactory().get("/something")
        request.COOKIES[settings.JWT_COOKIE_NAME] = self.jwt_ok

        result = self.backend.authenticate(request)

        self.assertEqual(self.user, result)

    def test_bad_jwt(self):
        request = RequestFactory().get("/something")
        request.COOKIES[settings.JWT_COOKIE_NAME] = self.jwt_wrong

        result = self.backend.authenticate(request)

        self.assertIsNone(result)
Пример #16
0
def start(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            # user = User.objects.create_user(
            #     username=form.cleaned_data['username'],
            #     password=form.cleaned_data['password1'],
            #     email=form.cleaned_data['email']
            # )
            user = User(username=form.cleaned_data['username'], password=form.cleaned_data['password1'], email=form.cleaned_data['email'])
            user.save()
            return HttpResponseRedirect('/users/success/')
    else:
        form = RegistrationForm()

    # 로그인 세션 확인
    # 아이디와 비밀번호 비교해서 로그인 성공 시 'login_info' 세션 생성해서 아이디 저장
    # request.session['login_info'] = "~~~id" 하고 is_login = TRUE 로 변경
    if request.session.get('login_info', False):
        is_login = True

    else:
        is_login = False

    print(is_login)

    variables = RequestContext(request, {
        'form': form,
        'is_login': is_login,
    })

    return render_to_response(
        'torch/start.html',
        variables,
    )
Пример #17
0
def count(request):
    msg = 'debug'
    user = User()
    if request.method == 'POST':
        username = request.POST.get('username', '')
        password = request.POST.get('password', None)
        if 'login' in request.POST:
            res = user.login(username, password)
            if res > 0:
                msg = 'Welcome %s<br>You have logged in %s times.' % (username, res)
            elif res == user.ERR_BAD_CREDENTIALS:
                msg = 'Invalid username and password combination. Please try again.'
            else:
                msg = 'An error occurred. Please try again.'
        elif 'add' in request.POST:
            res = user.add(username, password)
            if res > 0:
                msg = 'Welcome %s<br>You have logged in 1 time.' % (username)
            elif res == user.ERR_BAD_USERNAME:
                msg = 'The user name should not be empty or longer than 128 characters. Please try again.'
            elif res == user.ERR_BAD_PASSWORD:
                msg = 'The password should not be longer than 128 characters. Please try again.'
            elif res == user.ERR_USER_EXISTS:
                msg = 'This user name already exists. Please choose another one.'
            else:
                msg = 'A error occurred. Please try again.'
        return render(request, 'users/count.html', {'msg': msg})
    return HttpResponseRedirect('/client')
class BookRateSerializerTests(TestCase):
    def setUp(self):
        bookModel = {'isbn': '0-306-40615-2', 'title': 'title', 'price': 10, 'author': 'author',
                                 'image': 'test.jpg'}
        # Adding serializer extra fields that not required in model
        self.book = Book(**bookModel)
        self.user = User(user_id='3', name='test')
        self.book.save()
        self.user.save()
        self.expectedRateData = {'user_id': self.user.pk, 'rating': 4}
        self.fullRateData = {'book_id': self.book, 'user_id': self.user, 'rating': 4}
        # Adding serializer extra fields that not required in model
        self.rate = Rate(**self.fullRateData)

    def test_retrieve_rate_should_work(self):
        """
        We check that serialization an existing model is working
        """
        serializer = BookRateSerializer(self.rate)
        # Check we have a correct dictionary serialized with python datatypes
        # book_id is excluded from serialization
        self.assertEquals(serializer.data, self.expectedRateData)

    def test_create_valid_rate_should_work(self):
        """
        We check deserialization process of a dictionary where we get a valid object model with validations succeded
        """
        serializer = RateSerializer(data={'rating': 4, 'user_id': self.user.pk, 'book_id': self.book.pk})
        # Check validations works
        self.assertEquals(serializer.is_valid(), True)
        # Check object created is what we expect
        self.assertEquals(serializer.object, self.rate)
        self.assertEquals(serializer.data['rating'], 4)
Пример #19
0
    def setUp(self):

        # User 1 (can impersonate user 2)
        self.user = User(username="******",
                         email="*****@*****.**",
                         first_name="Bruce",
                         last_name="Wayne")
        self.user.save()
        self.user_password = "******"
        self.user.set_password(self.user_password)
        self.user.save()
        p = ProjectPermission.objects.get(key=settings.APP_PERMISSION_KEYS['impersonate'])
        self.user.project_permissions.add(p)
        self.user.save()

        # User 2 (can't impersonate user 1)
        self.user2 = User(username="******",
                                      email="*****@*****.**",
                                      first_name="Peter",
                                      last_name="Parker")
        self.user2.save()
        self.user2_password = "******"
        self.user2.set_password(self.user2_password)
        self.user2.save()

        # Urls
        self.login_url = reverse("auth:login")
        self.impersonate_user1_url = reverse("auth:impersonate",
                                             args=[self.user.id])
        self.impersonate_user2_url = reverse("auth:impersonate",
                                             args=[self.user2.id])
Пример #20
0
def unitTests(request):
    """Runs all the unit tests and returns a json object with the total number of tests run, their
    output, and the number of failed tests."""
    user = User()
    res = user.unitTests()
    result = {'nrFailed': res[0], 'output': res[1], 'totalTests': res[2]}
    return HttpResponse(json.dumps(result), content_type="application/json")
Пример #21
0
def register():
    form = RegisterForm(request.form)
    if form.validate_on_submit():
        # Create new User instance
        user = User(
            name=form.username.data,
            email=form.email.data,
            password=form.password.data,
        )

        try:
            user.save()
        except UniquenessViolation, err:
            if err.column_name == "email":
                form.email.errors.append("There is already an account registered with that email address.")
            elif err.column_name == "name":
                form.username.errors.append("There is already an account registered with that username.")
        else:
            login_user(user)

            # Flash a message that gets displayed only once.
            flash("Welcome to the herd.")

            return redirect(url_for("users.profile"))
        finally:
Пример #22
0
 def test_duplicate_add(self):
     """
     Tests the add method of the User class for adding duplicate users
     """
     User.add("xxxxxx", "xxxxxx")
     result = User.add("xxxxxx", "password")
     self.assertEqual(result, ERR_USER_EXISTS)
Пример #23
0
	def save_model(self, request, obj, form, change):
		old_obj = None
		cur_email = None
		try:		
			old_obj = Judge.objects.get(pk=obj.id)			
			cur_email = old_obj.email

		except ObjectDoesNotExist:
			pass
		
		new_obj = form.save(commit=False)
		new_email = new_obj.email

		try:
			user = User.objects.get(email=cur_email)
			user.name = new_obj.name
			user.email = new_obj.email
			user.organisation = new_obj.organisation
			user.save()	
		except ObjectDoesNotExist:
			#Does not exist, Add
			password = str(hashlib.sha1(new_obj.email).hexdigest())[:20]
			user = User(name=new_obj.name,email=new_obj.email,organisation=new_obj.organisation,date_registration=datetime.now(),category=USER_JUDGE,password=password)
			user.save()
			#Send mail
		
		obj.save()
Пример #24
0
def createUser(username,password,email):
		now = time.strftime('%Y-%m-%d',time.localtime(time.time()))
		newUser = User(username = username,
			password = password,
			regDate = now,
			email = email
			)
		newUser.save()
Пример #25
0
 def test_user_node_creates_a_node(self):
     user = User(username='******')
     user.save()
     qs = UserNode.objects.filter(user=user)
     eq_(0, len(qs))
     
     node = user_node(user)
     eq_(node, user.node)
Пример #26
0
 def test_get_by_name(self):
     """Test that you are able to retrieve a user by name"""
     user = User(name=u'good golly', email=u'*****@*****.**')
     user.put()
     
     new_user = users.get_by_name(user.name)
     self.assertEquals(user.key, new_user.key)
     self.assertEquals(None, users.get_by_name(""))
Пример #27
0
 def test_wrong_login(self):
     """
     Tests the login method of the User class for
     testing bad credentials
     """
     User.add("xxxxxx", "xxxxxx")
     result = User.login("xxxxxx", "password")
     self.assertEqual(result, ERR_BAD_CREDENTIALS)
Пример #28
0
  def testRegistration(self):
    flag = True
    try:
       User.registration()
    except AttributeError:
      flag = False

    self.assertTrue( flag, 'Registration implemented')
Пример #29
0
    def mutate(self, info, username, password, email):
        user = User(
            username=username,
            email=email,
        )
        user.set_password(password)
        user.save()

        return CreateUser(user=user)
Пример #30
0
 def test_formatting(self):
     self.assertIsNone(
         User.register(None, '*****@*****.**', 'abc', 'abc', 'first', 'last'),
         'About to test automatic capitalisation'
     )
     user = User.all().filter('email =', '*****@*****.**').get()
     self.assertIsNotNone(user)
     self.assertEqual(user.fname, 'First')
     self.assertEqual(user.lname, 'Last')
Пример #31
0
def _update_username_if_different(user: User, ldap_data: dict):
    potentially_new_username = ldap_data[
        'username'] if ldap_data else user.email.split("@")[0]
    if user.username != potentially_new_username:
        user.username = potentially_new_username
        user.save()
Пример #32
0
 def load_user(user_id):
     return User.objects(id=user_id).first()
Пример #33
0
 def setUp(self):
     self.user = User(username="******",
                      email="*****@*****.**",
                      first_name="Bruce",
                      last_name="Wayne")
     self.user.save()
Пример #34
0
    def migrate_users(self):
        User.objects.all().delete()

        new_users = []

        for legacy_user in LegacyUser.objects.all():
            assert isinstance(legacy_user, LegacyUser)

            reg_date_naive = datetime.utcfromtimestamp(legacy_user.regdate)
            reg_date = timezone.make_aware(reg_date_naive, timezone.utc)

            existing_user = User.objects.filter(
                Q(email=legacy_user.email) | Q(username=legacy_user.username))

            if existing_user:
                self.stdout.write(
                    "Duplicate user for id {id}".format(id=legacy_user.record))
                continue

            user = User()
            user.id = legacy_user.record
            user.email = legacy_user.email
            user.username = legacy_user.username
            user.display_name = legacy_user.username
            if legacy_user.rank >= 0:
                user.rank_id = legacy_user.rank + 1
            if legacy_user.rank > 19:
                user.rank_id = 19
            user.date_joined = reg_date
            user.ts_uid = legacy_user.tsuid
            if user.username == "Gromph" or user.username == "unkle" or user.username == "mrbaboon":
                user.is_superuser = True
                user.is_staff = True
            user.save()
Пример #35
0
 def save(self, *args, **kwargs):
     if self.buyer is None:
         self.buyer = User.get_default_params()
     super(Products, self).save(*args, **kwargs)
Пример #36
0
 def test_user(self):
     user = User("admin", "*****@*****.**", "admin")
     db.session.add(user)
     db.session.commit()
     assert user in db.session
Пример #37
0
 def create(self, validated_data):
     user = User(username=validated_data['username'],
                 type=validated_data['type'])
     user.set_password(validated_data['password'])
     user.save()
     return user
Пример #38
0
 def test_task_status_valid(self):
     user = User()
     user.save()
     task = Task(assignee=user,status='todo')
     task.save()
     self.assertIsNotNone(task)
Пример #39
0
 def create(self, validated_data):
     user = User(username=validated_data.get('username', None))
     user.set_password(validated_data('password', None))
     user.save()
     return user
Пример #40
0
def git_check(request):
    type = '1'
    request_code = request.GET.get('code')
    oauth_git = OAuth_GITHUB(settings.GITHUB_APP_ID, settings.GITHUB_KEY,
                             settings.GITHUB_CALLBACK_URL)
    try:
        access_token = oauth_git.get_access_token(request_code)
        time.sleep(0.1)
    except:
        data = {}
        data['goto_url'] = '/'
        data['goto_time'] = 10000
        data['goto_page'] = True
        data['message_title'] = '登录失败'
        data['message'] = '获取授权失败,请确认是否允许授权,并重试。若问题无法解决,请联系网站管理人员'
        return render_to_response('oauth/response.html', data)
    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 = "无个性签名"
    sex = '1'
    githubs = OAuth_ex.objects.filter(openid=open_id, type=type)
    if githubs:
        auth_login(request,
                   githubs[0].user,
                   backend='django.contrib.auth.backends.ModelBackend')
        return HttpResponseRedirect('/')
    else:
        try:
            email = oauth_git.get_email()
        except:
            url = "%s?nickname=%s&openid=%s&type=%s&signature=%s&image_url=%s&sex=%s" % (
                reverse('oauth:bind_email'), nickname, open_id, type,
                signature, image_url, sex)
            return HttpResponseRedirect(url)
    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,
                    sex=sex,
                    signature=signature)
        pwd = str(uuid.uuid1())
        user.set_password(pwd)
        user.is_active = True
        user.download_image(image_url, nickname)
        user.save()
    oauth_ex = OAuth_ex(user=user, openid=open_id, type=type)
    oauth_ex.save()
    auth_login(request,
               user,
               backend='django.contrib.auth.backends.ModelBackend')
    data = {}
    data['goto_url'] = '/'
    data['goto_time'] = 10000
    data['goto_page'] = True
    data['message_title'] = '绑定用户成功'
    data[
        'message'] = u'绑定成功!您的用户名为:<b>%s</b>。您现在可以同时使用本站账号和此第三方账号登录本站了!' % nickname
    return render_to_response('oauth/response.html', data)
Пример #41
0
def addUser(apps, schema_editor):
    user = User(username="******",
                password="******",
                is_active=1,
                user_privilages_id=2)
    user.save()
Пример #42
0
def edit(rec_handle=None):
    setExits()
    g.title = "Edit {} Record".format(g.title)
    #import pdb;pdb.set_trace()

    user = User(g.db)
    rec = None
    request_rec_id = cleanRecordID(
        request.form.get('id', request.args.get('id', -1)))
    is_admin = g.admin.has_access(g.user, User)
    no_delete = not is_admin
    session_roles = session["user_roles"]  #roles of currnet user
    new_password = ''
    confirm_password = ''
    user_roles = ['user']  # default
    roles = Role(g.db).select()
    include_inactive = True

    if not is_admin:
        g.listURL = g.homeURL  # Non admins can't see the list
        include_inactive = False

    if rec_handle != None:
        pass  #rec_handle has to come from admin() at this point
    elif rec_handle == None and g.user != None and request_rec_id == -1:
        rec_handle = g.user
    else:
        rec_handle = request_rec_id
        if rec_handle < 0:
            flash("That is not a valid User ID")
            return redirect(g.listURL)

    if not request.form:
        """ if no form object, send the form page """
        if rec_handle != g.user and not is_admin:
            flash("You do not have access to that area")
            return redirect(g.homeURL)
        elif rec_handle == 0:
            rec = user.new()
        else:
            rec = user.get(rec_handle, include_inactive=include_inactive)
            if not rec:
                flash("Unable to locate user record")
                return redirect('/')

            user_roles = get_user_role_names(rec)

    else:
        #have the request form
        #import pdb;pdb.set_trace()
        is_new_user = False
        if rec_handle and request.form['id'] != 'None':
            rec = user.get(rec_handle, include_inactive=include_inactive)
            user_roles = get_user_role_names(rec)
        else:
            # its a new unsaved record
            is_new_user = True
            rec = user.new()
            user.update(rec, request.form)

        if validForm(rec):

            #Are we editing the current user's record?
            editingCurrentUser = ''
            if (g.user == rec.username):
                if 'new_username' in request.form:
                    editingCurrentUser = request.form['new_username'].strip()
                else:
                    editingCurrentUser = g.user
            else:
                if (g.user == rec.email):
                    editingCurrentUser = request.form['email'].strip()

            #update the record
            user.update(rec, request.form)

            set_username_from_form(rec)
            set_password_from_form(rec)

            try:
                user.save(rec)

                # update the user roles
                if 'roles_select' in request.form:
                    #delete all the users current roles
                    user.clear_roles(rec.id)
                    for role_name in request.form.getlist('roles_select'):
                        #find the role by name
                        role = Role(g.db).select_one(
                            where='name = "{}"'.format(role_name))
                        if role:
                            user.add_role(rec.id, role.id)

                # if the username or email address are the same as g.user
                # update g.user if it changes
                if (editingCurrentUser != ''):
                    setUserStatus(editingCurrentUser, rec.id)

                g.db.commit()

            except Exception as e:
                g.db.rollback()
                flash(
                    printException(
                        'Error attempting to save ' + g.title + ' record.',
                        "error", e))
                return redirect(g.listURL)

            if is_new_user == True and rec.email:
                from takeabeltof.mailer import send_message

                # send an email to welcome the new user
                full_name = '{} {}'.format(rec.first_name,
                                           rec.last_name).strip()

                context = {
                    'rec': rec,
                    'full_name': full_name,
                }
                to_address_list = [(full_name, rec.email)]
                sent, msg = send_message(
                    to_address_list,
                    subject="Welcome to {{config.SITE_NAME}}",
                    context=context,
                    html_template='user/email/welcome.html',
                    text_template='user/email/welcome.txt',
                )
                if not sent:
                    flash('The welcome message could not be sent. Error: {}'.
                          format(msg))

            return redirect(g.listURL)

        else:
            # form did not validate, give user the option to keep their old password if there was one
            #need to restore the username
            user.update(rec, request.form)
            if 'new_username' in request.form:
                rec.username = request.form[
                    'new_username']  #preserve user input
            # preserve the selected roles
            #import pdb;pdb.set_trace()
            if 'roles_select' in request.form:
                user_roles = request.form.getlist('roles_select')
            #and password
            new_password = request.form.get('new_password', '')
            confirm_password = request.form.get('confirm_password', '')

    # display form
    return render_template(
        'user/user_edit.html',
        rec=rec,
        no_delete=no_delete,
        is_admin=is_admin,
        user_roles=user_roles,
        roles=roles,
        session_roles=session_roles,
        new_password=new_password,
        confirm_password=confirm_password,
    )
Пример #43
0
def register():
    """Allow people to sign up thier own accounts on the web site"""
    setExits()
    g.title = "Account Registration"
    g.editURL = url_for('.register')
    g.listURL = '/'  # incase user cancels
    user = User(g.db)
    rec = user.new()

    from takeabeltof.mailer import send_message
    from app import app

    is_admin = False
    user_roles = None
    roles = None
    no_delete = True
    success = True
    help = render_markdown_for(__file__, mod, "user/new_account_help.md")

    if 'confirm' in request.args:
        #Try to find the user record that requested registration
        rec = user.select_one(where='access_token = "{}"'.format(
            request.args.get('confirm', '')).strip())
        if rec and rec.access_token_expires > time():
            if rec.active == 1:
                success = "active"
            else:
                success = "waiting"

            #inform the admin
            to = [(app.config['MAIL_DEFAULT_SENDER'],
                   app.config['MAIL_DEFAULT_ADDR'])]
            confirmURL = "{}://{}{}?activate={}".format(
                app.config['HOST_PROTOCOL'], app.config['HOST_NAME'],
                url_for('.activate'), rec.access_token)
            deleteURL = "{}://{}{}?delete={}".format(
                app.config['HOST_PROTOCOL'], app.config['HOST_NAME'],
                url_for('.delete'), rec.access_token)
            context = {
                'rec': rec,
                'confirmURL': confirmURL,
                'deleteURL': deleteURL
            }
            subject = 'Activate Account Request from - {}'.format(
                app.config['SITE_NAME'])
            html_template = 'user/email/admin_activate_acct.html'
            text_template = None
            send_message(to,
                         context=context,
                         subject=subject,
                         html_template=html_template,
                         text_template=text_template)

            return render_template('user/registration_success.html',
                                   success=success)
        else:
            flash("That registration request has expired")
            return redirect('/')

    if not request.form:
        pass
    else:
        if validForm(rec):
            #update the record
            user.update(rec, request.form)
            rec.active = 0  # Self registered accounts are inactive by default
            set_password_from_form(rec)
            set_username_from_form(rec)
            rec.access_token = get_access_token()
            rec.access_token_expires = time() + (3600 * 48)

            try:
                user.save(rec)

                #Send confirmation email to user
                full_name = '{} {}'.format(rec.first_name,
                                           rec.last_name).strip()
                to = [(full_name, rec.email)]
                context = {'rec': rec, 'confirmation_code': rec.access_token}
                subject = 'Signup Success'
                html_template = 'user/email/registration_confirm.html'
                text_template = 'user/email/registration_confirm.txt'
                send_message(to,
                             context=context,
                             subject=subject,
                             html_template=html_template,
                             text_template=text_template)

                #inform the admin
                to = [(app.config['MAIL_DEFAULT_SENDER'],
                       app.config['MAIL_DEFAULT_ADDR'])]
                deleteURL = "{}://{}{}?delete={}".format(
                    app.config['HOST_PROTOCOL'], app.config['HOST_NAME'],
                    url_for('.delete'), rec.access_token)
                context = {
                    'rec':
                    rec,
                    'deleteURL':
                    deleteURL,
                    'registration_exp':
                    datetime.fromtimestamp(
                        rec.access_token_expires).strftime('%Y-%m-%d %H:%M:%S')
                }
                subject = 'Unconfirmed Account Request from - {}'.format(
                    app.config['SITE_NAME'])
                html_template = 'user/email/admin_activate_acct.html'
                text_template = None
                send_message(to,
                             context=context,
                             subject=subject,
                             html_template=html_template,
                             text_template=text_template)

                g.db.commit()

            except Exception as e:
                g.db.rollback()
                mes = "An error occured while new user was attempting to register"
                printException(mes, "error", e)
                # Send email to the administrator
                to = [(app.config['MAIL_DEFAULT_SENDER'],
                       app.config['MAIL_DEFAULT_ADDR'])]
                context = {'mes': mes, 'rec': rec, 'e': str(e)}
                body = "Signup Error\n{{context.mes}}\n{{context.e}}\nrec:\n{{context.rec}}"
                send_message(to, context=context, body=body, subject=mes)
                success = False

            return render_template('user/registration_success.html',
                                   success=success)
        else:
            #validation failed
            user.update(rec, request.form)

    return render_template('user/user_edit.html',
                           rec=rec,
                           no_delete=no_delete,
                           is_admin=is_admin,
                           user_roles=user_roles,
                           roles=roles,
                           help=help)
Пример #44
0
class Command(BaseCommand):
    help = 'Create 20 random users that can be used to test the application'
    u1 = User(username='******',
              first_name='Daniel',
              last_name='Goldschmidt',
              email='*****@*****.**',
              matr_nr=0,
              type=1)
    u2 = User(username='******',
              first_name='Julia',
              last_name='Unger',
              email='*****@*****.**',
              matr_nr=0,
              type=1)
    u3 = User(username='******',
              first_name='Florian',
              last_name='Foerster',
              email='*****@*****.**',
              matr_nr=0,
              type=1)
    u4 = User(username='******',
              first_name='Mathias',
              last_name='Faber',
              email='*****@*****.**',
              matr_nr=0,
              type=2)
    u5 = User(username='******',
              first_name='Lukas',
              last_name='Schultheiss',
              email='*****@*****.**',
              matr_nr=0,
              type=2)
    u6 = User(username='******',
              first_name='Ursula',
              last_name='Drescher',
              email='*****@*****.**',
              matr_nr=0,
              type=2)
    u7 = User(username='******',
              first_name='Janina',
              last_name='Dresner',
              email='*****@*****.**',
              matr_nr=0,
              type=2)
    u8 = User(username='******',
              first_name='David',
              last_name='Maurer',
              email='*****@*****.**',
              matr_nr=1659,
              type=3)
    u9 = User(username='******',
              first_name='Jens',
              last_name='Furst',
              email='*****@*****.**',
              matr_nr=3753,
              type=3)
    u10 = User(username='******',
               first_name='Erik',
               last_name='Muller',
               email='*****@*****.**',
               matr_nr=7076,
               type=3)
    u11 = User(username='******',
               first_name='Andrea',
               last_name='Hoch',
               email='*****@*****.**',
               matr_nr=9094,
               type=3)
    u12 = User(username='******',
               first_name='Ines',
               last_name='Maur',
               email='*****@*****.**',
               matr_nr=1922,
               type=3)
    u13 = User(username='******',
               first_name='Antje',
               last_name='Kunze',
               email='*****@*****.**',
               matr_nr=7492,
               type=3)

    def handle(self, *args, **options):
        users = [
            self.u1, self.u2, self.u3, self.u4, self.u5, self.u6, self.u7,
            self.u8, self.u9, self.u10, self.u11, self.u12, self.u13
        ]
        for i in range(0, 12):
            users[i].set_password('test123')
            users[i].save()
            self.stdout.write(
                self.style.SUCCESS(
                    'Successfully created testuser of type {} with username: {}'
                    .format(users[i].type, users[i].username)))
Пример #45
0
 def get_user_mfa_context(user=None):
     mfa_backends = User.get_user_mfa_backends(user)
     return {'mfa_backends': mfa_backends}
Пример #46
0
 def mutate(root, info, input=None):
     ok = True
     user_instance = User(first_name=input.first_name, last_name=input.last_name, email=input.email, country=input.country, job_position=input.job_position, date_joined=input.date_joined)
     user_instance.save()
     return CreateUser(ok=ok, user=user_instance)
Пример #47
0
    def handle(self, *args, **options):
        file_path = options["file_path"][0]
        if not os.path.exists(file_path):
            print(f"{file_path} does not exist")
            return
        test = options.get("test", False)
        print(f"Test mode {test}")
        with open(file_path, "r") as csv_file:
            reader = DictReader(csv_file)
            updated_users = []
            offset_users = []
            start = 80_000
            for count, row in enumerate(reader):
                print(row)
                email = row["email"].strip()
                if not email:
                    continue
                # try:
                user = User.objects.get(
                    Q(email__iexact=email) | Q(email_school__iexact=email))
                offset = start + count
                badge_number = row["correct"]
                chapter = user.chapter
                user_id = f"{chapter.greek}{badge_number}"
                user_id_offset = f"{chapter.greek}{offset}"
                updated_users.append({
                    "id": user.id,
                    "badge_number": badge_number,
                    "user_id": user_id
                })
                offset_users.append({
                    "id": user.id,
                    "badge_number": offset,
                    "user_id": user_id_offset
                })
        if not test:
            User.objects.bulk_update(
                [User(**kv) for kv in offset_users],
                [
                    "badge_number",
                    "user_id",
                ],
            )
            # After the bulk update, all remaining user_ids should not conflict
            new_ids = [new["user_id"] for new in updated_users]
            conflict_users = User.objects.filter(user_id__in=new_ids)
            nl = "\n"  # can't have backslashes in f-strings
            print(
                f"Conflicting users:\n {nl.join(conflict_users.values_list('email', flat=True))}"
            )
            start = 90_000
            conflict_users_update = [{
                "id":
                user.id,
                "badge_number":
                start + count,
                "user_id":
                f"{user.chapter.greek}{start + count}",
            } for count, user in enumerate(conflict_users)]

            User.objects.bulk_update(
                [User(**kv) for kv in conflict_users_update],
                [
                    "badge_number",
                    "user_id",
                ],
            )
            User.objects.bulk_update(
                [User(**kv) for kv in updated_users],
                [
                    "badge_number",
                    "user_id",
                ],
            )
Пример #48
0
def on_org_role_update(sender, instance, created, **kwargs):
    from users.models import User
    User.expire_users_rbac_perms_cache()
Пример #49
0
 def authenticate(self, phone):
     user = User.get_user_by_phone(phone)
     return user
Пример #50
0
 def get(self):
     users = User.query()
     return [self.get_user_base_context(u) for u in users]
Пример #51
0
    def handle(self, *args, **options):
        User.objects.all().delete()

        objects_list = []

        # Students
        for i in range(1, options['students'] + 1):
            user = User(
                username='******'.format(i),
                first_name='Firstname{}'.format(i),
                last_name='Lastname{}'.format(i),
                is_active=True
            )
            user.set_password(options['password'])
            objects_list.append(user)

        # Curators
        for i in range(1, options['curators'] + 1):
            user = User(
                username='******'.format(i),
                first_name='Name{}'.format(i),
                last_name='Lastname{}'.format(i),
                is_active=True,
                role=USER_ROLES[1][0]
            )
            user.set_password(options['password'])
            objects_list.append(user)

        # Admin
        user = User(
            username='******', first_name='Firstname', last_name='Lastname',
            is_active=True, is_staff=True, is_superuser=True, role=USER_ROLES[1][0]
        )
        user.set_password(options['password'])
        objects_list.append(user)

        User.objects.bulk_create(objects_list)

        if options['verbosity'] >= 1:
            self.stdout.write("Users were successfully populated.")
Пример #52
0
    def sync_intranet_user(self, user: User):
        """
        Ensure data for user is up-to-date (active or non-active respectively)

        Guarantee: at the end if the user is active, they get a single LDAP account or their account gets moved
        to ex-members group if that's not the case
        """
        if self.mock:
            print(" * Mocking ldap sync for user %s (%s)" % (user.username, user.get_full_name()))
        # User+Profile basic data synchronization
        profile = user.profile
        assert profile
        if not profile.current_member:
            self.__unsync_intranet_user(user)
            return

        assert profile.current_member
        uid = user.pk
        u_query = '(&%s(|(uid=%s)(employeeNumber=%d)))' % (self.filter_member, user.username, uid)
        self.connection.search(self.members_dn, u_query)
        response = self.connection.response
        found_users = len(response)
        assert found_users >= 0
        if found_users == 0:
            # No user found, check if a re-activated member?
            self.connection.search(self.exmembers_dn, u_query)
            response = self.connection.response
            found_exusers = len(response)
            assert found_exusers >= 0
            if found_exusers == 0:
                if self.mock:
                    print("Create new user for ", user.get_full_name(), ":", user.get_username())
                # Make new user
                self.__create_intranet_user(user)
                # Continue, as groups need to be synced too
                pass
            elif found_exusers > 1:
                # More than 1 user => this is an invalid state, just pick the first one and delete the rest
                for invalid_resp in response[1:]:
                    if not self.mock:
                        succ = self.connection.delete(invalid_resp['dn'])
                        assert succ
                    else:
                        print("Delete extra ex-user ", invalid_resp['dn'])
                found_exusers = 1
            if found_exusers == 1:
                # Move user into active members and continue resyncing
                dn: str = response[0]['dn']
                rdn = dn.split(',')[0]
                assert 0 < len(rdn) < len(dn)
                if not self.mock:
                    succ = self.connection.modify_dn(dn, rdn, delete_old_dn=True, new_superior=self.members_dn)
                    assert succ
                else:
                    print("Move not-ex-user ", dn, " to ", rdn, ",", self.members_dn)
                pass
        elif found_users > 1:
            # More than 1 user => invalid state, pick first one and delete the rest
            for invalid_resp in response[1:]:
                if not self.mock:
                    succ = self.connection.delete(invalid_resp['dn'])
                    assert succ
                else:
                    print("Delete extra user ", invalid_resp['dn'])
            pass
        else:
            if self.mock:
                print("A single LDAP user existing: " + response[0]['dn'])

        # 1 user in the members group to synchronize
        self.connection.search(self.members_dn,
                               u_query,
                               attributes=list(LDAP_ATTR_MAP.keys()) + ["memberOf"])
        response = self.connection.response
        if not self.mock:
            assert len(response) == 1
        else:
            if len(response) < 1:
                response = [{'dn': 'uid=%s,%s' % (user.username, self.members_dn), 'attributes': {}}]
        ldap_response = response[0]
        user_dn = ldap_response['dn']
        # Sync attributes
        attr_changes = {}
        num_changes = 0
        for ldap_attr, mapfn in LDAP_ATTR_MAP.items():
            real_value = type(mapfn) == str and mapfn or mapfn(profile)
            ldap_value = ldap_response['attributes'].get(ldap_attr, [])
            if type(ldap_value) == list:
                ldap_value = len(ldap_value) == 1 and ldap_value[0] or ''
            if type(ldap_value) == bytes:
                ldap_value = ldap_value.decode('utf-8')
            if real_value != ldap_value:
                attr_changes[ldap_attr] = [(MODIFY_REPLACE, [real_value])]
                if self.mock:
                    print("Updating field %s: '%s'->'%s'" % (ldap_attr, ldap_value, real_value))
                num_changes += 1
        if num_changes > 0:
            if not self.mock:
                succ = self.connection.modify(user_dn, attr_changes)
                assert succ
            else:
                print("Changing %d fields for dn %s" % (num_changes, user_dn))
Пример #53
0
def index(request):
    user = User("*****@*****.**", "sangil", "1234")
    user.save()

    return HttpResponse("Hello, world. You're at the polls index.")
Пример #54
0
 def extract_ref_rank(self, user: User, skill: Skill):
     ref_rank = ReferenceRank.objects.filter(yoe=user.get_yoe()).filter(skill=skill).first()
     if ref_rank is not None:
         return self.conv_rank(ref_rank.rank.name)
Пример #55
0
class JwtUtilsTest(TestCase):

    def setUp(self):
        self.user = User(username="******",
                         email="*****@*****.**",
                         first_name="Bruce",
                         last_name="Wayne")
        self.user.save()

    def test_create_jwt_payload(self):
        expiration_delta = 10 * settings.SECOND
        now = timezone.now()
        expiration_date = int((now + datetime.timedelta(
                              seconds=expiration_delta)).strftime("%s"))
        now_date = int((now).strftime("%s"))
        now_nbf = int((now - datetime.timedelta(
            seconds=settings.JWT_NBF_LEEWAY_SECONDS)).strftime("%s"))

        issuer = "wiggum_test"
        extra_args = {
            'extra1': "extra 1",
            'extra2': "extra 2",
        }
        payload = jwt_utils.create_jwt_payload(self.user, expiration_delta,
                                               issuer, **extra_args)

        # Check user
        for k, v in payload['user'].items():
            self.assertEqual(getattr(self.user, k), v)

        # Check permission
        for k, i in enumerate(self.user.project_permissions.all()):
            self.assertEqual(i.key, payload['permission'][k])

        # Check claims
        self.assertEqual(expiration_date, payload['exp'])
        self.assertEqual(issuer, payload['iss'])
        self.assertEqual(now_nbf, payload['nbf'])
        self.assertEqual(now_date, payload['iat'])

        # Check extra args
        self.assertEqual(extra_args['extra1'], payload['extra1'])
        self.assertEqual(extra_args['extra2'], payload['extra2'])


    def test_valid_create_jwt(self):
        encoded_jwt = jwt_utils.create_jwt(self.user)

        # Check bad signed
        with self.assertRaises(jwt.exceptions.DecodeError) as de:
            jwt.decode(encoded_jwt, "wrong_key")
        self.assertEqual(str(de.exception), "Signature verification failed")

        # Check good signed
        jwt_decoded = jwt.decode(encoded_jwt, settings.JWT_SECRET_KEY)

        # Simple payload check
        for k, v in jwt_decoded['user'].items():
            self.assertEqual(getattr(self.user, k), v)

    def test_valid_jwt(self):
        encoded_jwt = jwt_utils.create_jwt(self.user)

        self.assertTrue(jwt_utils.valid_jwt(encoded_jwt,
                                            settings.JWT_SECRET_KEY,
                                            settings.JWT_SIGN_VALID_ALGORITHMS))
        self.assertFalse(jwt_utils.valid_jwt(encoded_jwt,
                                             "wrong_key",
                                             settings.JWT_SIGN_VALID_ALGORITHMS))
        self.assertFalse(jwt_utils.valid_jwt(encoded_jwt,
                                             settings.JWT_SECRET_KEY,
                                             None))

    def test_validate_jwt_all_keys_main_ok(self):
        encoded_jwt = jwt_utils.create_jwt(self.user)

        self.assertTrue(jwt_utils.validate_jwt_all_keys(encoded_jwt))

    def test_validate_jwt_all_keys_transition_ok(self):
        encoded_jwt = jwt_utils.create_jwt(
            self.user,
            symm_priv_key2,
            settings.JWT_SIGN_ALGORITHM)

        # Check the main key is not valid
        self.assertFalse(jwt_utils.valid_jwt(encoded_jwt,
                                             settings.JWT_SECRET_KEY,
                                             settings.JWT_SIGN_VALID_ALGORITHMS))

        self.assertTrue(jwt_utils.validate_jwt_all_keys(encoded_jwt))

    def validate_jwt_all_keys_wrong(self):
        encoded_jwt = jwt_utils.create_jwt(self.user, "wrong")

        self.assertFalse(jwt_utils.validate_jwt_all_keys(encoded_jwt))

    def test_decode_jwt(self):
        encoded_jwt = jwt_utils.create_jwt(self.user)
        decoded_jwt = jwt_utils.decode_jwt(encoded_jwt)

        # Basic check (no claims)
        for k, v in decoded_jwt['user'].items():
            self.assertEqual(getattr(self.user, k), v)
        for k, i in enumerate(self.user.project_permissions.all()):
            self.assertEqual(i.key, decoded_jwt['permission'][k])

    @override_settings(
        JWT_SECRET_KEY=priv_key,
        JWT_VERIFICATION_KEY=pub_key,
        JWT_SIGN_ALGORITHM=asymm_alg,
        JWT_SIGN_VALID_ALGORITHMS=(asymm_alg,)
    )
    def test_asymmetric_jwt(self):
        encoded_jwt = jwt_utils.create_jwt(self.user)

        self.assertFalse(jwt_utils.valid_jwt(encoded_jwt,
                                             settings.JWT_SECRET_KEY,
                                             settings.JWT_SIGN_VALID_ALGORITHMS))

        self.assertTrue(jwt_utils.valid_jwt(encoded_jwt,
                                            settings.JWT_VERIFICATION_KEY,
                                            settings.JWT_SIGN_VALID_ALGORITHMS))

    @override_settings(
        JWT_SECRET_KEY=priv_key,
        JWT_VERIFICATION_KEY=pub_key,
        JWT_SIGN_ALGORITHM=asymm_alg,
        JWT_SIGN_VALID_ALGORITHMS=(asymm_alg,)
    )
    def test_asymmetric_jwt_guess(self):
        encoded_jwt = jwt_utils.create_jwt(self.user)
        self.assertTrue(jwt_utils.validate_jwt_all_keys(encoded_jwt))

    @override_settings(
        JWT_TRANSITION_VERIFICATION_KEY=pub_key,
        JWT_SIGN_VALID_ALGORITHMS=(asymm_alg),
        JWT_TRANSITION_ENABLE=True
    )
    def test_asymmetric_jwt_guess_transition(self):
        encoded_jwt = jwt_utils.create_jwt(self.user, priv_key, asymm_alg)

        self.assertFalse(jwt_utils.valid_jwt(encoded_jwt,
                                             settings.JWT_VERIFICATION_KEY,
                                             settings.JWT_SIGN_VALID_ALGORITHMS))

        self.assertTrue(jwt_utils.validate_jwt_all_keys(encoded_jwt))

    @override_settings(
        JWT_VERIFICATION_KEY=pub_key,
        JWT_TRANSITION_VERIFICATION_KEY=symm_priv_key,
        JWT_SIGN_VALID_ALGORITHMS=(asymm_alg, symm_alg),
        JWT_TRANSITION_ENABLE=True
    )
    def test_key_symm_asymm_mix(self):
        encoded_jwt = jwt_utils.create_jwt(self.user, symm_priv_key, symm_alg)

        self.assertTrue(jwt_utils.validate_jwt_all_keys(encoded_jwt))
Пример #56
0
 def get_search_results(self, request, queryset, search_term):
     queryset = User.annotate_full_name(
         queryset,
         self.user_lookup,
         lookup_name=self.name_for_full_name_lookup)
     return super().get_search_results(request, queryset, search_term)
Пример #57
0
 def get_search_fields(self, request):
     search_fields = super().get_search_fields(request)
     return search_fields + User.get_user_search_fields(
         self.user_lookup,
         annotated_full_name_lookup=self.name_for_full_name_lookup)
Пример #58
0
def init_model():
    if hasattr(User, 'init_account'):
        User.init_account()
Пример #59
0
def test_user_get_absolute_url(user: User):
    assert user.get_absolute_url() == f"/users/{user.username}/"
Пример #60
0
def handle_check_query(call):
    data = ast.literal_eval(call.data.split('/')[1])

    check = Check.get(data['check_id'])
    check.status = data['status']
    check.save()

    habit = Habit.get(check.habit_id)

    user = User.get(call.message.chat.id)

    called_button_label = call.message.json['reply_markup']['inline_keyboard'][0][0]['text'] if \
        data['status'] == CheckStatus.SUCCESS.name else \
        call.message.json['reply_markup']['inline_keyboard'][0][1]['text']

    try:
        bot.edit_message_text(
            chat_id=call.message.chat.id,
            text=call.message.text,
            message_id=call.message.message_id,
            reply_markup=markups.get_check_result_inline_markup(
                called_button_label),
            parse_mode='HTML')
    except:
        pass

    if data['status'] == CheckStatus.SUCCESS.name:
        user.score += habit.fine
        user.save()

        ru_text = f'{random.choice(ru_success_phrases)}\n\n*+{habit.fine} очков*'
        en_text = f'{random.choice(en_success_phrases)}\n\n*+{habit.fine} points*'
        text = ru_text if user.language_code == 'ru' else en_text

        try:
            bot.send_message(call.message.chat.id, text, parse_mode='Markdown')
            bot.send_sticker(call.message.chat.id,
                             random.choice(success_stickers))
        except:
            pass

        if habit.judge:
            judge = User.get(habit.judge)

            ru_text_judge = f'{get_user_naming(user, "Твой друг")} выполнил обещание *{habit.label}*'
            en_text_judge = f'{get_user_naming(user, "Your friend")} fulfilled the promise *{habit.label}*'
            text_judge = ru_text_judge if judge.language_code == 'ru' else en_text_judge

            try:
                bot.send_message(judge.id, text_judge, parse_mode='Markdown')
            except Exception:
                pass
    else:
        if habit.judge:
            user_violations_with_judge(user.id, habit.judge)
        else:
            try:
                bot.send_sticker(call.message.chat.id,
                                 random.choice(fail_stickers))
            except:
                pass
            user_violations(call.message)

    suggest_new_habit(user, habit)