Skip to content

Commit 2d2e0d9

Browse files
authored
Merge pull request #2107 from appwrite/dat-546
Added ssr and auth working with python
2 parents 76983e6 + 4ba777c commit 2d2e0d9

File tree

1 file changed

+155
-0
lines changed

1 file changed

+155
-0
lines changed

src/routes/docs/products/auth/server-side-rendering/+page.markdoc

Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,17 @@ $adminClient = (new Client())
7272
->setKey('<YOUR_API_KEY>'); // Your secret API key
7373

7474

75+
```
76+
```python
77+
from appwrite.client import Client
78+
79+
admin_client = (Client()
80+
.set_endpoint('https://<REGION>.cloud.appwrite.io/v1') # Your API Endpoint \
81+
.set_project('<PROJECT_ID>') # Your project ID
82+
.set_key('<YOUR_API_KEY>') # Your secret API key
83+
)
84+
85+
7586
```
7687
{% /multicode %}
7788

@@ -105,6 +116,22 @@ if ($session) {
105116
$sessionClient->setSession($session);
106117
}
107118
```
119+
120+
```python
121+
from flask import request
122+
from appwrite.client import Client
123+
124+
session_client = (Client()
125+
.set_endpoint('https://<REGION>.cloud.appwrite.io/v1') # Your API Endpoint
126+
.set_project('<PROJECT_ID>') # Your project ID
127+
)
128+
129+
# Get the session cookie from the request
130+
session = request.cookies.get('session')
131+
if session:
132+
session_client.set_session(session)
133+
134+
```
108135
{% /multicode %}
109136

110137
# Creating email/password sessions {% #creating-sessions %}
@@ -178,6 +205,39 @@ try {
178205
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
179206
}
180207
```
208+
```python
209+
from flask import Flask, request, jsonify, make_response
210+
211+
# Initialize admin client here
212+
# ...
213+
214+
@app.post('/login')
215+
def login():
216+
body = request.json
217+
# Get email and password from request
218+
email = body['email']
219+
password = body['password']
220+
221+
try:
222+
account = Account(admin_client)
223+
224+
# Create the session using the Appwrite client
225+
session = account.create_email_password_session(email, password)
226+
resp = make_response(jsonify({'success': True}))
227+
228+
# Set the session cookie
229+
resp.set_cookie('session',
230+
session['secret'],
231+
httponly=True,
232+
secure=True,
233+
samesite='Strict',
234+
expires=session['expire'],
235+
path='/'
236+
)
237+
return resp
238+
except Exception as e:
239+
return jsonify({'success': False, 'error': str(e)}), 400
240+
```
181241
{% /multicode %}
182242

183243
We also recommend using the `httpOnly`, `secure`, and `sameSite` cookie options to ensure that the cookie is only sent over HTTPS,
@@ -242,6 +302,30 @@ try {
242302
} catch (Exception $e) {
243303
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
244304
}
305+
```
306+
```python
307+
# Initialize the session client here
308+
309+
@app.get('/user')
310+
def get_user():
311+
# First, read the session cookie from the request
312+
session = request.cookies.get('session')
313+
314+
# If the session cookie is not present, return an error
315+
if not session:
316+
return jsonify({'success': False, 'error': 'Unauthorized'}), 401
317+
318+
# pass the session cookie to the Appwrite client
319+
session_client.set_session(session)
320+
account = Account(session_client)
321+
322+
# Now, you can make authenticated requests to the Appwrite API
323+
try:
324+
user = account.get()
325+
return jsonify({'success': True, 'user': user})
326+
except Exception as e:
327+
return jsonify({'success': False, 'error': str(e)}), 400
328+
245329
```
246330
{% /multicode %}
247331

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

320404
$result = $account->createAnonymousSession();
321405
```
406+
```python
407+
from appwrite.client import Client
408+
from appwrite.services.account import Account
409+
410+
client = (Client()
411+
.set_endpoint('https://<REGION>.cloud.appwrite.io/v1') # Your API Endpoint
412+
.set_project('<PROJECT_ID>') # Your project ID
413+
)
414+
415+
account = Account(client)
416+
417+
result = account.create_anonymous_session()
418+
```
322419
{% /multicode %}
323420

324421
# Forwarding user agent {% #forwarding-user-agent %}
@@ -333,6 +430,9 @@ client.setForwardedUserAgent(req.headers['user-agent']);
333430
<?php
334431
$client->setForwardedUserAgent($_SERVER['HTTP_USER_AGENT']);
335432
```
433+
```python
434+
client.set_forwarded_user_agent(request.headers.get('user-agent'))
435+
```
336436
{% /multicode %}
337437

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

384484
header('Location' . $redirectUrl);
385485
```
486+
```python
487+
from appwrite.client import Client
488+
from appwrite.services.account import Account, OAuthProvider
489+
from flask import Flask, request ,redirect, make_response, jsonify
490+
491+
admin_client = (Client()
492+
.set_endpoint('https://<REGION>.cloud.appwrite.io/v1')
493+
.set_project('<PROJECT_ID>')
494+
.set_key('<API_KEY>')
495+
)
496+
497+
@app.get('/oauth')
498+
def oauth():
499+
account = Account(admin_client)
500+
501+
redirect_url = account.create_o_auth2_token(
502+
OAuthProvider.Github, # Provider
503+
'https://example.com/oauth/success', # Success URL
504+
'https://example.com/oauth/failure', # Failure URL
505+
)
506+
507+
return redirect(redirect_url)
508+
```
386509
{% /multicode %}
387510

388511
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.
@@ -448,6 +571,38 @@ try {
448571
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
449572
}
450573
```
574+
```python
575+
@app.get('/oauth/success')
576+
def oauth_success():
577+
account = Account(admin_client)
578+
579+
# Get the userId and secret from the URL parameters
580+
user_id = request.args.get('userId')
581+
secret = request.args.get('secret')
582+
583+
try:
584+
# Create the session using the Appwrite client
585+
session = account.create_session(user_id, secret)
586+
587+
# Set the session cookie
588+
res = make_response(jsonify({'success': True}))
589+
590+
# Set session cookie
591+
res.set_cookie(
592+
'session',
593+
session['secret'],
594+
httponly=True,
595+
secure=True,
596+
samesite='Strict',
597+
max_age=session['expire'],
598+
path='/'
599+
)
600+
601+
return res
602+
603+
except Exception as e:
604+
return jsonify({'success': False, 'error': str(e)}), 400
605+
```
451606
{% /multicode %}
452607

453608
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.

0 commit comments

Comments
 (0)