-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.py
250 lines (205 loc) · 7.29 KB
/
example.py
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
from dataclasses import dataclass
from typing import Any, Dict, List, Optional
from example.models.configuration_model import OpenIDProvider, TenantConfig
from example.models.public_model import (
Configuration as PublicConfiguration,
)
from example.models.public_model import (
Customer,
)
from example.models.user_model import User
from zara.application.application import ASGIApplication, Request, Router
from zara.application.authentication import auth_required
from zara.application.events import Event
from zara.application.validation import (
Required,
ValidatorBase,
check_required_fields,
validate,
)
from zara.asgi.server import ASGIServer
from zara.errors import ForbiddenError, NotFoundError, UnauthenticatedError
from zara.utilities.jwt_encode_decode import (
create_password,
get_token_from_local_system,
get_token_from_openid_provider,
)
SECRET_KEY = "your_application_secret"
ALGORITHM = "HS256"
CLIENT_ID = "local"
CLIENT_SECRET = "I3EUXRwR1W1fSz2ZYy7XZOnmKSn7uruK" # If necessary
REDIRECT_URI = "http://localhost:8000/callback"
app = ASGIApplication()
router = Router()
@dataclass
class RegisterValidator(ValidatorBase):
name: Required[str] = None
receive_marketing: bool = False
email: Optional[str] = None
async def validate(self) -> List[Dict[str, Any]]:
errors = []
required_missing = check_required_fields(self)
for field in required_missing:
errors.append(
{
"field": field,
"message": f"validationErrors.{field}Missing",
}
)
if self.receive_marketing and not self.email:
errors.append(
{
"field": "email",
"message": "validationErrors.emailRequiredForMarketing",
}
)
if self.email is not None:
if "@" not in self.email or "." not in self.email:
errors.append(
{
"field": "email",
"message": "validationErrors.emailInvalid",
}
)
return errors
app.add_router(router)
@router.post("/customer/new/{customer:str}")
async def customer_new(request: Request, customer: str):
customer = await Customer(name=customer, logger=request.logger).create()
return customer
@router.get("/")
async def hello_world(request: Request):
return b"Hello, World!"
@router.post("/user/create/{username:str}")
async def hello_world_create(request: Request, username: str):
user = await User(
name="John Smith",
age=25,
password_hash="password",
).create()
tenant_entry = await TenantConfig.first_or_create()
public_entry = await PublicConfiguration.first_or_create()
password = create_password(
"password",
f"{public_entry.token_secret}{tenant_entry.token_secret}{user.token_secret}".encode(
"utf-8"
),
)
user.password_hash = password[0]
await user.save()
return user
@router.get("/user/{id:str}")
async def get_user(request: Request, id: str):
user = await User.get(id=id)
return user
@router.post("/validate")
@validate(RegisterValidator)
async def validate(request: Request):
return b"Valid!"
# Second router
router_two = Router(name="two", prefix="/two")
app.add_router(router_two)
@router.post("/create-openid-provider")
async def create_openid_provider(request: Request):
data = await request.json()
user = await User.get(username=data.get("username"))
if not user:
return {"error": "User not found"}, 404
if user.is_system:
return {"error": "User is system"}, 403
openid_provider = OpenIDProvider(
client_id=data.get("client_id"),
client_secret=data.get("client_secret"),
redirect_uri=data.get("redirect_uri"),
scope=data.get("scope"),
issuer=data.get("issuer"),
is_active=True,
)
await openid_provider.create()
return openid_provider
@router.post("/update-user")
async def update_user(request: Request):
data = await request.json()
user = await User.get(username=data.get("username"))
if not user:
raise NotFoundError("User not found")
if user.is_system:
raise ForbiddenError("User is system")
user.set(
openid_username=data.get("openid_username"),
openid_provider=data.get("openid_provider"),
)
await user.save()
return user
@router.post("/login")
async def login(request: Request):
data = await request.json()
username = data.get("username")
password = data.get("password")
if not username or not password:
return {"error": "Username and password are required"}, 400
user = await User.get(username=username)
if not user:
return {"error": "User not found"}, 404
config = None
if not user.is_system and user.openid_provider is not None:
openid_provider = await OpenIDProvider.get(id=user.openid_provider)
config = {
"client_id": openid_provider.client_id,
"client_secret": openid_provider.client_secret,
"redirect_uri": openid_provider.redirect_uri,
"token_url": openid_provider.issuer.replace("localhost", "keycloak"),
}
try:
token_response = await get_token_from_openid_provider(
user.openid_username or username,
password,
request.logger,
endpoint_config=config,
)
if "error" in token_response:
return {"error": token_response["error_description"]}, 401
request.set_cookie("refreshToken", token_response["refresh_token"])
return {
"access_token": token_response["access_token"],
"token_type": "Bearer",
}
except Exception as e:
if "401" in str(e):
raise UnauthenticatedError()
else:
raise e
else:
tenant_config = await TenantConfig.first()
public_config = await PublicConfiguration.first()
token_response = await get_token_from_local_system(
password,
user,
tenant_secret=tenant_config.token_secret,
public_secret=public_config.token_secret,
)
if "access_token" not in token_response:
raise UnauthenticatedError()
await user.sessions.create(
token=token_response["access_token"],
expires_at=token_response["expires_in"],
refresh_token=token_response["refresh_token"],
ip_address=request.headers.get(b"X-Real-IP"),
user_agent=request.headers.get(b"User-Agent"),
)
return token_response
@router_two.get("/greet")
async def greet(request: Request):
return b"Greetings!"
@router.post("/permit")
@auth_required(roles=["manage-account"])
async def permit(request: Request):
return b"Permitted!"
async def after_request(event: Event):
event.logger.debug(f"AfterRequest fired: {event.data}")
app.add_listener("AfterRequest", after_request)
async def on_scheduled_event(event: Event):
event.logger.debug(f"OnScheduledEvent fired: {event.data}")
app.add_listener("OnScheduledEvent", on_scheduled_event)
server = ASGIServer(app)
server.run()