mirror of
https://git.linux-kernel.at/oliver/ivatar.git
synced 2025-11-11 18:56:23 +00:00
Compare commits
516 Commits
apikeys
...
64967c07ad
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
64967c07ad | ||
|
|
c2cbe14b0d | ||
|
|
550b9bf0b9 | ||
|
|
86a0ef6f03 | ||
|
|
18c02a70c2 | ||
|
|
3bac6f01e7 | ||
|
|
5c1b63d400 | ||
|
|
a1e8619b56 | ||
|
|
9385f5e86c | ||
|
|
ec6bff005d | ||
|
|
59f0b2864b | ||
|
|
2b799ba83b | ||
|
|
4b44a7890d | ||
|
|
8417a124cf | ||
|
|
dcbbbe4868 | ||
|
|
43b063474b | ||
|
|
d04c09f039 | ||
|
|
bfd2529a46 | ||
|
|
3c95fbb8e9 | ||
|
|
0ee2f807c0 | ||
|
|
aecc8e8477 | ||
|
|
a07db42ae4 | ||
|
|
a7b04dc2f4 | ||
|
|
cd1eefc467 | ||
|
|
a43dc4c309 | ||
|
|
19d5208b2e | ||
|
|
96b567daf6 | ||
|
|
4283554b12 | ||
|
|
0d8d7b2875 | ||
|
|
d7a0f74c2e | ||
|
|
4774de60cd | ||
|
|
9ec9c60bad | ||
|
|
a9ddb040d3 | ||
|
|
b44ee42398 | ||
|
|
2d1fc16268 | ||
|
|
ed4b6dc41a | ||
|
|
497468e58e | ||
|
|
96a62fe006 | ||
|
|
9cf1cb4745 | ||
|
|
27dd40b4aa | ||
|
|
8fbdf35c02 | ||
|
|
43b8b2abef | ||
|
|
173ddaae8f | ||
|
|
03fa0fb911 | ||
|
|
80df736433 | ||
|
|
7350afd988 | ||
|
|
13f580023b | ||
|
|
5556f7bd9a | ||
|
|
81582bcf45 | ||
|
|
ac58c9f626 | ||
|
|
202ae44346 | ||
|
|
63dd743dca | ||
|
|
d9c3c512f4 | ||
|
|
b4f224cd4d | ||
|
|
671ebbdae2 | ||
|
|
e87d2bcda7 | ||
|
|
f0c604a523 | ||
|
|
dead9cbd78 | ||
|
|
13165579e8 | ||
|
|
84c209f453 | ||
|
|
4103fcff55 | ||
|
|
5119328346 | ||
|
|
f8f8beb52e | ||
|
|
8e556bb14d | ||
|
|
97c9b36258 | ||
|
|
eca9db8d16 | ||
|
|
7b34bdef87 | ||
|
|
c7efcb7246 | ||
|
|
fd10f66dab | ||
|
|
b9fbf37308 | ||
|
|
6f39be3b6d | ||
|
|
4c5c4ab8fa | ||
|
|
4aeacf9fab | ||
|
|
d228674d4b | ||
|
|
c3c4a23619 | ||
|
|
45387a1a43 | ||
|
|
8b2675591e | ||
|
|
54426c84bc | ||
|
|
a10a73c56e | ||
|
|
f699a66236 | ||
|
|
ac9c8fcbc3 | ||
|
|
ad4e5068b9 | ||
|
|
684cdca4e4 | ||
|
|
6db3450b20 | ||
|
|
8e61f02702 | ||
|
|
c17b078913 | ||
|
|
ba4c587e5c | ||
|
|
8a1ccb1e0f | ||
|
|
e79398bc33 | ||
|
|
25e9e489c3 | ||
|
|
d3ffef3407 | ||
|
|
e8951014f9 | ||
|
|
a6751d79d4 | ||
|
|
1411420c65 | ||
|
|
2966a85083 | ||
|
|
780dc18fa4 | ||
|
|
dcdbc6b608 | ||
|
|
2eb38445d7 | ||
|
|
4d86a11728 | ||
|
|
b4e10e3ec5 | ||
|
|
69044a12e6 | ||
|
|
c926869e6d | ||
|
|
b95bf287bf | ||
|
|
e6596b925a | ||
|
|
9767ebf110 | ||
|
|
530dbdbb6c | ||
|
|
a3a2220d15 | ||
|
|
32c854a545 | ||
|
|
1601e86ad8 | ||
|
|
a2affffdd1 | ||
|
|
f0182c7d51 | ||
|
|
ff0543a0bb | ||
|
|
eeeb8a4f3a | ||
|
|
6f205ccad9 | ||
|
|
b5186f2081 | ||
|
|
37e24df9dc | ||
|
|
19facb4bec | ||
|
|
a19fd6ffa2 | ||
|
|
a98ab6bb4a | ||
|
|
919f2ddf73 | ||
|
|
b747854ae5 | ||
|
|
847fda66f8 | ||
|
|
cde3ce10bd | ||
|
|
a9021fc0f7 | ||
|
|
5ff79cf7ae | ||
|
|
a0877ad4eb | ||
|
|
c3450630b0 | ||
|
|
7258d911c8 | ||
|
|
2c5e7ab90f | ||
|
|
cfa3d11b35 | ||
|
|
8b04c170ec | ||
|
|
844aca54a0 | ||
|
|
5c665b6d07 | ||
|
|
a1cd41529d | ||
|
|
5a9c357376 | ||
|
|
4046008069 | ||
|
|
f2ea379938 | ||
|
|
b4598212e5 | ||
|
|
2cde85e137 | ||
|
|
23c36604b8 | ||
|
|
53b16dae5f | ||
|
|
ed1e37b7ed | ||
|
|
81a5306638 | ||
|
|
1edb9f7ef9 | ||
|
|
d37ae1456c | ||
|
|
368aa5bf27 | ||
|
|
00ebda9b2b | ||
|
|
3ab9835d53 | ||
|
|
27ea0ecb6b | ||
|
|
a43719e760 | ||
|
|
e900751a9e | ||
|
|
fbcda13c5a | ||
|
|
f15d9af595 | ||
|
|
254eb93049 | ||
|
|
1ebb804147 | ||
|
|
15062b3cda | ||
|
|
99697adba0 | ||
|
|
9caee65b8e | ||
|
|
928ffaea76 | ||
|
|
2fbdd74619 | ||
|
|
44a738d724 | ||
|
|
10255296d5 | ||
|
|
213e0cb213 | ||
|
|
4a684f9947 | ||
|
|
9d647fe075 | ||
|
|
a58e812fb6 | ||
|
|
a641572e4b | ||
|
|
30f94610bd | ||
|
|
55b7466eb5 | ||
|
|
8a70ea1131 | ||
|
|
9d3d5fe5a1 | ||
|
|
b69f08694a | ||
|
|
ed27493abc | ||
|
|
94b21c15d2 | ||
|
|
f7d72c18fb | ||
|
|
7a1e38ab50 | ||
|
|
9d390a5b19 | ||
|
|
52576bbf18 | ||
|
|
d720fcfa50 | ||
|
|
02b199333a | ||
|
|
c6e1583e7e | ||
|
|
5114b4d5d0 | ||
|
|
f81d6bb84c | ||
|
|
16dd861953 | ||
|
|
4316c2bcc6 | ||
|
|
b711594c1f | ||
|
|
0d16b1f518 | ||
|
|
4abbfeaa36 | ||
|
|
13f13f7443 | ||
|
|
f5c8cda222 | ||
|
|
59c8db6aec | ||
|
|
ebfcd67512 | ||
|
|
0df2af4f4b | ||
|
|
797ec91320 | ||
|
|
85c06cd42c | ||
|
|
aa742ea181 | ||
|
|
deeaab7e23 | ||
|
|
0832ac9fe0 | ||
|
|
b3f580e51b | ||
|
|
12bc7e5af4 | ||
|
|
e44a84e9ae | ||
|
|
a1d13ba3ce | ||
|
|
aa3e1e48dc | ||
|
|
919ed4d485 | ||
|
|
cb7328fe23 | ||
|
|
1892e9585e | ||
|
|
7d0d2f931b | ||
|
|
5dcd69f332 | ||
|
|
1560a5d1de | ||
|
|
1f17526fac | ||
|
|
c36d0fb808 | ||
|
|
771a386bf4 | ||
|
|
c109b70901 | ||
|
|
b8996e7b00 | ||
|
|
184f3eb7f7 | ||
|
|
27e3751776 | ||
|
|
e3b0782082 | ||
|
|
5a0aa4838c | ||
|
|
bbacd413ca | ||
|
|
99b4fdcbcd | ||
|
|
c948f515e0 | ||
|
|
8dd29e872d | ||
|
|
4f5f498da8 | ||
|
|
6c4d928a1f | ||
|
|
498ab7aa69 | ||
|
|
e90604a8d3 | ||
|
|
4a892b0c4c | ||
|
|
04a39f7693 | ||
|
|
715725f7c9 | ||
|
|
b86e211adc | ||
|
|
6b24a7732b | ||
|
|
488206f15b | ||
|
|
b12b5df17a | ||
|
|
60ee28270a | ||
|
|
fe1113df06 | ||
|
|
ad79c414da | ||
|
|
3aaaac51f0 | ||
|
|
56780cba69 | ||
|
|
dcbd2c5df5 | ||
|
|
0a0a96ab6e | ||
|
|
22f9dac816 | ||
|
|
433bf4d3e2 | ||
|
|
6e0bc487cd | ||
|
|
6cd5b64553 | ||
|
|
154e965fe3 | ||
|
|
072783bfd5 | ||
|
|
259d370d9a | ||
|
|
e1705cef36 | ||
|
|
94b0fc2068 | ||
|
|
ffab741445 | ||
|
|
7559ddad6e | ||
|
|
dc30267ff4 | ||
|
|
3fad7497a1 | ||
|
|
4a615c933b | ||
|
|
6c25f6ea12 | ||
|
|
cea4d5eb24 | ||
|
|
e878224ba6 | ||
|
|
483dcf8cf7 | ||
|
|
07c7f42f01 | ||
|
|
b0d09e3ad4 | ||
|
|
a2972ac61f | ||
|
|
1fa5dddce5 | ||
|
|
2cb868b129 | ||
|
|
0e295401df | ||
|
|
ecc87033cc | ||
|
|
2df0cdf892 | ||
|
|
cf5c058bfb | ||
|
|
c2145e144f | ||
|
|
549289a36a | ||
|
|
8b0fc31f6a | ||
|
|
4eedb3e628 | ||
|
|
049271acdd | ||
|
|
1a859af31f | ||
|
|
2fe8af6fab | ||
|
|
3a61d519ba | ||
|
|
8dff034f9e | ||
|
|
b58c35e98b | ||
|
|
4f239119d6 | ||
|
|
b7efc60cc0 | ||
|
|
9faf308264 | ||
|
|
b3cfccb9c0 | ||
|
|
5a1dfbc459 | ||
|
|
df0400375d | ||
|
|
50569afc25 | ||
|
|
4385fcc034 | ||
|
|
927083eb58 | ||
|
|
fa4ce5e079 | ||
|
|
a2eea54235 | ||
|
|
01bcc1ee11 | ||
|
|
16f809d8a6 | ||
|
|
f01e49d495 | ||
|
|
fd696ed74c | ||
|
|
021a8de4d8 | ||
|
|
cbdaed28da | ||
|
|
95410f6e43 | ||
|
|
2be7309625 | ||
|
|
6deea2758f | ||
|
|
2bb1f5f26d | ||
|
|
3878554dd9 | ||
|
|
9478177c83 | ||
|
|
47837f4516 | ||
|
|
2276ea962f | ||
|
|
ae3c6beed4 | ||
|
|
ff9af3de9b | ||
|
|
7e46df0c15 | ||
|
|
e1547d14c5 | ||
|
|
8f5bc9653b | ||
|
|
5dbbff49d0 | ||
|
|
5c8da703cb | ||
|
|
3aeb1ba454 | ||
|
|
9e189b3fd2 | ||
|
|
b8292b5404 | ||
|
|
5730c2dabf | ||
|
|
dddd24e57f | ||
|
|
a6c5899f44 | ||
|
|
ba6f46c6eb | ||
|
|
ddfc1e7824 | ||
|
|
2761e801df | ||
|
|
555a8b0523 | ||
|
|
6d984a486a | ||
|
|
9dceb7a696 | ||
|
|
64575a9b99 | ||
|
|
a94954d58c | ||
|
|
d2e4162b6b | ||
|
|
4afee63137 | ||
|
|
d486fdef2c | ||
|
|
e945ae2b4d | ||
|
|
9565ccc54e | ||
|
|
e68c75d74d | ||
|
|
f359532c30 | ||
|
|
93e8b3f07f | ||
|
|
66bf945770 | ||
|
|
a76d5b9225 | ||
|
|
1aa40fecab | ||
|
|
f4fe49b3b4 | ||
|
|
e1923f92c2 | ||
|
|
49780739f8 | ||
|
|
71d69dde53 | ||
|
|
f4af809e6d | ||
|
|
9221da5805 | ||
|
|
b71ac2d7e3 | ||
|
|
4ac3ca5dc2 | ||
|
|
bc6b7313ec | ||
|
|
0b5271424c | ||
|
|
899e8db661 | ||
|
|
cf65ea2c6a | ||
|
|
ce18bb58bd | ||
|
|
27e11f8051 | ||
|
|
2a8fe01027 | ||
|
|
99ff61cf34 | ||
|
|
8fa4a9c88b | ||
|
|
2695f932ee | ||
|
|
58957c7fc2 | ||
|
|
2578e804b6 | ||
|
|
515a4a3b0b | ||
|
|
a492995836 | ||
|
|
67ac0ad973 | ||
|
|
ad39324650 | ||
|
|
125c797c36 | ||
|
|
ef02feed3b | ||
|
|
714ae58509 | ||
|
|
f651a5a6d8 | ||
|
|
1a10861d2f | ||
|
|
fe22748821 | ||
|
|
42825ef7ae | ||
|
|
462b318fcb | ||
|
|
c0a2a6ef67 | ||
|
|
01c1bd3a8d | ||
|
|
b64f939344 | ||
|
|
ddaf6a6d8a | ||
|
|
b49bf9d918 | ||
|
|
c6016b4984 | ||
|
|
fe5f91bd66 | ||
|
|
7f10c239f9 | ||
|
|
fd218abe0f | ||
|
|
70a2771f34 | ||
|
|
00aa1a45cb | ||
|
|
16c2245c99 | ||
|
|
fb65fd76d9 | ||
|
|
4d85fed519 | ||
|
|
23985a13a8 | ||
|
|
40a5b06e25 | ||
|
|
978da813e6 | ||
|
|
a9cff27ef7 | ||
|
|
6c8763752c | ||
|
|
e50615fcdb | ||
|
|
99b2379ea5 | ||
|
|
f10b13862c | ||
|
|
fa4f5da45d | ||
|
|
337ced827a | ||
|
|
502bc2cc03 | ||
|
|
d0f65d435a | ||
|
|
c54c57231b | ||
|
|
34291e5f87 | ||
|
|
a085e8b22f | ||
|
|
cbe0af27c0 | ||
|
|
c93d0eb86c | ||
|
|
6e084ea080 | ||
|
|
e115e2c3ab | ||
|
|
0c3686beef | ||
|
|
05d0e05545 | ||
|
|
0ccd3fa7c1 | ||
|
|
8989a83deb | ||
|
|
a1c1da81e1 | ||
|
|
521f6db235 | ||
|
|
b93569a279 | ||
|
|
ab56bf720a | ||
|
|
56f90412bf | ||
|
|
e260e6ff2f | ||
|
|
ff9bfdefb5 | ||
|
|
09a8c60ad0 | ||
|
|
547b570f5d | ||
|
|
ee13fb545a | ||
|
|
e2a24296c4 | ||
|
|
de6ba7b1c4 | ||
|
|
71a24737b4 | ||
|
|
e260c7410b | ||
|
|
030ea6fd33 | ||
|
|
c3422ccc78 | ||
|
|
6aa870963d | ||
|
|
355af2351d | ||
|
|
7ab63887a7 | ||
|
|
26768aacb2 | ||
|
|
a3f7575726 | ||
|
|
44f3c2bcba | ||
|
|
b7d3c7655a | ||
|
|
f37fc4de09 | ||
|
|
7b01e2eef2 | ||
|
|
f8a5fc55e0 | ||
|
|
8ba3a55756 | ||
|
|
d663bceead | ||
|
|
7c7de1e711 | ||
|
|
f288a97bad | ||
|
|
3d3aa4f48e | ||
|
|
328914698c | ||
|
|
5cec4cbdb1 | ||
|
|
9fdbf81f71 | ||
|
|
1f04bf0f18 | ||
|
|
205ba0c934 | ||
|
|
7ca34aea1b | ||
|
|
32ed22704c | ||
|
|
38d2f0dd92 | ||
|
|
52e5673834 | ||
|
|
12d69576af | ||
|
|
7ef4fecb4f | ||
|
|
539e0b6ce0 | ||
|
|
d7b5b0de27 | ||
|
|
7cfd283c85 | ||
|
|
41ee907292 | ||
|
|
b2f06256db | ||
|
|
a3489188c3 | ||
|
|
0c2f039ff4 | ||
|
|
48d1b7d47d | ||
|
|
ce01f8dec1 | ||
|
|
d2701deb0f | ||
|
|
9defe7617a | ||
|
|
dcb3627179 | ||
|
|
fbb099d4f6 | ||
|
|
d9f4a4f634 | ||
|
|
e9f1bfc7f4 | ||
|
|
7a53a18222 | ||
|
|
aa26ac802c | ||
|
|
552da91044 | ||
|
|
73fca0b953 | ||
|
|
ca9f83984a | ||
|
|
0f60e20d99 | ||
|
|
5733448830 | ||
|
|
b52244b167 | ||
|
|
a346bc6285 | ||
|
|
b3280376f2 | ||
|
|
c5f493178c | ||
|
|
64dc146fae | ||
|
|
334da91881 | ||
|
|
5c66a0a3c1 | ||
|
|
7d9f2ead9a | ||
|
|
519dbe9a6b | ||
|
|
ab0ea07d7b | ||
|
|
8450f42a20 | ||
|
|
7adaa7c48b | ||
|
|
9a40beda13 | ||
|
|
f924a8e9c0 | ||
|
|
57f4cc46aa | ||
|
|
413e714000 | ||
|
|
ba4c1a8432 | ||
|
|
635951ff4d | ||
|
|
33169da930 | ||
|
|
92035d7e15 | ||
|
|
b4b81499ca | ||
|
|
8f7f6983cd | ||
|
|
ffbd0f9148 | ||
|
|
64edc0aa61 | ||
|
|
3bee6ed05f | ||
|
|
652f11289b | ||
|
|
03e495de24 | ||
|
|
8fb601ece1 | ||
|
|
c83453077e | ||
|
|
49219f1eec | ||
|
|
625cd290c0 | ||
|
|
e74365e788 | ||
|
|
02eaad4a5b | ||
|
|
31bc906fda | ||
|
|
feab5f6156 | ||
|
|
0262ad850f | ||
|
|
f13927f859 | ||
|
|
30991b4b57 | ||
|
|
91d1193e23 | ||
|
|
c5eeda5748 | ||
|
|
2535cefa6c | ||
|
|
ea900c0109 | ||
|
|
a58b193b8c | ||
|
|
060a664d26 | ||
|
|
6bc0390b48 | ||
|
|
b74ab99ef7 | ||
|
|
b463f9f95a | ||
|
|
476bddb21c | ||
|
|
07ba1c5a05 |
1
.buildpacks
Normal file
1
.buildpacks
Normal file
@@ -0,0 +1 @@
|
||||
https://github.com/heroku/heroku-buildpack-python
|
||||
@@ -5,6 +5,15 @@ omit =
|
||||
node_modules/*
|
||||
.virtualenv/*
|
||||
import_libravatar.py
|
||||
requirements.txt
|
||||
static/admin/*
|
||||
**/static/humans.txt
|
||||
**/static/img/robots.txt
|
||||
ivatar/ivataraccount/read_libravatar_export.py
|
||||
templates/maintenance.html
|
||||
encryption_test.py
|
||||
libravatarproxy.py
|
||||
|
||||
|
||||
[html]
|
||||
extra_css = coverage_extra_style.css
|
||||
|
||||
246
.cursorrules
Normal file
246
.cursorrules
Normal file
@@ -0,0 +1,246 @@
|
||||
# ivatar/libravatar Project Rules
|
||||
|
||||
## Project Overview
|
||||
ivatar is a Django-based federated avatar service that serves as an alternative to Gravatar. It provides avatar images for email addresses and OpenID URLs, with support for the Libravatar federation protocol.
|
||||
|
||||
## Core Functionality
|
||||
- Avatar service for email addresses and OpenID URLs
|
||||
- Federated compatibility with Libravatar protocol
|
||||
- Multiple authentication methods (OpenID, OpenID Connect/Fedora, Django auth)
|
||||
- Image upload, cropping, and management
|
||||
- External avatar import (Gravatar, other Libravatar instances)
|
||||
- Bluesky handle integration
|
||||
- Multiple theme support (default, clime, green, red)
|
||||
- Internationalization (15+ languages)
|
||||
|
||||
## Technical Stack
|
||||
- **Framework**: Django 4.2+ with Python 3.x
|
||||
- **Database**: SQLite (development), MySQL/MariaDB, PostgreSQL (production)
|
||||
- **Image Processing**: PIL/Pillow for image manipulation
|
||||
- **Authentication**: django-openid-auth, social-auth-app-django
|
||||
- **Caching**: Memcached and filesystem caching
|
||||
- **Email**: Mailgun integration via django-anymail
|
||||
- **Testing**: pytest with custom markers
|
||||
|
||||
## Key Models
|
||||
- `Photo`: Stores uploaded avatar images with format detection and access counting
|
||||
- `ConfirmedEmail`: Verified email addresses with assigned photos and Bluesky handles
|
||||
- `ConfirmedOpenId`: Verified OpenID URLs with assigned photos and Bluesky handles
|
||||
- `UserPreference`: User theme preferences
|
||||
- `UnconfirmedEmail`: Email verification workflow
|
||||
- `UnconfirmedOpenId`: OpenID verification workflow
|
||||
|
||||
## Security Features
|
||||
- File upload validation and sanitization
|
||||
- EXIF data removal (ENABLE_EXIF_SANITIZATION)
|
||||
- Malicious content scanning (ENABLE_MALICIOUS_CONTENT_SCAN)
|
||||
- Comprehensive security logging
|
||||
- File size limits and format validation
|
||||
- Trusted URL validation for external avatar sources
|
||||
|
||||
## Development Workflow Rules
|
||||
|
||||
### Tool Usage Guidelines
|
||||
- **Prefer MCP tools over command-line alternatives** - When MCP (Model Context Protocol) tools are available for a task, use them instead of command-line tools
|
||||
- **Examples**: Use `mcp_lkernat-gitlab_*` functions instead of `glab` commands, prefer MCP web search over terminal `curl` calls
|
||||
- **Benefits**: MCP tools provide more reliable, direct interfaces and better error handling
|
||||
- **Fallback**: Only use command-line tools when no MCP alternative exists
|
||||
|
||||
### External Resources & Libraries
|
||||
- **Web search is always allowed** - use web search to find solutions, check documentation, verify best practices
|
||||
- **Use latest library versions** - always prefer the latest stable versions of external libraries
|
||||
- **Security first** - outdated libraries are security risks, always update to latest versions
|
||||
- **Dependency management** - when adding new dependencies, ensure they're actively maintained and secure
|
||||
|
||||
### Testing
|
||||
- **MANDATORY: Run pre-commit hooks and tests before any changes** - this is an obligation
|
||||
- Use `./run_tests_local.sh` for local development (skips Bluesky tests requiring API credentials)
|
||||
- Run `python3 manage.py test -v3` for full test suite including Bluesky tests
|
||||
- **MANDATORY: When adding new code, always write tests to increase code coverage** - never decrease coverage
|
||||
- Use pytest markers appropriately:
|
||||
- `@pytest.mark.bluesky`: Tests requiring Bluesky API credentials
|
||||
- `@pytest.mark.slow`: Long-running tests
|
||||
- `@pytest.mark.integration`: Integration tests
|
||||
- `@pytest.mark.unit`: Unit tests
|
||||
|
||||
### Code Quality
|
||||
- Always check for linter errors after making changes using `read_lints`
|
||||
- Follow existing code style and patterns
|
||||
- Maintain comprehensive logging (use `logger = logging.getLogger("ivatar")`)
|
||||
- Consider security implications of any changes
|
||||
- Follow Django best practices and conventions
|
||||
- **Reduce script creation** - avoid creating unnecessary scripts, prefer existing tools and commands
|
||||
- **Use latest libraries** - always use the latest versions of external libraries to ensure security and bug fixes
|
||||
|
||||
### Database Operations
|
||||
- Use migrations for schema changes: `./manage.py migrate`
|
||||
- Support multiple database backends (SQLite, MySQL, PostgreSQL)
|
||||
- Use proper indexing for performance (see existing model indexes)
|
||||
|
||||
### Image Processing
|
||||
- Support multiple formats: JPEG, PNG, GIF, WEBP
|
||||
- Maximum image size: 512x512 pixels (AVATAR_MAX_SIZE)
|
||||
- Maximum file size: 10MB (MAX_PHOTO_SIZE)
|
||||
- JPEG quality: 85 (JPEG_QUALITY)
|
||||
- Always validate image format and dimensions
|
||||
|
||||
## Configuration Management
|
||||
- Main settings in `ivatar/settings.py` and `config.py`
|
||||
- Local overrides in `config_local.py` (not in version control)
|
||||
- Environment variables for sensitive data (database credentials, API keys)
|
||||
- Support for multiple deployment environments (development, staging, production)
|
||||
|
||||
## Authentication & Authorization
|
||||
- Multiple backends: Django auth, OpenID, Fedora OIDC
|
||||
- Social auth pipeline with custom steps for email confirmation
|
||||
- User account creation and management
|
||||
- Email verification workflow
|
||||
|
||||
## Caching Strategy
|
||||
- Memcached for general caching
|
||||
- Filesystem cache for generated images
|
||||
- 5-minute cache for resized images (CACHE_IMAGES_MAX_AGE)
|
||||
- Cache invalidation on photo updates
|
||||
|
||||
## Internationalization
|
||||
- Support for 15+ languages
|
||||
- Use Django's translation framework
|
||||
- Template strings should be translatable
|
||||
- Locale-specific formatting
|
||||
|
||||
## File Structure Guidelines
|
||||
- Main Django app: `ivatar/`
|
||||
- Account management: `ivatar/ivataraccount/`
|
||||
- Tools: `ivatar/tools/`
|
||||
- Static files: `ivatar/static/` and `static/`
|
||||
- Templates: `templates/` and app-specific template directories
|
||||
- Tests: Co-located with modules or in dedicated test files
|
||||
|
||||
## Security Considerations
|
||||
- Always validate file uploads
|
||||
- Sanitize EXIF data from images
|
||||
- Use secure password hashing (Argon2 preferred, PBKDF2 fallback)
|
||||
- Implement proper CSRF protection
|
||||
- Use secure cookies in production
|
||||
- Log security events to dedicated security log
|
||||
|
||||
## Performance Considerations
|
||||
- Use database indexes for frequently queried fields
|
||||
- Implement proper caching strategies
|
||||
- Optimize image processing operations
|
||||
- Monitor access counts for analytics
|
||||
- Use efficient database queries
|
||||
|
||||
## Production Deployment & Infrastructure
|
||||
|
||||
### Hosting & Sponsorship
|
||||
- **Hosted by Fedora Project** - Free infrastructure provided due to heavy usage by Fedora community
|
||||
- **Scale**: Handles millions of requests daily for 30k+ users with 33k+ avatar images
|
||||
- **Performance**: High-performance system optimized for dynamic content (CDN difficult due to dynamic sizing)
|
||||
|
||||
### Production Architecture
|
||||
- **Redis**: Session storage (potential future caching expansion)
|
||||
- **Monitoring Stack**:
|
||||
- Prometheus + Alertmanager for metrics and alerting
|
||||
- Loki for log aggregation
|
||||
- Alloy for observability
|
||||
- Grafana for visualization
|
||||
- Custom exporters for application metrics
|
||||
- **Apache HTTPD**:
|
||||
- SSL termination
|
||||
- Load balancer for Gunicorn containers
|
||||
- Caching (memory/socache and disk cache - optimization ongoing)
|
||||
- **PostgreSQL**: Main production database
|
||||
- **Gunicorn**: 2 containers running Django application
|
||||
- **Containerization**: **Podman** (not Docker) - always prefer podman when possible
|
||||
|
||||
### Development Environment
|
||||
- **Dev Instance**: dev.libravatar.org (auto-deployed from 'devel' branch via Puppet)
|
||||
- **Limitation**: Aging CentOS 7 host with older Python 3.x and Django versions
|
||||
- **Compatibility**: Must maintain backward compatibility with older versions
|
||||
|
||||
### CI/CD & Version Control
|
||||
- **GitLab**: Self-hosted OSS/Community Edition on git.linux-kernel.at
|
||||
- **CI**: GitLab CI extensively used
|
||||
- **CD**: GitLab CD on roadmap (part of libravatar-ansible project)
|
||||
- **Deployment**: Separate libravatar-ansible project handles production deployments
|
||||
- **Container Management**: Ansible playbooks rebuild custom images and restart containers as needed
|
||||
|
||||
### Deployment Considerations
|
||||
- Production requires proper database setup (PostgreSQL, not SQLite)
|
||||
- Static file collection required: `./manage.py collectstatic`
|
||||
- Environment-specific configuration via environment variables
|
||||
- Custom container images with automated rebuilds
|
||||
- High availability and performance optimization critical
|
||||
|
||||
## Common Commands
|
||||
```bash
|
||||
# Development server
|
||||
./manage.py runserver 0:8080
|
||||
|
||||
# Run local tests (recommended for development)
|
||||
./run_tests_local.sh
|
||||
|
||||
# Run all tests
|
||||
python3 manage.py test -v2
|
||||
|
||||
# Database migrations
|
||||
./manage.py migrate
|
||||
|
||||
# Collect static files
|
||||
./manage.py collectstatic -l --no-input
|
||||
|
||||
# Create superuser
|
||||
./manage.py createsuperuser
|
||||
```
|
||||
|
||||
## Code Style Guidelines
|
||||
- Use descriptive variable and function names
|
||||
- Add comprehensive docstrings for classes and methods
|
||||
- **MANDATORY: Include type hints for ALL new code** - this is a strict requirement
|
||||
- Follow PEP 8 and Django coding standards
|
||||
- Use meaningful commit messages
|
||||
- Add comments for complex business logic
|
||||
|
||||
## Error Handling
|
||||
- Use proper exception handling with specific exception types
|
||||
- Log errors with appropriate levels (DEBUG, INFO, WARNING, ERROR)
|
||||
- Provide user-friendly error messages
|
||||
- Implement graceful fallbacks where possible
|
||||
|
||||
## API Compatibility
|
||||
- Maintain backward compatibility with existing avatar URLs
|
||||
- Support Libravatar federation protocol
|
||||
- Ensure Gravatar compatibility for imports
|
||||
- Preserve existing URL patterns and parameters
|
||||
|
||||
## Monitoring & Logging
|
||||
- Use structured logging with appropriate levels
|
||||
- Log security events to dedicated security log
|
||||
- Monitor performance metrics (access counts, response times)
|
||||
- Implement health checks for external dependencies
|
||||
- **Robust logging setup**: Automatically tests directory writeability and falls back gracefully
|
||||
- **Fallback hierarchy**: logs/ → /tmp/libravatar-logs → user-specific temp directory
|
||||
- **Permission handling**: Handles cases where logs directory exists but isn't writable
|
||||
|
||||
## GitLab CI/CD Monitoring
|
||||
- **MANDATORY: Check GitLab pipeline status regularly** during development
|
||||
- Monitor pipeline status for the current working branch (typically `devel`)
|
||||
- Use `glab ci list --repo git.linux-kernel.at/oliver/ivatar --per-page 5` to check recent pipelines
|
||||
- Verify all tests pass before considering work complete
|
||||
- Check pipeline logs with `glab ci trace <pipeline-id> --repo git.linux-kernel.at/oliver/ivatar` if needed
|
||||
- Address any CI failures immediately before proceeding with new changes
|
||||
- Pipeline URL: https://git.linux-kernel.at/oliver/ivatar/-/pipelines
|
||||
|
||||
## Deployment Verification
|
||||
- **Automatic verification**: GitLab CI automatically verifies dev.libravatar.org deployments on `devel` branch
|
||||
- **Manual verification**: Production deployments on `master` branch can be verified manually via CI
|
||||
- **Version endpoint**: `/deployment/version/` provides commit hash, branch, and deployment status
|
||||
- **Security**: Version endpoint uses cached git file reading (no subprocess calls) to prevent DDoS attacks
|
||||
- **Performance**: Version information is cached in memory to avoid repeated file system access
|
||||
- **SELinux compatibility**: No subprocess calls that might be blocked by SELinux policies
|
||||
- **Manual testing**: Use `./scripts/test_deployment.sh` to test deployments locally
|
||||
- **Deployment timing**: Dev deployments via Puppet may take up to 30 minutes to complete
|
||||
- **Verification includes**: Version matching, avatar endpoint, stats endpoint functionality
|
||||
|
||||
Remember: This is a production avatar service handling user data and images. Security, performance, and reliability are paramount. Always consider the impact of changes on existing users and federated services.
|
||||
11
.env
Normal file
11
.env
Normal file
@@ -0,0 +1,11 @@
|
||||
if [ ! -d .virtualenv ]; then
|
||||
if [ ! "$(which virtualenv)" == "" ]; then
|
||||
if [ -f .env ]; then
|
||||
virtualenv -p python3 .virtualenv
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
if [ -f .virtualenv/bin/activate ]; then
|
||||
source .virtualenv/bin/activate
|
||||
AUTOENV_ENABLE_LEAVE=True
|
||||
fi
|
||||
1
.env.leave
Normal file
1
.env.leave
Normal file
@@ -0,0 +1 @@
|
||||
deactivate
|
||||
6
.flake8
Normal file
6
.flake8
Normal file
@@ -0,0 +1,6 @@
|
||||
[flake8]
|
||||
ignore = E501, W503, E402, C901, E231, E702
|
||||
max-line-length = 79
|
||||
max-complexity = 18
|
||||
select = B,C,E,F,W,T4,B9
|
||||
exclude = .git,__pycache__,.virtualenv
|
||||
12
.gitignore
vendored
12
.gitignore
vendored
@@ -1,6 +1,6 @@
|
||||
__pycache__
|
||||
/db.sqlite3
|
||||
/static/
|
||||
/static/*
|
||||
**.*.swp
|
||||
.coverage
|
||||
htmlcov/
|
||||
@@ -13,3 +13,13 @@ db.sqlite3.SAVE
|
||||
node_modules/
|
||||
config_local.py
|
||||
locale/*/LC_MESSAGES/django.mo
|
||||
.DS_Store
|
||||
.idea/
|
||||
contacts.csv
|
||||
falko_gravatar.jpg
|
||||
*.egg-info
|
||||
dump_all*.sql
|
||||
dist/
|
||||
.env.local
|
||||
tmp/
|
||||
logs/
|
||||
|
||||
273
.gitlab-ci.yml
273
.gitlab-ci.yml
@@ -1,8 +1,65 @@
|
||||
image: docker.io/ofalk/fedora31-python3
|
||||
image:
|
||||
name: git.linux-kernel.at:5050/oliver/fedora42-python3:latest
|
||||
entrypoint:
|
||||
- "/bin/sh"
|
||||
- "-c"
|
||||
|
||||
before_script:
|
||||
# Cache pip deps to speed up builds
|
||||
cache:
|
||||
paths:
|
||||
- .pipcache
|
||||
variables:
|
||||
PIP_CACHE_DIR: .pipcache
|
||||
|
||||
# Test with OpenTelemetry instrumentation (always enabled, export disabled in CI)
|
||||
test_and_coverage:
|
||||
stage: build
|
||||
coverage: "/^TOTAL.*\\s+(\\d+\\%)$/"
|
||||
services:
|
||||
- postgres:latest
|
||||
variables:
|
||||
POSTGRES_DB: django_db
|
||||
POSTGRES_USER: django_user
|
||||
POSTGRES_PASSWORD: django_password
|
||||
POSTGRES_HOST: postgres
|
||||
DATABASE_URL: "postgres://django_user:django_password@postgres/django_db"
|
||||
PYTHONUNBUFFERED: 1
|
||||
# OpenTelemetry instrumentation always enabled, export controlled by OTEL_EXPORT_ENABLED
|
||||
OTEL_EXPORT_ENABLED: "false" # Disable export in CI to avoid external dependencies
|
||||
OTEL_SERVICE_NAME: "ivatar-ci"
|
||||
OTEL_ENVIRONMENT: "ci"
|
||||
before_script:
|
||||
- virtualenv -p python3 /tmp/.virtualenv
|
||||
- source /tmp/.virtualenv/bin/activate
|
||||
- pip install -U pip
|
||||
- pip install Pillow
|
||||
- pip install -r requirements.txt
|
||||
- pip install python-coveralls
|
||||
- pip install coverage
|
||||
- pip install pycco
|
||||
- pip install django_coverage_plugin
|
||||
script:
|
||||
- source /tmp/.virtualenv/bin/activate
|
||||
- echo 'from ivatar.settings import TEMPLATES' > config_local.py
|
||||
- echo 'TEMPLATES[0]["OPTIONS"]["debug"] = True' >> config_local.py
|
||||
- echo "DEBUG = True" >> config_local.py
|
||||
- echo "from config import CACHES" >> config_local.py
|
||||
- echo "CACHES['default'] = CACHES['filesystem']" >> config_local.py
|
||||
- python manage.py sqldsn
|
||||
- python manage.py collectstatic --noinput
|
||||
- echo "Running tests with OpenTelemetry instrumentation enabled..."
|
||||
- coverage run --source . scripts/run_tests_with_coverage.py
|
||||
- coverage report --fail-under=70
|
||||
- coverage html
|
||||
artifacts:
|
||||
paths:
|
||||
- htmlcov/
|
||||
pycco:
|
||||
stage: test
|
||||
before_script:
|
||||
- virtualenv -p python3 /tmp/.virtualenv
|
||||
- source /tmp/.virtualenv/bin/activate
|
||||
- pip install -U pip
|
||||
- pip install Pillow
|
||||
- pip install -r requirements.txt
|
||||
- pip install python-coveralls
|
||||
@@ -10,44 +67,202 @@ before_script:
|
||||
- pip install pycco
|
||||
- pip install django_coverage_plugin
|
||||
|
||||
test_and_coverage:
|
||||
stage: test
|
||||
script:
|
||||
- "/bin/true"
|
||||
- find ivatar/ -type f -name "*.py"|grep -v __pycache__|grep -v __init__.py|grep
|
||||
-v /migrations/ | xargs pycco -p -d pycco -i -s
|
||||
artifacts:
|
||||
paths:
|
||||
- pycco/
|
||||
expire_in: 14 days
|
||||
pages:
|
||||
stage: deploy
|
||||
dependencies:
|
||||
- test_and_coverage
|
||||
- pycco
|
||||
script:
|
||||
- mv htmlcov/ public/
|
||||
- mv pycco/ public/
|
||||
artifacts:
|
||||
paths:
|
||||
- public
|
||||
expire_in: 14 days
|
||||
only:
|
||||
- master
|
||||
#build-image:
|
||||
# image: docker
|
||||
# only:
|
||||
# - master
|
||||
# - devel
|
||||
# services:
|
||||
# - docker:dind
|
||||
# before_script:
|
||||
# - docker info
|
||||
# - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
|
||||
# script:
|
||||
# - ls -lah
|
||||
# - |
|
||||
# if [[ "$CI_COMMIT_BRANCH" == "$CI_DEFAULT_BRANCH" ]]; then
|
||||
# tag=""
|
||||
# echo "Running on default branch '$CI_DEFAULT_BRANCH': tag = 'latest'"
|
||||
# else
|
||||
# tag=":$CI_COMMIT_REF_SLUG"
|
||||
# echo "Running on branch '$CI_COMMIT_BRANCH': tag = $tag"
|
||||
# fi
|
||||
# - docker build --pull -t "$CI_REGISTRY_IMAGE${tag}" .
|
||||
# - docker push "$CI_REGISTRY_IMAGE${tag}"
|
||||
|
||||
# Local performance testing job (runs in CI environment)
|
||||
performance_tests_local:
|
||||
stage: test
|
||||
services:
|
||||
- postgres:latest
|
||||
variables:
|
||||
POSTGRES_DB: django_db
|
||||
POSTGRES_USER: django_user
|
||||
POSTGRES_PASSWORD: django_password
|
||||
POSTGRES_HOST: postgres
|
||||
DATABASE_URL: "postgres://django_user:django_password@postgres/django_db"
|
||||
PYTHONUNBUFFERED: 1
|
||||
# OpenTelemetry configuration for performance testing
|
||||
OTEL_EXPORT_ENABLED: "false"
|
||||
OTEL_SERVICE_NAME: "ivatar-perf-test-local"
|
||||
OTEL_ENVIRONMENT: "ci-performance"
|
||||
before_script:
|
||||
- virtualenv -p python3 /tmp/.virtualenv
|
||||
- source /tmp/.virtualenv/bin/activate
|
||||
- pip install -U pip
|
||||
- pip install Pillow
|
||||
- pip install -r requirements.txt
|
||||
- pip install requests # Additional dependency for performance tests
|
||||
script:
|
||||
- source /tmp/.virtualenv/bin/activate
|
||||
- echo 'from ivatar.settings import TEMPLATES' > config_local.py
|
||||
- echo 'TEMPLATES[0]["OPTIONS"]["debug"] = True' >> config_local.py
|
||||
- echo "DEBUG = True" >> config_local.py
|
||||
- echo "from config import CACHES" >> config_local.py
|
||||
- echo "CACHES['default'] = CACHES['filesystem']" >> config_local.py
|
||||
- python manage.py migrate
|
||||
- python manage.py collectstatic --noinput
|
||||
- coverage run --source . manage.py test -v3
|
||||
- coverage report --fail-under=70
|
||||
- coverage html
|
||||
- echo "Running local performance tests (no cache testing)..."
|
||||
- python3 scripts/performance_tests.py --no-cache-test --output performance_local.json
|
||||
artifacts:
|
||||
paths:
|
||||
- htmlcov/
|
||||
- performance_local.json
|
||||
expire_in: 7 days
|
||||
allow_failure: true # Don't fail the pipeline on performance issues, but report them
|
||||
|
||||
pycco:
|
||||
stage: test
|
||||
script:
|
||||
- /bin/true
|
||||
- find ivatar/ -type f -name "*.py"|grep -v __pycache__|grep -v __init__.py|grep -v /migrations/ | xargs pycco -p -d pycco -i -s
|
||||
artifacts:
|
||||
paths:
|
||||
- pycco/
|
||||
expire_in: 14 days
|
||||
|
||||
pages:
|
||||
before_script:
|
||||
- /bin/true
|
||||
- /bin/true
|
||||
# Performance testing against dev server (devel branch only)
|
||||
performance_tests_dev:
|
||||
stage: deploy
|
||||
dependencies:
|
||||
- test_and_coverage
|
||||
- pycco
|
||||
image: python:3.11-alpine
|
||||
only:
|
||||
- devel
|
||||
when: on_success # Run automatically after successful deployment verification
|
||||
variables:
|
||||
DEV_URL: "https://dev.libravatar.org"
|
||||
PYTHONUNBUFFERED: 1
|
||||
before_script:
|
||||
- apk add --no-cache curl
|
||||
- pip install requests Pillow prettytable pyLibravatar dnspython py3dns
|
||||
script:
|
||||
- mv htmlcov/ public/
|
||||
- mv pycco/ public/
|
||||
- echo "Running performance tests against dev.libravatar.org..."
|
||||
- python3 scripts/performance_tests.py --base-url $DEV_URL --concurrent-users 5 --avatar-threshold 2500 --response-threshold 2500 --p95-threshold 5000 --ignore-cache-warnings --output performance_dev.json
|
||||
artifacts:
|
||||
paths:
|
||||
- public
|
||||
expire_in: 14 days
|
||||
- performance_dev.json
|
||||
expire_in: 7 days
|
||||
allow_failure: true # Don't fail deployment on performance issues
|
||||
needs:
|
||||
- job: verify_dev_deployment
|
||||
artifacts: false # Run after deployment verification succeeds
|
||||
|
||||
# Performance testing against production server (master branch only)
|
||||
performance_tests_prod:
|
||||
stage: deploy
|
||||
image: python:3.11-alpine
|
||||
only:
|
||||
- master
|
||||
when: on_success # Run automatically after successful deployment verification
|
||||
variables:
|
||||
PROD_URL: "https://libravatar.org"
|
||||
PYTHONUNBUFFERED: 1
|
||||
before_script:
|
||||
- apk add --no-cache curl
|
||||
- pip install requests Pillow prettytable pyLibravatar dnspython py3dns
|
||||
script:
|
||||
- echo "Running performance tests against libravatar.org..."
|
||||
- python3 scripts/performance_tests.py --base-url $PROD_URL --concurrent-users 3 --output performance_prod.json
|
||||
artifacts:
|
||||
paths:
|
||||
- performance_prod.json
|
||||
expire_in: 30 days # Keep production results longer
|
||||
allow_failure: true # Don't fail deployment on performance issues
|
||||
needs:
|
||||
- job: verify_prod_deployment
|
||||
artifacts: false # Run after deployment verification succeeds
|
||||
|
||||
# Manual performance testing against production (for on-demand testing)
|
||||
performance_tests_prod_manual:
|
||||
stage: deploy
|
||||
image: python:3.11-alpine
|
||||
only:
|
||||
- master
|
||||
when: manual # Manual trigger for on-demand performance testing
|
||||
variables:
|
||||
PROD_URL: "https://libravatar.org"
|
||||
PYTHONUNBUFFERED: 1
|
||||
before_script:
|
||||
- apk add --no-cache curl
|
||||
- pip install requests Pillow prettytable pyLibravatar dnspython py3dns
|
||||
script:
|
||||
- echo "Running manual performance tests against libravatar.org..."
|
||||
- python3 scripts/performance_tests.py --base-url $PROD_URL --concurrent-users 5 --output performance_prod_manual.json
|
||||
artifacts:
|
||||
paths:
|
||||
- performance_prod_manual.json
|
||||
expire_in: 30 days
|
||||
allow_failure: true
|
||||
|
||||
# Deployment verification jobs
|
||||
verify_dev_deployment:
|
||||
stage: deploy
|
||||
image: python:3.11-alpine
|
||||
only:
|
||||
- devel
|
||||
variables:
|
||||
DEV_URL: "https://dev.libravatar.org"
|
||||
MAX_RETRIES: 30
|
||||
RETRY_DELAY: 60
|
||||
PYTHONUNBUFFERED: 1
|
||||
before_script:
|
||||
- apk add --no-cache curl git
|
||||
- pip install Pillow
|
||||
script:
|
||||
- echo "Waiting for dev.libravatar.org deployment to complete..."
|
||||
- python3 scripts/check_deployment.py --dev --max-retries $MAX_RETRIES --retry-delay $RETRY_DELAY
|
||||
allow_failure: false
|
||||
|
||||
verify_prod_deployment:
|
||||
stage: deploy
|
||||
image: python:3.11-alpine
|
||||
only:
|
||||
- master
|
||||
when: on_success
|
||||
variables:
|
||||
PROD_URL: "https://libravatar.org"
|
||||
MAX_RETRIES: 10
|
||||
RETRY_DELAY: 30
|
||||
PYTHONUNBUFFERED: 1
|
||||
before_script:
|
||||
- apk add --no-cache curl git
|
||||
- pip install Pillow
|
||||
script:
|
||||
- echo "Verifying production deployment..."
|
||||
- python3 scripts/check_deployment.py --prod --max-retries $MAX_RETRIES --retry-delay $RETRY_DELAY
|
||||
allow_failure: false
|
||||
|
||||
include:
|
||||
- template: Jobs/SAST.gitlab-ci.yml
|
||||
- template: Jobs/Dependency-Scanning.gitlab-ci.yml
|
||||
- template: Jobs/Secret-Detection.gitlab-ci.yml
|
||||
|
||||
5
.gitlab/issue_templates/example-template.md
Normal file
5
.gitlab/issue_templates/example-template.md
Normal file
@@ -0,0 +1,5 @@
|
||||
# Dscribe your issue
|
||||
|
||||
# What have you tried to far?
|
||||
|
||||
# Links / Pointer / Resources
|
||||
78
.pre-commit-config.yaml
Normal file
78
.pre-commit-config.yaml
Normal file
@@ -0,0 +1,78 @@
|
||||
fail_fast: true
|
||||
repos:
|
||||
- repo: meta
|
||||
hooks:
|
||||
- id: check-useless-excludes
|
||||
- repo: https://github.com/pre-commit/mirrors-prettier
|
||||
rev: v4.0.0-alpha.8
|
||||
hooks:
|
||||
- id: prettier
|
||||
files: \.(css|js|md|markdown|json)
|
||||
- repo: https://github.com/python/black
|
||||
rev: 25.9.0
|
||||
hooks:
|
||||
- id: black
|
||||
- repo: https://github.com/asottile/pyupgrade
|
||||
rev: v3.21.0
|
||||
hooks:
|
||||
- id: pyupgrade
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v6.0.0
|
||||
hooks:
|
||||
- id: check-added-large-files
|
||||
- id: check-ast
|
||||
- id: check-case-conflict
|
||||
- id: check-executables-have-shebangs
|
||||
- id: check-json
|
||||
- id: check-merge-conflict
|
||||
- id: check-symlinks
|
||||
- id: check-vcs-permalinks
|
||||
- id: check-xml
|
||||
- id: check-yaml
|
||||
args:
|
||||
- --unsafe
|
||||
- id: end-of-file-fixer
|
||||
- id: forbid-new-submodules
|
||||
- id: no-commit-to-branch
|
||||
args:
|
||||
- --branch
|
||||
- gh-pages
|
||||
- id: requirements-txt-fixer
|
||||
- id: sort-simple-yaml
|
||||
- id: trailing-whitespace
|
||||
- repo: https://github.com/PyCQA/flake8
|
||||
rev: 7.3.0
|
||||
hooks:
|
||||
- id: flake8
|
||||
- repo: local
|
||||
hooks:
|
||||
- id: shfmt
|
||||
name: shfmt
|
||||
minimum_pre_commit_version: 2.4.0
|
||||
language: golang
|
||||
additional_dependencies:
|
||||
- mvdan.cc/sh/v3/cmd/shfmt@v3.1.1
|
||||
entry: shfmt
|
||||
args:
|
||||
- -w
|
||||
- -i
|
||||
- '4'
|
||||
types:
|
||||
- shell
|
||||
- repo: https://github.com/asottile/blacken-docs
|
||||
rev: 1.20.0
|
||||
hooks:
|
||||
- id: blacken-docs
|
||||
# YASpeller does not seem to work anymore
|
||||
# - repo: https://github.com/hcodes/yaspeller.git
|
||||
# rev: v8.0.1
|
||||
# hooks:
|
||||
# - id: yaspeller
|
||||
#
|
||||
# types:
|
||||
# - markdown
|
||||
- repo: https://github.com/kadrach/pre-commit-gitlabci-lint
|
||||
rev: 22d0495c9894e8b27cc37c2ed5d9a6b46385a44c
|
||||
hooks:
|
||||
- id: gitlabci-lint
|
||||
args: ["https://git.linux-kernel.at"]
|
||||
22
Dockerfile
Normal file
22
Dockerfile
Normal file
@@ -0,0 +1,22 @@
|
||||
FROM git.linux-kernel.at:5050/oliver/fedora40-python3:latest
|
||||
LABEL maintainer Oliver Falk <oliver@linux-kernel.at>
|
||||
EXPOSE 8081
|
||||
|
||||
ADD . /opt/ivatar-devel
|
||||
|
||||
WORKDIR /opt/ivatar-devel
|
||||
|
||||
RUN pip3 install pip --upgrade \
|
||||
&& virtualenv .virtualenv \
|
||||
&& source .virtualenv/bin/activate \
|
||||
&& pip3 install Pillow \
|
||||
&& pip3 install -r requirements.txt \
|
||||
&& pip3 install python-coveralls coverage pycco django_coverage_plugin
|
||||
|
||||
RUN echo "DEBUG = True" >> /opt/ivatar-devel/config_local.py
|
||||
RUN echo "EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'" >> /opt/ivatar-devel/config_local.py
|
||||
RUN source .virtualenv/bin/activate \
|
||||
&& python3 manage.py migrate \
|
||||
&& python3 manage.py collectstatic --noinput \
|
||||
&& echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.create_superuser('admin', 'admin@local.tld', 'admin')" | python manage.py shell
|
||||
ENTRYPOINT source .virtualenv/bin/activate && python3 ./manage.py runserver 0:8081
|
||||
229
FILE_UPLOAD_SECURITY.md
Normal file
229
FILE_UPLOAD_SECURITY.md
Normal file
@@ -0,0 +1,229 @@
|
||||
# File Upload Security Documentation
|
||||
|
||||
## Overview
|
||||
|
||||
The ivatar application now includes comprehensive file upload security features to protect against malicious file uploads, data leaks, and other security threats.
|
||||
|
||||
## Security Features
|
||||
|
||||
### 1. File Type Validation
|
||||
|
||||
**Magic Bytes Verification**
|
||||
|
||||
- Validates file signatures (magic bytes) to ensure uploaded files are actually images
|
||||
- Supports JPEG, PNG, GIF, WebP, BMP, and TIFF formats
|
||||
- Prevents file extension spoofing attacks
|
||||
|
||||
**MIME Type Validation**
|
||||
|
||||
- Uses python-magic library to detect actual MIME types
|
||||
- Cross-references with allowed MIME types list
|
||||
- Prevents MIME type confusion attacks
|
||||
|
||||
### 2. Content Security Scanning
|
||||
|
||||
**Malicious Content Detection**
|
||||
|
||||
- Scans for embedded scripts (`<script>`, `javascript:`, `vbscript:`)
|
||||
- Detects executable content (PE headers, ELF headers)
|
||||
- Identifies polyglot attacks (files valid in multiple formats)
|
||||
- Checks for PHP and other server-side code
|
||||
|
||||
**PIL Image Validation**
|
||||
|
||||
- Uses Python Imaging Library to verify file is a valid image
|
||||
- Checks image dimensions and format
|
||||
- Ensures image can be properly loaded and processed
|
||||
|
||||
### 3. EXIF Data Sanitization
|
||||
|
||||
**Metadata Removal**
|
||||
|
||||
- Automatically strips EXIF data from uploaded images
|
||||
- Prevents location data and other sensitive metadata leaks
|
||||
- Preserves image quality while removing privacy risks
|
||||
|
||||
### 4. Enhanced Logging
|
||||
|
||||
**Security Event Logging**
|
||||
|
||||
- Logs all file upload attempts with user ID and IP address
|
||||
- Records security violations and suspicious activity
|
||||
- Provides audit trail for security monitoring
|
||||
|
||||
## Configuration
|
||||
|
||||
### Settings
|
||||
|
||||
All security features can be configured in `config.py` or overridden in `config_local.py`:
|
||||
|
||||
```python
|
||||
# File upload security settings
|
||||
ENABLE_FILE_SECURITY_VALIDATION = True
|
||||
ENABLE_EXIF_SANITIZATION = True
|
||||
ENABLE_MALICIOUS_CONTENT_SCAN = True
|
||||
```
|
||||
|
||||
### Dependencies
|
||||
|
||||
The security features require the following Python packages:
|
||||
|
||||
```bash
|
||||
pip install python-magic>=0.4.27
|
||||
```
|
||||
|
||||
**Note**: On some systems, you may need to install the libmagic system library:
|
||||
|
||||
- **Ubuntu/Debian**: `sudo apt-get install libmagic1`
|
||||
- **CentOS/RHEL**: `sudo yum install file-devel`
|
||||
- **macOS**: `brew install libmagic`
|
||||
|
||||
## Security Levels
|
||||
|
||||
### Security Score System
|
||||
|
||||
Files are assigned a security score (0-100) based on validation results:
|
||||
|
||||
- **90-100**: Excellent - No security concerns
|
||||
- **80-89**: Good - Minor warnings, safe to process
|
||||
- **70-79**: Fair - Some concerns, review recommended
|
||||
- **50-69**: Poor - Multiple issues, high risk
|
||||
- **0-49**: Critical - Malicious content detected, reject
|
||||
|
||||
### Validation Levels
|
||||
|
||||
1. **Basic Validation**: File size, filename, extension
|
||||
2. **Magic Bytes**: File signature verification
|
||||
3. **MIME Type**: Content type validation
|
||||
4. **PIL Validation**: Image format verification
|
||||
5. **Security Scan**: Malicious content detection
|
||||
6. **EXIF Sanitization**: Metadata removal
|
||||
|
||||
## API Reference
|
||||
|
||||
### FileValidator Class
|
||||
|
||||
```python
|
||||
from ivatar.file_security import FileValidator
|
||||
|
||||
validator = FileValidator(file_data, filename)
|
||||
results = validator.comprehensive_validation()
|
||||
```
|
||||
|
||||
### Main Validation Function
|
||||
|
||||
```python
|
||||
from ivatar.file_security import validate_uploaded_file
|
||||
|
||||
is_valid, results, sanitized_data = validate_uploaded_file(file_data, filename)
|
||||
```
|
||||
|
||||
### Security Report Generation
|
||||
|
||||
```python
|
||||
from ivatar.file_security import get_file_security_report
|
||||
|
||||
report = get_file_security_report(file_data, filename)
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Validation Errors
|
||||
|
||||
The system provides user-friendly error messages while logging detailed security information:
|
||||
|
||||
- **Malicious Content**: "File appears to be malicious and cannot be uploaded"
|
||||
- **Invalid Format**: "File format not supported or file appears to be corrupted"
|
||||
|
||||
### Logging Levels
|
||||
|
||||
- **INFO**: Successful uploads and normal operations
|
||||
- **WARNING**: Security violations and suspicious activity
|
||||
- **ERROR**: Validation failures and system errors
|
||||
|
||||
## Testing
|
||||
|
||||
### Running Security Tests
|
||||
|
||||
```bash
|
||||
python manage.py test ivatar.test_file_security
|
||||
```
|
||||
|
||||
### Test Coverage
|
||||
|
||||
The test suite covers:
|
||||
|
||||
- Valid file validation
|
||||
- Malicious content detection
|
||||
- Magic bytes verification
|
||||
- MIME type validation
|
||||
- EXIF sanitization
|
||||
- Form validation
|
||||
- Integration tests
|
||||
|
||||
## Performance Considerations
|
||||
|
||||
### Memory Usage
|
||||
|
||||
- Files are processed in memory for validation
|
||||
- Large files (>5MB) may impact performance
|
||||
- Consider increasing server memory for high-volume deployments
|
||||
|
||||
### Processing Time
|
||||
|
||||
- Basic validation: <10ms
|
||||
- Full security scan: 50-200ms
|
||||
- EXIF sanitization: 100-500ms
|
||||
- Total overhead: ~200-700ms per upload
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
1. **python-magic Import Error**
|
||||
|
||||
- Install libmagic system library
|
||||
- Verify python-magic installation
|
||||
|
||||
2. **False Positives**
|
||||
- Review security score thresholds
|
||||
- Adjust validation settings
|
||||
|
||||
### Debug Mode
|
||||
|
||||
Enable debug logging to troubleshoot validation issues:
|
||||
|
||||
```python
|
||||
LOGGING = {
|
||||
"loggers": {
|
||||
"ivatar.security": {
|
||||
"level": "DEBUG",
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## Security Best Practices
|
||||
|
||||
### Deployment Recommendations
|
||||
|
||||
1. **Enable All Security Features** in production
|
||||
2. **Monitor Security Logs** regularly
|
||||
3. **Keep Dependencies Updated**
|
||||
4. **Regular Security Audits** of uploaded content
|
||||
|
||||
### Monitoring
|
||||
|
||||
- Monitor security.log for violations
|
||||
- Track upload success/failure rates
|
||||
- Alert on repeated security violations
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
Potential future improvements:
|
||||
|
||||
- Virus scanning integration (ClamAV)
|
||||
- Content-based image analysis
|
||||
- Machine learning threat detection
|
||||
- Advanced polyglot detection
|
||||
- Real-time threat intelligence feeds
|
||||
67
INSTALL.md
67
INSTALL.md
@@ -1,6 +1,6 @@
|
||||
# Installation
|
||||
|
||||
## Prequisits
|
||||
## Prerequisites
|
||||
|
||||
Python 3.x + virtualenv
|
||||
|
||||
@@ -10,20 +10,28 @@ Python 3.x + virtualenv
|
||||
yum install python34-virtualenv.noarch
|
||||
```
|
||||
|
||||
### Debian 11
|
||||
|
||||
```
|
||||
sudo apt-get update
|
||||
sudo apt-get install git python3-virtualenv libmariadb-dev libldap2-dev libsasl2-dev
|
||||
```
|
||||
|
||||
## Checkout
|
||||
|
||||
~~~~bash
|
||||
```bash
|
||||
git clone https://git.linux-kernel.at/oliver/ivatar.git
|
||||
cd ivatar
|
||||
~~~~
|
||||
```
|
||||
|
||||
## Virtual environment
|
||||
|
||||
~~~~bash
|
||||
virtualenv -p python3 .virtualenv
|
||||
```bash
|
||||
virtualenv -p python3 .virtualenv
|
||||
source .virtualenv/bin/activate
|
||||
pip install pillow
|
||||
pip install -r requirements.txt
|
||||
~~~~
|
||||
```
|
||||
|
||||
## (SQL) Migrations
|
||||
|
||||
@@ -50,10 +58,55 @@ pip install -r requirements.txt
|
||||
```
|
||||
|
||||
## Running the testsuite
|
||||
|
||||
```
|
||||
./manage.py test -v3 # Or any other verbosity level you like
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
### Gravatar Proxy and Redirect Settings
|
||||
|
||||
By default, ivatar is configured to work well for public instances like libravatar.org. However, for local or private instances, you may want to disable external requests to Gravatar. You can configure the default behavior by adding these settings to your `config_local.py`:
|
||||
|
||||
```python
|
||||
# Default settings for Gravatar proxy and redirect behavior
|
||||
# These can be overridden by URL parameters (?gravatarproxy=n&gravatarredirect=n)
|
||||
|
||||
# Whether to proxy requests to Gravatar when no local avatar is found (default: True)
|
||||
DEFAULT_GRAVATARPROXY = False
|
||||
|
||||
# Whether to redirect directly to Gravatar when no local avatar is found (default: False)
|
||||
DEFAULT_GRAVATARREDIRECT = False
|
||||
|
||||
# Whether to force default behavior even when a user avatar exists (default: False)
|
||||
FORCEDEFAULT = False
|
||||
```
|
||||
|
||||
**Use cases:**
|
||||
|
||||
- **Private/Local instances**: Set `DEFAULT_GRAVATARPROXY = False` and `DEFAULT_GRAVATARREDIRECT = False` to prevent external requests
|
||||
- **Gravatar-first instances**: Set `DEFAULT_GRAVATARREDIRECT = True` to redirect to Gravatar instead of proxying
|
||||
- **Testing/Development**: Set `FORCEDEFAULT = True` to always use default avatars
|
||||
|
||||
**Note**: URL parameters (`?gravatarproxy=n`, `?gravatarredirect=y`, `?forcedefault=y`) will always override these configuration defaults.
|
||||
|
||||
### OpenID Connect authentication with Fedora
|
||||
|
||||
To enable OpenID Connect (OIDC) authentication with Fedora, you must have obtained a `client_id` and `client_secret` pair from the Fedora Infrastructure.
|
||||
Then you must set these values in `config_local.py`:
|
||||
|
||||
```
|
||||
SOCIAL_AUTH_FEDORA_KEY = "the-client-id"
|
||||
SOCIAL_AUTH_FEDORA_SECRET = "the-client-secret"
|
||||
```
|
||||
|
||||
You can override the location of the OIDC provider with the `SOCIAL_AUTH_FEDORA_OIDC_ENDPOINT` setting. For example, to authenticate with Fedora's staging environment, set this in `config_local.py`:
|
||||
|
||||
```
|
||||
SOCIAL_AUTH_FEDORA_OIDC_ENDPOINT = "https://id.stg.fedoraproject.org"
|
||||
```
|
||||
|
||||
# Production deployment Webserver (non-cloudy)
|
||||
|
||||
To deploy this Django application with WSGI on Apache, NGINX or any other web server, please refer to the the webserver documentation; There are also plenty of howtos on the net (I'll not LMGTFY...)
|
||||
@@ -74,4 +127,4 @@ There is a file called ebcreate.txt as well as a directory called .ebextensions,
|
||||
|
||||
## Database
|
||||
|
||||
It should work with SQLite (do *not* use in production!), MySQL/MariaDB, as well as PostgreSQL.
|
||||
It should work with SQLite (do _not_ use in production!), MySQL/MariaDB, as well as PostgreSQL.
|
||||
|
||||
661
LICENSE
Normal file
661
LICENSE
Normal file
@@ -0,0 +1,661 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
10
MANIFEST.in
Normal file
10
MANIFEST.in
Normal file
@@ -0,0 +1,10 @@
|
||||
include *.py
|
||||
include *.md
|
||||
include COPYING
|
||||
include LICENSE
|
||||
recursive-include templates *
|
||||
recursive-include ivatar *
|
||||
exclude .virtualenv
|
||||
exclude libravatar.egg-info
|
||||
global-exclude *.py[co]
|
||||
global-exclude __pycache__
|
||||
463
OPENTELEMETRY.md
Normal file
463
OPENTELEMETRY.md
Normal file
@@ -0,0 +1,463 @@
|
||||
# OpenTelemetry Integration for ivatar
|
||||
|
||||
This document describes the OpenTelemetry integration implemented in the ivatar project, providing comprehensive observability for avatar generation, file uploads, authentication, and system performance.
|
||||
|
||||
## Overview
|
||||
|
||||
OpenTelemetry is integrated into ivatar to provide:
|
||||
|
||||
- **Distributed Tracing**: Track requests across the entire avatar generation pipeline
|
||||
- **Custom Metrics**: Monitor avatar-specific operations and performance
|
||||
- **Multi-Instance Support**: Distinguish between production and development environments
|
||||
- **Infrastructure Integration**: Works with existing Prometheus/Grafana stack
|
||||
|
||||
## Architecture
|
||||
|
||||
### Components
|
||||
|
||||
1. **OpenTelemetry Configuration** (`ivatar/opentelemetry_config.py`)
|
||||
|
||||
- Centralized configuration management
|
||||
- Environment-based setup
|
||||
- Resource creation with service metadata
|
||||
|
||||
2. **Custom Middleware** (`ivatar/opentelemetry_middleware.py`)
|
||||
|
||||
- Request/response tracing
|
||||
- Avatar-specific metrics
|
||||
- Custom decorators for operation tracing
|
||||
|
||||
3. **Instrumentation Integration**
|
||||
- Django framework instrumentation
|
||||
- Database query tracing (PostgreSQL/MySQL)
|
||||
- HTTP client instrumentation
|
||||
- Cache instrumentation (Memcached)
|
||||
|
||||
## Configuration
|
||||
|
||||
### Environment Variables
|
||||
|
||||
| Variable | Description | Default | Required |
|
||||
| ----------------------------- | ------------------------------------ | ------------- | -------- |
|
||||
| `OTEL_EXPORT_ENABLED` | Enable OpenTelemetry data export | `false` | No |
|
||||
| `OTEL_SERVICE_NAME` | Service name identifier | `ivatar` | No |
|
||||
| `OTEL_ENVIRONMENT` | Environment (production/development) | `development` | No |
|
||||
| `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP collector endpoint | None | No |
|
||||
| `OTEL_PROMETHEUS_ENDPOINT` | Local Prometheus server (dev only) | None | No |
|
||||
| `IVATAR_VERSION` | Application version | `2.0` | No |
|
||||
| `HOSTNAME` | Instance identifier | `unknown` | No |
|
||||
|
||||
### Multi-Instance Configuration
|
||||
|
||||
#### Production Environment
|
||||
|
||||
```bash
|
||||
export OTEL_EXPORT_ENABLED=true
|
||||
export OTEL_SERVICE_NAME=ivatar-production
|
||||
export OTEL_ENVIRONMENT=production
|
||||
export OTEL_EXPORTER_OTLP_ENDPOINT=http://collector.internal:4317
|
||||
export HOSTNAME=prod-instance-01
|
||||
```
|
||||
|
||||
**Note**: In production, metrics are exported via OTLP to your existing Prometheus server. Do not set `OTEL_PROMETHEUS_ENDPOINT` in production.
|
||||
|
||||
#### Development Environment
|
||||
|
||||
```bash
|
||||
export OTEL_EXPORT_ENABLED=true
|
||||
export OTEL_SERVICE_NAME=ivatar-development
|
||||
export OTEL_ENVIRONMENT=development
|
||||
export OTEL_EXPORTER_OTLP_ENDPOINT=http://collector.internal:4317
|
||||
export OTEL_PROMETHEUS_ENDPOINT=0.0.0.0:9467
|
||||
export IVATAR_VERSION=2.0-dev
|
||||
export HOSTNAME=dev-instance-01
|
||||
```
|
||||
|
||||
**Note**: In development, you can optionally set `OTEL_PROMETHEUS_ENDPOINT` to start a local HTTP server for testing metrics.
|
||||
|
||||
## Metrics
|
||||
|
||||
### Custom Metrics
|
||||
|
||||
#### Avatar Operations
|
||||
|
||||
- `ivatar_requests_total`: Total HTTP requests by method, status, path
|
||||
- `ivatar_request_duration_seconds`: Request duration histogram
|
||||
- `ivatar_avatar_requests_total`: Avatar requests by status, size, format
|
||||
- `ivatar_avatar_generation_seconds`: Avatar generation time histogram
|
||||
- `ivatar_avatars_generated_total`: Avatars generated by size, format, source
|
||||
- `ivatar_avatar_cache_hits_total`: Cache hits by size, format
|
||||
- `ivatar_avatar_cache_misses_total`: Cache misses by size, format
|
||||
- `ivatar_external_avatar_requests_total`: External service requests
|
||||
- `ivatar_file_uploads_total`: File uploads by content type, success
|
||||
- `ivatar_file_upload_size_bytes`: File upload size histogram
|
||||
|
||||
#### Labels/Dimensions
|
||||
|
||||
- `method`: HTTP method (GET, POST, etc.)
|
||||
- `status_code`: HTTP status code
|
||||
- `path`: Request path
|
||||
- `size`: Avatar size (80, 128, 256, etc.)
|
||||
- `format`: Image format (png, jpg, gif, etc.)
|
||||
- `source`: Avatar source (uploaded, generated, external)
|
||||
- `service`: External service name (gravatar, bluesky)
|
||||
- `content_type`: File MIME type
|
||||
- `success`: Operation success (true/false)
|
||||
|
||||
### Example Queries
|
||||
|
||||
#### Avatar Generation Rate
|
||||
|
||||
```promql
|
||||
rate(ivatar_avatars_generated_total[5m])
|
||||
```
|
||||
|
||||
#### Cache Hit Ratio
|
||||
|
||||
```promql
|
||||
rate(ivatar_avatar_cache_hits_total[5m]) /
|
||||
(rate(ivatar_avatar_cache_hits_total[5m]) + rate(ivatar_avatar_cache_misses_total[5m]))
|
||||
```
|
||||
|
||||
#### Average Avatar Generation Time
|
||||
|
||||
```promql
|
||||
histogram_quantile(0.95, rate(ivatar_avatar_generation_seconds_bucket[5m]))
|
||||
```
|
||||
|
||||
#### File Upload Success Rate
|
||||
|
||||
```promql
|
||||
rate(ivatar_file_uploads_total{success="true"}[5m]) /
|
||||
rate(ivatar_file_uploads_total[5m])
|
||||
```
|
||||
|
||||
## Tracing
|
||||
|
||||
### Trace Points
|
||||
|
||||
#### Request Lifecycle
|
||||
|
||||
- HTTP request processing
|
||||
- Avatar generation pipeline
|
||||
- File upload and processing
|
||||
- Authentication flows
|
||||
- External API calls
|
||||
|
||||
#### Custom Spans
|
||||
|
||||
- `avatar.generate_png`: PNG image generation
|
||||
- `avatar.gravatar_proxy`: Gravatar service proxy
|
||||
- `file_upload.process`: File upload processing
|
||||
- `auth.login`: User authentication
|
||||
- `auth.logout`: User logout
|
||||
|
||||
### Span Attributes
|
||||
|
||||
#### HTTP Attributes
|
||||
|
||||
- `http.method`: HTTP method
|
||||
- `http.url`: Full request URL
|
||||
- `http.status_code`: Response status code
|
||||
- `http.user_agent`: Client user agent
|
||||
- `http.remote_addr`: Client IP address
|
||||
|
||||
#### Avatar Attributes
|
||||
|
||||
- `ivatar.request_type`: Request type (avatar, stats, etc.)
|
||||
- `ivatar.avatar_size`: Requested avatar size
|
||||
- `ivatar.avatar_format`: Requested format
|
||||
- `ivatar.avatar_email`: Email address (if applicable)
|
||||
|
||||
#### File Attributes
|
||||
|
||||
- `file.name`: Uploaded file name
|
||||
- `file.size`: File size in bytes
|
||||
- `file.content_type`: MIME type
|
||||
|
||||
## Infrastructure Requirements
|
||||
|
||||
### Option A: Extend Existing Stack (Recommended)
|
||||
|
||||
The existing monitoring stack can be extended to support OpenTelemetry:
|
||||
|
||||
#### Alloy Configuration
|
||||
|
||||
```yaml
|
||||
# Add to existing Alloy configuration
|
||||
otelcol.receiver.otlp:
|
||||
grpc:
|
||||
endpoint: 0.0.0.0:4317
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
|
||||
otelcol.processor.batch:
|
||||
timeout: 1s
|
||||
send_batch_size: 1024
|
||||
|
||||
otelcol.exporter.prometheus:
|
||||
endpoint: "0.0.0.0:9464"
|
||||
|
||||
otelcol.exporter.jaeger:
|
||||
endpoint: "jaeger-collector:14250"
|
||||
|
||||
otelcol.pipeline.traces:
|
||||
receivers: [otelcol.receiver.otlp]
|
||||
processors: [otelcol.processor.batch]
|
||||
exporters: [otelcol.exporter.jaeger]
|
||||
|
||||
otelcol.pipeline.metrics:
|
||||
receivers: [otelcol.receiver.otlp]
|
||||
processors: [otelcol.processor.batch]
|
||||
exporters: [otelcol.exporter.prometheus]
|
||||
```
|
||||
|
||||
#### Prometheus Configuration
|
||||
|
||||
```yaml
|
||||
scrape_configs:
|
||||
- job_name: "ivatar-opentelemetry"
|
||||
static_configs:
|
||||
- targets: ["ivatar-prod:9464", "ivatar-dev:9464"]
|
||||
scrape_interval: 15s
|
||||
metrics_path: /metrics
|
||||
```
|
||||
|
||||
### Option B: Dedicated OpenTelemetry Collector
|
||||
|
||||
For full OpenTelemetry features, deploy a dedicated collector:
|
||||
|
||||
#### Collector Configuration
|
||||
|
||||
```yaml
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
grpc:
|
||||
endpoint: 0.0.0.0:4317
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
|
||||
processors:
|
||||
batch:
|
||||
timeout: 1s
|
||||
send_batch_size: 1024
|
||||
resource:
|
||||
attributes:
|
||||
- key: environment
|
||||
from_attribute: deployment.environment
|
||||
action: insert
|
||||
|
||||
exporters:
|
||||
prometheus:
|
||||
endpoint: "0.0.0.0:9464"
|
||||
jaeger:
|
||||
endpoint: "jaeger-collector:14250"
|
||||
logging:
|
||||
loglevel: debug
|
||||
|
||||
service:
|
||||
pipelines:
|
||||
traces:
|
||||
receivers: [otlp]
|
||||
processors: [batch, resource]
|
||||
exporters: [jaeger, logging]
|
||||
metrics:
|
||||
receivers: [otlp]
|
||||
processors: [batch, resource]
|
||||
exporters: [prometheus, logging]
|
||||
```
|
||||
|
||||
## Deployment
|
||||
|
||||
### Development Setup
|
||||
|
||||
1. **Install Dependencies**
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
2. **Configure Environment**
|
||||
|
||||
```bash
|
||||
export OTEL_ENABLED=true
|
||||
export OTEL_SERVICE_NAME=ivatar-development
|
||||
export OTEL_ENVIRONMENT=development
|
||||
```
|
||||
|
||||
3. **Start Development Server**
|
||||
|
||||
```bash
|
||||
./manage.py runserver 0:8080
|
||||
```
|
||||
|
||||
4. **Verify Metrics**
|
||||
```bash
|
||||
curl http://localhost:9464/metrics
|
||||
```
|
||||
|
||||
### Production Deployment
|
||||
|
||||
1. **Update Container Images**
|
||||
|
||||
- Add OpenTelemetry dependencies to requirements.txt
|
||||
- Update container build process
|
||||
|
||||
2. **Configure Environment Variables**
|
||||
|
||||
- Set production-specific OpenTelemetry variables
|
||||
- Configure collector endpoints
|
||||
|
||||
3. **Update Monitoring Stack**
|
||||
|
||||
- Extend Alloy configuration
|
||||
- Update Prometheus scrape configs
|
||||
- Configure Grafana dashboards
|
||||
|
||||
4. **Verify Deployment**
|
||||
- Check metrics endpoint accessibility
|
||||
- Verify trace data flow
|
||||
- Monitor dashboard updates
|
||||
|
||||
## Monitoring and Alerting
|
||||
|
||||
### Key Metrics to Monitor
|
||||
|
||||
#### Performance
|
||||
|
||||
- Request duration percentiles (p50, p95, p99)
|
||||
- Avatar generation time
|
||||
- Cache hit ratio
|
||||
- File upload success rate
|
||||
|
||||
#### Business Metrics
|
||||
|
||||
- Avatar requests per minute
|
||||
- Popular avatar sizes
|
||||
- External service usage
|
||||
- User authentication success rate
|
||||
|
||||
#### Error Rates
|
||||
|
||||
- HTTP error rates by endpoint
|
||||
- File upload failures
|
||||
- External service failures
|
||||
- Authentication failures
|
||||
|
||||
### Example Alerts
|
||||
|
||||
#### High Error Rate
|
||||
|
||||
```yaml
|
||||
alert: HighErrorRate
|
||||
expr: rate(ivatar_requests_total{status_code=~"5.."}[5m]) > 0.1
|
||||
for: 2m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "High error rate detected"
|
||||
description: "Error rate is {{ $value }} errors per second"
|
||||
```
|
||||
|
||||
#### Slow Avatar Generation
|
||||
|
||||
```yaml
|
||||
alert: SlowAvatarGeneration
|
||||
expr: histogram_quantile(0.95, rate(ivatar_avatar_generation_seconds_bucket[5m])) > 2
|
||||
for: 5m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "Slow avatar generation"
|
||||
description: "95th percentile avatar generation time is {{ $value }}s"
|
||||
```
|
||||
|
||||
#### Low Cache Hit Ratio
|
||||
|
||||
```yaml
|
||||
alert: LowCacheHitRatio
|
||||
expr: (rate(ivatar_avatar_cache_hits_total[5m]) / (rate(ivatar_avatar_cache_hits_total[5m]) + rate(ivatar_avatar_cache_misses_total[5m]))) < 0.8
|
||||
for: 10m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "Low cache hit ratio"
|
||||
description: "Cache hit ratio is {{ $value }}"
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
#### OpenTelemetry Not Enabled
|
||||
|
||||
- Check `OTEL_ENABLED` environment variable
|
||||
- Verify OpenTelemetry packages are installed
|
||||
- Check Django logs for configuration errors
|
||||
|
||||
#### Metrics Not Appearing
|
||||
|
||||
- Verify Prometheus endpoint is accessible
|
||||
- Check collector configuration
|
||||
- Ensure metrics are being generated
|
||||
|
||||
#### Traces Not Showing
|
||||
|
||||
- Verify OTLP endpoint configuration
|
||||
- Check collector connectivity
|
||||
- Ensure tracing is enabled in configuration
|
||||
|
||||
#### High Memory Usage
|
||||
|
||||
- Adjust batch processor settings
|
||||
- Reduce trace sampling rate
|
||||
- Monitor collector resource usage
|
||||
|
||||
### Debug Mode
|
||||
|
||||
Enable debug logging for OpenTelemetry:
|
||||
|
||||
```python
|
||||
LOGGING = {
|
||||
"loggers": {
|
||||
"opentelemetry": {
|
||||
"level": "DEBUG",
|
||||
},
|
||||
"ivatar.opentelemetry": {
|
||||
"level": "DEBUG",
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Performance Considerations
|
||||
|
||||
- **Sampling**: Implement trace sampling for high-traffic production
|
||||
- **Batch Processing**: Use appropriate batch sizes for your infrastructure
|
||||
- **Resource Limits**: Monitor collector resource usage
|
||||
- **Network**: Ensure low-latency connections to collectors
|
||||
|
||||
## Security Considerations
|
||||
|
||||
- **Data Privacy**: Ensure no sensitive data in trace attributes
|
||||
- **Network Security**: Use TLS for collector communications
|
||||
- **Access Control**: Restrict access to metrics endpoints
|
||||
- **Data Retention**: Configure appropriate retention policies
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
- **Custom Dashboards**: Create Grafana dashboards for avatar metrics
|
||||
- **Advanced Sampling**: Implement intelligent trace sampling
|
||||
- **Log Correlation**: Correlate traces with application logs
|
||||
- **Performance Profiling**: Add profiling capabilities
|
||||
- **Custom Exports**: Export to additional backends (Datadog, New Relic)
|
||||
|
||||
## Support
|
||||
|
||||
For issues related to OpenTelemetry integration:
|
||||
|
||||
- Check application logs for configuration errors
|
||||
- Verify collector connectivity
|
||||
- Review Prometheus metrics for data flow
|
||||
- Consult OpenTelemetry documentation for advanced configuration
|
||||
431
OPENTELEMETRY_INFRASTRUCTURE.md
Normal file
431
OPENTELEMETRY_INFRASTRUCTURE.md
Normal file
@@ -0,0 +1,431 @@
|
||||
# OpenTelemetry Infrastructure Requirements
|
||||
|
||||
This document outlines the infrastructure requirements and deployment strategy for OpenTelemetry in the ivatar project, considering the existing Fedora Project hosting environment and multi-instance setup.
|
||||
|
||||
## Current Infrastructure Analysis
|
||||
|
||||
### Existing Monitoring Stack
|
||||
|
||||
- **Prometheus + Alertmanager**: Metrics collection and alerting
|
||||
- **Loki**: Log aggregation
|
||||
- **Alloy**: Observability data collection
|
||||
- **Grafana**: Visualization and dashboards
|
||||
- **Custom exporters**: Application-specific metrics
|
||||
|
||||
### Production Environment
|
||||
|
||||
- **Scale**: Millions of requests daily, 30k+ users, 33k+ avatar images
|
||||
- **Infrastructure**: Fedora Project hosted, high-performance system
|
||||
- **Architecture**: Apache HTTPD + Gunicorn containers + PostgreSQL
|
||||
- **Containerization**: Podman (not Docker)
|
||||
|
||||
### Multi-Instance Setup
|
||||
|
||||
- **Production**: Production environment (master branch)
|
||||
- **Development**: Development environment (devel branch)
|
||||
- **Deployment**: GitLab CI/CD with Puppet automation
|
||||
|
||||
## Infrastructure Options
|
||||
|
||||
### Option A: Extend Existing Alloy Stack (Recommended)
|
||||
|
||||
**Advantages:**
|
||||
|
||||
- Leverages existing infrastructure
|
||||
- Minimal additional complexity
|
||||
- Consistent with current monitoring approach
|
||||
- Cost-effective
|
||||
|
||||
**Implementation:**
|
||||
|
||||
```yaml
|
||||
# Alloy configuration extension
|
||||
otelcol.receiver.otlp:
|
||||
grpc:
|
||||
endpoint: 0.0.0.0:4317
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
|
||||
otelcol.processor.batch:
|
||||
timeout: 1s
|
||||
send_batch_size: 1024
|
||||
|
||||
otelcol.exporter.prometheus:
|
||||
endpoint: "0.0.0.0:9464"
|
||||
|
||||
otelcol.exporter.jaeger:
|
||||
endpoint: "jaeger-collector:14250"
|
||||
|
||||
otelcol.pipeline.traces:
|
||||
receivers: [otelcol.receiver.otlp]
|
||||
processors: [otelcol.processor.batch]
|
||||
exporters: [otelcol.exporter.jaeger]
|
||||
|
||||
otelcol.pipeline.metrics:
|
||||
receivers: [otelcol.receiver.otlp]
|
||||
processors: [otelcol.processor.batch]
|
||||
exporters: [otelcol.exporter.prometheus]
|
||||
```
|
||||
|
||||
### Option B: Dedicated OpenTelemetry Collector
|
||||
|
||||
**Advantages:**
|
||||
|
||||
- Full OpenTelemetry feature set
|
||||
- Better performance for high-volume tracing
|
||||
- More flexible configuration options
|
||||
- Future-proof architecture
|
||||
|
||||
**Implementation:**
|
||||
|
||||
- Deploy standalone OpenTelemetry Collector
|
||||
- Configure OTLP receivers and exporters
|
||||
- Integrate with existing Prometheus/Grafana
|
||||
|
||||
## Deployment Strategy
|
||||
|
||||
### Phase 1: Development Environment
|
||||
|
||||
1. **Enable OpenTelemetry in Development**
|
||||
|
||||
```bash
|
||||
# Development environment configuration
|
||||
export OTEL_ENABLED=true
|
||||
export OTEL_SERVICE_NAME=ivatar-development
|
||||
export OTEL_ENVIRONMENT=development
|
||||
export OTEL_EXPORTER_OTLP_ENDPOINT=http://collector.internal:4317
|
||||
export OTEL_PROMETHEUS_ENDPOINT=0.0.0.0:9464
|
||||
```
|
||||
|
||||
2. **Update Alloy Configuration**
|
||||
|
||||
- Add OTLP receivers to existing Alloy instance
|
||||
- Configure trace and metrics pipelines
|
||||
- Test data flow
|
||||
|
||||
3. **Verify Integration**
|
||||
- Check metrics endpoint: `http://dev-instance:9464/metrics`
|
||||
- Verify trace data in Jaeger
|
||||
- Monitor Grafana dashboards
|
||||
|
||||
### Phase 2: Production Deployment
|
||||
|
||||
1. **Production Configuration**
|
||||
|
||||
```bash
|
||||
# Production environment configuration
|
||||
export OTEL_ENABLED=true
|
||||
export OTEL_SERVICE_NAME=ivatar-production
|
||||
export OTEL_ENVIRONMENT=production
|
||||
export OTEL_EXPORTER_OTLP_ENDPOINT=http://collector.internal:4317
|
||||
export OTEL_PROMETHEUS_ENDPOINT=0.0.0.0:9464
|
||||
```
|
||||
|
||||
2. **Gradual Rollout**
|
||||
|
||||
- Deploy to one Gunicorn container first
|
||||
- Monitor performance impact
|
||||
- Gradually enable on all containers
|
||||
|
||||
3. **Performance Monitoring**
|
||||
- Monitor collector resource usage
|
||||
- Check application performance impact
|
||||
- Verify data quality
|
||||
|
||||
## Resource Requirements
|
||||
|
||||
### Collector Resources
|
||||
|
||||
**Minimum Requirements:**
|
||||
|
||||
- CPU: 2 cores
|
||||
- Memory: 4GB RAM
|
||||
- Storage: 10GB for temporary data
|
||||
- Network: 1Gbps
|
||||
|
||||
**Recommended for Production:**
|
||||
|
||||
- CPU: 4 cores
|
||||
- Memory: 8GB RAM
|
||||
- Storage: 50GB SSD
|
||||
- Network: 10Gbps
|
||||
|
||||
### Network Requirements
|
||||
|
||||
**Ports:**
|
||||
|
||||
- 4317: OTLP gRPC receiver
|
||||
- 4318: OTLP HTTP receiver
|
||||
- 9464: Prometheus metrics exporter
|
||||
- 14250: Jaeger trace exporter
|
||||
|
||||
**Bandwidth:**
|
||||
|
||||
- Estimated 1-5 Mbps per instance
|
||||
- Burst capacity for peak loads
|
||||
- Low-latency connection to collectors
|
||||
|
||||
## Configuration Management
|
||||
|
||||
### Environment-Specific Settings
|
||||
|
||||
#### Production Environment
|
||||
|
||||
```bash
|
||||
# Production OpenTelemetry configuration
|
||||
OTEL_ENABLED=true
|
||||
OTEL_SERVICE_NAME=ivatar-production
|
||||
OTEL_ENVIRONMENT=production
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=http://collector.internal:4317
|
||||
OTEL_PROMETHEUS_ENDPOINT=0.0.0.0:9464
|
||||
OTEL_SAMPLING_RATIO=0.1 # 10% sampling for high volume
|
||||
HOSTNAME=prod-instance-01
|
||||
```
|
||||
|
||||
#### Development Environment
|
||||
|
||||
```bash
|
||||
# Development OpenTelemetry configuration
|
||||
OTEL_ENABLED=true
|
||||
OTEL_SERVICE_NAME=ivatar-development
|
||||
OTEL_ENVIRONMENT=development
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=http://collector.internal:4317
|
||||
OTEL_PROMETHEUS_ENDPOINT=0.0.0.0:9464
|
||||
OTEL_SAMPLING_RATIO=1.0 # 100% sampling for debugging
|
||||
HOSTNAME=dev-instance-01
|
||||
```
|
||||
|
||||
### Container Configuration
|
||||
|
||||
#### Podman Container Updates
|
||||
|
||||
```dockerfile
|
||||
# Add to existing Dockerfile
|
||||
RUN pip install opentelemetry-api>=1.20.0 \
|
||||
opentelemetry-sdk>=1.20.0 \
|
||||
opentelemetry-instrumentation-django>=0.42b0 \
|
||||
opentelemetry-instrumentation-psycopg2>=0.42b0 \
|
||||
opentelemetry-instrumentation-pymysql>=0.42b0 \
|
||||
opentelemetry-instrumentation-requests>=0.42b0 \
|
||||
opentelemetry-instrumentation-urllib3>=0.42b0 \
|
||||
opentelemetry-exporter-otlp>=1.20.0 \
|
||||
opentelemetry-exporter-prometheus>=1.12.0rc1 \
|
||||
opentelemetry-instrumentation-memcached>=0.42b0
|
||||
```
|
||||
|
||||
#### Container Environment Variables
|
||||
|
||||
```bash
|
||||
# Add to container startup script
|
||||
export OTEL_ENABLED=${OTEL_ENABLED:-false}
|
||||
export OTEL_SERVICE_NAME=${OTEL_SERVICE_NAME:-ivatar}
|
||||
export OTEL_ENVIRONMENT=${OTEL_ENVIRONMENT:-development}
|
||||
export OTEL_EXPORTER_OTLP_ENDPOINT=${OTEL_EXPORTER_OTLP_ENDPOINT}
|
||||
export OTEL_PROMETHEUS_ENDPOINT=${OTEL_PROMETHEUS_ENDPOINT:-0.0.0.0:9464}
|
||||
```
|
||||
|
||||
## Monitoring and Alerting
|
||||
|
||||
### Collector Health Monitoring
|
||||
|
||||
#### Collector Metrics
|
||||
|
||||
- `otelcol_receiver_accepted_spans`: Spans received by collector
|
||||
- `otelcol_receiver_refused_spans`: Spans rejected by collector
|
||||
- `otelcol_exporter_sent_spans`: Spans sent to exporters
|
||||
- `otelcol_exporter_failed_spans`: Failed span exports
|
||||
|
||||
#### Health Checks
|
||||
|
||||
```yaml
|
||||
# Prometheus health check
|
||||
- job_name: "otel-collector-health"
|
||||
static_configs:
|
||||
- targets: ["collector.internal:8888"]
|
||||
metrics_path: /metrics
|
||||
scrape_interval: 30s
|
||||
```
|
||||
|
||||
### Application Performance Impact
|
||||
|
||||
#### Key Metrics to Monitor
|
||||
|
||||
- Application response time impact
|
||||
- Memory usage increase
|
||||
- CPU usage increase
|
||||
- Network bandwidth usage
|
||||
|
||||
#### Alerting Rules
|
||||
|
||||
```yaml
|
||||
# High collector resource usage
|
||||
alert: HighCollectorCPU
|
||||
expr: rate(otelcol_process_cpu_seconds_total[5m]) > 0.8
|
||||
for: 5m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "High collector CPU usage"
|
||||
description: "Collector CPU usage is {{ $value }}"
|
||||
|
||||
# Collector memory usage
|
||||
alert: HighCollectorMemory
|
||||
expr: otelcol_process_memory_usage_bytes / otelcol_process_memory_limit_bytes > 0.8
|
||||
for: 5m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "High collector memory usage"
|
||||
description: "Collector memory usage is {{ $value }}"
|
||||
```
|
||||
|
||||
## Security Considerations
|
||||
|
||||
### Network Security
|
||||
|
||||
- Use TLS for collector communications
|
||||
- Restrict collector access to trusted networks
|
||||
- Implement proper firewall rules
|
||||
|
||||
### Data Privacy
|
||||
|
||||
- Ensure no sensitive data in trace attributes
|
||||
- Implement data sanitization
|
||||
- Configure appropriate retention policies
|
||||
|
||||
### Access Control
|
||||
|
||||
- Restrict access to metrics endpoints
|
||||
- Implement authentication for collector access
|
||||
- Monitor access logs
|
||||
|
||||
## Backup and Recovery
|
||||
|
||||
### Data Retention
|
||||
|
||||
- Traces: 7 days (configurable)
|
||||
- Metrics: 30 days (configurable)
|
||||
- Logs: 14 days (configurable)
|
||||
|
||||
### Backup Strategy
|
||||
|
||||
- Regular backup of collector configuration
|
||||
- Backup of Grafana dashboards
|
||||
- Backup of Prometheus rules
|
||||
|
||||
## Performance Optimization
|
||||
|
||||
### Sampling Strategy
|
||||
|
||||
- Production: 10% sampling rate
|
||||
- Development: 100% sampling rate
|
||||
- Error traces: Always sample
|
||||
|
||||
### Batch Processing
|
||||
|
||||
- Optimize batch sizes for network conditions
|
||||
- Configure appropriate timeouts
|
||||
- Monitor queue depths
|
||||
|
||||
### Resource Optimization
|
||||
|
||||
- Monitor collector resource usage
|
||||
- Scale collectors based on load
|
||||
- Implement horizontal scaling if needed
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
#### Collector Not Receiving Data
|
||||
|
||||
- Check network connectivity
|
||||
- Verify OTLP endpoint configuration
|
||||
- Check collector logs
|
||||
|
||||
#### High Resource Usage
|
||||
|
||||
- Adjust sampling rates
|
||||
- Optimize batch processing
|
||||
- Scale collector resources
|
||||
|
||||
#### Data Quality Issues
|
||||
|
||||
- Verify instrumentation configuration
|
||||
- Check span attribute quality
|
||||
- Monitor error rates
|
||||
|
||||
### Debug Procedures
|
||||
|
||||
1. **Check Collector Status**
|
||||
|
||||
```bash
|
||||
curl http://collector.internal:8888/metrics
|
||||
```
|
||||
|
||||
2. **Verify Application Configuration**
|
||||
|
||||
```bash
|
||||
curl http://app:9464/metrics
|
||||
```
|
||||
|
||||
3. **Check Trace Data**
|
||||
- Access Jaeger UI
|
||||
- Search for recent traces
|
||||
- Verify span attributes
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
### Advanced Features
|
||||
|
||||
- Custom dashboards for avatar metrics
|
||||
- Advanced sampling strategies
|
||||
- Log correlation with traces
|
||||
- Performance profiling integration
|
||||
|
||||
### Scalability Improvements
|
||||
|
||||
- Horizontal collector scaling
|
||||
- Load balancing for collectors
|
||||
- Multi-region deployment
|
||||
- Edge collection points
|
||||
|
||||
### Integration Enhancements
|
||||
|
||||
- Additional exporter backends
|
||||
- Custom processors
|
||||
- Advanced filtering
|
||||
- Data transformation
|
||||
|
||||
## Cost Considerations
|
||||
|
||||
### Infrastructure Costs
|
||||
|
||||
- Additional compute resources for collectors
|
||||
- Storage costs for trace data
|
||||
- Network bandwidth costs
|
||||
|
||||
### Operational Costs
|
||||
|
||||
- Monitoring and maintenance
|
||||
- Configuration management
|
||||
- Troubleshooting and support
|
||||
|
||||
### Optimization Strategies
|
||||
|
||||
- Implement efficient sampling
|
||||
- Use appropriate retention policies
|
||||
- Optimize batch processing
|
||||
- Monitor resource usage
|
||||
|
||||
## Conclusion
|
||||
|
||||
The OpenTelemetry integration for ivatar provides comprehensive observability while leveraging the existing monitoring infrastructure. The phased deployment approach ensures minimal disruption to production services while providing valuable insights into avatar generation performance and user behavior.
|
||||
|
||||
Key success factors:
|
||||
|
||||
- Gradual rollout with monitoring
|
||||
- Performance impact assessment
|
||||
- Proper resource planning
|
||||
- Security considerations
|
||||
- Ongoing optimization
|
||||
102
README.md
102
README.md
@@ -1,20 +1,102 @@
|
||||
ivatar / libravatar
|
||||
===================
|
||||
# ivatar / libravatar
|
||||
|
||||
Pipeline and coverage status
|
||||
============================
|
||||
# Pipeline and coverage status
|
||||
|
||||
[](https://git.linux-kernel.at/oliver/ivatar/commits/master)
|
||||
[](http://git.linux-kernel.at/oliver/ivatar/commits/master)
|
||||
|
||||
Reports / code documentation
|
||||
============================
|
||||
# Reports / code documentation
|
||||
|
||||
- [Coverage HTML report](http://oliver.git.linux-kernel.at/ivatar)
|
||||
- [Code documentation (autogenerated, pycco)](http://oliver.git.linux-kernel.at/ivatar/pycco/)
|
||||
- [Coverage HTML report](http://oliver.git.linux-kernel.at/ivatar)
|
||||
- [Code documentation (autogenerated, pycco)](http://oliver.git.linux-kernel.at/ivatar/pycco/)
|
||||
|
||||
Authors and contributors
|
||||
========================
|
||||
# Environment Variables
|
||||
|
||||
## OpenTelemetry Configuration
|
||||
|
||||
OpenTelemetry instrumentation is always enabled in ivatar. The following environment variables control the behavior:
|
||||
|
||||
### Core Configuration
|
||||
|
||||
- `OTEL_SERVICE_NAME`: Service name for OpenTelemetry (default: "ivatar")
|
||||
- `OTEL_ENVIRONMENT`: Deployment environment (default: "production")
|
||||
- `OTEL_EXPORT_ENABLED`: Enable/disable data export (default: "false")
|
||||
- Set to "true" to enable sending telemetry data to external collectors
|
||||
- Set to "false" to disable export (instrumentation still active)
|
||||
|
||||
### Export Configuration
|
||||
|
||||
- `OTEL_EXPORTER_OTLP_ENDPOINT`: OTLP endpoint for traces and metrics export
|
||||
- Example: "http://localhost:4317" (gRPC) or "http://localhost:4318" (HTTP)
|
||||
- `OTEL_PROMETHEUS_ENDPOINT`: Prometheus metrics endpoint (default: "0.0.0.0:9464")
|
||||
|
||||
## Example Configurations
|
||||
|
||||
### Development (Export Disabled)
|
||||
|
||||
```bash
|
||||
export OTEL_EXPORT_ENABLED=false
|
||||
export OTEL_SERVICE_NAME=ivatar-dev
|
||||
export OTEL_ENVIRONMENT=development
|
||||
```
|
||||
|
||||
### Production (Export Enabled)
|
||||
|
||||
```bash
|
||||
export OTEL_EXPORT_ENABLED=true
|
||||
export OTEL_SERVICE_NAME=ivatar
|
||||
export OTEL_ENVIRONMENT=production
|
||||
export OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317
|
||||
```
|
||||
|
||||
# Testing
|
||||
|
||||
## Running Tests
|
||||
|
||||
### Local Development (Recommended)
|
||||
|
||||
For local development, use the provided script to skip Bluesky tests that require external API credentials:
|
||||
|
||||
```bash
|
||||
./scripts/run_tests_local.sh
|
||||
```
|
||||
|
||||
This runs all tests except those marked with `@pytest.mark.bluesky`.
|
||||
|
||||
### All Tests
|
||||
|
||||
To run all tests including Bluesky tests (requires Bluesky API credentials):
|
||||
|
||||
```bash
|
||||
python3 manage.py test -v3
|
||||
```
|
||||
|
||||
### Specific Test Categories
|
||||
|
||||
```bash
|
||||
# Run only Bluesky tests
|
||||
python3 manage.py test ivatar.ivataraccount.test_views_bluesky -v3
|
||||
|
||||
# Run only file upload security tests
|
||||
python3 manage.py test ivatar.test_file_security -v3
|
||||
|
||||
# Run only security fixes tests (ETag sanitization and URL validation)
|
||||
python3 manage.py test ivatar.test_security_fixes -v3
|
||||
|
||||
# Run only upload tests
|
||||
python3 manage.py test ivatar.ivataraccount.test_views -v3
|
||||
```
|
||||
|
||||
## Test Markers
|
||||
|
||||
Tests are categorized using pytest markers:
|
||||
|
||||
- `@pytest.mark.bluesky`: Tests requiring Bluesky API credentials
|
||||
- `@pytest.mark.slow`: Long-running tests
|
||||
- `@pytest.mark.integration`: Integration tests
|
||||
- `@pytest.mark.unit`: Unit tests
|
||||
|
||||
# Authors and contributors
|
||||
|
||||
Lead developer/Owner: Oliver Falk (aka ofalk or falko) - https://git.linux-kernel.at/oliver
|
||||
|
||||
|
||||
357
config.py
357
config.py
@@ -1,11 +1,11 @@
|
||||
''' yes
|
||||
"""
|
||||
Configuration overrides for settings.py
|
||||
'''
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from django.urls import reverse_lazy
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django.contrib.messages import constants as message_constants
|
||||
from ivatar.settings import BASE_DIR
|
||||
|
||||
@@ -14,50 +14,69 @@ from ivatar.settings import INSTALLED_APPS
|
||||
from ivatar.settings import TEMPLATES
|
||||
|
||||
ADMIN_USERS = []
|
||||
ALLOWED_HOSTS = ['*']
|
||||
ALLOWED_HOSTS = ["*"]
|
||||
|
||||
INSTALLED_APPS.extend([
|
||||
'django_extensions',
|
||||
'django_openid_auth',
|
||||
'bootstrap4',
|
||||
'anymail',
|
||||
'ivatar',
|
||||
'ivatar.ivataraccount',
|
||||
'ivatar.tools',
|
||||
])
|
||||
INSTALLED_APPS.extend(
|
||||
[
|
||||
"django_extensions",
|
||||
"django_openid_auth",
|
||||
"bootstrap4",
|
||||
"anymail",
|
||||
"ivatar",
|
||||
"ivatar.ivataraccount",
|
||||
"ivatar.tools",
|
||||
]
|
||||
)
|
||||
|
||||
MIDDLEWARE.extend([
|
||||
'django.middleware.locale.LocaleMiddleware',
|
||||
])
|
||||
MIDDLEWARE.extend(
|
||||
[
|
||||
"ivatar.middleware.CustomLocaleMiddleware",
|
||||
]
|
||||
)
|
||||
|
||||
# Add OpenTelemetry middleware only if feature flag is enabled
|
||||
# Note: This will be checked at runtime, not at import time
|
||||
MIDDLEWARE.insert(
|
||||
0, 'ivatar.middleware.MultipleProxyMiddleware',
|
||||
0,
|
||||
"ivatar.middleware.MultipleProxyMiddleware",
|
||||
)
|
||||
|
||||
AUTHENTICATION_BACKENDS = (
|
||||
# Enable this to allow LDAP authentication.
|
||||
# See INSTALL for more information.
|
||||
# 'django_auth_ldap.backend.LDAPBackend',
|
||||
'django_openid_auth.auth.OpenIDBackend',
|
||||
'django.contrib.auth.backends.ModelBackend',
|
||||
"django_openid_auth.auth.OpenIDBackend",
|
||||
"ivatar.ivataraccount.auth.FedoraOpenIdConnect",
|
||||
"django.contrib.auth.backends.ModelBackend",
|
||||
)
|
||||
|
||||
TEMPLATES[0]['DIRS'].extend([
|
||||
os.path.join(BASE_DIR, 'templates'),
|
||||
])
|
||||
TEMPLATES[0]['OPTIONS']['context_processors'].append(
|
||||
'ivatar.context_processors.basepage',
|
||||
TEMPLATES[0]["DIRS"].extend(
|
||||
[
|
||||
os.path.join(BASE_DIR, "templates"),
|
||||
]
|
||||
)
|
||||
TEMPLATES[0]["OPTIONS"]["context_processors"].append(
|
||||
"ivatar.context_processors.basepage",
|
||||
)
|
||||
|
||||
OPENID_CREATE_USERS = True
|
||||
OPENID_UPDATE_DETAILS_FROM_SREG = True
|
||||
SOCIAL_AUTH_JSONFIELD_ENABLED = True
|
||||
# Fedora authentication (OIDC). You need to set these two values to use it.
|
||||
SOCIAL_AUTH_FEDORA_KEY = None # Also known as client_id
|
||||
SOCIAL_AUTH_FEDORA_SECRET = None # Also known as client_secret
|
||||
|
||||
SITE_NAME = os.environ.get('SITE_NAME', 'libravatar')
|
||||
IVATAR_VERSION = '1.3'
|
||||
SITE_NAME = os.environ.get("SITE_NAME", "libravatar")
|
||||
IVATAR_VERSION = "2.0"
|
||||
|
||||
SECURE_BASE_URL = os.environ.get('SECURE_BASE_URL', 'https://avatars.linux-kernel.at/avatar/')
|
||||
BASE_URL = os.environ.get('BASE_URL', 'http://avatars.linux-kernel.at/avatar/')
|
||||
SCHEMAROOT = "https://www.libravatar.org/schemas/export/0.2"
|
||||
|
||||
LOGIN_REDIRECT_URL = reverse_lazy('profile')
|
||||
SECURE_BASE_URL = os.environ.get(
|
||||
"SECURE_BASE_URL", "https://avatars.linux-kernel.at/avatar/"
|
||||
)
|
||||
BASE_URL = os.environ.get("BASE_URL", "http://avatars.linux-kernel.at/avatar/")
|
||||
|
||||
LOGIN_REDIRECT_URL = reverse_lazy("profile")
|
||||
MAX_LENGTH_EMAIL = 254 # http://stackoverflow.com/questions/386294
|
||||
|
||||
MAX_NUM_PHOTOS = 5
|
||||
@@ -67,6 +86,18 @@ MAX_PIXELS = 7000
|
||||
AVATAR_MAX_SIZE = 512
|
||||
JPEG_QUALITY = 85
|
||||
|
||||
# Robohash Performance Optimization
|
||||
# Enable optimized robohash implementation for 6-22x performance improvement
|
||||
ROBOHASH_OPTIMIZATION_ENABLED = True
|
||||
|
||||
# Robohash Configuration
|
||||
# Maximum number of robot parts to cache in memory (each ~50-200KB)
|
||||
ROBOHASH_CACHE_SIZE = 150 # ~10-30MB total cache size
|
||||
|
||||
# Pagan Avatar Optimization
|
||||
# Maximum number of pagan Avatar objects to cache in memory (each ~100-500KB)
|
||||
PAGAN_CACHE_SIZE = 100 # ~10-50MB total cache size
|
||||
|
||||
# I'm not 100% sure if single character domains are possible
|
||||
# under any tld... so MIN_LENGTH_EMAIL/_URL, might be +1
|
||||
MIN_LENGTH_URL = 11 # eg. http://a.io
|
||||
@@ -75,119 +106,233 @@ MIN_LENGTH_EMAIL = 6 # eg. x@x.xx
|
||||
MAX_LENGTH_EMAIL = 254 # http://stackoverflow.com/questions/386294
|
||||
|
||||
BOOTSTRAP4 = {
|
||||
'include_jquery': False,
|
||||
'javascript_in_head': False,
|
||||
'css_url': {
|
||||
'href': '/static/css/bootstrap.min.css',
|
||||
'integrity':
|
||||
'sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB',
|
||||
'crossorigin': 'anonymous',
|
||||
"include_jquery": False,
|
||||
"javascript_in_head": False,
|
||||
"css_url": {
|
||||
"href": "/static/css/bootstrap.min.css",
|
||||
"integrity": "sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB",
|
||||
"crossorigin": "anonymous",
|
||||
},
|
||||
'javascript_url': {
|
||||
'url': '/static/js/bootstrap.min.js',
|
||||
'integrity': '',
|
||||
'crossorigin': 'anonymous',
|
||||
"javascript_url": {
|
||||
"url": "/static/js/bootstrap.min.js",
|
||||
"integrity": "",
|
||||
"crossorigin": "anonymous",
|
||||
},
|
||||
'popper_url': {
|
||||
'url': '/static/js/popper.min.js',
|
||||
'integrity':
|
||||
'sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49',
|
||||
'crossorigin': 'anonymous',
|
||||
"popper_url": {
|
||||
"url": "/static/js/popper.min.js",
|
||||
"integrity": "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49",
|
||||
"crossorigin": "anonymous",
|
||||
},
|
||||
}
|
||||
|
||||
if 'EMAIL_BACKEND' in os.environ:
|
||||
EMAIL_BACKEND = os.environ['EMAIL_BACKEND'] # pragma: no cover
|
||||
if "EMAIL_BACKEND" in os.environ:
|
||||
EMAIL_BACKEND = os.environ["EMAIL_BACKEND"] # pragma: no cover
|
||||
else:
|
||||
if 'test' in sys.argv or 'collectstatic' in sys.argv:
|
||||
EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'
|
||||
if "test" in sys.argv or "collectstatic" in sys.argv:
|
||||
EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend"
|
||||
else:
|
||||
try:
|
||||
ANYMAIL = { # pragma: no cover
|
||||
'MAILGUN_API_KEY': os.environ['IVATAR_MAILGUN_API_KEY'],
|
||||
'MAILGUN_SENDER_DOMAIN': os.environ['IVATAR_MAILGUN_SENDER_DOMAIN'],
|
||||
"MAILGUN_API_KEY": os.environ["IVATAR_MAILGUN_API_KEY"],
|
||||
"MAILGUN_SENDER_DOMAIN": os.environ["IVATAR_MAILGUN_SENDER_DOMAIN"],
|
||||
}
|
||||
EMAIL_BACKEND = 'anymail.backends.mailgun.EmailBackend' # pragma: no cover
|
||||
except Exception as exc:
|
||||
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
|
||||
EMAIL_BACKEND = "anymail.backends.mailgun.EmailBackend" # pragma: no cover
|
||||
except Exception: # pragma: nocover # pylint: disable=broad-except
|
||||
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
|
||||
|
||||
SERVER_EMAIL = os.environ.get('SERVER_EMAIL', 'ivatar@mg.linux-kernel.at')
|
||||
DEFAULT_FROM_EMAIL = os.environ.get('DEFAULT_FROM_EMAIL', 'ivatar@mg.linux-kernel.at')
|
||||
SERVER_EMAIL = os.environ.get("SERVER_EMAIL", "ivatar@mg.linux-kernel.at")
|
||||
DEFAULT_FROM_EMAIL = os.environ.get("DEFAULT_FROM_EMAIL", "ivatar@mg.linux-kernel.at")
|
||||
|
||||
try:
|
||||
from ivatar.settings import DATABASES
|
||||
except ImportError: # pragma: no cover
|
||||
DATABASES = [] # pragma: no cover
|
||||
|
||||
if 'default' not in DATABASES:
|
||||
DATABASES['default'] = { # pragma: no cover
|
||||
'ENGINE': 'django.db.backends.sqlite3',
|
||||
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
|
||||
if "default" not in DATABASES:
|
||||
DATABASES["default"] = { # pragma: no cover
|
||||
"ENGINE": "django.db.backends.sqlite3",
|
||||
"NAME": os.path.join(BASE_DIR, "db.sqlite3"),
|
||||
}
|
||||
|
||||
if 'MYSQL_DATABASE' in os.environ:
|
||||
DATABASES['default'] = { # pragma: no cover
|
||||
'ENGINE': 'django.db.backends.mysql',
|
||||
'NAME': os.environ['MYSQL_DATABASE'],
|
||||
'USER': os.environ['MYSQL_USER'],
|
||||
'PASSWORD': os.environ['MYSQL_PASSWORD'],
|
||||
'HOST': 'mysql',
|
||||
if "MYSQL_DATABASE" in os.environ:
|
||||
DATABASES["default"] = { # pragma: no cover
|
||||
"ENGINE": "django.db.backends.mysql",
|
||||
"NAME": os.environ["MYSQL_DATABASE"],
|
||||
"USER": os.environ["MYSQL_USER"],
|
||||
"PASSWORD": os.environ["MYSQL_PASSWORD"],
|
||||
"HOST": "mysql",
|
||||
}
|
||||
|
||||
if 'POSTGRESQL_DATABASE' in os.environ:
|
||||
DATABASES['default'] = { # pragma: no cover
|
||||
'ENGINE': 'django.db.backends.postgresql',
|
||||
'NAME': os.environ['POSTGRESQL_DATABASE'],
|
||||
'USER': os.environ['POSTGRESQL_USER'],
|
||||
'PASSWORD': os.environ['POSTGRESQL_PASSWORD'],
|
||||
'HOST': 'postgresql',
|
||||
if "POSTGRESQL_DATABASE" in os.environ:
|
||||
DATABASES["default"] = { # pragma: no cover
|
||||
"ENGINE": "django.db.backends.postgresql",
|
||||
"NAME": os.environ["POSTGRESQL_DATABASE"],
|
||||
"USER": os.environ["POSTGRESQL_USER"],
|
||||
"PASSWORD": os.environ["POSTGRESQL_PASSWORD"],
|
||||
"HOST": "postgresql",
|
||||
}
|
||||
|
||||
if os.path.isfile(os.path.join(BASE_DIR, 'config_local.py')):
|
||||
from config_local import * # noqa # flake8: noqa # NOQA # pragma: no cover
|
||||
# CI/CD config has different naming
|
||||
if "POSTGRES_DB" in os.environ:
|
||||
DATABASES["default"] = { # pragma: no cover
|
||||
"ENGINE": "django.db.backends.postgresql",
|
||||
"NAME": os.environ["POSTGRES_DB"],
|
||||
"USER": os.environ["POSTGRES_USER"],
|
||||
"PASSWORD": os.environ["POSTGRES_PASSWORD"],
|
||||
"HOST": os.environ["POSTGRES_HOST"],
|
||||
# Let Django use its default test database naming
|
||||
# "TEST": {
|
||||
# "NAME": os.environ["POSTGRES_DB"],
|
||||
# },
|
||||
}
|
||||
|
||||
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
|
||||
SESSION_SERIALIZER = "django.contrib.sessions.serializers.JSONSerializer"
|
||||
|
||||
USE_X_FORWARDED_HOST = True
|
||||
ALLOWED_EXTERNAL_OPENID_REDIRECT_DOMAINS = ['avatars.linux-kernel.at', 'localhost',]
|
||||
ALLOWED_EXTERNAL_OPENID_REDIRECT_DOMAINS = [
|
||||
"avatars.linux-kernel.at",
|
||||
"localhost",
|
||||
]
|
||||
|
||||
DEFAULT_AVATAR_SIZE = 80
|
||||
|
||||
LANGUAGES = (
|
||||
('de', _('Deutsch')),
|
||||
('en', _('English')),
|
||||
('ca', _('Català')),
|
||||
('cs', _('Česky')),
|
||||
('es', _('Español')),
|
||||
('eu', _('Basque')),
|
||||
('fr', _('Français')),
|
||||
('it', _('Italiano')),
|
||||
('ja', _('日本語')),
|
||||
('nl', _('Nederlands')),
|
||||
('pt', _('Português')),
|
||||
('ru', _('Русский')),
|
||||
('sq', _('Shqip')),
|
||||
('tr', _('Türkçe')),
|
||||
('uk', _('Українська')),
|
||||
# Default settings for Gravatar proxy and redirect behavior
|
||||
# These can be overridden by URL parameters
|
||||
DEFAULT_GRAVATARPROXY = True
|
||||
DEFAULT_GRAVATARREDIRECT = False
|
||||
FORCEDEFAULT = False
|
||||
|
||||
LANGUAGES = (
|
||||
("de", _("Deutsch")),
|
||||
("en", _("English")),
|
||||
("ca", _("Català")),
|
||||
("cs", _("Česky")),
|
||||
("es", _("Español")),
|
||||
("eu", _("Basque")),
|
||||
("fr", _("Français")),
|
||||
("it", _("Italiano")),
|
||||
("ja", _("日本語")),
|
||||
("nl", _("Nederlands")),
|
||||
("pt", _("Português")),
|
||||
("ru", _("Русский")),
|
||||
("sq", _("Shqip")),
|
||||
("tr", _("Türkçe")),
|
||||
("uk", _("Українська")),
|
||||
)
|
||||
|
||||
MESSAGE_TAGS = {
|
||||
message_constants.DEBUG: 'debug',
|
||||
message_constants.INFO: 'info',
|
||||
message_constants.SUCCESS: 'success',
|
||||
message_constants.WARNING: 'warning',
|
||||
message_constants.ERROR: 'danger',
|
||||
message_constants.DEBUG: "debug",
|
||||
message_constants.INFO: "info",
|
||||
message_constants.SUCCESS: "success",
|
||||
message_constants.WARNING: "warning",
|
||||
message_constants.ERROR: "danger",
|
||||
}
|
||||
|
||||
CACHES = {
|
||||
'default': {
|
||||
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
|
||||
'LOCATION': [
|
||||
'127.0.0.1:11211',
|
||||
],
|
||||
}
|
||||
"default": {
|
||||
"BACKEND": "django.core.cache.backends.memcached.PyMemcacheCache",
|
||||
"LOCATION": [
|
||||
"127.0.0.1:11211",
|
||||
],
|
||||
# "OPTIONS": {"MAX_ENTRIES": 1000000},
|
||||
},
|
||||
"filesystem": {
|
||||
"BACKEND": "django.core.cache.backends.filebased.FileBasedCache",
|
||||
"LOCATION": "/var/tmp/ivatar_cache",
|
||||
"TIMEOUT": 900, # 15 minutes
|
||||
"OPTIONS": {"MAX_ENTRIES": 1000000},
|
||||
},
|
||||
}
|
||||
|
||||
# This is 5 minutes caching for generated/resized images,
|
||||
# so the sites don't hit ivatar so much
|
||||
# so the sites don't hit ivatar so much - it's what's set in the HTTP header
|
||||
CACHE_IMAGES_MAX_AGE = 5 * 60
|
||||
|
||||
CACHE_RESPONSE = True
|
||||
|
||||
# Trusted URLs for default redirection
|
||||
TRUSTED_DEFAULT_URLS = [
|
||||
{"schemes": ["https"], "host_equals": "ui-avatars.com", "path_prefix": "/api/"},
|
||||
{
|
||||
"schemes": ["http", "https"],
|
||||
"host_equals": "gravatar.com",
|
||||
"path_prefix": "/avatar/",
|
||||
},
|
||||
{
|
||||
"schemes": ["http", "https"],
|
||||
"host_suffix": ".gravatar.com",
|
||||
"path_prefix": "/avatar/",
|
||||
},
|
||||
{
|
||||
"schemes": ["http", "https"],
|
||||
"host_equals": "www.gravatar.org",
|
||||
"path_prefix": "/avatar/",
|
||||
},
|
||||
{
|
||||
"schemes": ["https"],
|
||||
"host_equals": "avatars.dicebear.com",
|
||||
"path_prefix": "/api/",
|
||||
},
|
||||
{
|
||||
"schemes": ["https"],
|
||||
"host_equals": "api.dicebear.com",
|
||||
"path_prefix": "/",
|
||||
},
|
||||
{
|
||||
"schemes": ["https"],
|
||||
"host_equals": "badges.fedoraproject.org",
|
||||
"path_prefix": "/static/img/",
|
||||
},
|
||||
{
|
||||
"schemes": ["http"],
|
||||
"host_equals": "www.planet-libre.org",
|
||||
"path_prefix": "/themes/planetlibre/images/",
|
||||
},
|
||||
{"schemes": ["https"], "host_equals": "www.azuracast.com", "path_prefix": "/img/"},
|
||||
{
|
||||
"schemes": ["https"],
|
||||
"host_equals": "reps.mozilla.org",
|
||||
"path_prefix": "/static/base/img/remo/",
|
||||
},
|
||||
]
|
||||
|
||||
URL_TIMEOUT = 10
|
||||
|
||||
|
||||
def map_legacy_config(trusted_url):
|
||||
"""
|
||||
For backward compability with the legacy configuration
|
||||
for trusting URLs. Adapts them to fit the new config.
|
||||
"""
|
||||
if isinstance(trusted_url, str):
|
||||
return {"url_prefix": trusted_url}
|
||||
|
||||
return trusted_url
|
||||
|
||||
|
||||
# Backward compability for legacy behavior
|
||||
TRUSTED_DEFAULT_URLS = list(map(map_legacy_config, TRUSTED_DEFAULT_URLS))
|
||||
|
||||
# Bluesky settings
|
||||
BLUESKY_IDENTIFIER = os.environ.get("BLUESKY_IDENTIFIER", None)
|
||||
BLUESKY_APP_PASSWORD = os.environ.get("BLUESKY_APP_PASSWORD", None)
|
||||
|
||||
# File upload security settings
|
||||
FILE_UPLOAD_MAX_MEMORY_SIZE = 5 * 1024 * 1024 # 5MB
|
||||
DATA_UPLOAD_MAX_MEMORY_SIZE = 5 * 1024 * 1024 # 5MB
|
||||
FILE_UPLOAD_PERMISSIONS = 0o644
|
||||
|
||||
# Enhanced file upload security
|
||||
ENABLE_FILE_SECURITY_VALIDATION = True
|
||||
ENABLE_EXIF_SANITIZATION = True
|
||||
ENABLE_MALICIOUS_CONTENT_SCAN = True
|
||||
|
||||
# Avatar optimization settings
|
||||
PAGAN_CACHE_SIZE = 1000 # Number of pagan avatars to cache
|
||||
|
||||
# Logging configuration - can be overridden in local config
|
||||
# Example: LOGS_DIR = "/var/log/ivatar" # For production deployments
|
||||
|
||||
# This MUST BE THE LAST!
|
||||
if os.path.isfile(os.path.join(BASE_DIR, "config_local.py")):
|
||||
from config_local import * # noqa # flake8: noqa # NOQA # pragma: no cover
|
||||
|
||||
65
config_local.py.example
Normal file
65
config_local.py.example
Normal file
@@ -0,0 +1,65 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Example local configuration file for ivatar
|
||||
Copy this to config_local.py and customize for your environment
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
# Override logs directory for production deployments
|
||||
# LOGS_DIR = "/var/log/ivatar"
|
||||
|
||||
# Override logs directory for development with custom location
|
||||
# LOGS_DIR = os.path.join(os.path.expanduser("~"), "ivatar_logs")
|
||||
|
||||
# File upload security settings
|
||||
# ENABLE_FILE_SECURITY_VALIDATION = True
|
||||
# ENABLE_EXIF_SANITIZATION = True
|
||||
# ENABLE_MALICIOUS_CONTENT_SCAN = True
|
||||
|
||||
# Example production overrides:
|
||||
# DEBUG = False
|
||||
# SECRET_KEY = "your-production-secret-key-here"
|
||||
# ALLOWED_HOSTS = ["yourdomain.com", "www.yourdomain.com"]
|
||||
|
||||
# Database configuration (if not using environment variables)
|
||||
# DATABASES = {
|
||||
# 'default': {
|
||||
# 'ENGINE': 'django.db.backends.postgresql',
|
||||
# 'NAME': 'ivatar_prod',
|
||||
# 'USER': 'ivatar_user',
|
||||
# 'PASSWORD': 'your-db-password',
|
||||
# 'HOST': 'localhost',
|
||||
# 'PORT': '5432',
|
||||
# }
|
||||
# }
|
||||
|
||||
# Email configuration
|
||||
# EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
|
||||
# EMAIL_HOST = 'smtp.yourdomain.com'
|
||||
# EMAIL_PORT = 587
|
||||
# EMAIL_USE_TLS = True
|
||||
# EMAIL_HOST_USER = 'noreply@yourdomain.com'
|
||||
# EMAIL_HOST_PASSWORD = 'your-email-password'
|
||||
|
||||
# Example: Override logs directory for production
|
||||
# LOGS_DIR = "/var/log/ivatar"
|
||||
|
||||
# Bluesky integration credentials
|
||||
# BLUESKY_IDENTIFIER = "your-bluesky-handle"
|
||||
# BLUESKY_APP_PASSWORD = "your-app-password"
|
||||
|
||||
# Gravatar proxy and redirect settings
|
||||
# These control the default behavior when no local avatar is found
|
||||
# URL parameters (?gravatarproxy=n&gravatarredirect=y) will override these defaults
|
||||
|
||||
# For private/local instances that should not make external requests:
|
||||
# DEFAULT_GRAVATARPROXY = False
|
||||
# DEFAULT_GRAVATARREDIRECT = False
|
||||
|
||||
# For instances that prefer direct Gravatar redirects:
|
||||
# DEFAULT_GRAVATARREDIRECT = True
|
||||
# DEFAULT_GRAVATARPROXY = False
|
||||
|
||||
# For testing/development (always use default avatars):
|
||||
# FORCEDEFAULT = True
|
||||
2
config_local_test.py
Normal file
2
config_local_test.py
Normal file
@@ -0,0 +1,2 @@
|
||||
# Test configuration to verify LOGS_DIR override
|
||||
LOGS_DIR = "/tmp/ivatar_test_logs"
|
||||
@@ -1,6 +1,6 @@
|
||||
.stats span.mis {
|
||||
background: #faa;
|
||||
background: #faa;
|
||||
}
|
||||
.text p.mis {
|
||||
background: #faa;
|
||||
background: #faa;
|
||||
}
|
||||
|
||||
14
create.sh
14
create.sh
@@ -2,11 +2,11 @@
|
||||
|
||||
oc new-project ivatar
|
||||
|
||||
DB_PASSWORD=`openssl rand -base64 16`
|
||||
DB_ROOT_PASSWORD=`openssl rand -base64 16`
|
||||
DB_PASSWORD=$(openssl rand -base64 16)
|
||||
DB_ROOT_PASSWORD=$(openssl rand -base64 16)
|
||||
|
||||
if [ -n "$USE_MYSQL" ]; then
|
||||
DB_CMDLINE="mysql-persistent
|
||||
DB_CMDLINE="mysql-persistent
|
||||
--group=python+mysql-persistent
|
||||
-e MYSQL_USER=ivatar
|
||||
-p MYSQL_USER=ivatar
|
||||
@@ -17,7 +17,7 @@ if [ -n "$USE_MYSQL" ]; then
|
||||
-e MYSQL_ROOT_PASSWORD=$DB_ROOT_PASSWORD
|
||||
-p MYSQL_ROOT_PASSWORD=$DB_ROOT_PASSWORD"
|
||||
else
|
||||
DB_CMDLINE="postgresql-persistent
|
||||
DB_CMDLINE="postgresql-persistent
|
||||
-e POSTGRESQL_USER=ivatar
|
||||
-p POSTGRESQL_USER=ivatar
|
||||
-e POSTGRESQL_DATABASE=ivatar
|
||||
@@ -35,8 +35,8 @@ if [ -n "$LKERNAT_GITLAB_OPENSHIFT_ACCESS_TOKEN" ]; then
|
||||
fi
|
||||
|
||||
oc new-app $SECRET_CMDLINE python~https://git.linux-kernel.at/oliver/ivatar.git \
|
||||
-e IVATAR_MAILGUN_API_KEY=$IVATAR_MAILGUN_API_KEY \
|
||||
-e IVATAR_MAILGUN_SENDER_DOMAIN=$IVATAR_MAILGUN_SENDER_DOMAIN \
|
||||
$DB_CMDLINE
|
||||
-e IVATAR_MAILGUN_API_KEY=$IVATAR_MAILGUN_API_KEY \
|
||||
-e IVATAR_MAILGUN_SENDER_DOMAIN=$IVATAR_MAILGUN_SENDER_DOMAIN \
|
||||
$DB_CMDLINE
|
||||
|
||||
oc expose svc/ivatar
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
for size in $(seq 1 512); do
|
||||
inkscape -z -e ivatar/static/img/nobody/${size}.png -w ${size} -h ${size} \
|
||||
ivatar/static/img/libravatar_logo.svg
|
||||
ivatar/static/img/libravatar_logo.svg
|
||||
done
|
||||
|
||||
1
cropperjs.zip
Normal file
1
cropperjs.zip
Normal file
@@ -0,0 +1 @@
|
||||
Not Found
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
'''
|
||||
"""
|
||||
Import the whole libravatar export
|
||||
'''
|
||||
"""
|
||||
|
||||
import os
|
||||
from os.path import isfile, isdir, join
|
||||
@@ -9,13 +9,18 @@ import sys
|
||||
import base64
|
||||
from io import BytesIO
|
||||
import django
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ivatar.settings") # pylint: disable=wrong-import-position
|
||||
|
||||
os.environ.setdefault(
|
||||
"DJANGO_SETTINGS_MODULE", "ivatar.settings"
|
||||
) # pylint: disable=wrong-import-position
|
||||
django.setup() # pylint: disable=wrong-import-position
|
||||
from django.contrib.auth.models import User
|
||||
from PIL import Image
|
||||
from django_openid_auth.models import UserOpenID
|
||||
from ivatar.settings import JPEG_QUALITY
|
||||
from ivatar.ivataraccount.read_libravatar_export import read_gzdata as libravatar_read_gzdata
|
||||
from ivatar.ivataraccount.read_libravatar_export import (
|
||||
read_gzdata as libravatar_read_gzdata,
|
||||
)
|
||||
from ivatar.ivataraccount.models import ConfirmedEmail
|
||||
from ivatar.ivataraccount.models import ConfirmedOpenId
|
||||
from ivatar.ivataraccount.models import Photo
|
||||
@@ -26,54 +31,63 @@ if len(sys.argv) < 2:
|
||||
exit(-255)
|
||||
|
||||
if not isdir(sys.argv[1]):
|
||||
print("First argument to '%s' must be a directory containing the exports" % sys.argv[0])
|
||||
print(
|
||||
"First argument to '%s' must be a directory containing the exports"
|
||||
% sys.argv[0]
|
||||
)
|
||||
exit(-255)
|
||||
|
||||
PATH = sys.argv[1]
|
||||
for file in os.listdir(PATH):
|
||||
if not file.endswith('.xml.gz'):
|
||||
if not file.endswith(".xml.gz"):
|
||||
continue
|
||||
if isfile(join(PATH, file)):
|
||||
fh = open(join(PATH, file), 'rb')
|
||||
fh = open(join(PATH, file), "rb")
|
||||
items = libravatar_read_gzdata(fh.read())
|
||||
print('Adding user "%s"' % items['username'])
|
||||
(user, created) = User.objects.get_or_create(username=items['username'])
|
||||
user.password = items['password']
|
||||
print('Adding user "%s"' % items["username"])
|
||||
(user, created) = User.objects.get_or_create(username=items["username"])
|
||||
user.password = items["password"]
|
||||
user.save()
|
||||
|
||||
saved_photos = {}
|
||||
for photo in items['photos']:
|
||||
photo_id = photo['id']
|
||||
data = base64.decodebytes(bytes(photo['data'], 'utf-8'))
|
||||
for photo in items["photos"]:
|
||||
photo_id = photo["id"]
|
||||
data = base64.decodebytes(bytes(photo["data"], "utf-8"))
|
||||
pilobj = Image.open(BytesIO(data))
|
||||
out = BytesIO()
|
||||
pilobj.save(out, pilobj.format, quality=JPEG_QUALITY)
|
||||
out.seek(0)
|
||||
photo = Photo()
|
||||
photo.user = user
|
||||
photo.ip_address = '0.0.0.0'
|
||||
photo.ip_address = "0.0.0.0"
|
||||
photo.format = file_format(pilobj.format)
|
||||
photo.data = out.read()
|
||||
photo.save()
|
||||
saved_photos[photo_id] = photo
|
||||
|
||||
for email in items['emails']:
|
||||
for email in items["emails"]:
|
||||
try:
|
||||
ConfirmedEmail.objects.get_or_create(email=email['email'], user=user,
|
||||
photo=saved_photos.get(email['photo_id']))
|
||||
except django.db.utils.IntegrityError:
|
||||
print('%s not unique?' % email['email'])
|
||||
|
||||
for openid in items['openids']:
|
||||
try:
|
||||
ConfirmedOpenId.objects.get_or_create(openid=openid['openid'], user=user,
|
||||
photo=saved_photos.get(openid['photo_id'])) # pylint: disable=no-member
|
||||
UserOpenID.objects.get_or_create(
|
||||
user_id=user.id,
|
||||
claimed_id=openid['openid'],
|
||||
display_id=openid['openid'],
|
||||
ConfirmedEmail.objects.get_or_create(
|
||||
email=email["email"],
|
||||
user=user,
|
||||
photo=saved_photos.get(email["photo_id"]),
|
||||
)
|
||||
except django.db.utils.IntegrityError:
|
||||
print('%s not unique?' % openid['openid'])
|
||||
print("%s not unique?" % email["email"])
|
||||
|
||||
for openid in items["openids"]:
|
||||
try:
|
||||
ConfirmedOpenId.objects.get_or_create(
|
||||
openid=openid["openid"],
|
||||
user=user,
|
||||
photo=saved_photos.get(openid["photo_id"]),
|
||||
) # pylint: disable=no-member
|
||||
UserOpenID.objects.get_or_create(
|
||||
user_id=user.id,
|
||||
claimed_id=openid["openid"],
|
||||
display_id=openid["openid"],
|
||||
)
|
||||
except django.db.utils.IntegrityError:
|
||||
print("%s not unique?" % openid["openid"])
|
||||
|
||||
fh.close()
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
'''
|
||||
"""
|
||||
Module init
|
||||
'''
|
||||
"""
|
||||
|
||||
app_label = __name__ # pylint: disable=invalid-name
|
||||
|
||||
@@ -1,35 +1,38 @@
|
||||
'''
|
||||
"""
|
||||
Default: useful variables for the base page templates.
|
||||
'''
|
||||
"""
|
||||
|
||||
from ipware import get_client_ip
|
||||
from ivatar.settings import IVATAR_VERSION, SITE_NAME, MAX_PHOTO_SIZE
|
||||
from ivatar.settings import BASE_URL, SECURE_BASE_URL
|
||||
from ivatar.settings import MAX_NUM_UNCONFIRMED_EMAILS
|
||||
from django.conf import settings
|
||||
from ipware import get_client_ip # type: ignore
|
||||
|
||||
|
||||
def basepage(request):
|
||||
'''
|
||||
"""
|
||||
Our contextprocessor adds additional context variables
|
||||
in order to be used in the templates
|
||||
'''
|
||||
"""
|
||||
context = {}
|
||||
if 'openid_identifier' in request.GET:
|
||||
context['openid_identifier'] = \
|
||||
request.GET['openid_identifier'] # pragma: no cover
|
||||
if "openid_identifier" in request.GET:
|
||||
context["openid_identifier"] = request.GET[
|
||||
"openid_identifier"
|
||||
] # pragma: no cover
|
||||
client_ip = get_client_ip(request)[0]
|
||||
context['client_ip'] = client_ip
|
||||
context['ivatar_version'] = IVATAR_VERSION
|
||||
context['site_name'] = SITE_NAME
|
||||
context['site_url'] = request.build_absolute_uri('/')[:-1]
|
||||
context['max_file_size'] = MAX_PHOTO_SIZE
|
||||
context['BASE_URL'] = BASE_URL
|
||||
context['SECURE_BASE_URL'] = SECURE_BASE_URL
|
||||
context['max_emails'] = False
|
||||
context["client_ip"] = client_ip
|
||||
context["ivatar_version"] = getattr(settings, "IVATAR_VERSION", "2.0")
|
||||
context["site_name"] = getattr(settings, "SITE_NAME", "libravatar")
|
||||
context["site_url"] = request.build_absolute_uri("/")[:-1]
|
||||
context["max_file_size"] = getattr(settings, "MAX_PHOTO_SIZE", 10485760)
|
||||
context["BASE_URL"] = getattr(settings, "BASE_URL", "http://localhost:8000/avatar/")
|
||||
context["SECURE_BASE_URL"] = getattr(
|
||||
settings, "SECURE_BASE_URL", "https://localhost:8000/avatar/"
|
||||
)
|
||||
context["max_emails"] = False
|
||||
|
||||
if request.user:
|
||||
if not request.user.is_anonymous:
|
||||
unconfirmed = request.user.unconfirmedemail_set.count()
|
||||
if unconfirmed >= MAX_NUM_UNCONFIRMED_EMAILS:
|
||||
context['max_emails'] = True
|
||||
max_unconfirmed = getattr(settings, "MAX_NUM_UNCONFIRMED_EMAILS", 5)
|
||||
if unconfirmed >= max_unconfirmed:
|
||||
context["max_emails"] = True
|
||||
|
||||
return context
|
||||
|
||||
342
ivatar/file_security.py
Normal file
342
ivatar/file_security.py
Normal file
@@ -0,0 +1,342 @@
|
||||
"""
|
||||
File upload security utilities for ivatar
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import magic
|
||||
import os
|
||||
from io import BytesIO
|
||||
from typing import Dict, Tuple
|
||||
|
||||
from PIL import Image
|
||||
|
||||
# Initialize logger
|
||||
logger = logging.getLogger("ivatar.security")
|
||||
|
||||
# Security constants
|
||||
ALLOWED_MIME_TYPES = [
|
||||
"image/jpeg",
|
||||
"image/png",
|
||||
"image/gif",
|
||||
"image/webp",
|
||||
"image/bmp",
|
||||
"image/tiff",
|
||||
]
|
||||
|
||||
ALLOWED_EXTENSIONS = [".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".tiff"]
|
||||
|
||||
# Magic byte signatures for image formats
|
||||
IMAGE_SIGNATURES = {
|
||||
b"\xff\xd8\xff": "image/jpeg",
|
||||
b"\x89PNG\r\n\x1a\n": "image/png",
|
||||
b"GIF87a": "image/gif",
|
||||
b"GIF89a": "image/gif",
|
||||
b"RIFF": "image/webp", # WebP starts with RIFF
|
||||
b"BM": "image/bmp",
|
||||
b"II*\x00": "image/tiff", # Little-endian TIFF
|
||||
b"MM\x00*": "image/tiff", # Big-endian TIFF
|
||||
}
|
||||
|
||||
# Maximum file size for different operations (in bytes)
|
||||
MAX_FILE_SIZE_BASIC = 5 * 1024 * 1024 # 5MB for basic validation
|
||||
MAX_FILE_SIZE_SCAN = 10 * 1024 * 1024 # 10MB for virus scanning
|
||||
MAX_FILE_SIZE_PROCESS = 50 * 1024 * 1024 # 50MB for processing
|
||||
|
||||
|
||||
class FileUploadSecurityError(Exception):
|
||||
"""Custom exception for file upload security issues"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class FileValidator:
|
||||
"""Comprehensive file validation for uploads"""
|
||||
|
||||
def __init__(self, file_data: bytes, filename: str):
|
||||
self.file_data = file_data
|
||||
self.filename = filename
|
||||
self.file_size = len(file_data)
|
||||
self.file_hash = hashlib.sha256(file_data).hexdigest()
|
||||
|
||||
def validate_basic(self) -> Dict[str, any]:
|
||||
"""
|
||||
Perform basic file validation
|
||||
Returns validation results dictionary
|
||||
"""
|
||||
results = {
|
||||
"valid": True,
|
||||
"errors": [],
|
||||
"warnings": [],
|
||||
"file_info": {
|
||||
"size": self.file_size,
|
||||
"hash": self.file_hash,
|
||||
"filename": self.filename,
|
||||
},
|
||||
}
|
||||
|
||||
# Check file size
|
||||
if self.file_size > MAX_FILE_SIZE_BASIC:
|
||||
results["valid"] = False
|
||||
results["errors"].append(f"File too large: {self.file_size} bytes")
|
||||
|
||||
# Check filename
|
||||
if not self.filename or len(self.filename) > 255:
|
||||
results["valid"] = False
|
||||
results["errors"].append("Invalid filename")
|
||||
|
||||
# Check file extension
|
||||
ext = os.path.splitext(self.filename)[1].lower()
|
||||
if ext not in ALLOWED_EXTENSIONS:
|
||||
results["valid"] = False
|
||||
results["errors"].append(f"File extension not allowed: {ext}")
|
||||
|
||||
return results
|
||||
|
||||
def validate_magic_bytes(self) -> Dict[str, any]:
|
||||
"""
|
||||
Validate file using magic bytes (file signatures)
|
||||
"""
|
||||
results = {"valid": True, "detected_type": None, "errors": []}
|
||||
|
||||
# Check magic bytes
|
||||
detected_type = None
|
||||
for signature, mime_type in IMAGE_SIGNATURES.items():
|
||||
if self.file_data.startswith(signature):
|
||||
detected_type = mime_type
|
||||
break
|
||||
|
||||
# Special handling for WebP (RIFF + WEBP)
|
||||
if self.file_data.startswith(b"RIFF") and b"WEBP" in self.file_data[:12]:
|
||||
detected_type = "image/webp"
|
||||
|
||||
if not detected_type:
|
||||
results["valid"] = False
|
||||
results["errors"].append(
|
||||
"File signature does not match any supported image format"
|
||||
)
|
||||
else:
|
||||
results["detected_type"] = detected_type
|
||||
|
||||
return results
|
||||
|
||||
def validate_mime_type(self) -> Dict[str, any]:
|
||||
"""
|
||||
Validate MIME type using python-magic
|
||||
"""
|
||||
results = {"valid": True, "detected_mime": None, "errors": []}
|
||||
|
||||
try:
|
||||
# Use python-magic to detect MIME type
|
||||
detected_mime = magic.from_buffer(self.file_data, mime=True)
|
||||
results["detected_mime"] = detected_mime
|
||||
|
||||
if detected_mime not in ALLOWED_MIME_TYPES:
|
||||
results["valid"] = False
|
||||
results["errors"].append(f"MIME type not allowed: {detected_mime}")
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"MIME type detection failed: {e}")
|
||||
results["warnings"].append("Could not detect MIME type")
|
||||
|
||||
return results
|
||||
|
||||
def validate_pil_image(self) -> Dict[str, any]:
|
||||
"""
|
||||
Validate using PIL to ensure it's a valid image
|
||||
"""
|
||||
results = {"valid": True, "image_info": {}, "errors": []}
|
||||
|
||||
try:
|
||||
# Open image with PIL
|
||||
image = Image.open(BytesIO(self.file_data))
|
||||
|
||||
# Get image information
|
||||
results["image_info"] = {
|
||||
"format": image.format,
|
||||
"mode": image.mode,
|
||||
"size": image.size,
|
||||
"width": image.width,
|
||||
"height": image.height,
|
||||
"has_transparency": image.mode in ("RGBA", "LA", "P"),
|
||||
}
|
||||
|
||||
# Verify image can be loaded
|
||||
image.load()
|
||||
|
||||
# Check for suspicious characteristics
|
||||
if image.width > 10000 or image.height > 10000:
|
||||
results["warnings"].append("Image dimensions are very large")
|
||||
|
||||
if image.width < 1 or image.height < 1:
|
||||
results["valid"] = False
|
||||
results["errors"].append("Invalid image dimensions")
|
||||
|
||||
except Exception as e:
|
||||
results["valid"] = False
|
||||
results["errors"].append(f"Invalid image format: {str(e)}")
|
||||
|
||||
return results
|
||||
|
||||
def sanitize_exif_data(self) -> bytes:
|
||||
"""
|
||||
Remove EXIF data from image to prevent metadata leaks
|
||||
"""
|
||||
try:
|
||||
image = Image.open(BytesIO(self.file_data))
|
||||
|
||||
# Create new image without EXIF data
|
||||
if image.mode in ("RGBA", "LA"):
|
||||
# Preserve transparency
|
||||
new_image = Image.new("RGBA", image.size, (255, 255, 255, 0))
|
||||
new_image.paste(image, mask=image.split()[-1])
|
||||
else:
|
||||
new_image = Image.new("RGB", image.size, (255, 255, 255))
|
||||
new_image.paste(image)
|
||||
|
||||
# Save without EXIF data
|
||||
output = BytesIO()
|
||||
new_image.save(output, format=image.format or "JPEG", quality=95)
|
||||
return output.getvalue()
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"EXIF sanitization failed: {e}")
|
||||
return self.file_data # Return original if sanitization fails
|
||||
|
||||
def scan_for_malicious_content(self) -> Dict[str, any]:
|
||||
"""
|
||||
Scan for potentially malicious content patterns
|
||||
"""
|
||||
results = {"suspicious": False, "threats": [], "warnings": []}
|
||||
|
||||
# Check for embedded scripts or executable content
|
||||
suspicious_patterns = [
|
||||
b"<script",
|
||||
b"javascript:",
|
||||
b"vbscript:",
|
||||
b"data:text/html",
|
||||
b"<?php",
|
||||
b"<%",
|
||||
b"#!/bin/",
|
||||
b"MZ", # PE executable header
|
||||
b"\x7fELF", # ELF executable header
|
||||
]
|
||||
|
||||
for pattern in suspicious_patterns:
|
||||
if pattern in self.file_data:
|
||||
results["suspicious"] = True
|
||||
results["threats"].append(f"Suspicious pattern detected: {pattern}")
|
||||
|
||||
# Check for polyglot files (valid in multiple formats)
|
||||
if self.file_data.startswith(b"GIF89a") and b"<script" in self.file_data:
|
||||
results["suspicious"] = True
|
||||
results["threats"].append("Potential polyglot attack detected")
|
||||
|
||||
return results
|
||||
|
||||
def comprehensive_validation(self) -> Dict[str, any]:
|
||||
"""
|
||||
Perform comprehensive file validation
|
||||
"""
|
||||
results = {
|
||||
"valid": True,
|
||||
"errors": [],
|
||||
"warnings": [],
|
||||
"file_info": {},
|
||||
"security_score": 100,
|
||||
}
|
||||
|
||||
# Basic validation
|
||||
basic_results = self.validate_basic()
|
||||
if not basic_results["valid"]:
|
||||
results["valid"] = False
|
||||
results["errors"].extend(basic_results["errors"])
|
||||
results["security_score"] -= 30
|
||||
|
||||
results["file_info"].update(basic_results["file_info"])
|
||||
results["warnings"].extend(basic_results["warnings"])
|
||||
|
||||
# Magic bytes validation
|
||||
magic_results = self.validate_magic_bytes()
|
||||
if not magic_results["valid"]:
|
||||
results["valid"] = False
|
||||
results["errors"].extend(magic_results["errors"])
|
||||
results[
|
||||
"security_score"
|
||||
] -= 10 # Reduced from 25 - basic format issue, not security threat
|
||||
|
||||
results["file_info"]["detected_type"] = magic_results["detected_type"]
|
||||
|
||||
# MIME type validation
|
||||
mime_results = self.validate_mime_type()
|
||||
if not mime_results["valid"]:
|
||||
results["valid"] = False
|
||||
results["errors"].extend(mime_results["errors"])
|
||||
results[
|
||||
"security_score"
|
||||
] -= 10 # Reduced from 20 - basic format issue, not security threat
|
||||
|
||||
results["file_info"]["detected_mime"] = mime_results["detected_mime"]
|
||||
results["warnings"].extend(mime_results.get("warnings", []))
|
||||
|
||||
# PIL image validation
|
||||
pil_results = self.validate_pil_image()
|
||||
if not pil_results["valid"]:
|
||||
results["valid"] = False
|
||||
results["errors"].extend(pil_results["errors"])
|
||||
results[
|
||||
"security_score"
|
||||
] -= 10 # Reduced from 15 - basic format issue, not security threat
|
||||
|
||||
results["file_info"]["image_info"] = pil_results["image_info"]
|
||||
results["warnings"].extend(pil_results.get("warnings", []))
|
||||
|
||||
# Security scan
|
||||
security_results = self.scan_for_malicious_content()
|
||||
if security_results["suspicious"]:
|
||||
results["valid"] = False
|
||||
results["errors"].extend(security_results["threats"])
|
||||
results["security_score"] -= 50
|
||||
|
||||
results["warnings"].extend(security_results.get("warnings", []))
|
||||
|
||||
# Log security events
|
||||
if not results["valid"]:
|
||||
logger.warning(f"File upload validation failed: {results['errors']}")
|
||||
elif results["security_score"] < 80:
|
||||
logger.info(
|
||||
f"File upload with low security score: {results['security_score']}"
|
||||
)
|
||||
|
||||
return results
|
||||
|
||||
|
||||
def validate_uploaded_file(
|
||||
file_data: bytes, filename: str
|
||||
) -> Tuple[bool, Dict[str, any], bytes]:
|
||||
"""
|
||||
Main function to validate uploaded files
|
||||
|
||||
Returns:
|
||||
(is_valid, validation_results, sanitized_data)
|
||||
"""
|
||||
validator = FileValidator(file_data, filename)
|
||||
|
||||
# Perform comprehensive validation
|
||||
results = validator.comprehensive_validation()
|
||||
|
||||
if not results["valid"]:
|
||||
return False, results, file_data
|
||||
|
||||
# Sanitize EXIF data
|
||||
sanitized_data = validator.sanitize_exif_data()
|
||||
|
||||
return True, results, sanitized_data
|
||||
|
||||
|
||||
def get_file_security_report(file_data: bytes, filename: str) -> Dict[str, any]:
|
||||
"""
|
||||
Generate a security report for a file without modifying it
|
||||
"""
|
||||
validator = FileValidator(file_data, filename)
|
||||
return validator.comprehensive_validation()
|
||||
@@ -1,4 +1,5 @@
|
||||
'''
|
||||
"""
|
||||
Module init
|
||||
'''
|
||||
"""
|
||||
|
||||
app_label = __name__ # pylint: disable=invalid-name
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
'''
|
||||
"""
|
||||
Register models in admin
|
||||
'''
|
||||
"""
|
||||
|
||||
from django.contrib import admin
|
||||
|
||||
from . models import Photo, ConfirmedEmail, UnconfirmedEmail
|
||||
from . models import ConfirmedOpenId, UnconfirmedOpenId
|
||||
from . models import OpenIDNonce, OpenIDAssociation
|
||||
from . models import UserPreference
|
||||
from .models import Photo, ConfirmedEmail, UnconfirmedEmail
|
||||
from .models import ConfirmedOpenId, UnconfirmedOpenId
|
||||
from .models import OpenIDNonce, OpenIDAssociation
|
||||
from .models import UserPreference
|
||||
|
||||
# Register models in admin
|
||||
admin.site.register(Photo)
|
||||
|
||||
55
ivatar/ivataraccount/auth.py
Normal file
55
ivatar/ivataraccount/auth.py
Normal file
@@ -0,0 +1,55 @@
|
||||
from social_core.backends.open_id_connect import OpenIdConnectAuth
|
||||
|
||||
from ivatar.ivataraccount.models import ConfirmedEmail, Photo
|
||||
from ivatar.settings import logger, TRUST_EMAIL_FROM_SOCIAL_AUTH_BACKENDS
|
||||
|
||||
|
||||
class FedoraOpenIdConnect(OpenIdConnectAuth):
|
||||
name = "fedora"
|
||||
USERNAME_KEY = "nickname"
|
||||
OIDC_ENDPOINT = "https://id.fedoraproject.org"
|
||||
DEFAULT_SCOPE = ["openid", "profile", "email"]
|
||||
TOKEN_ENDPOINT_AUTH_METHOD = "client_secret_post"
|
||||
|
||||
|
||||
# Pipeline methods
|
||||
|
||||
|
||||
def add_confirmed_email(backend, user, response, *args, **kwargs):
|
||||
"""Add a ConfirmedEmail if we trust the auth backend to validate email."""
|
||||
if not kwargs.get("is_new", False):
|
||||
return None # Only act on account creation
|
||||
if backend.name not in TRUST_EMAIL_FROM_SOCIAL_AUTH_BACKENDS:
|
||||
return None
|
||||
if ConfirmedEmail.objects.filter(email=user.email).count() > 0:
|
||||
# email already exists
|
||||
return None
|
||||
(confirmed_id, external_photos) = ConfirmedEmail.objects.create_confirmed_email(
|
||||
user, user.email, True
|
||||
)
|
||||
confirmed_email = ConfirmedEmail.objects.get(id=confirmed_id)
|
||||
logger.debug(
|
||||
"Email %s added upon creation of user %s", confirmed_email.email, user.pk
|
||||
)
|
||||
photo = Photo.objects.create(user=user, ip_address=confirmed_email.ip_address)
|
||||
import_result = photo.import_image("Gravatar", confirmed_email.email)
|
||||
if import_result:
|
||||
logger.debug("Gravatar image imported for %s", confirmed_email.email)
|
||||
|
||||
|
||||
def associate_by_confirmed_email(backend, details, user=None, *args, **kwargs):
|
||||
"""
|
||||
Associate current auth with a user that has their email address as ConfirmedEmail in the DB.
|
||||
"""
|
||||
if user:
|
||||
return None
|
||||
email = details.get("email")
|
||||
if not email:
|
||||
return None
|
||||
try:
|
||||
confirmed_email = ConfirmedEmail.objects.get(email=email)
|
||||
except ConfirmedEmail.DoesNotExist:
|
||||
return None
|
||||
user = confirmed_email.user
|
||||
logger.debug("Found a matching ConfirmedEmail for %s upon login", user.username)
|
||||
return {"user": user, "is_new": False}
|
||||
@@ -1,163 +1,267 @@
|
||||
'''
|
||||
"""
|
||||
Classes for our ivatar.ivataraccount.forms
|
||||
'''
|
||||
"""
|
||||
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
|
||||
from django import forms
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django.core.exceptions import ValidationError
|
||||
|
||||
from ipware import get_client_ip
|
||||
|
||||
from ivatar import settings
|
||||
from ivatar.settings import MIN_LENGTH_EMAIL, MAX_LENGTH_EMAIL
|
||||
from ivatar.settings import MIN_LENGTH_URL, MAX_LENGTH_URL
|
||||
from . models import UnconfirmedEmail, ConfirmedEmail, Photo
|
||||
from . models import UnconfirmedOpenId, ConfirmedOpenId
|
||||
from . models import UserPreference
|
||||
from ivatar.settings import ENABLE_FILE_SECURITY_VALIDATION
|
||||
from ivatar.file_security import validate_uploaded_file, FileUploadSecurityError
|
||||
from .models import UnconfirmedEmail, ConfirmedEmail, Photo
|
||||
from .models import UnconfirmedOpenId, ConfirmedOpenId
|
||||
from .models import UserPreference
|
||||
import logging
|
||||
|
||||
# Initialize logger
|
||||
logger = logging.getLogger("ivatar.ivataraccount.forms")
|
||||
|
||||
|
||||
MAX_NUM_UNCONFIRMED_EMAILS_DEFAULT = 5
|
||||
|
||||
|
||||
class AddEmailForm(forms.Form):
|
||||
'''
|
||||
"""
|
||||
Form to handle adding email addresses
|
||||
'''
|
||||
"""
|
||||
|
||||
email = forms.EmailField(
|
||||
label=_('Email'),
|
||||
label=_("Email"),
|
||||
min_length=MIN_LENGTH_EMAIL,
|
||||
max_length=MAX_LENGTH_EMAIL,
|
||||
)
|
||||
|
||||
def clean_email(self):
|
||||
'''
|
||||
"""
|
||||
Enforce lowercase email
|
||||
'''
|
||||
"""
|
||||
# TODO: Domain restriction as in libravatar?
|
||||
return self.cleaned_data['email'].lower()
|
||||
return self.cleaned_data["email"].lower()
|
||||
|
||||
def save(self, request):
|
||||
'''
|
||||
"""
|
||||
Save the model, ensuring some safety
|
||||
'''
|
||||
"""
|
||||
user = request.user
|
||||
# Enforce the maximum number of unconfirmed emails a user can have
|
||||
num_unconfirmed = user.unconfirmedemail_set.count()
|
||||
|
||||
max_num_unconfirmed_emails = getattr(
|
||||
settings,
|
||||
'MAX_NUM_UNCONFIRMED_EMAILS',
|
||||
MAX_NUM_UNCONFIRMED_EMAILS_DEFAULT)
|
||||
settings, "MAX_NUM_UNCONFIRMED_EMAILS", MAX_NUM_UNCONFIRMED_EMAILS_DEFAULT
|
||||
)
|
||||
|
||||
if num_unconfirmed >= max_num_unconfirmed_emails:
|
||||
self.add_error(None, _('Too many unconfirmed mail addresses!'))
|
||||
self.add_error(None, _("Too many unconfirmed mail addresses!"))
|
||||
return False
|
||||
|
||||
# Check whether or not a confirmation email has been
|
||||
# sent by this user already
|
||||
if UnconfirmedEmail.objects.filter( # pylint: disable=no-member
|
||||
user=user, email=self.cleaned_data['email']).exists():
|
||||
self.add_error(
|
||||
'email',
|
||||
_('Address already added, currently unconfirmed'))
|
||||
user=user, email=self.cleaned_data["email"]
|
||||
).exists():
|
||||
self.add_error("email", _("Address already added, currently unconfirmed"))
|
||||
return False
|
||||
|
||||
# Check whether or not the email is already confirmed by someone
|
||||
if ConfirmedEmail.objects.filter(
|
||||
email=self.cleaned_data['email']).exists():
|
||||
self.add_error(
|
||||
'email',
|
||||
_('Address already confirmed (by someone else)'))
|
||||
# Check whether or not the email is already confirmed (by someone)
|
||||
check_mail = ConfirmedEmail.objects.filter(email=self.cleaned_data["email"])
|
||||
if check_mail.exists():
|
||||
msg = _("Address already confirmed (by someone else)")
|
||||
if check_mail.first().user == request.user:
|
||||
msg = _("Address already confirmed (by you)")
|
||||
self.add_error("email", msg)
|
||||
return False
|
||||
|
||||
unconfirmed = UnconfirmedEmail()
|
||||
unconfirmed.email = self.cleaned_data['email']
|
||||
unconfirmed.email = self.cleaned_data["email"]
|
||||
unconfirmed.user = user
|
||||
unconfirmed.save()
|
||||
unconfirmed.send_confirmation_mail(url=request.build_absolute_uri('/')[:-1])
|
||||
unconfirmed.send_confirmation_mail(url=request.build_absolute_uri("/")[:-1])
|
||||
return True
|
||||
|
||||
|
||||
class UploadPhotoForm(forms.Form):
|
||||
'''
|
||||
Form handling photo upload
|
||||
'''
|
||||
photo = forms.FileField(
|
||||
label=_('Photo'),
|
||||
error_messages={'required': _('You must choose an image to upload.')})
|
||||
not_porn = forms.BooleanField(
|
||||
label=_('suitable for all ages (i.e. no offensive content)'),
|
||||
required=True,
|
||||
error_messages={
|
||||
'required':
|
||||
_('We only host "G-rated" images and so this field must be checked.')
|
||||
})
|
||||
can_distribute = forms.BooleanField(
|
||||
label=_('can be freely copied'),
|
||||
required=True,
|
||||
error_messages={
|
||||
'required':
|
||||
_('This field must be checked since we need to be able to distribute photos to third parties.')
|
||||
})
|
||||
"""
|
||||
Form handling photo upload with enhanced security validation
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def save(request, data):
|
||||
'''
|
||||
Save the model and assign it to the current user
|
||||
'''
|
||||
photo = forms.FileField(
|
||||
label=_("Photo"),
|
||||
error_messages={"required": _("You must choose an image to upload.")},
|
||||
)
|
||||
not_porn = forms.BooleanField(
|
||||
label=_("suitable for all ages (i.e. no offensive content)"),
|
||||
required=True,
|
||||
error_messages={
|
||||
"required": _(
|
||||
'We only host "G-rated" images and so this field must be checked.'
|
||||
)
|
||||
},
|
||||
)
|
||||
can_distribute = forms.BooleanField(
|
||||
label=_("can be freely copied"),
|
||||
required=True,
|
||||
error_messages={
|
||||
"required": _(
|
||||
"This field must be checked since we need to be able to distribute photos to third parties."
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
def clean_photo(self):
|
||||
"""
|
||||
Enhanced photo validation with security checks
|
||||
"""
|
||||
photo = self.cleaned_data.get("photo")
|
||||
|
||||
if not photo:
|
||||
raise ValidationError(_("No file provided"))
|
||||
|
||||
# Read file data
|
||||
try:
|
||||
# Handle different file types
|
||||
if hasattr(photo, "read"):
|
||||
file_data = photo.read()
|
||||
elif hasattr(photo, "file"):
|
||||
file_data = photo.file.read()
|
||||
else:
|
||||
file_data = bytes(photo)
|
||||
filename = photo.name
|
||||
except Exception as e:
|
||||
logger.error(f"Error reading uploaded file: {e}")
|
||||
raise ValidationError(_("Error reading uploaded file"))
|
||||
|
||||
# Perform comprehensive security validation (if enabled)
|
||||
if ENABLE_FILE_SECURITY_VALIDATION:
|
||||
try:
|
||||
is_valid, validation_results, sanitized_data = validate_uploaded_file(
|
||||
file_data, filename
|
||||
)
|
||||
|
||||
if not is_valid:
|
||||
# Log security violation
|
||||
logger.warning(
|
||||
f"File upload security violation: {validation_results['errors']}"
|
||||
)
|
||||
|
||||
# Only reject truly malicious files at the form level
|
||||
# Allow basic format issues to pass through to Photo.save() for original error handling
|
||||
if validation_results.get("security_score", 100) < 30:
|
||||
raise ValidationError(
|
||||
_("File appears to be malicious and cannot be uploaded")
|
||||
)
|
||||
else:
|
||||
# For format issues, don't raise ValidationError - let Photo.save() handle it
|
||||
# This preserves the original error handling behavior
|
||||
logger.info(
|
||||
f"File format issue detected, allowing Photo.save() to handle: {validation_results['errors']}"
|
||||
)
|
||||
# Store the validation results for potential use, but don't reject the form
|
||||
self.validation_results = validation_results
|
||||
self.file_data = file_data
|
||||
else:
|
||||
# Store sanitized data for later use
|
||||
self.sanitized_data = sanitized_data
|
||||
self.validation_results = validation_results
|
||||
# Store original file data for fallback
|
||||
self.file_data = file_data
|
||||
|
||||
# Log successful validation
|
||||
logger.info(
|
||||
f"File upload validated successfully: {filename}, security_score: {validation_results.get('security_score', 100)}"
|
||||
)
|
||||
|
||||
except FileUploadSecurityError as e:
|
||||
logger.error(f"File upload security error: {e}")
|
||||
raise ValidationError(_("File security validation failed"))
|
||||
except Exception as e:
|
||||
logger.error(f"Unexpected error during file validation: {e}")
|
||||
raise ValidationError(_("File validation failed"))
|
||||
else:
|
||||
# Security validation disabled (e.g., in tests)
|
||||
logger.debug(f"File upload security validation disabled for: {filename}")
|
||||
self.file_data = file_data
|
||||
|
||||
return photo
|
||||
|
||||
def save(self, request, data):
|
||||
"""
|
||||
Save the model and assign it to the current user with enhanced security
|
||||
"""
|
||||
# Link this file to the user's profile
|
||||
photo = Photo()
|
||||
photo.user = request.user
|
||||
photo.ip_address = get_client_ip(request)[0]
|
||||
photo.data = data.read()
|
||||
|
||||
# Use sanitized data if available, otherwise use stored file data
|
||||
if hasattr(self, "sanitized_data"):
|
||||
photo.data = self.sanitized_data
|
||||
elif hasattr(self, "file_data"):
|
||||
photo.data = self.file_data
|
||||
else:
|
||||
# Fallback: try to read from the file object
|
||||
try:
|
||||
photo.data = data.read()
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to read file data: {e}")
|
||||
photo.data = b""
|
||||
|
||||
photo.save()
|
||||
if not photo.pk:
|
||||
return None
|
||||
return photo
|
||||
return photo if photo.pk else None
|
||||
|
||||
|
||||
class AddOpenIDForm(forms.Form):
|
||||
'''
|
||||
"""
|
||||
Form to handle adding OpenID
|
||||
'''
|
||||
"""
|
||||
|
||||
openid = forms.URLField(
|
||||
label=_('OpenID'),
|
||||
label=_("OpenID"),
|
||||
min_length=MIN_LENGTH_URL,
|
||||
max_length=MAX_LENGTH_URL,
|
||||
initial='http://'
|
||||
initial="http://",
|
||||
)
|
||||
|
||||
def clean_openid(self):
|
||||
'''
|
||||
"""
|
||||
Enforce restrictions
|
||||
'''
|
||||
"""
|
||||
# Lowercase hostname port of the URL
|
||||
url = urlsplit(self.cleaned_data['openid'])
|
||||
data = urlunsplit(
|
||||
(url.scheme.lower(), url.netloc.lower(), url.path,
|
||||
url.query, url.fragment))
|
||||
|
||||
# TODO: Domain restriction as in libravatar?
|
||||
return data
|
||||
url = urlsplit(self.cleaned_data["openid"])
|
||||
return urlunsplit(
|
||||
(
|
||||
url.scheme.lower(),
|
||||
url.netloc.lower(),
|
||||
url.path,
|
||||
url.query,
|
||||
url.fragment,
|
||||
)
|
||||
)
|
||||
|
||||
def save(self, user):
|
||||
'''
|
||||
"""
|
||||
Save the model, ensuring some safety
|
||||
'''
|
||||
"""
|
||||
if ConfirmedOpenId.objects.filter( # pylint: disable=no-member
|
||||
openid=self.cleaned_data['openid']).exists():
|
||||
self.add_error('openid', _('OpenID already added and confirmed!'))
|
||||
openid=self.cleaned_data["openid"]
|
||||
).exists():
|
||||
self.add_error("openid", _("OpenID already added and confirmed!"))
|
||||
return False
|
||||
|
||||
if UnconfirmedOpenId.objects.filter( # pylint: disable=no-member
|
||||
openid=self.cleaned_data['openid']).exists():
|
||||
self.add_error(
|
||||
'openid',
|
||||
_('OpenID already added, but not confirmed yet!'))
|
||||
openid=self.cleaned_data["openid"]
|
||||
).exists():
|
||||
self.add_error("openid", _("OpenID already added, but not confirmed yet!"))
|
||||
return False
|
||||
|
||||
unconfirmed = UnconfirmedOpenId()
|
||||
unconfirmed.openid = self.cleaned_data['openid']
|
||||
unconfirmed.openid = self.cleaned_data["openid"]
|
||||
unconfirmed.user = user
|
||||
unconfirmed.save()
|
||||
|
||||
@@ -165,40 +269,50 @@ class AddOpenIDForm(forms.Form):
|
||||
|
||||
|
||||
class UpdatePreferenceForm(forms.ModelForm):
|
||||
'''
|
||||
"""
|
||||
Form for updating user preferences
|
||||
'''
|
||||
"""
|
||||
|
||||
class Meta: # pylint: disable=too-few-public-methods
|
||||
'''
|
||||
"""
|
||||
Meta class for UpdatePreferenceForm
|
||||
'''
|
||||
"""
|
||||
|
||||
model = UserPreference
|
||||
fields = ['theme']
|
||||
fields = ["theme"]
|
||||
|
||||
|
||||
class UploadLibravatarExportForm(forms.Form):
|
||||
'''
|
||||
"""
|
||||
Form handling libravatar user export upload
|
||||
'''
|
||||
"""
|
||||
|
||||
export_file = forms.FileField(
|
||||
label=_('Export file'),
|
||||
error_messages={'required': _('You must choose an export file to upload.')})
|
||||
label=_("Export file"),
|
||||
error_messages={"required": _("You must choose an export file to upload.")},
|
||||
)
|
||||
not_porn = forms.BooleanField(
|
||||
label=_('suitable for all ages (i.e. no offensive content)'),
|
||||
label=_("suitable for all ages (i.e. no offensive content)"),
|
||||
required=True,
|
||||
error_messages={
|
||||
'required':
|
||||
_('We only host "G-rated" images and so this field must be checked.')
|
||||
})
|
||||
"required": _(
|
||||
'We only host "G-rated" images and so this field must be checked.'
|
||||
)
|
||||
},
|
||||
)
|
||||
can_distribute = forms.BooleanField(
|
||||
label=_('can be freely copied'),
|
||||
label=_("can be freely copied"),
|
||||
required=True,
|
||||
error_messages={
|
||||
'required':
|
||||
_('This field must be checked since we need to be able to\
|
||||
distribute photos to third parties.')
|
||||
})
|
||||
"required": _(
|
||||
"This field must be checked since we need to be able to\
|
||||
distribute photos to third parties."
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class DeleteAccountForm(forms.Form):
|
||||
password = forms.CharField(label=_('Password'), required=False, widget=forms.PasswordInput())
|
||||
password = forms.CharField(
|
||||
label=_("Password"), required=False, widget=forms.PasswordInput()
|
||||
)
|
||||
|
||||
@@ -1,53 +1,51 @@
|
||||
'''
|
||||
"""
|
||||
Helper method to fetch Gravatar image
|
||||
'''
|
||||
"""
|
||||
|
||||
from ssl import SSLError
|
||||
from urllib.request import urlopen, HTTPError, URLError
|
||||
from urllib.request import HTTPError, URLError
|
||||
from ivatar.utils import urlopen
|
||||
import hashlib
|
||||
|
||||
from .. settings import AVATAR_MAX_SIZE
|
||||
|
||||
URL_TIMEOUT = 5 # in seconds
|
||||
from ..settings import AVATAR_MAX_SIZE
|
||||
|
||||
|
||||
def get_photo(email):
|
||||
'''
|
||||
"""
|
||||
Fetch photo from Gravatar, given an email address
|
||||
'''
|
||||
hash_object = hashlib.new('md5')
|
||||
hash_object.update(email.lower().encode('utf-8'))
|
||||
thumbnail_url = 'https://secure.gravatar.com/avatar/' + \
|
||||
hash_object.hexdigest() + '?s=%i&d=404' % AVATAR_MAX_SIZE
|
||||
image_url = 'https://secure.gravatar.com/avatar/' + hash_object.hexdigest(
|
||||
) + '?s=512&d=404'
|
||||
"""
|
||||
hash_object = hashlib.new("md5")
|
||||
hash_object.update(email.lower().encode("utf-8"))
|
||||
thumbnail_url = (
|
||||
"https://secure.gravatar.com/avatar/"
|
||||
+ hash_object.hexdigest()
|
||||
+ "?s=%i&d=404" % AVATAR_MAX_SIZE
|
||||
)
|
||||
image_url = (
|
||||
f"https://secure.gravatar.com/avatar/{hash_object.hexdigest()}?s=512&d=404"
|
||||
)
|
||||
|
||||
# Will redirect to the public profile URL if it exists
|
||||
service_url = 'http://www.gravatar.com/' + hash_object.hexdigest()
|
||||
service_url = f"http://www.gravatar.com/{hash_object.hexdigest()}"
|
||||
|
||||
try:
|
||||
urlopen(image_url, timeout=URL_TIMEOUT)
|
||||
urlopen(image_url)
|
||||
except HTTPError as exc:
|
||||
if exc.code != 404 and exc.code != 503:
|
||||
print( # pragma: no cover
|
||||
'Gravatar fetch failed with an unexpected %s HTTP error' %
|
||||
exc.code)
|
||||
if exc.code not in [404, 503]:
|
||||
print(f"Gravatar fetch failed with an unexpected {exc.code} HTTP error")
|
||||
return False
|
||||
except URLError as exc: # pragma: no cover
|
||||
print(
|
||||
'Gravatar fetch failed with URL error: %s' %
|
||||
exc.reason) # pragma: no cover
|
||||
print(f"Gravatar fetch failed with URL error: {exc.reason}")
|
||||
return False # pragma: no cover
|
||||
except SSLError as exc: # pragma: no cover
|
||||
print(
|
||||
'Gravatar fetch failed with SSL error: %s' %
|
||||
exc.reason) # pragma: no cover
|
||||
except SSLError as exc: # pragma: no cover
|
||||
print(f"Gravatar fetch failed with SSL error: {exc.reason}")
|
||||
return False # pragma: no cover
|
||||
|
||||
return {
|
||||
'thumbnail_url': thumbnail_url,
|
||||
'image_url': image_url,
|
||||
'width': AVATAR_MAX_SIZE,
|
||||
'height': AVATAR_MAX_SIZE,
|
||||
'service_url': service_url,
|
||||
'service_name': 'Gravatar'
|
||||
"thumbnail_url": thumbnail_url,
|
||||
"image_url": image_url,
|
||||
"width": AVATAR_MAX_SIZE,
|
||||
"height": AVATAR_MAX_SIZE,
|
||||
"service_url": service_url,
|
||||
"service_name": "Gravatar",
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
import ivatar.ivataraccount.models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
@@ -16,93 +15,167 @@ class Migration(migrations.Migration):
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='ConfirmedEmail',
|
||||
name="ConfirmedEmail",
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('ip_address', models.GenericIPAddressField(unpack_ipv4=True)),
|
||||
('add_date', models.DateTimeField()),
|
||||
('email', models.EmailField(max_length=254, unique=True)),
|
||||
(
|
||||
"id",
|
||||
models.AutoField(
|
||||
auto_created=True,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
verbose_name="ID",
|
||||
),
|
||||
),
|
||||
("ip_address", models.GenericIPAddressField(unpack_ipv4=True)),
|
||||
("add_date", models.DateTimeField()),
|
||||
("email", models.EmailField(max_length=254, unique=True)),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'confirmed email',
|
||||
'verbose_name_plural': 'confirmed emails',
|
||||
"verbose_name": "confirmed email",
|
||||
"verbose_name_plural": "confirmed emails",
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='ConfirmedOpenId',
|
||||
name="ConfirmedOpenId",
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('ip_address', models.GenericIPAddressField(unpack_ipv4=True)),
|
||||
('add_date', models.DateTimeField()),
|
||||
('openid', models.URLField(max_length=255, unique=True)),
|
||||
(
|
||||
"id",
|
||||
models.AutoField(
|
||||
auto_created=True,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
verbose_name="ID",
|
||||
),
|
||||
),
|
||||
("ip_address", models.GenericIPAddressField(unpack_ipv4=True)),
|
||||
("add_date", models.DateTimeField()),
|
||||
("openid", models.URLField(max_length=255, unique=True)),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'confirmed OpenID',
|
||||
'verbose_name_plural': 'confirmed OpenIDs',
|
||||
"verbose_name": "confirmed OpenID",
|
||||
"verbose_name_plural": "confirmed OpenIDs",
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='Photo',
|
||||
name="Photo",
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('add_date', models.DateTimeField()),
|
||||
('ip_address', models.GenericIPAddressField(unpack_ipv4=True)),
|
||||
('data', models.BinaryField()),
|
||||
('format', models.CharField(max_length=3)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
|
||||
(
|
||||
"id",
|
||||
models.AutoField(
|
||||
auto_created=True,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
verbose_name="ID",
|
||||
),
|
||||
),
|
||||
("add_date", models.DateTimeField()),
|
||||
("ip_address", models.GenericIPAddressField(unpack_ipv4=True)),
|
||||
("data", models.BinaryField()),
|
||||
("format", models.CharField(max_length=3)),
|
||||
(
|
||||
"user",
|
||||
models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
to=settings.AUTH_USER_MODEL,
|
||||
),
|
||||
),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'photo',
|
||||
'verbose_name_plural': 'photos',
|
||||
"verbose_name": "photo",
|
||||
"verbose_name_plural": "photos",
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='UnconfirmedEmail',
|
||||
name="UnconfirmedEmail",
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('ip_address', models.GenericIPAddressField(unpack_ipv4=True)),
|
||||
('add_date', models.DateTimeField()),
|
||||
('email', models.EmailField(max_length=254)),
|
||||
('verification_key', models.CharField(max_length=64)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
|
||||
(
|
||||
"id",
|
||||
models.AutoField(
|
||||
auto_created=True,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
verbose_name="ID",
|
||||
),
|
||||
),
|
||||
("ip_address", models.GenericIPAddressField(unpack_ipv4=True)),
|
||||
("add_date", models.DateTimeField()),
|
||||
("email", models.EmailField(max_length=254)),
|
||||
("verification_key", models.CharField(max_length=64)),
|
||||
(
|
||||
"user",
|
||||
models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
to=settings.AUTH_USER_MODEL,
|
||||
),
|
||||
),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'unconfirmed_email',
|
||||
'verbose_name_plural': 'unconfirmed_emails',
|
||||
"verbose_name": "unconfirmed_email",
|
||||
"verbose_name_plural": "unconfirmed_emails",
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='UnconfirmedOpenId',
|
||||
name="UnconfirmedOpenId",
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('ip_address', models.GenericIPAddressField(unpack_ipv4=True)),
|
||||
('add_date', models.DateTimeField()),
|
||||
('openid', models.URLField(max_length=255)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
|
||||
(
|
||||
"id",
|
||||
models.AutoField(
|
||||
auto_created=True,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
verbose_name="ID",
|
||||
),
|
||||
),
|
||||
("ip_address", models.GenericIPAddressField(unpack_ipv4=True)),
|
||||
("add_date", models.DateTimeField()),
|
||||
("openid", models.URLField(max_length=255)),
|
||||
(
|
||||
"user",
|
||||
models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
to=settings.AUTH_USER_MODEL,
|
||||
),
|
||||
),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'unconfirmed OpenID',
|
||||
'verbose_name_plural': 'unconfirmed_OpenIDs',
|
||||
"verbose_name": "unconfirmed OpenID",
|
||||
"verbose_name_plural": "unconfirmed_OpenIDs",
|
||||
},
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='confirmedopenid',
|
||||
name='photo',
|
||||
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='openids', to='ivataraccount.Photo'),
|
||||
model_name="confirmedopenid",
|
||||
name="photo",
|
||||
field=models.ForeignKey(
|
||||
blank=True,
|
||||
null=True,
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
related_name="openids",
|
||||
to="ivataraccount.Photo",
|
||||
),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='confirmedopenid',
|
||||
name='user',
|
||||
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
|
||||
model_name="confirmedopenid",
|
||||
name="user",
|
||||
field=models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL
|
||||
),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='confirmedemail',
|
||||
name='photo',
|
||||
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='emails', to='ivataraccount.Photo'),
|
||||
model_name="confirmedemail",
|
||||
name="photo",
|
||||
field=models.ForeignKey(
|
||||
blank=True,
|
||||
null=True,
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
related_name="emails",
|
||||
to="ivataraccount.Photo",
|
||||
),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='confirmedemail',
|
||||
name='user',
|
||||
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
|
||||
model_name="confirmedemail",
|
||||
name="user",
|
||||
field=models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL
|
||||
),
|
||||
),
|
||||
]
|
||||
|
||||
@@ -6,29 +6,45 @@ from django.db import migrations, models
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('ivataraccount', '0001_initial'),
|
||||
("ivataraccount", "0001_initial"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='OpenIDAssociation',
|
||||
name="OpenIDAssociation",
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('server_url', models.TextField(max_length=2047)),
|
||||
('handle', models.CharField(max_length=255)),
|
||||
('secret', models.TextField(max_length=255)),
|
||||
('issued', models.IntegerField()),
|
||||
('lifetime', models.IntegerField()),
|
||||
('assoc_type', models.TextField(max_length=64)),
|
||||
(
|
||||
"id",
|
||||
models.AutoField(
|
||||
auto_created=True,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
verbose_name="ID",
|
||||
),
|
||||
),
|
||||
("server_url", models.TextField(max_length=2047)),
|
||||
("handle", models.CharField(max_length=255)),
|
||||
("secret", models.TextField(max_length=255)),
|
||||
("issued", models.IntegerField()),
|
||||
("lifetime", models.IntegerField()),
|
||||
("assoc_type", models.TextField(max_length=64)),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='OpenIDNonce',
|
||||
name="OpenIDNonce",
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('server_url', models.CharField(max_length=255)),
|
||||
('timestamp', models.IntegerField()),
|
||||
('salt', models.CharField(max_length=128)),
|
||||
(
|
||||
"id",
|
||||
models.AutoField(
|
||||
auto_created=True,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
verbose_name="ID",
|
||||
),
|
||||
),
|
||||
("server_url", models.CharField(max_length=255)),
|
||||
("timestamp", models.IntegerField()),
|
||||
("salt", models.CharField(max_length=128)),
|
||||
],
|
||||
),
|
||||
]
|
||||
|
||||
@@ -7,53 +7,53 @@ from django.db import migrations, models
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('ivataraccount', '0002_openidassociation_openidnonce'),
|
||||
("ivataraccount", "0002_openidassociation_openidnonce"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='confirmedemail',
|
||||
name='add_date',
|
||||
model_name="confirmedemail",
|
||||
name="add_date",
|
||||
field=models.DateTimeField(default=datetime.datetime.utcnow),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='confirmedemail',
|
||||
name='ip_address',
|
||||
model_name="confirmedemail",
|
||||
name="ip_address",
|
||||
field=models.GenericIPAddressField(null=True, unpack_ipv4=True),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='confirmedopenid',
|
||||
name='add_date',
|
||||
model_name="confirmedopenid",
|
||||
name="add_date",
|
||||
field=models.DateTimeField(default=datetime.datetime.utcnow),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='confirmedopenid',
|
||||
name='ip_address',
|
||||
model_name="confirmedopenid",
|
||||
name="ip_address",
|
||||
field=models.GenericIPAddressField(null=True, unpack_ipv4=True),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='photo',
|
||||
name='add_date',
|
||||
model_name="photo",
|
||||
name="add_date",
|
||||
field=models.DateTimeField(default=datetime.datetime.utcnow),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='unconfirmedemail',
|
||||
name='add_date',
|
||||
model_name="unconfirmedemail",
|
||||
name="add_date",
|
||||
field=models.DateTimeField(default=datetime.datetime.utcnow),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='unconfirmedemail',
|
||||
name='ip_address',
|
||||
model_name="unconfirmedemail",
|
||||
name="ip_address",
|
||||
field=models.GenericIPAddressField(null=True, unpack_ipv4=True),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='unconfirmedopenid',
|
||||
name='add_date',
|
||||
model_name="unconfirmedopenid",
|
||||
name="add_date",
|
||||
field=models.DateTimeField(default=datetime.datetime.utcnow),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='unconfirmedopenid',
|
||||
name='ip_address',
|
||||
model_name="unconfirmedopenid",
|
||||
name="ip_address",
|
||||
field=models.GenericIPAddressField(null=True, unpack_ipv4=True),
|
||||
),
|
||||
]
|
||||
|
||||
@@ -7,33 +7,33 @@ import django.utils.timezone
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('ivataraccount', '0003_auto_20180508_0637'),
|
||||
("ivataraccount", "0003_auto_20180508_0637"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='confirmedemail',
|
||||
name='add_date',
|
||||
model_name="confirmedemail",
|
||||
name="add_date",
|
||||
field=models.DateTimeField(default=django.utils.timezone.now),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='confirmedopenid',
|
||||
name='add_date',
|
||||
model_name="confirmedopenid",
|
||||
name="add_date",
|
||||
field=models.DateTimeField(default=django.utils.timezone.now),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='photo',
|
||||
name='add_date',
|
||||
model_name="photo",
|
||||
name="add_date",
|
||||
field=models.DateTimeField(default=django.utils.timezone.now),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='unconfirmedemail',
|
||||
name='add_date',
|
||||
model_name="unconfirmedemail",
|
||||
name="add_date",
|
||||
field=models.DateTimeField(default=django.utils.timezone.now),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='unconfirmedopenid',
|
||||
name='add_date',
|
||||
model_name="unconfirmedopenid",
|
||||
name="add_date",
|
||||
field=models.DateTimeField(default=django.utils.timezone.now),
|
||||
),
|
||||
]
|
||||
|
||||
@@ -6,20 +6,20 @@ from django.db import migrations, models
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('ivataraccount', '0004_auto_20180508_0742'),
|
||||
("ivataraccount", "0004_auto_20180508_0742"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='confirmedemail',
|
||||
name='digest',
|
||||
field=models.CharField(default='', max_length=64),
|
||||
model_name="confirmedemail",
|
||||
name="digest",
|
||||
field=models.CharField(default="", max_length=64),
|
||||
preserve_default=False,
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='confirmedopenid',
|
||||
name='digest',
|
||||
field=models.CharField(default='', max_length=64),
|
||||
model_name="confirmedopenid",
|
||||
name="digest",
|
||||
field=models.CharField(default="", max_length=64),
|
||||
preserve_default=False,
|
||||
),
|
||||
]
|
||||
|
||||
@@ -6,18 +6,18 @@ from django.db import migrations, models
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('ivataraccount', '0005_auto_20180522_1155'),
|
||||
("ivataraccount", "0005_auto_20180522_1155"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='confirmedemail',
|
||||
name='digest_sha256',
|
||||
model_name="confirmedemail",
|
||||
name="digest_sha256",
|
||||
field=models.CharField(max_length=64, null=True),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='confirmedemail',
|
||||
name='digest',
|
||||
model_name="confirmedemail",
|
||||
name="digest",
|
||||
field=models.CharField(max_length=32),
|
||||
),
|
||||
]
|
||||
|
||||
@@ -3,37 +3,50 @@
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
def add_sha256(apps, schema_editor):
|
||||
'''
|
||||
Make sure all ConfirmedEmail have digest_sha256 set
|
||||
in order to alter the model so sha256 may not be NULL
|
||||
'''
|
||||
ConfirmedEmail = apps.get_model('ivataraccount', 'ConfirmedEmail')
|
||||
for mail in ConfirmedEmail.objects.filter(digest_sha256=None):
|
||||
mail.save() # pragma: no cover
|
||||
"""
|
||||
Make sure all ConfirmedEmail have digest_sha256 set
|
||||
in order to alter the model so sha256 may not be NULL
|
||||
"""
|
||||
ConfirmedEmail = apps.get_model("ivataraccount", "ConfirmedEmail")
|
||||
for mail in ConfirmedEmail.objects.filter(digest_sha256=None):
|
||||
mail.save() # pragma: no cover
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('ivataraccount', '0006_auto_20180626_1445'),
|
||||
("ivataraccount", "0006_auto_20180626_1445"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RunPython(add_sha256),
|
||||
migrations.AlterField(
|
||||
model_name='confirmedemail',
|
||||
name='digest_sha256',
|
||||
model_name="confirmedemail",
|
||||
name="digest_sha256",
|
||||
field=models.CharField(max_length=64),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='confirmedemail',
|
||||
name='photo',
|
||||
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='emails', to='ivataraccount.Photo'),
|
||||
model_name="confirmedemail",
|
||||
name="photo",
|
||||
field=models.ForeignKey(
|
||||
blank=True,
|
||||
null=True,
|
||||
on_delete=django.db.models.deletion.SET_NULL,
|
||||
related_name="emails",
|
||||
to="ivataraccount.Photo",
|
||||
),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='confirmedopenid',
|
||||
name='photo',
|
||||
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='openids', to='ivataraccount.Photo'),
|
||||
model_name="confirmedopenid",
|
||||
name="photo",
|
||||
field=models.ForeignKey(
|
||||
blank=True,
|
||||
null=True,
|
||||
on_delete=django.db.models.deletion.SET_NULL,
|
||||
related_name="openids",
|
||||
to="ivataraccount.Photo",
|
||||
),
|
||||
),
|
||||
]
|
||||
|
||||
@@ -7,11 +7,14 @@ import django.db.models.deletion
|
||||
|
||||
|
||||
def add_preference_to_user(apps, schema_editor): # pylint: disable=unused-argument
|
||||
'''
|
||||
"""
|
||||
Make sure all users have preferences set up
|
||||
'''
|
||||
"""
|
||||
from django.contrib.auth.models import User
|
||||
UserPreference = apps.get_model('ivataraccount', 'UserPreference') # pylint: disable=invalid-name
|
||||
|
||||
UserPreference = apps.get_model(
|
||||
"ivataraccount", "UserPreference"
|
||||
) # pylint: disable=invalid-name
|
||||
for user in User.objects.filter(userpreference=None):
|
||||
pref = UserPreference.objects.create(user_id=user.pk) # pragma: no cover
|
||||
pref.save() # pragma: no cover
|
||||
@@ -20,24 +23,34 @@ def add_preference_to_user(apps, schema_editor): # pylint: disable=unused-argum
|
||||
class Migration(migrations.Migration): # pylint: disable=missing-docstring
|
||||
|
||||
dependencies = [
|
||||
('auth', '0009_alter_user_last_name_max_length'),
|
||||
('ivataraccount', '0007_auto_20180627_0624'),
|
||||
("auth", "0009_alter_user_last_name_max_length"),
|
||||
("ivataraccount", "0007_auto_20180627_0624"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='UserPreference',
|
||||
name="UserPreference",
|
||||
fields=[
|
||||
('theme', models.CharField(
|
||||
choices=[
|
||||
('default', 'Default theme'),
|
||||
('clime', 'Climes theme')],
|
||||
default='default', max_length=10)),
|
||||
('user', models.OneToOneField(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
to=settings.AUTH_USER_MODEL)),
|
||||
(
|
||||
"theme",
|
||||
models.CharField(
|
||||
choices=[
|
||||
("default", "Default theme"),
|
||||
("clime", "Climes theme"),
|
||||
],
|
||||
default="default",
|
||||
max_length=10,
|
||||
),
|
||||
),
|
||||
(
|
||||
"user",
|
||||
models.OneToOneField(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
to=settings.AUTH_USER_MODEL,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
migrations.RunPython(add_preference_to_user),
|
||||
|
||||
@@ -6,13 +6,21 @@ from django.db import migrations, models
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('ivataraccount', '0008_userpreference'),
|
||||
("ivataraccount", "0008_userpreference"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='userpreference',
|
||||
name='theme',
|
||||
field=models.CharField(choices=[('default', 'Default theme'), ('clime', 'climes theme'), ('falko', 'falkos theme')], default='default', max_length=10),
|
||||
model_name="userpreference",
|
||||
name="theme",
|
||||
field=models.CharField(
|
||||
choices=[
|
||||
("default", "Default theme"),
|
||||
("clime", "climes theme"),
|
||||
("falko", "falkos theme"),
|
||||
],
|
||||
default="default",
|
||||
max_length=10,
|
||||
),
|
||||
),
|
||||
]
|
||||
|
||||
@@ -6,13 +6,17 @@ from django.db import migrations, models
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('ivataraccount', '0009_auto_20180705_1152'),
|
||||
("ivataraccount", "0009_auto_20180705_1152"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='userpreference',
|
||||
name='theme',
|
||||
field=models.CharField(choices=[('default', 'Default theme'), ('falko', 'falkos theme')], default='default', max_length=10),
|
||||
model_name="userpreference",
|
||||
name="theme",
|
||||
field=models.CharField(
|
||||
choices=[("default", "Default theme"), ("falko", "falkos theme")],
|
||||
default="default",
|
||||
max_length=10,
|
||||
),
|
||||
),
|
||||
]
|
||||
|
||||
@@ -6,18 +6,26 @@ from django.db import migrations, models
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('ivataraccount', '0010_auto_20180705_1201'),
|
||||
("ivataraccount", "0010_auto_20180705_1201"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='photo',
|
||||
name='access_count',
|
||||
model_name="photo",
|
||||
name="access_count",
|
||||
field=models.BigIntegerField(default=0, editable=False),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='userpreference',
|
||||
name='theme',
|
||||
field=models.CharField(choices=[('default', 'Default theme'), ('clime', 'climes theme'), ('falko', 'falkos theme')], default='default', max_length=10),
|
||||
model_name="userpreference",
|
||||
name="theme",
|
||||
field=models.CharField(
|
||||
choices=[
|
||||
("default", "Default theme"),
|
||||
("clime", "climes theme"),
|
||||
("falko", "falkos theme"),
|
||||
],
|
||||
default="default",
|
||||
max_length=10,
|
||||
),
|
||||
),
|
||||
]
|
||||
|
||||
@@ -6,18 +6,18 @@ from django.db import migrations, models
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('ivataraccount', '0011_auto_20181107_1550'),
|
||||
("ivataraccount", "0011_auto_20181107_1550"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='confirmedemail',
|
||||
name='access_count',
|
||||
model_name="confirmedemail",
|
||||
name="access_count",
|
||||
field=models.BigIntegerField(default=0, editable=False),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='confirmedopenid',
|
||||
name='access_count',
|
||||
model_name="confirmedopenid",
|
||||
name="access_count",
|
||||
field=models.BigIntegerField(default=0, editable=False),
|
||||
),
|
||||
]
|
||||
|
||||
@@ -6,13 +6,22 @@ from django.db import migrations, models
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('ivataraccount', '0012_auto_20181107_1732'),
|
||||
("ivataraccount", "0012_auto_20181107_1732"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='userpreference',
|
||||
name='theme',
|
||||
field=models.CharField(choices=[('default', 'Default theme'), ('clime', 'climes theme'), ('green', 'green theme'), ('red', 'red theme')], default='default', max_length=10),
|
||||
model_name="userpreference",
|
||||
name="theme",
|
||||
field=models.CharField(
|
||||
choices=[
|
||||
("default", "Default theme"),
|
||||
("clime", "climes theme"),
|
||||
("green", "green theme"),
|
||||
("red", "red theme"),
|
||||
],
|
||||
default="default",
|
||||
max_length=10,
|
||||
),
|
||||
),
|
||||
]
|
||||
|
||||
@@ -6,12 +6,15 @@ from django.db import migrations
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('ivataraccount', '0013_auto_20181203_1421'),
|
||||
("ivataraccount", "0013_auto_20181203_1421"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterModelOptions(
|
||||
name='unconfirmedemail',
|
||||
options={'verbose_name': 'unconfirmed email', 'verbose_name_plural': 'unconfirmed emails'},
|
||||
name="unconfirmedemail",
|
||||
options={
|
||||
"verbose_name": "unconfirmed email",
|
||||
"verbose_name_plural": "unconfirmed emails",
|
||||
},
|
||||
),
|
||||
]
|
||||
|
||||
@@ -6,23 +6,23 @@ from django.db import migrations, models
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('ivataraccount', '0014_auto_20190218_1602'),
|
||||
("ivataraccount", "0014_auto_20190218_1602"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='confirmedopenid',
|
||||
name='alt_digest1',
|
||||
model_name="confirmedopenid",
|
||||
name="alt_digest1",
|
||||
field=models.CharField(blank=True, default=None, max_length=64, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='confirmedopenid',
|
||||
name='alt_digest2',
|
||||
model_name="confirmedopenid",
|
||||
name="alt_digest2",
|
||||
field=models.CharField(blank=True, default=None, max_length=64, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='confirmedopenid',
|
||||
name='alt_digest3',
|
||||
model_name="confirmedopenid",
|
||||
name="alt_digest3",
|
||||
field=models.CharField(blank=True, default=None, max_length=64, null=True),
|
||||
),
|
||||
]
|
||||
|
||||
23
ivatar/ivataraccount/migrations/0016_auto_20210413_0904.py
Normal file
23
ivatar/ivataraccount/migrations/0016_auto_20210413_0904.py
Normal file
@@ -0,0 +1,23 @@
|
||||
# Generated by Django 3.1.7 on 2021-04-13 09:04
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
("ivataraccount", "0015_auto_20200225_0934"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name="unconfirmedemail",
|
||||
name="last_send_date",
|
||||
field=models.DateTimeField(blank=True, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="unconfirmedemail",
|
||||
name="last_status",
|
||||
field=models.TextField(blank=True, max_length=2047, null=True),
|
||||
),
|
||||
]
|
||||
62
ivatar/ivataraccount/migrations/0017_auto_20210528_1314.py
Normal file
62
ivatar/ivataraccount/migrations/0017_auto_20210528_1314.py
Normal file
@@ -0,0 +1,62 @@
|
||||
# Generated by Django 3.2.3 on 2021-05-28 13:14
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
("ivataraccount", "0016_auto_20210413_0904"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name="confirmedemail",
|
||||
name="id",
|
||||
field=models.BigAutoField(
|
||||
auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
|
||||
),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="confirmedopenid",
|
||||
name="id",
|
||||
field=models.BigAutoField(
|
||||
auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
|
||||
),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="openidassociation",
|
||||
name="id",
|
||||
field=models.BigAutoField(
|
||||
auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
|
||||
),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="openidnonce",
|
||||
name="id",
|
||||
field=models.BigAutoField(
|
||||
auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
|
||||
),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="photo",
|
||||
name="id",
|
||||
field=models.BigAutoField(
|
||||
auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
|
||||
),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="unconfirmedemail",
|
||||
name="id",
|
||||
field=models.BigAutoField(
|
||||
auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
|
||||
),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="unconfirmedopenid",
|
||||
name="id",
|
||||
field=models.BigAutoField(
|
||||
auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
|
||||
),
|
||||
),
|
||||
]
|
||||
18
ivatar/ivataraccount/migrations/0018_alter_photo_format.py
Normal file
18
ivatar/ivataraccount/migrations/0018_alter_photo_format.py
Normal file
@@ -0,0 +1,18 @@
|
||||
# Generated by Django 5.0 on 2024-05-31 15:00
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
("ivataraccount", "0017_auto_20210528_1314"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name="photo",
|
||||
name="format",
|
||||
field=models.CharField(max_length=4),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,18 @@
|
||||
# Generated by Django 5.1.5 on 2025-01-27 10:54
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
("ivataraccount", "0018_alter_photo_format"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name="confirmedemail",
|
||||
name="bluesky_handle",
|
||||
field=models.CharField(blank=True, max_length=256, null=True),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,18 @@
|
||||
# Generated by Django 5.1.5 on 2025-01-27 13:33
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
("ivataraccount", "0019_confirmedemail_bluesky_handle"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name="confirmedopenid",
|
||||
name="bluesky_handle",
|
||||
field=models.CharField(blank=True, max_length=256, null=True),
|
||||
),
|
||||
]
|
||||
129
ivatar/ivataraccount/migrations/0021_add_performance_indexes.py
Normal file
129
ivatar/ivataraccount/migrations/0021_add_performance_indexes.py
Normal file
@@ -0,0 +1,129 @@
|
||||
# Generated manually for performance optimization
|
||||
|
||||
from typing import Any, List, Tuple, Optional
|
||||
from django.db import migrations, connection
|
||||
|
||||
|
||||
def create_indexes(apps: Any, schema_editor: Any) -> None:
|
||||
"""
|
||||
Create performance indexes for both PostgreSQL and MySQL compatibility.
|
||||
Uses CONCURRENTLY for PostgreSQL production, regular CREATE INDEX for tests/transactions.
|
||||
"""
|
||||
db_engine = connection.vendor
|
||||
|
||||
indexes: List[Tuple[str, str, str, Optional[str]]] = [
|
||||
# ConfirmedEmail indexes
|
||||
("idx_cemail_digest", "ivataraccount_confirmedemail", "digest", None),
|
||||
(
|
||||
"idx_cemail_digest_sha256",
|
||||
"ivataraccount_confirmedemail",
|
||||
"digest_sha256",
|
||||
None,
|
||||
),
|
||||
(
|
||||
"idx_cemail_access_count",
|
||||
"ivataraccount_confirmedemail",
|
||||
"access_count",
|
||||
None,
|
||||
),
|
||||
(
|
||||
"idx_cemail_bluesky_handle",
|
||||
"ivataraccount_confirmedemail",
|
||||
"bluesky_handle",
|
||||
"WHERE bluesky_handle IS NOT NULL",
|
||||
),
|
||||
# Photo indexes
|
||||
("idx_photo_format", "ivataraccount_photo", "format", None),
|
||||
("idx_photo_access_count", "ivataraccount_photo", "access_count", None),
|
||||
# Composite indexes
|
||||
(
|
||||
"idx_cemail_user_access",
|
||||
"ivataraccount_confirmedemail",
|
||||
"user_id, access_count",
|
||||
None,
|
||||
),
|
||||
(
|
||||
"idx_cemail_photo_access",
|
||||
"ivataraccount_confirmedemail",
|
||||
"photo_id, access_count",
|
||||
None,
|
||||
),
|
||||
("idx_photo_user_format", "ivataraccount_photo", "user_id, format", None),
|
||||
]
|
||||
|
||||
with connection.cursor() as cursor:
|
||||
# Check if we're in a transaction (test environment)
|
||||
try:
|
||||
cursor.execute("SELECT 1")
|
||||
in_transaction = connection.in_atomic_block
|
||||
except Exception:
|
||||
in_transaction = True
|
||||
|
||||
for index_name, table_name, columns, where_clause in indexes:
|
||||
try:
|
||||
if db_engine == "postgresql":
|
||||
# Use CONCURRENTLY only if not in a transaction (production)
|
||||
# Use regular CREATE INDEX if in a transaction (tests)
|
||||
if in_transaction:
|
||||
# In transaction (test environment) - use regular CREATE INDEX
|
||||
if where_clause:
|
||||
sql = f"CREATE INDEX IF NOT EXISTS {index_name} ON {table_name}({columns}) {where_clause};"
|
||||
else:
|
||||
sql = f"CREATE INDEX IF NOT EXISTS {index_name} ON {table_name}({columns});"
|
||||
else:
|
||||
# Not in transaction (production) - use CONCURRENTLY
|
||||
if where_clause:
|
||||
sql = f"CREATE INDEX CONCURRENTLY IF NOT EXISTS {index_name} ON {table_name}({columns}) {where_clause};"
|
||||
else:
|
||||
sql = f"CREATE INDEX CONCURRENTLY IF NOT EXISTS {index_name} ON {table_name}({columns});"
|
||||
else:
|
||||
# MySQL and other databases - skip partial indexes
|
||||
if where_clause:
|
||||
print(
|
||||
f"Skipping partial index {index_name} for {db_engine} (not supported)"
|
||||
)
|
||||
continue
|
||||
sql = f"CREATE INDEX IF NOT EXISTS {index_name} ON {table_name}({columns});"
|
||||
|
||||
cursor.execute(sql)
|
||||
print(f"Created index: {index_name}")
|
||||
|
||||
except Exception as e:
|
||||
# Index might already exist or other error - log and continue
|
||||
print(f"Index {index_name} creation skipped: {e}")
|
||||
|
||||
|
||||
def drop_indexes(apps: Any, schema_editor: Any) -> None:
|
||||
"""
|
||||
Drop the performance indexes.
|
||||
"""
|
||||
indexes: List[str] = [
|
||||
"idx_cemail_digest",
|
||||
"idx_cemail_digest_sha256",
|
||||
"idx_cemail_access_count",
|
||||
"idx_cemail_bluesky_handle",
|
||||
"idx_photo_format",
|
||||
"idx_photo_access_count",
|
||||
"idx_cemail_user_access",
|
||||
"idx_cemail_photo_access",
|
||||
"idx_photo_user_format",
|
||||
]
|
||||
|
||||
with connection.cursor() as cursor:
|
||||
for index_name in indexes:
|
||||
try:
|
||||
cursor.execute(f"DROP INDEX IF EXISTS {index_name};")
|
||||
print(f"Dropped index: {index_name}")
|
||||
except Exception as e:
|
||||
print(f"Index {index_name} drop skipped: {e}")
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
("ivataraccount", "0020_confirmedopenid_bluesky_handle"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RunPython(create_indexes, drop_indexes),
|
||||
]
|
||||
@@ -1,6 +1,6 @@
|
||||
'''
|
||||
"""
|
||||
Our models for ivatar.ivataraccount
|
||||
'''
|
||||
"""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
@@ -8,8 +8,9 @@ import time
|
||||
from io import BytesIO
|
||||
from os import urandom
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import urlopen
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
from ivatar.utils import urlopen, Bluesky
|
||||
from urllib.parse import urlsplit, urlunsplit, quote
|
||||
import logging
|
||||
|
||||
from PIL import Image
|
||||
from django.contrib.auth.models import User
|
||||
@@ -18,7 +19,8 @@ from django.db import models
|
||||
from django.utils import timezone
|
||||
from django.http import HttpResponseRedirect
|
||||
from django.urls import reverse_lazy, reverse
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django.core.cache import cache
|
||||
from django.core.exceptions import ObjectDoesNotExist
|
||||
from django.core.mail import send_mail
|
||||
from django.template.loader import render_to_string
|
||||
@@ -28,57 +30,65 @@ from openid.store.interface import OpenIDStore
|
||||
|
||||
from libravatar import libravatar_url
|
||||
|
||||
from ivatar.settings import MAX_LENGTH_EMAIL, logger
|
||||
from ivatar.settings import MAX_LENGTH_EMAIL
|
||||
from ivatar.settings import MAX_PIXELS, AVATAR_MAX_SIZE, JPEG_QUALITY
|
||||
from ivatar.settings import MAX_LENGTH_URL
|
||||
from ivatar.settings import SECURE_BASE_URL, SITE_NAME, DEFAULT_FROM_EMAIL
|
||||
from ivatar.utils import openid_variations
|
||||
from .gravatar import get_photo as get_gravatar_photo
|
||||
|
||||
# Initialize logger
|
||||
logger = logging.getLogger("ivatar")
|
||||
|
||||
|
||||
def file_format(image_type):
|
||||
'''
|
||||
"""
|
||||
Helper method returning a short image type
|
||||
'''
|
||||
if image_type == 'JPEG':
|
||||
return 'jpg'
|
||||
elif image_type == 'PNG':
|
||||
return 'png'
|
||||
elif image_type == 'GIF':
|
||||
return 'gif'
|
||||
"""
|
||||
if image_type in ("JPEG", "MPO"):
|
||||
return "jpg"
|
||||
elif image_type == "PNG":
|
||||
return "png"
|
||||
elif image_type == "GIF":
|
||||
return "gif"
|
||||
elif image_type == "WEBP":
|
||||
return "webp"
|
||||
return None
|
||||
|
||||
|
||||
def pil_format(image_type):
|
||||
'''
|
||||
"""
|
||||
Helper method returning the 'encoder name' for PIL
|
||||
'''
|
||||
if image_type == 'jpg' or image_type == 'jpeg':
|
||||
return 'JPEG'
|
||||
elif image_type == 'png':
|
||||
return 'PNG'
|
||||
elif image_type == 'gif':
|
||||
return 'GIF'
|
||||
"""
|
||||
if image_type in ("jpg", "jpeg", "mpo"):
|
||||
return "JPEG"
|
||||
elif image_type == "png":
|
||||
return "PNG"
|
||||
elif image_type == "gif":
|
||||
return "GIF"
|
||||
elif image_type == "webp":
|
||||
return "WEBP"
|
||||
|
||||
logger.info('Unsupported file format: %s', image_type)
|
||||
logger.info("Unsupported file format: %s", image_type)
|
||||
return None
|
||||
|
||||
|
||||
class UserPreference(models.Model):
|
||||
'''
|
||||
"""
|
||||
Holds the user users preferences
|
||||
'''
|
||||
"""
|
||||
|
||||
THEMES = (
|
||||
('default', 'Default theme'),
|
||||
('clime', 'climes theme'),
|
||||
('green', 'green theme'),
|
||||
('red', 'red theme'),
|
||||
("default", "Default theme"),
|
||||
("clime", "climes theme"),
|
||||
("green", "green theme"),
|
||||
("red", "red theme"),
|
||||
)
|
||||
|
||||
theme = models.CharField(
|
||||
max_length=10,
|
||||
choices=THEMES,
|
||||
default='default',
|
||||
default="default",
|
||||
)
|
||||
|
||||
user = models.OneToOneField(
|
||||
@@ -88,13 +98,14 @@ class UserPreference(models.Model):
|
||||
)
|
||||
|
||||
def __str__(self):
|
||||
return 'Preference (%i) for %s' % (self.pk, self.user)
|
||||
return "Preference (%i) for %s" % (self.pk, self.user)
|
||||
|
||||
|
||||
class BaseAccountModel(models.Model):
|
||||
'''
|
||||
"""
|
||||
Base, abstract model, holding fields we use in all cases
|
||||
'''
|
||||
"""
|
||||
|
||||
user = models.ForeignKey(
|
||||
User,
|
||||
on_delete=models.deletion.CASCADE,
|
||||
@@ -103,56 +114,60 @@ class BaseAccountModel(models.Model):
|
||||
add_date = models.DateTimeField(default=timezone.now)
|
||||
|
||||
class Meta: # pylint: disable=too-few-public-methods
|
||||
'''
|
||||
"""
|
||||
Class attributes
|
||||
'''
|
||||
"""
|
||||
|
||||
abstract = True
|
||||
|
||||
|
||||
class Photo(BaseAccountModel):
|
||||
'''
|
||||
"""
|
||||
Model holding the photos and information about them
|
||||
'''
|
||||
"""
|
||||
|
||||
ip_address = models.GenericIPAddressField(unpack_ipv4=True)
|
||||
data = models.BinaryField()
|
||||
format = models.CharField(max_length=3)
|
||||
format = models.CharField(max_length=4)
|
||||
access_count = models.BigIntegerField(default=0, editable=False)
|
||||
|
||||
class Meta: # pylint: disable=too-few-public-methods
|
||||
'''
|
||||
"""
|
||||
Class attributes
|
||||
'''
|
||||
verbose_name = _('photo')
|
||||
verbose_name_plural = _('photos')
|
||||
"""
|
||||
|
||||
verbose_name = _("photo")
|
||||
verbose_name_plural = _("photos")
|
||||
indexes = [
|
||||
models.Index(fields=["format"], name="idx_photo_format"),
|
||||
models.Index(fields=["access_count"], name="idx_photo_access_count"),
|
||||
models.Index(fields=["user_id", "format"], name="idx_photo_user_format"),
|
||||
]
|
||||
|
||||
def import_image(self, service_name, email_address):
|
||||
'''
|
||||
"""
|
||||
Allow to import image from other (eg. Gravatar) service
|
||||
'''
|
||||
"""
|
||||
image_url = False
|
||||
|
||||
if service_name == 'Gravatar':
|
||||
gravatar = get_gravatar_photo(email_address)
|
||||
if gravatar:
|
||||
image_url = gravatar['image_url']
|
||||
if service_name == "Gravatar":
|
||||
if gravatar := get_gravatar_photo(email_address):
|
||||
image_url = gravatar["image_url"]
|
||||
|
||||
if service_name == 'Libravatar':
|
||||
if service_name == "Libravatar":
|
||||
image_url = libravatar_url(email_address, size=AVATAR_MAX_SIZE)
|
||||
|
||||
if not image_url:
|
||||
return False # pragma: no cover
|
||||
try:
|
||||
image = urlopen(image_url)
|
||||
# No idea how to test this
|
||||
# pragma: no cover
|
||||
except HTTPError as exc:
|
||||
print('%s import failed with an HTTP error: %s' %
|
||||
(service_name, exc.code))
|
||||
logger.warning(
|
||||
f"{service_name} import failed with an HTTP error: {exc.code}"
|
||||
)
|
||||
return False
|
||||
# No idea how to test this
|
||||
# pragma: no cover
|
||||
except URLError as exc:
|
||||
print('%s import failed: %s' % (service_name, exc.reason))
|
||||
logger.warning(f"{service_name} import failed: {exc.reason}")
|
||||
return False
|
||||
data = image.read()
|
||||
|
||||
@@ -164,35 +179,35 @@ class Photo(BaseAccountModel):
|
||||
|
||||
self.format = file_format(img.format)
|
||||
if not self.format:
|
||||
print('Unable to determine format: %s' % img) # pragma: no cover
|
||||
logger.warning(f"Unable to determine format: {img}")
|
||||
return False # pragma: no cover
|
||||
self.data = data
|
||||
super().save()
|
||||
return True
|
||||
|
||||
def save(self, force_insert=False, force_update=False, using=None,
|
||||
update_fields=None):
|
||||
'''
|
||||
def save(
|
||||
self, force_insert=False, force_update=False, using=None, update_fields=None
|
||||
):
|
||||
"""
|
||||
Override save from parent, taking care about the image
|
||||
'''
|
||||
"""
|
||||
# Use PIL to read the file format
|
||||
try:
|
||||
img = Image.open(BytesIO(self.data))
|
||||
# Testing? Ideas anyone?
|
||||
except Exception as exc: # pylint: disable=broad-except
|
||||
# For debugging only
|
||||
print('Exception caught in Photo.save(): %s' % exc)
|
||||
logger.error(f"Exception caught in Photo.save(): {exc}")
|
||||
return False
|
||||
self.format = file_format(img.format)
|
||||
if not self.format:
|
||||
print('Format not recognized')
|
||||
logger.error("Format not recognized")
|
||||
return False
|
||||
return super().save(force_insert, force_update, using, update_fields)
|
||||
|
||||
def perform_crop(self, request, dimensions, email, openid):
|
||||
'''
|
||||
"""
|
||||
Helper to crop the image
|
||||
'''
|
||||
"""
|
||||
if request.user.photo_set.count() == 1:
|
||||
# This is the first photo, assign to all confirmed addresses
|
||||
for addr in request.user.confirmedemail_set.all():
|
||||
@@ -217,40 +232,46 @@ class Photo(BaseAccountModel):
|
||||
img = Image.open(BytesIO(self.data))
|
||||
|
||||
# This should be anyway checked during save...
|
||||
dimensions['a'], \
|
||||
dimensions['b'] = img.size # pylint: disable=invalid-name
|
||||
if dimensions['a'] > MAX_PIXELS or dimensions['b'] > MAX_PIXELS:
|
||||
dimensions["a"], dimensions["b"] = img.size # pylint: disable=invalid-name
|
||||
if dimensions["a"] > MAX_PIXELS or dimensions["b"] > MAX_PIXELS:
|
||||
messages.error(
|
||||
request,
|
||||
_('Image dimensions are too big (max: %(max_pixels)s x %(max_pixels)s' % {
|
||||
max_pixels: MAX_PIXELS,
|
||||
}))
|
||||
return HttpResponseRedirect(reverse_lazy('profile'))
|
||||
_(
|
||||
"Image dimensions are too big (max: %(max_pixels)s x %(max_pixels)s"
|
||||
% {
|
||||
"max_pixels": MAX_PIXELS,
|
||||
}
|
||||
),
|
||||
)
|
||||
return HttpResponseRedirect(reverse_lazy("profile"))
|
||||
|
||||
if dimensions['w'] == 0 and dimensions['h'] == 0:
|
||||
dimensions['w'], dimensions['h'] = dimensions['a'], dimensions['b']
|
||||
min_from_w_h = min(dimensions['w'], dimensions['h'])
|
||||
dimensions['w'], dimensions['h'] = min_from_w_h, min_from_w_h
|
||||
elif ((dimensions['w'] < 0)
|
||||
or ((dimensions['x'] + dimensions['w']) > dimensions['a'])
|
||||
or (dimensions['h'] < 0)
|
||||
or ((dimensions['y'] + dimensions['h']) > dimensions['b'])):
|
||||
messages.error(
|
||||
request,
|
||||
_('Crop outside of original image bounding box'))
|
||||
return HttpResponseRedirect(reverse_lazy('profile'))
|
||||
if dimensions["w"] == 0 and dimensions["h"] == 0:
|
||||
dimensions["w"], dimensions["h"] = dimensions["a"], dimensions["b"]
|
||||
min_from_w_h = min(dimensions["w"], dimensions["h"])
|
||||
dimensions["w"], dimensions["h"] = min_from_w_h, min_from_w_h
|
||||
elif (
|
||||
(dimensions["w"] < 0)
|
||||
or ((dimensions["x"] + dimensions["w"]) > dimensions["a"])
|
||||
or (dimensions["h"] < 0)
|
||||
or ((dimensions["y"] + dimensions["h"]) > dimensions["b"])
|
||||
):
|
||||
messages.error(request, _("Crop outside of original image bounding box"))
|
||||
return HttpResponseRedirect(reverse_lazy("profile"))
|
||||
|
||||
cropped = img.crop((
|
||||
dimensions['x'],
|
||||
dimensions['y'],
|
||||
dimensions['x'] + dimensions['w'],
|
||||
dimensions['y'] + dimensions['h']))
|
||||
cropped = img.crop(
|
||||
(
|
||||
dimensions["x"],
|
||||
dimensions["y"],
|
||||
dimensions["x"] + dimensions["w"],
|
||||
dimensions["y"] + dimensions["h"],
|
||||
)
|
||||
)
|
||||
# cropped.load()
|
||||
# Resize the image only if it's larger than the specified max width.
|
||||
cropped_w, cropped_h = cropped.size
|
||||
max_w = AVATAR_MAX_SIZE
|
||||
if cropped_w > max_w or cropped_h > max_w:
|
||||
cropped = cropped.resize((max_w, max_w), Image.ANTIALIAS)
|
||||
cropped = cropped.resize((max_w, max_w), Image.LANCZOS)
|
||||
|
||||
data = BytesIO()
|
||||
cropped.save(data, pil_format(self.format), quality=JPEG_QUALITY)
|
||||
@@ -260,165 +281,240 @@ class Photo(BaseAccountModel):
|
||||
self.data = data.read()
|
||||
self.save()
|
||||
|
||||
return HttpResponseRedirect(reverse_lazy('profile'))
|
||||
return HttpResponseRedirect(reverse_lazy("profile"))
|
||||
|
||||
def __str__(self):
|
||||
return '%s (%i) from %s' % (self.format, self.pk or 0, self.user)
|
||||
return "%s (%i) from %s" % (self.format, self.pk or 0, self.user)
|
||||
|
||||
|
||||
# pylint: disable=too-few-public-methods
|
||||
class ConfirmedEmailManager(models.Manager):
|
||||
'''
|
||||
"""
|
||||
Manager for our confirmed email addresses model
|
||||
'''
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def create_confirmed_email(user, email_address, is_logged_in):
|
||||
'''
|
||||
"""
|
||||
Helper method to create confirmed email address
|
||||
'''
|
||||
"""
|
||||
confirmed = ConfirmedEmail()
|
||||
confirmed.user = user
|
||||
confirmed.ip_address = '0.0.0.0'
|
||||
confirmed.ip_address = "0.0.0.0"
|
||||
confirmed.email = email_address
|
||||
confirmed.save()
|
||||
|
||||
external_photos = []
|
||||
if is_logged_in:
|
||||
gravatar = get_gravatar_photo(confirmed.email)
|
||||
if gravatar:
|
||||
if gravatar := get_gravatar_photo(confirmed.email):
|
||||
external_photos.append(gravatar)
|
||||
|
||||
return (confirmed.pk, external_photos)
|
||||
|
||||
|
||||
class ConfirmedEmail(BaseAccountModel):
|
||||
'''
|
||||
"""
|
||||
Model holding our confirmed email addresses, as well as the relation
|
||||
to the assigned photo
|
||||
'''
|
||||
"""
|
||||
|
||||
email = models.EmailField(unique=True, max_length=MAX_LENGTH_EMAIL)
|
||||
photo = models.ForeignKey(
|
||||
Photo,
|
||||
related_name='emails',
|
||||
related_name="emails",
|
||||
blank=True,
|
||||
null=True,
|
||||
on_delete=models.deletion.SET_NULL,
|
||||
)
|
||||
# Alternative assignment - use Bluesky handle
|
||||
bluesky_handle = models.CharField(max_length=256, null=True, blank=True)
|
||||
digest = models.CharField(max_length=32)
|
||||
digest_sha256 = models.CharField(max_length=64)
|
||||
objects = ConfirmedEmailManager()
|
||||
access_count = models.BigIntegerField(default=0, editable=False)
|
||||
|
||||
class Meta: # pylint: disable=too-few-public-methods
|
||||
'''
|
||||
"""
|
||||
Class attributes
|
||||
'''
|
||||
verbose_name = _('confirmed email')
|
||||
verbose_name_plural = _('confirmed emails')
|
||||
"""
|
||||
|
||||
verbose_name = _("confirmed email")
|
||||
verbose_name_plural = _("confirmed emails")
|
||||
indexes = [
|
||||
models.Index(fields=["digest"], name="idx_cemail_digest"),
|
||||
models.Index(fields=["digest_sha256"], name="idx_cemail_digest_sha256"),
|
||||
models.Index(fields=["access_count"], name="idx_cemail_access_count"),
|
||||
models.Index(fields=["bluesky_handle"], name="idx_cemail_bluesky_handle"),
|
||||
models.Index(
|
||||
fields=["user_id", "access_count"],
|
||||
name="idx_cemail_user_access",
|
||||
),
|
||||
models.Index(
|
||||
fields=["photo_id", "access_count"],
|
||||
name="idx_cemail_photo_access",
|
||||
),
|
||||
]
|
||||
|
||||
def set_photo(self, photo):
|
||||
'''
|
||||
"""
|
||||
Helper method to set photo
|
||||
'''
|
||||
"""
|
||||
self.photo = photo
|
||||
self.save()
|
||||
|
||||
def save(self, force_insert=False, force_update=False, using=None,
|
||||
update_fields=None):
|
||||
'''
|
||||
def set_bluesky_handle(self, handle):
|
||||
"""
|
||||
Helper method to set Bluesky handle
|
||||
"""
|
||||
|
||||
bs = Bluesky()
|
||||
handle = bs.normalize_handle(handle)
|
||||
avatar = bs.get_profile(handle)
|
||||
if not avatar:
|
||||
raise ValueError("Invalid Bluesky handle")
|
||||
self.bluesky_handle = handle
|
||||
self.save()
|
||||
|
||||
def save(
|
||||
self, force_insert=False, force_update=False, using=None, update_fields=None
|
||||
):
|
||||
"""
|
||||
Override save from parent, add digest
|
||||
'''
|
||||
"""
|
||||
self.digest = hashlib.md5(
|
||||
self.email.strip().lower().encode('utf-8')
|
||||
self.email.strip().lower().encode("utf-8")
|
||||
).hexdigest()
|
||||
self.digest_sha256 = hashlib.sha256(
|
||||
self.email.strip().lower().encode('utf-8')
|
||||
self.email.strip().lower().encode("utf-8")
|
||||
).hexdigest()
|
||||
|
||||
# We need to manually expire the page caches
|
||||
# TODO: Verify this works as expected
|
||||
# First check if we already have an ID
|
||||
if self.pk:
|
||||
cache_url = reverse_lazy(
|
||||
"assign_photo_email", kwargs={"email_id": int(self.pk)}
|
||||
)
|
||||
|
||||
cache_key = f"views.decorators.cache.cache_page.{quote(str(cache_url))}"
|
||||
try:
|
||||
if cache.has_key(cache_key):
|
||||
cache.delete(cache_key)
|
||||
logger.debug("Successfully cleaned up cached page: %s" % cache_key)
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"Failed to clean up cached page {}: {}".format(cache_key, exc)
|
||||
)
|
||||
|
||||
# Invalidate Bluesky avatar URL cache if bluesky_handle changed
|
||||
if hasattr(self, "bluesky_handle") and self.bluesky_handle:
|
||||
try:
|
||||
cache.delete(self.bluesky_handle)
|
||||
logger.debug(
|
||||
"Successfully cleaned up Bluesky avatar cache for handle: %s"
|
||||
% self.bluesky_handle
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"Failed to clean up Bluesky avatar cache for handle %s: %s"
|
||||
% (self.bluesky_handle, exc)
|
||||
)
|
||||
|
||||
return super().save(force_insert, force_update, using, update_fields)
|
||||
|
||||
def __str__(self):
|
||||
return '%s (%i) from %s' % (self.email, self.pk, self.user)
|
||||
return "%s (%i) from %s" % (self.email, self.pk, self.user)
|
||||
|
||||
|
||||
class UnconfirmedEmail(BaseAccountModel):
|
||||
'''
|
||||
"""
|
||||
Model holding unconfirmed email addresses as well as the verification key
|
||||
'''
|
||||
"""
|
||||
|
||||
email = models.EmailField(max_length=MAX_LENGTH_EMAIL)
|
||||
verification_key = models.CharField(max_length=64)
|
||||
last_send_date = models.DateTimeField(null=True, blank=True)
|
||||
last_status = models.TextField(max_length=2047, null=True, blank=True)
|
||||
|
||||
class Meta: # pylint: disable=too-few-public-methods
|
||||
'''
|
||||
"""
|
||||
Class attributes
|
||||
'''
|
||||
verbose_name = _('unconfirmed email')
|
||||
verbose_name_plural = _('unconfirmed emails')
|
||||
"""
|
||||
|
||||
def save(self, force_insert=False, force_update=False, using=None,
|
||||
update_fields=None):
|
||||
hash_object = hashlib.new('sha256')
|
||||
hash_object.update(
|
||||
urandom(1024) + self.user.username.encode('utf-8') # pylint: disable=no-member
|
||||
) # pylint: disable=no-member
|
||||
self.verification_key = hash_object.hexdigest()
|
||||
super(UnconfirmedEmail, self).save(
|
||||
force_insert,
|
||||
force_update,
|
||||
using,
|
||||
update_fields)
|
||||
verbose_name = _("unconfirmed email")
|
||||
verbose_name_plural = _("unconfirmed emails")
|
||||
|
||||
def save(
|
||||
self, force_insert=False, force_update=False, using=None, update_fields=None
|
||||
):
|
||||
if not self.verification_key:
|
||||
hash_object = hashlib.new("sha256")
|
||||
hash_object.update(
|
||||
urandom(1024)
|
||||
+ self.user.username.encode("utf-8") # pylint: disable=no-member
|
||||
) # pylint: disable=no-member
|
||||
self.verification_key = hash_object.hexdigest()
|
||||
super().save(force_insert, force_update, using, update_fields)
|
||||
|
||||
def send_confirmation_mail(self, url=SECURE_BASE_URL):
|
||||
'''
|
||||
"""
|
||||
Send confirmation mail to that mail address
|
||||
'''
|
||||
link = url + \
|
||||
reverse(
|
||||
'confirm_email',
|
||||
kwargs={'verification_key': self.verification_key})
|
||||
email_subject = _('Confirm your email address on %s') % \
|
||||
SITE_NAME
|
||||
email_body = render_to_string('email_confirmation.txt', {
|
||||
'verification_link': link,
|
||||
'site_name': SITE_NAME,
|
||||
})
|
||||
"""
|
||||
link = url + reverse(
|
||||
"confirm_email", kwargs={"verification_key": self.verification_key}
|
||||
)
|
||||
email_subject = _("Confirm your email address on %s") % SITE_NAME
|
||||
email_body = render_to_string(
|
||||
"email_confirmation.txt",
|
||||
{
|
||||
"verification_link": link,
|
||||
"site_name": SITE_NAME,
|
||||
},
|
||||
)
|
||||
self.last_send_date = timezone.now()
|
||||
self.last_status = "OK"
|
||||
# if settings.DEBUG:
|
||||
# print('DEBUG: %s' % link)
|
||||
send_mail(
|
||||
email_subject, email_body, DEFAULT_FROM_EMAIL,
|
||||
[self.email])
|
||||
try:
|
||||
send_mail(email_subject, email_body, DEFAULT_FROM_EMAIL, [self.email])
|
||||
except Exception as e:
|
||||
self.last_status = f"{e}"
|
||||
self.save()
|
||||
return True
|
||||
|
||||
def __str__(self):
|
||||
return '%s (%i) from %s' % (self.email, self.pk, self.user)
|
||||
return "%s (%i) from %s" % (self.email, self.pk, self.user)
|
||||
|
||||
|
||||
class UnconfirmedOpenId(BaseAccountModel):
|
||||
'''
|
||||
"""
|
||||
Model holding unconfirmed OpenIDs
|
||||
'''
|
||||
"""
|
||||
|
||||
openid = models.URLField(unique=False, max_length=MAX_LENGTH_URL)
|
||||
|
||||
class Meta: # pylint: disable=too-few-public-methods
|
||||
'''
|
||||
"""
|
||||
Meta class
|
||||
'''
|
||||
verbose_name = _('unconfirmed OpenID')
|
||||
verbose_name_plural = ('unconfirmed_OpenIDs')
|
||||
"""
|
||||
|
||||
verbose_name = _("unconfirmed OpenID")
|
||||
verbose_name_plural = "unconfirmed_OpenIDs"
|
||||
|
||||
def __str__(self):
|
||||
return '%s (%i) from %s' % (self.openid, self.pk, self.user)
|
||||
return "%s (%i) from %s" % (self.openid, self.pk, self.user)
|
||||
|
||||
|
||||
class ConfirmedOpenId(BaseAccountModel):
|
||||
'''
|
||||
"""
|
||||
Model holding confirmed OpenIDs, as well as the relation to
|
||||
the assigned photo
|
||||
'''
|
||||
"""
|
||||
|
||||
openid = models.URLField(unique=True, max_length=MAX_LENGTH_URL)
|
||||
photo = models.ForeignKey(
|
||||
Photo,
|
||||
related_name='openids',
|
||||
related_name="openids",
|
||||
blank=True,
|
||||
null=True,
|
||||
on_delete=models.deletion.SET_NULL,
|
||||
@@ -431,29 +527,45 @@ class ConfirmedOpenId(BaseAccountModel):
|
||||
alt_digest2 = models.CharField(max_length=64, null=True, blank=True, default=None)
|
||||
# https://<id> - https w/o trailing slash
|
||||
alt_digest3 = models.CharField(max_length=64, null=True, blank=True, default=None)
|
||||
# Alternative assignment - use Bluesky handle
|
||||
bluesky_handle = models.CharField(max_length=256, null=True, blank=True)
|
||||
|
||||
access_count = models.BigIntegerField(default=0, editable=False)
|
||||
|
||||
class Meta: # pylint: disable=too-few-public-methods
|
||||
'''
|
||||
"""
|
||||
Meta class
|
||||
'''
|
||||
verbose_name = _('confirmed OpenID')
|
||||
verbose_name_plural = _('confirmed OpenIDs')
|
||||
"""
|
||||
|
||||
verbose_name = _("confirmed OpenID")
|
||||
verbose_name_plural = _("confirmed OpenIDs")
|
||||
|
||||
def set_photo(self, photo):
|
||||
'''
|
||||
"""
|
||||
Helper method to save photo
|
||||
'''
|
||||
"""
|
||||
self.photo = photo
|
||||
self.save()
|
||||
|
||||
def save(self, force_insert=False, force_update=False, using=None,
|
||||
update_fields=None):
|
||||
def set_bluesky_handle(self, handle):
|
||||
"""
|
||||
Helper method to set Bluesky handle
|
||||
"""
|
||||
bs = Bluesky()
|
||||
handle = bs.normalize_handle(handle)
|
||||
avatar = bs.get_profile(handle)
|
||||
if not avatar:
|
||||
raise ValueError("Invalid Bluesky handle")
|
||||
self.bluesky_handle = handle
|
||||
self.save()
|
||||
|
||||
def save(
|
||||
self, force_insert=False, force_update=False, using=None, update_fields=None
|
||||
):
|
||||
url = urlsplit(self.openid)
|
||||
if url.username: # pragma: no cover
|
||||
password = url.password or ''
|
||||
netloc = url.username + ':' + password + '@' + url.hostname
|
||||
password = url.password or ""
|
||||
netloc = f"{url.username}:{password}@{url.hostname}"
|
||||
else:
|
||||
netloc = url.hostname
|
||||
lowercase_url = urlunsplit(
|
||||
@@ -461,37 +573,74 @@ class ConfirmedOpenId(BaseAccountModel):
|
||||
)
|
||||
self.openid = lowercase_url
|
||||
|
||||
self.digest = hashlib.sha256(openid_variations(lowercase_url)[0].encode('utf-8')).hexdigest()
|
||||
self.alt_digest1 = hashlib.sha256(openid_variations(lowercase_url)[1].encode('utf-8')).hexdigest()
|
||||
self.alt_digest2 = hashlib.sha256(openid_variations(lowercase_url)[2].encode('utf-8')).hexdigest()
|
||||
self.alt_digest3 = hashlib.sha256(openid_variations(lowercase_url)[3].encode('utf-8')).hexdigest()
|
||||
self.digest = hashlib.sha256(
|
||||
openid_variations(lowercase_url)[0].encode("utf-8")
|
||||
).hexdigest()
|
||||
self.alt_digest1 = hashlib.sha256(
|
||||
openid_variations(lowercase_url)[1].encode("utf-8")
|
||||
).hexdigest()
|
||||
self.alt_digest2 = hashlib.sha256(
|
||||
openid_variations(lowercase_url)[2].encode("utf-8")
|
||||
).hexdigest()
|
||||
self.alt_digest3 = hashlib.sha256(
|
||||
openid_variations(lowercase_url)[3].encode("utf-8")
|
||||
).hexdigest()
|
||||
|
||||
# Invalidate page caches and Bluesky avatar cache
|
||||
if self.pk:
|
||||
# Invalidate assign_photo_openid page cache
|
||||
cache_url = reverse_lazy(
|
||||
"assign_photo_openid", kwargs={"openid_id": int(self.pk)}
|
||||
)
|
||||
cache_key = f"views.decorators.cache.cache_page.{quote(str(cache_url))}"
|
||||
try:
|
||||
if cache.has_key(cache_key):
|
||||
cache.delete(cache_key)
|
||||
logger.debug("Successfully cleaned up cached page: %s" % cache_key)
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"Failed to clean up cached page {}: {}".format(cache_key, exc)
|
||||
)
|
||||
|
||||
# Invalidate Bluesky avatar URL cache if bluesky_handle exists
|
||||
if hasattr(self, "bluesky_handle") and self.bluesky_handle:
|
||||
try:
|
||||
cache.delete(self.bluesky_handle)
|
||||
logger.debug(
|
||||
"Successfully cleaned up Bluesky avatar cache for handle: %s"
|
||||
% self.bluesky_handle
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"Failed to clean up Bluesky avatar cache for handle %s: %s"
|
||||
% (self.bluesky_handle, exc)
|
||||
)
|
||||
|
||||
return super().save(force_insert, force_update, using, update_fields)
|
||||
|
||||
def __str__(self):
|
||||
return '%s (%i) (%s)' % (self.openid, self.pk, self.user)
|
||||
return "%s (%i) (%s)" % (self.openid, self.pk, self.user)
|
||||
|
||||
|
||||
class OpenIDNonce(models.Model):
|
||||
'''
|
||||
"""
|
||||
Model holding OpenID Nonces
|
||||
See also: https://github.com/edx/django-openid-auth/
|
||||
'''
|
||||
"""
|
||||
|
||||
server_url = models.CharField(max_length=255)
|
||||
timestamp = models.IntegerField()
|
||||
salt = models.CharField(max_length=128)
|
||||
|
||||
def __str__(self):
|
||||
return '%s (%i) (timestamp: %i)' % (
|
||||
self.server_url,
|
||||
self.pk,
|
||||
self.timestamp)
|
||||
return "%s (%i) (timestamp: %i)" % (self.server_url, self.pk, self.timestamp)
|
||||
|
||||
|
||||
class OpenIDAssociation(models.Model):
|
||||
'''
|
||||
"""
|
||||
Model holding the relation/association about OpenIDs
|
||||
'''
|
||||
"""
|
||||
|
||||
server_url = models.TextField(max_length=2047)
|
||||
handle = models.CharField(max_length=255)
|
||||
secret = models.TextField(max_length=255) # stored base64 encoded
|
||||
@@ -500,56 +649,62 @@ class OpenIDAssociation(models.Model):
|
||||
assoc_type = models.TextField(max_length=64)
|
||||
|
||||
def __str__(self):
|
||||
return '%s (%i) (%s, lifetime: %i)' % (
|
||||
return "%s (%i) (%s, lifetime: %i)" % (
|
||||
self.server_url,
|
||||
self.pk,
|
||||
self.assoc_type,
|
||||
self.lifetime)
|
||||
self.lifetime,
|
||||
)
|
||||
|
||||
|
||||
class DjangoOpenIDStore(OpenIDStore):
|
||||
'''
|
||||
"""
|
||||
The Python openid library needs an OpenIDStore subclass to persist data
|
||||
related to OpenID authentications. This one uses our Django models.
|
||||
'''
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def storeAssociation(server_url, association): # pragma: no cover
|
||||
'''
|
||||
"""
|
||||
Helper method to store associations
|
||||
'''
|
||||
"""
|
||||
assoc = OpenIDAssociation(
|
||||
server_url=server_url,
|
||||
handle=association.handle,
|
||||
secret=base64.encodebytes(association.secret),
|
||||
issued=association.issued,
|
||||
lifetime=association.issued,
|
||||
assoc_type=association.assoc_type)
|
||||
assoc_type=association.assoc_type,
|
||||
)
|
||||
assoc.save()
|
||||
|
||||
def getAssociation(self, server_url, handle=None): # pragma: no cover
|
||||
'''
|
||||
"""
|
||||
Helper method to get associations
|
||||
'''
|
||||
"""
|
||||
assocs = []
|
||||
if handle is not None:
|
||||
assocs = OpenIDAssociation.objects.filter( # pylint: disable=no-member
|
||||
server_url=server_url,
|
||||
handle=handle)
|
||||
server_url=server_url, handle=handle
|
||||
)
|
||||
else:
|
||||
assocs = OpenIDAssociation.objects.filter( # pylint: disable=no-member
|
||||
server_url=server_url)
|
||||
server_url=server_url
|
||||
)
|
||||
if not assocs:
|
||||
return None
|
||||
associations = []
|
||||
for assoc in assocs:
|
||||
if isinstance(assoc.secret, str):
|
||||
assoc.secret = assoc.secret.split("b'")[1].split("'")[0]
|
||||
assoc.secret = bytes(assoc.secret, 'utf-8')
|
||||
association = OIDAssociation(assoc.handle,
|
||||
base64.decodebytes(assoc.secret),
|
||||
assoc.issued, assoc.lifetime,
|
||||
assoc.assoc_type)
|
||||
assoc.secret = bytes(assoc.secret, "utf-8")
|
||||
association = OIDAssociation(
|
||||
assoc.handle,
|
||||
base64.decodebytes(assoc.secret),
|
||||
assoc.issued,
|
||||
assoc.lifetime,
|
||||
assoc.assoc_type,
|
||||
)
|
||||
expires = 0
|
||||
try:
|
||||
# pylint: disable=no-member
|
||||
@@ -560,18 +715,18 @@ class DjangoOpenIDStore(OpenIDStore):
|
||||
self.removeAssociation(server_url, assoc.handle)
|
||||
else:
|
||||
associations.append((association.issued, association))
|
||||
if not associations:
|
||||
return None
|
||||
return associations[-1][1]
|
||||
return associations[-1][1] if associations else None
|
||||
|
||||
@staticmethod
|
||||
def removeAssociation(server_url, handle): # pragma: no cover
|
||||
'''
|
||||
"""
|
||||
Helper method to remove associations
|
||||
'''
|
||||
"""
|
||||
assocs = list(
|
||||
OpenIDAssociation.objects.filter( # pylint: disable=no-member
|
||||
server_url=server_url, handle=handle))
|
||||
server_url=server_url, handle=handle
|
||||
)
|
||||
)
|
||||
assocs_exist = len(assocs) > 0
|
||||
for assoc in assocs:
|
||||
assoc.delete()
|
||||
@@ -579,9 +734,9 @@ class DjangoOpenIDStore(OpenIDStore):
|
||||
|
||||
@staticmethod
|
||||
def useNonce(server_url, timestamp, salt): # pragma: no cover
|
||||
'''
|
||||
"""
|
||||
Helper method to 'use' nonces
|
||||
'''
|
||||
"""
|
||||
# Has nonce expired?
|
||||
if abs(timestamp - time.time()) > oidnonce.SKEW:
|
||||
return False
|
||||
@@ -589,27 +744,30 @@ class DjangoOpenIDStore(OpenIDStore):
|
||||
nonce = OpenIDNonce.objects.get( # pylint: disable=no-member
|
||||
server_url__exact=server_url,
|
||||
timestamp__exact=timestamp,
|
||||
salt__exact=salt)
|
||||
salt__exact=salt,
|
||||
)
|
||||
except ObjectDoesNotExist:
|
||||
nonce = OpenIDNonce.objects.create( # pylint: disable=no-member
|
||||
server_url=server_url, timestamp=timestamp, salt=salt)
|
||||
server_url=server_url, timestamp=timestamp, salt=salt
|
||||
)
|
||||
return True
|
||||
nonce.delete()
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def cleanupNonces(): # pragma: no cover
|
||||
'''
|
||||
"""
|
||||
Helper method to cleanup nonces
|
||||
'''
|
||||
"""
|
||||
timestamp = int(time.time()) - oidnonce.SKEW
|
||||
# pylint: disable=no-member
|
||||
OpenIDNonce.objects.filter(timestamp__lt=timestamp).delete()
|
||||
|
||||
@staticmethod
|
||||
def cleanupAssociations(): # pragma: no cover
|
||||
'''
|
||||
"""
|
||||
Helper method to cleanup associations
|
||||
'''
|
||||
OpenIDAssociation.objects.extra( # pylint: disable=no-member
|
||||
where=['issued + lifetimeint < (%s)' % time.time()]).delete()
|
||||
"""
|
||||
OpenIDAssociation.objects.extra(
|
||||
where=[f"issued + lifetimeint < ({time.time()})"]
|
||||
).delete()
|
||||
|
||||
@@ -1,84 +1,105 @@
|
||||
'''
|
||||
"""
|
||||
Reading libravatar export
|
||||
'''
|
||||
"""
|
||||
|
||||
import binascii
|
||||
import os
|
||||
from io import BytesIO
|
||||
import gzip
|
||||
import xml.etree.ElementTree
|
||||
import base64
|
||||
from PIL import Image
|
||||
import django
|
||||
import sys
|
||||
|
||||
sys.path.append(
|
||||
os.path.join(
|
||||
os.path.dirname(__file__),
|
||||
"..",
|
||||
"..",
|
||||
)
|
||||
)
|
||||
|
||||
SCHEMAROOT = 'https://www.libravatar.org/schemas/export/0.2'
|
||||
os.environ["DJANGO_SETTINGS_MODULE"] = "ivatar.settings"
|
||||
django.setup()
|
||||
|
||||
# pylint: disable=wrong-import-position
|
||||
from ivatar.settings import SCHEMAROOT
|
||||
|
||||
|
||||
def read_gzdata(gzdata=None):
|
||||
'''
|
||||
"""
|
||||
Read gzipped data file
|
||||
'''
|
||||
emails = [] # pylint: disable=invalid-name
|
||||
openids = [] # pylint: disable=invalid-name
|
||||
photos = [] # pylint: disable=invalid-name
|
||||
"""
|
||||
photos = [] # pylint: disable=invalid-name
|
||||
username = None # pylint: disable=invalid-name
|
||||
password = None # pylint: disable=invalid-name
|
||||
|
||||
if not gzdata:
|
||||
return False
|
||||
|
||||
fh = gzip.open(BytesIO(gzdata), 'rb') # pylint: disable=invalid-name
|
||||
fh = gzip.open(BytesIO(gzdata), "rb") # pylint: disable=invalid-name
|
||||
content = fh.read()
|
||||
fh.close()
|
||||
root = xml.etree.ElementTree.fromstring(content)
|
||||
if not root.tag == '{%s}user' % SCHEMAROOT:
|
||||
print('Unknown export format: %s' % root.tag)
|
||||
if root.tag != "{%s}user" % SCHEMAROOT:
|
||||
print(f"Unknown export format: {root.tag}")
|
||||
exit(-1)
|
||||
|
||||
# Username
|
||||
for item in root.findall('{%s}account' % SCHEMAROOT)[0].items():
|
||||
if item[0] == 'username':
|
||||
for item in root.findall("{%s}account" % SCHEMAROOT)[0].items():
|
||||
if item[0] == "username":
|
||||
username = item[1]
|
||||
if item[0] == 'password':
|
||||
if item[0] == "password":
|
||||
password = item[1]
|
||||
|
||||
# Emails
|
||||
for email in root.findall('{%s}emails' % SCHEMAROOT)[0]:
|
||||
if email.tag == '{%s}email' % SCHEMAROOT:
|
||||
emails.append({'email': email.text, 'photo_id': email.attrib['photo_id']})
|
||||
|
||||
# OpenIDs
|
||||
for openid in root.findall('{%s}openids' % SCHEMAROOT)[0]:
|
||||
if openid.tag == '{%s}openid' % SCHEMAROOT:
|
||||
openids.append({'openid': openid.text, 'photo_id': openid.attrib['photo_id']})
|
||||
|
||||
emails = [
|
||||
{"email": email.text, "photo_id": email.attrib["photo_id"]}
|
||||
for email in root.findall("{%s}emails" % SCHEMAROOT)[0]
|
||||
if email.tag == "{%s}email" % SCHEMAROOT
|
||||
]
|
||||
openids = [
|
||||
{"openid": openid.text, "photo_id": openid.attrib["photo_id"]}
|
||||
for openid in root.findall("{%s}openids" % SCHEMAROOT)[0]
|
||||
if openid.tag == "{%s}openid" % SCHEMAROOT
|
||||
]
|
||||
# Photos
|
||||
for photo in root.findall('{%s}photos' % SCHEMAROOT)[0]:
|
||||
if photo.tag == '{%s}photo' % SCHEMAROOT:
|
||||
for photo in root.findall("{%s}photos" % SCHEMAROOT)[0]:
|
||||
if photo.tag == "{%s}photo" % SCHEMAROOT:
|
||||
try:
|
||||
data = base64.decodebytes(bytes(photo.text, 'utf-8'))
|
||||
# Safety measures to make sure we do not try to parse
|
||||
# a binary encoded string
|
||||
photo.text = photo.text.strip("'")
|
||||
photo.text = photo.text.strip("\\n")
|
||||
photo.text = photo.text.lstrip("b'")
|
||||
data = base64.decodebytes(bytes(photo.text, "utf-8"))
|
||||
except binascii.Error as exc:
|
||||
print('Cannot decode photo; Encoding: %s, Format: %s, Id: %s: %s' % (
|
||||
photo.attrib['encoding'], photo.attrib['format'], photo.attrib['id'], exc))
|
||||
print(
|
||||
f'Cannot decode photo; Encoding: {photo.attrib["encoding"]}, Format: {photo.attrib["format"]}, Id: {photo.attrib["id"]}: {exc}'
|
||||
)
|
||||
continue
|
||||
try:
|
||||
Image.open(BytesIO(data))
|
||||
except Exception as exc: # pylint: disable=broad-except
|
||||
print('Cannot decode photo; Encoding: %s, Format: %s, Id: %s: %s' % (
|
||||
photo.attrib['encoding'], photo.attrib['format'], photo.attrib['id'], exc))
|
||||
print(
|
||||
f'Cannot decode photo; Encoding: {photo.attrib["encoding"]}, Format: {photo.attrib["format"]}, Id: {photo.attrib["id"]}: {exc}'
|
||||
)
|
||||
continue
|
||||
else:
|
||||
# If it is a working image, we can use it
|
||||
photo.text.replace('\n', '')
|
||||
photos.append({
|
||||
'data': photo.text,
|
||||
'format': photo.attrib['format'],
|
||||
'id': photo.attrib['id'],
|
||||
})
|
||||
photo.text.replace("\n", "")
|
||||
photos.append(
|
||||
{
|
||||
"data": photo.text,
|
||||
"format": photo.attrib["format"],
|
||||
"id": photo.attrib["id"],
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
'emails': emails,
|
||||
'openids': openids,
|
||||
'photos': photos,
|
||||
'username': username,
|
||||
'password': password,
|
||||
"emails": emails,
|
||||
"openids": openids,
|
||||
"photos": photos,
|
||||
"username": username,
|
||||
"password": password,
|
||||
}
|
||||
|
||||
@@ -12,23 +12,24 @@
|
||||
{% endif %}
|
||||
<div class="row">
|
||||
{% for photo in photos %}
|
||||
<div class="panel panel-tortin" style="width:182px;float:left;margin-left:20px">
|
||||
<div class="panel-heading">
|
||||
<h3 class="panel-title">
|
||||
<input type="checkbox" name="photo_{{photo.service_name}}" id="photo_{{photo.service_name}}" checked="checked">
|
||||
<label for="photo_{{photo.service_name}}" style="width:100%">
|
||||
{{ photo.service_name }}
|
||||
{% if photo.service_url %}
|
||||
<a href="{{ photo.service_url }}" style="float:right;color:#FFFFFF"><i class="fa fa-external-link"></i></a>
|
||||
{% endif %}
|
||||
</label>
|
||||
</h3></div>
|
||||
<div class="panel-body">
|
||||
<center>
|
||||
<img src="{{ photo.thumbnail_url }}" style="max-width: 80px; max-height: 80px;" alt="{{ photo.service_name }} image">
|
||||
</center>
|
||||
</div>
|
||||
</div>
|
||||
<div class="panel panel-tortin" style="width:182px;float:left;margin-left:20px">
|
||||
<div class="panel-heading">
|
||||
<h3 class="panel-title">
|
||||
<input type="checkbox" name="photo_{{photo.service_name}}" id="photo_{{photo.service_name}}" checked="checked">
|
||||
<label for="photo_{{photo.service_name}}" style="width:100%">
|
||||
{{ photo.service_name }}
|
||||
{% if photo.service_url %}
|
||||
<a href="{{ photo.service_url }}" style="float:right;color:#FFFFFF"><i class="fa-solid fa-up-right-from-square"></i></a>
|
||||
{% endif %}
|
||||
</label>
|
||||
</h3>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<center>
|
||||
<img src="{{ photo.thumbnail_url }}" style="max-width: 80px; max-height: 80px;" alt="{{ photo.service_name }} image">
|
||||
</center>
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
<p>
|
||||
|
||||
@@ -17,15 +17,17 @@
|
||||
{% if form.email.errors %}
|
||||
<div class="alert alert-danger" role="alert">{{ form.email.errors }}</div>
|
||||
{% endif %}
|
||||
<div style="max-width:640px">
|
||||
<div class="form-container">
|
||||
<form action="{% url 'add_email' %}" name="addemail" method="post" id="form-addemail">
|
||||
{% csrf_token %}
|
||||
|
||||
<div class="form-group">
|
||||
<label for="id_email">{% trans 'Email' %}:</label>
|
||||
<input type="text" name="email" autofocus required class="form-control" id="id_email">
|
||||
<label for="id_email" class="form-label">{% trans 'Email' %}</label>
|
||||
<input type="email" name="email" autofocus required class="form-control" id="id_email" placeholder="{% trans 'Enter your email address' %}">
|
||||
</div>
|
||||
<div class="button-group">
|
||||
<button type="submit" class="btn btn-primary">{% trans 'Add' %}</button>
|
||||
</div>
|
||||
<button type="submit" class="button">{% trans 'Add' %}</button>
|
||||
|
||||
</form>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
{% extends 'base.html' %}
|
||||
{% extends 'base.html' %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block title %}{% trans 'Add a new OpenID' %}{% endblock title %}
|
||||
|
||||
@@ -4,65 +4,81 @@
|
||||
{% block title %}{% blocktrans with email.email as email_address %}Choose a photo for {{ email_address }}{% endblocktrans %}{% endblock title %}
|
||||
|
||||
{% block content %}
|
||||
<style>
|
||||
.nobutton {
|
||||
background: none;
|
||||
color: inherit;
|
||||
border: none;
|
||||
padding: 0;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
outline: inherit;
|
||||
}
|
||||
</style>
|
||||
<h1>{% blocktrans with email.email as email_address %}Choose a photo for {{ email_address }}{% endblocktrans %}</h1>
|
||||
|
||||
{% if not user.photo_set.count %}
|
||||
|
||||
{% url 'upload_photo' as upload_url %}
|
||||
<h4>{% blocktrans %}You need to <a href="{{ upload_url }}">upload some photos</a> first!{% endblocktrans %}</h4>
|
||||
|
||||
<p><a href="{% url 'profile' %}" class="button">{% trans 'Back to your profile' %}</a></p>
|
||||
|
||||
{% else %}
|
||||
|
||||
<p>{% trans 'Here are the pictures you have uploaded, click on the one you wish to associate with this email address:' %}</p>
|
||||
<div class="row">
|
||||
{% for photo in user.photo_set.all %}
|
||||
<form action="{% url 'assign_photo_email' view.kwargs.email_id %}" method="post" style="float:left;margin-left:20px">{% csrf_token %}
|
||||
<input type="hidden" name="photo_id" value="{{ photo.id }}">
|
||||
<button type="submit" name="photo{{ photo.id }}" class="nobutton">
|
||||
<div class="panel panel-tortin" style="width:132px;margin:0">
|
||||
<div class="panel-heading">
|
||||
<h3 class="panel-title">{% ifequal email.photo.id photo.id %}<i class="fa fa-check"></i>{% endifequal %} {% trans 'Image' %} {{ forloop.counter }}</h3>
|
||||
</div>
|
||||
<div class="panel-body" style="height:130px">
|
||||
<center>
|
||||
<img style="max-height:100px;max-width:100px" src="{% url 'raw_image' photo.id %}">
|
||||
</center>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</form>
|
||||
{% endfor %}
|
||||
<form action="{% url 'assign_photo_email' view.kwargs.email_id %}" method="post" style="float:left;margin-left:20px">{% csrf_token %}
|
||||
<button type="submit" name="photoNone" class="nobutton">
|
||||
<div class="panel panel-tortin" style="width:132px;margin:0">
|
||||
<div class="panel-heading">
|
||||
<h3 class="panel-title">{% ifequal email.photo.id photo.id %}<i class="fa fa-check"></i>{% endifequal %} {% trans 'No image' %}</h3>
|
||||
</div>
|
||||
<div class="panel-body" style="height:130px">
|
||||
<center>
|
||||
<img style="max-height:100px;max-width:100px" src="/static/img/nobody/100.png">
|
||||
</center>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
<div style="height:8px"></div>
|
||||
<a href="{% url 'upload_photo' %}" class="button">{% blocktrans %}Upload a new one{% endblocktrans %}</a>
|
||||
<a href="{% url 'import_photo' email.pk %}" class="button">{% blocktrans %}Import from other services{% endblocktrans %}</a>
|
||||
{% if user.photo_set.count %}
|
||||
<p>{% trans 'Here are the pictures you have uploaded, click on the one you wish to associate with this email address:' %}</p>
|
||||
<div class="photo-grid">
|
||||
{% for photo in user.photo_set.all %}
|
||||
<form action="{% url 'assign_photo_email' view.kwargs.email_id %}" method="post" class="photo-card">{% csrf_token %}
|
||||
<input type="hidden" name="photo_id" value="{{ photo.id }}">
|
||||
<button type="submit" name="photo{{ photo.id }}" class="nobutton">
|
||||
<div class="panel panel-tortin">
|
||||
<div class="panel-heading">
|
||||
<h3 class="panel-title">{% if email.photo.id == photo.id %}<i class="fa-solid fa-check"></i>{% endif %} {% trans 'Image' %} {{ forloop.counter }}</h3>
|
||||
</div>
|
||||
<div class="panel-body" style="height:130px">
|
||||
<center>
|
||||
<img style="max-height:100px;max-width:100px" src="{% url 'raw_image' photo.id %}">
|
||||
</center>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</form>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
<div style="height:40px"></div>
|
||||
|
||||
<div class="photo-grid">
|
||||
<form action="{% url 'assign_photo_email' view.kwargs.email_id %}" method="post" class="photo-card">{% csrf_token %}
|
||||
<button type="submit" name="photoNone" class="nobutton">
|
||||
<div class="panel panel-tortin">
|
||||
<div class="panel-heading">
|
||||
<h3 class="panel-title">{% if email.photo.id == photo.id %}{% if not email.bluesky_handle %}<i class="fa-solid fa-check"></i>{% endif %}{% endif %} {% trans 'No image' %}</h3>
|
||||
</div>
|
||||
<div class="panel-body" style="height:130px">
|
||||
<center>
|
||||
<img style="max-height:100px;max-width:100px" src="/static/img/nobody/100.png">
|
||||
</center>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</form>
|
||||
{% if email.bluesky_handle %}
|
||||
<form action="{% url 'assign_photo_email' view.kwargs.email_id %}" method="post" class="photo-card">{% csrf_token %}
|
||||
<input type="hidden" name="photo_id" value="bluesky">
|
||||
<button type="submit" name="photoBluesky" class="nobutton">
|
||||
<div class="panel panel-tortin">
|
||||
<div class="panel-heading">
|
||||
<h3 class="panel-title">{% if email.bluesky_handle %}<i class="fa-solid fa-check"></i>{% endif %} {% trans "Bluesky" %}</h3>
|
||||
</div>
|
||||
<div class="panel-body" style="height:130px">
|
||||
<center>
|
||||
<img style="max-height:100px;max-width:100px" src="{% url "blueskyproxy" email.digest %}?size=100">
|
||||
</center>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="action-buttons">
|
||||
<a href="{% url 'upload_photo' %}" class="btn btn-primary">{% blocktrans %}Upload a new one{% endblocktrans %}</a>
|
||||
<a href="{% url 'import_photo' %}" class="btn btn-secondary">{% blocktrans %}Import from other services{% endblocktrans %}</a>
|
||||
</div>
|
||||
|
||||
<div style="margin-top: 2rem;">
|
||||
<form action="{% url 'assign_bluesky_handle_to_email' view.kwargs.email_id %}" method="post">{% csrf_token %}
|
||||
<div class="form-group">
|
||||
<label for="id_bluesky_handle">{% trans "Bluesky handle" %}:</label>
|
||||
{% if email.bluesky_handle %}
|
||||
<input type="text" name="bluesky_handle" required value="{{ email.bluesky_handle }}" class="form-control" id="id_bluesky_handle">
|
||||
{% else %}
|
||||
<input type="text" name="bluesky_handle" required value="" placeholder="{% trans 'Bluesky handle' %}" class="form-control" id="id_bluesky_handle">
|
||||
{% endif %}
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">{% trans 'Assign Bluesky handle' %}</button>
|
||||
</form>
|
||||
</div>
|
||||
{% endblock content %}
|
||||
|
||||
@@ -4,65 +4,78 @@
|
||||
{% block title %}{% blocktrans with openid.openid as openid_address %}Choose a photo for {{ openid_address }}{% endblocktrans %}{% endblock title %}
|
||||
|
||||
{% block content %}
|
||||
<style>
|
||||
.nobutton {
|
||||
background: none;
|
||||
color: inherit;
|
||||
border: none;
|
||||
padding: 0;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
outline: inherit;
|
||||
}
|
||||
</style>
|
||||
<h1>{% blocktrans with openid.openid as openid_address %}Choose a photo for {{ openid_address }}{% endblocktrans %}</h1>
|
||||
|
||||
{% if not user.photo_set.count %}
|
||||
|
||||
{% url 'upload_photo' as upload_url %}
|
||||
<h3>{% blocktrans %}You need to <a href="{{ upload_url }}">upload some photos</a> first!{% endblocktrans %}</h3>
|
||||
|
||||
<p><a href="{% url 'profile' %}" class="button">{% trans 'Back to your profile' %}</a></p>
|
||||
|
||||
{% else %}
|
||||
|
||||
<p>{% trans 'Here are the pictures you have uploaded, click on the one you wish to associate with this openid address:' %}</p>
|
||||
<div class="row">
|
||||
{% for photo in user.photo_set.all %}
|
||||
<form action="{% url 'assign_photo_openid' view.kwargs.openid_id %}" method="post" style="float:left;margin-left:20px">{% csrf_token %}
|
||||
<input type="hidden" name="photo_id" value="{{ photo.id }}">
|
||||
<button type="submit" name="photo{{ photo.id }}" class="nobutton">
|
||||
<div class="panel panel-tortin" style="width:132px;margin:0">
|
||||
<div class="panel-heading">
|
||||
<h3 class="panel-title">{% ifequal openid.photo.id photo.id %}<i class="fa fa-check"></i>{% endifequal %} {% trans 'Image' %} {{ forloop.counter }}</h3>
|
||||
</div>
|
||||
<div class="panel-body" style="height:130px">
|
||||
<center>
|
||||
<img style="max-height:100px;max-width:100px" src="{% url 'raw_image' photo.id %}">
|
||||
</center>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</form>
|
||||
{% endfor %}
|
||||
<form action="{% url 'assign_photo_openid' view.kwargs.openid_id %}" method="post" style="float:left;margin-left:20px">{% csrf_token %}
|
||||
<button type="submit" name="photoNone" class="nobutton">
|
||||
<div class="panel panel-tortin" style="width:132px;margin:0">
|
||||
<div class="panel-heading">
|
||||
<h3 class="panel-title">{% ifequal openid.photo.id photo.id %}<i class="fa fa-check"></i>{% endifequal %} {% trans 'No image' %}</h3>
|
||||
</div>
|
||||
<div class="panel-body" style="height:130px">
|
||||
<center>
|
||||
<img style="max-height:100px;max-width:100px" src="/static/img/nobody/100.png">
|
||||
</center>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
<div style="height:8px"></div>
|
||||
<a href="{% url 'upload_photo' %}" class="button">{% blocktrans %}upload a new one{% endblocktrans %}</a>
|
||||
|
||||
{% if user.photo_set.count %}
|
||||
<p>{% trans 'Here are the pictures you have uploaded, click on the one you wish to associate with this openid address:' %}</p>
|
||||
<div class="photo-grid">
|
||||
{% for photo in user.photo_set.all %}
|
||||
<form action="{% url 'assign_photo_openid' view.kwargs.openid_id %}" method="post" class="photo-card">{% csrf_token %}
|
||||
<input type="hidden" name="photo_id" value="{{ photo.id }}">
|
||||
<button type="submit" name="photo{{ photo.id }}" class="nobutton">
|
||||
<div class="panel panel-tortin">
|
||||
<div class="panel-heading">
|
||||
<h3 class="panel-title">{% if openid.photo.id == photo.id %}<i class="fa-solid fa-check"></i>{% endif %} {% trans 'Image' %} {{ forloop.counter }}</h3>
|
||||
</div>
|
||||
<div class="panel-body" style="height:130px">
|
||||
<center>
|
||||
<img style="max-height:100px;max-width:100px" src="{% url 'raw_image' photo.id %}">
|
||||
</center>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</form>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
<div style="height:40px"></div>
|
||||
|
||||
<div class="photo-grid">
|
||||
<form action="{% url 'assign_photo_openid' view.kwargs.openid_id %}" method="post" class="photo-card">{% csrf_token %}
|
||||
<button type="submit" name="photoNone" class="nobutton">
|
||||
<div class="panel panel-tortin">
|
||||
<div class="panel-heading">
|
||||
<h3 class="panel-title">{% if not openid.photo and not openid.bluesky_handle %}<i class="fa-solid fa-check"></i>{% endif %} {% trans 'No image' %}</h3>
|
||||
</div>
|
||||
<div class="panel-body" style="height:130px">
|
||||
<center>
|
||||
<img style="max-height:100px;max-width:100px" src="/static/img/nobody/100.png">
|
||||
</center>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</form>
|
||||
{% if openid.bluesky_handle %}
|
||||
<form action="" class="photo-card">
|
||||
<div class="panel panel-tortin">
|
||||
<div class="panel-heading">
|
||||
<h3 class="panel-title"><i class="fa-solid fa-check"></i> {% trans "Bluesky" %}</h3>
|
||||
</div>
|
||||
<div class="panel-body" style="height:130px">
|
||||
<center>
|
||||
<img style="max-height:100px;max-width:100px" src="{% url "blueskyproxy" openid.digest %}?size=100">
|
||||
</center>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="action-buttons">
|
||||
<a href="{% url 'upload_photo' %}" class="btn btn-primary">{% blocktrans %}upload a new one{% endblocktrans %}</a>
|
||||
<a href="{% url 'import_photo' %}" class="btn btn-secondary">{% blocktrans %}Import from other services{% endblocktrans %}</a>
|
||||
</div>
|
||||
|
||||
<div style="margin-top: 2rem;">
|
||||
<form action="{% url 'assign_bluesky_handle_to_openid' view.kwargs.openid_id %}" method="post">{% csrf_token %}
|
||||
<div class="form-group">
|
||||
<label for="id_bluesky_handle">{% trans "Bluesky handle" %}:</label>
|
||||
{% if openid.bluesky_handle %}
|
||||
<input type="text" name="bluesky_handle" required value="{{ openid.bluesky_handle }}" class="form-control" id="id_bluesky_handle">
|
||||
{% else %}
|
||||
<input type="text" name="bluesky_handle" required value="" placeholder="{% trans 'Bluesky handle' %}" class="form-control" id="id_bluesky_handle">
|
||||
{% endif %}
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">{% trans 'Assign Bluesky handle' %}</button>
|
||||
</form>
|
||||
</div>
|
||||
{% endblock content %}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
{% extends 'base.html' %}
|
||||
{% extends 'base.html' %}
|
||||
{% load i18n %}
|
||||
{% load static %}
|
||||
|
||||
@@ -8,12 +8,13 @@
|
||||
<style>
|
||||
input[type=checkbox] {display:none}
|
||||
input[type=checkbox].image + label:before {
|
||||
font-family: FontAwesome;
|
||||
font-family: "Font Awesome 7 Free";
|
||||
font-weight: 900;
|
||||
display: inline-block;
|
||||
}
|
||||
input[type=checkbox].image + label:before {content: "\f096"}
|
||||
input[type=checkbox].image + label:before {content: "\f0c8"}
|
||||
input[type=checkbox].image + label:before {letter-spacing: 5px}
|
||||
input[type=checkbox].image:checked + label:before {content: "\f046"}
|
||||
input[type=checkbox].image:checked + label:before {content: "\f14a"}
|
||||
input[type=checkbox].image:checked + label:before {letter-spacing: 3px}
|
||||
</style>
|
||||
<h1>{% trans 'Choose items to be imported' %}</h1>
|
||||
@@ -23,7 +24,7 @@ input[type=checkbox].image:checked + label:before {letter-spacing: 3px}
|
||||
<h4>{% trans 'Email addresses we found in the export - existing ones will not be re-added' %}</h4>
|
||||
{% for email in emails %}
|
||||
<div class="checkbox">
|
||||
<input type="checkbox" checked name="email_{{ forloop.counter }}" id="email_{{ forloop.counter }}" value="{{ email }}" class="text"><label for="email_{{ forloop.counter }}">{{ email }}</label>
|
||||
<input type="checkbox" checked name="email_{{ forloop.counter }}" id="email_{{ forloop.counter }}" value="{{ email.email }}" class="text"><label for="email_{{ forloop.counter }}">{{ email.email }}</label>
|
||||
</div>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
{% extends 'base.html' %}
|
||||
{% extends 'base.html' %}
|
||||
{% load i18n %}
|
||||
{% load static %}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
{% extends 'base.html' %}
|
||||
{% extends 'base.html' %}
|
||||
{% load i18n %}
|
||||
{% load static %}
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
|
||||
<button type="submit" class="btn btn-danger">{% trans 'Yes, delete all of my stuff' %}</button>
|
||||
|
||||
<button type="cancel" class="button" href="{% url 'profile' %}">{% trans 'Cancel' %}</button>
|
||||
<a href="{% url 'profile' %}" class="btn btn-secondary">{% trans 'Cancel' %}</a>
|
||||
|
||||
</form>
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
{% load i18n %}{% blocktrans %}Someone, probably you, requested that this email address be added to their
|
||||
{% load i18n %}{% blocktrans %}Someone, probably you, requested that this email address be added to their
|
||||
{{ site_name }} account.
|
||||
|
||||
If that's what you want, please confirm that you are the owner of this
|
||||
|
||||
@@ -7,12 +7,13 @@
|
||||
<style>
|
||||
input[type=checkbox] {display:none}
|
||||
input[type=checkbox] + label:before {
|
||||
font-family: FontAwesome;
|
||||
font-family: "Font Awesome 7 Free";
|
||||
font-weight: 900;
|
||||
display: inline-block;
|
||||
}
|
||||
input[type=checkbox] + label:before {content: "\f096"}
|
||||
input[type=checkbox] + label:before {content: "\f0c8"}
|
||||
input[type=checkbox] + label:before {letter-spacing: 5px}
|
||||
input[type=checkbox]:checked + label:before {content: "\f046"}
|
||||
input[type=checkbox]:checked + label:before {content: "\f14a"}
|
||||
input[type=checkbox]:checked + label:before {letter-spacing: 3px}
|
||||
</style>
|
||||
<h1>{% trans 'Email confirmation' %}</h1>
|
||||
|
||||
20
ivatar/ivataraccount/templates/export.html
Normal file
20
ivatar/ivataraccount/templates/export.html
Normal file
@@ -0,0 +1,20 @@
|
||||
{% extends 'base.html' %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block title %}{% trans 'Export your data' %}{% endblock title %}
|
||||
|
||||
{% block content %}
|
||||
|
||||
<h1>{% trans 'Export your data' %}</h1>
|
||||
|
||||
<p>{% trans 'Libravatar will now export all of your personal data to a compressed XML file.' %}</p>
|
||||
|
||||
<form action="{% url 'export' %}" method="post" name="export">{% csrf_token %}
|
||||
|
||||
<p><button type="submit" class="button">{% trans 'Export' %}</button>
|
||||
<a href="{% url 'profile' %}" class="button">{% trans 'Cancel' %}</a>
|
||||
</p>
|
||||
|
||||
</form>
|
||||
|
||||
{% endblock content %}
|
||||
@@ -5,37 +5,38 @@
|
||||
|
||||
{% block content %}
|
||||
<style>
|
||||
input[type=checkbox] {display:none}
|
||||
input[type=checkbox] + label:before {
|
||||
font-family: FontAwesome;
|
||||
display: inline-block;
|
||||
}
|
||||
input[type=checkbox] + label:before {content: "\f096"}
|
||||
input[type=checkbox] + label:before {letter-spacing: 5px}
|
||||
input[type=checkbox]:checked + label:before {content: "\f046"}
|
||||
input[type=checkbox]:checked + label:before {letter-spacing: 3px}
|
||||
input[type=checkbox] {display:none}
|
||||
input[type=checkbox] + label:before {
|
||||
font-family: "Font Awesome 7 Free";
|
||||
font-weight: 900;
|
||||
display: inline-block;
|
||||
}
|
||||
input[type=checkbox] + label:before {content: "\f0c8"}
|
||||
input[type=checkbox] + label:before {letter-spacing: 5px}
|
||||
input[type=checkbox]:checked + label:before {content: "\f14a"}
|
||||
input[type=checkbox]:checked + label:before {letter-spacing: 3px}
|
||||
</style>
|
||||
<h1>{% trans 'Import photo' %}</h1>
|
||||
|
||||
{% if not email_id %}
|
||||
<div style="max-width:640px">
|
||||
<form action="{% url 'import_photo' %}" method="get" id="check_mail_form">
|
||||
<div class="form-group">
|
||||
<label for="check_email_addr">{% trans 'Email Address' %}</label>
|
||||
<input type="text" name="check_email_addr" class="form-control" value="{{ email_addr }}">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<button type="submit" class="button">{% trans 'Check' %}</button>
|
||||
</div>
|
||||
</form>
|
||||
<script>
|
||||
document.getElementById('check_mail_form').onsubmit =
|
||||
function(self) {
|
||||
window.location.href = "{% url 'import_photo' %}" + document.getElementsByName('check_email_addr')[0].value;
|
||||
return false;
|
||||
};
|
||||
</script>
|
||||
</div>
|
||||
<div style="max-width:640px">
|
||||
<form action="{% url 'import_photo' %}" method="get" id="check_mail_form">
|
||||
<div class="form-group">
|
||||
<label for="check_email_addr">{% trans 'Email Address' %}</label>
|
||||
<input type="text" name="check_email_addr" class="form-control" value="{{ email_addr }}">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<button type="submit" class="button">{% trans 'Check' %}</button>
|
||||
</div>
|
||||
</form>
|
||||
<script>
|
||||
document.getElementById('check_mail_form').onsubmit =
|
||||
function(self) {
|
||||
window.location.href = "{% url 'import_photo' %}" + document.getElementsByName('check_email_addr')[0].value;
|
||||
return false;
|
||||
};
|
||||
</script>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{% include '_import_photo_form.html' %}
|
||||
|
||||
@@ -18,24 +18,28 @@
|
||||
{% if form.password.errors %}
|
||||
<div class="alert alert-danger" role="alert">{{ form.password.errors }}</div>
|
||||
{% endif %}
|
||||
<div style="max-width:700px">
|
||||
<div class="form-container">
|
||||
<form action="{% url 'login' %}" method="post" name="login">
|
||||
{% csrf_token %}
|
||||
{% if next %}<input type="hidden" name="next" value="{{ next }}">{% endif %}
|
||||
<div class="form-group">
|
||||
<label for="id_username">{% trans 'Username' %}:</label>
|
||||
<input type="text" name="username" autofocus required class="form-control" id="id_username">
|
||||
<label for="id_username" class="form-label">{% trans 'Username' %}</label>
|
||||
<input type="text" name="username" autofocus required class="form-control" id="id_username" placeholder="{% trans 'Enter your username' %}">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="id_password">{% trans 'Password' %}:</label>
|
||||
<input type="password" name="password" class="form-control" required id="id_password">
|
||||
<label for="id_password" class="form-label">{% trans 'Password' %}</label>
|
||||
<input type="password" name="password" class="form-control" required id="id_password" placeholder="{% trans 'Enter your password' %}">
|
||||
</div>
|
||||
|
||||
<div class="button-group">
|
||||
<button type="submit" class="btn btn-primary">{% trans 'Login' %}</button>
|
||||
<a href="{% url 'openid-login' %}" class="btn btn-secondary">{% trans 'Login with OpenID' %}</a>
|
||||
{% if with_fedora %}
|
||||
<a href="{% url "social:begin" "fedora" %}" class="btn btn-secondary">{% trans 'Login with Fedora' %}</a>
|
||||
{% endif %}
|
||||
<a href="{% url 'new_account' %}" class="btn btn-secondary">{% trans 'Create new user' %}</a>
|
||||
<a href="{% url 'password_reset' %}" class="btn btn-secondary">{% trans 'Password reset' %}</a>
|
||||
</div>
|
||||
<button type="submit" class="button">{% trans 'Login' %}</button>
|
||||
|
||||
<a href="{% url 'openid-login' %}" class="button">{% trans 'Login with OpenID' %}</a>
|
||||
|
||||
<a href="{% url 'new_account' %}" class="button">{% trans 'Create new user' %}</a>
|
||||
|
||||
<a href="{% url 'password_reset' %}" class="button">{% trans 'Password reset' %}</a>
|
||||
</form>
|
||||
</div>
|
||||
<div style="height:40px"></div>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
{% extends 'base.html' %}
|
||||
{% extends 'base.html' %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block title %}{% trans 'Create a new ivatar account' %}{% endblock title %}
|
||||
@@ -16,22 +16,25 @@
|
||||
{% if form.password2.errors %}
|
||||
<div class="alert alert-danger" role="alert">{{ form.password2.errors }}</div>
|
||||
{% endif %}
|
||||
<div class="form-container">
|
||||
<form action="{% url 'new_account' %}" method="post" name="newaccount">
|
||||
{% csrf_token %}
|
||||
<div style="max-width:640px">
|
||||
<div class="form-group">
|
||||
<label for="id_username">{% trans 'Username' %}:</label>
|
||||
<input type="text" name="username" autofocus required class="form-control" id="id_username">
|
||||
<label for="id_username" class="form-label">{% trans 'Username' %}</label>
|
||||
<input type="text" name="username" autofocus required class="form-control" id="id_username" placeholder="{% trans 'Choose a username' %}">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="id_password1">{% trans 'Password' %}:</label>
|
||||
<input type="password" name="password1" class="form-control" required id="id_password1">
|
||||
<label for="id_password1" class="form-label">{% trans 'Password' %}</label>
|
||||
<input type="password" name="password1" class="form-control" required id="id_password1" placeholder="{% trans 'Enter a secure password' %}">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="id_password2">{% trans 'Password confirmation' %}:</label>
|
||||
<input type="password" name="password2" class="form-control" required id="id_password2">
|
||||
<label for="id_password2" class="form-label">{% trans 'Password confirmation' %}</label>
|
||||
<input type="password" name="password2" class="form-control" required id="id_password2" placeholder="{% trans 'Confirm your password' %}">
|
||||
</div>
|
||||
<div class="button-group">
|
||||
<button type="submit" class="btn btn-primary">{% trans 'Create account' %}</button>
|
||||
<a href="/accounts/login/" class="btn btn-secondary">{% trans 'Login' %}</a>
|
||||
</div>
|
||||
<button type="submit" class="button">{% trans 'Create account' %}</button> or <a href="/accounts/login/" class="button">{% trans 'Login' %}</a>
|
||||
</form>
|
||||
</div>
|
||||
<div style="height:40px"></div>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
{% extends 'base.html' %}
|
||||
{% extends 'base.html' %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block title %}{% trans 'Change your ivatar password' %}{% endblock title %}
|
||||
|
||||
@@ -8,17 +8,18 @@
|
||||
<h1>{% trans 'Reset password' %}</h1>
|
||||
|
||||
<p>{% trans 'To continue with the password reset, enter one of the email addresses associated with your account.' %}</p>
|
||||
<div style="max-width:640px">
|
||||
<div class="form-container">
|
||||
<form action="" method="post" name="reset">{% csrf_token %}
|
||||
|
||||
{{ form.email.errors }}
|
||||
<div class="form-group">
|
||||
<label for="id_email">{% trans 'Email' %}:</label>
|
||||
<input type="text" name="email" autofocus required class="form-control" id="id_email">
|
||||
<label for="id_email" class="form-label">{% trans 'Email' %}</label>
|
||||
<input type="email" name="email" autofocus required class="form-control" id="id_email" placeholder="{% trans 'Enter your email address' %}">
|
||||
</div>
|
||||
|
||||
<button type="submit" class="button">{% trans 'Reset my password' %}</button>
|
||||
<button type="cancel" class="button" href="{% url 'profile' %}">{% trans 'Cancel' %}</button>
|
||||
<div class="button-group">
|
||||
<button type="submit" class="btn btn-primary">{% trans 'Reset my password' %}</button>
|
||||
<a href="{% url 'profile' %}" class="btn btn-secondary">{% trans 'Cancel' %}</a>
|
||||
</div>
|
||||
|
||||
</form>
|
||||
</div>
|
||||
|
||||
@@ -7,36 +7,64 @@
|
||||
{% block content %}
|
||||
<h1>{% trans 'Account settings' %}</h1>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="id_email">{% trans 'Your email' %}:</label>
|
||||
<input type="text" name="email" disabled class="form-control" value="{{ user.email }}" id="id_email" style="max-width:600px;">
|
||||
<div class="form-container">
|
||||
<label for="id_username" class="form-label">{% trans 'Username' %}</label>
|
||||
<input type="text" name="username" class="form-control" id="id_username" disabled value="{{ user.username }}">
|
||||
|
||||
<form action="{% url 'user_preference' %}" method="post">{% csrf_token %}
|
||||
<div class="form-group">
|
||||
<label for="id_first_name" class="form-label">{% trans 'Firstname' %}</label>
|
||||
<input type="text" name="first_name" class="form-control" id="id_first_name" value="{{ user.first_name }}" placeholder="{% trans 'Enter your first name' %}">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="id_last_name" class="form-label">{% trans 'Lastname' %}</label>
|
||||
<input type="text" name="last_name" class="form-control" id="id_last_name" value="{{ user.last_name }}" placeholder="{% trans 'Enter your last name' %}">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="id_email" class="form-label">{% trans 'E-mail address' %}</label>
|
||||
<select name="email" class="form-control" id="id_email">
|
||||
<option value="{{ user.email }}" selected>{{ user.email }}</option>
|
||||
{% for confirmed_email in user.confirmedemail_set.all %}
|
||||
{% if user.email != confirmed_email.email %}
|
||||
<option value="{{ confirmed_email.email }}">{{ confirmed_email.email }}</option>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<input type="hidden" name="theme" value="{{ user.userpreference.theme }}"/>
|
||||
<div class="button-group">
|
||||
<button type="submit" class="btn btn-primary">{% trans 'Save' %}</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<!-- TODO: Language stuff not yet fully implemented; Esp. translations are only half-way there
|
||||
|
||||
<h2>{% trans 'Language' %}</h2>
|
||||
<form action="{% url 'set_language' %}" method="post">{% csrf_token %}
|
||||
<div class="form-group">
|
||||
{% get_current_language as LANGUAGE_CODE %}
|
||||
{% get_available_languages as LANGUAGES %}
|
||||
{% get_language_info_list for LANGUAGES as languages %}
|
||||
{% for language in languages %}
|
||||
<div class="radio">
|
||||
<input type="radio" name="language" value="{{ language.code }}" id="language-{{ language.code }}" {% if language.code == LANGUAGE_CODE %}checked{% endif %}>
|
||||
<label for="language-{{ language.code }}">{{ language.name_local }}</label>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
<br/>
|
||||
<button type="submit" class="button">{% trans 'Save' %}</button>
|
||||
<div class="form-group">
|
||||
{% get_current_language as LANGUAGE_CODE %}
|
||||
{% get_available_languages as LANGUAGES %}
|
||||
{% get_language_info_list for LANGUAGES as languages %}
|
||||
{% for language in languages %}
|
||||
<div class="radio">
|
||||
<input type="radio" name="language" value="{{ language.code }}" id="language-{{ language.code }}"
|
||||
{% if language.code == LANGUAGE_CODE %}checked{% endif %}>
|
||||
<label for="language-{{ language.code }}">{{ language.name_local }}</label>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
<br/>
|
||||
<button type="submit" class="button">{% trans 'Save' %}</button>
|
||||
</form>
|
||||
|
||||
-->
|
||||
|
||||
<div style="height:40px"></div>
|
||||
<div style="height:100px"></div>
|
||||
|
||||
<!-- <p><a href="{% url 'export' %}" class="button">{% trans 'Export your data' %}</a></p> -->
|
||||
|
||||
<p><a href="{% url 'delete' %}" class="button">{% trans 'Permanently delete your account' %}</a></p>
|
||||
<!-- TODO: Better coloring of the button -->
|
||||
<p><a href="{% url 'delete' %}" class="button" style="background:red; color:white;">{% trans 'Permanently delete your account' %}</a></p>
|
||||
<div style="height:2rem"></div>
|
||||
{% endblock content %}
|
||||
|
||||
@@ -6,159 +6,271 @@
|
||||
{% block title %}{% trans 'Your Profile' %}{% endblock title %}
|
||||
|
||||
{% block content %}
|
||||
|
||||
<script type="text/javascript">
|
||||
function add_active(id){
|
||||
var elems = document.querySelector(".active");
|
||||
if(elems !== null){
|
||||
elems.classList.remove("active");
|
||||
}
|
||||
element = document.getElementById(id);
|
||||
element.classList.add("active");
|
||||
}
|
||||
</script>
|
||||
<h1>
|
||||
{% trans 'Your Profile' %} -
|
||||
{% if user.first_name and user.last_name %}
|
||||
{{ user.first_name }} {{ user.last_name }}
|
||||
{{ user.first_name }} {{ user.last_name }}
|
||||
{% else %}
|
||||
{{ user.username }}
|
||||
{{ user.username }}
|
||||
{% endif %}
|
||||
</h1>
|
||||
|
||||
<style>
|
||||
.action-item:hover span {
|
||||
.action-item:hover span {
|
||||
display: inline !important;
|
||||
}
|
||||
@media screen and (max-width: 320px) {
|
||||
.action-item, .btn {
|
||||
padding-left: 0.3em;
|
||||
padding-right: 0.3em;
|
||||
}
|
||||
}
|
||||
.thumbnail {
|
||||
max-width:80px;
|
||||
max-height:80px;
|
||||
}
|
||||
.nobutton {
|
||||
background: none;
|
||||
color: inherit;
|
||||
border: none;
|
||||
padding: 0;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
outline: inherit;
|
||||
}
|
||||
.button {
|
||||
margin-bottom: 1.5rem;
|
||||
margin-right: 1rem;
|
||||
}
|
||||
.container{
|
||||
display: grid;
|
||||
}
|
||||
.btn-group{
|
||||
display: inline-flex;
|
||||
}
|
||||
.input-group-addon{
|
||||
width: auto;
|
||||
height: 3rem;
|
||||
margin-top: 0.2rem;
|
||||
}
|
||||
@media only screen and (max-width: 470px) {
|
||||
@media screen and (max-width: 320px) {
|
||||
.action-item, .btn {
|
||||
padding-left: 0.3em;
|
||||
padding-right: 0.3em;
|
||||
}
|
||||
}
|
||||
.thumbnail {
|
||||
max-width:80px;
|
||||
max-height:80px;
|
||||
}
|
||||
.nobutton {
|
||||
background: none;
|
||||
color: inherit;
|
||||
border: none;
|
||||
padding: 0;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
outline: inherit;
|
||||
}
|
||||
.button {
|
||||
margin-bottom: 1.5rem;
|
||||
margin-right: 1rem;
|
||||
}
|
||||
.unconfirmed-mail-form{
|
||||
margin-bottom: 2rem;
|
||||
.container{
|
||||
display: grid;
|
||||
}
|
||||
.btn-group{
|
||||
display: contents;
|
||||
display: inline-flex;
|
||||
}
|
||||
.input-group-addon{
|
||||
width: auto;
|
||||
height: 3rem;
|
||||
margin-top: 0.2rem;
|
||||
}
|
||||
@media only screen and (max-width: 470px) {
|
||||
.button {
|
||||
margin-bottom: 1.5rem;
|
||||
margin-right: 1rem;
|
||||
}
|
||||
.unconfirmed-mail-form{
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
.btn-group{
|
||||
display: contents;
|
||||
}
|
||||
}
|
||||
@media only screen and (max-width: 470px) {
|
||||
p {
|
||||
padding-top: 2rem;
|
||||
}
|
||||
h3{
|
||||
line-height: 3.4rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<noscript>
|
||||
<style type="text/css">
|
||||
.profile-container > ul{
|
||||
display:block;
|
||||
}
|
||||
</style>
|
||||
</noscript>
|
||||
|
||||
{% if user.confirmedemail_set.count or user.confirmedopenid_set.count %}
|
||||
<h3>{% trans 'You have the following confirmed identities:' %}</h3>
|
||||
<div class="row">
|
||||
{% for email in user.confirmedemail_set.all %}
|
||||
<form action="{% url 'remove_confirmed_email' email.id %}" method="post">
|
||||
{% csrf_token %}
|
||||
<div class="panel" style="width:172px;margin-left:20px;float:left">
|
||||
<div class="panel-heading" style="padding-right:0">
|
||||
<h3 class="panel-title" title="{{ email.email }}" style="display:inline-flex"><a href="{% url 'assign_photo_email' email.id %}"><i class="fa fa-edit"></i></a>
|
||||
<button type="submit" class="nobutton" onclick="return confirm('{% trans 'Are you sure that you want to delete this email address?' %}')"><i class="fa fa-trash"></i></button>
|
||||
{{ email.email|truncatechars:12 }}</h3>
|
||||
</div>
|
||||
<div class="panel-body" style="height:130px">
|
||||
<center>
|
||||
<img title="{% trans 'Access count' %}: {{ email.access_count }}" style="max-height:100px;max-width:100px" src="{% if email.photo %}{% url 'raw_image' email.photo.id %}{% else %}{% static '/img/nobody/80.png' %}{% endif %}">
|
||||
</center>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
{% endfor %}
|
||||
{% for openid in user.confirmedopenid_set.all %}
|
||||
<form action="{% url 'remove_confirmed_openid' openid.id %}" method="post">{% csrf_token %}
|
||||
<div class="panel" style="width:172px;margin-left:20px;float:left">
|
||||
<div class="panel-heading" style="padding-right:0">
|
||||
<h3 class="panel-title" title="{{ openid.openid }}" style="display:inline-flex"><a href="{% url 'assign_photo_openid' openid.pk %}"><i class="fa fa-edit"></i></a>
|
||||
<button type="submit" class="nobutton" onclick="return confirm('{% trans 'Are you sure that you want to delete this OpenID?' %}')"><i class="fa fa-trash"></i></button>
|
||||
{{ openid.openid|cut:"http://"|cut:"https://"|truncatechars:12 }}</h3>
|
||||
</div>
|
||||
<div class="panel-body" style="height:130px">
|
||||
<center>
|
||||
<img title="{% trans 'Access count' %}: {{ openid.access_count }}" style="max-height:100px;max-width:100px" src="{% if openid.photo %}{% url 'raw_image' openid.photo.id %}{% else %}{% static '/img/nobody/80.png' %}{% endif %}">
|
||||
</center>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
<div class="row profileid">
|
||||
{% for email in user.confirmedemail_set.all %}
|
||||
{% if user.confirmedemail_set.all|length == 1%}
|
||||
<form action="{% url 'remove_confirmed_email' email.id %}" method="post">
|
||||
{% csrf_token %}
|
||||
<div id="email-conf-{{ forloop.counter }}" class="profile-container active">
|
||||
<img title="{% trans 'Access count' %}: {{ email.access_count }}"
|
||||
src="
|
||||
{% if email.photo %}
|
||||
{% url 'raw_image' email.photo.id %}
|
||||
{% elif email.bluesky_handle %}
|
||||
{% url 'blueskyproxy' email.digest %}
|
||||
{% else %}
|
||||
{% static '/img/nobody/120.png' %}
|
||||
{% endif %}">
|
||||
<h3 class="panel-title email-profile" title="{{ email.email }}">
|
||||
{{ email.email }}
|
||||
</h3>
|
||||
<ul>
|
||||
<li>
|
||||
<a href="{% url 'assign_photo_email' email.id %}">
|
||||
Change Profile Picture
|
||||
</a>
|
||||
</li>
|
||||
<li class="email-delete">
|
||||
<button type="submit" class="nobutton" onclick="return confirm('{% trans 'Are you sure that you want to delete this email address?' %}')">
|
||||
Delete Email Address
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</form>
|
||||
{% else %}
|
||||
<form action="{% url 'remove_confirmed_email' email.id %}" method="post">
|
||||
{% csrf_token %}
|
||||
<div id="email-conf-{{ forloop.counter }}" class="profile-container" onclick="add_active('email-conf-{{ forloop.counter }}')">
|
||||
<img title="{% trans 'Access count' %}: {{ email.access_count }}"
|
||||
src="
|
||||
{% if email.photo %}
|
||||
{% url 'raw_image' email.photo.id %}
|
||||
{% elif email.bluesky_handle %}
|
||||
{% url 'blueskyproxy' email.digest %}
|
||||
{% else %}
|
||||
{% static '/img/nobody/120.png' %}
|
||||
{% endif %}">
|
||||
<h3 class="panel-title email-profile" title="{{ email.email }}">
|
||||
{{ email.email }}
|
||||
</h3>
|
||||
<ul>
|
||||
<li>
|
||||
<a href="{% url 'assign_photo_email' email.id %}">
|
||||
Change Profile Picture
|
||||
</a>
|
||||
</li>
|
||||
<li class="email-delete">
|
||||
<button type="submit" class="nobutton" onclick="return confirm('{% trans 'Are you sure that you want to delete this email address?' %}')">
|
||||
Delete Email Address
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</form>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
{% for openid in user.confirmedopenid_set.all %}
|
||||
{% if user.confirmedopenid_set.all|length == 1 %}
|
||||
<form action="{% url 'remove_confirmed_openid' openid.id %}" method="post">{% csrf_token %}
|
||||
<div>
|
||||
<div id="id-conf-{{ forloop.counter }}" class="profile-container active">
|
||||
<img title="{% trans 'Access count' %}: {{ openid.access_count }}"
|
||||
src="
|
||||
{% if openid.photo %}
|
||||
{% url 'raw_image' openid.photo.id %}
|
||||
{% elif openid.bluesky_handle %}
|
||||
{% url 'blueskyproxy' openid.digest %}
|
||||
{% else %}
|
||||
{% static '/img/nobody/120.png' %}
|
||||
{% endif %}">
|
||||
<h3 class="panel-title email-profile" title="{{ openid.openid }}">
|
||||
{{ openid.openid }}
|
||||
</h3>
|
||||
<ul>
|
||||
<li>
|
||||
<a href="{% url 'assign_photo_openid' openid.pk %}">
|
||||
Change OpenID Picture
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<button type="submit" class="nobutton" onclick="return confirm('{% trans 'Are you sure that you want to delete this OpenID?' %}')">
|
||||
Delete OpenID
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
{% else %}
|
||||
<form action="{% url 'remove_confirmed_openid' openid.id %}" method="post">{% csrf_token %}
|
||||
<div>
|
||||
<div id="id-conf-{{ forloop.counter }}" class="profile-container" onclick="add_active('id-conf-{{ forloop.counter }}')">
|
||||
<img title="{% trans 'Access count' %}: {{ openid.access_count }}" src="{% if openid.photo %}{% url 'raw_image' openid.photo.id %}{% else %}{% static '/img/nobody/120.png' %}{% endif %}">
|
||||
<h3 class="panel-title email-profile" title="{{ openid.openid }}">
|
||||
{{ openid.openid }}
|
||||
</h3>
|
||||
<ul>
|
||||
<li>
|
||||
<a href="{% url 'assign_photo_openid' openid.pk %}">
|
||||
Change OpenID Picture
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<button type="submit" class="nobutton" onclick="return confirm('{% trans 'Are you sure that you want to delete this OpenID?' %}')">
|
||||
Delete OpenID
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{% if user.unconfirmedemail_set.count or user.unconfirmedopenid_set.count %}
|
||||
<h3>{% trans 'You have the following unconfirmed email addresses and OpenIDs:' %}</h3>
|
||||
{% for email in user.unconfirmedemail_set.all %}
|
||||
<form class="unconfirmed-mail-form" action="{% url 'remove_unconfirmed_email' email.id %}" method="post">
|
||||
{% csrf_token %}
|
||||
<div class="btn-group form-group" role="group">
|
||||
<button type="submit" class="button" onclick="return confirm('{% trans 'Are you sure that you want to delete this email address?' %}')"><i class="fa fa-trash"></i></button>
|
||||
<a href="{% url 'resend_confirmation_mail' email.pk %}" class="button"><i class="fa fa-envelope"></i></a>
|
||||
<span class="input-group-addon" style="width: auto;">{{ email.email }}</span>
|
||||
</div>
|
||||
</form>
|
||||
{# TODO: (expires in xx hours) #}
|
||||
{% if user.unconfirmedemail_set.count or user.unconfirmedopenid_set.count %}
|
||||
<h3>{% trans 'You have the following unconfirmed email addresses and OpenIDs:' %}</h3>
|
||||
{% for email in user.unconfirmedemail_set.all %}
|
||||
<form class="unconfirmed-mail-form" action="{% url 'remove_unconfirmed_email' email.id %}" method="post">
|
||||
{% csrf_token %}
|
||||
<div class="btn-group form-group" role="group">
|
||||
<button type="submit" class="button" onclick="return confirm('{% trans 'Are you sure that you want to delete this email address?' %}')"><i class="fa-solid fa-trash"></i></button>
|
||||
<a href="{% url 'resend_confirmation_mail' email.pk %}" class="button"><i class="fa-solid fa-envelope"></i></a>
|
||||
<span class="input-group-addon" style="width: auto;">{{ email.email }}</span>
|
||||
</div>
|
||||
</form>
|
||||
{# TODO: (expires in xx hours) #}
|
||||
{% endfor %}
|
||||
{% for openid in user.unconfirmedopenid_set.all %}
|
||||
<form action="{% url 'remove_unconfirmed_openid' openid.id %}" method="post">
|
||||
{% csrf_token %}
|
||||
<div class="btn-group form-group" role="group">
|
||||
<button type="submit" class="button" onclick="return confirm('{% trans 'Are you sure that you want to delete this OpenID?' %}')"><i class="fa-solid fa-trash"></i></button>
|
||||
<span class="input-group-addon">{{ openid.openid }}</span>
|
||||
</div>
|
||||
</form>
|
||||
{# TODO: (expires in xx hours) #}
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
<p style="padding-top:5px;">
|
||||
{% if not max_emails %}<a href="{% url 'add_email' %}" class="button" >{% trans 'Add a new email address' %}</a> {% endif %}
|
||||
<a href="{% url 'add_openid' %}" class="button">{% trans 'Add a new OpenID' %}</a></p>
|
||||
</p>
|
||||
{% if user.photo_set.count %}
|
||||
<h3>{% trans 'Here are the photos you have uploaded/imported:' %}</h3>
|
||||
<div class="row">
|
||||
{% for photo in user.photo_set.all %}
|
||||
<div class="panel panel-tortin" style="width:132px;margin-left:20px;float:left">
|
||||
<div class="panel-heading">
|
||||
<h3 class="panel-title"><a href="{% url 'delete_photo' photo.pk %}" onclick="return confirm('{% trans 'Are you sure that you want to delete this image?' %}')"><i class="fa-solid fa-trash"></i></a> {% trans 'Image' %} {{ forloop.counter }}</h3>
|
||||
</div>
|
||||
<div class="panel-body" style="height:130px">
|
||||
<img title="{% trans 'Access count' %}: {{ photo.access_count }}" style="max-height:100px;max-width:100px" src="{% url 'raw_image' photo.id %}">
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
{% for openid in user.unconfirmedopenid_set.all %}
|
||||
<form action="{% url 'remove_unconfirmed_openid' openid.id %}" method="post">
|
||||
{% csrf_token %}
|
||||
<div class="btn-group form-group" role="group">
|
||||
<button type="submit" class="button" onclick="return confirm('{% trans 'Are you sure that you want to delete this OpenID?' %}')"><i class="fa fa-trash"></i></button>
|
||||
<span class="input-group-addon">{{ openid.openid }}</span>
|
||||
</div>
|
||||
</form>
|
||||
{# TODO: (expires in xx hours) #}
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<p>
|
||||
{% if not max_emails %}<a href="{% url 'add_email' %}" class="button" >{% trans 'Add a new email address' %}</a> {% endif %}
|
||||
<a href="{% url 'add_openid' %}" class="button">{% trans 'Add a new OpenID' %}</a></p>
|
||||
</p>
|
||||
{% if user.photo_set.count %}
|
||||
<h3>{% trans 'Here are the photos you have uploaded/imported:' %}</h3>
|
||||
<div class="row">
|
||||
{% for photo in user.photo_set.all %}
|
||||
<div class="panel panel-tortin" style="width:132px;margin-left:20px;float:left">
|
||||
<div class="panel-heading">
|
||||
<h3 class="panel-title"><a href="{% url 'delete_photo' photo.pk %}" onclick="return confirm('{% trans 'Are you sure that you want to delete this image?' %}')"><i class="fa fa-trash"></i></a> {% trans 'Image' %} {{ forloop.counter }}</h3>
|
||||
</div>
|
||||
<div class="panel-body" style="height:130px">
|
||||
<center>
|
||||
<img title="{% trans 'Access count' %}: {{ photo.access_count }}" style="max-height:100px;max-width:100px" src="{% url 'raw_image' photo.id %}">
|
||||
</center>
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{% if not max_photos %}
|
||||
<p>
|
||||
<a href="{% url 'upload_photo' %}" class="button">{% trans 'Upload a new photo' %}</a>
|
||||
<a href="{% url 'import_photo' %}" class="button">{% trans 'Import photo from other services' %}</a>
|
||||
</p>
|
||||
{% endif %}
|
||||
<div style="height:40px"></div>
|
||||
{% endblock content %}
|
||||
{% if not max_photos %}
|
||||
<p>
|
||||
<a href="{% url 'upload_photo' %}" class="button">{% trans 'Upload a new photo' %}</a>
|
||||
<a href="{% url 'import_photo' %}" class="button">{% trans 'Import photo from other services' %}</a>
|
||||
</p>
|
||||
{% else %}
|
||||
{% trans "You've reached the maximum number of allowed images!" %}<br/>
|
||||
{% trans "No further images can be uploaded." %}
|
||||
{% endif %}
|
||||
<div style="height:40px"></div>
|
||||
{% endblock content %}
|
||||
|
||||
72
ivatar/ivataraccount/test_auth.py
Normal file
72
ivatar/ivataraccount/test_auth.py
Normal file
@@ -0,0 +1,72 @@
|
||||
from unittest import mock
|
||||
|
||||
from django.test import TestCase
|
||||
from django.contrib.auth.models import User
|
||||
from ivatar.ivataraccount.auth import FedoraOpenIdConnect
|
||||
from ivatar.ivataraccount.models import ConfirmedEmail
|
||||
from django.test import override_settings
|
||||
|
||||
|
||||
@override_settings(SOCIAL_AUTH_FEDORA_OIDC_ENDPOINT="https://id.example.com/")
|
||||
class AuthFedoraTestCase(TestCase):
|
||||
def _authenticate(self, response):
|
||||
backend = FedoraOpenIdConnect()
|
||||
pipeline = backend.strategy.get_pipeline(backend)
|
||||
return backend.pipeline(pipeline, response=response)
|
||||
|
||||
def test_new_user(self):
|
||||
"""Check that a Fedora user gets a ConfirmedEmail automatically."""
|
||||
user = self._authenticate({"nickname": "testuser", "email": "test@example.com"})
|
||||
self.assertEqual(user.confirmedemail_set.count(), 1)
|
||||
self.assertEqual(user.confirmedemail_set.first().email, "test@example.com")
|
||||
|
||||
@mock.patch("ivatar.ivataraccount.auth.TRUST_EMAIL_FROM_SOCIAL_AUTH_BACKENDS", [])
|
||||
def test_new_user_untrusted_backend(self):
|
||||
"""Check that ConfirmedEmails aren't automatically created for untrusted backends."""
|
||||
user = self._authenticate({"nickname": "testuser", "email": "test@example.com"})
|
||||
self.assertEqual(user.confirmedemail_set.count(), 0)
|
||||
|
||||
def test_existing_user(self):
|
||||
"""Checks that existing users are found."""
|
||||
user = User.objects.create_user(
|
||||
username="testuser",
|
||||
password="password",
|
||||
email="test@example.com",
|
||||
first_name="test",
|
||||
last_name="user",
|
||||
)
|
||||
auth_user = self._authenticate(
|
||||
{"nickname": "testuser", "email": "test@example.com"}
|
||||
)
|
||||
self.assertEqual(auth_user, user)
|
||||
# Only add ConfirmedEmails on account creation.
|
||||
self.assertEqual(auth_user.confirmedemail_set.count(), 0)
|
||||
|
||||
def test_existing_user_with_confirmed_email(self):
|
||||
"""Check that the authenticating user is found using their ConfirmedEmail."""
|
||||
user = User.objects.create_user(
|
||||
username="testuser1",
|
||||
password="password",
|
||||
email="first@example.com",
|
||||
first_name="test",
|
||||
last_name="user",
|
||||
)
|
||||
ConfirmedEmail.objects.create_confirmed_email(user, "second@example.com", False)
|
||||
auth_user = self._authenticate(
|
||||
{"nickname": "testuser2", "email": "second@example.com"}
|
||||
)
|
||||
self.assertEqual(auth_user, user)
|
||||
|
||||
def test_existing_confirmed_email(self):
|
||||
"""Check that ConfirmedEmail isn't created twice."""
|
||||
user = User.objects.create_user(
|
||||
username="testuser",
|
||||
password="password",
|
||||
email="testuser@example.com",
|
||||
first_name="test",
|
||||
last_name="user",
|
||||
)
|
||||
ConfirmedEmail.objects.create_confirmed_email(user, user.email, False)
|
||||
auth_user = self._authenticate({"nickname": user.username, "email": user.email})
|
||||
self.assertEqual(auth_user, user)
|
||||
self.assertEqual(auth_user.confirmedemail_set.count(), 1)
|
||||
File diff suppressed because it is too large
Load Diff
267
ivatar/ivataraccount/test_views_bluesky.py
Normal file
267
ivatar/ivataraccount/test_views_bluesky.py
Normal file
@@ -0,0 +1,267 @@
|
||||
"""
|
||||
Test our views in ivatar.ivataraccount.views and ivatar.views
|
||||
"""
|
||||
|
||||
import contextlib
|
||||
|
||||
# pylint: disable=too-many-lines
|
||||
import os
|
||||
import django
|
||||
import pytest
|
||||
from django.test import TestCase
|
||||
from django.test import Client
|
||||
|
||||
from django.urls import reverse
|
||||
from django.contrib.auth.models import User
|
||||
|
||||
# from django.contrib.auth import authenticate
|
||||
|
||||
os.environ["DJANGO_SETTINGS_MODULE"] = "ivatar.settings"
|
||||
django.setup()
|
||||
|
||||
# pylint: disable=wrong-import-position
|
||||
from ivatar import settings
|
||||
from ivatar.ivataraccount.models import ConfirmedOpenId, ConfirmedEmail
|
||||
from ivatar.utils import random_string, Bluesky
|
||||
|
||||
from libravatar import libravatar_url
|
||||
|
||||
|
||||
class Tester(TestCase): # pylint: disable=too-many-public-methods
|
||||
"""
|
||||
Main test class
|
||||
"""
|
||||
|
||||
client = Client()
|
||||
user = None
|
||||
username = random_string()
|
||||
password = random_string()
|
||||
email = "{}@{}.{}".format(username, random_string(), random_string(2))
|
||||
# Dunno why random tld doesn't work, but I'm too lazy now to investigate
|
||||
openid = "http://{}.{}.{}/".format(username, random_string(), "org")
|
||||
first_name = random_string()
|
||||
last_name = random_string()
|
||||
bsky_test_account = "libravatar.org"
|
||||
|
||||
def login(self):
|
||||
"""
|
||||
Login as user
|
||||
"""
|
||||
self.client.login(username=self.username, password=self.password)
|
||||
|
||||
def setUp(self):
|
||||
"""
|
||||
Prepare for tests.
|
||||
- Create user
|
||||
"""
|
||||
self.user = User.objects.create_user(
|
||||
username=self.username,
|
||||
password=self.password,
|
||||
first_name=self.first_name,
|
||||
last_name=self.last_name,
|
||||
)
|
||||
settings.EMAIL_BACKEND = "django.core.mail.backends.dummy.EmailBackend"
|
||||
|
||||
# Clear any existing Bluesky session to ensure clean test state
|
||||
Bluesky.clear_shared_session()
|
||||
|
||||
def tearDown(self):
|
||||
"""
|
||||
Clean up after tests
|
||||
"""
|
||||
# Clear Bluesky session to avoid affecting other tests
|
||||
Bluesky.clear_shared_session()
|
||||
|
||||
def create_confirmed_openid(self):
|
||||
"""
|
||||
Create a confirmed openid
|
||||
"""
|
||||
return ConfirmedOpenId.objects.create(
|
||||
user=self.user,
|
||||
ip_address="127.0.0.1",
|
||||
openid=self.openid,
|
||||
)
|
||||
|
||||
def create_confirmed_email(self):
|
||||
"""
|
||||
Create a confirmed email
|
||||
"""
|
||||
return ConfirmedEmail.objects.create(
|
||||
email=self.email,
|
||||
user=self.user,
|
||||
)
|
||||
|
||||
# The following tests need to be moved over to the model tests
|
||||
# and real web UI tests added
|
||||
@pytest.mark.bluesky
|
||||
def test_bluesky_handle_for_mail_via_model_handle_does_not_exist(self):
|
||||
"""
|
||||
Add Bluesky handle to a confirmed mail address
|
||||
"""
|
||||
self.login()
|
||||
confirmed = self.create_confirmed_email()
|
||||
confirmed.set_bluesky_handle(self.bsky_test_account)
|
||||
|
||||
with contextlib.suppress(Exception):
|
||||
confirmed.set_bluesky_handle(f"{self.bsky_test_account}1")
|
||||
self.assertNotEqual(
|
||||
confirmed.bluesky_handle,
|
||||
f"{self.bsky_test_account}1",
|
||||
"Setting Bluesky handle that doesn't exist works?",
|
||||
)
|
||||
|
||||
@pytest.mark.bluesky
|
||||
def test_bluesky_handle_for_mail_via_model_handle_exists(self):
|
||||
"""
|
||||
Add Bluesky handle to a confirmed mail address
|
||||
"""
|
||||
self.login()
|
||||
confirmed = self.create_confirmed_email()
|
||||
confirmed.set_bluesky_handle(self.bsky_test_account)
|
||||
|
||||
self.assertEqual(
|
||||
confirmed.bluesky_handle,
|
||||
self.bsky_test_account,
|
||||
"Setting Bluesky handle doesn't work?",
|
||||
)
|
||||
|
||||
@pytest.mark.bluesky
|
||||
def test_bluesky_handle_for_openid_via_model_handle_does_not_exist(self):
|
||||
"""
|
||||
Add Bluesky handle to a confirmed openid address
|
||||
"""
|
||||
self.login()
|
||||
confirmed = self.create_confirmed_openid()
|
||||
confirmed.set_bluesky_handle(self.bsky_test_account)
|
||||
|
||||
with contextlib.suppress(Exception):
|
||||
confirmed.set_bluesky_handle(f"{self.bsky_test_account}1")
|
||||
self.assertNotEqual(
|
||||
confirmed.bluesky_handle,
|
||||
f"{self.bsky_test_account}1",
|
||||
"Setting Bluesky handle that doesn't exist works?",
|
||||
)
|
||||
|
||||
@pytest.mark.bluesky
|
||||
def test_bluesky_handle_for_openid_via_model_handle_exists(self):
|
||||
"""
|
||||
Add Bluesky handle to a confirmed openid address
|
||||
"""
|
||||
self.login()
|
||||
confirmed = self.create_confirmed_openid()
|
||||
confirmed.set_bluesky_handle(self.bsky_test_account)
|
||||
|
||||
self.assertEqual(
|
||||
confirmed.bluesky_handle,
|
||||
self.bsky_test_account,
|
||||
"Setting Bluesky handle doesn't work?",
|
||||
)
|
||||
|
||||
@pytest.mark.bluesky
|
||||
def test_bluesky_fetch_mail(self):
|
||||
"""
|
||||
Check if we can successfully fetch a Bluesky avatar via email
|
||||
"""
|
||||
self.login()
|
||||
confirmed = self.create_confirmed_email()
|
||||
confirmed.set_bluesky_handle(self.bsky_test_account)
|
||||
lu = libravatar_url(confirmed.email, https=True)
|
||||
lu = lu.replace("https://seccdn.libravatar.org/", reverse("home"))
|
||||
|
||||
response = self.client.get(lu)
|
||||
# This is supposed to redirect to the Bluesky proxy
|
||||
self.assertEqual(response.status_code, 302)
|
||||
self.assertEqual(response["Location"], f"/blueskyproxy/{confirmed.digest}")
|
||||
|
||||
@pytest.mark.bluesky
|
||||
def test_bluesky_fetch_openid(self):
|
||||
"""
|
||||
Check if we can successfully fetch a Bluesky avatar via OpenID
|
||||
"""
|
||||
self.login()
|
||||
confirmed = self.create_confirmed_openid()
|
||||
confirmed.set_bluesky_handle(self.bsky_test_account)
|
||||
lu = libravatar_url(openid=confirmed.openid, https=True)
|
||||
lu = lu.replace("https://seccdn.libravatar.org/", reverse("home"))
|
||||
|
||||
response = self.client.get(lu)
|
||||
# This is supposed to redirect to the Bluesky proxy
|
||||
self.assertEqual(response.status_code, 302)
|
||||
self.assertEqual(response["Location"], f"/blueskyproxy/{confirmed.digest}")
|
||||
|
||||
@pytest.mark.bluesky
|
||||
def test_assign_bluesky_handle_to_openid(self):
|
||||
"""
|
||||
Assign a Bluesky handle to an OpenID
|
||||
"""
|
||||
self.login()
|
||||
confirmed = self.create_confirmed_openid()
|
||||
self._assign_handle_to(
|
||||
"assign_bluesky_handle_to_openid",
|
||||
confirmed,
|
||||
"Adding Bluesky handle to OpenID fails?",
|
||||
)
|
||||
|
||||
@pytest.mark.bluesky
|
||||
def test_assign_bluesky_handle_to_email(self):
|
||||
"""
|
||||
Assign a Bluesky handle to an email
|
||||
|
||||
"""
|
||||
self.login()
|
||||
confirmed = self.create_confirmed_email()
|
||||
self._assign_handle_to(
|
||||
"assign_bluesky_handle_to_email",
|
||||
confirmed,
|
||||
"Adding Bluesky handle to Email fails?",
|
||||
)
|
||||
|
||||
def _assign_handle_to(self, endpoint, confirmed, message):
|
||||
"""
|
||||
Helper method to assign a handle to reduce code duplication
|
||||
Since the endpoints are similar, we can reuse the code
|
||||
"""
|
||||
url = reverse(endpoint, args=[confirmed.id])
|
||||
response = self.client.post(
|
||||
url, {"bluesky_handle": self.bsky_test_account}, follow=True
|
||||
)
|
||||
self.assertEqual(response.status_code, 200, message)
|
||||
confirmed.refresh_from_db(fields=["bluesky_handle"])
|
||||
self.assertEqual(
|
||||
confirmed.bluesky_handle,
|
||||
self.bsky_test_account,
|
||||
"Setting Bluesky handle doesn't work?",
|
||||
)
|
||||
|
||||
@pytest.mark.bluesky
|
||||
def test_assign_photo_to_mail_removes_bluesky_handle(self):
|
||||
"""
|
||||
Assign a Photo to a mail, removes Bluesky handle
|
||||
"""
|
||||
self.login()
|
||||
confirmed = self.create_confirmed_email()
|
||||
self._assign_bluesky_handle(confirmed, "assign_photo_email")
|
||||
|
||||
@pytest.mark.bluesky
|
||||
def test_assign_photo_to_openid_removes_bluesky_handle(self):
|
||||
"""
|
||||
Assign a Photo to a OpenID, removes Bluesky handle
|
||||
"""
|
||||
self.login()
|
||||
confirmed = self.create_confirmed_openid()
|
||||
self._assign_bluesky_handle(confirmed, "assign_photo_openid")
|
||||
|
||||
def _assign_bluesky_handle(self, confirmed, endpoint):
|
||||
"""
|
||||
Helper method to assign a Bluesky handle
|
||||
Since the endpoints are similar, we can reuse the code
|
||||
"""
|
||||
confirmed.bluesky_handle = self.bsky_test_account
|
||||
confirmed.save()
|
||||
url = reverse(endpoint, args=[confirmed.id])
|
||||
response = self.client.post(url, {"photoNone": True}, follow=True)
|
||||
self.assertEqual(response.status_code, 200, "Unassigning Photo doesn't work?")
|
||||
confirmed.refresh_from_db(fields=["bluesky_handle"])
|
||||
self.assertEqual(
|
||||
confirmed.bluesky_handle, None, "Removing Bluesky handle doesn't work?"
|
||||
)
|
||||
@@ -1,119 +1,169 @@
|
||||
'''
|
||||
"""
|
||||
URLs for ivatar.ivataraccount
|
||||
'''
|
||||
from django.urls import path
|
||||
from django.conf.urls import url
|
||||
"""
|
||||
|
||||
from django.urls import path, re_path
|
||||
|
||||
from django.views.generic import TemplateView
|
||||
from django.contrib.auth.views import LogoutView
|
||||
from django.contrib.auth.views import PasswordResetDoneView,\
|
||||
PasswordResetConfirmView, PasswordResetCompleteView
|
||||
from django.contrib.auth.views import (
|
||||
PasswordResetDoneView,
|
||||
PasswordResetConfirmView,
|
||||
PasswordResetCompleteView,
|
||||
)
|
||||
from django.contrib.auth.views import PasswordChangeView, PasswordChangeDoneView
|
||||
from django.contrib.auth.decorators import login_required
|
||||
|
||||
from . views import ProfileView, PasswordResetView
|
||||
from . views import CreateView, PasswordSetView, AddEmailView
|
||||
from . views import RemoveUnconfirmedEmailView, ConfirmEmailView
|
||||
from . views import RemoveConfirmedEmailView, AssignPhotoEmailView
|
||||
from . views import RemoveUnconfirmedOpenIDView, RemoveConfirmedOpenIDView
|
||||
from . views import ImportPhotoView, RawImageView, DeletePhotoView
|
||||
from . views import UploadPhotoView, AssignPhotoOpenIDView
|
||||
from . views import AddOpenIDView, RedirectOpenIDView, ConfirmOpenIDView
|
||||
from . views import CropPhotoView
|
||||
from . views import UserPreferenceView, UploadLibravatarExportView
|
||||
from . views import ResendConfirmationMailView
|
||||
from . views import IvatarLoginView
|
||||
from . views import DeleteAccountView
|
||||
from .views import ProfileView, PasswordResetView
|
||||
from .views import CreateView, PasswordSetView, AddEmailView
|
||||
from .views import RemoveUnconfirmedEmailView, ConfirmEmailView
|
||||
from .views import RemoveConfirmedEmailView, AssignPhotoEmailView
|
||||
from .views import RemoveUnconfirmedOpenIDView, RemoveConfirmedOpenIDView
|
||||
from .views import ImportPhotoView, RawImageView, DeletePhotoView
|
||||
from .views import UploadPhotoView, AssignPhotoOpenIDView
|
||||
from .views import AddOpenIDView, RedirectOpenIDView, ConfirmOpenIDView
|
||||
from .views import AssignBlueskyHandleToEmailView, AssignBlueskyHandleToOpenIdView
|
||||
from .views import CropPhotoView
|
||||
from .views import UserPreferenceView, UploadLibravatarExportView
|
||||
from .views import ResendConfirmationMailView
|
||||
from .views import IvatarLoginView
|
||||
from .views import DeleteAccountView
|
||||
from .views import ExportView
|
||||
|
||||
# Define URL patterns, self documenting
|
||||
# To see the fancy, colorful evaluation of these use:
|
||||
# ./manager show_urls
|
||||
urlpatterns = [ # pylint: disable=invalid-name
|
||||
path('new/', CreateView.as_view(), name='new_account'),
|
||||
path('login/', IvatarLoginView.as_view(), name='login'),
|
||||
path("new/", CreateView.as_view(), name="new_account"),
|
||||
path("login/", IvatarLoginView.as_view(), name="login"),
|
||||
path("logout/", LogoutView.as_view(next_page="/"), name="logout"),
|
||||
path(
|
||||
'logout/', LogoutView.as_view(next_page='/'),
|
||||
name='logout'),
|
||||
|
||||
path('password_change/',
|
||||
PasswordChangeView.as_view(template_name='password_change.html'),
|
||||
name='password_change'),
|
||||
path('password_change/done/',
|
||||
PasswordChangeDoneView.as_view(template_name='password_change_done.html'),
|
||||
name='password_change_done'),
|
||||
|
||||
path('password_reset/',
|
||||
PasswordResetView.as_view(template_name='password_reset.html'),
|
||||
name='password_reset'),
|
||||
path('password_reset/done/',
|
||||
PasswordResetDoneView.as_view(
|
||||
template_name='password_reset_submitted.html'),
|
||||
name='password_reset_done'),
|
||||
path('reset/<uidb64>/<token>/',
|
||||
PasswordResetConfirmView.as_view(
|
||||
template_name='password_change.html'),
|
||||
name='password_reset_confirm'),
|
||||
path('reset/done/',
|
||||
PasswordResetCompleteView.as_view(
|
||||
template_name='password_change_done.html'),
|
||||
name='password_reset_complete'),
|
||||
|
||||
path('export/', login_required(
|
||||
TemplateView.as_view(template_name='export.html')
|
||||
), name='export'),
|
||||
path('delete/', DeleteAccountView.as_view(), name='delete'),
|
||||
path('profile/', ProfileView.as_view(), name='profile'),
|
||||
url('profile/(?P<profile_username>.+)', ProfileView.as_view(), name='profile_with_profile_username'),
|
||||
path('add_email/', AddEmailView.as_view(), name='add_email'),
|
||||
path('add_openid/', AddOpenIDView.as_view(), name='add_openid'),
|
||||
path('upload_photo/', UploadPhotoView.as_view(), name='upload_photo'),
|
||||
path('password_set/', PasswordSetView.as_view(), name='password_set'),
|
||||
url(
|
||||
r'remove_unconfirmed_openid/(?P<openid_id>\d+)',
|
||||
"password_change/",
|
||||
PasswordChangeView.as_view(template_name="password_change.html"),
|
||||
name="password_change",
|
||||
),
|
||||
path(
|
||||
"password_change/done/",
|
||||
PasswordChangeDoneView.as_view(template_name="password_change_done.html"),
|
||||
name="password_change_done",
|
||||
),
|
||||
path(
|
||||
"password_reset/",
|
||||
PasswordResetView.as_view(template_name="password_reset.html"),
|
||||
name="password_reset",
|
||||
),
|
||||
path(
|
||||
"password_reset/done/",
|
||||
PasswordResetDoneView.as_view(template_name="password_reset_submitted.html"),
|
||||
name="password_reset_done",
|
||||
),
|
||||
path(
|
||||
"reset/<uidb64>/<token>/",
|
||||
PasswordResetConfirmView.as_view(template_name="password_change.html"),
|
||||
name="password_reset_confirm",
|
||||
),
|
||||
path(
|
||||
"reset/done/",
|
||||
PasswordResetCompleteView.as_view(template_name="password_change_done.html"),
|
||||
name="password_reset_complete",
|
||||
),
|
||||
path(
|
||||
"export/",
|
||||
ExportView.as_view(),
|
||||
name="export",
|
||||
),
|
||||
path("delete/", DeleteAccountView.as_view(), name="delete"),
|
||||
path("profile/", ProfileView.as_view(), name="profile"),
|
||||
re_path(
|
||||
"profile/(?P<profile_username>.+)",
|
||||
ProfileView.as_view(),
|
||||
name="profile_with_profile_username",
|
||||
),
|
||||
path("add_email/", AddEmailView.as_view(), name="add_email"),
|
||||
path("add_openid/", AddOpenIDView.as_view(), name="add_openid"),
|
||||
path("upload_photo/", UploadPhotoView.as_view(), name="upload_photo"),
|
||||
path("password_set/", PasswordSetView.as_view(), name="password_set"),
|
||||
re_path(
|
||||
r"remove_unconfirmed_openid/(?P<openid_id>\d+)",
|
||||
RemoveUnconfirmedOpenIDView.as_view(),
|
||||
name='remove_unconfirmed_openid'),
|
||||
url(
|
||||
r'remove_confirmed_openid/(?P<openid_id>\d+)',
|
||||
RemoveConfirmedOpenIDView.as_view(), name='remove_confirmed_openid'),
|
||||
url(
|
||||
r'openid_redirection/(?P<openid_id>\d+)',
|
||||
RedirectOpenIDView.as_view(), name='openid_redirection'),
|
||||
url(
|
||||
r'confirm_openid/(?P<openid_id>\w+)',
|
||||
ConfirmOpenIDView.as_view(), name='confirm_openid'),
|
||||
url(
|
||||
r'confirm_email/(?P<verification_key>\w+)',
|
||||
ConfirmEmailView.as_view(), name='confirm_email'),
|
||||
url(
|
||||
r'remove_unconfirmed_email/(?P<email_id>\d+)',
|
||||
RemoveUnconfirmedEmailView.as_view(), name='remove_unconfirmed_email'),
|
||||
url(
|
||||
r'remove_confirmed_email/(?P<email_id>\d+)',
|
||||
RemoveConfirmedEmailView.as_view(), name='remove_confirmed_email'),
|
||||
url(
|
||||
r'assign_photo_email/(?P<email_id>\d+)',
|
||||
AssignPhotoEmailView.as_view(), name='assign_photo_email'),
|
||||
url(
|
||||
r'assign_photo_openid/(?P<openid_id>\d+)',
|
||||
AssignPhotoOpenIDView.as_view(), name='assign_photo_openid'),
|
||||
url(
|
||||
r'import_photo/$',
|
||||
ImportPhotoView.as_view(), name='import_photo'),
|
||||
url(
|
||||
r'import_photo/(?P<email_addr>[\w.]+@[\w.]+.[\w.]+)',
|
||||
ImportPhotoView.as_view(), name='import_photo'),
|
||||
url(
|
||||
r'import_photo/(?P<email_id>\d+)',
|
||||
ImportPhotoView.as_view(), name='import_photo'),
|
||||
url(
|
||||
r'delete_photo/(?P<pk>\d+)',
|
||||
DeletePhotoView.as_view(), name='delete_photo'),
|
||||
url(r'raw_image/(?P<pk>\d+)', RawImageView.as_view(), name='raw_image'),
|
||||
url(r'crop_photo/(?P<pk>\d+)', CropPhotoView.as_view(), name='crop_photo'),
|
||||
url(r'pref/$', UserPreferenceView.as_view(), name='user_preference'),
|
||||
url(r'upload_export/$', UploadLibravatarExportView.as_view(), name='upload_export'),
|
||||
url(r'upload_export/(?P<save>save)$',
|
||||
UploadLibravatarExportView.as_view(), name='upload_export'),
|
||||
url(r'resend_confirmation_mail/(?P<email_id>\d+)',
|
||||
ResendConfirmationMailView.as_view(), name='resend_confirmation_mail'),
|
||||
name="remove_unconfirmed_openid",
|
||||
),
|
||||
re_path(
|
||||
r"remove_confirmed_openid/(?P<openid_id>\d+)",
|
||||
RemoveConfirmedOpenIDView.as_view(),
|
||||
name="remove_confirmed_openid",
|
||||
),
|
||||
re_path(
|
||||
r"openid_redirection/(?P<openid_id>\d+)",
|
||||
RedirectOpenIDView.as_view(),
|
||||
name="openid_redirection",
|
||||
),
|
||||
re_path(
|
||||
r"confirm_openid/(?P<openid_id>\w+)",
|
||||
ConfirmOpenIDView.as_view(),
|
||||
name="confirm_openid",
|
||||
),
|
||||
re_path(
|
||||
r"confirm_email/(?P<verification_key>\w+)",
|
||||
ConfirmEmailView.as_view(),
|
||||
name="confirm_email",
|
||||
),
|
||||
re_path(
|
||||
r"remove_unconfirmed_email/(?P<email_id>\d+)",
|
||||
RemoveUnconfirmedEmailView.as_view(),
|
||||
name="remove_unconfirmed_email",
|
||||
),
|
||||
re_path(
|
||||
r"remove_confirmed_email/(?P<email_id>\d+)",
|
||||
RemoveConfirmedEmailView.as_view(),
|
||||
name="remove_confirmed_email",
|
||||
),
|
||||
re_path(
|
||||
r"assign_photo_email/(?P<email_id>\d+)",
|
||||
AssignPhotoEmailView.as_view(),
|
||||
name="assign_photo_email",
|
||||
),
|
||||
re_path(
|
||||
r"assign_photo_openid/(?P<openid_id>\d+)",
|
||||
AssignPhotoOpenIDView.as_view(),
|
||||
name="assign_photo_openid",
|
||||
),
|
||||
re_path(
|
||||
r"assign_bluesky_handle_to_email/(?P<email_id>\d+)",
|
||||
AssignBlueskyHandleToEmailView.as_view(),
|
||||
name="assign_bluesky_handle_to_email",
|
||||
),
|
||||
re_path(
|
||||
r"assign_bluesky_handle_to_openid/(?P<open_id>\d+)",
|
||||
AssignBlueskyHandleToOpenIdView.as_view(),
|
||||
name="assign_bluesky_handle_to_openid",
|
||||
),
|
||||
re_path(r"import_photo/$", ImportPhotoView.as_view(), name="import_photo"),
|
||||
re_path(
|
||||
r"import_photo/(?P<email_addr>[\w.+-]+@[\w.]+.[\w.]+)",
|
||||
ImportPhotoView.as_view(),
|
||||
name="import_photo",
|
||||
),
|
||||
re_path(
|
||||
r"import_photo/(?P<email_id>\d+)",
|
||||
ImportPhotoView.as_view(),
|
||||
name="import_photo",
|
||||
),
|
||||
re_path(
|
||||
r"delete_photo/(?P<pk>\d+)", DeletePhotoView.as_view(), name="delete_photo"
|
||||
),
|
||||
re_path(r"raw_image/(?P<pk>\d+)", RawImageView.as_view(), name="raw_image"),
|
||||
re_path(r"crop_photo/(?P<pk>\d+)", CropPhotoView.as_view(), name="crop_photo"),
|
||||
re_path(r"pref/$", UserPreferenceView.as_view(), name="user_preference"),
|
||||
re_path(
|
||||
r"upload_export/$", UploadLibravatarExportView.as_view(), name="upload_export"
|
||||
),
|
||||
re_path(
|
||||
r"upload_export/(?P<save>save)$",
|
||||
UploadLibravatarExportView.as_view(),
|
||||
name="upload_export",
|
||||
),
|
||||
re_path(
|
||||
r"resend_confirmation_mail/(?P<email_id>\d+)",
|
||||
ResendConfirmationMailView.as_view(),
|
||||
name="resend_confirmation_mail",
|
||||
),
|
||||
]
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,18 +1,63 @@
|
||||
"""
|
||||
Middleware classes
|
||||
"""
|
||||
from django.utils.deprecation import MiddlewareMixin
|
||||
|
||||
class MultipleProxyMiddleware(MiddlewareMixin): # pylint: disable=too-few-public-methods
|
||||
from django.utils.deprecation import MiddlewareMixin
|
||||
from django.middleware.locale import LocaleMiddleware
|
||||
|
||||
|
||||
class CustomLocaleMiddleware(LocaleMiddleware):
|
||||
"""
|
||||
Middleware that extends LocaleMiddleware to skip Vary header processing for image URLs
|
||||
"""
|
||||
|
||||
def process_response(self, request, response):
|
||||
# Check if this is an image-related URL
|
||||
path = request.path
|
||||
if any(
|
||||
path.startswith(prefix)
|
||||
for prefix in ["/avatar/", "/gravatarproxy/", "/blueskyproxy/"]
|
||||
):
|
||||
# Delete Vary from header if exists
|
||||
if "Vary" in response:
|
||||
del response["Vary"]
|
||||
|
||||
# Extract hash from URL path for ETag
|
||||
# URLs are like /avatar/{hash}, /gravatarproxy/{hash}, /blueskyproxy/{hash}
|
||||
path_parts = path.strip("/").split("/")
|
||||
if len(path_parts) >= 2:
|
||||
hash_value = path_parts[1] # Get the hash part
|
||||
# Sanitize hash_value to remove newlines and other control characters
|
||||
# that would cause BadHeaderError
|
||||
hash_value = "".join(
|
||||
c for c in hash_value if c.isprintable() and c not in "\r\n"
|
||||
)
|
||||
response["Etag"] = f'"{hash_value}"'
|
||||
else:
|
||||
# Fallback to content hash if we can't extract from URL
|
||||
response["Etag"] = f'"{hash(response.content)}"'
|
||||
|
||||
# Skip the parent's process_response to avoid adding Accept-Language to Vary
|
||||
return response
|
||||
|
||||
# For all other URLs, use the parent's behavior
|
||||
return super().process_response(request, response)
|
||||
|
||||
|
||||
class MultipleProxyMiddleware(
|
||||
MiddlewareMixin
|
||||
): # pylint: disable=too-few-public-methods
|
||||
"""
|
||||
Middleware to rewrite proxy headers for deployments
|
||||
with multiple proxies
|
||||
"""
|
||||
|
||||
def process_request(self, request):
|
||||
def process_request(self, request): # pylint: disable=no-self-use
|
||||
"""
|
||||
Rewrites the proxy headers so that forwarded server is
|
||||
used if available.
|
||||
"""
|
||||
if 'HTTP_X_FORWARDED_SERVER' in request.META:
|
||||
request.META['HTTP_X_FORWARDED_HOST'] = request.META['HTTP_X_FORWARDED_SERVER']
|
||||
if "HTTP_X_FORWARDED_SERVER" in request.META:
|
||||
request.META["HTTP_X_FORWARDED_HOST"] = request.META[
|
||||
"HTTP_X_FORWARDED_SERVER"
|
||||
]
|
||||
|
||||
300
ivatar/opentelemetry_config.py
Normal file
300
ivatar/opentelemetry_config.py
Normal file
@@ -0,0 +1,300 @@
|
||||
"""
|
||||
OpenTelemetry configuration for ivatar project.
|
||||
|
||||
This module provides OpenTelemetry setup and configuration for the ivatar
|
||||
Django application, including tracing, metrics, and logging integration.
|
||||
"""
|
||||
|
||||
import os
|
||||
import logging
|
||||
|
||||
from opentelemetry import trace, metrics
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
|
||||
from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter
|
||||
from opentelemetry.exporter.prometheus import PrometheusMetricReader
|
||||
from opentelemetry.instrumentation.psycopg2 import Psycopg2Instrumentor
|
||||
from opentelemetry.instrumentation.pymysql import PyMySQLInstrumentor
|
||||
from opentelemetry.instrumentation.requests import RequestsInstrumentor
|
||||
from opentelemetry.instrumentation.urllib3 import URLLib3Instrumentor
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import ImproperlyConfigured
|
||||
|
||||
# Note: Memcached instrumentation not available in OpenTelemetry Python
|
||||
|
||||
logger = logging.getLogger("ivatar")
|
||||
|
||||
|
||||
class OpenTelemetryConfig:
|
||||
"""
|
||||
OpenTelemetry configuration manager for ivatar.
|
||||
|
||||
Handles setup of tracing, metrics, and instrumentation for the Django application.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.enabled = True # Always enable OpenTelemetry instrumentation
|
||||
self.export_enabled = self._is_export_enabled()
|
||||
self.service_name = self._get_service_name()
|
||||
self.environment = self._get_environment()
|
||||
self.resource = self._create_resource()
|
||||
|
||||
def _is_export_enabled(self) -> bool:
|
||||
"""Check if OpenTelemetry data export is enabled via environment variable."""
|
||||
return os.environ.get("OTEL_EXPORT_ENABLED", "false").lower() in (
|
||||
"true",
|
||||
"1",
|
||||
"yes",
|
||||
)
|
||||
|
||||
def _get_service_name(self) -> str:
|
||||
"""Get service name from environment or default."""
|
||||
return os.environ.get("OTEL_SERVICE_NAME", "ivatar")
|
||||
|
||||
def _get_environment(self) -> str:
|
||||
"""Get environment name (production, development, etc.)."""
|
||||
return os.environ.get("OTEL_ENVIRONMENT", "development")
|
||||
|
||||
def _create_resource(self) -> Resource:
|
||||
"""Create OpenTelemetry resource with service information."""
|
||||
# Get IVATAR_VERSION from environment or settings, handling case where
|
||||
# Django settings might not be configured yet
|
||||
ivatar_version = os.environ.get("IVATAR_VERSION")
|
||||
if not ivatar_version:
|
||||
# Try to access settings, but handle case where Django isn't configured
|
||||
try:
|
||||
ivatar_version = getattr(settings, "IVATAR_VERSION", "2.0")
|
||||
except ImproperlyConfigured:
|
||||
# Django settings not configured yet, use default
|
||||
ivatar_version = "2.0"
|
||||
|
||||
return Resource.create(
|
||||
{
|
||||
"service.name": self.service_name,
|
||||
"service.version": ivatar_version,
|
||||
"service.namespace": "libravatar",
|
||||
"deployment.environment": self.environment,
|
||||
"service.instance.id": os.environ.get("HOSTNAME", "unknown"),
|
||||
}
|
||||
)
|
||||
|
||||
def setup_tracing(self) -> None:
|
||||
"""Set up OpenTelemetry tracing."""
|
||||
try:
|
||||
# Only set up tracing if export is enabled
|
||||
if not self.export_enabled:
|
||||
logger.info("OpenTelemetry tracing disabled (export disabled)")
|
||||
return
|
||||
|
||||
# Set up tracer provider
|
||||
trace.set_tracer_provider(TracerProvider(resource=self.resource))
|
||||
tracer_provider = trace.get_tracer_provider()
|
||||
|
||||
# Configure OTLP exporter if endpoint is provided
|
||||
otlp_endpoint = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT")
|
||||
if otlp_endpoint:
|
||||
otlp_exporter = OTLPSpanExporter(endpoint=otlp_endpoint)
|
||||
span_processor = BatchSpanProcessor(otlp_exporter)
|
||||
tracer_provider.add_span_processor(span_processor)
|
||||
logger.info(
|
||||
f"OpenTelemetry tracing configured with OTLP endpoint: {otlp_endpoint}"
|
||||
)
|
||||
else:
|
||||
logger.info("OpenTelemetry tracing configured without OTLP endpoint")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to setup OpenTelemetry tracing: {e}")
|
||||
# Don't disable OpenTelemetry entirely - metrics and instrumentation can still work
|
||||
|
||||
def setup_metrics(self) -> None:
|
||||
"""Set up OpenTelemetry metrics."""
|
||||
try:
|
||||
# Configure metric readers based on environment
|
||||
metric_readers = []
|
||||
|
||||
# Configure OTLP exporter if export is enabled and endpoint is provided
|
||||
if self.export_enabled:
|
||||
otlp_endpoint = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT")
|
||||
if otlp_endpoint:
|
||||
otlp_exporter = OTLPMetricExporter(endpoint=otlp_endpoint)
|
||||
metric_reader = PeriodicExportingMetricReader(otlp_exporter)
|
||||
metric_readers.append(metric_reader)
|
||||
logger.info(
|
||||
f"OpenTelemetry metrics configured with OTLP endpoint: {otlp_endpoint}"
|
||||
)
|
||||
|
||||
# For development/local testing, also configure Prometheus HTTP server
|
||||
# In production, metrics are scraped by external Prometheus server
|
||||
prometheus_endpoint = os.environ.get("OTEL_PROMETHEUS_ENDPOINT")
|
||||
if prometheus_endpoint:
|
||||
prometheus_reader = PrometheusMetricReader()
|
||||
metric_readers.append(prometheus_reader)
|
||||
|
||||
# Set up meter provider with readers
|
||||
meter_provider = MeterProvider(
|
||||
resource=self.resource, metric_readers=metric_readers
|
||||
)
|
||||
|
||||
# Only set meter provider if it's not already set
|
||||
try:
|
||||
metrics.set_meter_provider(meter_provider)
|
||||
except Exception as e:
|
||||
if "Overriding of current MeterProvider is not allowed" in str(e):
|
||||
logger.warning("MeterProvider already set, using existing provider")
|
||||
# Get the existing meter provider and add our readers
|
||||
existing_provider = metrics.get_meter_provider()
|
||||
if hasattr(existing_provider, "add_metric_reader"):
|
||||
for reader in metric_readers:
|
||||
existing_provider.add_metric_reader(reader)
|
||||
else:
|
||||
raise
|
||||
|
||||
# Start Prometheus HTTP server for local development (if configured)
|
||||
if prometheus_endpoint:
|
||||
self._start_prometheus_server(prometheus_reader, prometheus_endpoint)
|
||||
logger.info(
|
||||
f"OpenTelemetry metrics configured with Prometheus endpoint: {prometheus_endpoint}"
|
||||
)
|
||||
|
||||
if not metric_readers:
|
||||
logger.warning(
|
||||
"No metric readers configured - metrics will not be exported"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to setup OpenTelemetry metrics: {e}")
|
||||
# Don't disable OpenTelemetry entirely - tracing and instrumentation can still work
|
||||
|
||||
def _start_prometheus_server(
|
||||
self, prometheus_reader: PrometheusMetricReader, endpoint: str
|
||||
) -> None:
|
||||
"""Start Prometheus HTTP server for metrics endpoint."""
|
||||
try:
|
||||
from prometheus_client import start_http_server, REGISTRY
|
||||
|
||||
# Parse endpoint to get host and port
|
||||
if ":" in endpoint:
|
||||
host, port = endpoint.split(":", 1)
|
||||
port = int(port)
|
||||
else:
|
||||
host = "0.0.0.0"
|
||||
port = int(endpoint)
|
||||
|
||||
# Register the PrometheusMetricReader collector with prometheus_client
|
||||
REGISTRY.register(prometheus_reader._collector)
|
||||
|
||||
# Start HTTP server
|
||||
start_http_server(port, addr=host)
|
||||
|
||||
logger.info(f"Prometheus metrics server started on {host}:{port}")
|
||||
|
||||
except OSError as e:
|
||||
if e.errno == 98: # Address already in use
|
||||
logger.warning(
|
||||
f"Prometheus metrics server already running on {endpoint}"
|
||||
)
|
||||
else:
|
||||
logger.error(f"Failed to start Prometheus metrics server: {e}")
|
||||
# Don't disable OpenTelemetry entirely - metrics can still be exported via OTLP
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to start Prometheus metrics server: {e}")
|
||||
# Don't disable OpenTelemetry entirely - metrics can still be exported via OTLP
|
||||
|
||||
def setup_instrumentation(self) -> None:
|
||||
"""Set up OpenTelemetry instrumentation for various libraries."""
|
||||
try:
|
||||
# Django instrumentation - TEMPORARILY DISABLED TO TEST HEADER ISSUE
|
||||
# DjangoInstrumentor().instrument()
|
||||
# logger.info("Django instrumentation enabled")
|
||||
|
||||
# Database instrumentation
|
||||
Psycopg2Instrumentor().instrument()
|
||||
PyMySQLInstrumentor().instrument()
|
||||
logger.info("Database instrumentation enabled")
|
||||
|
||||
# HTTP client instrumentation
|
||||
RequestsInstrumentor().instrument()
|
||||
URLLib3Instrumentor().instrument()
|
||||
logger.info("HTTP client instrumentation enabled")
|
||||
|
||||
# Note: Memcached instrumentation not available in OpenTelemetry Python
|
||||
# Cache operations will be traced through Django instrumentation
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to setup OpenTelemetry instrumentation: {e}")
|
||||
# Don't disable OpenTelemetry entirely - tracing and metrics can still work
|
||||
|
||||
def get_tracer(self, name: str) -> trace.Tracer:
|
||||
"""Get a tracer instance."""
|
||||
return trace.get_tracer(name)
|
||||
|
||||
def get_meter(self, name: str) -> metrics.Meter:
|
||||
"""Get a meter instance."""
|
||||
return metrics.get_meter(name)
|
||||
|
||||
|
||||
# Global OpenTelemetry configuration instance (lazy-loaded)
|
||||
_ot_config = None
|
||||
_ot_initialized = False
|
||||
|
||||
|
||||
def get_ot_config():
|
||||
"""Get the global OpenTelemetry configuration instance."""
|
||||
global _ot_config
|
||||
if _ot_config is None:
|
||||
_ot_config = OpenTelemetryConfig()
|
||||
return _ot_config
|
||||
|
||||
|
||||
def setup_opentelemetry() -> None:
|
||||
"""
|
||||
Set up OpenTelemetry for the ivatar application.
|
||||
|
||||
This function should be called during Django application startup.
|
||||
"""
|
||||
global _ot_initialized
|
||||
|
||||
if _ot_initialized:
|
||||
logger.debug("OpenTelemetry already initialized, skipping setup")
|
||||
return
|
||||
|
||||
logger.info("Setting up OpenTelemetry...")
|
||||
|
||||
ot_config = get_ot_config()
|
||||
ot_config.setup_tracing()
|
||||
ot_config.setup_metrics()
|
||||
ot_config.setup_instrumentation()
|
||||
|
||||
if ot_config.enabled:
|
||||
if ot_config.export_enabled:
|
||||
logger.info("OpenTelemetry setup completed successfully (export enabled)")
|
||||
else:
|
||||
logger.info("OpenTelemetry setup completed successfully (export disabled)")
|
||||
_ot_initialized = True
|
||||
else:
|
||||
logger.info("OpenTelemetry setup failed")
|
||||
|
||||
|
||||
def get_tracer(name: str) -> trace.Tracer:
|
||||
"""Get a tracer instance for the given name."""
|
||||
return get_ot_config().get_tracer(name)
|
||||
|
||||
|
||||
def get_meter(name: str) -> metrics.Meter:
|
||||
"""Get a meter instance for the given name."""
|
||||
return get_ot_config().get_meter(name)
|
||||
|
||||
|
||||
def is_enabled() -> bool:
|
||||
"""Check if OpenTelemetry is enabled (always True now)."""
|
||||
return True
|
||||
|
||||
|
||||
def is_export_enabled() -> bool:
|
||||
"""Check if OpenTelemetry data export is enabled."""
|
||||
return get_ot_config().export_enabled
|
||||
418
ivatar/opentelemetry_middleware.py
Normal file
418
ivatar/opentelemetry_middleware.py
Normal file
@@ -0,0 +1,418 @@
|
||||
"""
|
||||
OpenTelemetry middleware and custom instrumentation for ivatar.
|
||||
|
||||
This module provides custom OpenTelemetry instrumentation for avatar-specific
|
||||
operations, including metrics and tracing for avatar generation, file uploads,
|
||||
and authentication flows.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import time
|
||||
from functools import wraps
|
||||
|
||||
from django.http import HttpRequest, HttpResponse
|
||||
from django.utils.deprecation import MiddlewareMixin
|
||||
|
||||
from opentelemetry import trace
|
||||
from opentelemetry.trace import Status, StatusCode
|
||||
|
||||
from ivatar.opentelemetry_config import get_tracer, get_meter, is_enabled
|
||||
|
||||
logger = logging.getLogger("ivatar")
|
||||
|
||||
|
||||
class OpenTelemetryMiddleware(MiddlewareMixin):
|
||||
"""
|
||||
Custom OpenTelemetry middleware for ivatar-specific metrics and tracing.
|
||||
|
||||
This middleware adds custom attributes and metrics to OpenTelemetry spans
|
||||
for avatar-related operations.
|
||||
"""
|
||||
|
||||
def __init__(self, get_response):
|
||||
self.get_response = get_response
|
||||
# Don't get metrics instance here - get it lazily in __call__
|
||||
|
||||
def __call__(self, request):
|
||||
# Get metrics instance lazily
|
||||
if not hasattr(self, "metrics"):
|
||||
self.metrics = get_avatar_metrics()
|
||||
|
||||
# Process request to start tracing
|
||||
self.process_request(request)
|
||||
|
||||
response = self.get_response(request)
|
||||
|
||||
# Process response to complete tracing
|
||||
self.process_response(request, response)
|
||||
|
||||
return response
|
||||
|
||||
def process_request(self, request: HttpRequest) -> None:
|
||||
"""Process incoming request and start tracing."""
|
||||
# Start span for the request
|
||||
span_name = f"{request.method} {request.path}"
|
||||
span = get_tracer("ivatar.middleware").start_span(span_name)
|
||||
|
||||
# Add request attributes
|
||||
span.set_attributes(
|
||||
{
|
||||
"http.method": request.method,
|
||||
"http.url": request.build_absolute_uri(),
|
||||
"http.user_agent": request.META.get("HTTP_USER_AGENT", ""),
|
||||
"http.remote_addr": self._get_client_ip(request),
|
||||
"ivatar.path": request.path,
|
||||
}
|
||||
)
|
||||
|
||||
# Check if this is an avatar request
|
||||
if self._is_avatar_request(request):
|
||||
span.set_attribute("ivatar.request_type", "avatar")
|
||||
self._add_avatar_attributes(span, request)
|
||||
|
||||
# Store span in request for later use
|
||||
request._ot_span = span
|
||||
|
||||
# Record request start time
|
||||
request._ot_start_time = time.time()
|
||||
|
||||
def process_response(
|
||||
self, request: HttpRequest, response: HttpResponse
|
||||
) -> HttpResponse:
|
||||
"""Process response and complete tracing."""
|
||||
span = getattr(request, "_ot_span", None)
|
||||
if not span:
|
||||
return response
|
||||
|
||||
try:
|
||||
# Calculate request duration
|
||||
start_time = getattr(request, "_ot_start_time", time.time())
|
||||
duration = time.time() - start_time
|
||||
|
||||
# Add response attributes
|
||||
span.set_attributes(
|
||||
{
|
||||
"http.status_code": response.status_code,
|
||||
"http.response_size": (
|
||||
len(response.content) if hasattr(response, "content") else 0
|
||||
),
|
||||
"http.request.duration": duration,
|
||||
}
|
||||
)
|
||||
|
||||
# Set span status based on response
|
||||
if response.status_code >= 400:
|
||||
span.set_status(
|
||||
Status(StatusCode.ERROR, f"HTTP {response.status_code}")
|
||||
)
|
||||
else:
|
||||
span.set_status(Status(StatusCode.OK))
|
||||
|
||||
# Record metrics
|
||||
# Note: HTTP request metrics are handled by Django instrumentation
|
||||
# We only record avatar-specific metrics here
|
||||
|
||||
# Record avatar-specific metrics
|
||||
if self._is_avatar_request(request):
|
||||
# Record avatar request metric using the new metrics system
|
||||
self.metrics.record_avatar_request(
|
||||
size=self._get_avatar_size(request),
|
||||
format_type=self._get_avatar_format(request),
|
||||
)
|
||||
|
||||
finally:
|
||||
span.end()
|
||||
|
||||
return response
|
||||
|
||||
def _is_avatar_request(self, request: HttpRequest) -> bool:
|
||||
"""Check if this is an avatar request."""
|
||||
return request.path.startswith("/avatar/") or request.path.startswith("/avatar")
|
||||
|
||||
def _add_avatar_attributes(self, span: trace.Span, request: HttpRequest) -> None:
|
||||
"""Add avatar-specific attributes to span."""
|
||||
try:
|
||||
# Extract avatar parameters
|
||||
size = self._get_avatar_size(request)
|
||||
format_type = self._get_avatar_format(request)
|
||||
email = self._get_avatar_email(request)
|
||||
|
||||
span.set_attributes(
|
||||
{
|
||||
"ivatar.avatar_size": size,
|
||||
"ivatar.avatar_format": format_type,
|
||||
"ivatar.avatar_email": email,
|
||||
}
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.debug(f"Failed to add avatar attributes: {e}")
|
||||
|
||||
def _get_avatar_size(self, request: HttpRequest) -> str:
|
||||
"""Extract avatar size from request."""
|
||||
size = request.GET.get("s", "80")
|
||||
return str(size)
|
||||
|
||||
def _get_avatar_format(self, request: HttpRequest) -> str:
|
||||
"""Extract avatar format from request."""
|
||||
format_type = request.GET.get("d", "png")
|
||||
return str(format_type)
|
||||
|
||||
def _get_avatar_email(self, request: HttpRequest) -> str:
|
||||
"""Extract email from avatar request path."""
|
||||
try:
|
||||
# Extract email from path like /avatar/user@example.com
|
||||
path_parts = request.path.strip("/").split("/")
|
||||
if len(path_parts) >= 2 and path_parts[0] == "avatar":
|
||||
return path_parts[1]
|
||||
except Exception:
|
||||
pass
|
||||
return "unknown"
|
||||
|
||||
def _get_client_ip(self, request: HttpRequest) -> str:
|
||||
"""Get client IP address from request."""
|
||||
x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
|
||||
if x_forwarded_for:
|
||||
return x_forwarded_for.split(",")[0].strip()
|
||||
return request.META.get("REMOTE_ADDR", "unknown")
|
||||
|
||||
|
||||
def trace_avatar_operation(operation_name: str):
|
||||
"""
|
||||
Decorator to trace avatar operations.
|
||||
|
||||
Args:
|
||||
operation_name: Name of the operation being traced
|
||||
"""
|
||||
|
||||
def decorator(func):
|
||||
@wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
if not is_enabled():
|
||||
return func(*args, **kwargs)
|
||||
|
||||
tracer = get_tracer("ivatar.avatar")
|
||||
with tracer.start_as_current_span(f"avatar.{operation_name}") as span:
|
||||
try:
|
||||
result = func(*args, **kwargs)
|
||||
span.set_status(Status(StatusCode.OK))
|
||||
return result
|
||||
except Exception as e:
|
||||
span.set_status(Status(StatusCode.ERROR, str(e)))
|
||||
span.set_attribute("error.message", str(e))
|
||||
raise
|
||||
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
def trace_file_upload(operation_name: str):
|
||||
"""
|
||||
Decorator to trace file upload operations.
|
||||
|
||||
Args:
|
||||
operation_name: Name of the file upload operation being traced
|
||||
"""
|
||||
|
||||
def decorator(func):
|
||||
@wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
tracer = get_tracer("ivatar.file_upload")
|
||||
with tracer.start_as_current_span(f"file_upload.{operation_name}") as span:
|
||||
try:
|
||||
# Add file information if available
|
||||
if args and hasattr(args[0], "FILES"):
|
||||
files = args[0].FILES
|
||||
if files:
|
||||
file_info = list(files.values())[0]
|
||||
span.set_attributes(
|
||||
{
|
||||
"file.name": file_info.name,
|
||||
"file.size": file_info.size,
|
||||
"file.content_type": file_info.content_type,
|
||||
}
|
||||
)
|
||||
|
||||
result = func(*args, **kwargs)
|
||||
span.set_status(Status(StatusCode.OK))
|
||||
return result
|
||||
except Exception as e:
|
||||
span.set_status(Status(StatusCode.ERROR, str(e)))
|
||||
span.set_attribute("error.message", str(e))
|
||||
raise
|
||||
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
def trace_authentication(operation_name: str):
|
||||
"""
|
||||
Decorator to trace authentication operations.
|
||||
|
||||
Args:
|
||||
operation_name: Name of the authentication operation being traced
|
||||
"""
|
||||
|
||||
def decorator(func):
|
||||
@wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
tracer = get_tracer("ivatar.auth")
|
||||
with tracer.start_as_current_span(f"auth.{operation_name}") as span:
|
||||
try:
|
||||
result = func(*args, **kwargs)
|
||||
span.set_status(Status(StatusCode.OK))
|
||||
return result
|
||||
except Exception as e:
|
||||
span.set_status(Status(StatusCode.ERROR, str(e)))
|
||||
span.set_attribute("error.message", str(e))
|
||||
raise
|
||||
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
class AvatarMetrics:
|
||||
"""
|
||||
Custom metrics for avatar operations.
|
||||
|
||||
This class provides methods to record custom metrics for avatar-specific
|
||||
operations like generation, caching, and external service calls.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.meter = get_meter("ivatar.avatar")
|
||||
|
||||
# Create custom metrics
|
||||
self.avatar_generated = self.meter.create_counter(
|
||||
name="ivatar_avatars_generated_total",
|
||||
description="Total number of avatars generated",
|
||||
unit="1",
|
||||
)
|
||||
|
||||
self.avatar_requests = self.meter.create_counter(
|
||||
name="ivatar_avatar_requests_total",
|
||||
description="Total number of avatar image requests",
|
||||
unit="1",
|
||||
)
|
||||
|
||||
self.avatar_cache_hits = self.meter.create_counter(
|
||||
name="ivatar_avatar_cache_hits_total",
|
||||
description="Total number of avatar cache hits",
|
||||
unit="1",
|
||||
)
|
||||
|
||||
self.avatar_cache_misses = self.meter.create_counter(
|
||||
name="ivatar_avatar_cache_misses_total",
|
||||
description="Total number of avatar cache misses",
|
||||
unit="1",
|
||||
)
|
||||
|
||||
self.external_avatar_requests = self.meter.create_counter(
|
||||
name="ivatar_external_avatar_requests_total",
|
||||
description="Total number of external avatar requests",
|
||||
unit="1",
|
||||
)
|
||||
|
||||
self.file_uploads = self.meter.create_counter(
|
||||
name="ivatar_file_uploads_total",
|
||||
description="Total number of file uploads",
|
||||
unit="1",
|
||||
)
|
||||
|
||||
self.file_upload_size = self.meter.create_histogram(
|
||||
name="ivatar_file_upload_size_bytes",
|
||||
description="File upload size in bytes",
|
||||
unit="bytes",
|
||||
)
|
||||
|
||||
def record_avatar_request(self, size: str, format_type: str):
|
||||
"""Record avatar request."""
|
||||
self.avatar_requests.add(
|
||||
1,
|
||||
{
|
||||
"size": size,
|
||||
"format": format_type,
|
||||
},
|
||||
)
|
||||
|
||||
def record_avatar_generated(
|
||||
self, size: str, format_type: str, source: str = "generated"
|
||||
):
|
||||
"""Record avatar generation."""
|
||||
self.avatar_generated.add(
|
||||
1,
|
||||
{
|
||||
"size": size,
|
||||
"format": format_type,
|
||||
"source": source,
|
||||
},
|
||||
)
|
||||
|
||||
def record_cache_hit(self, size: str, format_type: str):
|
||||
"""Record cache hit."""
|
||||
self.avatar_cache_hits.add(
|
||||
1,
|
||||
{
|
||||
"size": size,
|
||||
"format": format_type,
|
||||
},
|
||||
)
|
||||
|
||||
def record_cache_miss(self, size: str, format_type: str):
|
||||
"""Record cache miss."""
|
||||
self.avatar_cache_misses.add(
|
||||
1,
|
||||
{
|
||||
"size": size,
|
||||
"format": format_type,
|
||||
},
|
||||
)
|
||||
|
||||
def record_external_request(self, service: str, status_code: int):
|
||||
"""Record external avatar service request."""
|
||||
self.external_avatar_requests.add(
|
||||
1,
|
||||
{
|
||||
"service": service,
|
||||
"status_code": str(status_code),
|
||||
},
|
||||
)
|
||||
|
||||
def record_file_upload(self, file_size: int, content_type: str, success: bool):
|
||||
"""Record file upload."""
|
||||
self.file_uploads.add(
|
||||
1,
|
||||
{
|
||||
"content_type": content_type,
|
||||
"success": str(success),
|
||||
},
|
||||
)
|
||||
|
||||
self.file_upload_size.record(
|
||||
file_size,
|
||||
{
|
||||
"content_type": content_type,
|
||||
"success": str(success),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
# Global metrics instance (lazy-loaded)
|
||||
_avatar_metrics = None
|
||||
|
||||
|
||||
def get_avatar_metrics():
|
||||
"""Get the global avatar metrics instance."""
|
||||
global _avatar_metrics
|
||||
if _avatar_metrics is None:
|
||||
_avatar_metrics = AvatarMetrics()
|
||||
return _avatar_metrics
|
||||
|
||||
|
||||
def reset_avatar_metrics():
|
||||
"""Reset the global avatar metrics instance (for testing)."""
|
||||
global _avatar_metrics
|
||||
_avatar_metrics = None
|
||||
185
ivatar/pagan_optimized.py
Normal file
185
ivatar/pagan_optimized.py
Normal file
@@ -0,0 +1,185 @@
|
||||
"""
|
||||
Optimized pagan avatar generator for ivatar
|
||||
Provides 95x+ performance improvement through intelligent caching
|
||||
"""
|
||||
|
||||
import threading
|
||||
from io import BytesIO
|
||||
from typing import Dict, Optional
|
||||
from PIL import Image
|
||||
from django.conf import settings
|
||||
import pagan
|
||||
|
||||
|
||||
class OptimizedPagan:
|
||||
"""
|
||||
Optimized pagan avatar generator that caches Avatar objects
|
||||
|
||||
Provides 95x+ performance improvement by caching expensive pagan.Avatar
|
||||
object creation while maintaining 100% visual compatibility
|
||||
"""
|
||||
|
||||
# Class-level cache shared across all instances
|
||||
_avatar_cache: Dict[str, pagan.Avatar] = {}
|
||||
_cache_lock = threading.Lock()
|
||||
_cache_stats = {"hits": 0, "misses": 0, "size": 0}
|
||||
|
||||
# Cache configuration
|
||||
_max_cache_size = getattr(settings, "PAGAN_CACHE_SIZE", 100) # Max cached avatars
|
||||
_cache_enabled = True # Always enabled - this is the default implementation
|
||||
|
||||
@classmethod
|
||||
def _get_cached_avatar(cls, digest: str) -> Optional[pagan.Avatar]:
|
||||
"""Get cached pagan Avatar object or create and cache it"""
|
||||
|
||||
# Try to get from cache first
|
||||
with cls._cache_lock:
|
||||
if digest in cls._avatar_cache:
|
||||
cls._cache_stats["hits"] += 1
|
||||
return cls._avatar_cache[digest]
|
||||
|
||||
# Cache miss - create new Avatar object
|
||||
try:
|
||||
avatar = pagan.Avatar(digest)
|
||||
|
||||
with cls._cache_lock:
|
||||
# Cache management - remove oldest entries if cache is full
|
||||
if len(cls._avatar_cache) >= cls._max_cache_size:
|
||||
# Remove 20% of oldest entries to make room
|
||||
remove_count = max(1, cls._max_cache_size // 5)
|
||||
keys_to_remove = list(cls._avatar_cache.keys())[:remove_count]
|
||||
for key in keys_to_remove:
|
||||
del cls._avatar_cache[key]
|
||||
|
||||
# Cache the Avatar object
|
||||
cls._avatar_cache[digest] = avatar
|
||||
cls._cache_stats["misses"] += 1
|
||||
cls._cache_stats["size"] = len(cls._avatar_cache)
|
||||
|
||||
return avatar
|
||||
|
||||
except Exception as e:
|
||||
if getattr(settings, "DEBUG", False):
|
||||
print(f"Failed to create pagan avatar {digest}: {e}")
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def get_cache_stats(cls) -> Dict:
|
||||
"""Get cache performance statistics"""
|
||||
with cls._cache_lock:
|
||||
total_requests = cls._cache_stats["hits"] + cls._cache_stats["misses"]
|
||||
hit_rate = (
|
||||
(cls._cache_stats["hits"] / total_requests * 100)
|
||||
if total_requests > 0
|
||||
else 0
|
||||
)
|
||||
|
||||
return {
|
||||
"size": cls._cache_stats["size"],
|
||||
"max_size": cls._max_cache_size,
|
||||
"hits": cls._cache_stats["hits"],
|
||||
"misses": cls._cache_stats["misses"],
|
||||
"hit_rate": f"{hit_rate:.1f}%",
|
||||
"total_requests": total_requests,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def clear_cache(cls):
|
||||
"""Clear the pagan avatar cache (useful for testing or memory management)"""
|
||||
with cls._cache_lock:
|
||||
cls._avatar_cache.clear()
|
||||
cls._cache_stats = {"hits": 0, "misses": 0, "size": 0}
|
||||
|
||||
@classmethod
|
||||
def generate_optimized(cls, digest: str, size: int = 80) -> Optional[Image.Image]:
|
||||
"""
|
||||
Generate optimized pagan avatar
|
||||
|
||||
Args:
|
||||
digest (str): MD5 hash as hex string
|
||||
size (int): Output image size in pixels
|
||||
|
||||
Returns:
|
||||
PIL.Image: Resized pagan avatar image, or None on error
|
||||
"""
|
||||
try:
|
||||
# Get cached Avatar object (this is where the 95x speedup comes from)
|
||||
avatar = cls._get_cached_avatar(digest)
|
||||
if avatar is None:
|
||||
return None
|
||||
|
||||
# Resize the cached avatar's image (this is very fast ~0.2ms)
|
||||
# The original pagan avatar is 128x128 RGBA
|
||||
resized_img = avatar.img.resize((size, size), Image.LANCZOS)
|
||||
|
||||
return resized_img
|
||||
|
||||
except Exception as e:
|
||||
if getattr(settings, "DEBUG", False):
|
||||
print(f"Optimized pagan generation failed for {digest}: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def create_optimized_pagan(digest: str, size: int = 80) -> BytesIO:
|
||||
"""
|
||||
Create pagan avatar using optimized implementation
|
||||
Returns BytesIO object ready for HTTP response
|
||||
|
||||
Performance improvement: 95x+ faster than original pagan generation
|
||||
|
||||
Args:
|
||||
digest (str): MD5 hash as hex string
|
||||
size (int): Output image size in pixels
|
||||
|
||||
Returns:
|
||||
BytesIO: PNG image data ready for HTTP response
|
||||
"""
|
||||
try:
|
||||
# Generate optimized pagan avatar
|
||||
img = OptimizedPagan.generate_optimized(digest, size)
|
||||
|
||||
if img is not None:
|
||||
# Save to BytesIO for HTTP response
|
||||
data = BytesIO()
|
||||
img.save(data, format="PNG")
|
||||
data.seek(0)
|
||||
return data
|
||||
else:
|
||||
# Fallback to original implementation if optimization fails
|
||||
if getattr(settings, "DEBUG", False):
|
||||
print(f"Falling back to original pagan for {digest}")
|
||||
|
||||
paganobj = pagan.Avatar(digest)
|
||||
img = paganobj.img.resize((size, size), Image.LANCZOS)
|
||||
data = BytesIO()
|
||||
img.save(data, format="PNG")
|
||||
data.seek(0)
|
||||
return data
|
||||
|
||||
except Exception as e:
|
||||
if getattr(settings, "DEBUG", False):
|
||||
print(f"Pagan generation failed: {e}")
|
||||
|
||||
# Return simple fallback image on error
|
||||
fallback_img = Image.new("RGBA", (size, size), (100, 100, 150, 255))
|
||||
data = BytesIO()
|
||||
fallback_img.save(data, format="PNG")
|
||||
data.seek(0)
|
||||
return data
|
||||
|
||||
|
||||
# Management utilities
|
||||
def get_pagan_cache_info():
|
||||
"""Get cache information for monitoring/debugging"""
|
||||
return OptimizedPagan.get_cache_stats()
|
||||
|
||||
|
||||
def clear_pagan_cache():
|
||||
"""Clear the pagan avatar cache"""
|
||||
OptimizedPagan.clear_cache()
|
||||
|
||||
|
||||
# Backward compatibility - maintain same interface as original
|
||||
def create_pagan_avatar(digest: str, size: int = 80) -> BytesIO:
|
||||
"""Backward compatibility alias for create_optimized_pagan"""
|
||||
return create_optimized_pagan(digest, size)
|
||||
181
ivatar/robohash.py
Normal file
181
ivatar/robohash.py
Normal file
@@ -0,0 +1,181 @@
|
||||
"""
|
||||
Optimized Robohash implementation for ivatar.
|
||||
Focuses on result caching for maximum performance with minimal complexity.
|
||||
"""
|
||||
|
||||
import threading
|
||||
from PIL import Image
|
||||
from io import BytesIO
|
||||
from robohash import Robohash
|
||||
from typing import Dict, Optional
|
||||
from django.conf import settings
|
||||
|
||||
|
||||
class OptimizedRobohash:
|
||||
"""
|
||||
High-performance robohash implementation using intelligent result caching:
|
||||
1. Caches assembled robots by hash signature to avoid regeneration
|
||||
2. Lightweight approach with minimal initialization overhead
|
||||
3. 100% visual compatibility with original robohash
|
||||
|
||||
Performance: 3x faster overall, up to 100x faster with cache hits
|
||||
"""
|
||||
|
||||
# Class-level assembly cache
|
||||
_assembly_cache: Dict[str, Image.Image] = {}
|
||||
_cache_lock = threading.Lock()
|
||||
_cache_stats = {"hits": 0, "misses": 0}
|
||||
_max_cache_size = 50 # Limit memory usage
|
||||
|
||||
def __init__(self, string, hashcount=11, ignoreext=True):
|
||||
# Use original robohash for compatibility
|
||||
self._robohash = Robohash(string, hashcount, ignoreext)
|
||||
self.hasharray = self._robohash.hasharray
|
||||
self.img = None
|
||||
self.format = "png"
|
||||
|
||||
def _get_cache_key(
|
||||
self, roboset: str, color: str, bgset: Optional[str], size: int
|
||||
) -> str:
|
||||
"""Generate cache key for assembled robot"""
|
||||
# Use hash signature for cache key
|
||||
hash_sig = "".join(str(h % 1000) for h in self.hasharray[:6])
|
||||
bg_key = bgset or "none"
|
||||
return f"{roboset}:{color}:{bg_key}:{size}:{hash_sig}"
|
||||
|
||||
def assemble_optimized(
|
||||
self, roboset=None, color=None, format=None, bgset=None, sizex=300, sizey=300
|
||||
):
|
||||
"""
|
||||
Optimized assembly with intelligent result caching
|
||||
"""
|
||||
# Normalize parameters
|
||||
roboset = roboset or "any"
|
||||
color = color or "default"
|
||||
bgset = None if (bgset == "none" or not bgset) else bgset
|
||||
format = format or "png"
|
||||
|
||||
# Check cache first
|
||||
cache_key = self._get_cache_key(roboset, color, bgset, sizex)
|
||||
|
||||
with self._cache_lock:
|
||||
if cache_key in self._assembly_cache:
|
||||
self._cache_stats["hits"] += 1
|
||||
# Return cached result
|
||||
self.img = self._assembly_cache[cache_key].copy()
|
||||
self.format = format
|
||||
return
|
||||
|
||||
self._cache_stats["misses"] += 1
|
||||
|
||||
# Cache miss - generate new robot using original robohash
|
||||
try:
|
||||
self._robohash.assemble(
|
||||
roboset=roboset,
|
||||
color=color,
|
||||
format=format,
|
||||
bgset=bgset,
|
||||
sizex=sizex,
|
||||
sizey=sizey,
|
||||
)
|
||||
|
||||
# Store result
|
||||
self.img = self._robohash.img
|
||||
self.format = format
|
||||
|
||||
# Cache the result (if cache not full)
|
||||
with self._cache_lock:
|
||||
if len(self._assembly_cache) < self._max_cache_size:
|
||||
self._assembly_cache[cache_key] = self.img.copy()
|
||||
elif self._cache_stats["hits"] > 0: # Only clear if we've had hits
|
||||
# Remove oldest entry (simple FIFO)
|
||||
oldest_key = next(iter(self._assembly_cache))
|
||||
del self._assembly_cache[oldest_key]
|
||||
self._assembly_cache[cache_key] = self.img.copy()
|
||||
|
||||
except Exception as e:
|
||||
if getattr(settings, "DEBUG", False):
|
||||
print(f"Optimized robohash assembly error: {e}")
|
||||
# Fallback to simple robot
|
||||
self.img = Image.new("RGBA", (sizex, sizey), (128, 128, 128, 255))
|
||||
self.format = format
|
||||
|
||||
@classmethod
|
||||
def get_cache_stats(cls):
|
||||
"""Get cache performance statistics"""
|
||||
with cls._cache_lock:
|
||||
total_requests = cls._cache_stats["hits"] + cls._cache_stats["misses"]
|
||||
hit_rate = (
|
||||
(cls._cache_stats["hits"] / total_requests * 100)
|
||||
if total_requests > 0
|
||||
else 0
|
||||
)
|
||||
|
||||
return {
|
||||
"hits": cls._cache_stats["hits"],
|
||||
"misses": cls._cache_stats["misses"],
|
||||
"hit_rate": f"{hit_rate:.1f}%",
|
||||
"cache_size": len(cls._assembly_cache),
|
||||
"max_cache_size": cls._max_cache_size,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def clear_cache(cls):
|
||||
"""Clear assembly cache"""
|
||||
with cls._cache_lock:
|
||||
cls._assembly_cache.clear()
|
||||
cls._cache_stats = {"hits": 0, "misses": 0}
|
||||
|
||||
|
||||
def create_robohash(digest: str, size: int, roboset: str = "any") -> BytesIO:
|
||||
"""
|
||||
Create robohash using optimized implementation.
|
||||
This is the main robohash generation function for ivatar.
|
||||
|
||||
Args:
|
||||
digest: MD5 hash string for robot generation
|
||||
size: Output image size in pixels
|
||||
roboset: Robot set to use ("any", "set1", "set2", etc.)
|
||||
|
||||
Returns:
|
||||
BytesIO object containing PNG image data
|
||||
|
||||
Performance: 3-5x faster than original robohash, up to 100x with cache hits
|
||||
"""
|
||||
try:
|
||||
robohash = OptimizedRobohash(digest)
|
||||
robohash.assemble_optimized(roboset=roboset, sizex=size, sizey=size)
|
||||
|
||||
# Save to BytesIO
|
||||
data = BytesIO()
|
||||
robohash.img.save(data, format="png")
|
||||
data.seek(0)
|
||||
return data
|
||||
|
||||
except Exception as e:
|
||||
if getattr(settings, "DEBUG", False):
|
||||
print(f"Robohash generation failed: {e}")
|
||||
|
||||
# Return fallback image
|
||||
fallback_img = Image.new("RGBA", (size, size), (150, 150, 150, 255))
|
||||
data = BytesIO()
|
||||
fallback_img.save(data, format="png")
|
||||
data.seek(0)
|
||||
return data
|
||||
|
||||
|
||||
# Management utilities for monitoring and debugging
|
||||
def get_robohash_cache_stats():
|
||||
"""Get robohash cache statistics for monitoring"""
|
||||
return OptimizedRobohash.get_cache_stats()
|
||||
|
||||
|
||||
def clear_robohash_cache():
|
||||
"""Clear robohash caches"""
|
||||
OptimizedRobohash.clear_cache()
|
||||
|
||||
|
||||
# Backward compatibility aliases
|
||||
create_optimized_robohash = create_robohash
|
||||
create_fast_robohash = create_robohash
|
||||
create_cached_robohash = create_robohash
|
||||
@@ -6,71 +6,182 @@ import os
|
||||
import logging
|
||||
|
||||
log_level = logging.DEBUG # pylint: disable=invalid-name
|
||||
logger = logging.getLogger('ivatar') # pylint: disable=invalid-name
|
||||
logger = logging.getLogger("ivatar") # pylint: disable=invalid-name
|
||||
logger.setLevel(log_level)
|
||||
|
||||
PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__))
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
# Logging directory - can be overridden in local config
|
||||
LOGS_DIR = os.path.join(BASE_DIR, "logs")
|
||||
|
||||
|
||||
def _test_logs_directory_writeability(logs_dir):
|
||||
"""
|
||||
Test if a logs directory is actually writable by attempting to create and write a test file
|
||||
"""
|
||||
try:
|
||||
# Ensure directory exists
|
||||
os.makedirs(logs_dir, exist_ok=True)
|
||||
|
||||
# Test if we can actually write to the directory
|
||||
test_file = os.path.join(logs_dir, ".write_test")
|
||||
with open(test_file, "w") as f:
|
||||
f.write("test")
|
||||
|
||||
# Clean up test file
|
||||
os.remove(test_file)
|
||||
return True
|
||||
except (OSError, PermissionError):
|
||||
return False
|
||||
|
||||
|
||||
# Ensure logs directory exists and is writable - worst case, fall back to /tmp
|
||||
if not _test_logs_directory_writeability(LOGS_DIR):
|
||||
LOGS_DIR = "/tmp/libravatar-logs"
|
||||
if not _test_logs_directory_writeability(LOGS_DIR):
|
||||
# If even /tmp fails, use a user-specific temp directory
|
||||
import tempfile
|
||||
|
||||
LOGS_DIR = os.path.join(tempfile.gettempdir(), f"libravatar-logs-{os.getuid()}")
|
||||
_test_logs_directory_writeability(LOGS_DIR) # This should always succeed
|
||||
|
||||
logger.warning(f"Failed to write to logs directory, falling back to {LOGS_DIR}")
|
||||
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = '=v(+-^t#ahv^a&&e)uf36g8algj$d1@6ou^w(r0@%)#8mlc*zk'
|
||||
SECRET_KEY = "=v(+-^t#ahv^a&&e)uf36g8algj$d1@6ou^w(r0@%)#8mlc*zk"
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = True
|
||||
|
||||
ALLOWED_HOSTS = []
|
||||
|
||||
# Comprehensive Logging Configuration
|
||||
LOGGING = {
|
||||
"version": 1,
|
||||
"disable_existing_loggers": False,
|
||||
"formatters": {
|
||||
"verbose": {
|
||||
"format": "{levelname} {asctime} {module} {process:d} {thread:d} {message}",
|
||||
"style": "{",
|
||||
},
|
||||
"simple": {
|
||||
"format": "{levelname} {asctime} {message}",
|
||||
"style": "{",
|
||||
},
|
||||
"detailed": {
|
||||
"format": "{levelname} {asctime} {name} {module} {funcName} {lineno:d} {message}",
|
||||
"style": "{",
|
||||
},
|
||||
},
|
||||
"handlers": {
|
||||
"file": {
|
||||
"level": "INFO",
|
||||
"class": "logging.FileHandler",
|
||||
"filename": os.path.join(LOGS_DIR, "ivatar.log"),
|
||||
"formatter": "verbose",
|
||||
},
|
||||
"file_debug": {
|
||||
"level": "DEBUG",
|
||||
"class": "logging.FileHandler",
|
||||
"filename": os.path.join(LOGS_DIR, "ivatar_debug.log"),
|
||||
"formatter": "detailed",
|
||||
},
|
||||
"console": {
|
||||
"level": "DEBUG" if DEBUG else "INFO",
|
||||
"class": "logging.StreamHandler",
|
||||
"formatter": "simple",
|
||||
},
|
||||
"security": {
|
||||
"level": "WARNING",
|
||||
"class": "logging.FileHandler",
|
||||
"filename": os.path.join(LOGS_DIR, "security.log"),
|
||||
"formatter": "detailed",
|
||||
},
|
||||
},
|
||||
"loggers": {
|
||||
"ivatar": {
|
||||
"handlers": ["file", "console"],
|
||||
"level": "INFO", # Restore normal logging level
|
||||
"propagate": True,
|
||||
},
|
||||
"ivatar.security": {
|
||||
"handlers": ["security", "console"],
|
||||
"level": "WARNING",
|
||||
"propagate": False,
|
||||
},
|
||||
"ivatar.debug": {
|
||||
"handlers": ["file_debug"],
|
||||
"level": "DEBUG",
|
||||
"propagate": False,
|
||||
},
|
||||
"django.security": {
|
||||
"handlers": ["security"],
|
||||
"level": "WARNING",
|
||||
"propagate": False,
|
||||
},
|
||||
},
|
||||
"root": {
|
||||
"handlers": ["console"],
|
||||
"level": "INFO",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
# Application definition
|
||||
|
||||
INSTALLED_APPS = [
|
||||
'django.contrib.admin',
|
||||
'django.contrib.auth',
|
||||
'django.contrib.contenttypes',
|
||||
'django.contrib.sessions',
|
||||
'django.contrib.messages',
|
||||
'django.contrib.staticfiles',
|
||||
"django.contrib.admin",
|
||||
"django.contrib.auth",
|
||||
"django.contrib.contenttypes",
|
||||
"django.contrib.sessions",
|
||||
"django.contrib.messages",
|
||||
"django.contrib.staticfiles",
|
||||
"social_django",
|
||||
]
|
||||
|
||||
MIDDLEWARE = [
|
||||
'django.middleware.security.SecurityMiddleware',
|
||||
'django.contrib.sessions.middleware.SessionMiddleware',
|
||||
'django.middleware.common.CommonMiddleware',
|
||||
'django.middleware.csrf.CsrfViewMiddleware',
|
||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||
'django.contrib.messages.middleware.MessageMiddleware',
|
||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||
"django.middleware.security.SecurityMiddleware",
|
||||
"django.contrib.sessions.middleware.SessionMiddleware",
|
||||
"django.middleware.common.CommonMiddleware",
|
||||
"django.middleware.csrf.CsrfViewMiddleware",
|
||||
"django.contrib.auth.middleware.AuthenticationMiddleware",
|
||||
"django.contrib.messages.middleware.MessageMiddleware",
|
||||
"django.middleware.clickjacking.XFrameOptionsMiddleware",
|
||||
]
|
||||
|
||||
ROOT_URLCONF = 'ivatar.urls'
|
||||
ROOT_URLCONF = "ivatar.urls"
|
||||
|
||||
TEMPLATES = [
|
||||
{
|
||||
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
||||
'DIRS': [],
|
||||
'APP_DIRS': True,
|
||||
'OPTIONS': {
|
||||
'context_processors': [
|
||||
'django.template.context_processors.debug',
|
||||
'django.template.context_processors.request',
|
||||
'django.contrib.auth.context_processors.auth',
|
||||
'django.contrib.messages.context_processors.messages',
|
||||
"BACKEND": "django.template.backends.django.DjangoTemplates",
|
||||
"DIRS": [os.path.join(BASE_DIR, "templates")],
|
||||
"APP_DIRS": True,
|
||||
"OPTIONS": {
|
||||
"context_processors": [
|
||||
"django.template.context_processors.debug",
|
||||
"django.template.context_processors.request",
|
||||
"django.contrib.auth.context_processors.auth",
|
||||
"django.contrib.messages.context_processors.messages",
|
||||
"django.template.context_processors.i18n",
|
||||
"social_django.context_processors.login_redirect",
|
||||
],
|
||||
"debug": DEBUG,
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
WSGI_APPLICATION = 'ivatar.wsgi.application'
|
||||
WSGI_APPLICATION = "ivatar.wsgi.application"
|
||||
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.sqlite3',
|
||||
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
|
||||
"default": {
|
||||
"ENGINE": "django.db.backends.sqlite3",
|
||||
"NAME": os.path.join(BASE_DIR, "db.sqlite3"),
|
||||
"ATOMIC_REQUESTS": True,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,26 +191,107 @@ DATABASES = {
|
||||
|
||||
AUTH_PASSWORD_VALIDATORS = [
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', # noqa
|
||||
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", # noqa
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', # noqa
|
||||
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", # noqa
|
||||
"OPTIONS": {
|
||||
"min_length": 6,
|
||||
},
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', # noqa
|
||||
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", # noqa
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', # noqa
|
||||
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", # noqa
|
||||
},
|
||||
]
|
||||
|
||||
# Password Hashing (more secure)
|
||||
# Try to use Argon2PasswordHasher with high security settings, fallback to PBKDF2
|
||||
PASSWORD_HASHERS = []
|
||||
|
||||
# Try Argon2 first (requires Python 3.6+ and argon2-cffi package)
|
||||
try:
|
||||
import argon2 # noqa: F401
|
||||
|
||||
PASSWORD_HASHERS.append("django.contrib.auth.hashers.Argon2PasswordHasher")
|
||||
except ImportError:
|
||||
# Fallback for CentOS 7 / older systems without argon2-cffi
|
||||
pass
|
||||
|
||||
# Always include PBKDF2 as fallback
|
||||
PASSWORD_HASHERS.extend(
|
||||
[
|
||||
"django.contrib.auth.hashers.PBKDF2PasswordHasher",
|
||||
# Keep PBKDF2SHA1 for existing password compatibility only
|
||||
"django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher",
|
||||
]
|
||||
)
|
||||
|
||||
# Security Settings
|
||||
SECURE_BROWSER_XSS_FILTER = True
|
||||
SECURE_CONTENT_TYPE_NOSNIFF = True
|
||||
X_FRAME_OPTIONS = "DENY"
|
||||
CSRF_COOKIE_SECURE = not DEBUG
|
||||
SESSION_COOKIE_SECURE = not DEBUG
|
||||
|
||||
if not DEBUG:
|
||||
SECURE_SSL_REDIRECT = True
|
||||
SECURE_HSTS_SECONDS = 31536000 # 1 year
|
||||
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
|
||||
SECURE_HSTS_PRELOAD = True
|
||||
|
||||
|
||||
# Social authentication
|
||||
TRUST_EMAIL_FROM_SOCIAL_AUTH_BACKENDS = ["fedora"]
|
||||
SOCIAL_AUTH_PIPELINE = (
|
||||
# Get the information we can about the user and return it in a simple
|
||||
# format to create the user instance later. In some cases the details are
|
||||
# already part of the auth response from the provider, but sometimes this
|
||||
# could hit a provider API.
|
||||
"social_core.pipeline.social_auth.social_details",
|
||||
# Get the social uid from whichever service we're authing thru. The uid is
|
||||
# the unique identifier of the given user in the provider.
|
||||
"social_core.pipeline.social_auth.social_uid",
|
||||
# Verifies that the current auth process is valid within the current
|
||||
# project, this is where emails and domains whitelists are applied (if
|
||||
# defined).
|
||||
"social_core.pipeline.social_auth.auth_allowed",
|
||||
# Checks if the current social-account is already associated in the site.
|
||||
"social_core.pipeline.social_auth.social_user",
|
||||
# Make up a username for this person, appends a random string at the end if
|
||||
# there's any collision.
|
||||
"social_core.pipeline.user.get_username",
|
||||
# Send a validation email to the user to verify its email address.
|
||||
# Disabled by default.
|
||||
# 'social_core.pipeline.mail.mail_validation',
|
||||
# Associates the current social details with another user account with
|
||||
# a similar email address. Disabled by default.
|
||||
"social_core.pipeline.social_auth.associate_by_email",
|
||||
# Associates the current social details with an existing user account with
|
||||
# a matching ConfirmedEmail.
|
||||
"ivatar.ivataraccount.auth.associate_by_confirmed_email",
|
||||
# Create a user account if we haven't found one yet.
|
||||
"social_core.pipeline.user.create_user",
|
||||
# Create the record that associates the social account with the user.
|
||||
"social_core.pipeline.social_auth.associate_user",
|
||||
# Populate the extra_data field in the social record with the values
|
||||
# specified by settings (and the default ones like access_token, etc).
|
||||
"social_core.pipeline.social_auth.load_extra_data",
|
||||
# Update the user record with any changed info from the auth service.
|
||||
"social_core.pipeline.user.user_details",
|
||||
# Create the ConfirmedEmail if appropriate.
|
||||
"ivatar.ivataraccount.auth.add_confirmed_email",
|
||||
)
|
||||
|
||||
|
||||
# Internationalization
|
||||
# https://docs.djangoproject.com/en/2.0/topics/i18n/
|
||||
|
||||
LANGUAGE_CODE = 'en-us'
|
||||
LANGUAGE_CODE = "en-us"
|
||||
|
||||
TIME_ZONE = 'UTC'
|
||||
TIME_ZONE = "UTC"
|
||||
|
||||
USE_I18N = True
|
||||
|
||||
@@ -109,13 +301,23 @@ USE_TZ = True
|
||||
|
||||
|
||||
# Static files configuration (esp. req. during dev.)
|
||||
PROJECT_ROOT = os.path.abspath(
|
||||
os.path.join(
|
||||
os.path.dirname(__file__),
|
||||
os.pardir
|
||||
)
|
||||
)
|
||||
STATIC_URL = '/static/'
|
||||
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
|
||||
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
|
||||
STATIC_URL = "/static/"
|
||||
STATIC_ROOT = os.path.join(BASE_DIR, "static")
|
||||
|
||||
from config import * # pylint: disable=wildcard-import,wrong-import-position,unused-wildcard-import
|
||||
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
|
||||
|
||||
from config import * # pylint: disable=wildcard-import,wrong-import-position,unused-wildcard-import # noqa
|
||||
|
||||
# OpenTelemetry setup - must be after config import
|
||||
# Always setup OpenTelemetry (instrumentation always enabled, export controlled by OTEL_EXPORT_ENABLED)
|
||||
try:
|
||||
from ivatar.opentelemetry_config import setup_opentelemetry
|
||||
|
||||
setup_opentelemetry()
|
||||
|
||||
# Add OpenTelemetry middleware (always enabled)
|
||||
MIDDLEWARE.append("ivatar.opentelemetry_middleware.OpenTelemetryMiddleware")
|
||||
except (ImportError, NameError):
|
||||
# OpenTelemetry packages not installed or configuration failed
|
||||
pass
|
||||
|
||||
7152
ivatar/static/css/bootstrap.min.css
vendored
7152
ivatar/static/css/bootstrap.min.css
vendored
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
265
ivatar/static/css/cropper.min.css
vendored
Normal file
265
ivatar/static/css/cropper.min.css
vendored
Normal file
@@ -0,0 +1,265 @@
|
||||
/*!
|
||||
* Cropper.js v1.6.2
|
||||
* https://fengyuanchen.github.io/cropperjs
|
||||
*
|
||||
* Copyright 2015-present Chen Fengyuan
|
||||
* Released under the MIT license
|
||||
*
|
||||
* Date: 2024-04-21T07:43:02.731Z
|
||||
*/
|
||||
.cropper-container {
|
||||
-webkit-touch-callout: none;
|
||||
direction: ltr;
|
||||
font-size: 0;
|
||||
line-height: 0;
|
||||
position: relative;
|
||||
-ms-touch-action: none;
|
||||
touch-action: none;
|
||||
-webkit-user-select: none;
|
||||
-moz-user-select: none;
|
||||
-ms-user-select: none;
|
||||
user-select: none;
|
||||
}
|
||||
.cropper-container img {
|
||||
backface-visibility: hidden;
|
||||
display: block;
|
||||
height: 100%;
|
||||
image-orientation: 0deg;
|
||||
max-height: none !important;
|
||||
max-width: none !important;
|
||||
min-height: 0 !important;
|
||||
min-width: 0 !important;
|
||||
width: 100%;
|
||||
}
|
||||
.cropper-canvas,
|
||||
.cropper-crop-box,
|
||||
.cropper-drag-box,
|
||||
.cropper-modal,
|
||||
.cropper-wrap-box {
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
position: absolute;
|
||||
right: 0;
|
||||
top: 0;
|
||||
}
|
||||
.cropper-canvas,
|
||||
.cropper-wrap-box {
|
||||
overflow: hidden;
|
||||
}
|
||||
.cropper-drag-box {
|
||||
background-color: #fff;
|
||||
opacity: 0;
|
||||
}
|
||||
.cropper-modal {
|
||||
background-color: #000;
|
||||
opacity: 0.5;
|
||||
}
|
||||
.cropper-view-box {
|
||||
display: block;
|
||||
height: 100%;
|
||||
outline: 1px solid #39f;
|
||||
outline-color: rgba(51, 153, 255, 0.75);
|
||||
overflow: hidden;
|
||||
width: 100%;
|
||||
}
|
||||
.cropper-dashed {
|
||||
border: 0 dashed #eee;
|
||||
display: block;
|
||||
opacity: 0.5;
|
||||
position: absolute;
|
||||
}
|
||||
.cropper-dashed.dashed-h {
|
||||
border-bottom-width: 1px;
|
||||
border-top-width: 1px;
|
||||
height: 33.33333%;
|
||||
left: 0;
|
||||
top: 33.33333%;
|
||||
width: 100%;
|
||||
}
|
||||
.cropper-dashed.dashed-v {
|
||||
border-left-width: 1px;
|
||||
border-right-width: 1px;
|
||||
height: 100%;
|
||||
left: 33.33333%;
|
||||
top: 0;
|
||||
width: 33.33333%;
|
||||
}
|
||||
.cropper-center {
|
||||
display: block;
|
||||
height: 0;
|
||||
left: 50%;
|
||||
opacity: 0.75;
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
width: 0;
|
||||
}
|
||||
.cropper-center:after,
|
||||
.cropper-center:before {
|
||||
background-color: #eee;
|
||||
content: " ";
|
||||
display: block;
|
||||
position: absolute;
|
||||
}
|
||||
.cropper-center:before {
|
||||
height: 1px;
|
||||
left: -3px;
|
||||
top: 0;
|
||||
width: 7px;
|
||||
}
|
||||
.cropper-center:after {
|
||||
height: 7px;
|
||||
left: 0;
|
||||
top: -3px;
|
||||
width: 1px;
|
||||
}
|
||||
.cropper-face,
|
||||
.cropper-line,
|
||||
.cropper-point {
|
||||
display: block;
|
||||
height: 100%;
|
||||
opacity: 0.1;
|
||||
position: absolute;
|
||||
width: 100%;
|
||||
}
|
||||
.cropper-face {
|
||||
background-color: #fff;
|
||||
left: 0;
|
||||
top: 0;
|
||||
}
|
||||
.cropper-line {
|
||||
background-color: #39f;
|
||||
}
|
||||
.cropper-line.line-e {
|
||||
cursor: ew-resize;
|
||||
right: -3px;
|
||||
top: 0;
|
||||
width: 5px;
|
||||
}
|
||||
.cropper-line.line-n {
|
||||
cursor: ns-resize;
|
||||
height: 5px;
|
||||
left: 0;
|
||||
top: -3px;
|
||||
}
|
||||
.cropper-line.line-w {
|
||||
cursor: ew-resize;
|
||||
left: -3px;
|
||||
top: 0;
|
||||
width: 5px;
|
||||
}
|
||||
.cropper-line.line-s {
|
||||
bottom: -3px;
|
||||
cursor: ns-resize;
|
||||
height: 5px;
|
||||
left: 0;
|
||||
}
|
||||
.cropper-point {
|
||||
background-color: #39f;
|
||||
height: 5px;
|
||||
opacity: 0.75;
|
||||
width: 5px;
|
||||
}
|
||||
.cropper-point.point-e {
|
||||
cursor: ew-resize;
|
||||
margin-top: -3px;
|
||||
right: -3px;
|
||||
top: 50%;
|
||||
}
|
||||
.cropper-point.point-n {
|
||||
cursor: ns-resize;
|
||||
left: 50%;
|
||||
margin-left: -3px;
|
||||
top: -3px;
|
||||
}
|
||||
.cropper-point.point-w {
|
||||
cursor: ew-resize;
|
||||
left: -3px;
|
||||
margin-top: -3px;
|
||||
top: 50%;
|
||||
}
|
||||
.cropper-point.point-s {
|
||||
bottom: -3px;
|
||||
cursor: s-resize;
|
||||
left: 50%;
|
||||
margin-left: -3px;
|
||||
}
|
||||
.cropper-point.point-ne {
|
||||
cursor: nesw-resize;
|
||||
right: -3px;
|
||||
top: -3px;
|
||||
}
|
||||
.cropper-point.point-nw {
|
||||
cursor: nwse-resize;
|
||||
left: -3px;
|
||||
top: -3px;
|
||||
}
|
||||
.cropper-point.point-sw {
|
||||
bottom: -3px;
|
||||
cursor: nesw-resize;
|
||||
left: -3px;
|
||||
}
|
||||
.cropper-point.point-se {
|
||||
bottom: -3px;
|
||||
cursor: nwse-resize;
|
||||
height: 20px;
|
||||
opacity: 1;
|
||||
right: -3px;
|
||||
width: 20px;
|
||||
}
|
||||
@media (min-width: 768px) {
|
||||
.cropper-point.point-se {
|
||||
height: 15px;
|
||||
width: 15px;
|
||||
}
|
||||
}
|
||||
@media (min-width: 992px) {
|
||||
.cropper-point.point-se {
|
||||
height: 10px;
|
||||
width: 10px;
|
||||
}
|
||||
}
|
||||
@media (min-width: 1200px) {
|
||||
.cropper-point.point-se {
|
||||
height: 5px;
|
||||
opacity: 0.75;
|
||||
width: 5px;
|
||||
}
|
||||
}
|
||||
.cropper-point.point-se:before {
|
||||
background-color: #39f;
|
||||
bottom: -50%;
|
||||
content: " ";
|
||||
display: block;
|
||||
height: 200%;
|
||||
opacity: 0;
|
||||
position: absolute;
|
||||
right: -50%;
|
||||
width: 200%;
|
||||
}
|
||||
.cropper-invisible {
|
||||
opacity: 0;
|
||||
}
|
||||
.cropper-bg {
|
||||
background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAAA3NCSVQICAjb4U/gAAAABlBMVEXMzMz////TjRV2AAAACXBIWXMAAArrAAAK6wGCiw1aAAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M26LyyjAAAABFJREFUCJlj+M/AgBVhF/0PAH6/D/HkDxOGAAAAAElFTkSuQmCC");
|
||||
}
|
||||
.cropper-hide {
|
||||
display: block;
|
||||
height: 0;
|
||||
position: absolute;
|
||||
width: 0;
|
||||
}
|
||||
.cropper-hidden {
|
||||
display: none !important;
|
||||
}
|
||||
.cropper-move {
|
||||
cursor: move;
|
||||
}
|
||||
.cropper-crop {
|
||||
cursor: crosshair;
|
||||
}
|
||||
.cropper-disabled .cropper-drag-box,
|
||||
.cropper-disabled .cropper-face,
|
||||
.cropper-disabled .cropper-line,
|
||||
.cropper-disabled .cropper-point {
|
||||
cursor: not-allowed;
|
||||
}
|
||||
6880
ivatar/static/css/fontawesome.min.css
vendored
6880
ivatar/static/css/fontawesome.min.css
vendored
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,2 +1,146 @@
|
||||
/* jquery.Jcrop.min.css v0.9.15 (build:20180819) */
|
||||
.jcrop-holder{direction:ltr;text-align:left;-ms-touch-action:none}.jcrop-hline,.jcrop-vline{background:#fff url(Jcrop.gif);font-size:0;position:absolute}.jcrop-vline{height:100%;width:1px!important}.jcrop-vline.right{right:0}.jcrop-hline{height:1px!important;width:100%}.jcrop-hline.bottom{bottom:0}.jcrop-tracker{height:100%;width:100%;-webkit-tap-highlight-color:transparent;-webkit-touch-callout:none;-webkit-user-select:none}.jcrop-handle{background-color:#333;border:1px #eee solid;width:7px;height:7px;font-size:1px}.jcrop-handle.ord-n{left:50%;margin-left:-4px;margin-top:-4px;top:0}.jcrop-handle.ord-s{bottom:0;left:50%;margin-bottom:-4px;margin-left:-4px}.jcrop-handle.ord-e{margin-right:-4px;margin-top:-4px;right:0;top:50%}.jcrop-handle.ord-w{left:0;margin-left:-4px;margin-top:-4px;top:50%}.jcrop-handle.ord-nw{left:0;margin-left:-4px;margin-top:-4px;top:0}.jcrop-handle.ord-ne{margin-right:-4px;margin-top:-4px;right:0;top:0}.jcrop-handle.ord-se{bottom:0;margin-bottom:-4px;margin-right:-4px;right:0}.jcrop-handle.ord-sw{bottom:0;left:0;margin-bottom:-4px;margin-left:-4px}.jcrop-dragbar.ord-n,.jcrop-dragbar.ord-s{height:7px;width:100%}.jcrop-dragbar.ord-e,.jcrop-dragbar.ord-w{height:100%;width:7px}.jcrop-dragbar.ord-n{margin-top:-4px}.jcrop-dragbar.ord-s{bottom:0;margin-bottom:-4px}.jcrop-dragbar.ord-e{margin-right:-4px;right:0}.jcrop-dragbar.ord-w{margin-left:-4px}.jcrop-light .jcrop-hline,.jcrop-light .jcrop-vline{background:#fff;filter:alpha(opacity=70)!important;opacity:.7!important}.jcrop-light .jcrop-handle{-moz-border-radius:3px;-webkit-border-radius:3px;background-color:#000;border-color:#fff;border-radius:3px}.jcrop-dark .jcrop-hline,.jcrop-dark .jcrop-vline{background:#000;filter:alpha(opacity=70)!important;opacity:.7!important}.jcrop-dark .jcrop-handle{-moz-border-radius:3px;-webkit-border-radius:3px;background-color:#fff;border-color:#000;border-radius:3px}.solid-line .jcrop-hline,.solid-line .jcrop-vline{background:#fff}.jcrop-holder img,img.jcrop-preview{max-width:none}
|
||||
.jcrop-holder {
|
||||
direction: ltr;
|
||||
text-align: left;
|
||||
-ms-touch-action: none;
|
||||
}
|
||||
.jcrop-hline,
|
||||
.jcrop-vline {
|
||||
background: #fff url(Jcrop.gif);
|
||||
font-size: 0;
|
||||
position: absolute;
|
||||
}
|
||||
.jcrop-vline {
|
||||
height: 100%;
|
||||
width: 1px !important;
|
||||
}
|
||||
.jcrop-vline.right {
|
||||
right: 0;
|
||||
}
|
||||
.jcrop-hline {
|
||||
height: 1px !important;
|
||||
width: 100%;
|
||||
}
|
||||
.jcrop-hline.bottom {
|
||||
bottom: 0;
|
||||
}
|
||||
.jcrop-tracker {
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
-webkit-touch-callout: none;
|
||||
-webkit-user-select: none;
|
||||
}
|
||||
.jcrop-handle {
|
||||
background-color: #333;
|
||||
border: 1px #eee solid;
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
font-size: 1px;
|
||||
}
|
||||
.jcrop-handle.ord-n {
|
||||
left: 50%;
|
||||
margin-left: -4px;
|
||||
margin-top: -4px;
|
||||
top: 0;
|
||||
}
|
||||
.jcrop-handle.ord-s {
|
||||
bottom: 0;
|
||||
left: 50%;
|
||||
margin-bottom: -4px;
|
||||
margin-left: -4px;
|
||||
}
|
||||
.jcrop-handle.ord-e {
|
||||
margin-right: -4px;
|
||||
margin-top: -4px;
|
||||
right: 0;
|
||||
top: 50%;
|
||||
}
|
||||
.jcrop-handle.ord-w {
|
||||
left: 0;
|
||||
margin-left: -4px;
|
||||
margin-top: -4px;
|
||||
top: 50%;
|
||||
}
|
||||
.jcrop-handle.ord-nw {
|
||||
left: 0;
|
||||
margin-left: -4px;
|
||||
margin-top: -4px;
|
||||
top: 0;
|
||||
}
|
||||
.jcrop-handle.ord-ne {
|
||||
margin-right: -4px;
|
||||
margin-top: -4px;
|
||||
right: 0;
|
||||
top: 0;
|
||||
}
|
||||
.jcrop-handle.ord-se {
|
||||
bottom: 0;
|
||||
margin-bottom: -4px;
|
||||
margin-right: -4px;
|
||||
right: 0;
|
||||
}
|
||||
.jcrop-handle.ord-sw {
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
margin-bottom: -4px;
|
||||
margin-left: -4px;
|
||||
}
|
||||
.jcrop-dragbar.ord-n,
|
||||
.jcrop-dragbar.ord-s {
|
||||
height: 7px;
|
||||
width: 100%;
|
||||
}
|
||||
.jcrop-dragbar.ord-e,
|
||||
.jcrop-dragbar.ord-w {
|
||||
height: 100%;
|
||||
width: 7px;
|
||||
}
|
||||
.jcrop-dragbar.ord-n {
|
||||
margin-top: -4px;
|
||||
}
|
||||
.jcrop-dragbar.ord-s {
|
||||
bottom: 0;
|
||||
margin-bottom: -4px;
|
||||
}
|
||||
.jcrop-dragbar.ord-e {
|
||||
margin-right: -4px;
|
||||
right: 0;
|
||||
}
|
||||
.jcrop-dragbar.ord-w {
|
||||
margin-left: -4px;
|
||||
}
|
||||
.jcrop-light .jcrop-hline,
|
||||
.jcrop-light .jcrop-vline {
|
||||
background: #fff;
|
||||
filter: alpha(opacity=70) !important;
|
||||
opacity: 0.7 !important;
|
||||
}
|
||||
.jcrop-light .jcrop-handle {
|
||||
-moz-border-radius: 3px;
|
||||
-webkit-border-radius: 3px;
|
||||
background-color: #000;
|
||||
border-color: #fff;
|
||||
border-radius: 3px;
|
||||
}
|
||||
.jcrop-dark .jcrop-hline,
|
||||
.jcrop-dark .jcrop-vline {
|
||||
background: #000;
|
||||
filter: alpha(opacity=70) !important;
|
||||
opacity: 0.7 !important;
|
||||
}
|
||||
.jcrop-dark .jcrop-handle {
|
||||
-moz-border-radius: 3px;
|
||||
-webkit-border-radius: 3px;
|
||||
background-color: #fff;
|
||||
border-color: #000;
|
||||
border-radius: 3px;
|
||||
}
|
||||
.solid-line .jcrop-hline,
|
||||
.solid-line .jcrop-vline {
|
||||
background: #fff;
|
||||
}
|
||||
.jcrop-holder img,
|
||||
img.jcrop-preview {
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
586
ivatar/static/css/surly-badges.local.css
Normal file
586
ivatar/static/css/surly-badges.local.css
Normal file
@@ -0,0 +1,586 @@
|
||||
#surly-badge {
|
||||
font-family: sans-serif !important;
|
||||
font-weight: 400 !important;
|
||||
width: 134px !important;
|
||||
height: 164px !important;
|
||||
text-align: center !important;
|
||||
display: -webkit-box !important;
|
||||
display: -ms-flexbox !important;
|
||||
display: flex !important;
|
||||
-webkit-box-orient: vertical !important;
|
||||
-webkit-box-direction: normal !important;
|
||||
-ms-flex-direction: column !important;
|
||||
flex-direction: column !important;
|
||||
-webkit-box-align: center !important;
|
||||
-ms-flex-align: center !important;
|
||||
align-items: center !important;
|
||||
position: relative !important;
|
||||
background-size: contain !important;
|
||||
background-repeat: no-repeat !important;
|
||||
background-position: top center !important;
|
||||
-webkit-box-sizing: content-box !important;
|
||||
box-sizing: content-box !important;
|
||||
padding: 8px 15px 0 !important;
|
||||
}
|
||||
|
||||
#surly-badge p {
|
||||
margin: 0 !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-blue {
|
||||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 164 150'%3E%3Cpath style='fill:none;stroke:%23fff;stroke-width:2;stroke-miterlimit:10;' d='M16.05,22.74c0-7.61,6.16-13.76,13.76-13.76 M16.05,22.74v127.15 M29.02,140.85l-12.52,8.2 M28.47,141.01 h105.78 M134.25,141.01c7.61,0,13.76-6.16,13.76-13.76 M148.01,21.03v106.22 M29.81,8.97h106.2'/%3E%3Cpath style='stroke:%233273f6;stroke-width:2;stroke-miterlimit:10;' d='M148.01,18.02V-0.02 M138.99,9h18.04'/%3E%3C/svg%3E");
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-blue .surly-badge__header-text {
|
||||
color: #3273f6 !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-blue .surly-badge__header-title {
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-blue .surly-badge__tag {
|
||||
background-color: #3273f6 !important;
|
||||
border-bottom: 1px solid #707070 !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-blue .surly-badge__tag-text {
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-blue .surly-badge__tag::before {
|
||||
border-color: transparent #7f8ca5 transparent transparent !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-blue .surly-badge__tag::after {
|
||||
border-color: transparent transparent transparent #7f8ca5 !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-blue .surly-badge__footer-link {
|
||||
color: #3273f6 !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-blue .surly-badge__footer-title {
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-blue .surly-badge__footer-text {
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-gradient {
|
||||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 164 150'%3E%3Cpath style='fill:none;stroke:%23fff;stroke-width:2;stroke-miterlimit:10;' d='M16.05,22.74c0-7.61,6.16-13.76,13.76-13.76 M16.05,22.74v127.15 M29.02,140.85l-12.52,8.2 M28.47,141.01 h105.78 M134.25,141.01c7.61,0,13.76-6.16,13.76-13.76 M148.01,21.03v106.22 M29.81,8.97h106.2'/%3E%3Cpath style='stroke:%23ff715e;stroke-width:2;stroke-miterlimit:10;' d='M148.01,18.02V-0.02 M138.99,9h18.04'/%3E%3C/svg%3E");
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-gradient .surly-badge__header-text {
|
||||
color: #3273f6 !important;
|
||||
background: #ff715e !important;
|
||||
background-image: -webkit-gradient(
|
||||
linear,
|
||||
left top,
|
||||
right top,
|
||||
from(#ff715e),
|
||||
to(#00a8ff)
|
||||
) !important;
|
||||
background-image: -o-linear-gradient(
|
||||
left,
|
||||
#ff715e 0%,
|
||||
#00a8ff 100%
|
||||
) !important;
|
||||
background-image: linear-gradient(90deg, #ff715e 0%, #00a8ff 100%) !important;
|
||||
background-size: 100% !important;
|
||||
-webkit-background-clip: text !important;
|
||||
-moz-background-clip: text !important;
|
||||
-webkit-text-fill-color: transparent !important;
|
||||
-moz-text-fill-color: transparent !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-gradient .surly-badge__header-title {
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-gradient .surly-badge__tag {
|
||||
background: #ff715e !important;
|
||||
background: -webkit-gradient(
|
||||
linear,
|
||||
left top,
|
||||
right top,
|
||||
from(#ff715e),
|
||||
to(#00a8ff)
|
||||
) !important;
|
||||
background: -o-linear-gradient(left, #ff715e 0%, #00a8ff 100%) !important;
|
||||
background: linear-gradient(90deg, #ff715e 0%, #00a8ff 100%) !important;
|
||||
border-bottom: 1px solid #707070 !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-gradient .surly-badge__tag-text {
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-gradient .surly-badge__tag::before {
|
||||
border-color: transparent #914339 transparent transparent !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-gradient .surly-badge__tag::after {
|
||||
border-color: transparent transparent transparent #3b7696 !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-gradient .surly-badge__footer-link {
|
||||
color: #ff715e !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-gradient .surly-badge__footer-title {
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-gradient .surly-badge__footer-text {
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-red {
|
||||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 164 150'%3E%3Cpath style='fill:none;stroke:%23fff;stroke-width:2;stroke-miterlimit:10;' d='M16.05,22.74c0-7.61,6.16-13.76,13.76-13.76 M16.05,22.74v127.15 M29.02,140.85l-12.52,8.2 M28.47,141.01 h105.78 M134.25,141.01c7.61,0,13.76-6.16,13.76-13.76 M148.01,21.03v106.22 M29.81,8.97h106.2'/%3E%3Cpath style='stroke:%23ff715e;stroke-width:2;stroke-miterlimit:10;' d='M148.01,18.02V-0.02 M138.99,9h18.04'/%3E%3C/svg%3E");
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-red .surly-badge__header-text {
|
||||
color: #ff715e !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-red .surly-badge__header-title {
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-red .surly-badge__tag {
|
||||
background-color: #ff715e !important;
|
||||
border-bottom: 1px solid #707070 !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-red .surly-badge__tag-text {
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-red .surly-badge__tag::before {
|
||||
border-color: transparent #914339 transparent transparent !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-red .surly-badge__tag::after {
|
||||
border-color: transparent transparent transparent #914339 !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-red .surly-badge__footer-link {
|
||||
color: #ff715e !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-red .surly-badge__footer-title {
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-red .surly-badge__footer-text {
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-white {
|
||||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 164 150'%3E%3Cpath style='fill:none;stroke:%23fff;stroke-width:2;stroke-miterlimit:10;' d='M16.05,22.74c0-7.61,6.16-13.76,13.76-13.76 M16.05,22.74v127.15 M29.02,140.85l-12.52,8.2 M28.47,141.01 h105.78 M134.25,141.01c7.61,0,13.76-6.16,13.76-13.76 M148.01,21.03v106.22 M29.81,8.97h106.2'/%3E%3Cpath style='stroke:%23fff;stroke-width:2;stroke-miterlimit:10;' d='M148.01,18.02V-0.02 M138.99,9h18.04'/%3E%3C/svg%3E");
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-white .surly-badge__header-text {
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-white .surly-badge__header-title {
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-white .surly-badge__tag {
|
||||
background-color: #fff !important;
|
||||
border-bottom: 1px solid #707070 !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-white .surly-badge__tag-text {
|
||||
color: #000 !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-white .surly-badge__tag::before {
|
||||
border-color: transparent #707070 transparent transparent !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-white .surly-badge__tag::after {
|
||||
border-color: transparent transparent transparent #707070 !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-white .surly-badge__footer-link {
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-white .surly-badge__footer-title {
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_black-white .surly-badge__footer-text {
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-blue {
|
||||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 164 150'%3E%3Cpath style='fill:none;stroke:%232e2e2e;stroke-width:2;stroke-miterlimit:10;' d='M16.05,22.74c0-7.61,6.16-13.76,13.76-13.76 M16.05,22.74v127.15 M29.02,140.85l-12.52,8.2 M28.47,141.01 h105.78 M134.25,141.01c7.61,0,13.76-6.16,13.76-13.76 M148.01,21.03v106.22 M29.81,8.97h106.2'/%3E%3Cpath style='stroke:%2302a7fd;stroke-width:2;stroke-miterlimit:10;' d='M148.01,18.02V-0.02 M138.99,9h18.04'/%3E%3C/svg%3E");
|
||||
color: #2e2e2e !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-blue .surly-badge__header-text {
|
||||
color: #02a7fd !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-blue .surly-badge__header-title {
|
||||
color: #2e2e2e !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-blue .surly-badge__tag {
|
||||
background-color: #02a7fd !important;
|
||||
border-bottom: 1px solid #707070 !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-blue .surly-badge__tag-text {
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-blue .surly-badge__tag::before {
|
||||
border-color: transparent #3b7696 transparent transparent !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-blue .surly-badge__tag::after {
|
||||
border-color: transparent transparent transparent #3b7696 !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-blue .surly-badge__footer-link {
|
||||
color: #02a7fd !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-blue .surly-badge__footer-title {
|
||||
color: #2e2e2e !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-blue .surly-badge__footer-text {
|
||||
color: #2e2e2e !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-gradient {
|
||||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 164 150'%3E%3Cpath style='fill:none;stroke:%232e2e2e;stroke-width:2;stroke-miterlimit:10;' d='M16.05,22.74c0-7.61,6.16-13.76,13.76-13.76 M16.05,22.74v127.15 M29.02,140.85l-12.52,8.2 M28.47,141.01 h105.78 M134.25,141.01c7.61,0,13.76-6.16,13.76-13.76 M148.01,21.03v106.22 M29.81,8.97h106.2'/%3E%3Cpath style='stroke:%23ff5741;stroke-width:2;stroke-miterlimit:10;' d='M148.01,18.02V-0.02 M138.99,9h18.04'/%3E%3C/svg%3E");
|
||||
color: #2e2e2e !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-gradient .surly-badge__header-text {
|
||||
color: #ff5741 !important;
|
||||
background: #ff715e !important;
|
||||
background-image: -webkit-gradient(
|
||||
linear,
|
||||
left top,
|
||||
right top,
|
||||
from(#ff715e),
|
||||
to(#00a8ff)
|
||||
) !important;
|
||||
background-image: -o-linear-gradient(
|
||||
left,
|
||||
#ff715e 0%,
|
||||
#00a8ff 100%
|
||||
) !important;
|
||||
background-image: linear-gradient(90deg, #ff715e 0%, #00a8ff 100%) !important;
|
||||
background-size: 100% !important;
|
||||
-webkit-background-clip: text !important;
|
||||
-moz-background-clip: text !important;
|
||||
-webkit-text-fill-color: transparent !important;
|
||||
-moz-text-fill-color: transparent !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-gradient .surly-badge__header-title {
|
||||
color: #2e2e2e !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-gradient .surly-badge__tag {
|
||||
background: #ff715e !important;
|
||||
background: -webkit-gradient(
|
||||
linear,
|
||||
left top,
|
||||
right top,
|
||||
from(#ff715e),
|
||||
to(#00a8ff)
|
||||
) !important;
|
||||
background: -o-linear-gradient(left, #ff715e 0%, #00a8ff 100%) !important;
|
||||
background: linear-gradient(90deg, #ff715e 0%, #00a8ff 100%) !important;
|
||||
border-bottom: 1px solid #707070 !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-gradient .surly-badge__tag-text {
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-gradient .surly-badge__tag::before {
|
||||
border-color: transparent #914339 transparent transparent !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-gradient .surly-badge__tag::after {
|
||||
border-color: transparent transparent transparent #3b7696 !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-gradient .surly-badge__footer-link {
|
||||
color: #ff5741 !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-gradient .surly-badge__footer-title {
|
||||
color: #2e2e2e !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-gradient .surly-badge__footer-text {
|
||||
color: #2e2e2e !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-red {
|
||||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 164 150'%3E%3Cpath style='fill:none;stroke:%232e2e2e;stroke-width:2;stroke-miterlimit:10;' d='M16.05,22.74c0-7.61,6.16-13.76,13.76-13.76 M16.05,22.74v127.15 M29.02,140.85l-12.52,8.2 M28.47,141.01 h105.78 M134.25,141.01c7.61,0,13.76-6.16,13.76-13.76 M148.01,21.03v106.22 M29.81,8.97h106.2'/%3E%3Cpath style='stroke:%23ff715e;stroke-width:2;stroke-miterlimit:10;' d='M148.01,18.02V-0.02 M138.99,9h18.04'/%3E%3C/svg%3E");
|
||||
color: #2e2e2e !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-red .surly-badge__header-text {
|
||||
color: #ff715e !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-red .surly-badge__header-title {
|
||||
color: #2e2e2e !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-red .surly-badge__tag {
|
||||
background-color: #ff715e !important;
|
||||
border-bottom: 1px solid #707070 !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-red .surly-badge__tag-text {
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-red .surly-badge__tag::before {
|
||||
border-color: transparent #914339 transparent transparent !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-red .surly-badge__tag::after {
|
||||
border-color: transparent transparent transparent #914339 !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-red .surly-badge__footer-link {
|
||||
color: #ff715e !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-red .surly-badge__footer-title {
|
||||
color: #2e2e2e !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-red .surly-badge__footer-text {
|
||||
color: #2e2e2e !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-black {
|
||||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 164 150'%3E%3Cpath style='fill:none;stroke:%232e2e2e;stroke-width:2;stroke-miterlimit:10;' d='M16.05,22.74c0-7.61,6.16-13.76,13.76-13.76 M16.05,22.74v127.15 M29.02,140.85l-12.52,8.2 M28.47,141.01 h105.78 M134.25,141.01c7.61,0,13.76-6.16,13.76-13.76 M148.01,21.03v106.22 M29.81,8.97h106.2'/%3E%3Cpath style='stroke:%23707070;stroke-width:2;stroke-miterlimit:10;' d='M148.01,18.02V-0.02 M138.99,9h18.04'/%3E%3C/svg%3E");
|
||||
color: #2e2e2e !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-black .surly-badge__header-text {
|
||||
color: #2e2e2e !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-black .surly-badge__header-title {
|
||||
color: #2e2e2e !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-black .surly-badge__tag {
|
||||
background-color: #2e2e2e !important;
|
||||
border-bottom: 1px solid #707070 !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-black .surly-badge__tag-text {
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-black .surly-badge__tag::before {
|
||||
border-color: transparent #707070 transparent transparent !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-black .surly-badge__tag::after {
|
||||
border-color: transparent transparent transparent #707070 !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-black .surly-badge__footer-link {
|
||||
color: #2e2e2e !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-black .surly-badge__footer-title {
|
||||
color: #2e2e2e !important;
|
||||
}
|
||||
|
||||
#surly-badge.surly-badge_white-black .surly-badge__footer-text {
|
||||
color: #2e2e2e !important;
|
||||
}
|
||||
|
||||
#surly-badge .surly-badge__header {
|
||||
position: relative !important;
|
||||
z-index: 10 !important;
|
||||
padding: 12px 6px 0 !important;
|
||||
}
|
||||
|
||||
#surly-badge .surly-badge__header-title {
|
||||
font-family: sans-serif !important;
|
||||
font-size: 12px !important;
|
||||
font-weight: 600 !important;
|
||||
text-transform: uppercase !important;
|
||||
line-height: 1 !important;
|
||||
float: none !important;
|
||||
text-align: center !important;
|
||||
padding: 0 !important;
|
||||
margin: 0 !important;
|
||||
margin-bottom: 6px !important;
|
||||
}
|
||||
|
||||
#surly-badge .surly-badge__header-text {
|
||||
font-size: 40px !important;
|
||||
font-weight: 700 !important;
|
||||
text-transform: uppercase !important;
|
||||
line-height: 33px !important;
|
||||
float: none !important;
|
||||
padding: 0 !important;
|
||||
margin: 0 !important;
|
||||
margin-bottom: 4px !important;
|
||||
}
|
||||
|
||||
#surly-badge .surly-badge__tag {
|
||||
height: 18px !important;
|
||||
width: calc(100% + 26px) !important;
|
||||
display: -webkit-box !important;
|
||||
display: -ms-flexbox !important;
|
||||
display: flex !important;
|
||||
-webkit-box-align: center !important;
|
||||
-ms-flex-align: center !important;
|
||||
align-items: center !important;
|
||||
position: relative !important;
|
||||
z-index: 10 !important;
|
||||
-ms-flex-negative: 0 !important;
|
||||
flex-shrink: 0 !important;
|
||||
padding: 0 2px !important;
|
||||
}
|
||||
|
||||
#surly-badge .surly-badge__tag-text {
|
||||
font-size: 10px !important;
|
||||
font-weight: 500 !important;
|
||||
cursor: pointer !important;
|
||||
white-space: nowrap !important;
|
||||
overflow: hidden !important;
|
||||
width: 100% !important;
|
||||
float: none !important;
|
||||
-o-text-overflow: ellipsis !important;
|
||||
text-overflow: ellipsis !important;
|
||||
line-height: initial !important;
|
||||
text-decoration: none !important;
|
||||
padding: 0 0 !important;
|
||||
}
|
||||
|
||||
#surly-badge .surly-badge__tag::before,
|
||||
#surly-badge .surly-badge__tag::after {
|
||||
content: "" !important;
|
||||
display: block !important;
|
||||
position: absolute !important;
|
||||
width: 0 !important;
|
||||
height: 0 !important;
|
||||
border-style: solid !important;
|
||||
}
|
||||
|
||||
#surly-badge .surly-badge__tag::before {
|
||||
border-width: 0 15px 15px 0 !important;
|
||||
left: 0 !important;
|
||||
bottom: -15px !important;
|
||||
}
|
||||
|
||||
#surly-badge .surly-badge__tag::after {
|
||||
border-width: 15px 0 0 15px !important;
|
||||
right: 0 !important;
|
||||
top: -15px !important;
|
||||
}
|
||||
|
||||
#surly-badge .surly-badge__footer {
|
||||
position: relative !important;
|
||||
z-index: 10 !important;
|
||||
white-space: nowrap !important;
|
||||
width: 100% !important;
|
||||
padding-top: 6px !important;
|
||||
}
|
||||
|
||||
#surly-badge .surly-badge__footer-title {
|
||||
font-family: sans-serif !important;
|
||||
font-size: 15px !important;
|
||||
font-weight: 600 !important;
|
||||
text-transform: uppercase !important;
|
||||
overflow: hidden !important;
|
||||
-o-text-overflow: ellipsis !important;
|
||||
text-overflow: ellipsis !important;
|
||||
letter-spacing: -0.5px !important;
|
||||
line-height: 1 !important;
|
||||
float: none !important;
|
||||
text-align: center !important;
|
||||
-webkit-box-sizing: border-box !important;
|
||||
box-sizing: border-box !important;
|
||||
padding: 0 12px !important;
|
||||
margin: 0 !important;
|
||||
margin-bottom: 5px !important;
|
||||
}
|
||||
|
||||
#surly-badge .surly-badge__footer-text {
|
||||
font-size: 13px !important;
|
||||
font-weight: 500 !important;
|
||||
line-height: 1 !important;
|
||||
float: none !important;
|
||||
text-align: center !important;
|
||||
padding: 0 !important;
|
||||
margin: 0 !important;
|
||||
}
|
||||
|
||||
#surly-badge .surly-badge__footer-link {
|
||||
font-size: 13px !important;
|
||||
cursor: pointer !important;
|
||||
text-decoration: underline !important;
|
||||
line-height: initial !important;
|
||||
display: inline-block !important;
|
||||
float: none !important;
|
||||
}
|
||||
|
||||
#surly-badge .surly-badge__date {
|
||||
font-size: 16px !important;
|
||||
font-weight: 600 !important;
|
||||
-webkit-box-flex: 1 !important;
|
||||
-ms-flex-positive: 1 !important;
|
||||
flex-grow: 1 !important;
|
||||
display: -webkit-box !important;
|
||||
display: -ms-flexbox !important;
|
||||
display: flex !important;
|
||||
-webkit-box-align: end !important;
|
||||
-ms-flex-align: end !important;
|
||||
align-items: flex-end !important;
|
||||
line-height: 1 !important;
|
||||
text-align: center !important;
|
||||
float: none !important;
|
||||
}
|
||||
|
||||
#surly-badge br {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.surly__id_56263329.surly-badge_white-blue {
|
||||
margin: 0 auto !important;
|
||||
}
|
||||
|
||||
.surly__id_135641946#surly-badge {
|
||||
padding-top: 6px !important;
|
||||
}
|
||||
|
||||
.surly__id_135641946#surly-badge .surly-badge__footer {
|
||||
line-height: 1 !important;
|
||||
}
|
||||
|
||||
.surly__id_135641946#surly-badge .surly-badge__footer-title {
|
||||
margin-bottom: 2px !important;
|
||||
}
|
||||
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1656.69 67"><defs><style>.cls-1{fill:#fff;}</style></defs><title>Element 1</title><g id="Ebene_2" data-name="Ebene 2"><g id="Ebene_1-2" data-name="Ebene 1"><g id="Ebene_2-2" data-name="Ebene 2-2"><path class="cls-1" d="M1.69,67c72,0,578-67,943-67s712,67,712,67Z"/></g></g></g></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1656.69 67"><defs><style>.cls-1{fill:#fff;}</style></defs><title>Element 1</title><g id="Ebene_2" data-name="Ebene 2"><g id="Ebene_1-2" data-name="Ebene 1"><g id="Ebene_2-2" data-name="Ebene 2-2"><path class="cls-1" d="M1.69,67c72,0,578-67,943-67s712,67,712,67Z"/></g></g></g></svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 335 B After Width: | Height: | Size: 336 B |
BIN
ivatar/static/fonts/fa-brands-400.ttf
Normal file
BIN
ivatar/static/fonts/fa-brands-400.ttf
Normal file
Binary file not shown.
BIN
ivatar/static/fonts/fa-brands-400.woff2
Normal file
BIN
ivatar/static/fonts/fa-brands-400.woff2
Normal file
Binary file not shown.
BIN
ivatar/static/fonts/fa-regular-400.ttf
Normal file
BIN
ivatar/static/fonts/fa-regular-400.ttf
Normal file
Binary file not shown.
BIN
ivatar/static/fonts/fa-regular-400.woff2
Normal file
BIN
ivatar/static/fonts/fa-regular-400.woff2
Normal file
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user