# Org Based Code

{% hint style="info" %}
This page describes code related to organization creation and authentication in matar app.
{% endhint %}

***

### Organization Schema

Here is the organization database schema and its attributes:

```python
class Organization(Base):
    __tablename__ = 'organization'

    _id = db.Column(db.String, primary_key=True)
    title = db.Column(db.String)
    language = db.Column(db.String)
    is_chatgpt_enabled = db.Column(db.Boolean, default=True)
    max_post_duration = db.Column(db.Integer, default=15)  # in seconds
    org_type = db.Column(db.Integer, default=0)  # 0 - public, 1 - private
    is_active = db.Column(db.Boolean, default=True)
    description = db.Column(db.String)
    code = db.Column(db.String)
    

    sort_order = db.Column(db.Integer)
```

**Describing Code:** A SQLAlchemy model class named **Organization** defines a table named 'organization' with several columns. Here's an explanation of each column:

1. **\_id**: This is the primary key column of the table. It's of type **String**, which suggests it to store string values. Primary keys are typically used for uniquely identifying each row in the table.
2. **title**: This column appears to store the title of an organization
3. **language**: This column stores the language of the organization
4. **is\_chatgpt\_enabled**: This is a boolean column (True/False) indicating whether chat gpt functionality is enabled for the organization. It has a default value of True.
5. **max\_post\_duration**: This column appears to store the maximum post duration in seconds. It is of type integer and has a default value of 15 seconds.
6. **org\_type**: This column is used to define the type of organization, with 0 representing public and 1 representing private. It is of type **Integer** and has a default value of 0.
7. **is\_active**: This is another boolean column indicating whether the organization is active. It has a default value of True.
8. **description**: This column is used to store organization description.
9. **code**: This column appears to store a code related to the organization.
10. **sort\_order**: This column does not have a default value specified but depending on application it will have a value when inserting data into the table.

***

### Organization Authentication

Here is a code snippet of how org authentication is protected with JWT functions below:

```python
def authentication_required_organization(func):
    @jwt_required()
    def inner(*args, **kwargs):
        user_id = get_jwt_identity()
        user = User.query.get(user_id)
        organization_id = request.args.get("organization_id")
        organization = Organization.query.get(organization_id)
        if(not user):
            return {"error": "no such user"}, 403
        if(not organization):
            return {"error": "no such organization"}, 400
        default_organizations = user.roles.get("default") or []
        if(organization_id not in default_organizations and not user.roles.get("superadmin")):
            return {"error": "User doesnt have permission for this organization"}, 400

        return func(user=user, organization=organization, *args, **kwargs)

    inner.__name__ = func.__name__
    return inner
```

**Describing Code:**

* When it comes to org-level authentication a JSON Web Token is required for authentication if valid you will be able to retrieve the authenticated user information using the [get\_jwt\_identity()](https://flask-jwt-extended.readthedocs.io/en/3.0.0_release/api/#flask_jwt_extended.get_jwt_identity) function . The [jwt\_required()](https://flask-jwt-extended.readthedocs.io/en/3.0.0_release/api/#flask_jwt_extended.jwt_required) is used to protect all the routes by requiring authentication via JSON Web Tokens (JWT) and checking the user's permissions within an organization.
* **@jwt\_required()** decorator requires a valid JWT token to access. If a request doesn't include a valid token, it won't proceed further.
* The **inner** function is defined inside the **@jwt\_required() decorator which receives the same arguments as the decorated function (\*args** and **\*\*kwargs**) along with two additional arguments: **user** and **organization**. These two additional arguments will receive information based on the user's JWT identity and the **organization\_id** from the request.
* First the **user\_id** is extracted from the JWT token's identity using **get\_jwt\_identity()** and fetches the corresponding **User** object from the database. The **organization\_id** is also retrieved from the request's query parameters and fetches the **Organization** object from db.
* The code also checks whether the user and organization exist. If either the user or the organization doesn't exist, it returns an appropriate error response with a 403 or 400 status code, respectively.
* The user's permissions. are also checked to determine the user's roles whether they have permission for the specified organization. A user can have a superadmin role (admin of all orgs) or can have a default role (admin of a particular organization.
* If the user is not super admin or not part of default org app will return <mark style="background-color:blue;">`User doesn't have permission for this organization.`</mark>
* If all checks pass, it calls the original function (**func**) with the **user** and **organization** arguments along with any other arguments and keyword arguments passed to the decorated route.
