Ejemplo n.º 1
0
 def test_add_feature(self):
     _group11 = FeatureGroup.get(11)
     NAME_FEATURE = 'NAME_FEATURE'
     _feature = Feature(n=1, name=NAME_FEATURE, feature_group=[_group11])
     Session.add(_feature)
     assert _feature.n is not None
     assert len(_feature.feature_group) == 1
Ejemplo n.º 2
0
def main(argv=sys.argv):
    if len(argv) < 2:
        usage(argv)
    config_uri = argv[1]
    options = parse_vars(argv[2:])
    setup_logging(config_uri)
    settings = get_appsettings(config_uri, options=options)
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)

    Base.metadata.drop_all(engine)
    Base.metadata.create_all(engine)
    with transaction.manager:
        model = User(name=u'admin', password=u'admin')
        DBSession.add(model)
        from jinja2.utils import generate_lorem_ipsum
        for id, article in enumerate(range(100), start=1):
            title = generate_lorem_ipsum(
                n=1,  # Одно предложение
                html=False,  # В виде обычного текста
                min=2,  # Минимум 2 слова
                max=5  # Максимум 5
            )
            content = generate_lorem_ipsum()
            article = Article(**{'title': title, 'content': content})
            DBSession.add(article)
Ejemplo n.º 3
0
def main(argv=sys.argv):
    # Usage and configuration
    if len(argv) != 2:
        usage(argv)
    config_uri = argv[1]
    setup_logging(config_uri)
    settings = get_appsettings(config_uri)
    config = Configurator(settings=settings)
    config.include('pyramid_sqlalchemy')

    # Make the database with schema and default data
    with transaction.manager:
        metadata.create_all()
        root = RootFolder(name='',
                      title='Moonbase Demo',
                      __acl__=[
                          ['Allow', ['paul'], 'view']
                      ]
                      )
        Session.add(root)
        f1 = root['f1'] = Folder(
            title='Folder 1',
            __acl__=[
                ['Allow', ['shane'], 'view']
            ]
        )
        f1['da'] = Document(title='Document 1A')
Ejemplo n.º 4
0
def fix_many_feature_groups(request, sql_session):
  Session.add(FeatureGroup(n=1, name='group1'))
  Session.add(FeatureGroup(n=11, name='group11', parent_n=1))
  Session.add(FeatureGroup(n=12, name='group12', parent_n=1))

  Session.add(FeatureGroup(n=2, name='group2'))
  Session.add(FeatureGroup(n=21, name='group21', parent_n=2))
Ejemplo n.º 5
0
 def test_model_sets_n_automatically(self):
     _group = FeatureGroup(name='NAME_FEATURE_GROUP')
     Session.add(_group)
     Session.flush()
     assert _group.n is not None
     assert _group.parent_n is None
     assert _group.name == 'NAME_FEATURE_GROUP'
Ejemplo n.º 6
0
    def put(self):
        try:
            uuid.UUID(self.password_id)
        except ValueError:
            return invalid_password_id()

        password = self._get_password()
        if password is None:
            return password_not_found()

        else:
            cleaned_data, errors = validate_password(self.request.body,
                                                     self.request.charset)

            if errors:
                result = {'message': ','.join(errors)}
                return HTTPBadRequest(body=json.dumps(result),
                                      charset='utf8',
                                      content_type='application/json')

            password.secret = cleaned_data['secret']
            password.service = cleaned_data['service']
            password.account = cleaned_data['account']
            password.expiration = cleaned_data['expiration']
            password.notes = cleaned_data['notes']
            password.tags = cleaned_data['tags']

            Session.add(password)

            return {'password': password.as_dict()}
Ejemplo n.º 7
0
    def test_password_collection_get_non_empty(self):
        password = Password(service='testing',
                            secret='s3cr3t',
                            user_id=self.user_id)

        with transaction.manager:
            Session.add(password)
            Session.flush()
            password_id = password.id

        res = self.testapp.get('/passwords', headers=self.auth_header)
        self.assertEqual(res.status, '200 OK')

        self.assertEqual(res.json, {
            "passwords": [{
                'account': '',
                'creation': '2014-02-23T08:00:00',
                'modification': '2014-02-23T08:00:00',
                'expiration': None,
                'id': password_id,
                'notes': u'',
                'owner': self.user_id,
                'user': self.user_id,
                'secret': 's3cr3t',
                'service': 'testing',
                'tags': [],
            }],
        })
Ejemplo n.º 8
0
 def __setitem__(self, key, node):
     node.name = str(key)
     if self.id is None:
         Session.flush()
     node.parent_id = self.id
     Session.add(node)
     Session.flush()
Ejemplo n.º 9
0
    def test_password_delete_found(self):
        password = Password(service='myservice',
                            secret='s3cr3t',
                            user_id=self.user_id)

        with transaction.manager:
            Session.add(password)
            Session.flush()
            password_id = password.id

        count_before = Session.query(Password).count()
        self.assertEqual(count_before, 1)

        res = self.testapp.delete('/passwords/%s' % str(password_id),
                                  headers=self.auth_header)
        self.assertEqual(res.status, '200 OK')
        self.assertEqual(res.body, (b'{"password": {"id": "'
                                    + text_type(password_id).encode('ascii')
                                    + b'"}}'))
        count_after = Session.query(Password).count()
        self.assertEqual(count_after, 0)
        try:
            password = Session.query(Password).filter(
                Password.id == password_id
            ).one()
        except NoResultFound:
            password = None

        self.assertEqual(password, None)
Ejemplo n.º 10
0
def handle_refresh_token(request, client):
    if 'refresh_token' not in request.POST:
        log.info('refresh_token field missing')
        return HTTPBadRequest(InvalidRequest(error_description='refresh_token '
            'field required'))

    if 'user_id' not in request.POST:
        log.info('user_id field missing')
        return HTTPBadRequest(InvalidRequest(error_description='user_id '
            'field required'))

    auth_token = db.query(Oauth2Token).filter_by(
        refresh_token=request.POST.get('refresh_token')).first()

    if not auth_token:
        log.info('invalid refresh_token')
        return HTTPUnauthorized(InvalidToken(error_description='Provided '
            'refresh_token is not valid.'))

    if auth_token.client.client_id != client.client_id:
        log.info('invalid client_id')
        return HTTPBadRequest(InvalidClient(error_description='Client does '
            'not own this refresh_token.'))

    if str(auth_token.user_id) != request.POST.get('user_id'):
        log.info('invalid user_id')
        return HTTPBadRequest(InvalidClient(error_description='The given '
            'user_id does not match the given refresh_token.'))

    new_token = auth_token.refresh()
    db.add(new_token)
    db.flush()
    return new_token.asJSON(token_type='bearer')
Ejemplo n.º 11
0
    def test_application_edit_invalid_change(self):
        user = User(screen_name='John Doe',
                    first_name='John',
                    last_name='Doe',
                    email='*****@*****.**')

        app = Application(name='Test Application',
                          main_url='http://example.com',
                          callback_url='http://example.com/callback',
                          authorized_origins=['http://example.com',
                                              'https://example.com'],
                          production_ready=False,
                          image_url='http://example.com/image.png',
                          description='example description')
        user.applications.append(app)

        with transaction.manager:
            Session.add(user)
            Session.flush()
            app_id = app.id
            user_id = user.id

        self.testapp.get('/__login/' + str(user_id))

        res = self.testapp.post('/oauth2/applications/%s/edit' % str(app_id), {
            'submit': 'Save changes',
        })
        self.assertEqual(res.status, '200 OK')
        res.mustcontain('There was a problem with your submission')
        res.mustcontain('Required')
Ejemplo n.º 12
0
def add_view_via_post(request):
    import os, shutil
    from pkg_resources import resource_filename
    from pyramid_sqlalchemy import Session
    from pyramid.httpexceptions import HTTPFound
    from ..forms import NewStudentForm
    from ..models import NewStudentModel

    form = NewStudentForm(request.POST)
    # 該欄位是文字欄位,可省略不輸入,但我們希望在這情況下塞到資料庫是 NULL,所以這邊強制改成 None
    if form.signup_number.data == '': form.signup_number.data = None
    if form.validate():
        new_student = NewStudentModel()
        form.populate_obj(new_student)
        if form.picture.data:
            # 有上傳大頭照,要存檔,並將資料庫對應的欄位設定
            picture_name = form.id_number.data + os.path.splitext(form.picture.data.filename)[-1]
            with open(resource_filename('tp_enroll', 'static/pictures/{}'.format(picture_name)), 'wb') as output:
                shutil.copyfileobj(form.picture.data.file, output)
            new_student.picture_name = picture_name
        # 觸發 auto increment
        new_student.id = None
        # 鄰的欄位,應該要純數字。如果使用者誤填了鄰,要刪掉多餘的文字
        if new_student.neighborhood.endswith('鄰'):
            new_student.neighborhood = new_student.neighborhood[:-1]
        Session.add(new_student)
        return HTTPFound(location=request.route_path('home'))
    return {'form': form}
Ejemplo n.º 13
0
    def create(self, collection_id, parent_id, record, id_generator=None,
               unique_fields=None, id_field=DEFAULT_ID_FIELD,
               modified_field=DEFAULT_MODIFIED_FIELD,
               auth=None):
        """Create the specified `object` in this `collection_id` for this `parent_id`.
        Assign the id to the object, using the attribute
        :attr:`cliquet.resource.Model.id_field`.

        .. note::

            This will update the collection timestamp.

        :raises: :exc:`cliquet.storage.exceptions.UnicityError`

        :param str collection_id: the collection id.
        :param str parent_id: the collection parent.

        :param dict record: the object to create.

        :returns: the newly created object.
        :rtype: dict
        """
        obj = self.collection.serialize(record)
        obj.parent_id = parent_id
        setattr(obj, modified_field, datetime.datetime.utcnow())
        try:
            Session.add(obj)
            Session.flush()
        except IntegrityError as e:
            logger.exception('Object %s for collection %s raised %s', record, self.collection, e)
            process_unicity_error(e, Session, self.collection, record)
        # TODO: store new timestamps date
        return self.collection.deserialize(obj)
Ejemplo n.º 14
0
def import_via_hro_view_via_post(request):
    from datetime import datetime
    from pyramid.httpexceptions import HTTPFound
    from pyramid_sqlalchemy import Session
    from ..forms import UploadForm
    from ..models import NewStudentModel

    form = UploadForm(request.POST)
    if form.validate():
        # 取得資料庫裡面已有的學生資料,藉此資料來實作 "已存在的學生不更動,只新增不存在的學生" 的功能
        existed_new_students = { i.signup_number for i in Session.query(NewStudentModel.signup_number) }
        file_content = form.file.data.file.read().decode('cp950')
        content_lines = file_content.split('\r\n')
        for each_line in content_lines:
            splitted_line = each_line.split(',')
            if not splitted_line[0].isdigit(): continue
            if len(splitted_line) != 15: continue
            new_student = NewStudentModel()
            new_student.signup_number    = int(splitted_line[0])
            new_student.name             = splitted_line[1]
            new_student.parent_name      = splitted_line[2]
            new_student.id_number        = splitted_line[3]
            new_student.parent_id_number = splitted_line[4]
            new_student.birthday         = datetime.strptime(splitted_line[5], '%Y/%m/%d')
            new_student.move_in_date     = datetime.strptime(splitted_line[6], '%Y/%m/%d')
            new_student.gender           = splitted_line[7]
            new_student.village          = splitted_line[9]
            new_student.neighborhood     = splitted_line[10]
            new_student.address          = splitted_line[11]
            new_student.note             = splitted_line[14].strip()
            if new_student.signup_number not in existed_new_students:
                Session.add(new_student)
        return HTTPFound(location=request.route_path('home'))
    else:
        return {'form': form}
Ejemplo n.º 15
0
    def test_backups_export_some_passwords(self):
        user_id = create_and_login_user(self.testapp)

        with freeze_time('2012-12-12 12:12:12'):
            password1 = Password(secret='secret1', user_id=user_id)
            password2 = Password(secret='secret2', user_id=user_id)

            with transaction.manager:
                Session.add(password1)
                Session.add(password2)
                Session.flush()

        with freeze_time('2012-01-10'):
            res = self.testapp.get('/backup/export')
            self.assertEqual(res.status, '200 OK')
            self.assertEqual(res.content_type, 'application/yith-library')
            uncompressedData = self.getUncompressData(res.body)
            self.assertEqual(json.loads(uncompressedData), [
                {"account": "", "service": "", "tags": [], "notes": "",
                 "creation": "2012-12-12T12:12:12", "secret": "secret1",
                 "expiration": None, "modification": "2012-12-12T12:12:12"},
                {"account": "", "service": "", "tags": [], "notes": "",
                 "creation": "2012-12-12T12:12:12", "secret": "secret2",
                 "expiration": None, "modification": "2012-12-12T12:12:12"},
            ])
            self.assertEqual(
                res.content_disposition,
                'attachment; filename=yith-library-backup-2012-01-10.yith',
            )
Ejemplo n.º 16
0
def add_order(request):
    """
    Форма заказа
    """
    if 'form.submitted' in request.params:
        date = request.params['date']
        date = date.split("-")
        time = request.params['time']
        time = time.split(":")
        order = Order(name=request.params['name'],
                      phone=request.params['phone'],
                      email=request.params['email'],
                      contact_face=request.params['contact_face'],
                      event=int(request.params['event']),
                      date=datetime.date(year=int(date[0]),
                                         month=int(date[1]),
                                         day=int(date[2])),
                      time=datetime.time(hour=int(time[0]),
                                         minute=int(time[1])),
                      address=request.params['address'],
                      count_participants=int(
                          request.params['count_participants']),
                      note=request.params['note'])
        Session.add(order)
        current_order_id = Order.get_last_order().id
        next_url = request.route_url('order', id=current_order_id)
        return HTTPFound(location=next_url)
    return {
        "title": "Добавление новой записи",
        "save_url": request.route_url('new_order'),
        "events": Event.get_events()
    }
Ejemplo n.º 17
0
    def collection_timestamp(self, collection_id, parent_id, auth=None):
        """Get the highest timestamp of every objects in this `collection_id` for
        this `parent_id`.

        .. note::

            This should take deleted objects into account.

        :param str collection_id: the collection id.
        :param str parent_id: the collection parent.

        :returns: the latest timestamp of the collection.
        :rtype: int
        """
        tb = Timestamps.__table__
        qry = select([label('last_modified', func.max(tb.c.last_modified))]).where(and_(
                                                                                   tb.c.parent_id == parent_id,
                                                                                   tb.c.collection_id == collection_id))
        last_modified,  = Session.execute(qry).fetchone()
        if last_modified is None:
            last_modified = datetime.datetime.utcnow()
            with transaction.manager:
                Session.add(Timestamps(parent_id=parent_id, collection_id=collection_id,
                                       last_modified=last_modified))
        return last_modified.replace(tzinfo=datetime.timezone.utc).timestamp()
Ejemplo n.º 18
0
def main(argv=sys.argv):
    if len(argv) < 2:
        usage(argv)
    config_uri = argv[1]
    options = parse_vars(argv[2:])
    setup_logging(config_uri)
    settings = get_appsettings(config_uri, options=options)
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)

    Base.metadata.drop_all(engine)
    Base.metadata.create_all(engine)
    with transaction.manager:
        model = User(name=u'admin', password=u'admin')
        DBSession.add(model)
        from jinja2.utils import generate_lorem_ipsum
        for id, article in enumerate(range(100), start=1):
            title = generate_lorem_ipsum(
                n=1,         # Одно предложение
                html=False,  # В виде обычного текста
                min=2,       # Минимум 2 слова
                max=5        # Максимум 5
            )
            content = generate_lorem_ipsum()
            article = Article(**{'title': title, 'content': content})
            DBSession.add(article)
Ejemplo n.º 19
0
def preferences(request):
    schema = UserPreferencesSchema()
    button1 = Button('submit', _('Save changes'))
    button1.css_class = 'btn-primary'

    form = Form(schema, buttons=(button1, ))

    user = request.user

    if 'submit' in request.POST:
        controls = request.POST.items()
        try:
            appstruct = form.validate(controls)
        except ValidationFailure as e:
            return {'form': e.render()}

        user.update_preferences(appstruct)
        Session.add(user)

        request.session.flash(
            _('The changes were saved successfully'),
            'success',
        )
        return HTTPFound(location=request.route_path('user_preferences'))

    return {
        'form':
        form.render({
            'allow_google_analytics':
            user.allow_google_analytics,
            'send_passwords_periodically':
            user.send_passwords_periodically,
        })
    }
Ejemplo n.º 20
0
def create_user(email='',
                email_verified=False,
                provider='twitter',
                external_id='twitter1',
                **kwargs):
    date = datetime.datetime(2012, 12, 12, 12, 12)
    user = User(screen_name='John Doe',
                first_name='John',
                last_name='Doe',
                email=email,
                email_verified=email_verified,
                creation=date,
                last_login=date,
                **kwargs)
    identity = ExternalIdentity(provider=provider,
                                external_id=external_id,
                                user=user)

    with transaction.manager:
        Session.add(user)
        Session.add(identity)
        Session.flush()
        user_id = user.id

    return user_id
Ejemplo n.º 21
0
    def test_user_get(self):
        expiration = datetime.datetime(2014, 2, 23, 9, 0)

        access_code = AccessCode(code=self.access_code,
                                 code_type='Bearer',
                                 expiration=expiration,
                                 scope=['read-userinfo'],
                                 user_id=self.user_id,
                                 application_id=self.application_id)
        with transaction.manager:
            Session.add(access_code)
            Session.flush()

        auth_header = {'Authorization': 'Bearer %s' % self.access_code}

        res = self.testapp.get('/user', headers=auth_header)
        self.assertEqual(res.status, '200 OK')
        self.assertEqual(
            res.json, {
                'id': self.user_id,
                'screen_name': 'John Doe',
                'first_name': 'John',
                'last_name': 'Doe',
                'email': '*****@*****.**',
                'email_verified': True,
                'allow_google_analytics': True,
                'send_passwords_periodically': False,
                'creation': '2012-12-12T12:12:00',
                'last_login': '******',
            })
Ejemplo n.º 22
0
    def test_applications_list_apps_one_app(self):
        user = User(screen_name='John Doe',
                    first_name='John',
                    last_name='Doe',
                    email='*****@*****.**')

        app = Application(name='Test Application',
                          main_url='https://example.com',
                          callback_url='https://example.com/callback',
                          production_ready=False)
        user.applications.append(app)

        with transaction.manager:
            Session.add(user)
            Session.flush()
            app_id = app.id
            user_id = user.id

        self.testapp.get('/__login/' + str(user_id))

        res = self.testapp.get('/oauth2/applications')
        self.assertEqual(res.status, '200 OK')
        res.mustcontain('John')
        res.mustcontain('Log out')
        res.mustcontain('Developer Applications')
        res.mustcontain('Register new application')
        res.mustcontain(app_id)
        res.mustcontain('Test Application')
        res.mustcontain('https://example.com')
Ejemplo n.º 23
0
    def test_user_get(self):
        expiration = datetime.datetime(2014, 2, 23, 9, 0)

        access_code = AccessCode(code=self.access_code,
                                 code_type='Bearer',
                                 expiration=expiration,
                                 scope=['read-userinfo'],
                                 user_id=self.user_id,
                                 application_id=self.application_id)
        with transaction.manager:
            Session.add(access_code)
            Session.flush()

        auth_header = {'Authorization': 'Bearer %s' % self.access_code}

        res = self.testapp.get('/user', headers=auth_header)
        self.assertEqual(res.status, '200 OK')
        self.assertEqual(res.json, {
            'id': self.user_id,
            'screen_name': 'John Doe',
            'first_name': 'John',
            'last_name': 'Doe',
            'email': '*****@*****.**',
            'email_verified': True,
            'allow_google_analytics': True,
            'send_passwords_periodically': False,
            'creation': '2012-12-12T12:12:00',
            'last_login': '******',
        })
Ejemplo n.º 24
0
def preferences(request):
    schema = UserPreferencesSchema()
    button1 = Button('submit', _('Save changes'))
    button1.css_class = 'btn-primary'

    form = Form(schema, buttons=(button1, ))

    user = request.user

    if 'submit' in request.POST:
        controls = request.POST.items()
        try:
            appstruct = form.validate(controls)
        except ValidationFailure as e:
            return {'form': e.render()}

        user.update_preferences(appstruct)
        Session.add(user)

        request.session.flash(
            _('The changes were saved successfully'),
            'success',
        )
        return HTTPFound(location=request.route_path('user_preferences'))

    return {
        'form': form.render({
            'allow_google_analytics': user.allow_google_analytics,
            'send_passwords_periodically': user.send_passwords_periodically,
        })
    }
Ejemplo n.º 25
0
    def collection_timestamp(self, collection_id, parent_id, auth=None):
        """Get the highest timestamp of every objects in this `collection_id` for
        this `parent_id`.

        .. note::

            This should take deleted objects into account.

        :param str collection_id: the collection id.
        :param str parent_id: the collection parent.

        :returns: the latest timestamp of the collection.
        :rtype: int
        """
        tb = Timestamps.__table__
        qry = select([label('last_modified', func.max(tb.c.last_modified))]).where(and_(
                                                                                   tb.c.parent_id == parent_id,
                                                                                   tb.c.collection_id == collection_id))
        last_modified,  = Session.execute(qry).fetchone()
        if last_modified is None:
            last_modified = datetime.datetime.utcnow()
            with transaction.manager:
                Session.add(Timestamps(parent_id=parent_id, collection_id=collection_id,
                                       last_modified=last_modified))
        return last_modified.replace(tzinfo=datetime.timezone.utc).timestamp()
Ejemplo n.º 26
0
    def test_application_edit_cancel(self):
        user = User(screen_name='John Doe',
                    first_name='John',
                    last_name='Doe',
                    email='*****@*****.**')

        app = Application(name='Test Application',
                          main_url='http://example.com',
                          callback_url='http://example.com/callback',
                          authorized_origins=['http://example.com',
                                              'https://example.com'],
                          production_ready=False,
                          image_url='http://example.com/image.png',
                          description='example description')
        user.applications.append(app)

        with transaction.manager:
            Session.add(user)
            Session.flush()
            app_id = app.id
            user_id = user.id

        self.testapp.get('/__login/' + str(user_id))

        res = self.testapp.post('/oauth2/applications/%s/edit' % str(app_id), {
            'cancel': 'Cancel',
        })
        self.assertEqual(res.status, '302 Found')
        self.assertEqual(res.location, 'http://localhost/oauth2/applications')
Ejemplo n.º 27
0
    def test_cors_headers_app_origins(self):
        cm = CORSManager('')

        user = User(screen_name='John Doe',
                    first_name='John',
                    last_name='Doe',
                    email='*****@*****.**')

        app = Application(name='Test Application',
                          authorized_origins=['http://localhost'])
        user.applications.append(app)

        with transaction.manager:
            Session.add(user)
            Session.add(app)
            Session.flush()
            app_id = app.id

        request = DummyRequest(headers={'Origin': 'http://localhost'},
                               params={'client_id': app_id})
        response = request.response

        cm.add_cors_header(request, response)

        self.assertEqual(response.headers, {
            'Content-Type': 'text/html; charset=UTF-8',
            'Content-Length': '0',
            'Access-Control-Allow-Origin': 'http://localhost',
        })
Ejemplo n.º 28
0
def verify_email(request):
    try:
        code = request.params['code']
    except KeyError:
        return HTTPBadRequest('Missing code parameter')

    try:
        email = request.params['email']
    except KeyError:
        return HTTPBadRequest('Missing email parameter')

    evc = EmailVerificationCode(code)
    user = evc.verify(email)
    if user is not None:
        request.session.flash(
            _('Congratulations, your email has been successfully verified'),
            'success',
        )
        user.verify_email()
        Session.add(user)
        return {
            'verified': True,
        }
    else:
        request.session.flash(
            _('Sorry, your verification code is not correct or has expired'),
            'error',
        )
        return {
            'verified': False,
        }
def main(argv=sys.argv):
    # Usage and configuration
    if len(argv) != 2:
        usage(argv)
    config_uri = argv[1]
    setup_logging(config_uri)
    settings = get_appsettings(config_uri)
    config = Configurator(settings=settings)
    config.include('pyramid_sqlalchemy')

    # Make the database with schema and default data
    with transaction.manager:
        metadata.create_all()
        for todo in sample_todos:
            t = ToDo(title=todo['title'], acl=todo.get('acl'))
            Session.add(t)

        for user in sample_users:
            u = User(id=user['id'],
                     username=user['username'],
                     password=user['password'],
                     first_name=user['first_name'],
                     last_name=user['last_name'],
                     groups=user['groups'])
            Session.add(u)
Ejemplo n.º 30
0
    def test_cors_headers_app_origins(self):
        cm = CORSManager('')

        user = User(screen_name='John Doe',
                    first_name='John',
                    last_name='Doe',
                    email='*****@*****.**')

        app = Application(name='Test Application',
                          authorized_origins=['http://localhost'])
        user.applications.append(app)

        with transaction.manager:
            Session.add(user)
            Session.add(app)
            Session.flush()
            app_id = app.id

        request = DummyRequest(headers={'Origin': 'http://localhost'},
                               params={'client_id': app_id})
        response = request.response

        cm.add_cors_header(request, response)

        self.assertEqual(
            response.headers, {
                'Content-Type': 'text/html; charset=UTF-8',
                'Content-Length': '0',
                'Access-Control-Allow-Origin': 'http://localhost',
            })
Ejemplo n.º 31
0
def verify_email(request):
    try:
        code = request.params['code']
    except KeyError:
        return HTTPBadRequest('Missing code parameter')

    try:
        email = request.params['email']
    except KeyError:
        return HTTPBadRequest('Missing email parameter')

    evc = EmailVerificationCode(code)
    user = evc.verify(email)
    if user is not None:
        request.session.flash(
            _('Congratulations, your email has been successfully verified'),
            'success',
        )
        user.verify_email()
        Session.add(user)
        return {
            'verified': True,
        }
    else:
        request.session.flash(
            _('Sorry, your verification code is not correct or has expired'),
            'error',
        )
        return {
            'verified': False,
        }
Ejemplo n.º 32
0
    def test_register_or_update_existing_user(self):
        user = User(screen_name='JohnDoe',
                    first_name='John',
                    last_name='')
        identity = ExternalIdentity(provider='twitter',
                                    external_id='1',
                                    user=user)
        Session.add(user)
        Session.add(identity)
        Session.flush()
        user_id = user.id

        request = testing.DummyRequest()
        request.session = {USER_ATTR: True}
        request.google_analytics = GoogleAnalytics(request)
        response = register_or_update(request, 'twitter', '1', {
            'screen_name': 'JohnDoe',
            'first_name': 'John',
            'last_name': 'Doe',
            'email': '*****@*****.**',
        }, '/next')
        self.assertEqual(response.status, '302 Found')
        self.assertEqual(response.location, '/next')
        user = Session.query(User).filter(User.id == user_id).one()
        self.assertEqual(user.email, '*****@*****.**')
        self.assertEqual(user.last_name, 'Doe')
        self.assertEqual(user.allow_google_analytics, True)
Ejemplo n.º 33
0
    def create(self, collection_id, parent_id, record, id_generator=None,
               unique_fields=None, id_field=DEFAULT_ID_FIELD,
               modified_field=DEFAULT_MODIFIED_FIELD,
               auth=None):
        """Create the specified `object` in this `collection_id` for this `parent_id`.
        Assign the id to the object, using the attribute
        :attr:`cliquet.resource.Model.id_field`.

        .. note::

            This will update the collection timestamp.

        :raises: :exc:`cliquet.storage.exceptions.UnicityError`

        :param str collection_id: the collection id.
        :param str parent_id: the collection parent.

        :param dict record: the object to create.

        :returns: the newly created object.
        :rtype: dict
        """
        obj = self.collection.serialize(record)
        obj.parent_id = parent_id
        setattr(obj, modified_field, datetime.datetime.utcnow())
        try:
            Session.add(obj)
            Session.flush()
        except IntegrityError as e:
            logger.exception('Object %s for collection %s raised %s', record, self.collection, e)
            process_unicity_error(e, Session, self.collection, record)
        # TODO: store new timestamps date
        return self.collection.deserialize(obj)
Ejemplo n.º 34
0
    def test_application_edit_unauthorized(self):
        create_and_login_user(self.testapp)

        app = Application(name='Test Application',
                          main_url='http://example.com',
                          callback_url='http://example.com/callback',
                          authorized_origins=['http://example.com',
                                              'https://example.com'],
                          production_ready=False,
                          image_url='http://example.com/image.png',
                          description='example description')

        other_user = User(screen_name='Alice doe',
                          first_name='Alice',
                          last_name='Doe',
                          email='*****@*****.**')

        other_user.applications.append(app)

        with transaction.manager:
            Session.add(other_user)
            Session.flush()
            app_id = app.id

        res = self.testapp.get('/oauth2/applications/%s/edit' % str(app_id),
                               status=401)
        self.assertEqual(res.status, '401 Unauthorized')
Ejemplo n.º 35
0
    def test_clients_two_apps(self):
        administrator = User(screen_name='Alice doe',
                             first_name='Alice',
                             last_name='Doe',
                             email='*****@*****.**')

        app1 = Application(name='Example app 1',
                           main_url='https://example.com',
                           callback_url='https://example.com/callback',
                           image_url='https://example.com/image.png',
                           description='example description',
                           production_ready=True,
                           user=administrator)

        app2 = Application(name='Example app 2',
                           main_url='https://2.example.com',
                           callback_url='https://2.example.com/callback',
                           production_ready=False,
                           user=administrator)

        with transaction.manager:
            Session.add(app1)
            Session.add(app2)
            Session.flush()

        res = self.testapp.get('/oauth2/clients')
        self.assertEqual(res.status, '200 OK')
        res.mustcontain(
            'Available Clients', 'Example app 1', 'https://example.com',
            'https://example.com/image.png', 'example description',
            no=('Example app 2', 'https://2.example.com'),
        )
Ejemplo n.º 36
0
    def put(self):
        try:
            uuid.UUID(self.password_id)
        except ValueError:
            return invalid_password_id()

        password = self._get_password()
        if password is None:
            return password_not_found()

        else:
            cleaned_data, errors = validate_password(self.request.body,
                                                     self.request.charset)

            if errors:
                result = {'message': ','.join(errors)}
                return HTTPBadRequest(body=json.dumps(result),
                                      charset='utf8',
                                      content_type='application/json')

            password.secret = cleaned_data['secret']
            password.service = cleaned_data['service']
            password.account = cleaned_data['account']
            password.expiration = cleaned_data['expiration']
            password.notes = cleaned_data['notes']
            password.tags = cleaned_data['tags']

            Session.add(password)

            return {'password': password.as_dict()}
Ejemplo n.º 37
0
def new_item(clazz, request):
    text = request.params['text']
    username = request.authenticated_userid
    item = clazz(text=text, user_id=username)
    with transaction.manager:
        db.add(item)

    return came_from(request)
Ejemplo n.º 38
0
 def collection_post(self):
     set_config(self.request.user)
     if self.model.is_readonly:
         raise HTTPBadRequest()
     validate_colander_schema(self._schema, self.request)
     obj = self.model(**self.request.json_body)
     Session.add(obj)
     return obj
Ejemplo n.º 39
0
 def addEvent(self):
     request = self.request
     if 'form.submitted' in request.params:
         name = request.params['name']
         date = request.params['date']
         DBSession.add(Event(EventName=name, EventTime=date))
     events = DBSession.query(Event).order_by(Event.id)
     return {'events': events}
Ejemplo n.º 40
0
    def test_merge_with_itself(self):
        user = User()
        Session.add(user)
        Session.flush()

        self.assertEqual(1, Session.query(User).count())
        self.assertEqual(0, merge_accounts(user, [user.id]))
        self.assertEqual(1, Session.query(User).count())
Ejemplo n.º 41
0
def test_update_instance():
    balloon = BalloonModel(figure=u'Giraffe')
    Session.add(balloon)
    Session.flush()
    request = DummyRequest(matchdict={'id': balloon.id})
    resource = BalloonResource(request)
    resource.update_from_dict({'figure': u'Elephant'})
    assert balloon.figure == u'Elephant'
Ejemplo n.º 42
0
def test_update_instance():
    balloon = BalloonModel(figure=u'Giraffe')
    Session.add(balloon)
    Session.flush()
    request = DummyRequest(matchdict={'id': balloon.id})
    resource = BalloonResource(request)
    resource.update_from_dict({'figure': u'Elephant'})
    assert balloon.figure == u'Elephant'
Ejemplo n.º 43
0
 def test_model_sets_n_automatically(self):
     plan = Plan(employee_n=1, year=2000, month=1)
     Session.add(plan)
     Session.flush()
     assert plan.n is not None
     assert plan.employee_n == 1
     assert plan.year == 2000
     assert plan.month == 1
Ejemplo n.º 44
0
 def create_answer(question, params):
     if 'txt' in params and params['txt'] != '':
         answer = Answer()
         answer.txt = params['txt']
         answer.question_n = question.n
         Session.add(answer)
         Session.flush()
         return answer
Ejemplo n.º 45
0
def new_category(request):
    username = request.authenticated_userid()
    label = request.params['label']
    cat = ItemCategories(label=label, user_id=username)

    with transaction.manager:
        db.add(cat)

    return came_from(request)
Ejemplo n.º 46
0
    def test_model_sets_n_automatically(self):
        question = Question(feature_n=3, txt='CONTENT31', answer_n=311)
        Session.add(question)
        Session.flush()
        assert question.answer_n == 311

        questions = Session.query(Question).filter(
            Question.feature_n == 3).all()
        assert len(questions) == 1
Ejemplo n.º 47
0
    def test_merge_with_invented_users(self):
        user = User()
        Session.add(user)
        Session.flush()

        fake_id = '00000000-0000-0000-0000-000000000000'
        self.assertEqual(1, Session.query(User).count())
        self.assertEqual(0, merge_accounts(user, [fake_id]))
        self.assertEqual(1, Session.query(User).count())
Ejemplo n.º 48
0
    def test_add_childs(self):
        _group12 = FeatureGroup(n=13, name='NAME_FEATURE_GROUP', parent_n=1)
        Session.add(_group12)
        Session.flush()

        _group = FeatureGroup.get(1)
        assert len(_group.children) == 2
        assert _group.children[0].n == 13
        assert _group.children[1].n == 11
Ejemplo n.º 49
0
    def test_authorized_applications(self):
        administrator = User(screen_name='Alice doe',
                             first_name='Alice',
                             last_name='Doe',
                             email='*****@*****.**')
        user = User(screen_name='John Doe',
                    first_name='John',
                    last_name='Doe',
                    email='*****@*****.**')

        app1 = Application(name='Test Application 1',
                           main_url='http://example.com/1',
                           callback_url='http://example.com/1/callback',
                           image_url='http://example.com/1/image.png',
                           description='Test description 1',
                           user=administrator)

        auth_app1 = AuthorizedApplication(
            scope=['scope1'],
            response_type='code',
            redirect_uri='http://example.com/1/callback',
            application=app1,
            user=user,
        )

        app2 = Application(name='Test Application 2',
                           main_url='http://example.com/2',
                           callback_url='http://example.com/2/callback',
                           image_url='http://example.com/2/image.png',
                           description='Test description 2',
                           user=administrator)

        auth_app2 = AuthorizedApplication(
            scope=['scope1'],
            response_type='code',
            redirect_uri='http://example.com/2/callback',
            application=app2,
            user=user,
        )

        with transaction.manager:
            Session.add(user)
            Session.add(app1)
            Session.add(auth_app1)
            Session.add(app2)
            Session.add(auth_app2)
            Session.flush()
            user_id = user.id

        self.testapp.get('/__login/' + str(user_id))

        res = self.testapp.get('/oauth2/authorized-applications')
        self.assertEqual(res.status, '200 OK')
        res.mustcontain('Authorized Applications')
        res.mustcontain('Test Application 1')
        res.mustcontain('Test Application 2')
Ejemplo n.º 50
0
def test_known_id():
    balloon = BalloonModel(figure=u'Giraffe')
    Session.add(balloon)
    Session.flush()
    config = Configurator()
    config.include('rest_toolkit')
    config.scan('resource_sql')
    app = make_app(config)
    r = app.get('/balloons/%s' % balloon.id)
    assert r.json['figure'] == u'Giraffe'
Ejemplo n.º 51
0
 def test_get_accounts_no_provider(self):
     user = User(email='*****@*****.**')
     Session.add(user)
     Session.flush()
     self.assertEqual(user.get_accounts(''), [
         {'id': user.id,
          'is_current': False,
          'is_verified': False,
          'passwords': 0,
          'providers': []}
     ])
Ejemplo n.º 52
0
 def test_scale_existing_scale(self):
     from pyramid_sqlalchemy import Session
     from s4u.image.testing import PNG
     session = Session()
     image = self.Image(PNG)
     session.add(image)
     session.flush()
     scale = self.ImageScale(image, width=123)
     session.add(scale)
     result = image.scale(width=123)
     self.assertTrue(result is scale)
Ejemplo n.º 53
0
    def test_application_delete(self):
        user = User(screen_name='John Doe',
                    first_name='John',
                    last_name='Doe',
                    email='*****@*****.**')

        app = Application(name='Test Application',
                          callback_url='https://example.com/callback',
                          production_ready=False)
        user.applications.append(app)
        auth_app = AuthorizedApplication(
            scope=['scope1'],
            response_type='code',
            redirect_uri='http://example.com/callback',
            application=app,
            user=user,
        )

        with transaction.manager:
            Session.add(user)
            Session.add(auth_app)
            Session.flush()
            app_id = app.id
            user_id = user.id

        self.testapp.get('/__login/' + str(user_id))

        self.assertEqual(Session.query(Application).count(), 1)
        self.assertEqual(Session.query(AuthorizedApplication).count(), 1)

        res = self.testapp.get('/oauth2/applications/%s/delete' % str(app_id))
        self.assertEqual(res.status, '200 OK')
        res.mustcontain('Delete Application <span>Test Application</span>')
        res.mustcontain('Are you sure you want to remove the application')
        res.mustcontain('Yes, I am sure')
        res.mustcontain('No, take me back to the application list')

        # now delete it
        res = self.testapp.post('/oauth2/applications/%s/delete' % str(app_id),
                                {'submit': 'Yes, I am sure'})
        self.assertEqual(res.status, '302 Found')
        self.assertEqual(res.location, 'http://localhost/oauth2/applications')

        try:
            app = Session.query(Application).filter(Application.id == app_id).one()
        except NoResultFound:
            app = None

        self.assertEqual(app, None)

        self.assertEqual(Session.query(User).count(), 1)
        self.assertEqual(Session.query(Application).count(), 0)
        # Related authorizations should be deleted on cascade
        self.assertEqual(Session.query(AuthorizedApplication).count(), 0)