CLI Authentication

If you’re building a command line application that runs in a terminal, you can use Stack Auth to let your users log in to their accounts.

To do so, we provide a Python template that you can use as a starting point. Download it here and copy it into your project, for example:

1└─ my-python-app
2 ├─ main.py
3 └─ stack_auth_cli_template.py # <- the file you just downloaded

Then, you can import the prompt_cli_login function:

1from stack_auth_cli_template import prompt_cli_login
2
3# prompt the user to log in
4refresh_token = prompt_cli_login(
5 app_url="https://your-app-url.example.com",
6 project_id="your-project-id-here",
7 publishable_client_key="your-publishable-client-key-here",
8)
9
10if refresh_token is None:
11 print("User cancelled the login process. Exiting")
12 exit(1)
13
14# you can also store the refresh token in a file, and only prompt the user to log in if the file doesn't exist
15
16# you can now use the REST API with the refresh token
17def stack_auth_request(method, endpoint, **kwargs):
18 # ... see Stack Auth's Getting Started section to see how this function should look like
19 # https://docs.stack-auth.com/python/getting-started/setup
20
21def get_access_token(refresh_token):
22 access_token_response = stack_auth_request(
23 'post',
24 '/api/v1/auth/sessions/current/refresh',
25 headers={
26 'x-stack-refresh-token': refresh_token,
27 }
28 )
29
30 return access_token_response['access_token']
31
32def get_user_object(access_token):
33 return stack_auth_request(
34 'get',
35 '/api/v1/users/me',
36 headers={
37 'x-stack-access-token': access_token,
38 }
39 )
40
41user = get_user_object(get_access_token(refresh_token))
42print("The user is logged in as", user['display_name'] or user['primary_email'])