~qeef/damn-server

ref: 4506336eac532c83cf2bd3328fc9207b8bcdb924 damn-server/damn_server/api.py -rw-r--r-- 9.5 KiB
4506336eJiri Vlasak Update area priority documentation 1 year, 2 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
"""Web app serving JSON API.

`API documentation`_ is generated automatically.

.. _API documentation: https://server.damn-project.org/docs

"""
import fastapi
import json
import jwt
import os
import pydantic
import rauth
import xml.etree.ElementTree as ET

from asyncpg.exceptions import SerializationError
from datetime import datetime
from dateutil import parser as dt_parser
from fastapi import Security
from fastapi.security import HTTPAuthorizationCredentials
from fastapi.security import HTTPBearer
from pydantic import conint
from pydantic import constr
from pydantic import validate_arguments
from starlette.middleware.cors import CORSMiddleware
from starlette.middleware.sessions import SessionMiddleware
from starlette.responses import RedirectResponse
from starlette.responses import Response
from typing import Tuple
from typing import Union

from damn_server import conf
from damn_server import db
from damn_server import area
from damn_server.area import Area
from damn_server.area import CreateArea
from damn_server.area import UpdateArea
from damn_server import list_of
from damn_server.list_of import AreaGeometry
from damn_server.list_of import Commit
from damn_server.list_of import Square
from damn_server.list_of import ThinArea
from damn_server import new
from damn_server.new import CreateCommit
from damn_server import square
from damn_server import user
from damn_server.user import User

class Token(pydantic.BaseModel):
    """Structure containing JWT token."""
    token: str

    class Config:
        extra = "forbid"
        fields = {"token": {"description": "JWT token."}}

class Good(pydantic.BaseModel):
    """Structure containing `detail` `string` ``Good.``"""
    detail: str = "Good."
    class Config:
        extra = "forbid"
        fields = {"detail": {"description": "Detail of the good message."}}

app = fastapi.FastAPI(
    title="Damn server API",
    version="0.2.1",
)
app.add_middleware(SessionMiddleware, secret_key=conf.SESSION_SECRET)
app.add_middleware(
    CORSMiddleware,
    allow_origins=conf.DAMN_CLIENTS,
    allow_methods=["GET", "POST", "PUT"],
    allow_headers=["Authorization", "Content-Type"],
)
osm = rauth.OAuth1Service(
    consumer_key=conf.OAUTH_CONSUMER_KEY,
    consumer_secret=conf.OAUTH_CONSUMER_SECRET,
    name="OSM",
    access_token_url=conf.OAUTH_ACCESS_TOKEN_URL,
    authorize_url=conf.OAUTH_AUTHORIZE_URL,
    request_token_url=conf.OAUTH_REQUEST_TOKEN_URL,
    base_url=conf.OAUTH_BASE_URL,
)

@validate_arguments
def dn(b: HTTPAuthorizationCredentials) -> constr(min_length=3):
    """Return display name from the authorization bearer `b`."""
    try:
        t = jwt.decode(b.credentials, conf.JWT_SECRET, algorithms=["HS256"])
        return t["display_name"]
    except:
        raise fastapi.HTTPException(status_code=401, detail="bad JWT")

@app.on_event("startup")
async def startup():
    await db.init_pool()

@app.on_event("shutdown")
async def shutdown():
    await db.pool.close()
    db.pool = None

@app.get("/auth/{token_identifier}", status_code=307)
async def redirect_to_openstreetmap_for_authorization(
    token_identifier: constr(min_length=8),
):
    """Authorization starts here. Specify your temporary `token_identifier`.

    Authorization steps are the following:

    - Create your temporary `token_identifier`. Initiate the authorization
      process by the ``GET`` request to ``/auth/{token_identifier}`` endpoint.
    - You are redirected to OpenStreetMap OAuth1 server. Fill the username and
      password in the OpenStreetMap login form.
    - When OK, you are redirected to ``/authed/{token_identifier}`` endpoint,
      ``user/details`` from OpenStreetMap are retrieved, and the JSON Web Token
      (JWT) is created based on ``user/details``. You get ``Good.`` message.
    - Now the JWT is ready and you can retrieve it by ``GET`` request to
      ``/token/{token_identifier}`` endpoint.
    """
    request_token, request_token_secret = osm.get_request_token(
        params={'oauth_callback': "{}/{}".format(
            conf.OAUTH_CALLBACK_URL,
            token_identifier,
        )}
    )
    t = {
        "request_token": request_token,
        "request_token_secret": request_token_secret,
    }
    with open("{}/damn_{}".format(
        conf.TMP_AUTH_STORE_DIR,
        token_identifier,
    ), "w") as f:
        json.dump(t, f)
    authorize_url = osm.get_authorize_url(request_token)
    return RedirectResponse(url=authorize_url)

@app.get("/authed/{token_identifier}", response_model=Good)
async def authorized_by_openstreetmap_so_create_and_store_token(
    token_identifier: constr(min_length=8),
    oauth_token: str,
    oauth_verifier: str,
):
    """OpenStreetMap authorization process redirects to this endpoint."""
    try:
        with open("{}/damn_{}".format(
            conf.TMP_AUTH_STORE_DIR,
            token_identifier,
        ), "r") as f:
            t = json.load(f)
        os.remove("{}/damn_{}".format(
            conf.TMP_AUTH_STORE_DIR,
            token_identifier,
        ))
        assert oauth_token == t["request_token"]
        osm_s = osm.get_auth_session(
            t["request_token"],
            t["request_token_secret"],
            data={'oauth_verifier': oauth_verifier},
        )
        osm_r = osm_s.get("user/details")
    except:
        raise fastapi.HTTPException(status_code=401, detail="OSM auth failed")
    root = ET.fromstring(osm_r.content)
    xml_user = root.find("user")
    u = User(display_name=xml_user.get("display_name"))
    try:
        xml_img = xml_user.find("img")
        u.avatar = xml_img.get("href")
    except:
        pass
    try:
        xml_languages = xml_user.find("languages")
        xml_lang = xml_languages.find("lang")
        u.lang = xml_lang.text
    except:
        pass
    try:
        db_user = await user.load(u.display_name)
        u.tags = db_user.tags
        u.newbie = db_user.newbie
    except:
        await user.save(u)
    await user.update(u)
    t = Token(token=jwt.encode(
        json.loads(u.json()), # this is because datetime isn't serializable
        conf.JWT_SECRET,
        algorithm="HS256",
    ))
    with open("{}/damn_{}".format(
        conf.TMP_AUTH_STORE_DIR,
        token_identifier,
    ), "w") as f:
        json.dump(t.dict(), f)
    return Good()

@app.get("/token/{token_identifier}", response_model=Token)
async def retrieve_stored_token(token_identifier: constr(min_length=8)):
    """Retrieve the JWT paired to your temporary `token_identifier`."""
    try:
        with open("{}/damn_{}".format(
            conf.TMP_AUTH_STORE_DIR,
            token_identifier,
        ), "r") as f:
            t = json.load(f)
        assert "token" in t
        os.remove("{}/damn_{}".format(
            conf.TMP_AUTH_STORE_DIR,
            token_identifier,
        ))
        return Token(**t)
    except:
        raise fastapi.HTTPException(
            status_code=401,
            detail="token not yet ready",
        )

@app.get("/areas", response_model=Tuple[ThinArea, ...])
async def list_of_thin_areas(
    since: datetime=None,
    including_archived: bool=False,
):
    return await list_of.thin_areas(since, including_archived)

@app.post("/areas", response_model=Area, status_code=201)
async def create_area(
    ca: CreateArea,
    b: HTTPAuthorizationCredentials=Security(HTTPBearer()),
):
    aid = await area.save(ca, dn(b))
    return await area.load(aid)

@app.get("/geometries", response_model=Tuple[AreaGeometry, ...])
async def list_of_geometries(
    including_archived: bool=False,
):
    return await list_of.geometries(including_archived)

@app.get("/area/{aid}", response_model=Area)
async def load_area(aid: conint(ge=1000, le=9999)):
    return await area.load(aid)

@app.put("/area/{aid}", response_model=Area)
async def update_area(
    aid: conint(ge=1000, le=9999),
    ua: UpdateArea,
    b: HTTPAuthorizationCredentials=Security(HTTPBearer()),
):
    assert aid == ua.aid
    await area.update(ua, dn(b))
    return await area.load(aid)

@app.get("/area/{aid}/commits", response_model=Tuple[Commit, ...])
async def list_of_area_commits(
    aid: conint(ge=1000, le=9999),
    since: datetime=None,
    todo: bool=False
):
    return await list_of.area_commits(aid, since, todo)

@app.get("/area/{aid}/squares", response_model=Tuple[Square, ...])
async def list_of_area_squares(
    aid: conint(ge=1000, le=9999),
):
    return await list_of.area_squares(aid)

@app.post(
    "/area/{aid}/commits",
    status_code=201,
    response_model=Union[Square, dict],
)
async def create_new_commit_to_the_area(
    aid: conint(ge=1000, le=9999),
    c: CreateCommit,
    b: HTTPAuthorizationCredentials=Security(HTTPBearer()),
):
    return await new.commit(c, aid, dn(b))

@app.get("/area/{aid}/square/{sid}/gpx")
async def square_gpx(aid: conint(ge=1000, le=9999), sid: conint(ge=1)):
    return Response(
        content=await square.gpx_border(aid, sid),
        media_type="text/xml",
    )

@app.put("/user/{display_name}", response_model=Token)
async def update_user(
    display_name: constr(min_length=3),
    u: User,
    b: HTTPAuthorizationCredentials=Security(HTTPBearer()),
):
    assert display_name == dn(b)
    assert display_name == u.display_name
    await user.update(u)
    return Token(token=jwt.encode(
        json.loads(u.json()), # this is because datetime isn't serializable
        conf.JWT_SECRET,
        algorithm="HS256",
    ))

@app.get("/user/{display_name}/commits", response_model=Tuple[Commit, ...])
async def list_of_user_commits(
    display_name: constr(min_length=3),
    since: datetime=None,
    that_are_distinct: bool=False
):
    return await list_of.user_commits(display_name, since, that_are_distinct)