示例#1
0
 def show(self, id, **kwargs):
     id = int(id)
     event = api.find_event_by_id(cherrypy.request.orm_session, id)
     if event:
         registrations = api.get_event_registrations(
             cherrypy.request.orm_session, event.id)
         logger.debug(registrations)
         e = to_collection(event, sort_keys=True)
         e.update({
             'invites':
             [to_collection(i, sort_keys=True) for i in event.invites]
         })
         e.update({
             'registrations':
             [to_collection(r, sort_keys=True) for r in registrations]
         })
         for r in e['registrations']:
             r.update({'cardUrl': aes_encrypt(str(r['id']))})
             r.update({
                 'participant':
                 to_collection(api.find_user_by_id(
                     cherrypy.request.orm_session, r['googler_id']),
                               excludes=('password', 'salt'))
             })
         logger.debug(e)
         return e
     raise HTTPError(404)
示例#2
0
 def show(self, id, **kwargs):
     id = int(id)
     user = api.find_user_by_id(cherrypy.request.orm_session, id)
     if user:
         events = api.find_events_by_user(cherrypy.request.orm_session,
                                          user)
         logger.debug(events)
         u = to_collection(user, excludes=("password", "salt"),
                           sort_keys=True)
         u.update({'events': [
             to_collection(e, sort_keys=True) for e in events]})
         logger.debug(u)
         return u
     raise HTTPError(404)
示例#3
0
 def show(self, id, **kwargs):
     id = int(id)
     user = api.find_user_by_id(cherrypy.request.orm_session, id)
     if user:
         events = api.find_events_by_user(cherrypy.request.orm_session,
                                          user)
         logger.debug(events)
         u = to_collection(user,
                           excludes=('password', 'salt'),
                           sort_keys=True)
         u.update(
             {'events': [to_collection(e, sort_keys=True) for e in events]})
         logger.debug(u)
         return u
     raise HTTPError(404)
示例#4
0
 def create(self, **kwargs):
     req = cherrypy.request
     orm_session = req.orm_session
     event = from_collection(req.json, Event())
     orm_session.add(event)
     orm_session.commit()
     return to_collection(event, sort_keys=True)
示例#5
0
    def google(self, **kwargs):
        req = cherrypy.request
        orm_session = req.orm_session
        try:
            # Aquire API token internally
            pub('oauth-token')

            # Aquire OAuth2Session instance, built with token
            google_api = pub('google-api')

            cherrypy.session['google_user'] = google_api.get(
                'https://www.googleapis.com/oauth2/v1/userinfo').json()

            cherrypy.session['admin_user'] = to_collection(find_admin_by_email(
                orm_session,
                cherrypy.session['google_user']['email']))
            cherrypy.session['google_oauth'] = kwargs

            if cherrypy.session.get('auth_redirect'):
                print('redirect after auth')
                logger.debug('redirect after auth')
                raise HTTPRedirect(cherrypy.session['auth_redirect'])
            else:
                raise HTTPRedirect(url_for_class('controller.Root'))

            return cherrypy.session['admin_user']
        except MissingCodeError as mce:
            raise HTTPError(401,
                            'Error: {}'.format(kwargs.get('error'))) from mce
        except (MismatchingStateError, KeyError) as wrong_state:
            raise HTTPRedirect(
                url_for_class('controller.Root.auth')) from wrong_state
示例#6
0
    def google(self, **kwargs):
        req = cherrypy.request
        orm_session = req.orm_session
        try:
            # Aquire API token internally
            pub('oauth-token')

            # Aquire OAuth2Session instance, built with token
            google_api = pub('google-api')

            cherrypy.session['google_user'] = google_api.get(
                'https://www.googleapis.com/oauth2/v1/userinfo').json()

            cherrypy.session['admin_user'] = to_collection(
                find_admin_by_email(orm_session,
                                    cherrypy.session['google_user']['email']))
            cherrypy.session['google_oauth'] = kwargs

            if cherrypy.session.get('auth_redirect'):
                logger.debug('redirect after auth')
                raise HTTPRedirect(cherrypy.session['auth_redirect'])

            raise HTTPRedirect(url_for_class('controller.Root.admin'))

        except MissingCodeError as mce:
            raise HTTPError(401,
                            'Error: {}'.format(kwargs.get('error'))) from mce
        except (MismatchingStateError, KeyError) as wrong_state:
            raise HTTPRedirect(
                url_for_class('controller.Root.auth')) from wrong_state
示例#7
0
    def sign_in(self):
        # Doc:
        # https://developers.google.com/identity/sign-in/web/backend-auth
        # #using-a-google-api-client-library

        req = cherrypy.request

        try:
            pub('oauth-code-token', req.json['access_code'])

            with pub('google-api') as google_api:
                # TODO: do whatever we need with google_api
                cherrypy.session['google_user'] = google_api.get(
                    'https://www.googleapis.com/oauth2/v1/userinfo').json()

                try:
                    cherrypy.session['admin_user'] = to_collection(
                        api.find_admin_by_email(
                            req.orm_session,
                            cherrypy.session['google_user']['email']))
                except:
                    # It seems he's not an admin. Forgive this
                    pass

                user_info = google_api.get(
                    'https://www.googleapis.com/plus/v1/people/{}'.format(
                        cherrypy.session['google_user']['id'])).json()
        except KeyError as ke:
            raise HTTPError(400, 'Missing input parameter') from ke
        except RequestsHTTPError as httperr:
            raise HTTPError(400, 'Invalid user data') from httperr
        except Exception as exc:
            raise HTTPError(500, 'Some unexpected error happened') from exc
        else:
            return user_info
示例#8
0
    def fake_login(self):
        """This is a method to be used while testing secured area

        It requires `bypass_auth`  option to be enabled in global config
        section and sets fake data about the user into session
        """

        if not cherrypy.config.get('bypass_auth'):
            raise HTTPError(403)

        req = cherrypy.request
        orm_session = req.orm_session

        cherrypy.session['google_user'] = {
            "given_name": "Petryk",
            "gender": "male",
            "link": "https://plus.google.com/+SvyatoslavSydorenko",
            "picture": "https://www.wired.com/wp-content/uploads/blogs"
                       "/wiredenterprise/wp-content/uploads/2012/06"
                       "/Screen-shot-2012-06-18-at-10.32.45-AM.png",
            "name": "Petryk Piatochkin",
            "hd": "gdg.org.ua",
            "email": "*****@*****.**",
            "id": "133555540822907599802",
            "locale": "uk",
            "verified_email": True,
            "family_name": "Piatochkin"
        }
        cherrypy.session['admin_user'] = to_collection(find_admin_by_email(
            orm_session,
            cherrypy.session['google_user']['email']))

        HTTPRedirect(url_for_class('controller.Root'))
示例#9
0
    def sign_in(self):
        # Doc:
        # https://developers.google.com/identity/sign-in/web/backend-auth
        # #using-a-google-api-client-library

        req = cherrypy.request

        try:
            pub('oauth-code-token', req.json['access_code'])

            with pub('google-api') as google_api:
                # TODO: do whatever we need with google_api
                cherrypy.session['google_user'] = google_api.get(
                    'https://www.googleapis.com/oauth2/v1/userinfo').json()

                try:
                    cherrypy.session['admin_user'] = to_collection(
                        api.find_admin_by_email(
                            req.orm_session,
                            cherrypy.session['google_user']['email']))
                except:
                    # It seems he's not an admin. Forgive this
                    pass

                user_info = google_api.get(
                    'https://www.googleapis.com/plus/v1/people/{}'.format(
                        cherrypy.session['google_user']['id'])).json()
        except KeyError as ke:
            raise HTTPError(400, 'Missing input parameter') from ke
        except RequestsHTTPError as httperr:
            raise HTTPError(400, 'Invalid user data') from httperr
        except Exception as exc:
            raise HTTPError(500, 'Some unexpected error happened') from exc
        else:
            return user_info
示例#10
0
 def create(self, **kwargs):
     req = cherrypy.request
     orm_session = req.orm_session
     event = from_collection(req.json, Event())
     orm_session.add(event)
     orm_session.commit()
     return to_collection(event, sort_keys=True)
示例#11
0
 def list_all(self, **kwargs):
     logger.debug('listing users')
     users = api.get_all_users(cherrypy.request.orm_session)
     if users:
         return [to_collection(
             u, excludes=("password", "salt"), sort_keys=True)
             for u in users]
     raise HTTPError(404)
示例#12
0
 def list_own_rooms(self, **kwargs):
     '''
     `user_show_own_rooms`
     [GET] /user/rooms/own
     '''
     user = api.find_user_by_id(cherrypy.request.orm_session,
                                 cherrypy.session['user_id'])
     return [to_collection(room, sort_keys=True) for room in user.own_rooms]
示例#13
0
    def show(self, id:'room id here', **kwargs):
        '''
            `room_list_messages`
            [GET] /room/{id}
        '''

        room_id = int(id)
        room = api.get_room(cherrypy.request.orm_session, id)
        if room:
            msgs = []
            for msg in room.messages:
                author = to_collection(msg.author, excludes=("password", "salt"),
                                        sort_keys=True)
                msg = to_collection(msg, sort_keys=True)
                msg['author'] = author
                msgs.append(msg)
            return msgs
        raise HTTPError(404)
示例#14
0
 def list_all(self, **kwargs):
     logger.debug('listing users')
     users = api.get_all_users(cherrypy.request.orm_session)
     if users:
         return [
             to_collection(u, excludes=('password', 'salt'), sort_keys=True)
             for u in users
         ]
     raise HTTPError(404)
示例#15
0
 def list(self, **kwargs):
     '''
         `room_list`
         [GET] /room/
     '''
     rooms = api.get_all_rooms(cherrypy.request.orm_session)
     if rooms:
         return [to_collection(room, sort_keys=True) for room in rooms]
     raise httperror(404)
示例#16
0
 def show(self, id, **kwargs):
     id = int(id)
     event = api.find_event_by_id(cherrypy.request.orm_session, id)
     if event:
         registrations = api.get_event_registrations(
             cherrypy.request.orm_session, event.id)
         logger.debug(registrations)
         e = to_collection(event, sort_keys=True)
         e.update({'invites': [to_collection(i, sort_keys=True)
                  for i in event.invites]})
         e.update({'registrations': [to_collection(r, sort_keys=True)
                  for r in registrations]})
         for r in e['registrations']:
             r.update({'participant': to_collection(
                 api.find_user_by_id(cherrypy.request.orm_session,
                                     r['googler_id']),
                 excludes=("password", "salt"))})
         logger.debug(e)
         return e
     raise HTTPError(404)
示例#17
0
 def show(self, **kwargs):
     '''
     `user_show`
     [GET] /user/
     '''
     user = api.find_user_by_id(cherrypy.request.orm_session,
                                 cherrypy.session['user_id'])
     if user:
         return to_collection(user, excludes=("password", "salt"),
                           sort_keys=True)
     raise HTTPError(404)
示例#18
0
 def info(self):
     req = cherrypy.request
     user = {'admin': True}
     user.update(req.admin_user)
     user.update(req.google_user)
     user.update(req.google_oauth_token)
     res = {'user': user}
     if user.get('filter_place'):
         res['place'] = to_collection(
             api.get_place_by_id(cherrypy.request.orm_session,
                                 req.admin_user['filter_place']))
     return res
示例#19
0
 def login(self, **kwargs):
     req = cherrypy.request
     orm_session = req.orm_session
     params = req.json
     if 'username' in params and 'password' in params:
         user = api.find_user_by_name(orm_session, params['username'])
         if user and user.validate_password(params['password']):
             cherrypy.session['user_id'] = user.id
             return to_collection(user, excludes=("password", "salt"),
                               sort_keys=True)
         raise HTTPError(401)
     raise HTTPError(400)
示例#20
0
 def update(self, id, **kwargs):
     id = int(id)
     req = cherrypy.request
     orm_session = req.orm_session
     user = api.find_user_by_id(orm_session, id)
     if user:
         user = from_collection(req.json, user)
         orm_session.merge(user)
         orm_session.commit()
         return to_collection(user, excludes=("password", "salt"),
                              sort_keys=True)
     raise HTTPError(404)
示例#21
0
 def show(self, **kwargs):
     '''
     `user_show`
     [GET] /user/
     '''
     user = api.find_user_by_id(cherrypy.request.orm_session,
                                cherrypy.session['user_id'])
     if user:
         return to_collection(user,
                              excludes=("password", "salt"),
                              sort_keys=True)
     raise HTTPError(404)
示例#22
0
 def info(self):
     req = cherrypy.request
     user = {'admin': True}
     user.update(req.admin_user)
     user.update(req.google_user)
     user.update(req.google_oauth_token)
     res = {'user': user}
     if user.get('filter_place'):
         res['place'] = to_collection(
             api.get_place_by_id(
                 cherrypy.request.orm_session,
                 req.admin_user['filter_place']))
     return res
示例#23
0
 def update(self, id, **kwargs):
     id = int(id)
     req = cherrypy.request
     orm_session = req.orm_session
     user = api.find_user_by_id(orm_session, id)
     if user:
         user = from_collection(req.json, user)
         orm_session.merge(user)
         orm_session.commit()
         return to_collection(user,
                              excludes=('password', 'salt'),
                              sort_keys=True)
     raise HTTPError(404)
示例#24
0
 def login(self, **kwargs):
     req = cherrypy.request
     orm_session = req.orm_session
     params = req.json
     if 'username' in params and 'password' in params:
         user = api.find_user_by_name(orm_session, params['username'])
         if user and user.validate_password(params['password']):
             cherrypy.session['user_id'] = user.id
             return to_collection(user,
                                  excludes=("password", "salt"),
                                  sort_keys=True)
         raise HTTPError(401)
     raise HTTPError(400)
示例#25
0
 def create(self, **kwargs):
     '''
     `user_register`
     [POST] /user/
     '''
     req = cherrypy.request
     orm_session = req.orm_session
     user = from_collection(req.json, User())
     orm_session.add(user)
     orm_session.commit()
     cherrypy.session['user_id'] = user.id
     return to_collection(user, excludes=("password", "salt"),
                       sort_keys=True)
示例#26
0
 def record_visit(self, id):
     '''POST /api/events/:id/check-in'''
     req = cherrypy.request
     orm_session = req.orm_session
     reg_id = int(id)
     reg_data = api.get_event_registration_by_id(orm_session, reg_id)
     if not reg_data:
         raise HTTPError(
             400, 'There is no registration record'
             'for id={id}'.format(id=reg_id))
     reg_data.visited = True
     orm_session.merge(reg_data)
     orm_session.commit()
     return to_collection(reg_data, sort_keys=True)
示例#27
0
 def record_visit(self, id):
     '''POST /api/events/:id/check-in'''
     req = cherrypy.request
     orm_session = req.orm_session
     reg_id = int(id)
     reg_data = api.get_event_registration_by_id(orm_session, reg_id)
     if not reg_data:
         raise HTTPError(400,
                         'There is no registration record'
                         'for id={id}'.format(id=reg_id))
     reg_data.visited = True
     orm_session.merge(reg_data)
     orm_session.commit()
     return to_collection(reg_data, sort_keys=True)
示例#28
0
 def create(self, **kwargs):
     '''
     `user_register`
     [POST] /user/
     '''
     req = cherrypy.request
     orm_session = req.orm_session
     user = from_collection(req.json, User())
     orm_session.add(user)
     orm_session.commit()
     cherrypy.session['user_id'] = user.id
     return to_collection(user,
                          excludes=("password", "salt"),
                          sort_keys=True)
示例#29
0
 def create(self, **kwargs):
     req = cherrypy.request
     orm_session = req.orm_session
     u = req.json['user']
     logger.debug(req.json)
     logger.debug(u)
     user = User(**u)
     eu = api.find_user_by_email(orm_session, user.email)
     if eu:
         user.id = eu.id
         orm_session.merge(user)
     else:
         orm_session.add(user)
     orm_session.commit()
     if req.json.get('event'):
         eid = int(req.json['event'])
         # check if the invitation is valid
         i = None
         if req.json.get('invite_code'):
             i = api.find_invitation_by_code(orm_session,
                                             req.json['invite_code'])
             if i is None or i.used or \
                     (i.event is not None and
                         i.event != api.find_event_by_id(
                             orm_session,
                             req.json['event'])) or \
                     (i.email is not None and i.email != user.email):
                 raise HTTPError(403, "Invalid invite code.")
         logger.debug(type(req.json.get('fields')))
         logger.debug(req.json.get('fields'))
         eep = api.get_event_registration(orm_session, user.id, eid)
         ep = EventParticipant(
             id=eep.id if eep else None,
             event_id=eid,
             googler_id=user.id,
             register_date=date.today(),
             fields=req.json['fields'] if req.json.get('fields') else None)
         logger.debug(ep.fields)
         if eep:
             orm_session.merge(ep)
         else:
             orm_session.add(ep)
         if i is not None:
             i.email = user.email
             i.used = True
             orm_session.merge(i)
         orm_session.commit()
         logger.debug(ep.fields)
         logger.debug(type(ep.fields))
     return to_collection(user, sort_keys=True)
示例#30
0
 def create(self, **kwargs):
     req = cherrypy.request
     orm_session = req.orm_session
     u = req.json['user']
     logger.debug(req.json)
     logger.debug(u)
     user = User(**u)
     eu = api.find_user_by_email(orm_session, user.email)
     if eu:
         user.id = eu.id
         orm_session.merge(user)
     else:
         orm_session.add(user)
     orm_session.commit()
     if req.json.get('event'):
         eid = int(req.json['event'])
         # check if the invitation is valid
         i = None
         if req.json.get('invite_code'):
             i = api.find_invitation_by_code(orm_session,
                                             req.json['invite_code'])
             if i is None or i.used or \
                     (i.event is not None and
                         i.event != api.find_event_by_id(
                             orm_session,
                             req.json['event'])) or \
                     (i.email is not None and i.email != user.email):
                 raise HTTPError(403, "Invalid invite code.")
         logger.debug(type(req.json.get('fields')))
         logger.debug(req.json.get('fields'))
         eep = api.get_event_registration(orm_session, user.id, eid)
         ep = EventParticipant(
             id=eep.id if eep else None, event_id=eid, googler_id=user.id,
             register_date=date.today(),
             fields=req.json['fields'] if req.json.get('fields') else None)
         logger.debug(ep.fields)
         if eep:
             orm_session.merge(ep)
         else:
             orm_session.add(ep)
         if i is not None:
             i.email = user.email
             i.used = True
             orm_session.merge(i)
         orm_session.commit()
         logger.debug(ep.fields)
         logger.debug(type(ep.fields))
     return to_collection(user, sort_keys=True)
示例#31
0
    def join_user(self, **kwargs):
        '''
            `room_join_user`
            [PUT] /room/{id}
        '''

        req = cherrypy.request
        orm_session = req.orm_session
        room = api.get_room(orm_session, req.json['room_id'])
        user = api.find_user_by_id(orm_session, cherrypy.session['user_id'])
        if room:
            room.members.append(user)
            orm_session.merge(room) # add() ?
            orm_session.commit()
            return to_collection(room, sort_keys=True)
        raise HTTPError(400)
示例#32
0
 def update(self, id, **kwargs):
     id = int(id)
     req = cherrypy.request
     orm_session = req.orm_session
     event = api.find_event_by_id(orm_session, id)
     logger.debug(event)
     if event:
         # Caution! crunches ahead
         event = from_collection(req.json, event,
                                 excludes=['fields'])  # skip jsonencoded
         # since 'hidden' is not implemented in the model, skip it for now
         event.fields = req.json['fields']  # and set them manually
         orm_session.merge(event)
         orm_session.commit()
         return to_collection(event, sort_keys=True)
     raise HTTPError(404)
示例#33
0
 def update(self, id, **kwargs):
     id = int(id)
     req = cherrypy.request
     orm_session = req.orm_session
     event = api.find_event_by_id(orm_session, id)
     logger.debug(event)
     if event:
         # Caution! crunches ahead
         event = from_collection(req.json, event,
                                 excludes=['fields'])  # skip jsonencoded
         # since 'hidden' is not implemented in the model, skip it for now
         event.fields = req.json['fields']  # and set them manually
         orm_session.merge(event)
         orm_session.commit()
         return to_collection(event, sort_keys=True)
     raise HTTPError(404)
示例#34
0
 def create(self, **kwargs):
     '''
         `room_create`
         [POST] /room/
     '''
     req = cherrypy.request
     orm_session = req.orm_session
     room = from_collection(req.json, Room())
     room.creator_id = cherrypy.session['user_id']
     user = api.find_user_by_id(orm_session, cherrypy.session['user_id'])
     room.members.append(user)
     try:
         orm_session.add(room)
         orm_session.commit()
         return to_collection(room, sort_keys=True)
     except sqlalchemy.exc.IntegrityError:
         raise HTTPError(403)
示例#35
0
 def post_message(self, id, **kwargs):
     '''
         `room_post_message`
         [POST] /room/{id}
     '''
     req = cherrypy.request
     req.json['user_id'] = cherrypy.session['user_id']
     req.json['room_id'] = int(id)
     if 'meta' not in req.json:
         req.json['meta'] = {}
     orm_session = req.orm_session
     msg = from_collection(req.json, Message())
     orm_session.add(msg)
     orm_session.commit()
     resp = to_collection(msg, sort_keys=True)
     #resp['author'] = to_collection(msg.author, sort_keys=True)
     return resp
示例#36
0
    def fake_login(self):
        """This is a method to be used while testing secured area

        It requires `bypass_auth`  option to be enabled in global config
        section and sets fake data about the user into session
        """

        if not cherrypy.config.get('global', {}).get('bypass_auth'):
            raise HTTPError(403)

        req = cherrypy.request
        orm_session = req.orm_session

        cherrypy.session['google_user'] = {
            "given_name":
            "Petryk",
            "gender":
            "male",
            "link":
            "https://plus.google.com/+SvyatoslavSydorenko",
            "picture":
            "https://www.wired.com/wp-content/uploads/blogs"
            "/wiredenterprise/wp-content/uploads/2012/06"
            "/Screen-shot-2012-06-18-at-10.32.45-AM.png",
            "name":
            "Petryk Piatochkin",
            "hd":
            "gdg.org.ua",
            "email":
            "*****@*****.**",
            "id":
            "133555540822907599802",
            "locale":
            "uk",
            "verified_email":
            True,
            "family_name":
            "Piatochkin"
        }
        cherrypy.session['admin_user'] = to_collection(
            find_admin_by_email(orm_session,
                                cherrypy.session['google_user']['email']))

        HTTPRedirect(url_for_class('controller.Root'))
示例#37
0
    def create(self, secret_key, **kwargs):
        orm_session = cherrypy.request.orm_session

        if secret_key != self.secret_key:
            logger.debug('Invalid secret.')
            logger.debug(kwargs)
            raise HTTPError(403, 'Invalid secret.')

        if cherrypy.request.method != 'POST':
            return {'status':'ok'}

        logger.debug('Integration query')

        parsed_params = parse_mailchimp_params(kwargs)
        logger.debug(parsed_params)
        logger.debug(parsed_params['data'])

        #mc_event = from_collection(parsed_params, MailChimpEvents())
        mc_event = MailChimpEvents(**parsed_params)
        logger.debug(mc_event.data)
        orm_session.merge(mc_event)
        orm_session.commit()

        return to_collection(mc_event, sort_keys=True, excludes=('id',))
示例#38
0
    def test_to_collection(self):
        self.assertEqual(1, to_collection(1))
        self.assertEqual(1.1, to_collection(1.1))
        self.assertEqual("str", to_collection("str"))
        self.assertEqual([1, 2, 3], to_collection([1, 2, 3]))
        self.assertEqual([1, 2, 3], to_collection((1, 2, 3)))
        self.assertEqual([1, 2, 3], to_collection(set([1, 2, 3])))
        self.assertEqual([1, 2, 3], to_collection(frozenset([1, 2, 3])))
        self.assertEqual({"1": [2]}, to_collection({1: [2]}))
        self.assertEqual({"a": [1, 2], "b": 2}, to_collection({"a": set([1, 2]), "b": 2}))

        doc = {'date': {'date': '2012-01-01'},
               'time': {'time': '00:00:00'},
               'interval': {'interval': 3600},
               'id': 1,
               'discriminator': 'derived',
               'derivedprop': 2,
               'datetime': {'datetime': '2012-01-01T00:00:00'},
               'geo': {'type': 'Point',
                       'coordinates': (45, 45)}}

        session = Session()
        te = session.query(TestEntity).get(1)
        result = to_collection(te)
        self.assertEqual(doc, result)

        doc = {'date': {'date': '2012-01-01'},
               'time': {'time': '00:00:00'},
               'interval': {'interval': 3600},
               'id': 1,
               'discriminator': 'derived',
               'derivedprop': 2,
               'datetime': {'datetime': '2012-01-01T00:00:00'},
               'geo': {'type': 'Point',
                       'coordinates': (45, 45)},
               'related': [{'id': 1,
                            'discriminator': 'related',
                            'key': u'related1',
                            'parent_id': 1},
                           {'id': 2,
                            'discriminator': 'relatedsubclass',
                            'key': u'related2',
                            'parent_id': 1,
                            'subclass_prop': u'sub1'}]}

        te = session.query(TestEntity).get(1)
        result = to_collection(te, recursive=True)
        self.assertEqual(doc, result)

        serialized_doc = '{"date": {"date": "2012-01-01"}, "datetime": {"datetime": "2012-01-01T00:00:00"}, "derivedprop": 2, "discriminator": "derived", "geo": {"coordinates": [45.0, 45.0], "type": "Point"}, "id": 1, "interval": {"interval": 3600}, "related": [{"discriminator": "related", "id": 1, "key": "related1", "parent_id": 1}, {"discriminator": "relatedsubclass", "id": 2, "key": "related2", "parent_id": 1, "subclass_prop": "sub1"}], "time": {"time": "00:00:00"}}'
        result = to_collection(te, format="json", recursive=True, sort_keys=True)
        self.assertEqual(serialized_doc, result)

        doc = {'date': {'date': '2012-01-01'},
               'time': {'time': '00:00:00'},
               'discriminator': 'derived',
               'datetime': {'datetime': '2012-01-01T00:00:00'},
               'combined': {'datetime': '2012-01-01T00:00:00'},
               'geo': {'type': 'Point', 'coordinates': (45, 45)}}

        self.assertEqual(doc, to_collection(te, includes=["combined"],
                                            excludes=["id", "interval", "derivedprop", "related"]))
        self.assertEqual("a", to_collection("a"))
        self.assertEqual(1, to_collection(1))
        self.assertEqual(1.1, to_collection(1.1))
        self.assertEqual({'date': '2012-01-01'}, to_collection(date(2012, 1, 1)))
        self.assertEqual({'time': '00:00:00'}, to_collection(time(0, 0, 0)))
        self.assertEqual({'interval': 3600}, to_collection(timedelta(seconds=3600)))
        self.assertEqual({'datetime': '2012-01-01T00:00:00'}, to_collection(datetime(2012, 1, 1, 0, 0, 0)))
        self.assertEqual({'type': 'Point', 'coordinates': (45, 45)}, to_collection(te.geo))

        tes = session.query(TestEntity).all()
        result = to_collection(tes, recursive=True,
                               includes={DerivedTestEntity: set(['combined'])},
                               excludes={DerivedTestEntity: set(['id', 'interval', 'derivedprop'])},
                               format="json", sort_keys=True)

        serialized_doc = '[{"combined": {"datetime": "2012-01-01T00:00:00"}, "date": {"date": "2012-01-01"}, "datetime": {"datetime": "2012-01-01T00:00:00"}, "discriminator": "derived", "geo": {"coordinates": [45.0, 45.0], "type": "Point"}, "related": [{"discriminator": "related", "id": 1, "key": "related1", "parent_id": 1}, {"discriminator": "relatedsubclass", "id": 2, "key": "related2", "parent_id": 1, "subclass_prop": "sub1"}], "time": {"time": "00:00:00"}}, {"date": {"date": "2013-02-02"}, "datetime": {"datetime": "2013-02-02T01:01:01"}, "discriminator": "base", "geo": {"coordinates": [46.0, 44.0], "type": "Point"}, "id": 2, "interval": {"interval": 3601}, "related": [{"discriminator": "related", "id": 3, "key": "related3", "parent_id": 2}, {"discriminator": "related", "id": 4, "key": "related4", "parent_id": 2}], "time": {"time": "01:01:01"}}]'
        self.assertEqual(serialized_doc, result)
示例#39
0
 def list_all(self, **kwargs):
     places = api.get_all_gdg_places(cherrypy.request.orm_session)
     if places:
         return [to_collection(p, sort_keys=True) for p in places]
     raise HTTPError(404)
示例#40
0
 def list_all(self, **kwargs):
     events = api.get_all_events(cherrypy.request.orm_session)
     return [to_collection(e, sort_keys=True)
             for e in events] if events else []
示例#41
0
    def create(self, **kwargs):
        req = cherrypy.request
        orm_session = req.orm_session

        try:
            event_id = int(req.json['event'])
        except (ValueError, TypeError, KeyError):
            raise HTTPError(400, 'Invalid `event` param')

        event = api.find_event_by_id(orm_session, event_id)
        if not event:
            raise HTTPError(404, 'Event not found')

        # Get request data
        u = req.json.get('user', {})
        fields = req.json.get('fields', {})

        # Validate form data
        regform = RegistrationForm(hidden=None, formdata=InputDict(u))
        fieldsform_cls = get_additional_fields_form_cls(event.fields)
        fieldsform = fieldsform_cls(InputDict(fields))
        if not all([regform.validate(), fieldsform.validate()]):
            errors = deepcopy(regform.errors)
            errors.update(fieldsform.errors)
            raise InvalidFormDataError(errors)

        # Registration BL
        user = User(**u)

        invitation = None
        if req.json.get('invite_code'):
            invitation = api.find_invitation_by_code(orm_session,
                                                     req.json['invite_code'])

            # check if the invitation is valid
            if (invitation is None or invitation.used
                    or (invitation.event and invitation.event.id != event.id)
                    or (invitation.email is not None
                        and invitation.email != user.email)):
                raise HTTPError(403, 'Invalid invite code.')

        eu = api.find_user_by_email(orm_session, user.email)
        if eu:
            user.id = eu.id
            orm_session.merge(user)
        else:
            orm_session.add(user)
        orm_session.flush()

        eep = api.get_event_registration(orm_session, user.id, event.id)
        ep = EventParticipant(
            id=eep.id if eep else None,
            event_id=event.id,
            googler_id=user.id,
            register_date=date.today(),
            fields=fields,
        )

        if eep:
            orm_session.merge(ep)
        else:
            orm_session.add(ep)
        if invitation is not None:
            invitation.email = user.email
            invitation.used = True
            orm_session.merge(invitation)
        orm_session.commit()

        return to_collection(user, sort_keys=True)
示例#42
0
    def create(self, **kwargs):
        req = cherrypy.request
        orm_session = req.orm_session

        try:
            event_id = int(req.json['event'])
        except (ValueError, TypeError, KeyError):
            raise HTTPError(400, 'Invalid `event` param')

        event = api.find_event_by_id(orm_session, event_id)
        if not event:
            raise HTTPError(404, 'Event not found')

        # Get request data
        u = req.json.get('user', {})
        fields = req.json.get('fields', {})

        # Validate form data
        regform = RegistrationForm(hidden=None, formdata=InputDict(u))
        fieldsform_cls = get_additional_fields_form_cls(event.fields)
        fieldsform = fieldsform_cls(InputDict(fields))
        if not all([regform.validate(), fieldsform.validate()]):
            errors = deepcopy(regform.errors)
            errors.update(fieldsform.errors)
            raise InvalidFormDataError(errors)

        # Registration BL
        user = User(**u)

        invitation = None
        if req.json.get('invite_code'):
            invitation = api.find_invitation_by_code(
                orm_session, req.json['invite_code']
            )

            # check if the invitation is valid
            if (
                invitation is None or invitation.used or
                (invitation.event and invitation.event.id != event.id) or
                (invitation.email is not None and invitation.email != user.email)
            ):
                raise HTTPError(403, 'Invalid invite code.')

        eu = api.find_user_by_email(orm_session, user.email)
        if eu:
            user.id = eu.id
            orm_session.merge(user)
        else:
            orm_session.add(user)
        orm_session.flush()

        eep = api.get_event_registration(orm_session, user.id, event.id)
        ep = EventParticipant(
            id=eep.id if eep else None,
            event_id=event.id,
            googler_id=user.id,
            register_date=date.today(),
            fields=fields,
        )

        if eep:
            orm_session.merge(ep)
        else:
            orm_session.add(ep)
        if invitation is not None:
            invitation.email = user.email
            invitation.used = True
            orm_session.merge(invitation)
        orm_session.commit()

        return to_collection(user, sort_keys=True)
示例#43
0
 def list_all(self, **kwargs):
     events = api.get_all_events(cherrypy.request.orm_session)
     return [to_collection(e, sort_keys=True)
             for e in events] if events else []
示例#44
0
 def list_all(self, **kwargs):
     places = api.get_all_gdg_places(cherrypy.request.orm_session)
     if places:
         return [to_collection(p, sort_keys=True) for p in places]
     raise HTTPError(404)