Debian Codegraph @

examples/oauth2_backend.py

raw
1 # This script shows how to authenticate with OAuth2 with a backend application
2 # The token is saved to disk in $HOME/.osmapi/token.json
3 # It can be reused until it's revoked or expired.
4
5 # install oauthlib for requests: pip install oauthlib requests-oauthlib
6 from requests_oauthlib import OAuth2Session
7 import json
8 import webbrowser
9 import osmapi
10 from dotenv import load_dotenv, find_dotenv
11 import os
12 import sys
13
14 load_dotenv(find_dotenv())
15
16 # Credentials you get from registering a new application
17 # register here: https://master.apis.dev.openstreetmap.org/oauth2/applications
18 # or on production: https://www.openstreetmap.org/oauth2/applications
19 client_id = os.getenv("OSM_OAUTH_CLIENT_ID")
20 client_secret = os.getenv("OSM_OAUTH_CLIENT_SECRET")
21
22 if client_id is None:
23 raise
24 if client_secret is None:
25 raise
26
27 # special value for redirect_uri for non-web applications
28 redirect_uri = "urn:ietf:wg:oauth:2.0:oob"
29
30 authorization_base_url = "https://master.apis.dev.openstreetmap.org/oauth2/authorize"
31 token_url = "https://master.apis.dev.openstreetmap.org/oauth2/token"
32 scope = ["write_api", "write_notes"]
33
34
35 def get_osmapi_path():
36 base_dir = ""
37
38 if os.getenv("HOME"):
39 base_dir = os.getenv("HOME")
40 elif os.getenv("HOMEDRIVE") and os.getenv("HOMEPATH"):
41 base_dir = os.path.join(os.getenv("HOMEDRIVE"), os.getenv("HOMEPATH"))
42 elif os.getenv("USERPROFILE"):
43 base_dir = os.getenv("USERPROFILE")
44
45 if not base_dir:
46 print(
47 "Unable to find home directory (check env vars HOME, HOMEDRIVE, HOMEPATH and USERPROFILE)", # noqa
48 file=sys.stderr,
49 )
50 raise Exception("Home directory not found")
51
52 return os.path.join(base_dir, ".osmapi")
53
54
55 def token_saver(token):
56 osmapi_path = get_osmapi_path()
57 token_path = os.path.join(osmapi_path, "token.json")
58
59 with open(token_path, "w") as f:
60 print(f"Saving token {token} to {token_path}")
61 f.write(json.dumps(token))
62
63
64 def token_loader():
65 osmapi_path = get_osmapi_path()
66 token_path = os.path.join(osmapi_path, "token.json")
67
68 with open(token_path, "r") as f:
69 token = json.loads(f.read())
70 print(f"Loaded token {token} from {token_path}")
71 return token
72
73
74 def save_and_get_access_token(client_id, client_secret, redirect_uri, scope):
75 oauth = OAuth2Session(
76 client_id=client_id,
77 redirect_uri=redirect_uri,
78 scope=scope,
79 )
80
81 login_url, _ = oauth.authorization_url(authorization_base_url)
82
83 print(f"Authorize user using this URL: {login_url}")
84 webbrowser.open(login_url)
85
86 authorization_code = input("Paste the authorization code here: ")
87
88 token = oauth.fetch_token(
89 token_url=token_url,
90 client_secret=client_secret,
91 code=authorization_code,
92 )
93
94 token_saver(token)
95 return token
96
97
98 def make_osm_change(oauth_session):
99 api = osmapi.OsmApi(
100 api="https://api06.dev.openstreetmap.org", session=oauth_session
101 )
102 with api.changeset({"comment": "My first test"}) as changeset_id:
103 print(f"Part of Changeset {changeset_id}")
104 node1 = api.node_create({"lon": 1, "lat": 1, "tag": {}})
105 print(node1)
106
107
108 # load a previously saved token
109 try:
110 token = token_loader()
111 except FileNotFoundError:
112 print("Token not found, get a new one...")
113 token = save_and_get_access_token(client_id, client_secret, redirect_uri, scope)
114
115 # test the token
116 try:
117 oauth_session = OAuth2Session(client_id, token=token)
118 make_osm_change(oauth_session)
119 except osmapi.errors.UnauthorizedApiError:
120 print("Token expired, let's create a new one")
121 token = save_and_get_access_token(client_id, client_secret, redirect_uri, scope)
122 oauth_session = OAuth2Session(client_id, token=token)
123 make_osm_change(oauth_session)