コード例 #1
0
    def post(self):
        """Create a new User object following the User model.

        Yields:
            Save a new User with the required username, email, password
            fields.
            Hash the password.
            Create three Snippets for the user to have some UI to play with
            upon authentication.
        Flags:
            Errors and returns status code with error message,
                200, otherwise.
        Returns:
            {dict}: JSON Flask Response
                with an access token and a username.
                sets a refresh cookie in headers.
        Note:
            The computation to update, save, reload a Snippet is required to
            ensure Objects have fully landed before they are referenced. It is extra 
            complicated for this endpoint as we are awaiting reloads for three models:
            User, Collection and Snippet, all of which vary in `having to exist` before
            the other.
        """
        try:
            body = request.get_json()
            user = User(**body)

            user.hash_password()
            user.save()
            user.reload()

            now = datetime.datetime.now(datetime.timezone.utc)

            id = user.id
            username = user.username

            # Required to instantiate a new reference to the very same
            # and very new User for the purposes of attaching an owner
            # to the snippets.
            saved_user = User.objects.get(username=username)

            snippet_py = Snippet(
                title="{}.py".format(username),
                tags=["first post"],
                description="From Cheat-Hub",
                language="python",
                value="print('hello {}')".format(username),
                addedBy=saved_user,
                addedOn=now,
            )

            snippet_js = Snippet(
                title="{}.js".format(username),
                tags=["first post"],
                description="From Cheat-Hub",
                language="javascript",
                value="console.log('hello {}');".format(username),
                addedBy=saved_user,
                addedOn=now,
            )

            snippet_sh = Snippet(
                title="{}.sh".format(username),
                tags=["first post"],
                description="From Cheat-Hub",
                language="bash",
                value="#!/bin/bash\n\necho 'hello {}'".format(username),
                addedBy=saved_user,
                addedOn=now,
            )

            snippet_py.save()
            snippet_py.reload()
            snippet_js.save()
            snippet_js.reload()
            snippet_sh.save()
            snippet_sh.reload()

            user.update(push_all__snippets_created=[
                snippet_py, snippet_js, snippet_sh
            ])
            user.save()
            user.reload()

            collection = Collection(
                name="Greetings {}".format(username),
                snippets=[snippet_py, snippet_js, snippet_sh],
                date=now,
                owner=user,
            )

            collection.save()

            user.update(push__collections=collection)
            user.save()

            expires = datetime.timedelta(hours=3)
            access_token = create_access_token(identity=str(username),
                                               expires_delta=expires)
            refresh_token = create_refresh_token(identity=str(id),
                                                 expires_delta=expires)
            refresh_cookie = [("Set-Cookie",
                               "refresh_token={}".format(refresh_token))]

            return (
                {
                    "access_token": access_token,
                    "username": username,
                },
                200,
                refresh_cookie,
            )

        except FieldDoesNotExist:
            return {"message": "Request is missing required fields."}, 400

        except NotUniqueError:
            return {
                "message": "User with given email address already exists."
            }, 401

        except Exception as e:
            return {"message": "Something went wrong."}, 500