示例#1
0
    def register(self):
        """
        Register a user.

        :returns: A JSON object containing:

            :data:    An object reflecting the registered user.
            :errors: ``null`` if no error was encountered, otherwise an object
                     containing the error message(s).

        Example request::

            http -j POST :/api/users/register [email protected] password=secret confirm=secret profile:='{"first_name": "John", "last_name": "Smith"}'

        Example response:

        .. code-block:: json

            {
                "data": {
                    "api_token": "1a2b3c4d5e",
                    "email": "*****@*****.**",
                    "id": 1,
                    "last_login": "******",
                    "profile": {
                        "first_name": "John",
                        "last_name": "Smith"
                    },
                    "role": "user"
                },
                "errors": {}
            }
        """
        # Initialize request variables
        request = self.request
        flash = request.session.flash
        params = self.validation_results or request.POST
        errors = self.validation_errors
        data = None

        # Check and process form submission
        if errors:
            request.response.status = '422 Unprocessable Entity'
        else:
            try:
                user = User(email=params['email'], password=params['password'])
                user.last_login = datetime.utcnow()
                user.profile = UserProfile(**params['profile'])

                DBSession.add(user)
                DBSession.flush()
            except Exception as exc:
                if 'unique' in str(exc).lower():
                    errors['email'] = 'Email address is already registered'
                    request.response.status = '422 Unprocessable Entity'
                else:
                    errors['_global'] = 'Unable to process register'
                    logger.error('Failed to register user: %s' % exc)
                    request.response.status = '500 Internal Server Error'
            else:
                data = dict(id=user.id,
                            email=user.email,
                            role=user.role,
                            last_login=user.last_login.isoformat(),
                            api_token=user.api_token)
                data['profile'] = dict(first_name=user.profile.first_name,
                                       last_name=user.profile.last_name)

        return dict(data=data, errors=errors)
    def register(self):
        """
        Register a user.

        :returns: A JSON object containing:

            :data:    An object reflecting the registered user.
            :errors: ``null`` if no error was encountered, otherwise an object
                     containing the error message(s).

        Example request::

            http -j POST :/api/users/register [email protected] password=secret confirm=secret profile:='{"first_name": "John", "last_name": "Smith"}'

        Example response:

        .. code-block:: json

            {
                "data": {
                    "api_token": "1a2b3c4d5e",
                    "email": "*****@*****.**",
                    "id": 1,
                    "last_login": "******",
                    "profile": {
                        "first_name": "John",
                        "last_name": "Smith"
                    },
                    "role": "user"
                },
                "errors": {}
            }
        """
        # Initialize request variables
        request = self.request
        flash = request.session.flash
        params = self.validation_results or request.POST
        errors = self.validation_errors
        data = None

        # Check and process form submission
        if errors:
            request.response.status = '422 Unprocessable Entity'
        else:
            try:
                user = User(email=params['email'], password=params['password'])
                user.last_login = datetime.utcnow()
                user.profile = UserProfile(**params['profile'])

                DBSession.add(user)
                DBSession.flush()
            except Exception as exc:
                if 'unique' in str(exc).lower():
                    errors['email'] = 'Email address is already registered'
                    request.response.status = '422 Unprocessable Entity'
                else:
                    errors['_global'] = 'Unable to process register'
                    logger.error('Failed to register user: %s' % exc)
                    request.response.status = '500 Internal Server Error'
            else:
                data = dict(id=user.id, email=user.email, role=user.role,
                            last_login=user.last_login.isoformat(),
                            api_token=user.api_token)
                data['profile'] = dict(first_name=user.profile.first_name,
                                       last_name=user.profile.last_name)

        return dict(data=data, errors=errors)
示例#3
0
    def create(self):
        """
        Create a user.

        :returns: A JSON object containing:

            :data:   An object reflecting the created user.
            :errors: ``null`` if no error was encountered, otherwise an object
                     containing the error message(s).

        Example request::

            http -j POST :/api/users/ [email protected] password=secret profile:='{"first_name": "John", "last_name": "Smith"}' Authorization:"Token ..."

        Example response:

        .. code-block:: json

            {
                "errors": {},
                "data": {
                    "created": "2014-09-23T09:38:25.131009+00:00",
                    "email": "*****@*****.**",
                    "id": 1,
                    "last_login": null,
                    "profile": {
                        "first_name": "John",
                        "last_name": "Smith"
                    },
                    "role": "user",
                    "updated": "2014-09-23T09:38:25.130992+00:00"
                }
            }
        """
        # Initialize request variables
        request = self.request
        params = self.validation_results
        errors = self.validation_errors

        user = None

        if errors:
            request.response.status = '422 Unprocessable Entity'
        else:
            try:
                user = User(params['email'],
                            params['password'],
                            role=params['role'])
                user.profile = UserProfile(**params['profile'])

                DBSession.add(user)
                DBSession.flush()
            except Exception as exc:
                # Prepare the "error" response
                user = None

                if 'unique' in str(exc).lower():
                    errors['email'] = 'Email address must be unique'
                    request.response.status = '422 Unprocessable Entity'
                else:
                    errors['_global'] = 'Unable to process create'
                    logger.error('Failed to create user: %s' % exc)
                    request.response.status = '500 Internal Server Error'
            else:
                request.response.status = '201 Created'

        return dict(data=user, errors=errors)
    def create(self):
        """
        Create a user.

        :returns: A JSON object containing:

            :data:   An object reflecting the created user.
            :errors: ``null`` if no error was encountered, otherwise an object
                     containing the error message(s).

        Example request::

            http -j POST :/api/users/ [email protected] password=secret profile:='{"first_name": "John", "last_name": "Smith"}' Authorization:"Token ..."

        Example response:

        .. code-block:: json

            {
                "errors": {},
                "data": {
                    "created": "2014-09-23T09:38:25.131009+00:00",
                    "email": "*****@*****.**",
                    "id": 1,
                    "last_login": null,
                    "profile": {
                        "first_name": "John",
                        "last_name": "Smith"
                    },
                    "role": "user",
                    "updated": "2014-09-23T09:38:25.130992+00:00"
                }
            }
        """
        # Initialize request variables
        request = self.request
        params = self.validation_results
        errors = self.validation_errors

        user = None

        if errors:
            request.response.status = '422 Unprocessable Entity'
        else:
            try:
                user = User(params['email'], params['password'],
                            role=params['role'])
                user.profile = UserProfile(**params['profile'])

                DBSession.add(user)
                DBSession.flush()
            except Exception as exc:
                # Prepare the "error" response
                user = None

                if 'unique' in str(exc).lower():
                    errors['email'] = 'Email address must be unique'
                    request.response.status = '422 Unprocessable Entity'
                else:
                    errors['_global'] = 'Unable to process create'
                    logger.error('Failed to create user: %s' % exc)
                    request.response.status = '500 Internal Server Error'
            else:
                request.response.status = '201 Created'

        return dict(data=user, errors=errors)