]> git.ipfire.org Git - ipfire.org.git/blob - src/web/people.py
fe167763e7eba8a3bb95a6eaf4c7a4edbfc544fe
[ipfire.org.git] / src / web / people.py
1 #!/usr/bin/python
2
3 import datetime
4 import ldap
5 import logging
6 import imghdr
7 import tornado.web
8 import urllib.parse
9
10 from .. import countries
11
12 from . import auth
13 from . import base
14 from . import ui_modules
15
16 class IndexHandler(auth.CacheMixin, base.BaseHandler):
17 @tornado.web.authenticated
18 def get(self):
19 hints = []
20
21 # Suggest uploading an avatar if this user does not have one
22 if not self.current_user.has_avatar():
23 hints.append("avatar")
24
25 self.render("people/index.html", hints=hints)
26
27
28 class AvatarHandler(base.BaseHandler):
29 def get(self, uid):
30 # Get the desired size of the avatar file
31 size = self.get_argument("size", None)
32
33 try:
34 size = int(size)
35 except (TypeError, ValueError):
36 size = None
37
38 logging.debug("Querying for avatar of %s" % uid)
39
40 # Fetch user account
41 account = self.backend.accounts.get_by_uid(uid)
42 if not account:
43 raise tornado.web.HTTPError(404, "Could not find account %s" % uid)
44
45 # Allow downstream to cache this for 60 minutes
46 self.set_expires(3600)
47
48 # Resize avatar
49 avatar = account.get_avatar(size)
50
51 # If there is no avatar, we serve a default image
52 if not avatar:
53 logging.debug("No avatar uploaded for %s" % account)
54
55 return self.redirect(self.static_url("img/default-avatar.jpg"))
56
57 # Guess content type
58 type = imghdr.what(None, avatar)
59
60 # Set headers about content
61 self.set_header("Content-Disposition", "inline; filename=\"%s.%s\"" % (account.uid, type))
62 self.set_header("Content-Type", "image/%s" % type)
63
64 # Deliver payload
65 self.finish(avatar)
66
67
68 class CallsHandler(auth.CacheMixin, base.BaseHandler):
69 @tornado.web.authenticated
70 def get(self, uid, date=None):
71 account = self.backend.accounts.get_by_uid(uid)
72 if not account:
73 raise tornado.web.HTTPError(404, "Could not find account %s" % uid)
74
75 # Check for permissions
76 if not account.can_be_managed_by(self.current_user):
77 raise tornado.web.HTTPError(403, "%s cannot manage %s" % (self.current_user, account))
78
79 if date:
80 try:
81 date = datetime.datetime.strptime(date, "%Y-%m-%d").date()
82 except ValueError:
83 raise tornado.web.HTTPError(400, "Invalid date: %s" % date)
84 else:
85 date = datetime.date.today()
86
87 self.render("people/calls.html", account=account, date=date)
88
89
90 class CallHandler(auth.CacheMixin, base.BaseHandler):
91 @tornado.web.authenticated
92 def get(self, uid, uuid):
93 account = self.backend.accounts.get_by_uid(uid)
94 if not account:
95 raise tornado.web.HTTPError(404, "Could not find account %s" % uid)
96
97 # Check for permissions
98 if not account.can_be_managed_by(self.current_user):
99 raise tornado.web.HTTPError(403, "%s cannot manage %s" % (self.current_user, account))
100
101 call = self.backend.talk.freeswitch.get_call_by_uuid(uuid)
102 if not call:
103 raise tornado.web.HTTPError(404, "Could not find call %s" % uuid)
104
105 # XXX limit
106
107 self.render("people/call.html", account=account, call=call)
108
109
110 class ConferencesHandler(auth.CacheMixin, base.BaseHandler):
111 @tornado.web.authenticated
112 def get(self):
113 self.render("people/conferences.html", conferences=self.backend.talk.conferences)
114
115
116 class GroupsHandler(auth.CacheMixin, base.BaseHandler):
117 @tornado.web.authenticated
118 def get(self):
119 # Only staff can see other groups
120 if not self.current_user.is_staff():
121 raise tornado.web.HTTPError(403)
122
123 self.render("people/groups.html")
124
125
126 class GroupHandler(auth.CacheMixin, base.BaseHandler):
127 @tornado.web.authenticated
128 def get(self, gid):
129 # Only staff can see other groups
130 if not self.current_user.is_staff():
131 raise tornado.web.HTTPError(403)
132
133 # Fetch group
134 group = self.backend.groups.get_by_gid(gid)
135 if not group:
136 raise tornado.web.HTTPError(404, "Could not find group %s" % gid)
137
138 self.render("people/group.html", group=group)
139
140
141 class SearchHandler(auth.CacheMixin, base.BaseHandler):
142 @tornado.web.authenticated
143 def get(self):
144 q = self.get_argument("q")
145
146 # Perform the search
147 accounts = self.backend.accounts.search(q)
148
149 # Redirect when only one result was found
150 if len(accounts) == 1:
151 self.redirect("/users/%s" % accounts[0].uid)
152 return
153
154 self.render("people/search.html", q=q, accounts=accounts)
155
156
157 class SIPHandler(auth.CacheMixin, base.BaseHandler):
158 @tornado.web.authenticated
159 def get(self, uid):
160 account = self.backend.accounts.get_by_uid(uid)
161 if not account:
162 raise tornado.web.HTTPError(404, "Could not find account %s" % uid)
163
164 # Check for permissions
165 if not account.can_be_managed_by(self.current_user):
166 raise tornado.web.HTTPError(403, "%s cannot manage %s" % (self.current_user, account))
167
168 self.render("people/sip.html", account=account)
169
170
171 class UsersHandler(auth.CacheMixin, base.BaseHandler):
172 @tornado.web.authenticated
173 def get(self):
174 # Only staff can see other users
175 if not self.current_user.is_staff():
176 raise tornado.web.HTTPError(403)
177
178 self.render("people/users.html")
179
180
181 class UserHandler(auth.CacheMixin, base.BaseHandler):
182 @tornado.web.authenticated
183 def get(self, uid):
184 account = self.backend.accounts.get_by_uid(uid)
185 if not account:
186 raise tornado.web.HTTPError(404, "Could not find account %s" % uid)
187
188 self.render("people/user.html", account=account)
189
190
191 class UserEditHandler(auth.CacheMixin, base.BaseHandler):
192 @tornado.web.authenticated
193 def get(self, uid):
194 account = self.backend.accounts.get_by_uid(uid)
195 if not account:
196 raise tornado.web.HTTPError(404, "Could not find account %s" % uid)
197
198 # Check for permissions
199 if not account.can_be_managed_by(self.current_user):
200 raise tornado.web.HTTPError(403, "%s cannot manage %s" % (self.current_user, account))
201
202 self.render("people/user-edit.html", account=account, countries=countries.get_all())
203
204 @tornado.web.authenticated
205 def post(self, uid):
206 account = self.backend.accounts.get_by_uid(uid)
207 if not account:
208 raise tornado.web.HTTPError(404, "Could not find account %s" % uid)
209
210 # Check for permissions
211 if not account.can_be_managed_by(self.current_user):
212 raise tornado.web.HTTPError(403, "%s cannot manage %s" % (self.current_user, account))
213
214 # Unfortunately this cannot be wrapped into a transaction
215 try:
216 account.first_name = self.get_argument("first_name")
217 account.last_name = self.get_argument("last_name")
218 account.nickname = self.get_argument("nickname", None)
219 account.street = self.get_argument("street", None)
220 account.city = self.get_argument("city", None)
221 account.postal_code = self.get_argument("postal_code", None)
222 account.country_code = self.get_argument("country_code", None)
223
224 # Avatar
225 try:
226 filename, data, mimetype = self.get_file("avatar")
227
228 if not mimetype.startswith("image/"):
229 raise tornado.web.HTTPError(400, "Avatar is not an image file: %s" % mimetype)
230
231 account.upload_avatar(data)
232 except TypeError:
233 pass
234
235 # Email
236 account.mail_routing_address = self.get_argument("mail_routing_address", None)
237
238 # Telephone
239 account.phone_numbers = self.get_argument("phone_numbers", "").splitlines()
240 account.sip_routing_address = self.get_argument("sip_routing_address", None)
241 except ldap.STRONG_AUTH_REQUIRED as e:
242 raise tornado.web.HTTPError(403, "%s" % e) from e
243
244 # Redirect back to user page
245 self.redirect("/users/%s" % account.uid)
246
247
248 class UserPasswdHandler(auth.CacheMixin, base.BaseHandler):
249 @tornado.web.authenticated
250 def get(self, uid):
251 account = self.backend.accounts.get_by_uid(uid)
252 if not account:
253 raise tornado.web.HTTPError(404, "Could not find account %s" % uid)
254
255 # Check for permissions
256 if not account.can_be_managed_by(self.current_user):
257 raise tornado.web.HTTPError(403, "%s cannot manage %s" % (self.current_user, account))
258
259 self.render("people/passwd.html", account=account)
260
261 @tornado.web.authenticated
262 def post(self, uid):
263 account = self.backend.accounts.get_by_uid(uid)
264 if not account:
265 raise tornado.web.HTTPError(404, "Could not find account %s" % uid)
266
267 # Check for permissions
268 if not account.can_be_managed_by(self.current_user):
269 raise tornado.web.HTTPError(403, "%s cannot manage %s" % (self.current_user, account))
270
271 # Get current password
272 password = self.get_argument("password")
273
274 # Get new password
275 password1 = self.get_argument("password1")
276 password2 = self.get_argument("password2")
277
278 # Passwords must match
279 if not password1 == password2:
280 raise tornado.web.HTTPError(400, "Passwords do not match")
281
282 # XXX Check password complexity
283
284 # Check if old password matches
285 if not account.check_password(password):
286 raise tornado.web.HTTPError(403, "Incorrect password for %s" % account)
287
288 # Save new password
289 account.passwd(password1)
290
291 # Redirect back to user's page
292 self.redirect("/users/%s" % account.uid)
293
294
295 class SSODiscourse(auth.CacheMixin, base.BaseHandler):
296 def _get_discourse_params(self):
297 # Fetch Discourse's parameters
298 sso = self.get_argument("sso")
299 sig = self.get_argument("sig")
300
301 # Decode payload
302 try:
303 return self.accounts.decode_discourse_payload(sso, sig)
304
305 # Raise bad request if the signature is invalid
306 except ValueError:
307 raise tornado.web.HTTPError(400)
308
309 def _redirect_user_to_discourse(self, account, nonce, return_sso_url):
310 """
311 Redirects the user back to Discourse passing some
312 attributes of the user account to Discourse
313 """
314 args = {
315 "nonce" : nonce,
316 "external_id" : account.uid,
317
318 # Pass email address
319 "email" : account.email,
320 "require_activation" : "false",
321
322 # More details about the user
323 "username" : account.uid,
324 "name" : "%s" % account,
325
326 # Avatar
327 "avatar_url" : account.avatar_url(),
328 "avatar_force_update" : "true",
329
330 # Send a welcome message
331 "suppress_welcome_message" : "false",
332
333 # Group memberships
334 "admin" : "true" if account.is_admin() else "false",
335 "moderator" : "true" if account.is_moderator() else "false",
336 }
337
338 # Format payload and sign it
339 payload = self.accounts.encode_discourse_payload(**args)
340 signature = self.accounts.sign_discourse_payload(payload)
341
342 qs = urllib.parse.urlencode({
343 "sso" : payload,
344 "sig" : signature,
345 })
346
347 # Redirect user
348 self.redirect("%s?%s" % (return_sso_url, qs))
349
350 @base.ratelimit(minutes=24*60, requests=100)
351 def get(self):
352 params = self._get_discourse_params()
353
354 # Redirect back if user is already logged in
355 if self.current_user:
356 return self._redirect_user_to_discourse(self.current_user, **params)
357
358 # Otherwise the user needs to authenticate
359 self.render("auth/login.html", next=None)
360
361 @base.ratelimit(minutes=24*60, requests=100)
362 def post(self):
363 params = self._get_discourse_params()
364
365 # Get credentials
366 username = self.get_argument("username")
367 password = self.get_argument("password")
368
369 # Check credentials
370 account = self.accounts.auth(username, password)
371 if not account:
372 raise tornado.web.HTTPError(401, "Unknown user or invalid password: %s" % username)
373
374 # If the user has been authenticated, we will redirect to Discourse
375 self._redirect_user_to_discourse(account, **params)
376
377
378 class NewAccountsModule(ui_modules.UIModule):
379 def render(self, days=14):
380 t = datetime.datetime.utcnow() - datetime.timedelta(days=days)
381
382 # Fetch all accounts created after t
383 accounts = self.backend.accounts.get_created_after(t)
384
385 accounts.sort(key=lambda a: a.created_at, reverse=True)
386
387 return self.render_string("people/modules/accounts-new.html",
388 accounts=accounts, t=t)
389
390
391 class AccountsListModule(ui_modules.UIModule):
392 def render(self, accounts=None):
393 if accounts is None:
394 accounts = self.backend.accounts
395
396 return self.render_string("people/modules/accounts-list.html", accounts=accounts)
397
398
399 class CDRModule(ui_modules.UIModule):
400 def render(self, account, date=None, limit=None):
401 cdr = account.get_cdr(date=date, limit=limit)
402
403 return self.render_string("people/modules/cdr.html",
404 account=account, cdr=list(cdr))
405
406
407 class ChannelsModule(ui_modules.UIModule):
408 def render(self, account):
409 return self.render_string("people/modules/channels.html",
410 account=account, channels=account.sip_channels)
411
412
413 class MOSModule(ui_modules.UIModule):
414 def render(self, call):
415 return self.render_string("people/modules/mos.html", call=call)
416
417
418 class PasswordModule(ui_modules.UIModule):
419 def render(self, account=None):
420 return self.render_string("people/modules/password.html", account=account)
421
422 def javascript_files(self):
423 return "js/zxcvbn.js"
424
425 def embedded_javascript(self):
426 return self.render_string("people/modules/password.js")
427
428
429 class RegistrationsModule(ui_modules.UIModule):
430 def render(self, account):
431 return self.render_string("people/modules/registrations.html", account=account)
432
433
434 class SIPStatusModule(ui_modules.UIModule):
435 def render(self, account):
436 return self.render_string("people/modules/sip-status.html", account=account)