From f17b2655d50764289a88e4fae5852f302e4bddc0 Mon Sep 17 00:00:00 2001
From: jgutix <whan.kharlos@gmail.com>
Date: Fri, 15 May 2020 15:34:09 -0600
Subject: [PATCH] feat(middleware): add helpers for authorization middleware

---
 authorization.js |  4 ++++
 src/helpers.js   | 21 +++++++++++++++++++++
 2 files changed, 25 insertions(+)
 create mode 100644 src/helpers.js

diff --git a/authorization.js b/authorization.js
index 7ac282e..eb8160b 100644
--- a/authorization.js
+++ b/authorization.js
@@ -9,6 +9,8 @@ const {
   not,
 } = require('graphql-shield')
 
+const { isAdmin, isAuthenticated } = require('./src/helpers')
+
 module.exports = {
   rule,
   inputRule,
@@ -18,4 +20,6 @@ module.exports = {
   chain,
   or,
   not,
+  isAuthenticated,
+  isAdmin,
 }
diff --git a/src/helpers.js b/src/helpers.js
new file mode 100644
index 0000000..62a81da
--- /dev/null
+++ b/src/helpers.js
@@ -0,0 +1,21 @@
+const { rule } = require('graphql-shield')
+
+const isAuthenticated = rule()(async (parent, args, ctx, info) => {
+  return !!ctx.user
+})
+
+const isAdmin = rule()(
+  async (parent, args, { user: userId, connectors: { User } }, info) => {
+    if (!userId) {
+      return false
+    }
+
+    const user = await User.model.findById(userId)
+    return user.admin
+  },
+)
+
+module.exports = {
+  isAuthenticated,
+  isAdmin,
+}
-- 
GitLab