Skip to content
Back

Python SDK: implementing login / auth

  • 0
  • Auth
lost_RD
27 May, 2025, 01:46

I'm working my way through a basic CRUD app. So far it's been a great experience. I implemented a registration route and a login route. I registered and logged in. I continued to code and test and life was good.

Later on I logged out and now I can't log in again. I'm now left wondering how I ever managed to authenticate in the first place.

https://github.com/lost-RD/HTMXxAppwrite-Todo/ register(): https://github.com/lost-RD/HTMXxAppwrite-Todo/blob/main/main.py#L190 login(): https://github.com/lost-RD/HTMXxAppwrite-Todo/blob/main/main.py#L219 logout(): https://github.com/lost-RD/HTMXxAppwrite-Todo/blob/main/main.py#L242

I'm pretty sure the code here is in the state it was when I logged in that one time, but I could be wrong (since it doesn't work now).

Account doesn't seem to be a scope for an API token, which suggests it's a client-side role and all auth happens on the client side. So how did I ever log in in the first place? Is there something about the registration code there that enables a login to work without client-side auth?

This is the result of trying to use the /logout route:

TypeScript
web-1  | requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://fra.cloud.appwrite.io/v1/account/sessions/current
...
web-1  | appwrite.exception.AppwriteException: app.*******@service.fra.cloud.appwrite.io (role: applications) missing scope (account)
TL;DR
Developers are implementing login and authentication using a Python SDK. They are facing issues with logging out and have concerns about session storage and permissions. The solution involves following the server-side rendering docs and ensuring the correct permissions and scopes are set. The developers are also confused about how authentication was working initially. Checking the provided GitHub links for registration, login, and logout functions might provide insight into the issue.
Steven
27 May, 2025, 02:16
lost_RD
27 May, 2025, 03:56

Thanks. I've had a read.

Now I'll initialise a new client per request, and have a distinction between an admin client and a user client.

I have an API key with every permission allowed, and it gets passed to any new admin client.

Account is not an admin scope (https://appwrite.io/docs/references/cloud/server-python/account), so I'll try a user client.

I have made a guest session button, which works. I now have a guest session. However, logout of the guest session doesn't work.

TypeScript
web-1  |   File "/app/main.py", line 266, in logout
web-1  |     account.delete_session('current')
web-1  | appwrite.exception.AppwriteException: User (role: guests) missing scope (account)  
lost_RD
27 May, 2025, 04:18
TypeScript
@app.route('/logout')
def logout():
    """Handle user logout."""
    logger.debug(f"Session: {session}")
    if 'user_id' in session:
        # Delete the current session
        client = get_client().set_session(session['user_id'])
        account = Account(client)
        
        account.delete_session('current')
        session.clear()  # Clear all session data
    
    return redirect(url_for('login'))

Probably doing something wrong here?

Here's a thread facing the same issue that doesn't have any responses: https://appwrite.io/threads/1294295794274533467

Steven
27 May, 2025, 04:23

what's the code for get_client?

lost_RD
27 May, 2025, 04:25
TypeScript
from appwrite.client import Client
from appwrite.services.databases import Databases
from appwrite.services.account import Account
from appwrite.id import ID
from appwrite.exception import AppwriteException

def get_client():
    client = Client()
    client.set_endpoint(os.getenv('APPWRITE_ENDPOINT'))
    client.set_project(os.getenv('APPWRITE_PROJECT_ID'))
    return client

def get_admin_client():
    client = get_client()
    client.set_key(os.getenv('APPWRITE_API_KEY'))
    return client
Steven
27 May, 2025, 04:25

what's being stored in session['user_id']?

lost_RD
27 May, 2025, 04:25

web-1 | 2025-05-27 03:54:59,110 - __main__ - DEBUG - Session: <SecureCookieSession {'user_id': '6831aa8e0036dae0f8c2', 'user_name': 'Guest'}>

Steven
27 May, 2025, 04:26

no. you need to store the session secret as described by the docs

lost_RD
27 May, 2025, 04:38

Alright, I make a guest session. This is the result, no secret:

web-1 | 2025-05-27 04:31:25,498 - __main__ - DEBUG - Session data: {'$id': '6835401d3fa9c7591ed4', '$createdAt': '2025-05-27T04:31:25.271+00:00', '$updatedAt': '2025-05-27T04:31:25.271+00:00', 'userId': '6835401d33ec673ea6af', 'expire': '2026-05-27T04:31:25.260+00:00', 'provider': 'anonymous', 'providerUid': '', 'providerAccessToken': '', 'providerAccessTokenExpiry': '', 'providerRefreshToken': '', 'ip': 'xxx.yyy.zzz.aaa', 'osCode': 'LIN', 'osName': 'GNU/Linux', 'osVersion': '', 'clientType': '', 'clientCode': '', 'clientName': '', 'clientVersion': '', 'clientEngine': '', 'clientEngineVersion': '', 'deviceName': 'desktop', 'deviceBrand': '', 'deviceModel': '', 'countryCode': 'au', 'countryName': 'Australia', 'current': True, 'factors': ['anonymous'], 'secret': '', 'mfaUpdatedAt': ''}

There's a session ID and a user ID

Steven
27 May, 2025, 04:39

as mentioend in the docs, you need to use an admin sdk (that has an api key with the approriate scopes)

lost_RD
27 May, 2025, 05:01

Alrighty, auth is working. Thank you for your help Steven. Once I've tested everything thoroughly, do you want simple demos of combining various technologies to be submitted to BuiltWith? Or is that for more serious projects?

Steven
27 May, 2025, 15:51

more serious projects than demos

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more