Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
192 changes: 88 additions & 104 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,149 +1,133 @@
# Python SDK
Python library used to integrate with Descope
# ExpresSDK for Python

### Prerequisites
Use the Descope ExpresSDK for Python to quickly and easily add user authentication to your application or website. If you need a bit more background on how the ExpresSDKs work, [click here](/sdk/index.mdx).

In order to initiate the AuthClient object you must specify the project ID given by Descope either by:
- Set the `DESCOPE_PROJECT_ID` environment variable.
- Set the project_id argument when initialization the AuthClient object.
The Descope ExpresSDK for Python supports 3.6 and above.

## ExpressStart with OTP Authentication

### Installation
Install the Descope Python SDK using the following command.
Descope Python SDK supports Python 3.6 and above
This section will show you how to implement user authentication using a one-time password (OTP). A typical four step flow for OTP authentictaion is shown below.

.. code-block:: python
```mermaid
flowchart LR
signup[1. customer sign-up]-- customer gets OTP -->verify[3. customer verification]
signin[2. customer sign-in]-- customer gets OTP -->verify
verify-- customer does stuff -->validate[4. session validation]
```

pip install Descope-Auth
Decorators shown in the code below are valid for Python Flask.

### Prerequisites

## Usage
Use (copy-paste) the pre defined samples decorators based on your framework (Flask supported) or the api as describe below
Replace any instance of `<ProjectID>` in the code below with your company's Project ID, which can be found in the [Descope console](link).

### API
.. code-block:: python
* Run the following code in your project:

from descope import DeliveryMethod, User, AuthClient
These commands will add the Descope ExpresSDK for Python as a project dependency, and set the `DESCOPE_PROJECT_ID` variable to a valid \<ProjectID\>.

class DeliveryMethod(Enum):
WHATSAPP = 1
PHONE = 2
EMAIL = 3
```code Python
pip install Descope-Auth
export DESCOPE_PROJECT_ID=<ProjectID>
```

User(username: str, name: str, phone: str, email: str)
* Import and initialize the ExpresSDK for Python client in your source code

AuthClient(PROJECT_ID, PUBLIC_KEY=None)
```code Python
from descope import DeliveryMethod, User, AuthClient
```

sign_up_otp(method: DeliveryMethod, identifier: str, user: User)
Example:
from descope import DeliveryMethod, User, AuthClient
user = User("username", "name", "11111111111", "dummy@dummy.com")
auth_client = AuthClient(PROJECT_ID)
auth_client.sign_up_otp(DeliveryMethod.EMAIL, "dummy@dummy.com", user)
### 1. Customer Sign-up

In your sign-up route for OTP (for example, `myapp.com/signup`) generate a sign-up request and send the OTP verification code via the selected OTP delivery method. In the example below an email is sent to "mytestmail@test.com". In additon, optional user data (for exmaple, a custom username in the code sample below) can be gathered during the sign-up process.

sign_in_otp(method: DeliveryMethod, identifier: str)
Example:
from descope import DeliveryMethod, AuthClient
auth_client = AuthClient(PROJECT_ID)
auth_client.sign_in_otp(DeliveryMethod.EMAIL, "dummy@dummy.com")
```code Python
user = User("newusername", "full name", "555-555-1212", "mytestmail@test.com")
auth_client.sign_up_otp(DeliveryMethod.EMAIL, "mytestmail@test.com, user)
```

### 2. Customer Sign-in
In your sign-in route for OTP (for exmaple, `myapp.com/login`) generate a sign-in request send the OTP verification code via the selected OTP delivery method. In the example below an email is sent to "mytestmail@test.com".

```code Python
auth_client.sign_in_otp(DeliveryMethod.EMAIL, "mytestemail@test.com")
}
```
```code Flask Decorator
@descope_signin_otp_by_email
```

verify_code(method: DeliveryMethod, identifier: str, code: str)
--Upon successful verification new session cookies will returned and should be set on the response
Or one of the decorators:
@descope_verify_code_by_email
@descope_verify_code_by_phone
@descope_verify_code_by_whatsapp
### 3. Customer Verification


Example:
from descope import DeliveryMethod, AuthClient
auth_client = AuthClient(PROJECT_ID)
auth_client.verify_code(DeliveryMethod.EMAIL, "1111")
Or decorator
In your verify customer route for OTP (for example, `myapp.com/verify`) verify the OTP from either a customer sign-up or sign-in. The validate_session_request function call will write the necessary tokens and cookies to validate each session interaction.

APP = Flask(__name__)
@APP.route("/api/verify")
```code Python
claims, tokens = validate_session_request(signed_token: str, signed_refresh_token: str)
```
```code Flask Decorator
@descope_verify_code_by_email
def verify():
pass
```

### 4. Session Validation

Session validation checks to see that the visitor to your website or application is who they say they are, by comparing the value in the validation variables against the session data that is already stored.

In the code below the validates the original session tokens and cookies (`session_token`) and validates the tokens and cookies from the client. ValidateSession returns true if the user is authorized, and false if the user is not authorized. In addition, the session will automatically be extended if the user is valid but the sesssion has expired by writing the updated tokens and cookies to the response writer (w).

validate_session_request(signed_token: str, signed_refresh_token: str)
Or decorator
```code Python
claims, tokens = auth_client.validate_session_request('session_token', 'refresh_token')
```
```code Flask Decorator
@descope_validate_auth
```

Example:
from descope import AuthClient
auth_client = AuthClient(PROJECT_ID)
new_valid_token = auth_client.validate_session_request('session_token', 'refresh_token')
## ExpressStart with MagicLink Authentication

logout(signed_token: str, signed_refresh_token: str)
Example:
from descope import AuthClient
auth_client = AuthClient(PROJECT_ID)
auth_client.logout('session_token', 'refresh_token')
:::warning for the reviewer!
This is currenly a placeholder section only - to demonstrate how the framework can include addtional SDK flows.
:::

#### Exception
.. code-block:: python
This section will help you implement user authentication using Magiclinks. etc. etc. The flow for MagicLinks is

AuthException
Example:
from descope import DeliveryMethod, AuthClient, AuthException
try:
auth_client = AuthClient(PROJECT_ID)
auth_client.sign_in_otp(DeliveryMethod.EMAIL, "dummy@dummy.com")
except AuthException:
#Handle exception
```mermaid
flowchart LR
signup[1. customer sign-up]-- customer gets MagicLink -->verify[3. MagicLink verification]
signin[2. customer sign-in]-- customer gets MagicLink -->verify
verify-- customer does stuff -->validate[4. session validation]
```

#
### Run The Example
### Prerequisites

1. Clone repo locally `git clone github.com/descope/python-sdk`
2. Install the requirements `pip3 install -r requirements-dev.txt`
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc laoreet diam vel dignissim posuere. Vestibulum consectetur ante justo, in pretium ligula sollicitudin ut.

3. export your project id
### 1. do this

```
export DESCOPE_PROJECT_ID=<insert here>
```
Sed porttitor eu metus vitae molestie. Sed sed erat risus. Donec eu tempor leo. In hac habitasse platea dictumst. Etiam ornare non tellus eget ultricies.

5. Run the example application `python samples/web_sample_app.py`
6. Application runs on `http://localhost:9000`
7. Now you can perform GET requests to the server api like the following example:
### 2. do that

Signup a new user by OTP via email, verify the OTP code and then access private (authenticated) api
Praesent a eros ut est fermentum egestas. Nulla eget leo diam. Vestibulum nec mi nisi. In finibus est in tellus sodales mattis. Etiam gravida nisl id arcu commodo malesuada.

.. code-block
## ExpressStart with Oauth

/api/signup
Body:
{
"email": "dummy@dummy.com",
"user": {
"username": "dummy",
"name": "dummy",
"phone": "11111111111",
"email": "dummy@dummy.com"
}
}
:::warning placeholder
placeholder for instanst-start OAuth example
:::

/api/verify
Body:
{
"code": "111111",
"email": "dummy@dummy.com"
}
## ExpresStart for WebAuthn

** Response will have the new generate session cookies
:::warning placeholder
placeholder for instanst-start WebAuthn example
:::

/api/private
Use the session cookies (otherwise you will get HTTP 401 - Unauthorized)

### Unit Testing
.. code-block:: python
## Unit Testing
Simplify your unit testing by using the predefined mocks and mock objects provided with the ExpresSDK.

```code python
python -m pytest tests/*
```

## License

The Descope ExpresSDK for Python is licensed for use under the terms and conditions of the [MIT license Agreement](https://github.com/descope/python-sdk/blob/main/LICENSE).