Dylan  Iqbal

Dylan Iqbal

1559276342

Using JWTs for GraphQL Authorization with Hasura

Learn about the Hasura platform and how their GraphQL APIs can be secured using JSON Web Tokens

If you’re developing an API today for consumption by third-parties, you’d be more than forgiven for choosing the REST interface to develop the API, as it is a tried and tested standard for delivering data to consumers, as well as accepting changes to the data in a structured way. In more recent times, GraphQL has become an attractive alternative for developing APIs thanks to its flexible, semantic, and performant nature.

But what if you’d like finer control over the details of the data exchange, including integration with third-party authorization servers using JWTs, and being able to quickly and easily set role-based permissions at the field level?

That’s what Hasura have achieved with their GraphQL platform that generates a GraphQL API over a PostgreSQL database. To highlight just a few of the features:

[“The Hasura platform takes advantage of JWT and GraphQL technologies to provide a platform for querying and manipulating data in a PostgreSQL database, taking into account the role specified in the authorization token.”> [“The Hasura platform takes advantage of JWT and GraphQL technologies to provide a platform for querying and manipulating data in a PostgreSQL database, taking into account the role specified in the authorization token.”## A Short Introduction to JSON Web Tokens

From jwt.io:

[“The Hasura platform takes advantage of JWT and GraphQL technologies to provide a platform for querying and manipulating data in a PostgreSQL database, taking into account the role specified in the authorization token.”
What this looks like in practice is a string that is made up of three parts separated by a period:

A JWT is issued as a result of a user authenticating with an authorization server. In the case of the Hasura platform, this JWT can then be used to authorize the request and as such can make queries and mutations depending on the claims present in the token. We will see how this works in the demo a little bit later in the article.

The compact nature of a JWT makes it easy to pass around in query strings, headers, and request bodies, or store in a cookie.

What is GraphQL? An Overview

GraphQL is essentially a query language that allows you to define your API in terms of types. It is datastore-agnostic and has server-side support for many different platforms and languages. Instead of defining your API in terms of status codes and semantic URLs, you define the types and then construct queries using a familiar but powerful syntax. As an example:

{
  article {
    id,
    title,
    author {
      name
    }
  }
}


This describes a query for articles, returning the id, title, and the author’s name. As you can see, it supports nested database objects (the author is another table in the schema, linked to from an article). Mutations can also be defined, which describe how to change data.

In addition, multiple queries can be made in a single request, which is most useful when a client wants to retrieve lots of possibly unrelated data points from the server.

The Hasura Approach

The Hasura platform takes advantage of these technologies to provide a platform for querying and manipulating data in a PostgreSQL database, taking into account the role specified in the authorization token.

The Hasura console allows the user to create a database, define its schema, and populate it with data. Hasura will then generate a GraphQL API on top of this database, automatically generating the appropriate types, queries, and mutations that allow the client to completely query for and manipulate the underlying data.

Hasura takes a role-based approach to authorization, and as such an individual role’s access can be narrowed down to only a subset of the overall schema (even down to the field level). As each role is mapped to certain authorization rules, it can even be prevented from running certain mutations if so desired. Furthermore, queries can be delegated to an upstream service based on the claims present in the authorization token.

Custom claims inside the JWT are used to tell Hasura about the role of the caller, so that Hasura may enforce the necessary authorization rules to decide what the caller can and cannot do.

[Source]

An example of the claims used by Hasura may look like the following:

{
  "https://hasura.io/jwt/claims": {
    "x-hasura-default-role": "anonymous",
    "x-hasura-allowed-roles": [
      "user",
      "anonymous"
    ]
}


These two keys define the possible roles as well as the default role in the absence of the “X-Hasura-Role” header. In the case of Auth0, these custom claims can be put in place using Rules, a platform feature that can be used to dynamically enhance tokens as users are authenticated.

Demo: Querying Data

Let’s have a look at how authorization with Hasura and JWTs works in practice. A demo has been set up that will allow you to construct queries and see the role-based permissions system in action.

This demo has been pre-configured with a database that has authors, articles, tags, and a relationship table that joins many articles to many tags. Let’s see how we can query for some of this data.

Executing anonymous queries

Browse to https://auth0-hasura-demo.herokuapp.com, and use “hasurademo” as the access key.

Next, you will be presented with the Hasura console:

The interface gives you the opportunity to specify some request headers that will be used when querying the GraphQL interface. To demonstrate how the user’s role affects their ability to query and modify data, remove the X-Hasura-Access-Key header by clicking on the cross on the right-hand side, and enter a new header X-Hasura-Role with a value of “anonymous”:

Now, let’s make a query. Use the following query inside the Graphiql query entry area in the lower half of the screen:

{
  article {
    id,
    title
  }
}


To run the query, press Ctrl+Enter (Cmd+Enter if you’re on a Mac), or click on the large ‘play’ button above the query panel. You will see the results of the query on the right-hand side of the screen; you have successfully managed to retrieve the results for two articles that are currently in the database!

Now let’s try a mutation. Alter the query so that it executes the following mutation:

mutation {
  insert_tag(objects:[{name:"<YOUR TAG NAME HERE>"}]) {
    returning {
      name
    }
  }
}


This is a mutation that inserts a new tag with your specified tag name into the database. You should replace the value <YOUR TAG NAME HERE> with a value of your choosing.

Running this mutation right now will return an error, letting you know that the mutation does not exist.

This is correct since the permissions have effectively been set up so that the anonymous role cannot make changes to the database. This is also indicated by the GraphQL API docs, as it does not show any mutations that can be called by this role. To see this, click the “< Docs” button on the right-hand side of the query window to open the API documentation.

Only queries and subscriptions are available as root types here, but no mutations.

Let’s have a closer look at how permissions are set within the Hasura interface.

Validating query permissions

To view the permissions matrix for the “tag” table:

  1. Click the “data” tab at the top of the screen
  2. Click the “tag” table on the left-hand side
  3. Click the “permissions” tab in the main part of the interface

You will arrive at a matrix that describes all the role permissions for the “tag” table. On this screen we can see a number of things:

You can see here that, since the “anonymous” user cannot modify or insert any data, it makes sense that there are no mutations available.

Let’s now switch to the “user” role and see how we can make this mutation work.

Executing Authorized Queries

Click the “Graphiql” heading at the top of the screen to return to the query interface. Now, change the “X-Hasura-Role” request header so that its value is “user”.

If you try to run the mutation again now, you will notice that it will fail for the same reason as before. This is because the “user” role needs to also provide a valid JWT in order to be properly authorized to run this mutation.

[“The Hasura platform takes advantage of JWT and GraphQL technologies to provide a platform for querying and manipulating data in a PostgreSQL database, taking into account the role specified in the authorization token.”> [“The Hasura platform takes advantage of JWT and GraphQL technologies to provide a platform for querying and manipulating data in a PostgreSQL database, taking into account the role specified in the authorization token.”### Generating a valid JWT

For the purposes of this demo, a tool has been provided to make it easy for you to generate a JWT and run this mutation.

Browse to https://auth0-hasura-demo.now.sh/ and log in with your Auth0 account. If you do not currently have one, you can register for a free account.

[“The Hasura platform takes advantage of JWT and GraphQL technologies to provide a platform for querying and manipulating data in a PostgreSQL database, taking into account the role specified in the authorization token.”

Once logged in, you will be able to see your token. Select the entire token string and press Ctrl+C (or Cmd+C on a Mac) to copy it into your clipboard.

Before we head back to the Hasura console, let’s inspect the token to see if it contains the claims that we inspect. Head to http://jwt.io, scroll down and paste the token into the left-hand side of the screen. The right-hand side will automatically update to show you the data contained within the token, and you should be able to see that the correct Hasura claims have been included:

With the token still in your clipboard, head back to the Hasura console. The way we attach this token to the request is through the standard “Authorization” request header.

Add a new header into the “headers” section, specifying the Authorization header and the JWT that you have in your clipboard as the bearer token:

Next, try running the mutation again. You should find that the query now works and that the name of the tag is being played back to you in the response:

[“The Hasura platform takes advantage of JWT and GraphQL technologies to provide a platform for querying and manipulating data in a PostgreSQL database, taking into account the role specified in the authorization token.”
Before we head away from this screen, let’s expand the API docs again to show that the “mutations” root now appears and that you can browse through all the available mutations given that you are now authorized to do so:

Finally, to prove that the mutation has worked we can explore the raw data in the database. Once again, click the “Data” heading at the top of the screen and then click on the “tags” table on the left.

The resulting screen will show you the data that is present in the table, and you can see that the “example-tag” entry that was created by the mutation is there.

Wrapping Up

In this post, you learned a bit about GraphQL and the main differences from a traditional REST API. You also had an introduction to JSON Web Tokens, how they are made up, and how easy they are to pass around.

Next, you discovered how Hasura tackles the idea of a role-based architecture when it comes to securing GraphQL APIs, and how it uses JWTs to authorize incoming requests and grant permissions to specific areas of the schema, even down to the field level.

Finally, you had a practical look at the Hasura platform, learning how to perform anonymous queries, and how to perform authorized mutations using a JWT that was issued to you by Auth0.

Learn More

Build a Simple Web App with Express, Angular, and GraphQL

GraphQL Tutorial: Understanding Spring Data JPA/SpringBoot

How to set up GraphQL with Golang: a deep dive from basics to advanced

Build a Health Tracking App with React, GraphQL, and User Authentication

The Modern GraphQL Bootcamp (Advanced Node.js)

NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

GraphQL with React: The Complete Developers Guide

GraphQL with Angular & Apollo - The Full-stack Guide

GraphQL: Learning GraphQL with Node.Js

Complete guide to building a GraphQL API

GraphQL: Introduction to GraphQL for beginners

#graphql #json #web-development

What is GEEK

Buddha Community

Using JWTs for GraphQL Authorization with Hasura

Why Use WordPress? What Can You Do With WordPress?

Can you use WordPress for anything other than blogging? To your surprise, yes. WordPress is more than just a blogging tool, and it has helped thousands of websites and web applications to thrive. The use of WordPress powers around 40% of online projects, and today in our blog, we would visit some amazing uses of WordPress other than blogging.
What Is The Use Of WordPress?

WordPress is the most popular website platform in the world. It is the first choice of businesses that want to set a feature-rich and dynamic Content Management System. So, if you ask what WordPress is used for, the answer is – everything. It is a super-flexible, feature-rich and secure platform that offers everything to build unique websites and applications. Let’s start knowing them:

1. Multiple Websites Under A Single Installation
WordPress Multisite allows you to develop multiple sites from a single WordPress installation. You can download WordPress and start building websites you want to launch under a single server. Literally speaking, you can handle hundreds of sites from one single dashboard, which now needs applause.
It is a highly efficient platform that allows you to easily run several websites under the same login credentials. One of the best things about WordPress is the themes it has to offer. You can simply download them and plugin for various sites and save space on sites without losing their speed.

2. WordPress Social Network
WordPress can be used for high-end projects such as Social Media Network. If you don’t have the money and patience to hire a coder and invest months in building a feature-rich social media site, go for WordPress. It is one of the most amazing uses of WordPress. Its stunning CMS is unbeatable. And you can build sites as good as Facebook or Reddit etc. It can just make the process a lot easier.
To set up a social media network, you would have to download a WordPress Plugin called BuddyPress. It would allow you to connect a community page with ease and would provide all the necessary features of a community or social media. It has direct messaging, activity stream, user groups, extended profiles, and so much more. You just have to download and configure it.
If BuddyPress doesn’t meet all your needs, don’t give up on your dreams. You can try out WP Symposium or PeepSo. There are also several themes you can use to build a social network.

3. Create A Forum For Your Brand’s Community
Communities are very important for your business. They help you stay in constant connection with your users and consumers. And allow you to turn them into a loyal customer base. Meanwhile, there are many good technologies that can be used for building a community page – the good old WordPress is still the best.
It is the best community development technology. If you want to build your online community, you need to consider all the amazing features you get with WordPress. Plugins such as BB Press is an open-source, template-driven PHP/ MySQL forum software. It is very simple and doesn’t hamper the experience of the website.
Other tools such as wpFoRo and Asgaros Forum are equally good for creating a community blog. They are lightweight tools that are easy to manage and integrate with your WordPress site easily. However, there is only one tiny problem; you need to have some technical knowledge to build a WordPress Community blog page.

4. Shortcodes
Since we gave you a problem in the previous section, we would also give you a perfect solution for it. You might not know to code, but you have shortcodes. Shortcodes help you execute functions without having to code. It is an easy way to build an amazing website, add new features, customize plugins easily. They are short lines of code, and rather than memorizing multiple lines; you can have zero technical knowledge and start building a feature-rich website or application.
There are also plugins like Shortcoder, Shortcodes Ultimate, and the Basics available on WordPress that can be used, and you would not even have to remember the shortcodes.

5. Build Online Stores
If you still think about why to use WordPress, use it to build an online store. You can start selling your goods online and start selling. It is an affordable technology that helps you build a feature-rich eCommerce store with WordPress.
WooCommerce is an extension of WordPress and is one of the most used eCommerce solutions. WooCommerce holds a 28% share of the global market and is one of the best ways to set up an online store. It allows you to build user-friendly and professional online stores and has thousands of free and paid extensions. Moreover as an open-source platform, and you don’t have to pay for the license.
Apart from WooCommerce, there are Easy Digital Downloads, iThemes Exchange, Shopify eCommerce plugin, and so much more available.

6. Security Features
WordPress takes security very seriously. It offers tons of external solutions that help you in safeguarding your WordPress site. While there is no way to ensure 100% security, it provides regular updates with security patches and provides several plugins to help with backups, two-factor authorization, and more.
By choosing hosting providers like WP Engine, you can improve the security of the website. It helps in threat detection, manage patching and updates, and internal security audits for the customers, and so much more.

Read More

#use of wordpress #use wordpress for business website #use wordpress for website #what is use of wordpress #why use wordpress #why use wordpress to build a website

Elm Graphql: Autogenerate Type-safe GraphQL Queries in Elm

dillonkearns/elm-graphql  

Why use this package over the other available Elm GraphQL packages? This is the only one that generates type-safe code for your entire schema. Check out this blog post, Type-Safe & Composable GraphQL in Elm, to learn more about the motivation for this library. (It's also the only type-safe library with Elm 0.18 or 0.19 support, see this discourse thread).

I built this package because I wanted to have something that:

  1. Gives you type-safe GraphQL queries (if it compiles, it's valid according to the schema),
  2. Creates decoders for you in a seamless and failsafe way, and
  3. Eliminates GraphQL features in favor of Elm language constructs where possible for a simpler UX (for example, GraphQL variables & fragments should just be Elm functions, constants, lets).

See an example in action on Ellie. See more end-to-end example code in the examples/ folder.

Overview

dillonkearns/elm-graphql is an Elm package and accompanying command-line code generator that creates type-safe Elm code for your GraphQL endpoint. You don't write any decoders for your API with dillonkearns/elm-graphql, instead you simply select which fields you would like, similar to a standard GraphQL query but in Elm. For example, this GraphQL query

query {
  human(id: "1001") {
    name
    homePlanet
  }
}

would look like this in dillonkearns/elm-graphql (the code in this example that is prefixed with StarWars is auto-generated)

import Graphql.Operation exposing (RootQuery)
import Graphql.SelectionSet as SelectionSet exposing (SelectionSet)
import StarWars.Object
import StarWars.Object.Human as Human
import StarWars.Query as Query
import StarWars.Scalar exposing (Id(..))


query : SelectionSet (Maybe HumanData) RootQuery
query =
    Query.human { id = Id "1001" } humanSelection


type alias HumanData =
    { name : String
    , homePlanet : Maybe String
    }


humanSelection : SelectionSet HumanData StarWars.Object.Human
humanSelection =
    SelectionSet.map2 HumanData
        Human.name
        Human.homePlanet

GraphQL and Elm are a perfect match because GraphQL is used to enforce the types that your API takes as inputs and outputs, much like Elm's type system does within Elm. elm-graphql simply bridges this gap by making your Elm code aware of your GraphQL server's schema. If you are new to GraphQL, graphql.org/learn/ is an excellent way to learn the basics.

After following the installation instructions to install the @dillonkearns/elm-graphql NPM package and the proper Elm packages (see the Setup section for details). Once you've installed everything, running the elm-graphql code generation tool is as simple as this:

npx elm-graphql https://elm-graphql.herokuapp.com --base StarWars --output examples/src

If headers are required, such as a Bearer Token, the --header flag can be supplied.

npx elm-graphql https://elm-graphql.herokuapp.com --base StarWars --output examples/src --header 'headerKey: header value'

Learning Resources

There is a thorough tutorial in the SelectionSet docs. SelectionSets are the core concept in this library, so I recommend reading through the whole page (it's not very long!).

The examples/ folder is another great place to start.

If you want to learn more GraphQL basics, this is a great tutorial, and a short read: graphql.org/learn/

My Elm Conf 2018 talk goes into the philosophy behind dillonkearns/elm-graphql

Types Without Borders Elm Conf Talk

(Skip to 13:06 to go straight to the dillonkearns/elm-graphql demo).

If you're wondering why code is generated a certain way, you're likely to find an answer in the Frequently Asked Questions (FAQ).

There's a very helpful group of people in the #graphql channel in the Elm Slack. Don't hesitate to ask any questions about getting started, best practices, or just general GraphQL in there!

Setup

dillonkearns/elm-graphql generates Elm code that allows you to build up type-safe GraphQL requests. Here are the steps to setup dillonkearns/elm-graphql.

Add the dillonkearns/elm-graphql elm package as a dependency in your elm.json. You will also need to make sure that elm/json is a dependency of your project since the generated code has lots of JSON decoders in it.

elm install dillonkearns/elm-graphql
elm install elm/json

Install the @dillonkearns/elm-graphql command line tool through npm. This is what you will use to generate Elm code for your API. It is recommended that you save the @dillonkearns/elm-graphql command line tool as a dev dependency so that everyone on your project is using the same version.

npm install --save-dev @dillonkearns/elm-graphql
# you can now run it locally using `npx elm-graphql`,
# or by calling it through an npm script as in this project's package.json

Run the @dillonkearns/elm-graphql command line tool installed above to generate your code. If you used the --save-dev method above, you can simply create a script in your package.json like the following:

{
  "name": "star-wars-elm-graphql-project",
  "version": "1.0.0",
  "scripts": {
    "api": "elm-graphql https://elm-graphql.herokuapp.com/api --base StarWars"
  }

With the above in your package.json, running npm run api will generate dillonkearns/elm-graphql code for you to call in ./src/StarWars/. You can now use the generated code as in this Ellie example or in the examples folder.

Subscriptions Support

You can do real-time APIs using GraphQL Subscriptions and dillonkearns/elm-graphql. Just wire in the framework-specific JavaScript code for opening the WebSocket connection through a port. Here's a live demo and its source code. The demo server is running Elixir/Absinthe.

Contributors

Thank you Mario Martinez (martimatix) for all your feedback, the elm-format PR, and for the incredible logo design!

Thank you Mike Stock (mikeastock) for setting up Travis CI!

Thanks for the reserved words pull request @madsflensted!

A huge thanks to @xtian for doing the vast majority of the 0.19 upgrade work! :tada:

Thank you Josh Adams (@knewter) for the code example for Subscriptions with Elixir/Absinthe wired up through Elm ports!

Thank you Romario for adding OptionalArgument.map!

Thank you Aaron White for your pull request to improve the performance and stability of the elm-format step! 🎉

Roadmap

All core features are supported. That is, you can build any query or mutation with your dillonkearns/elm-graphql-generated code, and it is guaranteed to be valid according to your server's schema.

dillonkearns/elm-graphql will generate code for you to generate subscriptions and decode the responses, but it doesn't deal with the low-level details for how to send them over web sockets. To do that, you will need to use custom code or a package that knows how to communicate over websockets (or whichever protocol) to setup a subscription with your particular framework. See this discussion for why those details are not handled by this library directly.

I would love to hear feedback if you are using GraphQL Subscriptions. In particular, I'd love to see live code examples to drive any improvements to the Subscriptions design. Please ping me on Slack, drop a message in the #graphql channel, or open up a Github issue to discuss!

I would like to investigate generating helpers to make pagination simpler for Connections (based on the Relay Cursor Connections Specification). If you have ideas on this chime in on this thread.

See the full roadmap on Trello.


Author: dillonkearns
Source Code: https://github.com/dillonkearns/elm-graphql
License: View license

#graphql 

Dylan  Iqbal

Dylan Iqbal

1559276342

Using JWTs for GraphQL Authorization with Hasura

Learn about the Hasura platform and how their GraphQL APIs can be secured using JSON Web Tokens

If you’re developing an API today for consumption by third-parties, you’d be more than forgiven for choosing the REST interface to develop the API, as it is a tried and tested standard for delivering data to consumers, as well as accepting changes to the data in a structured way. In more recent times, GraphQL has become an attractive alternative for developing APIs thanks to its flexible, semantic, and performant nature.

But what if you’d like finer control over the details of the data exchange, including integration with third-party authorization servers using JWTs, and being able to quickly and easily set role-based permissions at the field level?

That’s what Hasura have achieved with their GraphQL platform that generates a GraphQL API over a PostgreSQL database. To highlight just a few of the features:

[“The Hasura platform takes advantage of JWT and GraphQL technologies to provide a platform for querying and manipulating data in a PostgreSQL database, taking into account the role specified in the authorization token.”> [“The Hasura platform takes advantage of JWT and GraphQL technologies to provide a platform for querying and manipulating data in a PostgreSQL database, taking into account the role specified in the authorization token.”## A Short Introduction to JSON Web Tokens

From jwt.io:

[“The Hasura platform takes advantage of JWT and GraphQL technologies to provide a platform for querying and manipulating data in a PostgreSQL database, taking into account the role specified in the authorization token.”
What this looks like in practice is a string that is made up of three parts separated by a period:

A JWT is issued as a result of a user authenticating with an authorization server. In the case of the Hasura platform, this JWT can then be used to authorize the request and as such can make queries and mutations depending on the claims present in the token. We will see how this works in the demo a little bit later in the article.

The compact nature of a JWT makes it easy to pass around in query strings, headers, and request bodies, or store in a cookie.

What is GraphQL? An Overview

GraphQL is essentially a query language that allows you to define your API in terms of types. It is datastore-agnostic and has server-side support for many different platforms and languages. Instead of defining your API in terms of status codes and semantic URLs, you define the types and then construct queries using a familiar but powerful syntax. As an example:

{
  article {
    id,
    title,
    author {
      name
    }
  }
}


This describes a query for articles, returning the id, title, and the author’s name. As you can see, it supports nested database objects (the author is another table in the schema, linked to from an article). Mutations can also be defined, which describe how to change data.

In addition, multiple queries can be made in a single request, which is most useful when a client wants to retrieve lots of possibly unrelated data points from the server.

The Hasura Approach

The Hasura platform takes advantage of these technologies to provide a platform for querying and manipulating data in a PostgreSQL database, taking into account the role specified in the authorization token.

The Hasura console allows the user to create a database, define its schema, and populate it with data. Hasura will then generate a GraphQL API on top of this database, automatically generating the appropriate types, queries, and mutations that allow the client to completely query for and manipulate the underlying data.

Hasura takes a role-based approach to authorization, and as such an individual role’s access can be narrowed down to only a subset of the overall schema (even down to the field level). As each role is mapped to certain authorization rules, it can even be prevented from running certain mutations if so desired. Furthermore, queries can be delegated to an upstream service based on the claims present in the authorization token.

Custom claims inside the JWT are used to tell Hasura about the role of the caller, so that Hasura may enforce the necessary authorization rules to decide what the caller can and cannot do.

[Source]

An example of the claims used by Hasura may look like the following:

{
  "https://hasura.io/jwt/claims": {
    "x-hasura-default-role": "anonymous",
    "x-hasura-allowed-roles": [
      "user",
      "anonymous"
    ]
}


These two keys define the possible roles as well as the default role in the absence of the “X-Hasura-Role” header. In the case of Auth0, these custom claims can be put in place using Rules, a platform feature that can be used to dynamically enhance tokens as users are authenticated.

Demo: Querying Data

Let’s have a look at how authorization with Hasura and JWTs works in practice. A demo has been set up that will allow you to construct queries and see the role-based permissions system in action.

This demo has been pre-configured with a database that has authors, articles, tags, and a relationship table that joins many articles to many tags. Let’s see how we can query for some of this data.

Executing anonymous queries

Browse to https://auth0-hasura-demo.herokuapp.com, and use “hasurademo” as the access key.

Next, you will be presented with the Hasura console:

The interface gives you the opportunity to specify some request headers that will be used when querying the GraphQL interface. To demonstrate how the user’s role affects their ability to query and modify data, remove the X-Hasura-Access-Key header by clicking on the cross on the right-hand side, and enter a new header X-Hasura-Role with a value of “anonymous”:

Now, let’s make a query. Use the following query inside the Graphiql query entry area in the lower half of the screen:

{
  article {
    id,
    title
  }
}


To run the query, press Ctrl+Enter (Cmd+Enter if you’re on a Mac), or click on the large ‘play’ button above the query panel. You will see the results of the query on the right-hand side of the screen; you have successfully managed to retrieve the results for two articles that are currently in the database!

Now let’s try a mutation. Alter the query so that it executes the following mutation:

mutation {
  insert_tag(objects:[{name:"<YOUR TAG NAME HERE>"}]) {
    returning {
      name
    }
  }
}


This is a mutation that inserts a new tag with your specified tag name into the database. You should replace the value <YOUR TAG NAME HERE> with a value of your choosing.

Running this mutation right now will return an error, letting you know that the mutation does not exist.

This is correct since the permissions have effectively been set up so that the anonymous role cannot make changes to the database. This is also indicated by the GraphQL API docs, as it does not show any mutations that can be called by this role. To see this, click the “< Docs” button on the right-hand side of the query window to open the API documentation.

Only queries and subscriptions are available as root types here, but no mutations.

Let’s have a closer look at how permissions are set within the Hasura interface.

Validating query permissions

To view the permissions matrix for the “tag” table:

  1. Click the “data” tab at the top of the screen
  2. Click the “tag” table on the left-hand side
  3. Click the “permissions” tab in the main part of the interface

You will arrive at a matrix that describes all the role permissions for the “tag” table. On this screen we can see a number of things:

You can see here that, since the “anonymous” user cannot modify or insert any data, it makes sense that there are no mutations available.

Let’s now switch to the “user” role and see how we can make this mutation work.

Executing Authorized Queries

Click the “Graphiql” heading at the top of the screen to return to the query interface. Now, change the “X-Hasura-Role” request header so that its value is “user”.

If you try to run the mutation again now, you will notice that it will fail for the same reason as before. This is because the “user” role needs to also provide a valid JWT in order to be properly authorized to run this mutation.

[“The Hasura platform takes advantage of JWT and GraphQL technologies to provide a platform for querying and manipulating data in a PostgreSQL database, taking into account the role specified in the authorization token.”> [“The Hasura platform takes advantage of JWT and GraphQL technologies to provide a platform for querying and manipulating data in a PostgreSQL database, taking into account the role specified in the authorization token.”### Generating a valid JWT

For the purposes of this demo, a tool has been provided to make it easy for you to generate a JWT and run this mutation.

Browse to https://auth0-hasura-demo.now.sh/ and log in with your Auth0 account. If you do not currently have one, you can register for a free account.

[“The Hasura platform takes advantage of JWT and GraphQL technologies to provide a platform for querying and manipulating data in a PostgreSQL database, taking into account the role specified in the authorization token.”

Once logged in, you will be able to see your token. Select the entire token string and press Ctrl+C (or Cmd+C on a Mac) to copy it into your clipboard.

Before we head back to the Hasura console, let’s inspect the token to see if it contains the claims that we inspect. Head to http://jwt.io, scroll down and paste the token into the left-hand side of the screen. The right-hand side will automatically update to show you the data contained within the token, and you should be able to see that the correct Hasura claims have been included:

With the token still in your clipboard, head back to the Hasura console. The way we attach this token to the request is through the standard “Authorization” request header.

Add a new header into the “headers” section, specifying the Authorization header and the JWT that you have in your clipboard as the bearer token:

Next, try running the mutation again. You should find that the query now works and that the name of the tag is being played back to you in the response:

[“The Hasura platform takes advantage of JWT and GraphQL technologies to provide a platform for querying and manipulating data in a PostgreSQL database, taking into account the role specified in the authorization token.”
Before we head away from this screen, let’s expand the API docs again to show that the “mutations” root now appears and that you can browse through all the available mutations given that you are now authorized to do so:

Finally, to prove that the mutation has worked we can explore the raw data in the database. Once again, click the “Data” heading at the top of the screen and then click on the “tags” table on the left.

The resulting screen will show you the data that is present in the table, and you can see that the “example-tag” entry that was created by the mutation is there.

Wrapping Up

In this post, you learned a bit about GraphQL and the main differences from a traditional REST API. You also had an introduction to JSON Web Tokens, how they are made up, and how easy they are to pass around.

Next, you discovered how Hasura tackles the idea of a role-based architecture when it comes to securing GraphQL APIs, and how it uses JWTs to authorize incoming requests and grant permissions to specific areas of the schema, even down to the field level.

Finally, you had a practical look at the Hasura platform, learning how to perform anonymous queries, and how to perform authorized mutations using a JWT that was issued to you by Auth0.

Learn More

Build a Simple Web App with Express, Angular, and GraphQL

GraphQL Tutorial: Understanding Spring Data JPA/SpringBoot

How to set up GraphQL with Golang: a deep dive from basics to advanced

Build a Health Tracking App with React, GraphQL, and User Authentication

The Modern GraphQL Bootcamp (Advanced Node.js)

NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

GraphQL with React: The Complete Developers Guide

GraphQL with Angular & Apollo - The Full-stack Guide

GraphQL: Learning GraphQL with Node.Js

Complete guide to building a GraphQL API

GraphQL: Introduction to GraphQL for beginners

#graphql #json #web-development

Delbert  Ferry

Delbert Ferry

1622105190

How to use GraphQL with Javascript – GraphQL.js tutorial

One of the fastest ways to get up and running with GraphQL is to install Apollo Server as middleware on your new or existing HTTP server.

In this short post, we demonstrate how to use Apollo Server to create a GraphQL server with Express.js using the [apollo-server-express] package. At the end, we’ll discuss the tradeoffs of this approach.

#graphql #javascript #graphql.js #graphql.js tutorial

Josefa  Corwin

Josefa Corwin

1659736920

Mailboxer: A Rails Gem to Send Messages inside A Web Application

Mailboxer

This project is based on the need for a private message system for ging / social_stream. Instead of creating our core message system heavily dependent on our development, we are trying to implement a generic and potent messaging gem.

After looking for a good gem to use we noticed the lack of messaging gems and functionality in them. Mailboxer tries to fill this void delivering a powerful and flexible message system. It supports the use of conversations with two or more participants, sending notifications to recipients (intended to be used as system notifications “Your picture has new comments”, “John Doe has updated his document”, etc.), and emailing the messageable model (if configured to do so). It has a complete implementation of a Mailbox object for each messageable with inbox, sentbox and trash.

The gem is constantly growing and improving its functionality. As it is used with our parallel development ging / social_stream we are finding and fixing bugs continously. If you want some functionality not supported yet or marked as TODO, you can create an issue to ask for it. It will be great feedback for us, and we will know what you may find useful in the gem.

Mailboxer was born from the great, but outdated, code from lpsergi / acts_as_messageable.

We are now working to make exhaustive documentation and some wiki pages in order to make it even easier to use the gem to its full potential. Please, give us some time if you find something missing or ask for it. You can also find us on the Gitter room for this repo. Join us there to talk.

Installation

Add to your Gemfile:

gem 'mailboxer'

Then run:

$ bundle install

Run install script:

$ rails g mailboxer:install

And don't forget to migrate your database:

$ rake db:migrate

You can also generate email views:

$ rails g mailboxer:views

Upgrading

If upgrading from 0.11.0 to 0.12.0, run the following generators:

$ rails generate mailboxer:namespacing_compatibility
$ rails generate mailboxer:install -s

Then, migrate your database:

$ rake db:migrate

Requirements & Settings

Emails

We are now adding support for sending emails when a Notification or a Message is sent to one or more recipients. You should modify the mailboxer initializer (/config/initializer/mailboxer.rb) to edit these settings:

Mailboxer.setup do |config|
  #Enables or disables email sending for Notifications and Messages
  config.uses_emails = true
  #Configures the default `from` address for the email sent for Messages and Notifications of Mailboxer
  config.default_from = "no-reply@dit.upm.es"
  ...
end

You can change the way in which emails are delivered by specifying a custom implementation of notification and message mailers:

Mailboxer.setup do |config|
  config.notification_mailer = CustomNotificationMailer
  config.message_mailer = CustomMessageMailer
  ...
end

If you have subclassed the Mailboxer::Notification class, you can specify the mailers using a member method:

class NewDocumentNotification < Mailboxer::Notification
  def mailer_class
    NewDocumentNotificationMailer
  end
end

class NewCommentNotification < Mailboxer::Notification
  def mailer_class
    NewDocumentNotificationMailer
  end
end

Otherwise, the mailer class will be determined by appending 'Mailer' to the mailable class name.

User identities

Users must have an identity defined by a name and an email. We must ensure that Messageable models have some specific methods. These methods are:

#Returning any kind of identification you want for the model
def name
  return "You should add method :name in your Messageable model"
end
#Returning the email address of the model if an email should be sent for this object (Message or Notification).
#If no mail has to be sent, return nil.
def mailboxer_email(object)
  #Check if an email should be sent for that object
  #if true
  return "define_email@on_your.model"
  #if false
  #return nil
end

These names are explicit enough to avoid colliding with other methods, but as long as you need to change them you can do it by using mailboxer initializer (/config/initializer/mailboxer.rb). Just add or uncomment the following lines:

Mailboxer.setup do |config|
  # ...
  #Configures the methods needed by mailboxer
  config.email_method = :mailboxer_email
  config.name_method = :name
  config.notify_method = :notify
  # ...
end

You may change whatever you want or need. For example:

config.email_method = :notification_email
config.name_method = :display_name
config.notify_method = :notify_mailboxer

Will use the method notification_email(object) instead of mailboxer_email(object), display_name for name and notify_mailboxer for notify.

Using default or custom method names, if your model doesn't implement them, Mailboxer will use dummy methods so as to notify you of missing methods rather than crashing.

Preparing your models

In your model:

class User < ActiveRecord::Base
  acts_as_messageable
end

You are not limited to the User model. You can use Mailboxer in any other model and use it in several different models. If you have ducks and cylons in your application and you want to exchange messages as if they were the same, just add acts_as_messageable to each one and you will be able to send duck-duck, duck-cylon, cylon-duck and cylon-cylon messages. Of course, you can extend it for as many classes as you need.

Example:

class Duck < ActiveRecord::Base
  acts_as_messageable
end
class Cylon < ActiveRecord::Base
  acts_as_messageable
end

Mailboxer API

Warning for version 0.8.0

Version 0.8.0 sees Messageable#read and Messageable#unread renamed to mark_as_(un)read, and Receipt#read and Receipt#unread to is_(un)read. This may break existing applications, but read is a reserved name for Active Record, and the best pratice in this case is simply avoid using it.

How can I send a message?

#alfa wants to send a message to beta
alfa.send_message(beta, "Body", "subject")

How can I read the messages of a conversation?

As a messageable, what you receive are receipts, which are associated with the message itself. You should retrieve your receipts for the conversation and get the message associated with them.

This is done this way because receipts save the information about the relation between messageable and the messages: is it read?, is it trashed?, etc.

#alfa gets the last conversation (chronologically, the first in the inbox)
conversation = alfa.mailbox.inbox.first

#alfa gets it receipts chronologically ordered.
receipts = conversation.receipts_for alfa

#using the receipts (i.e. in the view)
receipts.each do |receipt|
  ...
  message = receipt.message
  read = receipt.is_unread? #or message.is_unread?(alfa)
  ...
end

How can I reply to a message?

#alfa wants to reply to all in a conversation
#using a receipt
alfa.reply_to_all(receipt, "Reply body")

#using a conversation
alfa.reply_to_conversation(conversation, "Reply body")
#alfa wants to reply to the sender of a message (and ONLY the sender)
#using a receipt
alfa.reply_to_sender(receipt, "Reply body")

How can I delete a message from trash?

#delete conversations forever for one receipt (still in database)
receipt.mark_as_deleted

#you can mark conversation as deleted for one participant
conversation.mark_as_deleted participant

#Mark the object as deleted for messageable
#Object can be:
  #* A Receipt
  #* A Conversation
  #* A Notification
  #* A Message
  #* An array with any of them
alfa.mark_as_deleted conversation

# get available message for specific user
conversation.messages_for(alfa)

How can I retrieve my conversations?

#alfa wants to retrieve all his conversations
alfa.mailbox.conversations

#A wants to retrieve his inbox
alfa.mailbox.inbox

#A wants to retrieve his sent conversations
alfa.mailbox.sentbox

#alfa wants to retrieve his trashed conversations
alfa.mailbox.trash

How can I paginate conversations?

You can use Kaminari to paginate the conversations as normal. Please, make sure you use the last version as mailboxer uses select('DISTINCT conversations.*') which was not respected before Kaminari 0.12.4 according to its changelog. Working correctly on Kaminari 0.13.0.

#Paginating all conversations using :page parameter and 9 per page
conversations = alfa.mailbox.conversations.page(params[:page]).per(9)

#Paginating received conversations using :page parameter and 9 per page
conversations = alfa.mailbox.inbox.page(params[:page]).per(9)

#Paginating sent conversations using :page parameter and 9 per page
conversations = alfa.mailbox.sentbox.page(params[:page]).per(9)

#Paginating trashed conversations using :page parameter and 9 per page
conversations = alfa.mailbox.trash.page(params[:page]).per(9)

You can take a look at the full documentation for Mailboxer in rubydoc.info.

Do you want to test Mailboxer?

Thanks to Roman Kushnir (@RKushnir) you can test Mailboxer with this sample app.

I need a GUI!

If you need a GUI you should take a look at these links:

Contributors


Author: mailboxer
Source code: https://github.com/mailboxer/mailboxer
License: MIT license

#ruby  #ruby-on-rails