Skip to content

Added ssr and auth working with python #2107

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jun 17, 2025
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
155 changes: 155 additions & 0 deletions src/routes/docs/products/auth/server-side-rendering/+page.markdoc
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,17 @@ $adminClient = (new Client())
->setKey('<YOUR_API_KEY>'); // Your secret API key


```
```python
from appwrite.client import Client

admin_client = (Client()
.set_endpoint('https://<REGION>.cloud.appwrite.io/v1') # Your API Endpoint \
.set_project('<PROJECT_ID>') # Your project ID
.set_key('<YOUR_API_KEY>') # Your secret API key
)


```
{% /multicode %}

Expand Down Expand Up @@ -105,6 +116,22 @@ if ($session) {
$sessionClient->setSession($session);
}
```

```python
from flask import request
from appwrite.client import Client

session_client = (Client()
.set_endpoint('https://<REGION>.cloud.appwrite.io/v1') # Your API Endpoint
.set_project('<PROJECT_ID>') # Your project ID
)

# Get the session cookie from the request
session = request.cookies.get('session')
if session:
session_client.set_session(session)

```
{% /multicode %}

# Creating email/password sessions {% #creating-sessions %}
Expand Down Expand Up @@ -178,6 +205,39 @@ try {
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
```
```python
from flask import Flask, request, jsonify, make_response

# Initialize admin client here
# ...

@app.post('/login')
def login():
body = request.json
# Get email and password from request
email = body['email']
password = body['password']

try:
account = Account(admin_client)

# Create the session using the Appwrite client
session = account.create_email_password_session(email, password)
resp = make_response(jsonify({'success': True}))

# Set the session cookie
resp.set_cookie('session',
session['secret'],
httponly=True,
secure=True,
samesite='Strict',
expires=session['expire'],
path='/'
)
return resp
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 400
```
{% /multicode %}

We also recommend using the `httpOnly`, `secure`, and `sameSite` cookie options to ensure that the cookie is only sent over HTTPS,
Expand Down Expand Up @@ -242,6 +302,30 @@ try {
} catch (Exception $e) {
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
```
```python
# Initialize the session client here

@app.get('/user')
def get_user():
# First, read the session cookie from the request
session = request.cookies.get('session')

# If the session cookie is not present, return an error
if not session:
return jsonify({'success': False, 'error': 'Unauthorized'}), 401

# pass the session cookie to the Appwrite client
session_client.set_session(session)
account = Account(session_client)

# Now, you can make authenticated requests to the Appwrite API
try:
user = account.get()
return jsonify({'success': True, 'user': user})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 400

```
{% /multicode %}

Expand Down Expand Up @@ -319,6 +403,19 @@ $account = new Account($client);

$result = $account->createAnonymousSession();
```
```python
from appwrite.client import Client
from appwrite.services.account import Account

client = (Client()
.set_endpoint('https://<REGION>.cloud.appwrite.io/v1') # Your API Endpoint
.set_project('<PROJECT_ID>') # Your project ID
)

account = Account(client)

result = account.create_anonymous_session()
```
{% /multicode %}

# Forwarding user agent {% #forwarding-user-agent %}
Expand All @@ -333,6 +430,9 @@ client.setForwardedUserAgent(req.headers['user-agent']);
<?php
$client->setForwardedUserAgent($_SERVER['HTTP_USER_AGENT']);
```
```python
client.set_forwarded_user_agent(request.headers.get('user-agent'))
```
{% /multicode %}

# OAuth2 {% #oauth2 %}
Expand Down Expand Up @@ -383,6 +483,29 @@ $redirectUrl = $account->createOAuth2Token(

header('Location' . $redirectUrl);
```
```python
from appwrite.client import Client
from appwrite.services.account import Account, OAuthProvider
from flask import Flask, request ,redirect, make_response, jsonify

admin_client = (Client()
.set_endpoint('https://<REGION>.cloud.appwrite.io/v1')
.set_project('<PROJECT_ID>')
.set_key('<API_KEY>')
)

@app.get('/oauth')
def oauth():
account = Account(admin_client)

redirect_url = account.create_o_auth2_token(
OAuthProvider.Github, # Provider
'https://example.com/oauth/success', # Success URL
'https://example.com/oauth/failure', # Failure URL
)

return redirect(redirect_url)
```
{% /multicode %}

Next, create a success callback endpoint that receives the `userId` and `secret` URL parameters, and then calls `createSession` on the server side. This endpoint returns a session object, which you can store in a cookie.
Expand Down Expand Up @@ -448,6 +571,38 @@ try {
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
```
```python
@app.get('/oauth/success')
def oauth_success():
account = Account(admin_client)

# Get the userId and secret from the URL parameters
user_id = request.args.get('userId')
secret = request.args.get('secret')

try:
# Create the session using the Appwrite client
session = account.create_session(user_id, secret)

# Set the session cookie
res = make_response(jsonify({'success': True}))

# Set session cookie
res.set_cookie(
'session',
session['secret'],
httponly=True,
secure=True,
samesite='Strict',
max_age=session['expire'],
path='/'
)

return res

except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 400
```
{% /multicode %}

Now the cookie is set, it will be passed to the server with subsequent requests, and you can use it to make authenticated requests to the Appwrite API on behalf of the end-user.
Expand Down