# User Management & Authentication

### `GET` Current User

Fetches the information of the currently logged-in user. The response includes user details such as their primary key, name, email, and various attributes.

**Path:** `/current_user/`

**Authentication Required:** Yes

**Headers:**

```
Accept-Language: <iso_language_code>
Cookie: <cookie-name>=<session_id>
```

**Example Request**

```py
import requests

url = "https://{commerce_url}/current_user/"

headers = {
    'Accept-Language': '<iso_language_code>',
    'Cookie': '<cookie-name>=<session_id>'
}

response = requests.get(url, headers=headers, data=payload)

print(response.text)
```

**Example Response (200 OK)**

```json
{
    "pk": 64571,
    "first_name": "John",
    "last_name": "Doe",
    "phone": "0000000000",
    "email": "example@example.com",
    "email_allowed": true,
    "sms_allowed": true,
    "call_allowed": false,
    "attributes": {
        "register_client_type": "default",
        "logged_ip": "0.0.0.0",
        "kvkk_flat_page_version": "000",
        "confirm": true
    },
    "hashed_email": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "date_joined": "2024-01-01T00:00:00.000000Z",
    "last_login": "2024-01-02T00:00:00.000000Z",
    "gender": "male",
    "date_of_birth": "2016-01-01",
    "is_email_verified": true,
    "is_social_networks_connected": false,
    "client_type": "default",
    "selected_address": {
        "pk": 54,
        "tax_no": null,
        "last_name": "",
        "extra_field": null,
        "primary": true,
        "e_bill_taxpayer": false,
        "postcode": null,
        "hash_data": "GMWuUyFOAJyyeAQXpDdoxbsNFOcgSitIqNAvetSWa",
        "line": "wQFgRqjIwMtSdtmwgzyhQmmTTQjFLzaaRYIjVlZyiLeIYbGHhAy",
        "is_corporate": false,
        "city": 54,
        "first_name": "",
        "district": 1,
        "title": "home",
        "remote_id": null,
        "company_name": null,
        "tax_office": null,
        "address_type": "customer",
        "email": "wnyWrjRpnt@example.com",
        "phone_number": null,
        "user": 856,
        "township": 1,
        "country": 107,
        "notes": null,
        "identity_number": null,
        "retail_store": null
    }
}
```

**Response Parameters:**

| Property                        | Data Type | Description                                                               |
| ------------------------------- | --------- | ------------------------------------------------------------------------- |
| email\_allowed                  | Boolean   | Indicates whether the user has allowed receiving emails.                  |
| sms\_allowed                    | Boolean   | Indicates whether the user has allowed receiving SMS.                     |
| call\_allowed                   | Boolean   | Indicates whether the user has allowed receiving phone calls.             |
| hashed\_email                   | String    | The hashed version of the user's email for privacy and security purposes. |
| is\_email\_verified             | Boolean   | Indicates whether the user's email address has been verified.             |
| is\_social\_networks\_connected | Boolean   | Indicates whether the user's account is connected to any social networks. |
| client\_type                    | Enum      | Values: “default”, “android”, “ios”, “instore”, “b2b”.                    |
| selected\_address               | Dict      | Contains the details of the user’s selected address.                      |

### `POST` User Login

Used to facilitate the user’s log-in process. Cookies of the returned response must be stored by the client and sent with the next API requests.

**Path:** `/users/login`

**Authentication Required:** No

**Headers:**

```
Content-Type: application/json
Accept-Language: <iso_language_code>
x-csrftoken: <token>
```

**Body Parameters**

| Property | Data Type | Required | Description                    |
| -------- | --------- | -------- | ------------------------------ |
| email    | string    | True     | The email address of the user. |
| password | string    | True     | The password of the user.      |

**Request Body**

```json
{
    "email": "<USER_EMAIL>",
    "password": "<PASSWORD>"
}
```

**Example Request**

```py
import requests

url = "https://{commerce_url}/users/login/"

payload = json.dumps({
    "email": "<USER_EMAIL>",
    "password": "<PASSWORD>"
})

headers = {
    'Content-Type': 'application/json',
    'Accept-Language': '<iso_language_code>',
    'x-csrftoken': '<token>'
}

response = requests.post(url, headers=headers, data=payload)
print(response.text)
```

**Example Response (200 OK)**

**Response Headers:**

```js
set-cookie: csrftoken=KxlMDi8Nfy0HljwuWTRnJwDMfGtP5Zh8xHn4BMOEJFAxaRAFJx6MarlaHDM66LZ7; expires=Mon, 24-Nov-2025 10:51:51 GMT; Max-Age=31449600; Path=/; Secure, osessionid=yji6ppwys9a2k2myv3k9e5q2jifggqt9; expires=Mon, 09-Dec-2024 10:51:51 GMT; httponly; Max-Age=1209600; Path=/; SameSite=None; Secure
```

{% hint style="info" %}
`csrftoken` must be included in the header of subsequent requests except the `GET` method.

**Example:**

```
x-csrftoken: KxlMDi8Nfy0HljwuWTRnJwDMfGtP5Zh8xHn4BMOEJFAxaRAFJx6MarlaHDM66LZ7
```

The `osessionid` is the default value determined by the `SESSION_COOKIE_NAME` parameter, which is read from the `SESSION_COOKIE_NAME` environment variable in the `settings.py` file. If this value has been modified, the updated `SESSION_COOKIE_NAME` must be included in the Cookie header.

**Example:**

```
Cokkie:<modified_session_cookie_name>=yji6ppwys9a2k2myv3k9e5q2jifggqt9
```

{% endhint %}

**Example Response (400 Bad Request)**

```json
{
    "non_field_errors": [
        "Unable to log in with provided credentials."
    ]
}
```

### `POST` User Logout

This endpoint logs out the currently authenticated user by deleting their session data. After the request is processed, the user is unauthenticated and must log in again to access authenticated endpoints.

**Path:** `/users/logout/`

**Authentication Required:** Yes

**Headers:**

```
Accept-Language: <iso_language_code>
Cookie: <cookie-name>=<session_id>
x-csrftoken: <token>
```

**Request Body**

None

**Example Request**

```py
import requests

url = "https://{commerce_url}/users/logout/"

headers = {
    'Accept-Language': '<iso_language_code>',
    'Cookie': '<cookie-name>=<session_id>',
    'x-csrftoken': '<token>'
}
response = requests.post(url, data=payload, headers=headers)
```

**Example Response (200 OK)**

No content is returned in the response body. The 200 OK status indicates that the user has been successfully logged out and their session invalidated.

### `POST` User Registration with OTP

This endpoint allows users to create a new account. The registration process requires SMS OTP verification, which must be activated via the settings.

To enable SMS OTP verification, the following two environment variables must be added to the Commerce service in ACC.

```
Name: REST_REGISTER_VIEW 

Value: omnishop.users.views.RegisterSMSOtpView
```

```
Name: REST_AUTH_REGISTER_SERIALIZERS

Value: {"REGISTER_SERIALIZER": "omnishop.users.resources.serializers.RegisterSMSOtpSerializer"}
```

Additionally, for the system to send SMS OTP, the `SMS_GATEWAY` and `SMS_GATEWAYS` dynamic settings must be properly configured. Ensure the correct SMS gateway provider is set up in the application settings, and verify that the gateway is operational.

**Path:** `/users/registration/`

**Authentication Required:** No

**Headers:**

```
Content-Type: application/json
Accept-Language: <iso_language_code>
x-csrftoken: <token>
```

**Query Parameters**

| Property | Data Type | Required | Description  |
| -------- | --------- | -------- | ------------ |
| next     | String    | False    | Redirect url |

**Body Parameters**

| Property        | Data Type | Required | Description                                                                                                                                                                     |
| --------------- | --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| first\_name     | String    | True     | The first name of the user.                                                                                                                                                     |
| last\_name      | String    | True     | The last name of the user                                                                                                                                                       |
| email           | String    | True     | The email address of the user.                                                                                                                                                  |
| password        | String    | True     | The password of the user.                                                                                                                                                       |
| confirm         | Boolean   | True     | Indicates that confirmation of the privacy policy must be set to `True`.                                                                                                        |
| email\_allowed  | Boolean   | False    | Indicates if the user consents to receiving emails.                                                                                                                             |
| sms\_allowed    | Boolean   | False    | Indicates if the user consents to receiving SMS messages.                                                                                                                       |
| call\_allowed   | Boolean   | False    | Indicates if the user consents to receiving phone calls.                                                                                                                        |
| gender          | String    | False    | Enum type representing the user's gender (`male`, `female`).                                                                                                                    |
| date\_of\_birth | String    | False    | The user's date of birth, formatted as `YYYY-MM-DD`.                                                                                                                            |
| username        | String    | False    | The username of the user.                                                                                                                                                       |
| user\_type      | String    | False    | A string that indicates the type of user. A string that indicates the type of user.                                                                                             |
| phone           | String    | False    | The user's phone number, validated and required for updates.                                                                                                                    |
| attributes      | Dict      | False    | Additional customizable user attributes in key-value pairs.                                                                                                                     |
| code            | String    | False    | The verification code required for phone number changes. This parameter is used in RegisterKvkkView - RegisterKvkkSerializer and RegisterSMSOtpView - RegisterSMSOtpSerializer. |
| resend          | String    | False    | Indicates if an verification code should be resent. This parameter is used in RegisterKvkkView - RegisterKvkkSerializer and RegisterSMSOtpView - RegisterSMSOtpSerializer.      |

**Request Body**

```json
{
    "first_name": "John",
    "last_name": "Doe",
    "email": "john.doe@example.com",
    "password: "Test123",
    "confirm": true
}
```

**Example Request**

```py
import requests
import json

url = "https://{commerce_url}/users/registration/"

headers = {
  'Content-Type': 'application/json',
  'Accept-Language': '<iso_language_code>',
  'x-csrftoken': '<token>'
}

payload = json.dumps({
    "first_name": "John",
    "last_name": "Doe",
    "email": "john.doe@example.com",
    "password: "Test123",
    "confirm": true
})

response = requests.post(url, headers=headers, data=payload)
print(response.text)
```

**Example Response (201 Created)**

If the `next` query parameter is provided, it is used to set the **redirect\_url**.

* **key**: `token` is used for authentication.

```json
{
    "key": "290724f203a94a8fc4a3fe549cc2fa8e9566044e",
    "redirect_url": "abc"
}
```

**Example Response (201 Created)**

```json
{
  "id": 1234,
  "first_name": "John",
  "last_name": "Doe",
  "email_allowed": false,
  "sms_allowed": true,
  "call_allowed": false,
  "avatar": "https://example.com/avatar.png",
  "email": "john.doe@example.com",
  "phone": "0123456789",
  "date_of_birth": "1990-05-15",
  "gender": "male",
  "genders": [
    {
      "value": "female",
      "label": "female"
    },
    {
      "value": "male",
      "label": "male"
    }
  ],
  "language_code": "en-gb",
  "attributes": {
    "register_client_type": "mobile",
    "logged_ip": "192.168.1.1",
    "kvkk_flat_page_version": "101",
    "confirm": false
  },
  "date_joined": "2023-06-01T12:30:45.123456Z"
}
```

**Example Response (202 Accepted)**

```json
{
  "id": 1234,
  "first_name": "John",
  "last_name": "Doe",
  "email_allowed": false,
  "sms_allowed": true,
  "call_allowed": false,
  "avatar": "https://example.com/avatar.png",
  "email": "john.doe@example.com",
  "phone": "0123456789",
  "date_of_birth": "1990-05-15",
  "gender": "male",
  "genders": [
    {
      "value": "female",
      "label": "female"
    },
    {
      "value": "male",
      "label": "male"
    }
  ],
  "language_code": "en-gb",
  "attributes": {
    "register_client_type": "mobile",
    "logged_ip": "192.168.1.1",
    "kvkk_flat_page_version": "101",
    "confirm": false
  },
  "date_joined": "2023-06-01T12:30:45.123456Z"
}
```

**Example Response (200 OK)**

When `resend` is True:

```json
{
    "message": "ok"
}
```

**Example Response (400 Bad Request)**

When `confirm` is False:

```json
{
    "confirm": [
        "You must confirm privacy policy."
    ]
}
```

**Example Response (400 Bad Request)**

There is a `GUEST_USER_REGISTRATION_REQUIRES_EMAIL_VERIFICATION` dynamic setting. When it is set to true and the request data is available:

```json
"attributes": {
    "verification_required": true
}
```

```json
[
    "Please verify your email address before login."
]
```

**Example Response (406 Not Acceptable)**

```json
{
    "non_field_errors": "Mismatch confirmation data {phone}, {sms_allowed}, {email_allowed}, {call_allowed}, {email}.",
    "error_code": "kvkk_service_100_2"
}
```

### `POST`/`GET` User Registration Email Confirmation

This endpoint handles email confirmation for users during the account activation process. It validates the confirmation key provided in the URL and confirms the user's email address.

**Path:** `/users/registration/account-confirm-email/<key>/`

**Authentication Required:** Yes

**Headers:**

```
Content-Type: application/json
Accept-Language: <iso_language_code>
x-csrftoken: <token>
Cookie: <cookie-name>=<session_id>
```

**Example Request**

```py
import requests
import json

url = "https://{commerce_url}/users/registration/account-confirm-email/sdjfklwıoghsfg/"

headers = {
  'Content-Type': 'application/json',
  'Cookie': '<cookie-name>=<session_id>',
  'Accept-Language: '<iso_language_code>',
  'x-csrftoken': '<token>'
}

response = requests.get(url, headers=headers)
print(response.text)
```

**Example Response (200 OK)**

Email confirmation succeeded, and the HTML file returned.

```javascript

<div data-gb-custom-block data-tag="extends" data-0='base.html'></div>

<div data-gb-custom-block data-tag="block">

  <div class="account-contact__success js-account-success-box" style="display: block;">
    <div class="account-contact__success__box">
      <span class="account-contact__success__check fa fa-check"></span>
      <div class="account-contact__success__title">
        E-POSTA ADRESİNİZİ DOĞRULAYIN
      </div>
      <p class="account-contact__success__description">
        E-posta adresinizi doğrulamak için allttaki butona basınız.
      </p>
    </div>
      <form method="post" action="{{ url('account_confirm_email', key=confirmation.key) }}">
        

<div data-gb-custom-block data-tag="csrf_token"></div>

        <button type="submit" class="account-contact__success__redirect">DOĞRULA</button>
      </form>
    </a>
  </div>

</div>
```

**Example Response (404 Not Found)**

If the confirmation key is invalid or expired:

```json
{}
```

### `POST` User Registration Verify Email

This endpoint verifies the user's email address by using the token sent via email. After the user registers, they will receive an email with a token that they need to submit to verify their email and activate their account.

**Path:** `/users/registration/verify-email/`

**Authentication Required:** Yes

**Headers**

```
Content-Type: application/json
Accept-Language: <iso_language_code>
Cookie: <cookie-name>=<session_id>
x-csrftoken: <token>
```

**Body Parameters**

| Property | Data Type | Required | Description                                      |
| -------- | --------- | -------- | ------------------------------------------------ |
| key      | string    | True     | The verification token sent to the user’s email. |

**Request Body**

```json
{
    "key": "12345abcdef"
}
```

**Example Request**

```py
import requests

url = "https://{commerce_url}/users/registration/verify-email/"

payload = json.dumps({
    "key": "12345abcdef"
})

headers = {
  'Content-Type': 'application/json',
  'Accept-Language: '<iso_language_code>',
  'Cookie': '<cookie-name>=<session_id>',
  'x-csrftoken': '<token>'
}

response = requests.post(url, headers=headers, data=payload)
print(response.json())
```

**Example Response (200 OK)**

```json
{
    "detail": "ok"
}
```

### `GET` Verify User Email

This endpoint verifies the user's email address. The user completes the verification process by clicking a confirmation link sent to their email. The `signed_email` and `user_id_key` are unique tokens generated by the commerce system to ensure secure validation.

**Path:** `/users/email-verify/<signed_email>/<user_id_key>/`

### `POST` Add New User Email

This endpoint allows users to add a new email address to their account. A confirmation email is sent to the provided email address. The email is added only after the user confirms it through the link in the confirmation email.

**Path:** `/users/emails/`

**Authentication Required:** Yes

**Headers:**

```
Accept-Language: <iso_language_code>
Cookie: <cookie-name>=<session_id>
x-csrftoken: <token>
Content-Type: 'application/json'
```

**Body Parameters**

| Property | Data Type | Required | Description                    |
| -------- | --------- | -------- | ------------------------------ |
| email    | string    | True     | The email address to be added. |

**Request Body**

```json
{
	"email": "example@example.com"
}
```

**Example Request**

```py
import requests
import json

url = "https://{commerce_url}/users/emails/"

payload = json.dumps({
  "email": "example@example.com"
})
headers = {
  'Accept-Language': ' <iso_language_code>',
  'Cookie': ' <cookie-name>=<session_id>',
  'x-csrftoken': ' <token>',
  'Content-Type': 'application/json'
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)
```

**Example Response (200 OK)**

The email has been added successfully, and a confirmation email has been sent:

```json
{}
```

**Example Response (400 Bad Request)**

If the email already exists:

```json
{
  "email": [
	"Email address is already exists."
  ]
}
```

### `GET` Set User Email as Primary

This endpoint confirms the user's selection of a primary email address. The user completes the confirmation process by clicking a link sent to their email. The `signed_email` and `user_id_key` are unique tokens generated by the commerce system to ensure secure validation.

**Path:** `/users/email-set-primary/<signed_email>/<user_id_key>/`

### `POST` User Email Change

This endpoint updates the primary email address of an authenticated user. A verification email is sent to the new email address, and the change is confirmed only after successful verification.

**Path:** `/users/email-change/`

**Authentication Required:** Yes

**Headers:**

```
Content-Type: application/json
Accept-Language: <iso_language_code>
Cookie: <cookie-name>=<session_id>
x-csrftoken: <token>
```

**Body Parameters**

| Property | Data Type | Required | Description                                 |
| -------- | --------- | -------- | ------------------------------------------- |
| email    | string    | True     | The new email address to set for the user.  |
| password | string    | True     | The user's current password for validation. |

**Request Body**

```json
{
  "email":"test_info@akinon.com",
  "password": "test.pass"
}
```

**Example Request**

```py
import requests
import json

url = "https://{commerce_url}/users/email-change/"

payload = json.dumps({
  "email": "test_info@akinon.com",
  "password": "test.pass"
})
headers = {
    'Content-Type': 'application/json',
    'Accept-Language': '<iso_language_code>'
    'Cookie': '<cookie-name>=<session_id>',
    'x-csrftoken': '<token>'
}

response = requests.post(url, headers=headers, data=payload)

print(response.text)
```

**Example Response (200 OK)**

```json
{
    "user": 6471,
    "email": "test_info@akinon.com"
}
```

**Example Response (400 Bad Request)**

```json
{
    "non_field_errors": [
        "Invalid password."
    ]
}
```

### `GET` User Email Show

This endpoint retrieves the email details associated with the authenticated user, including whether the email is verified and if it is the primary email.

**Path:** `/users/emails/`

**Authentication Required:** Yes

**Headers:**

```
Accept-Language: <iso_language_code>
Cookie: <cookie-name>=<session_id>
```

**Example Request**

```py
import requests

url = "https://{commerce_url}/users/emails/"

headers = {
    'Accept-Language': '<iso_language_code>',
    'Cookie': '<cookie-name>=<session_id>'
}

response = requests.get(url, headers=headers)
print(response.text)
```

**Example Response (200 OK)**

```json
{
    "id": 2,
    "email": "test@akinon.com",
    "verified": false,
    "primary": true,
    "user": 1
}
```

**Response Parameters:**

| Property | Data Type | Description                                                 |
| :------: | :-------: | ----------------------------------------------------------- |
|    id    |  Integer  | The unique identifier of the email record.                  |
|   email  |   String  | The email address associated with the user.                 |
| verified |  Boolean  | Indicates if the email address has been verified.           |
|  primary |  Boolean  | Indicates if this is the primary email address of the user. |
|   user   |  Integer  | The unique identifier of the user who owns the email.       |

### `PATCH` KVKK Unsubscribe User

This endpoint is used to update users' communication preferences as per KVKK (Turkish Personal Data Protection Law). The service utilizing this hook must be pre-registered. It allows unsubscribing users from email, SMS, or phone call permissions.

**Path:** `/users/hooks/kvkk-unsubscribe-user/`

**Authentication Required:** No

**Headers:**

```
Accept-Language: <iso_language_code>
x-csrftoken: <token>
Content-Type: 'application/json'
```

**Body Parameters**

| Property                           | Data Type | Required | Description                                                                                                          |
| ---------------------------------- | --------- | -------- | -------------------------------------------------------------------------------------------------------------------- |
| service\_name                      | String    | True     | The name of the service using the hook.                                                                              |
| hash\_value                        | String    | True     | A SHA-256 hash generated by encrypting the `secret_key` and `request_datetime`.                                      |
| request\_datetime                  | String    | True     | Specifies the time the request was sent. It must be in timezone-aware ISO format: `YYYY-MM-DDTHH:MM:SS.ffffff+HH:MM` |
| unsubscribed\_users                | List      | True     | A list of users to unsubscribe, including their email or phone details.                                              |
| unsubscribed\_users.phone          | String    | False    | The phone number of the user (either `phone` or `email` must be provided, but not both).                             |
| unsubscribed\_users.email          | String    | False    | The email address of the user (either `phone` or `email` must be provided, but not both).                            |
| unsubscribed\_users.email\_allowed | Boolean   | False    | Whether the user allows email communication.                                                                         |
| unsubscribed\_users.sms\_allowed   | Boolean   | False    | Whether the user allows SMS communication.                                                                           |
| unsubscribed\_users.call\_allowed  | Boolean   | False    | Whether the user allows phone call communication.                                                                    |

Each user's subscription information must be specified as follows:

* Only one of the `phone` or `email` fields can be used. Both cannot be provided at the same time.
* The `email_allowed`, `sms_allowed`, and `call_allowed` fields can only have a value of `False`; these fields only allow the user to opt out of these communication channels.

```json
{
    "phone": string | not required,
    "email": string | not required,
    "email_allowed": bool | not required,
    "sms_allowed": bool | not required,
    "call_allowed": bool | not required
}
```

**Hash Calculation**

The service checks the `hash_value` provided by the user. This value is calculated using the `secret_key` and `request_datetime`. Below is a step-by-step explanation of how to compute the hash value.

**1. Creating the Hash String:** First, a string is created using the combination of `secret_key` and `request_datetime` (the time of the request) in ISO format.

* **secret\_key:** The key provided by the subscription service.
* **request\_datetime:** The timestamp of the request in ISO format.

The hash string is concatenated as follows:

```
hash_string = secret_key + request_datetime.isoformat()
```

**Example:**

* `secret_key`: `"my_secret_key"`
* `request_datetime`: `"2024-09-26 10:49:58.694785+00:00"`
* `request_datetime.isoformat()`: `“2024-09-26T10:49:58.694785+00:00”`

**Hash string:**

```
my_secret_key2024-09-26T10:49:58.694785+00:00
```

**2. Calculating the Hash:** The generated string is then hashed using the SHA-256 algorithm. This process converts the string into a fixed-length hash value, ensuring data confidentiality.

**Example:**

* `hash_string`: `"my_secret_key2024-09-26T10:49:58.694785+00:00"`

**Calculated hash:**

```
calculated_hash = SHA-256("my_secret_key2024-09-26T10:49:58.694785+00:00")
```

**Resulting hash value:**

```
c804723c11619670b969845e9011a154099dafc324794c52696c5c22264dcea4
```

**Request Body**

```json
{
	"service_name": "test",
	"hash_value": "hash_value",
	"request_datetime": "2024-12-04T14:30:00",
	"unsubscribed_users": [
    	{
        	"email": "test@test.com",
        	"email_allowed": false,
        	"sms_allowed": false,
        	"call_allowed": false
    	}
	]
}
```

**Example Request**

```py
import requests
import json

url = "https://{commerce_url}/users/hooks/kvkk-unsubscribe-user/"

payload = json.dumps({
  "service_name": "test",
  "hash_value": "hash_value",
  "request_datetime": "2024-12-04T14:30:00",
  "unsubscribed_users": [
	{
  	"email": "test@test.com",
  	"email_allowed": False,
  	"sms_allowed": False,
  	"call_allowed": False
	}
  ]
})
headers = {
  'Content-Type': 'application/json'
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)
```

**Example Response (200 OK)**

```javascript
{}
```

### `PATCH` Unsubscribe User

This endpoint is used to update users' communication preferences. The service utilizing this hook must be pre-registered. It specifically targets unsubscribing users from various communication permissions (email, SMS, or phone).

**Path:** `/users/hooks/unsubscribe-user/`

**Authentication Required:** No

**Headers:**

```
Accept-Language: <iso_language_code>
x-csrftoken: <token>
Content-Type: 'application/json'
```

**Body Parameters**

| Property                           | Data Type | Required | Description                                                                                                          |
| ---------------------------------- | --------- | -------- | -------------------------------------------------------------------------------------------------------------------- |
| service\_name                      | String    | True     | The name of the service using the hook.                                                                              |
| hash\_value                        | String    | True     | A SHA-256 hash generated by encrypting the `secret_key` and `request_datetime`.                                      |
| request\_datetime                  | String    | True     | Specifies the time the request was sent. It must be in timezone-aware ISO format: `YYYY-MM-DDTHH:MM:SS.ffffff+HH:MM` |
| unsubscribed\_users                | List      | True     | A list of users to unsubscribe, including their email or phone details.                                              |
| unsubscribed\_users.email          | String    | True     | The email of the user to be unsubscribed.                                                                            |
| unsubscribed\_users.email\_allowed | Boolean   | False    | Whether the user allows email communication.                                                                         |
| unsubscribed\_users.sms\_allowed   | Boolean   | False    | Whether the user allows SMS communication.                                                                           |
| unsubscribed\_users.call\_allowed  | Boolean   | False    | Whether the user allows phone call communication.                                                                    |

**Hash Calculation**

The hash calculation varies depending on each subscription gateway.

**Request Body**

```json
{
	"service_name": "test",
	"hash_value": "hash_value",
	"request_datetime": "2024-12-04T14:30:00",
	"unsubscribed_users": [
    	{
        	"email": "test@test.com",
        	"email_allowed": false,
        	"sms_allowed": false,
        	"call_allowed": false
    	}
	]
}
```

**Example Request**

```py
import requests
import json

url = "https://{commerce_url}/users/hooks/unsubscribe-user/"

payload = json.dumps({
  "service_name": "test",
  "hash_value": "hash_value",
  "request_datetime": "2024-12-04T14:30:00",
  "unsubscribed_users": [
	{
  	"email": "test@test.com",
  	"email_allowed": False,
  	"sms_allowed": False,
  	"call_allowed": False
	}
  ]
})
headers = {
  'Content-Type': 'application/json'
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)
```

**Example Response (200 OK)**

```json
{}
```

### `PATCH` User Anonymization

This endpoint allows an authenticated user to anonymize their personal data, in compliance with data privacy regulations. When anonymized, the following actions occur:

* **Identifying details (e.g., name, email, phone number):** These are hashed to ensure user privacy.
* **Linked social accounts and email addresses:** All associated accounts are anonymized.
* **User account:** The account is deactivated.

{% hint style="warning" %}
The feature depends on the `dynamic_settings.SELF_ANONYMIZATION_ENABLED` configuration being set to `True`. By default, this setting is `False`.
{% endhint %}

**Path:** `/users/anonymize/`

**Authentication Required:** Yes

**Headers:**

```
Content-Type: application/json
Accept-Language: <iso_language_code>
Cookie: <cookie-name>=<session_id>
x-csrftoken: <token>
```

**Example Request**

```py
import requests

url = "http://{commerce_url}/users/anonymize/"

headers = {
  'Content-Type': 'application/json',
  'Accept-Language: '<iso_language_code>',
  'Cookie': '<cookie-name>=<session_id>',
  'x-csrftoken': '<token>'
}

response = requests.patch(url, headers=headers)

print(response.status_code)
print(response.text)
```

**Example Response (401 Unauthorized)**

Authentication credentials were not provided:

```json
{
    "detail": "Authentication credentials were not provided."
}
```

**Example Response (403 Forbidden)**

The feature is disabled (`SELF_ANONYMIZATION_ENABLED` is `False`):

```json
{
    "detail": "You do not have permission to perform this action."
}
```

**Example Response (200 OK)**

Anonymization is successful, and no content is returned.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://apidocs.akinon.com/commerce/users/user-management-and-authentication.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
