> ## Documentation Index
> Fetch the complete documentation index at: https://openfga.dev/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Modeling Authorization for an IoT Security System with OpenFGA

> Modeling fine-grained authorization for an IoT security camera system

export const WriteRequestViewer = ({relationshipTuples, deleteRelationshipTuples, authorizationModelId, skipSetup, conflictOptions, allowedLanguages}) => {
  const [runtime, setRuntime] = useState(null);
  const [loadError, setLoadError] = useState(null);
  const [selectedLanguage, setSelectedLanguage] = useState(null);
  useEffect(() => {
    if (window.openfgaViewer) {
      setLoadError(null);
      setRuntime(window.openfgaViewer);
      return;
    }
    let script = document.querySelector('script[src="/openfga-viewer.js"]');
    const loaded = () => {
      clearTimeout(timeout);
      if (window.openfgaViewer) {
        setLoadError(null);
        setRuntime(window.openfgaViewer);
      } else setLoadError('The OpenFGA example helper did not initialize. Reload this page to retry.');
    };
    const failed = () => {
      clearTimeout(timeout);
      setLoadError('Unable to load OpenFGA examples. Reload this page to retry.');
    };
    if (!script) {
      script = document.createElement('script');
      script.src = '/openfga-viewer.js';
    }
    script.addEventListener('load', loaded);
    script.addEventListener('error', failed);
    const timeout = setTimeout(() => {
      if (!window.openfgaViewer) failed();
    }, 10000);
    if (!script.isConnected) document.head.appendChild(script);
    return () => {
      clearTimeout(timeout);
      script.removeEventListener('load', loaded);
      script.removeEventListener('error', failed);
    };
  }, []);
  if (loadError) return <div className="openfga-code-viewer__status" role="alert">
        {loadError}
      </div>;
  if (!runtime) return <div className="openfga-code-viewer__status" role="status">
        Loading examples...
      </div>;
  const {languageLabels: LANG_LABEL, languageGrammars: LANG_CODE} = runtime;
  const langs = runtime.selectLanguages('WriteRequestViewer', allowedLanguages);
  const activeLang = langs.includes(selectedLanguage) ? selectedLanguage : langs[0];
  const setupLangs = langs.filter(runtime.hasSetup);
  const buildSetupCode = lang => runtime.buildSdkSetup(lang, 'WriteRequestViewer');
  const buildCode = lang => runtime.buildRequestCode(lang, 'WriteRequestViewer', {
    relationshipTuples,
    deleteRelationshipTuples,
    authorizationModelId,
    conflictOptions
  });
  return <div data-openfga-viewer="WriteRequestViewer">
      {!skipSetup && runtime.hasSetup(activeLang) && <Accordion title="Initialize the SDK">
          <p>
            Install the <a href="https://openfga.dev/docs/getting-started/install-sdk">SDK or CLI</a> and deploy an OpenFGA server. Set
            FGA_API_URL, FGA_STORE_ID, and optionally FGA_MODEL_ID. These examples use no authentication; see{' '}
            <a href="https://openfga.dev/docs/getting-started/setup-sdk-client">client setup</a> for authentication and runtime
            prerequisites. Go snippets run inside main; Python requests run inside an async function and the client must
            be closed afterward.
          </p>
          <CodeGroup key={setupLangs.join(',')} onChange={index => setSelectedLanguage(setupLangs[index])}>
            {setupLangs.map(lang => <code key={lang} className={`language-${LANG_CODE[lang]}`} language={LANG_CODE[lang]} filename={LANG_LABEL[lang]}>
                {buildSetupCode(lang)}
              </code>)}
          </CodeGroup>
        </Accordion>}
      <CodeGroup key={langs.join(',')} onChange={index => setSelectedLanguage(langs[index])}>
        {langs.map(lang => <code key={lang} className={`language-${LANG_CODE[lang]}`} language={LANG_CODE[lang]} filename={LANG_LABEL[lang]}>
            {buildCode(lang)}
          </code>)}
      </CodeGroup>
    </div>;
};

export const CheckRequestViewer = ({user, relation, object, allowed, contextualTuples, context, headers, authorizationModelId, skipSetup, allowedLanguages, consistency}) => {
  const [runtime, setRuntime] = useState(null);
  const [loadError, setLoadError] = useState(null);
  const [selectedLanguage, setSelectedLanguage] = useState(null);
  useEffect(() => {
    if (window.openfgaViewer) {
      setLoadError(null);
      setRuntime(window.openfgaViewer);
      return;
    }
    let script = document.querySelector('script[src="/openfga-viewer.js"]');
    const loaded = () => {
      clearTimeout(timeout);
      if (window.openfgaViewer) {
        setLoadError(null);
        setRuntime(window.openfgaViewer);
      } else setLoadError('The OpenFGA example helper did not initialize. Reload this page to retry.');
    };
    const failed = () => {
      clearTimeout(timeout);
      setLoadError('Unable to load OpenFGA examples. Reload this page to retry.');
    };
    if (!script) {
      script = document.createElement('script');
      script.src = '/openfga-viewer.js';
    }
    script.addEventListener('load', loaded);
    script.addEventListener('error', failed);
    const timeout = setTimeout(() => {
      if (!window.openfgaViewer) failed();
    }, 10000);
    if (!script.isConnected) document.head.appendChild(script);
    return () => {
      clearTimeout(timeout);
      script.removeEventListener('load', loaded);
      script.removeEventListener('error', failed);
    };
  }, []);
  if (loadError) return <div className="openfga-code-viewer__status" role="alert">
        {loadError}
      </div>;
  if (!runtime) return <div className="openfga-code-viewer__status" role="status">
        Loading examples...
      </div>;
  const {languageLabels: LANG_LABEL, languageGrammars: LANG_CODE} = runtime;
  const langs = runtime.selectLanguages('CheckRequestViewer', allowedLanguages);
  const activeLang = langs.includes(selectedLanguage) ? selectedLanguage : langs[0];
  const setupLangs = langs.filter(runtime.hasSetup);
  const buildSetupCode = lang => runtime.buildSdkSetup(lang, 'CheckRequestViewer');
  const buildCode = lang => runtime.buildRequestCode(lang, 'CheckRequestViewer', {
    user,
    relation,
    object,
    allowed,
    contextualTuples,
    context,
    headers,
    authorizationModelId,
    consistency
  });
  return <div data-openfga-viewer="CheckRequestViewer">
      {!skipSetup && runtime.hasSetup(activeLang) && <Accordion title="Initialize the SDK">
          <p>
            Install the <a href="https://openfga.dev/docs/getting-started/install-sdk">SDK or CLI</a> and deploy an OpenFGA server. Set
            FGA_API_URL, FGA_STORE_ID, and optionally FGA_MODEL_ID. These examples use no authentication; see{' '}
            <a href="https://openfga.dev/docs/getting-started/setup-sdk-client">client setup</a> for authentication and runtime
            prerequisites. Go snippets run inside main; Python requests run inside an async function and the client must
            be closed afterward.
          </p>
          <CodeGroup key={setupLangs.join(',')} onChange={index => setSelectedLanguage(setupLangs[index])}>
            {setupLangs.map(lang => <code key={lang} className={`language-${LANG_CODE[lang]}`} language={LANG_CODE[lang]} filename={LANG_LABEL[lang]}>
                {buildSetupCode(lang)}
              </code>)}
          </CodeGroup>
        </Accordion>}
      <CodeGroup key={langs.join(',')} onChange={index => setSelectedLanguage(langs[index])}>
        {langs.map(lang => <code key={lang} className={`language-${LANG_CODE[lang]}`} language={LANG_CODE[lang]} filename={LANG_LABEL[lang]}>
            {buildCode(lang)}
          </code>)}
      </CodeGroup>
    </div>;
};

export const AuthzModelSnippetViewer = ({configuration, syntaxesToShow = ['dsl', 'json'], skipVersion}) => {
  const [codegenReady, setCodegenReady] = useState(false);
  const [dslReady, setDslReady] = useState(false);
  const [activeTab, setActiveTab] = useState(syntaxesToShow[0] || 'dsl');
  useEffect(() => {
    if (window.fgaCodegen) {
      setCodegenReady(true);
      return;
    }
    let script = document.querySelector('script[src="/fga-codegen.js"]');
    const loaded = () => {
      if (window.fgaCodegen) setCodegenReady(true);
    };
    if (!script) {
      script = document.createElement('script');
      script.src = '/fga-codegen.js';
    }
    script.addEventListener('load', loaded);
    if (!script.isConnected) document.head.appendChild(script);
    return () => script.removeEventListener('load', loaded);
  }, []);
  useEffect(() => {
    if (window.openfgaDsl) {
      setDslReady(true);
      return;
    }
    let script = document.querySelector('script[src="/openfga-dsl-highlight.js"]');
    const loaded = () => {
      if (window.openfgaDsl) setDslReady(true);
    };
    if (!script) {
      script = document.createElement('script');
      script.src = '/openfga-dsl-highlight.js';
    }
    script.addEventListener('load', loaded);
    if (!script.isConnected) document.head.appendChild(script);
    return () => script.removeEventListener('load', loaded);
  }, []);
  if (!codegenReady) {
    return <div className="openfga-code-viewer__status" role="status">Loading model viewer...</div>;
  }
  const {transformer} = window.fgaCodegen;
  const getDsl = () => {
    try {
      const isTypeDefinition = !configuration.type_definitions && Boolean(configuration.type);
      const model = isTypeDefinition ? {
        schema_version: '1.1',
        type_definitions: [configuration]
      } : configuration;
      const dsl = transformer.transformJSONToDSL(model);
      return skipVersion || isTypeDefinition ? dsl.replace('model\n  schema 1.1\n', '') : dsl;
    } catch (e) {
      return `// error converting to DSL: ${e.message}`;
    }
  };
  const getJson = () => {
    const json = {
      ...configuration
    };
    delete json.id;
    if (skipVersion) delete json.schema_version;
    return JSON.stringify(json, null, 2);
  };
  const showTabs = syntaxesToShow.length > 1;
  const DSL_COLORS = dslReady && window.openfgaDsl ? window.openfgaDsl.colors : {};
  const THEME_STYLE = {
    '--openfga-dark-background': DSL_COLORS.background,
    '--openfga-dark-default': DSL_COLORS.default,
    '--openfga-dark-accent': DSL_COLORS.green
  };
  const renderDsl = () => {
    const code = getDsl().replace(/^\n/, '').replace(/\n$/, '');
    const hasError = code.startsWith('// error converting to DSL:');
    const tokens = hasError ? [{
      text: code,
      type: 'error'
    }] : dslReady && window.openfgaDsl ? window.openfgaDsl.tokenize(code) : [{
      text: code,
      type: 'default'
    }];
    return <div className="openfga-code-viewer__code" data-language="dsl" data-state={hasError ? 'error' : undefined} role={hasError ? 'alert' : undefined}>
        {tokens.map((t, i) => <span className="openfga-code-token" data-token={t.type || 'default'} key={i} style={{
      '--openfga-dark-token-color': t.color || DSL_COLORS.default
    }}>
            {t.text}
          </span>)}
      </div>;
  };
  const tokenizeJson = text => {
    const strRanges = [];
    const claims = [];
    let m;
    const strRe = /"(?:[^"\\]|\\.)*"/g;
    while (m = strRe.exec(text)) {
      const s = m.index, e = s + m[0].length;
      strRanges.push({
        s,
        e
      });
      const isKey = (/^\s*:/).test(text.slice(e));
      claims.push({
        s,
        e,
        type: isKey ? 'json-key' : 'json-string'
      });
    }
    const inStr = (s, e) => strRanges.some(r => s >= r.s && e <= r.e);
    const numRe = /-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g;
    while (m = numRe.exec(text)) {
      const s = m.index, e = s + m[0].length;
      if (!inStr(s, e)) claims.push({
        s,
        e,
        type: 'json-number'
      });
    }
    const kwRe = /\b(true|false|null)\b/g;
    while (m = kwRe.exec(text)) {
      const s = m.index, e = s + m[0].length;
      if (!inStr(s, e)) claims.push({
        s,
        e,
        type: 'json-keyword'
      });
    }
    const puncRe = /[{}\[\]:,]/g;
    while (m = puncRe.exec(text)) {
      const s = m.index;
      if (!inStr(s, s + 1)) claims.push({
        s,
        e: s + 1,
        type: 'json-punctuation'
      });
    }
    claims.sort((a, b) => a.s - b.s);
    const tokens = [];
    let cursor = 0;
    for (const c of claims) {
      if (c.s > cursor) tokens.push({
        text: text.slice(cursor, c.s),
        type: 'default'
      });
      tokens.push({
        text: text.slice(c.s, c.e),
        type: c.type
      });
      cursor = c.e;
    }
    if (cursor < text.length) tokens.push({
      text: text.slice(cursor),
      type: 'default'
    });
    return tokens;
  };
  const renderJson = () => {
    const code = getJson();
    const tokens = tokenizeJson(code);
    return <div className="openfga-code-viewer__code" data-language="json">
        {tokens.map((t, i) => <span className="openfga-code-token" data-token={t.type} key={i}>{t.text}</span>)}
      </div>;
  };
  return <div className="openfga-code-viewer" style={THEME_STYLE}>
      {showTabs && <div className="openfga-code-viewer__tabs">
          {syntaxesToShow.map(fmt => <button aria-pressed={activeTab === fmt} className="openfga-code-viewer__tab" data-state={activeTab === fmt ? 'active' : 'inactive'} key={fmt} onClick={() => setActiveTab(fmt)}>
              {fmt.toUpperCase()}
            </button>)}
        </div>}
      {(!showTabs || activeTab === 'dsl') && syntaxesToShow.includes('dsl') && renderDsl()}
      {(!showTabs || activeTab === 'json') && syntaxesToShow.includes('json') && renderJson()}
    </div>;
};

This tutorial explains how to model permissions for an IoT system using OpenFGA.

<Note>
  **What you will learn**

  * How to model a permission system using OpenFGA
  * How to see OpenFGA Authorization in action by modeling an IoT Security Camera System
</Note>

## Before you start

In order to understand this guide correctly you must be familiar with some OpenFGA concepts and know how to develop the things that we will list below.

It would be helpful to have an understanding of some concepts of OpenFGA before you start.

<Accordion title="OpenFGA concepts" id="-concepts">
  <h4 id="direct-access">Direct access</h4>

  You need to know how to create an authorization model and create a relationship tuple to grant a user access to an object. [Learn more →](/docs/modeling/direct-access)

  <h4 id="modeling-concentric-relationships">Modeling concentric relationships</h4>

  You need to know how to update the authorization model to allow having nested relations such as all writers are readers. [Learn more →](/docs/modeling/building-blocks/concentric-relationships)
  Used here to indicate that both IT Admins and Security Guards can view live video.

  <h4 id="direct-relationships">Direct relationships</h4>

  You need to know how to disallow granting direct relation to an object and requiring the user to have a relation with another object that would imply a relation with the first one. [Learn more →](/docs/modeling/building-blocks/direct-relationships)
  Used here to indicate that "Rename Device" is a permission that cannot be assigned directly, but can only be granted through the "IT Admin" role.

  <h4 id="user-groups">User groups</h4>

  You need to know how to add users to groups and create relationships between groups of users and an object. [Learn more →](/docs/modeling/building-blocks/direct-relationships)

  Used here to indicate that security guards on a certain group are security guards on a device in that group.

  <h4 id="concepts--configuration-language">Concepts & configuration language</h4>

  * Some [OpenFGA Concepts](/docs/concepts)
  * [Configuration Language](/docs/configuration-language)
</Accordion>

## What You Will be modeling

In this tutorial, you will build an authorization model for a sample IoT Security Camera System (detailed below) using OpenFGA. You will use some scenarios to validate the model.

The goal by the end of this post is to ask OpenFGA: Does person X have permission to perform action Y on device Z? In response, you want to either get a confirmation that person X can indeed do that, or a rejection that they cannot.

### Requirements

These are the requirements:

* **Security guards** have access to **view live and recorded video** from **Devices**.
* **IT Admins** can **view live and recorded videos**, as well as **rename** **Devices**.
* To make access management easier, **Devices** can be grouped into **Device Groups**. **Security guards** with access to the **Device Group** are **Security Guards** with access to each **Device** in the group. Similarly for **IT Admins**.

### Defined Scenarios

Use the following scenarios to be able to validate whether the model of the requirements is correct.

There will be the following users:

* Anne
* Beth
* Charles
* Dianne

These users have the following roles and permissions:

* Anne is a Security Guard with access to only Device 1
* Beth is an IT Admin with access to only Device 1
* Charles is a Security Guard with access to Device 1 and everything in Device Group 1 (which is Device 2 and Device 3)
* Dianne is an IT Admin with access to Device 1 and everything in Device Group 1

<img src="https://mintcdn.com/fga/sFng5HcsvGPlDD3_/modeling/advanced/assets/iot-01.svg?fit=max&auto=format&n=sFng5HcsvGPlDD3_&q=85&s=b3001a075fb7d461196b0d0f3e5f62a6" alt="Image showing requirements" width="1205" height="461" data-path="modeling/advanced/assets/iot-01.svg" />

<Warning>
  In production, it is highly recommended to use unique, immutable identifiers. Names are used in this article to make it easier to read and follow.
</Warning>

## Modeling device authorization

The OpenFGA service is based on [Zanzibar](https://zanzibar.academy), a Relationship Based Access Control system. This means it relies on [object](/docs/concepts#what-is-an-object) and [user](/docs/concepts#what-is-a-user) [relations](/docs/concepts#what-is-a-relation) to perform authorization [checks](/docs/concepts#what-is-a-check-request).

Starting with devices, you will learn how to express the requirements in terms of relations you can feed into OpenFGA.

### 01. Writing the initial model for a device

The requirements stated:

* **Security guards** have access to **view live and recorded video** from **Devices**.
* **IT Admins** can **view live and recorded videos**, as well as **rename** **Devices**.

The goal is to ask OpenFGA whether person X has permission to perform action Y on device Z. To start, you will set aside the Security Guard and IT Admin designations and focus on the actions a user can take.

The actions users can take on a device are: *view live videos*, *view recorded videos*, and *rename devices*. Mapping them to relations, they become: *live\_video\_viewer*, *recorded\_video\_viewer*, *device\_renamer*.

In OpenFGA, the [authorization model](/docs/concepts#what-is-an-authorization-model) for the device would be:

<AuthzModelSnippetViewer
  configuration={{
schema_version: '1.1',
type_definitions: [
  {
    type: 'user',
  },
  {
    type: 'device', // objects of type "device"
    relations: {
      // have users related to them as...
      live_video_viewer: {
        // "live_video_viewer": if they belong to the userset of all users related to the device as "live_video_viewer"
        this: {},
      },
      recorded_video_viewer: {
        // "recorded_video_viewer": if they belong to the userset of all users related to the device as "recorded_video_viewer"
        this: {},
      },
      device_renamer: {
        this: {}, // "device_renamer": if they belong to the userset of all users related to the device as "device_renamer"
      },
    },
    metadata: {
      relations: {
        live_video_viewer: { directly_related_user_types: [{ type: 'user' }] },
        recorded_video_viewer: { directly_related_user_types: [{ type: 'user' }] },
        device_renamer: { directly_related_user_types: [{ type: 'user' }] },
      },
    },
  },
],
}}
/>

### 02. Inserting some relationship tuples

The requirements are:

* **Anne** is a **Security Guard** with access to only **Device 1**
* **Beth** is an **IT Admin** with access to only **Device 1**
* **Security Guards** can **view live and recorded video**
* **IT Admins** can **view live and recorded video** and **rename** devices

Before we tackle the problem of users access to device based on their role, we will try to grant user access based on their view relationship directly.

We will first focus on Anne and Beth's relationship with Device 1.

To add Anne as live\_video\_viewer of device:1:

<WriteRequestViewer
  relationshipTuples={[
{
  user: 'user:anne',
  relation: 'live_video_viewer',
  object: 'device:1',
},
]}
/>

To add Anne as recorded\_video\_viewer of device:1

<WriteRequestViewer
  relationshipTuples={[
{
  user: 'user:anne',
  relation: 'recorded_video_viewer',
  object: 'device:1',
},
]}
/>

Likewise, we will add Beth's relationship with device:1.

<WriteRequestViewer
  relationshipTuples={[
{
  user: 'user:beth',
  relation: 'live_video_viewer',
  object: 'device:1',
},
{
  user: 'user:beth',
  relation: 'recorded_video_viewer',
  object: 'device:1',
},
{
  user: 'user:beth',
  relation: 'device_renamer',
  object: 'device:1',
},
]}
/>

#### Verification

Now that you have some relationship tuples added, you can start using it to [ask](/docs/concepts#what-is-a-check-request) some questions, e.g., whether a person has access to rename a device.

First, you will find out if `anne` has permission to `view the live video` on `device:1`, then you will see if `anne` can `rename` `device:1`.

Anne has `live_video_viewer` relationship with device:1.

<CheckRequestViewer user={'user:anne'} relation={'live_video_viewer'} object={'device:1'} allowed={true} />

On the other hand, Anne does not have `device_renamer` relationship with device:1.

<CheckRequestViewer user={'user:anne'} relation={'device_renamer'} object={'device:1'} allowed={false} />

Now, check the other relationships fore Anne and Beth.

| User | Object | Relation | Query | Relation? |
| - | - | - | - | - |
| `anne` | `device:1` | `live_video_viewer` | `is anne related to device:1 as live_video_viewer?` | Yes |
| `beth` | `device:1` | `live_video_viewer` | `is beth related to device:1 as live_video_viewer?` | Yes |
| `anne` | `device:1` | `recorded_video_viewer` | `is anne related to device:1 as recorded_video_viewer?` | Yes |
| `beth` | `device:1` | `recorded_video_viewer` | `is beth related to device:1 as recorded_video_viewer?` | Yes |
| `anne` | `device:1` | `device_renamer` | `is anne related to device:1 as device_renamer?` | No |
| `beth` | `device:1` | `device_renamer` | `is beth related to device:1 as device_renamer?` | Yes |

### 03. Updating our authorization model to facilitate future changes

Notice how you had to add the Anne and Beth as [direct relations](/docs/concepts#what-are-direct-and-implied-relationships) to all the actions they can take on Device 1 instead of just stating that they are related as Security Guard or IT Admin, and having the other permissions implied? In practice this might have some disadvantages: if your authorization model changes, (e.g so that Security Guards can no longer view previously recorded videos), you would need to change relationship tuples in the system instead of just changing the configuration.

We can address this by using [**concentric relation models**](/docs/modeling/building-blocks/concentric-relationships). It allows you to express that sets of users who have a relation X to the object also have relation Y. For example, anyone that is related to the device as a `security_guard` is also related as a `live_video_viewer` and `recorded_video_viewer`, and anyone who is related to the device as an `it_admin` is also related as a `live_video_viewer`, a `recorded_video_viewer`, and a `device_renamer`.

At the end you want to make sure that [checking](/docs/concepts#what-is-a-check-request) if Anne, Beth, Charles, or Dianne have permission to view the live video or rename the device, will get you the correct answers back.

The resulting authorization model is:

<AuthzModelSnippetViewer
  configuration={{
schema_version: '1.1',
type_definitions: [
  {
    type: 'device',
    relations: {
      it_admin: {
        this: {},
      },
      security_guard: {
        this: {},
      },
      live_video_viewer: {
        // objects of type "device" have users related to them as "live_video_viewer", if they belong to:
        union: {
          // any of (the union of)
          child: [
            {
              this: {}, // the userset of all users related to the github-repo as "repo_reader"
            },
            {
              computedUserset: {
                //  The userset of all users who are related to the device as it_admin
                relation: 'it_admin',
              },
            },
            {
              computedUserset: {
                // The userset of all users who are related to the device as it_admin
                relation: 'security_guard',
              },
            },
          ],
        },
      },
      recorded_video_viewer: {
        union: {
          child: [
            {
              this: {},
            },
            {
              computedUserset: {
                relation: 'it_admin',
              },
            },
            {
              computedUserset: {
                relation: 'security_guard',
              },
            },
          ],
        },
      },
      device_renamer: {
        union: {
          child: [
            {
              this: {},
            },
            {
              computedUserset: {
                relation: 'it_admin',
              },
            },
          ],
        },
      },
    },
    metadata: {
      relations: {
        it_admin: { directly_related_user_types: [{ type: 'user' }] },
        security_guard: { directly_related_user_types: [{ type: 'user' }] },
        live_video_viewer: { directly_related_user_types: [{ type: 'user' }] },
        recorded_video_viewer: { directly_related_user_types: [{ type: 'user' }] },
        device_renamer: { directly_related_user_types: [{ type: 'user' }] },
      },
    },
  },
],
}}
/>

The requirements are:

* **Anne** and **Charles** are **Security Guards** with access **Device 1**
* **Beth** and **Dianne** are **IT Admins** with access **Device 1**
* **Security Guards** can **view live and recorded video**
* **IT Admins** can **view live and recorded video** and **rename** devices

Instead of adding different relationship tuples with direct relations to the actions they can take, as you did in the previous section, you will only add the relation to their role: `it_admin` or `security_guard`.

<WriteRequestViewer
  relationshipTuples={[
{
  user: 'user:anne',
  relation: 'security_guard',
  object: 'device:1',
},
{
  user: 'user:beth',
  relation: 'it_admin',
  object: 'device:1',
},
{
  user: 'user:charles',
  relation: 'security_guard',
  object: 'device:1',
},
{
  user: 'user:dianne',
  relation: 'it_admin',
  object: 'device:1',
},
]}
/>

<h4 id="verification-1">Verification</h4>

We can now verify whether charles is related to device:1 as live\_video\_viewer.

<CheckRequestViewer user={'user:charles'} relation={'live_video_viewer'} object={'device:1'} allowed={true} />

Check the other relationships for anne, beth, charles and dianne.

| User | Object | Relation | Query | Relation? |
| - | - | - | - | - |
| `anne` | `device:1` | `live_video_viewer` | `is anne related to device:1 as live_video_viewer?` | Yes |
| `beth` | `device:1` | `live_video_viewer` | `is beth related to device:1 as live_video_viewer?` | Yes |
| `anne` | `device:1` | `recorded_video_viewer` | `is anne related to device:1 as recorded_video_viewer?` | Yes |
| `beth` | `device:1` | `recorded_video_viewer` | `is beth related to device:1 as recorded_video_viewer?` | Yes |
| `anne` | `device:1` | `device_renamer` | `is anne related to device:1 as device_renamer?` | No |
| `beth` | `device:1` | `device_renamer` | `is beth related to device:1 as device_renamer?` | Yes |
| `charles` | `device:1` | `live_video_viewer` | `is charles related to device:1 as live_video_viewer?` | Yes |
| `dianne` | `device:1` | `live_video_viewer` | `is dianne related to device:1 as live_video_viewer?` | Yes |
| `charles` | `device:1` | `recorded_video_viewer` | `is charles related to device:1 as recorded_video_viewer?` | Yes |
| `dianne` | `device:1` | `recorded_video_viewer` | `is dianne related to device:1 as recorded_video_viewer?` | Yes |
| `charles` | `device:1` | `device_renamer` | `is charles related to device:1 as device_renamer?` | No |
| `dianne` | `device:1` | `device_renamer` | `is dianne related to device:1 as device_renamer?` | Yes |

### 04. Modeling device groups

Now that you are done with devices. Let us tackle device groups.

The requirements regarding device groups were:

* **Devices** can be grouped into **Device Groups**
* **Security guards** with access to the **Device Group** are **Security Guards** with access to the **Devices** within the **Device Group**. Similarly for **IT Admins**

The [type definition](/docs/concepts#what-is-a-type-definition) for the device group:

<AuthzModelSnippetViewer
  configuration={{
schema_version: '1.1',
type: 'device_group',
relations: {
  it_admin: {
    this: {},
  },
  security_guard: {
    this: {},
  },
},
metadata: {
  relations: {
    it_admin: { directly_related_user_types: [{ type: 'user' }] },
    security_guard: { directly_related_user_types: [{ type: 'user' }] },
  },
},
}}
  skipVersion={true}
/>

With this change, the full [authorization model](/docs/concepts#what-is-an-authorization-model) becomes:

<AuthzModelSnippetViewer
  configuration={{
schema_version: '1.1',
type_definitions: [
  {
    type: 'user',
  },
  {
    type: 'device',
    relations: {
      it_admin: {
        this: {},
      },
      security_guard: {
        this: {},
      },
      live_video_viewer: {
        union: {
          child: [
            {
              this: {},
            },
            {
              computedUserset: {
                relation: 'it_admin',
              },
            },
            {
              computedUserset: {
                relation: 'security_guard',
              },
            },
          ],
        },
      },
      recorded_video_viewer: {
        union: {
          child: [
            {
              this: {},
            },
            {
              computedUserset: {
                relation: 'it_admin',
              },
            },
            {
              computedUserset: {
                relation: 'security_guard',
              },
            },
          ],
        },
      },
      device_renamer: {
        union: {
          child: [
            {
              this: {},
            },
            {
              computedUserset: {
                relation: 'it_admin',
              },
            },
          ],
        },
      },
    },
    metadata: {
      relations: {
        it_admin: {
          directly_related_user_types: [{ type: 'user' }, { type: 'device_group', relation: 'it_admin' }],
        },
        security_guard: {
          directly_related_user_types: [{ type: 'user' }, { type: 'device_group', relation: 'security_guard' }],
        },
        live_video_viewer: { directly_related_user_types: [{ type: 'user' }] },
        recorded_video_viewer: { directly_related_user_types: [{ type: 'user' }] },
        device_renamer: { directly_related_user_types: [{ type: 'user' }] },
      },
    },
  },
  {
    type: 'device_group',
    relations: {
      it_admin: {
        this: {},
      },
      security_guard: {
        this: {},
      },
    },
    metadata: {
      relations: {
        it_admin: { directly_related_user_types: [{ type: 'user' }] },
        security_guard: { directly_related_user_types: [{ type: 'user' }] },
      },
    },
  },
],
}}
/>

#### Updating relationship tuples on roles

Remember that **Charles** is a **Security Guard**, and **Dianne** an **IT Admin** on **Group 1**, enter the [relationship tuples](/docs/concepts#what-is-a-relationship-tuple) below to reflect that.

<WriteRequestViewer
  relationshipTuples={[
{
  user: 'user:charles',
  relation: 'security_guard',
  object: 'device_group:group1',
},
{
  user: 'user:dianne',
  relation: 'it_admin',
  object: 'device_group:group1',
},
]}
/>

You still need to give all the security guards of group1 a `security_guard` relation to devices 2 and 3, and similarly for IT Admins. Add the following relationship tuples to do that.

<WriteRequestViewer
  relationshipTuples={[
{
  // the userset of all users related to "device_group:group1" as "security_guard" are related to device:2 as "security_guard"
  user: 'device_group:group1#security_guard',
  relation: 'security_guard',
  object: 'device:2',
},
{
  user: 'device_group:group1#security_guard',
  relation: 'security_guard',
  object: 'device:3',
},
{
  // the userset of all users related to "device_group:group1" as "it_admin" are related to device:2 as "it_admin"
  user: 'device_group:group1#it_admin',
  relation: 'it_admin',
  object: 'device:2',
},
{
  user: 'device_group:group1#it_admin',
  relation: 'it_admin',
  object: 'device:3',
},
]}
/>

<h4 id="verification-2">Verification</h4>

Now that you have finalized the model and added the relationship tuples, you can start asking some queries. Try asking the same queries you did earlier but on device 2 instead of device 1.

We can ask `is dianne related to device:2 as live_video_viewer?`

<CheckRequestViewer user={'dianne'} relation={'live_video_viewer'} object={'device:2'} allowed={true} />

Type any of the following queries in the **TUPLE QUERIES** section and press **ENTER** on your keyboard to see the results.

| User | Object | Relation | Query | Relation? |
| - | - | - | - | - |
| `anne` | `device:2` | `live_video_viewer` | `is anne related to device:2 as live_video_viewer?` | No |
| `beth` | `device:2` | `live_video_viewer` | `is beth related to device:2 as live_video_viewer?` | No |
| `anne` | `device:2` | `recorded_video_viewer` | `is anne related to device:2 as recorded_video_viewer?` | No |
| `beth` | `device:2` | `recorded_video_viewer` | `is beth related to device:2 as recorded_video_viewer?` | No |
| `anne` | `device:2` | `device_renamer` | `is anne related to device:2 as device_renamer?` | No |
| `beth` | `device:2` | `device_renamer` | `is beth related to device:2 as device_renamer?` | No |
| `charles` | `device:2` | `live_video_viewer` | `is charles related to device:2 as live_video_viewer?` | Yes |
| `dianne` | `device:2` | `live_video_viewer` | `is dianne related to device:2 as live_video_viewer?` | Yes |
| `charles` | `device:2` | `recorded_video_viewer` | `is charles related to device:2 as recorded_video_viewer?` | Yes |
| `dianne` | `device:2` | `recorded_video_viewer` | `is dianne related to device:2 as recorded_video_viewer?` | Yes |
| `charles` | `device:2` | `device_renamer` | `is charles related to device:2 as device_renamer?` | No |
| `dianne` | `device:2` | `device_renamer` | `is dianne related to device:2 as device_renamer?` | Yes |

### 05. Disallow direct relationships To users

Notice that despite following **[Step 03](/docs/modeling/advanced/iot#03-updating-our-authorization-model-to-facilitate-future-changes)**, anne and beth still have direct relations to all the actions they can take on device:1.

#### Updating the authorization model

`anne` is a `live_video_viewer` by both her position as `security_guard` as well as her [direct relationship](/docs/concepts#what-are-direct-and-implied-relationships) assignment. This is undesirable. Imagine `anne` left her position of `security_guard` and she will still have `live_video_viewer` access to `device:1`.

To remedy this, remove `[user]` from `live_video_viewer`, `recorded_video_viewer` and `device_renamer`. This denies direct relations to `live_video_viewer`, `recorded_video_viewer` and `device_renamer` from having an effect. To do this:

<AuthzModelSnippetViewer
  configuration={{
schema_version: '1.1',
type_definitions: [
  {
    type: 'user',
  },
  {
    type: 'device',
    relations: {
      it_admin: {
        this: {},
      },
      security_guard: {
        this: {},
      },
      live_video_viewer: {
        union: {
          child: [
            {
              computedUserset: {
                relation: 'it_admin',
              },
            },
            {
              computedUserset: {
                relation: 'security_guard',
              },
            },
          ],
        },
      },
      recorded_video_viewer: {
        union: {
          child: [
            {
              computedUserset: {
                relation: 'it_admin',
              },
            },
            {
              computedUserset: {
                relation: 'security_guard',
              },
            },
          ],
        },
      },
      device_renamer: {
        union: {
          child: [
            {
              computedUserset: {
                relation: 'it_admin',
              },
            },
          ],
        },
      },
    },
    metadata: {
      relations: {
        it_admin: {
          directly_related_user_types: [{ type: 'user' }, { type: 'device_group', relation: 'it_admin' }],
        },
        security_guard: {
          directly_related_user_types: [{ type: 'user' }, { type: 'device_group', relation: 'security_guard' }],
        },
      },
    },
  },
  {
    type: 'device_group',
    relations: {
      it_admin: {
        this: {},
      },
      security_guard: {
        this: {},
      },
    },
    metadata: {
      relations: {
        it_admin: { directly_related_user_types: [{ type: 'user' }] },
        security_guard: { directly_related_user_types: [{ type: 'user' }] },
      },
    },
  },
],
}}
/>

<Note>
  Notice that any reference to the [**direct relationship type restrictions**](/docs/configuration-language#direct-relationship-type-restrictions) has been removed. That indicates that a user cannot have a [direct relationship](/docs/concepts#what-are-direct-and-implied-relationships) with an object in this type.

  With this change, `anne` can no longer have a `live_video_viewer` permission for `device:1` except through having a `security_guard` or `it_admin` role first, and when she loses access to that role, she will automatically lose access to the `live_video_viewer` permission.
</Note>

<h4 id="verification-3">Verification</h4>

Now that direct relationship is denied, we should see that `anne` has `live_video_viewer` relation to `device:1` solely based on her position as `security_guard` to `device:1`. Let's find out.

To test this, we can add a new user `emily`. Emily is **not** a `security_guard` nor an `it_admin`. However, we attempt to access via direct relations by adding the following [relationship tuples](/docs/concepts#what-is-a-relationship-tuple):

<WriteRequestViewer
  relationshipTuples={[
{
  user: 'user:emily',
  relation: 'live_video_viewer',
  object: 'device:1',
},
{
  user: 'user:emily',
  relation: 'recorded_video_viewer',
  object: 'device:1',
},
{
  user: 'user:emily',
  relation: 'device_renamer',
  object: 'device:1',
},
]}
/>

Now try to query `is emily related to device:1 as live_video_viewer?`. The returned result should be `emily is not related to device:1 as live_video_viewer`. This confirms that direct relations have no effect on the `live_video_viewer` relations, and that is because the [**direct relationship type restriction**](/docs/configuration-language#direct-relationship-type-restrictions) was removed from the relation configuration.

<CheckRequestViewer user={'user:emily'} relation={'live_video_viewer'} object={'device:1'} allowed={false} />

Query on the other relationships and you will see:

| User | Object | Relation | Query | Relation? |
| - | - | - | - | - |
| `emily` | `device:1` | `recorded_video_viewer` | `is emily related to device:1 as recorded_video_viewer?` | No |
| `emily` | `device:1` | `device_renamer` | `is emily related to device:1 as device_renamer?` | No |

## Summary

In this post, you were introduced to [fine grain authentication](/docs/authorization-concepts#what-is-fine-grained-authorization) and OpenFGA.

Upcoming posts will dive deeper into OpenFGA, introducing concepts that will improve on the model you built today, and tackling more complex permission systems, with more relations and requirements that need to be met.

### Exercises for you

* Try adding a second group tied to devices 4 and 5. Add only Charles and Dianne to this group, then try to run queries that would validate your model.
* Management has decided that Security Guards can only access live videos, and instituted a new position called Security Officer who can view both live and recorded videos. Can you update the authorization model to reflect that?


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.