Compare commits
509 Commits
01c80e6e9e
...
master
Author | SHA1 | Date | |
---|---|---|---|
e8e4aab0eb | |||
7abbb78dda | |||
e26faee426 | |||
a7a761f32a | |||
c05718b2d7 | |||
0e83f64f24 | |||
8a14521d6e | |||
e3e4e8280c | |||
03c538cc96 | |||
77d3e49a94 | |||
df40e5e6be | |||
e5c6f0d372 | |||
46c561ca0b | |||
4a3c1b62e0 | |||
64e9844f65 | |||
958a614f19 | |||
f869bbde07 | |||
257c9c2b85 | |||
96b3f35ad0 | |||
658e6d498b | |||
5241115f79 | |||
23e8f33069 | |||
77c3dc9e94 | |||
0a8fc3c805 | |||
b820ca4b49 | |||
dc30d65d68 | |||
dbea05552d | |||
fc416752db | |||
99dd85c973 | |||
69cabe650e | |||
18e6ee16ae | |||
1e5fc7acfe | |||
e16e1a5a6a | |||
80b9ffd4e0 | |||
0a8f441ecb | |||
ee00b31fd0 | |||
7b9ada9164 | |||
991f732f22 | |||
e11a902c98 | |||
dc0455c526 | |||
4cefc7bb0a | |||
9bcdc84824 | |||
9c79c3d93c | |||
bfe6c25f39 | |||
b77e7895b7 | |||
19f99cf9b9 | |||
73988fe5ec | |||
ad1ba1bf19 | |||
cabb74b0a3 | |||
2d7635668d | |||
eeb0594e80 | |||
4f74e7cfc1 | |||
10247deb2e | |||
286b982506 | |||
25f7221d0b | |||
c5b083f2df | |||
2170d53bb4 | |||
19a1fba460 | |||
402bcbc4cd | |||
19a7ae24cf | |||
44de2d320a | |||
b7310bd7ad | |||
e9c14cf146 | |||
ce07e8e0eb | |||
5b58b70ca7 | |||
1bbfe494d8 | |||
80de6e224e | |||
1bb417d02c | |||
dd05ab563e | |||
428a4f8f31 | |||
89d0955137 | |||
ea34f867b0 | |||
cbda0db231 | |||
91b468ee54 | |||
c9d41f2517 | |||
1a1a41d5dc | |||
d01311abf1 | |||
a73ad4bf41 | |||
4a248e84ac | |||
e650fe0c29 | |||
473abb2d38 | |||
1b743c86bf | |||
8c25e2aa4c | |||
f7e4eb955c | |||
7d521ef040 | |||
c59e7b96db | |||
a0d204ad09 | |||
a06be2e889 | |||
42862aea7f | |||
8173ac5bc1 | |||
79a00ff7ad | |||
f2e4d82f87 | |||
022073f26a | |||
c22fcdab74 | |||
672267d521 | |||
c26a3af253 | |||
84d69de09b | |||
76faa33c4e | |||
fb0ebde748 | |||
e0f33c133b | |||
8a0ef75295 | |||
a4f73db82e | |||
31ad52607f | |||
a201f175a2 | |||
f5eaecc189 | |||
6c18a58c43 | |||
677b4221eb | |||
ae92f8f405 | |||
16083a7624 | |||
09da003f35 | |||
f5dde48e9f | |||
c59c735291 | |||
c2dc140002 | |||
d26c9ead7d | |||
5da918cc86 | |||
f7d1115b5a | |||
6d5f65559f | |||
872fa25d77 | |||
6901803ae8 | |||
2f8b02a866 | |||
6ce1b20ad0 | |||
de3896b703 | |||
14c2bb5ac6 | |||
398e95aa83 | |||
4223094222 | |||
a15f1821ff | |||
10824b22c5 | |||
256329cebf | |||
4a14ef7ae6 | |||
42531f32d4 | |||
06152429c1 | |||
1ce9a4d8ec | |||
a8521e7a60 | |||
8a582036a0 | |||
78a8b8732b | |||
8ce1fa7cb1 | |||
ebf4c40ce2 | |||
16f300f3d1 | |||
0fa6834365 | |||
caf3662fbd | |||
451de9392d | |||
0a96e6b47e | |||
b0b978b77c | |||
ec36e964bf | |||
d275460119 | |||
9028b341d6 | |||
705031f2ff | |||
20fffc4868 | |||
066da24c76 | |||
51f9df029a | |||
b2ad0f5475 | |||
7cfe7b4583 | |||
32f2144471 | |||
86e7f35283 | |||
a8290acf12 | |||
639c8a54fd | |||
d6c085e06c | |||
9981b25b86 | |||
34bd7348ab | |||
36d28d1a85 | |||
c7841b0abc | |||
848e14afd1 | |||
0e5e2f55c5 | |||
c0b29c03f2 | |||
3b78af07ae | |||
b07877d46b | |||
ace6cc6215 | |||
433599c087 | |||
687846321f | |||
cb9e259f8c | |||
e0291b72dd | |||
c95cb9fbee | |||
feae2312d3 | |||
d66f51af1d | |||
924ebf2be6 | |||
ce76861739 | |||
216c6d04d4 | |||
ec89f9432b | |||
6da48d5a3b | |||
d6478ac920 | |||
5c3efde9cf | |||
18f017928c | |||
6ec86ab959 | |||
5c0aa6390b | |||
7f7bb0871f | |||
aa0b46906d | |||
c8c4ce0b41 | |||
0511dbf3c7 | |||
5020e898dd | |||
473e5bfe50 | |||
58a68d3f37 | |||
fe019a14ce | |||
8da1344596 | |||
16b2efb2af | |||
3ecdae98e5 | |||
66eb3eb436 | |||
3f2a332d5c | |||
32aa27e177 | |||
3157963dee | |||
e9c3163c11 | |||
0ca6ae23fb | |||
b1f930a471 | |||
a1f1fbfcfb | |||
0c83571e6d | |||
dadf1d4aa4 | |||
91ef6c25d5 | |||
d087c5629d | |||
0a5649fcb9 | |||
7060ce3fe4 | |||
cf0e7e1e68 | |||
64b1bd4de9 | |||
d0cb503f50 | |||
9df0d6da00 | |||
9a79ef701b | |||
c6fc7ff4aa | |||
8d739c6f72 | |||
771cbc0888 | |||
3a7e2d01f0 | |||
dfb277d636 | |||
4bb515366d | |||
5644e40763 | |||
b704e9868b | |||
5b35ec6cf0 | |||
d4e2d7a904 | |||
8dcc2a101d | |||
c504a7c098 | |||
e8d7b0cdee | |||
3a2c969830 | |||
06766a2af4 | |||
c7302c70d8 | |||
348c200f39 | |||
042b9f3f60 | |||
f57de93ac2 | |||
8e303466b0 | |||
5e4ff97b97 | |||
7eb014d5f9 | |||
753e52ff70 | |||
5a5913d5fe | |||
55be4935f1 | |||
e71fad8546 | |||
75b70008e3 | |||
36399604fc | |||
281c94349a | |||
86e723f38c | |||
c9e4bb48e7 | |||
ae0f6f8183 | |||
42e9ca5cfc | |||
9796231dd9 | |||
589bcf247f | |||
4d3f09f011 | |||
00d1057ac6 | |||
1c2aaa4c46 | |||
99add10a4e | |||
9ebe88a7b4 | |||
3928e65d66 | |||
942908ca35 | |||
361865574b | |||
eace55a4e8 | |||
25a898b219 | |||
eeba5d4771 | |||
0a2b512b1d | |||
572837bf70 | |||
36f9d9bc61 | |||
348222f36c | |||
3df5851ab5 | |||
34c9c7d5f3 | |||
939ceea272 | |||
ec508607e7 | |||
606add4f12 | |||
83a8ecf797 | |||
29fc7985dd | |||
2ddba2fd01 | |||
d806823773 | |||
141d8cf7c2 | |||
f39bad6499 | |||
d591307a22 | |||
e26c23efb6 | |||
d638122d3a | |||
3b0f77e8d3 | |||
823ccdfc27 | |||
a217d5dbb0 | |||
07ad3e613e | |||
295b90946b | |||
8f37ae840d | |||
8a2ff91cdc | |||
5f6f2c02ad | |||
b88ff0340c | |||
3001ce4276 | |||
763a6e7ca2 | |||
be163e81e6 | |||
e6c3e22bf9 | |||
335a60d717 | |||
1b1e5c1af7 | |||
e2e70a3c41 | |||
6d46d5e96b | |||
e7a7c5910e | |||
0f9042aa4b | |||
7ed3a30d5a | |||
03207ba7cb | |||
4aaeb75bf3 | |||
c0aded3ef0 | |||
6cdf7a43da | |||
be5554664a | |||
30ff72f409 | |||
5517a42c1c | |||
ad666aace9 | |||
004ea96f59 | |||
8c9b211a50 | |||
1bc1d185b6 | |||
fde97ce507 | |||
dce6aa6330 | |||
b4c7a9ed26 | |||
97ee1d891a | |||
2a5af9f86b | |||
5772f3aa68 | |||
6af4161648 | |||
8567e317c9 | |||
2c1e1d62fb | |||
5dbcf6e4bf | |||
7774f574bf | |||
176b6cbe61 | |||
2465e21977 | |||
adf242b3fd | |||
6bd4fff2ce | |||
8f2834029e | |||
e6da20ee51 | |||
1758b97d67 | |||
1d783f8248 | |||
945f4a832e | |||
a7b0ab1879 | |||
ee1d52d8bf | |||
47d62c0000 | |||
35b7b141d6 | |||
b8295de049 | |||
e1cb5015a3 | |||
6164925a43 | |||
ff7f5c3667 | |||
3f5025f2ab | |||
3c84f9ac3a | |||
686c988b59 | |||
7a5e58d177 | |||
0b238899a3 | |||
87518100b7 | |||
c86a3f547a | |||
726c69b325 | |||
8d6661cca1 | |||
e6078e432d | |||
6002c0a5c3 | |||
7ae4a5d78f | |||
22fbd0ce94 | |||
05dec6a5d8 | |||
8c54a1df3d | |||
6c347b5ad0 | |||
ae5a03aa37 | |||
f5cc643957 | |||
e5fdb97aab | |||
642d713a11 | |||
7afa65f762 | |||
f57104d53a | |||
e031c90f3a | |||
be7c6beb59 | |||
c874a22952 | |||
334883bef2 | |||
4160bb0a63 | |||
48310a2c7d | |||
094c72f13f | |||
3bc80c3e5e | |||
b2209de854 | |||
8f47891d3a | |||
d6147b0393 | |||
f151b92974 | |||
4dbf09a097 | |||
3cd2bb4ec9 | |||
09b67d1fd6 | |||
9b75abd7f4 | |||
42863d4395 | |||
d9c01ab5be | |||
191f2bc78c | |||
a7068ce817 | |||
a6cc049291 | |||
feadbbb1ce | |||
a0fa6d8237 | |||
e367105c5a | |||
a6ffa92aac | |||
4f2a444cbc | |||
46ef623c76 | |||
710bdce3a6 | |||
0c25932c97 | |||
9aa021e3a2 | |||
39eeaea355 | |||
550f1b63d4 | |||
9ef92f279b | |||
f3f9334349 | |||
0900182cd0 | |||
c84a94a394 | |||
5b5e8a69ca | |||
b51f0c8ca0 | |||
e955f6adc1 | |||
d8a28fb74a | |||
b5573beb6a | |||
4f96601851 | |||
4b6cf81219 | |||
81f2401a3f | |||
ccada234bc | |||
9403891143 | |||
8f1725b8e0 | |||
d040c2475e | |||
3b0b8aabcd | |||
f8483b55e3 | |||
3ae3dc784a | |||
7cd5576d1a | |||
493aca2eb9 | |||
eca04f8488 | |||
530118967a | |||
a50be773c2 | |||
43ca92ac12 | |||
dfedbfd94d | |||
f6ff52b310 | |||
6857684d64 | |||
97784a9ef7 | |||
cb7c2b24f2 | |||
61dd064a6c | |||
85f697a746 | |||
78fece539a | |||
6cc9f4c54c | |||
f262e6f183 | |||
e351c333fc | |||
570ee4c3a6 | |||
2b1d0fde3a | |||
5e53da0afa | |||
14ff5c9f41 | |||
9b18b787a9 | |||
4f7c56a4b8 | |||
6d2e52d632 | |||
f1ac19cca1 | |||
6e9fbc325a | |||
3605f0e13c | |||
27d02480ac | |||
c3c8a1c49b | |||
dd82a6dac2 | |||
c085081c5f | |||
f91cfe2c96 | |||
1ca47c0454 | |||
f558b382cb | |||
dc449dfe42 | |||
5064ac33ed | |||
31a433974d | |||
0c50603e22 | |||
a7339939c7 | |||
d28914eac8 | |||
eca0d48e05 | |||
de8f8614e3 | |||
9a415c8795 | |||
e99213c678 | |||
4d4f9f0bdf | |||
8d419dc74f | |||
da59e33687 | |||
b3b15468fb | |||
f2e4826b14 | |||
107b613be5 | |||
e35f890241 | |||
222c950505 | |||
3282b0e693 | |||
f6a2285e22 | |||
41d9f79ba9 | |||
3a8fa9192a | |||
40440a4056 | |||
84180f35a3 | |||
14f672253a | |||
04222e3bf0 | |||
b461f00849 | |||
88bf4596df | |||
d6fa2cae4f | |||
9eca79aa1d | |||
eb0edaaac0 | |||
241e8ab8f9 | |||
99780104e0 | |||
85e165bd29 | |||
9c928ff0a8 | |||
6c1716c0ba | |||
fc6ab00e30 | |||
a2d731bfff | |||
0d8af58e16 | |||
f5ac7bf278 | |||
b68304c976 | |||
83c4a8b27b | |||
fa7eb92481 | |||
ecb3edf90b | |||
9dc4de82ff | |||
292f4179d0 | |||
43a77a5dcd | |||
9b621960d1 | |||
de5a71fdf8 | |||
3e65555d0f | |||
e739b10065 | |||
ec2f271ed4 | |||
fcf3ec7036 | |||
65d334b947 | |||
75d894d648 | |||
0c35400e64 | |||
b10c48d080 | |||
d06c0352fc | |||
c242a492fc | |||
702d338c07 | |||
95f7bbab51 | |||
afb5229336 | |||
8f8adb46a0 | |||
20fbebed54 | |||
bbf23dea15 |
3034
Cargo.lock
generated
3034
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
70
Cargo.toml
70
Cargo.toml
@@ -1,40 +1,42 @@
|
||||
[package]
|
||||
name = "basic-oidc"
|
||||
version = "0.1.3"
|
||||
edition = "2021"
|
||||
version = "0.1.5"
|
||||
edition = "2024"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
actix = "0.13.0"
|
||||
actix-identity = "0.5.2"
|
||||
actix-web = "4"
|
||||
actix-session = { version = "0.7.2", features = ["cookie-session"] }
|
||||
clap = { version = "4.0.22", features = ["derive", "env"] }
|
||||
include_dir = "0.7.3"
|
||||
log = "0.4.17"
|
||||
serde_json = "1.0.87"
|
||||
serde_yaml = "0.9.14"
|
||||
env_logger = "0.9.1"
|
||||
serde = { version = "1.0.147", features = ["derive"] }
|
||||
bcrypt = "0.13.0"
|
||||
uuid = { version = "1.2.1", features = ["v4"] }
|
||||
mime_guess = "2.0.4"
|
||||
askama = "0.11.1"
|
||||
futures-util = "0.3.25"
|
||||
urlencoding = "2.1.2"
|
||||
rand = "0.8.5"
|
||||
base64 = "0.13.1"
|
||||
jwt-simple = "0.11.2"
|
||||
digest = "0.10.5"
|
||||
sha2 = "0.10.6"
|
||||
lazy-regex = "2.3.1"
|
||||
totp_rfc6238 = "0.5.1"
|
||||
base32 = "0.4.0"
|
||||
qrcode-generator = "4.1.6"
|
||||
webauthn-rs = { version = "0.4.8", features = ["danger-allow-state-serialisation"] }
|
||||
url = "2.3.1"
|
||||
aes-gcm = { version = "0.10.1", features = ["aes"] }
|
||||
bincode = "1.3.3"
|
||||
chrono = "0.4.22"
|
||||
lazy_static = "1.4.0"
|
||||
actix = "0.13.5"
|
||||
actix-identity = "0.8.0"
|
||||
actix-web = "4.11.0"
|
||||
actix-session = { version = "0.10.1", features = ["cookie-session"] }
|
||||
actix-remote-ip = "0.1.0"
|
||||
clap = { version = "4.5.41", features = ["derive", "env"] }
|
||||
include_dir = "0.7.4"
|
||||
log = "0.4.27"
|
||||
serde_json = "1.0.141"
|
||||
serde_yaml = "0.9.34"
|
||||
env_logger = "0.11.8"
|
||||
serde = { version = "1.0.219", features = ["derive"] }
|
||||
bcrypt = "0.17.0"
|
||||
uuid = { version = "1.17.0", features = ["v4"] }
|
||||
mime_guess = "2.0.5"
|
||||
askama = "0.14.0"
|
||||
futures-util = "0.3.31"
|
||||
urlencoding = "2.1.3"
|
||||
rand = "0.9.1"
|
||||
base64 = "0.22.1"
|
||||
jwt-simple = { version = "0.12.12", default-features = false, features = ["pure-rust"] }
|
||||
digest = "0.10.7"
|
||||
sha2 = "0.10.9"
|
||||
lazy-regex = "3.4.1"
|
||||
totp_rfc6238 = "0.6.1"
|
||||
base32 = "0.5.1"
|
||||
qrcode-generator = "5.0.0"
|
||||
webauthn-rs = { version = "0.5.2", features = ["danger-allow-state-serialisation"] }
|
||||
url = "2.5.4"
|
||||
light-openid = { version = "1.0.4", features = ["crypto-wrapper"] }
|
||||
bincode = "2.0.1"
|
||||
chrono = "0.4.41"
|
||||
lazy_static = "1.5.0"
|
||||
mailchecker = "6.0.17"
|
||||
|
@@ -1,5 +1,9 @@
|
||||
FROM debian:bullseye-slim
|
||||
FROM debian:bookworm-slim
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y libcurl4 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY basic-oidc /usr/local/bin/basic-oidc
|
||||
|
||||
ENTRYPOINT /usr/local/bin/basic-oidc
|
||||
ENTRYPOINT ["/usr/local/bin/basic-oidc"]
|
||||
|
76
README.md
76
README.md
@@ -5,32 +5,76 @@ Basic & lightweight OpenID provider, written in Rust using the Actix framework.
|
||||
|
||||
**WARNING :** This tool has not been audited, use it at your own risks!
|
||||
|
||||
BasicOIDC operates without any database, just with two files :
|
||||
BasicOIDC operates without any database, just with three files :
|
||||
* `clients.yaml`: a list of authorized relying parties.
|
||||
* `providers.yaml`: a list of upstream providers for authentication federation (this file is optional)
|
||||
* `users.json`: a list of users, managed through a web UI.
|
||||
|
||||
## Configuration
|
||||
You can configure a list of clients (Relying Parties) in a `clients.yaml` file with the following syntax :
|
||||
```yaml
|
||||
# Client ID
|
||||
- id: gitea
|
||||
# Client name
|
||||
name: Gitea
|
||||
# Client description
|
||||
description: Git with a cup of tea
|
||||
# Client secret. Specify this value to use authorization code flow, remove it for implicit authentication flow
|
||||
secret: TOP_SECRET
|
||||
# The URL where user shall be redirected after authentication
|
||||
redirect_uri: https://mygit.mywebsite.com/
|
||||
# Optional, If you want new accounts to be granted access to this client by default
|
||||
default: true
|
||||
# Optional, If you want the client to be granted to every user, regardless their account configuration
|
||||
granted_to_all_users: true
|
||||
# Optional, If you want users to have performed recent second factor authentication before accessing this client, set this setting to true
|
||||
enforce_2fa_auth: true
|
||||
# Optional, claims to be added to the ID token payload.
|
||||
# The following placeholders can be set, they will the replaced when the token is created:
|
||||
# * {username}: user name of the user
|
||||
# * {mail}: email address of the user
|
||||
# * {first_name}: first name of the user
|
||||
# * {last_name}: last name of the user
|
||||
# * {uid}: user id of the user
|
||||
claims_id_token:
|
||||
groups: ["group_{user}"]
|
||||
service: "auth"
|
||||
# Optional, claims to be added to the user info endpoint response
|
||||
# The placeholders of `claims_id_token` can also be used here
|
||||
claims_user_info:
|
||||
groups: ["group_{user}"]
|
||||
service: "auth"
|
||||
```
|
||||
|
||||
On the first run, BasicOIDC will create a new administrator with credentials `admin` / `admin`. On first login you will have to change these default credentials.
|
||||
|
||||
In order to run BasicOIDC for development, you will need to create a least an empty `clients.yaml` file inside the storage directory.
|
||||
|
||||
Features :
|
||||
## Features
|
||||
* [x] `authorization_code` flow
|
||||
* [x] `implicit` flow
|
||||
* [x] Client authentication using secrets
|
||||
* [x] Bruteforce protection
|
||||
* [x] 2 factor authentication
|
||||
* [x] 2 factors authentication
|
||||
* [x] TOTP (authenticator app)
|
||||
* [x] Using a security key (Webauthn)
|
||||
* [ ] Fully responsive webui
|
||||
* [x] `robots.txt` prevents indexing
|
||||
* [x] Support authentication from upstream provider
|
||||
|
||||
## Add an upstream provider
|
||||
You can add as much upstream provider as you want, using the following syntax in `providers.yaml`:
|
||||
```yaml
|
||||
- id: gitlab
|
||||
name: GitLab
|
||||
logo: gitlab # Can be either gitea, gitlab, github, microsoft, google or a full URL
|
||||
client_id: CLIENT_ID_GIVEN_BY_PROVIDER
|
||||
client_secret: CLIENT_SECRET_GIVEN_BY_PROVIDER
|
||||
configuration_url: https://gitlab.com/.well-known/openid-configuration
|
||||
|
||||
```
|
||||
|
||||
> Warning! Self-registration has not been implemented, therfore the accounts must have been previously created through the administration.
|
||||
|
||||
## Compiling
|
||||
You will need the Rust toolchain to compile this project. To build it for production, just run:
|
||||
@@ -38,5 +82,31 @@ You will need the Rust toolchain to compile this project. To build it for produc
|
||||
cargo build --release
|
||||
```
|
||||
|
||||
## Testing with OAauth proxy
|
||||
If you want to test the solution with OAuth proxy, you can try to adapt the following commands (considering `192.168.2.103` is your local IP address):
|
||||
|
||||
```bash
|
||||
export IP=192.168.2.103
|
||||
|
||||
# In a shell, start BasicOID
|
||||
RUST_LOG=debug cargo run -- -s storage -w "http://$IP.nip.io:8000"
|
||||
|
||||
# In another shell, run OAuth proxy
|
||||
docker run --rm -p 4180:4180 quay.io/oauth2-proxy/oauth2-proxy:latest --provider=oidc --email-domain=* --client-id=oauthproxy --client-secret=secretoauth --cookie-secret=SECRETCOOKIE1234 --oidc-issuer-url=http://$IP.nip.io:8000 --http-address 0.0.0.0:4180 --upstream http://$IP --redirect-url http://$IP:4180/oauth2/callback --cookie-secure=false
|
||||
```
|
||||
|
||||
Corresponding client configuration:
|
||||
```yaml
|
||||
- id: oauthproxy
|
||||
name: Oauth proxy
|
||||
description: oauth proxy
|
||||
secret: secretoauth
|
||||
redirect_uri: http://192.168.2.103:4180/
|
||||
```
|
||||
|
||||
> Note: We do need to use real domain name instead of IP address due to the `webauthn-rs` crate limitations. We therefore use the `nip.io` domain helper.
|
||||
|
||||
OAuth proxy can then be access on this URL: http://192.168.2.103:4180/
|
||||
|
||||
## Contributing
|
||||
If you wish to contribute to this software, feel free to send an email to contact@communiquons.org to get an account on my system, managed by BasicOIDC :)
|
||||
|
@@ -1,14 +1,14 @@
|
||||
html,
|
||||
body {
|
||||
height: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
body {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding-top: 40px;
|
||||
padding-bottom: 40px;
|
||||
/* background-color: #f5f5f5; */
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding-top: 40px;
|
||||
padding-bottom: 40px;
|
||||
/* background-color: #f5f5f5; */
|
||||
}
|
||||
|
||||
/* background */
|
||||
@@ -26,50 +26,57 @@ body {
|
||||
}
|
||||
|
||||
.form-signin {
|
||||
width: 100%;
|
||||
max-width: 330px;
|
||||
padding: 15px;
|
||||
margin: auto;
|
||||
width: 100%;
|
||||
max-width: 330px;
|
||||
padding: 15px;
|
||||
margin: auto;
|
||||
}
|
||||
|
||||
.form-signin .checkbox {
|
||||
font-weight: 400;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.form-signin .form-floating:focus-within {
|
||||
z-index: 2;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
.form-floating:first-child input {
|
||||
margin-bottom: -1px;
|
||||
border-bottom-right-radius: 0;
|
||||
border-bottom-left-radius: 0;
|
||||
margin-bottom: -1px;
|
||||
border-bottom-right-radius: 0;
|
||||
border-bottom-left-radius: 0;
|
||||
}
|
||||
|
||||
.form-floating:not(:first-child):not(:last-child) input {
|
||||
margin-bottom: -1px;
|
||||
border-bottom-right-radius: 0;
|
||||
border-bottom-left-radius: 0;
|
||||
border-top-left-radius: 0;
|
||||
border-top-right-radius: 0;
|
||||
margin-bottom: -1px;
|
||||
border-bottom-right-radius: 0;
|
||||
border-bottom-left-radius: 0;
|
||||
border-top-left-radius: 0;
|
||||
border-top-right-radius: 0;
|
||||
}
|
||||
|
||||
.form-floating:last-child input {
|
||||
margin-bottom: 10px;
|
||||
border-top-left-radius: 0;
|
||||
border-top-right-radius: 0;
|
||||
margin-bottom: 10px;
|
||||
border-top-left-radius: 0;
|
||||
border-top-right-radius: 0;
|
||||
}
|
||||
|
||||
.form-control {
|
||||
background-color: var(--bs-gray-700);
|
||||
color: var(--bs-gray-100);
|
||||
background-color: var(--bs-gray-700);
|
||||
color: var(--bs-gray-100);
|
||||
}
|
||||
|
||||
.form-control:focus {
|
||||
background-color: var(--bs-gray-600);
|
||||
color: var(--bs-gray-100);
|
||||
background-color: var(--bs-gray-600);
|
||||
color: var(--bs-gray-100);
|
||||
}
|
||||
|
||||
.text-muted {
|
||||
color: #c6c4c4 !important;
|
||||
}
|
||||
|
||||
.form-floating > .form-control:focus ~ label::after,
|
||||
.form-floating > .form-control:not(:placeholder-shown) ~ label::after,
|
||||
.form-floating > .form-control-plaintext ~ label::after,
|
||||
.form-floating > .form-select ~ label::after {
|
||||
background-color: unset !important;
|
||||
}
|
@@ -13,3 +13,11 @@ body {
|
||||
padding: 3rem;
|
||||
overflow-y: scroll;
|
||||
}
|
||||
|
||||
.nav-link.link-dark {
|
||||
color: white !important;
|
||||
}
|
||||
|
||||
.form-control::placeholder {
|
||||
color: #555;
|
||||
}
|
6919
assets/css/bootstrap.css
vendored
6919
assets/css/bootstrap.css
vendored
File diff suppressed because it is too large
Load Diff
12
assets/img/brands/gitea.svg
Normal file
12
assets/img/brands/gitea.svg
Normal file
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg version="1.1" id="main_outline" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 640 640" style="enable-background:new 0 0 640 640;" xml:space="preserve"><link xmlns="" type="text/css" rel="stylesheet" id="dark-mode-custom-link"/><link xmlns="" type="text/css" rel="stylesheet" id="dark-mode-general-link"/><style xmlns="" lang="en" type="text/css" id="dark-mode-custom-style"/><style xmlns="" lang="en" type="text/css" id="dark-mode-native-style"/><style xmlns="" lang="en" type="text/css" id="dark-mode-native-sheet"/>
|
||||
<g>
|
||||
<path id="teabag" style="fill:#FFFFFF" d="M395.9,484.2l-126.9-61c-12.5-6-17.9-21.2-11.8-33.8l61-126.9c6-12.5,21.2-17.9,33.8-11.8 c17.2,8.3,27.1,13,27.1,13l-0.1-109.2l16.7-0.1l0.1,117.1c0,0,57.4,24.2,83.1,40.1c3.7,2.3,10.2,6.8,12.9,14.4 c2.1,6.1,2,13.1-1,19.3l-61,126.9C423.6,484.9,408.4,490.3,395.9,484.2z"/>
|
||||
<g>
|
||||
<g>
|
||||
<path style="fill:#609926" d="M622.7,149.8c-4.1-4.1-9.6-4-9.6-4s-117.2,6.6-177.9,8c-13.3,0.3-26.5,0.6-39.6,0.7c0,39.1,0,78.2,0,117.2 c-5.5-2.6-11.1-5.3-16.6-7.9c0-36.4-0.1-109.2-0.1-109.2c-29,0.4-89.2-2.2-89.2-2.2s-141.4-7.1-156.8-8.5 c-9.8-0.6-22.5-2.1-39,1.5c-8.7,1.8-33.5,7.4-53.8,26.9C-4.9,212.4,6.6,276.2,8,285.8c1.7,11.7,6.9,44.2,31.7,72.5 c45.8,56.1,144.4,54.8,144.4,54.8s12.1,28.9,30.6,55.5c25,33.1,50.7,58.9,75.7,62c63,0,188.9-0.1,188.9-0.1s12,0.1,28.3-10.3 c14-8.5,26.5-23.4,26.5-23.4s12.9-13.8,30.9-45.3c5.5-9.7,10.1-19.1,14.1-28c0,0,55.2-117.1,55.2-231.1 C633.2,157.9,624.7,151.8,622.7,149.8z M125.6,353.9c-25.9-8.5-36.9-18.7-36.9-18.7S69.6,321.8,60,295.4 c-16.5-44.2-1.4-71.2-1.4-71.2s8.4-22.5,38.5-30c13.8-3.7,31-3.1,31-3.1s7.1,59.4,15.7,94.2c7.2,29.2,24.8,77.7,24.8,77.7 S142.5,359.9,125.6,353.9z M425.9,461.5c0,0-6.1,14.5-19.6,15.4c-5.8,0.4-10.3-1.2-10.3-1.2s-0.3-0.1-5.3-2.1l-112.9-55 c0,0-10.9-5.7-12.8-15.6c-2.2-8.1,2.7-18.1,2.7-18.1L322,273c0,0,4.8-9.7,12.2-13c0.6-0.3,2.3-1,4.5-1.5c8.1-2.1,18,2.8,18,2.8 l110.7,53.7c0,0,12.6,5.7,15.3,16.2c1.9,7.4-0.5,14-1.8,17.2C474.6,363.8,425.9,461.5,425.9,461.5z"/>
|
||||
<path style="fill:#609926" d="M326.8,380.1c-8.2,0.1-15.4,5.8-17.3,13.8c-1.9,8,2,16.3,9.1,20c7.7,4,17.5,1.8,22.7-5.4 c5.1-7.1,4.3-16.9-1.8-23.1l24-49.1c1.5,0.1,3.7,0.2,6.2-0.5c4.1-0.9,7.1-3.6,7.1-3.6c4.2,1.8,8.6,3.8,13.2,6.1 c4.8,2.4,9.3,4.9,13.4,7.3c0.9,0.5,1.8,1.1,2.8,1.9c1.6,1.3,3.4,3.1,4.7,5.5c1.9,5.5-1.9,14.9-1.9,14.9 c-2.3,7.6-18.4,40.6-18.4,40.6c-8.1-0.2-15.3,5-17.7,12.5c-2.6,8.1,1.1,17.3,8.9,21.3c7.8,4,17.4,1.7,22.5-5.3 c5-6.8,4.6-16.3-1.1-22.6c1.9-3.7,3.7-7.4,5.6-11.3c5-10.4,13.5-30.4,13.5-30.4c0.9-1.7,5.7-10.3,2.7-21.3 c-2.5-11.4-12.6-16.7-12.6-16.7c-12.2-7.9-29.2-15.2-29.2-15.2s0-4.1-1.1-7.1c-1.1-3.1-2.8-5.1-3.9-6.3c4.7-9.7,9.4-19.3,14.1-29 c-4.1-2-8.1-4-12.2-6.1c-4.8,9.8-9.7,19.7-14.5,29.5c-6.7-0.1-12.9,3.5-16.1,9.4c-3.4,6.3-2.7,14.1,1.9,19.8 C343.2,346.5,335,363.3,326.8,380.1z"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
After Width: | Height: | Size: 2.9 KiB |
1
assets/img/brands/github.svg
Normal file
1
assets/img/brands/github.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg width="98" height="96" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M48.854 0C21.839 0 0 22 0 49.217c0 21.756 13.993 40.172 33.405 46.69 2.427.49 3.316-1.059 3.316-2.362 0-1.141-.08-5.052-.08-9.127-13.59 2.934-16.42-5.867-16.42-5.867-2.184-5.704-5.42-7.17-5.42-7.17-4.448-3.015.324-3.015.324-3.015 4.934.326 7.523 5.052 7.523 5.052 4.367 7.496 11.404 5.378 14.235 4.074.404-3.178 1.699-5.378 3.074-6.6-10.839-1.141-22.243-5.378-22.243-24.283 0-5.378 1.94-9.778 5.014-13.2-.485-1.222-2.184-6.275.486-13.038 0 0 4.125-1.304 13.426 5.052a46.97 46.97 0 0 1 12.214-1.63c4.125 0 8.33.571 12.213 1.63 9.302-6.356 13.427-5.052 13.427-5.052 2.67 6.763.97 11.816.485 13.038 3.155 3.422 5.015 7.822 5.015 13.2 0 18.905-11.404 23.06-22.324 24.283 1.78 1.548 3.316 4.481 3.316 9.126 0 6.6-.08 11.897-.08 13.526 0 1.304.89 2.853 3.316 2.364 19.412-6.52 33.405-24.935 33.405-46.691C97.707 22 75.788 0 48.854 0z" fill="#fff"/></svg>
|
After Width: | Height: | Size: 960 B |
1
assets/img/brands/gitlab.svg
Normal file
1
assets/img/brands/gitlab.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 380 380"><defs><style>.cls-1{fill:#e24329;}.cls-2{fill:#fc6d26;}.cls-3{fill:#fca326;}</style></defs><g id="LOGO"><path class="cls-1" d="M282.83,170.73l-.27-.69-26.14-68.22a6.81,6.81,0,0,0-2.69-3.24,7,7,0,0,0-8,.43,7,7,0,0,0-2.32,3.52l-17.65,54H154.29l-17.65-54A6.86,6.86,0,0,0,134.32,99a7,7,0,0,0-8-.43,6.87,6.87,0,0,0-2.69,3.24L97.44,170l-.26.69a48.54,48.54,0,0,0,16.1,56.1l.09.07.24.17,39.82,29.82,19.7,14.91,12,9.06a8.07,8.07,0,0,0,9.76,0l12-9.06,19.7-14.91,40.06-30,.1-.08A48.56,48.56,0,0,0,282.83,170.73Z"/><path class="cls-2" d="M282.83,170.73l-.27-.69a88.3,88.3,0,0,0-35.15,15.8L190,229.25c19.55,14.79,36.57,27.64,36.57,27.64l40.06-30,.1-.08A48.56,48.56,0,0,0,282.83,170.73Z"/><path class="cls-3" d="M153.43,256.89l19.7,14.91,12,9.06a8.07,8.07,0,0,0,9.76,0l12-9.06,19.7-14.91S209.55,244,190,229.25C170.45,244,153.43,256.89,153.43,256.89Z"/><path class="cls-2" d="M132.58,185.84A88.19,88.19,0,0,0,97.44,170l-.26.69a48.54,48.54,0,0,0,16.1,56.1l.09.07.24.17,39.82,29.82s17-12.85,36.57-27.64Z"/></g></svg>
|
After Width: | Height: | Size: 1.0 KiB |
1
assets/img/brands/google.svg
Normal file
1
assets/img/brands/google.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="705.6" height="720" viewBox="0 0 186.69 190.5" xmlns:v="https://vecta.io/nano"><link xmlns="" type="text/css" rel="stylesheet" id="dark-mode-custom-link"/><link xmlns="" type="text/css" rel="stylesheet" id="dark-mode-general-link"/><style xmlns="" lang="en" type="text/css" id="dark-mode-custom-style"/><style xmlns="" lang="en" type="text/css" id="dark-mode-native-style"/><style xmlns="" lang="en" type="text/css" id="dark-mode-native-sheet"/><g transform="translate(1184.583 765.171)"><path clip-path="none" mask="none" d="M-1089.333-687.239v36.888h51.262c-2.251 11.863-9.006 21.908-19.137 28.662l30.913 23.986c18.011-16.625 28.402-41.044 28.402-70.052 0-6.754-.606-13.249-1.732-19.483z" fill="#4285f4"/><path clip-path="none" mask="none" d="M-1142.714-651.791l-6.972 5.337-24.679 19.223h0c15.673 31.086 47.796 52.561 85.03 52.561 25.717 0 47.278-8.486 63.038-23.033l-30.913-23.986c-8.486 5.715-19.31 9.179-32.125 9.179-24.765 0-45.806-16.712-53.34-39.226z" fill="#34a853"/><path clip-path="none" mask="none" d="M-1174.365-712.61c-6.494 12.815-10.217 27.276-10.217 42.689s3.723 29.874 10.217 42.689c0 .086 31.693-24.592 31.693-24.592-1.905-5.715-3.031-11.776-3.031-18.098s1.126-12.383 3.031-18.098z" fill="#fbbc05"/><path d="M-1089.333-727.244c14.028 0 26.497 4.849 36.455 14.201l27.276-27.276c-16.539-15.413-38.013-24.852-63.731-24.852-37.234 0-69.359 21.388-85.032 52.561l31.692 24.592c7.533-22.514 28.575-39.226 53.34-39.226z" fill="#ea4335" clip-path="none" mask="none"/></g></svg>
|
After Width: | Height: | Size: 1.5 KiB |
1
assets/img/brands/microsoft.svg
Normal file
1
assets/img/brands/microsoft.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 21 21"><path fill="#f35325" d="M0 0h10v10H0z"/><path fill="#81bc06" d="M11 0h10v10H11z"/><path fill="#05a6f0" d="M0 11h10v10H0z"/><path fill="#ffba08" d="M11 11h10v10H11z"/></svg>
|
After Width: | Height: | Size: 232 B |
6315
assets/js/bootstrap.bundle.min.js
vendored
6315
assets/js/bootstrap.bundle.min.js
vendored
File diff suppressed because one or more lines are too long
@@ -1,3 +1,3 @@
|
||||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json"
|
||||
"extends": ["local>renovate/presets"]
|
||||
}
|
@@ -1,5 +1,5 @@
|
||||
use std::collections::hash_map::Entry;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::Entry;
|
||||
use std::net::IpAddr;
|
||||
|
||||
use actix::{Actor, AsyncContext, Context, Handler, Message};
|
||||
|
@@ -1,3 +1,4 @@
|
||||
pub mod bruteforce_actor;
|
||||
pub mod openid_sessions_actor;
|
||||
pub mod providers_states_actor;
|
||||
pub mod users_actor;
|
||||
|
130
src/actors/providers_states_actor.rs
Normal file
130
src/actors/providers_states_actor.rs
Normal file
@@ -0,0 +1,130 @@
|
||||
//! # Providers state actor
|
||||
//!
|
||||
//! This actor stores the content of the states
|
||||
//! during authentication with upstream providers
|
||||
|
||||
use crate::constants::{
|
||||
MAX_OIDC_PROVIDERS_STATES, OIDC_PROVIDERS_STATE_DURATION, OIDC_PROVIDERS_STATE_LEN,
|
||||
OIDC_STATES_CLEANUP_INTERVAL,
|
||||
};
|
||||
use actix::{Actor, AsyncContext, Context, Handler, Message};
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::Entry;
|
||||
use std::net::IpAddr;
|
||||
|
||||
use crate::data::login_redirect::LoginRedirect;
|
||||
use crate::data::provider::ProviderID;
|
||||
use crate::utils::string_utils::rand_str;
|
||||
use crate::utils::time::time;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ProviderLoginState {
|
||||
pub provider_id: ProviderID,
|
||||
pub state_id: String,
|
||||
pub redirect: LoginRedirect,
|
||||
pub expire: u64,
|
||||
}
|
||||
|
||||
impl ProviderLoginState {
|
||||
pub fn new(prov_id: &ProviderID, redirect: LoginRedirect) -> Self {
|
||||
Self {
|
||||
provider_id: prov_id.clone(),
|
||||
state_id: rand_str(OIDC_PROVIDERS_STATE_LEN),
|
||||
redirect,
|
||||
expire: time() + OIDC_PROVIDERS_STATE_DURATION,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(result = "()")]
|
||||
pub struct RecordState {
|
||||
pub ip: IpAddr,
|
||||
pub state: ProviderLoginState,
|
||||
}
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(result = "Option<ProviderLoginState>")]
|
||||
pub struct ConsumeState {
|
||||
pub ip: IpAddr,
|
||||
pub state_id: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ProvidersStatesActor {
|
||||
states: HashMap<IpAddr, Vec<ProviderLoginState>>,
|
||||
}
|
||||
|
||||
impl ProvidersStatesActor {
|
||||
/// Clean outdated states
|
||||
fn clean_old_states(&mut self) {
|
||||
#[allow(clippy::map_clone)]
|
||||
let keys = self.states.keys().map(|i| *i).collect::<Vec<_>>();
|
||||
|
||||
for ip in keys {
|
||||
// Remove old states
|
||||
let states = self.states.get_mut(&ip).unwrap();
|
||||
states.retain(|i| i.expire < time());
|
||||
|
||||
// Remove empty entry keys
|
||||
if states.is_empty() {
|
||||
self.states.remove(&ip);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a new provider login state
|
||||
pub fn insert_state(&mut self, ip: IpAddr, state: ProviderLoginState) {
|
||||
if let Entry::Vacant(e) = self.states.entry(ip) {
|
||||
e.insert(vec![state]);
|
||||
} else {
|
||||
let states = self.states.get_mut(&ip).unwrap();
|
||||
|
||||
// We limit the number of states per IP address
|
||||
if states.len() > MAX_OIDC_PROVIDERS_STATES {
|
||||
states.remove(0);
|
||||
}
|
||||
|
||||
states.push(state);
|
||||
}
|
||||
}
|
||||
|
||||
/// Get & consume a login state
|
||||
pub fn consume_state(&mut self, ip: IpAddr, state_id: &str) -> Option<ProviderLoginState> {
|
||||
let idx = self
|
||||
.states
|
||||
.get(&ip)?
|
||||
.iter()
|
||||
.position(|val| val.state_id.as_str() == state_id)?;
|
||||
|
||||
Some(self.states.get_mut(&ip)?.remove(idx))
|
||||
}
|
||||
}
|
||||
|
||||
impl Actor for ProvidersStatesActor {
|
||||
type Context = Context<Self>;
|
||||
|
||||
fn started(&mut self, ctx: &mut Self::Context) {
|
||||
// Clean up at a regular interval failed attempts
|
||||
ctx.run_interval(OIDC_STATES_CLEANUP_INTERVAL, |act, _ctx| {
|
||||
log::trace!("Cleaning up old states");
|
||||
act.clean_old_states();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler<RecordState> for ProvidersStatesActor {
|
||||
type Result = ();
|
||||
|
||||
fn handle(&mut self, req: RecordState, _ctx: &mut Self::Context) -> Self::Result {
|
||||
self.insert_state(req.ip, req.state);
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler<ConsumeState> for ProvidersStatesActor {
|
||||
type Result = Option<ProviderLoginState>;
|
||||
|
||||
fn handle(&mut self, req: ConsumeState, _ctx: &mut Self::Context) -> Self::Result {
|
||||
self.consume_state(req.ip, &req.state_id)
|
||||
}
|
||||
}
|
@@ -1,24 +1,59 @@
|
||||
use actix::{Actor, Context, Handler, Message, MessageResult};
|
||||
use std::net::IpAddr;
|
||||
|
||||
use crate::data::entity_manager::EntityManager;
|
||||
use crate::data::user::{User, UserID};
|
||||
use crate::data::provider::{Provider, ProviderID};
|
||||
use actix::{Actor, Context, Handler, Message, MessageResult};
|
||||
|
||||
use crate::data::user::{FactorID, GeneralSettings, GrantedClients, TwoFactor, User, UserID};
|
||||
use crate::utils::err::Res;
|
||||
|
||||
/// User storage interface
|
||||
pub trait UsersSyncBackend {
|
||||
fn find_by_username_or_email(&self, u: &str) -> Res<Option<User>>;
|
||||
fn find_by_email(&self, u: &str) -> Res<Option<User>>;
|
||||
fn find_by_user_id(&self, id: &UserID) -> Res<Option<User>>;
|
||||
fn get_entire_users_list(&self) -> Res<Vec<User>>;
|
||||
fn create_user_account(&mut self, settings: GeneralSettings) -> Res<UserID>;
|
||||
fn set_general_user_settings(&mut self, settings: GeneralSettings) -> Res;
|
||||
fn change_user_password(&mut self, id: &UserID, password: &str, temporary: bool) -> Res;
|
||||
fn verify_user_password(&self, user: &UserID, password: &str) -> Res<bool>;
|
||||
fn add_2fa_factor(&mut self, user: &UserID, factor: TwoFactor) -> Res;
|
||||
fn remove_2fa_factor(&mut self, user: &UserID, factor: FactorID) -> Res;
|
||||
fn save_new_successful_2fa_authentication(&mut self, id: &UserID, ip: IpAddr) -> Res;
|
||||
fn clear_2fa_login_history(&mut self, id: &UserID) -> Res;
|
||||
fn delete_account(&mut self, id: &UserID) -> Res;
|
||||
fn set_authorized_authentication_sources(
|
||||
&mut self,
|
||||
id: &UserID,
|
||||
sources: AuthorizedAuthenticationSources,
|
||||
) -> Res;
|
||||
fn set_granted_2fa_clients(&mut self, id: &UserID, clients: GrantedClients) -> Res;
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum LoginResult {
|
||||
Error,
|
||||
AccountNotFound,
|
||||
InvalidPassword,
|
||||
AccountDisabled,
|
||||
LocalAuthForbidden,
|
||||
AuthFromProviderForbidden,
|
||||
Success(Box<User>),
|
||||
}
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(LoginResult)]
|
||||
pub struct LoginRequest {
|
||||
pub struct LocalLoginRequest {
|
||||
pub login: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(LoginResult)]
|
||||
pub struct ProviderLoginRequest {
|
||||
pub email: String,
|
||||
pub provider: Provider,
|
||||
}
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(GetUserResult)]
|
||||
pub struct GetUserRequest(pub UserID);
|
||||
@@ -26,6 +61,10 @@ pub struct GetUserRequest(pub UserID);
|
||||
#[derive(Debug)]
|
||||
pub struct GetUserResult(pub Option<User>);
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(result = "bool")]
|
||||
pub struct VerifyUserPasswordRequest(pub UserID, pub String);
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(FindUserByUsernameResult)]
|
||||
pub struct FindUserByUsername(pub String);
|
||||
@@ -34,22 +73,28 @@ pub struct FindUserByUsername(pub String);
|
||||
pub struct FindUserByUsernameResult(pub Option<User>);
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(GetAllUsersResult)]
|
||||
pub struct GetAllUsersRequest;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct GetAllUsersResult(pub Vec<User>);
|
||||
#[rtype(result = "Vec<User>")]
|
||||
pub struct GetAllUsers;
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(ChangePasswordResult)]
|
||||
#[rtype(result = "Option<UserID>")]
|
||||
pub struct CreateAccount(pub GeneralSettings);
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(result = "bool")]
|
||||
pub struct ChangePasswordRequest {
|
||||
pub user_id: UserID,
|
||||
pub new_password: String,
|
||||
pub temporary: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ChangePasswordResult(pub bool);
|
||||
#[derive(Message)]
|
||||
#[rtype(result = "bool")]
|
||||
pub struct Add2FAFactor(pub UserID, pub TwoFactor);
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(result = "bool")]
|
||||
pub struct Remove2FAFactor(pub UserID, pub FactorID);
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(result = "bool")]
|
||||
@@ -59,27 +104,40 @@ pub struct AddSuccessful2FALogin(pub UserID, pub IpAddr);
|
||||
#[rtype(result = "bool")]
|
||||
pub struct Clear2FALoginHistory(pub UserID);
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct UpdateUserResult(pub bool);
|
||||
#[derive(Eq, PartialEq, Debug, Clone)]
|
||||
pub struct AuthorizedAuthenticationSources {
|
||||
pub local: bool,
|
||||
pub upstream: Vec<ProviderID>,
|
||||
}
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(UpdateUserResult)]
|
||||
pub struct UpdateUserRequest(pub User);
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct DeleteUserResult(pub bool);
|
||||
#[rtype(result = "bool")]
|
||||
pub struct SetAuthorizedAuthenticationSources(pub UserID, pub AuthorizedAuthenticationSources);
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(DeleteUserResult)]
|
||||
#[rtype(result = "bool")]
|
||||
pub struct SetGrantedClients(pub UserID, pub GrantedClients);
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(result = "bool")]
|
||||
pub struct UpdateUserSettings(pub GeneralSettings);
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(result = "bool")]
|
||||
pub struct DeleteUserRequest(pub UserID);
|
||||
|
||||
pub struct UsersActor {
|
||||
manager: EntityManager<User>,
|
||||
manager: Box<dyn UsersSyncBackend>,
|
||||
}
|
||||
|
||||
impl UsersActor {
|
||||
pub fn new(manager: EntityManager<User>) -> Self {
|
||||
Self { manager }
|
||||
pub fn new<E>(manager: E) -> Self
|
||||
where
|
||||
E: UsersSyncBackend + 'static,
|
||||
{
|
||||
Self {
|
||||
manager: Box::new(manager),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,14 +145,22 @@ impl Actor for UsersActor {
|
||||
type Context = Context<Self>;
|
||||
}
|
||||
|
||||
impl Handler<LoginRequest> for UsersActor {
|
||||
type Result = MessageResult<LoginRequest>;
|
||||
impl Handler<LocalLoginRequest> for UsersActor {
|
||||
type Result = MessageResult<LocalLoginRequest>;
|
||||
|
||||
fn handle(&mut self, msg: LoginRequest, _ctx: &mut Self::Context) -> Self::Result {
|
||||
fn handle(&mut self, msg: LocalLoginRequest, _ctx: &mut Self::Context) -> Self::Result {
|
||||
match self.manager.find_by_username_or_email(&msg.login) {
|
||||
None => MessageResult(LoginResult::AccountNotFound),
|
||||
Some(user) => {
|
||||
if !user.verify_password(&msg.password) {
|
||||
Err(e) => {
|
||||
log::error!("Failed to find user! {e}");
|
||||
MessageResult(LoginResult::Error)
|
||||
}
|
||||
Ok(None) => MessageResult(LoginResult::AccountNotFound),
|
||||
Ok(Some(user)) => {
|
||||
if !self
|
||||
.manager
|
||||
.verify_user_password(&user.uid, &msg.password)
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return MessageResult(LoginResult::InvalidPassword);
|
||||
}
|
||||
|
||||
@@ -102,21 +168,97 @@ impl Handler<LoginRequest> for UsersActor {
|
||||
return MessageResult(LoginResult::AccountDisabled);
|
||||
}
|
||||
|
||||
if !user.allow_local_login {
|
||||
return MessageResult(LoginResult::LocalAuthForbidden);
|
||||
}
|
||||
|
||||
MessageResult(LoginResult::Success(Box::new(user)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler<ProviderLoginRequest> for UsersActor {
|
||||
type Result = MessageResult<ProviderLoginRequest>;
|
||||
|
||||
fn handle(&mut self, msg: ProviderLoginRequest, _ctx: &mut Self::Context) -> Self::Result {
|
||||
match self.manager.find_by_email(&msg.email) {
|
||||
Err(e) => {
|
||||
log::error!("Failed to find user! {e}");
|
||||
MessageResult(LoginResult::Error)
|
||||
}
|
||||
Ok(None) => MessageResult(LoginResult::AccountNotFound),
|
||||
Ok(Some(user)) => {
|
||||
if !user.can_login_from_provider(&msg.provider) {
|
||||
return MessageResult(LoginResult::AuthFromProviderForbidden);
|
||||
}
|
||||
|
||||
if !user.enabled {
|
||||
return MessageResult(LoginResult::AccountDisabled);
|
||||
}
|
||||
|
||||
MessageResult(LoginResult::Success(Box::new(user)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler<CreateAccount> for UsersActor {
|
||||
type Result = <CreateAccount as actix::Message>::Result;
|
||||
|
||||
fn handle(&mut self, msg: CreateAccount, _ctx: &mut Self::Context) -> Self::Result {
|
||||
match self.manager.create_user_account(msg.0) {
|
||||
Ok(id) => Some(id),
|
||||
Err(e) => {
|
||||
log::error!("Failed to create user account! {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler<ChangePasswordRequest> for UsersActor {
|
||||
type Result = MessageResult<ChangePasswordRequest>;
|
||||
type Result = <ChangePasswordRequest as actix::Message>::Result;
|
||||
|
||||
fn handle(&mut self, msg: ChangePasswordRequest, _ctx: &mut Self::Context) -> Self::Result {
|
||||
MessageResult(ChangePasswordResult(self.manager.change_user_password(
|
||||
&msg.user_id,
|
||||
&msg.new_password,
|
||||
msg.temporary,
|
||||
)))
|
||||
match self
|
||||
.manager
|
||||
.change_user_password(&msg.user_id, &msg.new_password, msg.temporary)
|
||||
{
|
||||
Ok(_) => true,
|
||||
Err(e) => {
|
||||
log::error!("Failed to change user password! {e:?}");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler<Add2FAFactor> for UsersActor {
|
||||
type Result = <Add2FAFactor as actix::Message>::Result;
|
||||
|
||||
fn handle(&mut self, msg: Add2FAFactor, _ctx: &mut Self::Context) -> Self::Result {
|
||||
match self.manager.add_2fa_factor(&msg.0, msg.1) {
|
||||
Ok(_) => true,
|
||||
Err(e) => {
|
||||
log::error!("Failed to add 2FA factor! {e}");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler<Remove2FAFactor> for UsersActor {
|
||||
type Result = <Remove2FAFactor as actix::Message>::Result;
|
||||
|
||||
fn handle(&mut self, msg: Remove2FAFactor, _ctx: &mut Self::Context) -> Self::Result {
|
||||
match self.manager.remove_2fa_factor(&msg.0, msg.1) {
|
||||
Ok(_) => true,
|
||||
Err(e) => {
|
||||
log::error!("Failed to remove 2FA factor! {e}");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,15 +266,66 @@ impl Handler<AddSuccessful2FALogin> for UsersActor {
|
||||
type Result = <AddSuccessful2FALogin as actix::Message>::Result;
|
||||
|
||||
fn handle(&mut self, msg: AddSuccessful2FALogin, _ctx: &mut Self::Context) -> Self::Result {
|
||||
self.manager
|
||||
match self
|
||||
.manager
|
||||
.save_new_successful_2fa_authentication(&msg.0, msg.1)
|
||||
{
|
||||
Ok(_) => true,
|
||||
Err(e) => {
|
||||
log::error!("Failed to save successful 2FA authentication! {e}");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler<Clear2FALoginHistory> for UsersActor {
|
||||
type Result = <Clear2FALoginHistory as actix::Message>::Result;
|
||||
fn handle(&mut self, msg: Clear2FALoginHistory, _ctx: &mut Self::Context) -> Self::Result {
|
||||
self.manager.clear_2fa_login_history(&msg.0)
|
||||
match self.manager.clear_2fa_login_history(&msg.0) {
|
||||
Ok(_) => true,
|
||||
Err(e) => {
|
||||
log::error!(
|
||||
"Failed to clear 2FA login history of user {:?} ! {}",
|
||||
msg.0,
|
||||
e
|
||||
);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler<SetAuthorizedAuthenticationSources> for UsersActor {
|
||||
type Result = <SetAuthorizedAuthenticationSources as actix::Message>::Result;
|
||||
fn handle(
|
||||
&mut self,
|
||||
msg: SetAuthorizedAuthenticationSources,
|
||||
_ctx: &mut Self::Context,
|
||||
) -> Self::Result {
|
||||
match self
|
||||
.manager
|
||||
.set_authorized_authentication_sources(&msg.0, msg.1)
|
||||
{
|
||||
Ok(_) => true,
|
||||
Err(e) => {
|
||||
log::error!("Failed to set authorized authentication sources for user! {e}");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler<SetGrantedClients> for UsersActor {
|
||||
type Result = <SetGrantedClients as actix::Message>::Result;
|
||||
fn handle(&mut self, msg: SetGrantedClients, _ctx: &mut Self::Context) -> Self::Result {
|
||||
match self.manager.set_granted_2fa_clients(&msg.0, msg.1) {
|
||||
Ok(_) => true,
|
||||
Err(e) => {
|
||||
log::error!("Failed to set granted 2FA clients! {e}");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,7 +333,26 @@ impl Handler<GetUserRequest> for UsersActor {
|
||||
type Result = MessageResult<GetUserRequest>;
|
||||
|
||||
fn handle(&mut self, msg: GetUserRequest, _ctx: &mut Self::Context) -> Self::Result {
|
||||
MessageResult(GetUserResult(self.manager.find_by_user_id(&msg.0)))
|
||||
MessageResult(GetUserResult(match self.manager.find_by_user_id(&msg.0) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
log::error!("Failed to find user by id! {e}");
|
||||
None
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler<VerifyUserPasswordRequest> for UsersActor {
|
||||
type Result = <VerifyUserPasswordRequest as actix::Message>::Result;
|
||||
|
||||
fn handle(&mut self, msg: VerifyUserPasswordRequest, _ctx: &mut Self::Context) -> Self::Result {
|
||||
self.manager
|
||||
.verify_user_password(&msg.0, &msg.1)
|
||||
.unwrap_or_else(|e| {
|
||||
log::error!("Failed to verify user password! {e}");
|
||||
false
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,54 +361,54 @@ impl Handler<FindUserByUsername> for UsersActor {
|
||||
|
||||
fn handle(&mut self, msg: FindUserByUsername, _ctx: &mut Self::Context) -> Self::Result {
|
||||
MessageResult(FindUserByUsernameResult(
|
||||
self.manager.find_by_username_or_email(&msg.0),
|
||||
self.manager
|
||||
.find_by_username_or_email(&msg.0)
|
||||
.unwrap_or_else(|e| {
|
||||
log::error!("Failed to find user by username or email! {e}");
|
||||
None
|
||||
}),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler<GetAllUsersRequest> for UsersActor {
|
||||
type Result = MessageResult<GetAllUsersRequest>;
|
||||
impl Handler<GetAllUsers> for UsersActor {
|
||||
type Result = <GetAllUsers as actix::Message>::Result;
|
||||
|
||||
fn handle(&mut self, _msg: GetAllUsersRequest, _ctx: &mut Self::Context) -> Self::Result {
|
||||
MessageResult(GetAllUsersResult(self.manager.cloned()))
|
||||
fn handle(&mut self, _msg: GetAllUsers, _ctx: &mut Self::Context) -> Self::Result {
|
||||
match self.manager.get_entire_users_list() {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
log::error!("Failed to get entire users list! {e}");
|
||||
vec![]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler<UpdateUserRequest> for UsersActor {
|
||||
type Result = MessageResult<UpdateUserRequest>;
|
||||
impl Handler<UpdateUserSettings> for UsersActor {
|
||||
type Result = <UpdateUserSettings as actix::Message>::Result;
|
||||
|
||||
fn handle(&mut self, msg: UpdateUserRequest, _ctx: &mut Self::Context) -> Self::Result {
|
||||
MessageResult(UpdateUserResult(match self.manager.update_or_push(msg.0) {
|
||||
fn handle(&mut self, msg: UpdateUserSettings, _ctx: &mut Self::Context) -> Self::Result {
|
||||
match self.manager.set_general_user_settings(msg.0) {
|
||||
Ok(_) => true,
|
||||
Err(e) => {
|
||||
log::error!("Failed to update user information! {:?}", e);
|
||||
log::error!("Failed to update general user information! {e:?}");
|
||||
false
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler<DeleteUserRequest> for UsersActor {
|
||||
type Result = MessageResult<DeleteUserRequest>;
|
||||
type Result = <DeleteUserRequest as actix::Message>::Result;
|
||||
|
||||
fn handle(&mut self, msg: DeleteUserRequest, _ctx: &mut Self::Context) -> Self::Result {
|
||||
let user = match self.manager.find_by_user_id(&msg.0) {
|
||||
None => {
|
||||
log::warn!(
|
||||
"Could not delete account {:?} because it was not found!",
|
||||
msg.0
|
||||
);
|
||||
return MessageResult(DeleteUserResult(false));
|
||||
}
|
||||
Some(s) => s,
|
||||
};
|
||||
|
||||
MessageResult(DeleteUserResult(match self.manager.remove(&user) {
|
||||
match self.manager.delete_account(&msg.0) {
|
||||
Ok(_) => true,
|
||||
Err(e) => {
|
||||
log::error!("Failed to update delete account! {:?}", e);
|
||||
log::error!("Failed to delete user account! {e}");
|
||||
false
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -6,6 +6,9 @@ pub const USERS_LIST_FILE: &str = "users.json";
|
||||
/// File in storage containing clients list
|
||||
pub const CLIENTS_LIST_FILE: &str = "clients.yaml";
|
||||
|
||||
/// File in storage containing providers list
|
||||
pub const PROVIDERS_LIST_FILE: &str = "providers.yaml";
|
||||
|
||||
/// Default built-in credentials
|
||||
pub const DEFAULT_ADMIN_USERNAME: &str = "admin";
|
||||
pub const DEFAULT_ADMIN_PASSWORD: &str = "admin";
|
||||
@@ -19,10 +22,17 @@ pub const MAX_INACTIVITY_DURATION: u64 = 60 * 30;
|
||||
/// Maximum session duration (6 hours)
|
||||
pub const MAX_SESSION_DURATION: u64 = 3600 * 6;
|
||||
|
||||
/// Maximum length of a second factor name
|
||||
pub const MAX_SECOND_FACTOR_NAME_LEN: usize = 25;
|
||||
|
||||
/// When the user successfully authenticate using 2FA, period of time during which the user is
|
||||
/// exempted from this IP address to use 2FA
|
||||
pub const SECOND_FACTOR_EXEMPTION_AFTER_SUCCESSFUL_LOGIN: u64 = 7 * 24 * 3600;
|
||||
|
||||
/// The maximum acceptable interval of time between last two factors authentication of a user and
|
||||
/// access to a critical route / a critical client
|
||||
pub const SECOND_FACTOR_EXPIRATION_FOR_CRITICAL_OPERATIONS: u64 = 60 * 10;
|
||||
|
||||
/// Minimum password length
|
||||
pub const MIN_PASS_LEN: usize = 4;
|
||||
|
||||
@@ -59,9 +69,22 @@ pub const OPEN_ID_AUTHORIZATION_CODE_LEN: usize = 120;
|
||||
pub const OPEN_ID_AUTHORIZATION_CODE_TIMEOUT: u64 = 300;
|
||||
pub const OPEN_ID_ACCESS_TOKEN_LEN: usize = 50;
|
||||
pub const OPEN_ID_ACCESS_TOKEN_TIMEOUT: u64 = 3600;
|
||||
pub const OPEN_ID_ID_TOKEN_TIMEOUT: u64 = 3600;
|
||||
pub const OPEN_ID_REFRESH_TOKEN_LEN: usize = 120;
|
||||
pub const OPEN_ID_REFRESH_TOKEN_TIMEOUT: u64 = 360000;
|
||||
|
||||
/// Webauthn constants
|
||||
pub const WEBAUTHN_REGISTER_CHALLENGE_EXPIRE: u64 = 3600;
|
||||
pub const WEBAUTHN_LOGIN_CHALLENGE_EXPIRE: u64 = 3600;
|
||||
|
||||
/// OpenID providers login state constants
|
||||
pub const OIDC_STATES_CLEANUP_INTERVAL: Duration = Duration::from_secs(60);
|
||||
pub const MAX_OIDC_PROVIDERS_STATES: usize = 10;
|
||||
pub const OIDC_PROVIDERS_STATE_LEN: usize = 40;
|
||||
pub const OIDC_PROVIDERS_STATE_DURATION: u64 = 60 * 15;
|
||||
|
||||
/// OpenID providers configuration constants
|
||||
pub const OIDC_PROVIDERS_LIFETIME: u64 = 3600;
|
||||
|
||||
/// OpenID provider callback URI
|
||||
pub const OIDC_PROVIDER_CB_URI: &str = "/prov_cb";
|
||||
|
@@ -1,9 +1,13 @@
|
||||
use crate::actors::users_actor;
|
||||
use actix::Addr;
|
||||
use actix_web::{web, HttpResponse, Responder};
|
||||
use actix_web::{HttpResponse, Responder, web};
|
||||
|
||||
use crate::actors::users_actor::{DeleteUserRequest, FindUserByUsername, UsersActor};
|
||||
use crate::data::action_logger::{Action, ActionLogger};
|
||||
use crate::data::critical_route::CriticalRoute;
|
||||
use crate::data::current_user::CurrentUser;
|
||||
use crate::data::user::UserID;
|
||||
use crate::utils::string_utils;
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
pub struct FindUserNameReq {
|
||||
@@ -16,9 +20,14 @@ struct FindUserResult {
|
||||
}
|
||||
|
||||
pub async fn find_username(
|
||||
_critical: CriticalRoute,
|
||||
req: web::Form<FindUserNameReq>,
|
||||
users: web::Data<Addr<UsersActor>>,
|
||||
) -> impl Responder {
|
||||
if !string_utils::is_acceptable_login(&req.username) {
|
||||
return HttpResponse::BadRequest().json("Invalid login!");
|
||||
}
|
||||
|
||||
let res = users
|
||||
.send(FindUserByUsername(req.0.username))
|
||||
.await
|
||||
@@ -34,16 +43,29 @@ pub struct DeleteUserReq {
|
||||
}
|
||||
|
||||
pub async fn delete_user(
|
||||
_critical: CriticalRoute,
|
||||
user: CurrentUser,
|
||||
req: web::Form<DeleteUserReq>,
|
||||
users: web::Data<Addr<UsersActor>>,
|
||||
action_logger: ActionLogger,
|
||||
) -> impl Responder {
|
||||
if user.uid == req.user_id {
|
||||
return HttpResponse::BadRequest().body("You can not remove your own account!");
|
||||
}
|
||||
|
||||
let user = match users
|
||||
.send(users_actor::GetUserRequest(req.user_id.clone()))
|
||||
.await
|
||||
.unwrap()
|
||||
.0
|
||||
{
|
||||
None => return HttpResponse::NotFound().body("Could not find a user to remove!"),
|
||||
Some(u) => u,
|
||||
};
|
||||
|
||||
let res = users.send(DeleteUserRequest(req.0.user_id)).await.unwrap();
|
||||
if res.0 {
|
||||
if res {
|
||||
action_logger.log(Action::AdminDeleteUser(&user));
|
||||
HttpResponse::Ok().finish()
|
||||
} else {
|
||||
HttpResponse::InternalServerError().finish()
|
||||
|
@@ -1,44 +1,62 @@
|
||||
use std::ops::Deref;
|
||||
use std::sync::Arc;
|
||||
|
||||
use actix::Addr;
|
||||
use actix_web::{web, HttpResponse, Responder};
|
||||
use actix_web::{HttpResponse, Responder, web};
|
||||
use askama::Template;
|
||||
|
||||
use crate::actors::users_actor;
|
||||
use crate::actors::users_actor::UsersActor;
|
||||
use crate::actors::users_actor::{AuthorizedAuthenticationSources, UsersActor};
|
||||
use crate::constants::TEMPORARY_PASSWORDS_LEN;
|
||||
use crate::controllers::settings_controller::BaseSettingsPage;
|
||||
use crate::data::action_logger::{Action, ActionLogger};
|
||||
use crate::data::app_config::AppConfig;
|
||||
use crate::data::client::{Client, ClientID, ClientManager};
|
||||
use crate::data::critical_route::CriticalRoute;
|
||||
use crate::data::current_user::CurrentUser;
|
||||
use crate::data::user::{hash_password, User, UserID};
|
||||
use crate::data::provider::{Provider, ProviderID, ProvidersManager};
|
||||
use crate::data::user::{GeneralSettings, GrantedClients, User, UserID};
|
||||
use crate::utils::string_utils;
|
||||
use crate::utils::string_utils::rand_str;
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "settings/clients_list.html")]
|
||||
struct ClientsListTemplate {
|
||||
_p: BaseSettingsPage,
|
||||
struct ClientsListTemplate<'a> {
|
||||
p: BaseSettingsPage<'a>,
|
||||
clients: Vec<Client>,
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "settings/providers_list.html")]
|
||||
struct ProvidersListTemplate<'a> {
|
||||
p: BaseSettingsPage<'a>,
|
||||
providers: Vec<Provider>,
|
||||
redirect_url: String,
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "settings/users_list.html")]
|
||||
struct UsersListTemplate {
|
||||
_p: BaseSettingsPage,
|
||||
struct UsersListTemplate<'a> {
|
||||
p: BaseSettingsPage<'a>,
|
||||
users: Vec<User>,
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "settings/edit_user.html")]
|
||||
struct EditUserTemplate {
|
||||
_p: BaseSettingsPage,
|
||||
struct EditUserTemplate<'a> {
|
||||
p: BaseSettingsPage<'a>,
|
||||
u: User,
|
||||
clients: Vec<Client>,
|
||||
providers: Vec<Provider>,
|
||||
}
|
||||
|
||||
pub async fn clients_route(user: CurrentUser, clients: web::Data<ClientManager>) -> impl Responder {
|
||||
pub async fn clients_route(
|
||||
user: CurrentUser,
|
||||
clients: web::Data<Arc<ClientManager>>,
|
||||
) -> impl Responder {
|
||||
HttpResponse::Ok().body(
|
||||
ClientsListTemplate {
|
||||
_p: BaseSettingsPage::get("Clients list", &user, None, None),
|
||||
p: BaseSettingsPage::get("Clients list", &user, None, None),
|
||||
clients: clients.cloned(),
|
||||
}
|
||||
.render()
|
||||
@@ -46,6 +64,21 @@ pub async fn clients_route(user: CurrentUser, clients: web::Data<ClientManager>)
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn providers_route(
|
||||
user: CurrentUser,
|
||||
providers: web::Data<Arc<ProvidersManager>>,
|
||||
) -> impl Responder {
|
||||
HttpResponse::Ok().body(
|
||||
ProvidersListTemplate {
|
||||
p: BaseSettingsPage::get("OpenID Providers list", &user, None, None),
|
||||
providers: providers.cloned(),
|
||||
redirect_url: AppConfig::get().oidc_provider_redirect_url(),
|
||||
}
|
||||
.render()
|
||||
.unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, Debug)]
|
||||
pub struct UpdateUserQuery {
|
||||
uid: UserID,
|
||||
@@ -57,6 +90,8 @@ pub struct UpdateUserQuery {
|
||||
enabled: Option<String>,
|
||||
two_factor_exemption_after_successful_login: Option<String>,
|
||||
admin: Option<String>,
|
||||
allow_local_login: Option<String>,
|
||||
authorized_sources: String,
|
||||
grant_type: String,
|
||||
granted_clients: String,
|
||||
two_factor: String,
|
||||
@@ -64,72 +99,165 @@ pub struct UpdateUserQuery {
|
||||
}
|
||||
|
||||
pub async fn users_route(
|
||||
user: CurrentUser,
|
||||
_critical: CriticalRoute,
|
||||
admin: CurrentUser,
|
||||
users: web::Data<Addr<UsersActor>>,
|
||||
update_query: Option<web::Form<UpdateUserQuery>>,
|
||||
logger: ActionLogger,
|
||||
) -> impl Responder {
|
||||
let mut danger = None;
|
||||
let mut success = None;
|
||||
|
||||
if let Some(update) = update_query {
|
||||
let current_user: Option<User> = users
|
||||
.send(users_actor::FindUserByUsername(update.username.to_string()))
|
||||
// Check update query for invalid input
|
||||
if update_query
|
||||
.as_ref()
|
||||
.map(|l| string_utils::is_acceptable_login(&l.username))
|
||||
== Some(false)
|
||||
{
|
||||
danger = Some("Invalid login provided, the modifications could not be saved!".to_string());
|
||||
}
|
||||
// Perform request (if any)
|
||||
else if let Some(update) = update_query {
|
||||
let edited_user: Option<User> = users
|
||||
.send(users_actor::GetUserRequest(update.uid.clone()))
|
||||
.await
|
||||
.unwrap()
|
||||
.0;
|
||||
let is_creating = current_user.is_none();
|
||||
let is_creating = edited_user.is_none();
|
||||
|
||||
let mut user = current_user.unwrap_or_default();
|
||||
user.uid = update.0.uid;
|
||||
user.username = update.0.username;
|
||||
user.first_name = update.0.first_name;
|
||||
user.last_name = update.0.last_name;
|
||||
user.email = update.0.email;
|
||||
user.enabled = update.0.enabled.is_some();
|
||||
user.two_factor_exemption_after_successful_login = update
|
||||
.0
|
||||
.two_factor_exemption_after_successful_login
|
||||
.is_some();
|
||||
user.admin = update.0.admin.is_some();
|
||||
let settings = GeneralSettings {
|
||||
uid: update.0.uid,
|
||||
username: update.0.username,
|
||||
first_name: update.0.first_name,
|
||||
last_name: update.0.last_name,
|
||||
email: update.0.email,
|
||||
enabled: update.0.enabled.is_some(),
|
||||
two_factor_exemption_after_successful_login: update
|
||||
.0
|
||||
.two_factor_exemption_after_successful_login
|
||||
.is_some(),
|
||||
is_admin: update.0.admin.is_some(),
|
||||
};
|
||||
let mut edited_user = edited_user.unwrap_or_default();
|
||||
edited_user.update_general_settings(settings.clone());
|
||||
|
||||
let factors_to_keep = update.0.two_factor.split(';').collect::<Vec<_>>();
|
||||
user.two_factor
|
||||
.retain(|f| factors_to_keep.contains(&f.id.0.as_str()));
|
||||
|
||||
user.authorized_clients = match update.0.grant_type.as_str() {
|
||||
"all_clients" => None,
|
||||
"custom_clients" => Some(
|
||||
update
|
||||
.0
|
||||
.granted_clients
|
||||
.split(',')
|
||||
.map(|c| ClientID(c.to_string()))
|
||||
.collect::<Vec<_>>(),
|
||||
),
|
||||
_ => Some(Vec::new()),
|
||||
let res = match is_creating {
|
||||
true => {
|
||||
match users
|
||||
.send(users_actor::CreateAccount(settings))
|
||||
.await
|
||||
.unwrap()
|
||||
{
|
||||
Some(id) => {
|
||||
edited_user.uid = id;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
false => users
|
||||
.send(users_actor::UpdateUserSettings(settings))
|
||||
.await
|
||||
.unwrap(),
|
||||
};
|
||||
|
||||
// Update the list of factors
|
||||
let factors_to_keep = update.0.two_factor.split(';').collect::<Vec<_>>();
|
||||
for factor in &edited_user.two_factor {
|
||||
if !factors_to_keep.contains(&factor.id.0.as_str()) {
|
||||
logger.log(Action::AdminRemoveUserFactor(&edited_user, factor));
|
||||
users
|
||||
.send(users_actor::Remove2FAFactor(
|
||||
edited_user.uid.clone(),
|
||||
factor.id.clone(),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
// Update the list of authorized authentication sources
|
||||
let auth_sources = AuthorizedAuthenticationSources {
|
||||
local: update.0.allow_local_login.is_some(),
|
||||
upstream: match update.0.authorized_sources.as_str() {
|
||||
"" => vec![],
|
||||
s => s.split(',').map(|s| ProviderID(s.to_string())).collect(),
|
||||
},
|
||||
};
|
||||
|
||||
if edited_user.authorized_authentication_sources() != auth_sources {
|
||||
logger.log(Action::AdminSetAuthorizedAuthenticationSources(
|
||||
&edited_user,
|
||||
&auth_sources,
|
||||
));
|
||||
users
|
||||
.send(users_actor::SetAuthorizedAuthenticationSources(
|
||||
edited_user.uid.clone(),
|
||||
auth_sources,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
// Update list of granted clients
|
||||
let granted_clients = match update.0.grant_type.as_str() {
|
||||
"all_clients" => GrantedClients::AllClients,
|
||||
"custom_clients" if !update.0.granted_clients.is_empty() => {
|
||||
GrantedClients::SomeClients(
|
||||
update
|
||||
.0
|
||||
.granted_clients
|
||||
.split(',')
|
||||
.map(|c| ClientID(c.to_string()))
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
}
|
||||
_ => GrantedClients::NoClient,
|
||||
};
|
||||
|
||||
if edited_user.granted_clients() != granted_clients {
|
||||
logger.log(Action::AdminSetNewGrantedClientsList(
|
||||
&edited_user,
|
||||
&granted_clients,
|
||||
));
|
||||
users
|
||||
.send(users_actor::SetGrantedClients(
|
||||
edited_user.uid.clone(),
|
||||
granted_clients,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
// Clear user 2FA history if requested
|
||||
if update.0.clear_2fa_history.is_some() {
|
||||
logger.log(Action::AdminClear2FAHistory(&edited_user));
|
||||
users
|
||||
.send(users_actor::Clear2FALoginHistory(edited_user.uid.clone()))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
// If the admin requested it, reset user password
|
||||
let new_password = match update.0.gen_new_password.is_some() {
|
||||
false => None,
|
||||
true => {
|
||||
logger.log(Action::AdminResetUserPassword(&edited_user));
|
||||
|
||||
let temp_pass = rand_str(TEMPORARY_PASSWORDS_LEN);
|
||||
user.password = hash_password(&temp_pass).expect("Failed to hash password");
|
||||
user.need_reset_password = true;
|
||||
user.last_successful_2fa = Default::default();
|
||||
users
|
||||
.send(users_actor::ChangePasswordRequest {
|
||||
user_id: edited_user.uid.clone(),
|
||||
new_password: temp_pass.clone(),
|
||||
temporary: true,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
Some(temp_pass)
|
||||
}
|
||||
};
|
||||
|
||||
if update.0.clear_2fa_history.is_some() {
|
||||
user.last_successful_2fa = Default::default();
|
||||
}
|
||||
|
||||
let res = users
|
||||
.send(users_actor::UpdateUserRequest(user.clone()))
|
||||
.await
|
||||
.unwrap()
|
||||
.0;
|
||||
|
||||
if !res {
|
||||
danger = Some(
|
||||
match is_creating {
|
||||
@@ -140,25 +268,31 @@ pub async fn users_route(
|
||||
)
|
||||
} else {
|
||||
success = Some(match is_creating {
|
||||
true => format!("User {} was successfully created!", user.full_name()),
|
||||
false => format!("User {} was successfully updated!", user.full_name()),
|
||||
true => {
|
||||
logger.log(Action::AdminCreateUser(&edited_user));
|
||||
format!("User {} was successfully created!", edited_user.full_name())
|
||||
}
|
||||
false => {
|
||||
logger.log(Action::AdminUpdateUser(&edited_user));
|
||||
format!("User {} was successfully updated!", edited_user.full_name())
|
||||
}
|
||||
});
|
||||
|
||||
if let Some(pass) = new_password {
|
||||
danger = Some(format!(
|
||||
"{}'s temporary password is {}",
|
||||
user.full_name(),
|
||||
edited_user.full_name(),
|
||||
pass
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let users = users.send(users_actor::GetAllUsersRequest).await.unwrap().0;
|
||||
let users = users.send(users_actor::GetAllUsers).await.unwrap();
|
||||
|
||||
HttpResponse::Ok().body(
|
||||
UsersListTemplate {
|
||||
_p: BaseSettingsPage::get("Users list", &user, danger, success),
|
||||
p: BaseSettingsPage::get("Users list", &admin, danger, success),
|
||||
users,
|
||||
}
|
||||
.render()
|
||||
@@ -166,12 +300,29 @@ pub async fn users_route(
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn create_user(user: CurrentUser, clients: web::Data<ClientManager>) -> impl Responder {
|
||||
pub async fn create_user(
|
||||
_critical: CriticalRoute,
|
||||
admin: CurrentUser,
|
||||
clients: web::Data<Arc<ClientManager>>,
|
||||
providers: web::Data<Arc<ProvidersManager>>,
|
||||
) -> impl Responder {
|
||||
let user = User {
|
||||
authorized_clients: Some(
|
||||
clients
|
||||
.get_default_clients()
|
||||
.iter()
|
||||
.map(|u| u.id.clone())
|
||||
.collect(),
|
||||
),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
HttpResponse::Ok().body(
|
||||
EditUserTemplate {
|
||||
_p: BaseSettingsPage::get("Create a new user", user.deref(), None, None),
|
||||
u: Default::default(),
|
||||
p: BaseSettingsPage::get("Create a new user", admin.deref(), None, None),
|
||||
u: user,
|
||||
clients: clients.cloned(),
|
||||
providers: providers.cloned(),
|
||||
}
|
||||
.render()
|
||||
.unwrap(),
|
||||
@@ -184,8 +335,10 @@ pub struct EditUserQuery {
|
||||
}
|
||||
|
||||
pub async fn edit_user(
|
||||
user: CurrentUser,
|
||||
clients: web::Data<ClientManager>,
|
||||
_critical: CriticalRoute,
|
||||
admin: CurrentUser,
|
||||
clients: web::Data<Arc<ClientManager>>,
|
||||
providers: web::Data<Arc<ProvidersManager>>,
|
||||
users: web::Data<Addr<UsersActor>>,
|
||||
query: web::Query<EditUserQuery>,
|
||||
) -> impl Responder {
|
||||
@@ -197,9 +350,9 @@ pub async fn edit_user(
|
||||
|
||||
HttpResponse::Ok().body(
|
||||
EditUserTemplate {
|
||||
_p: BaseSettingsPage::get(
|
||||
p: BaseSettingsPage::get(
|
||||
"Edit user account",
|
||||
user.deref(),
|
||||
admin.deref(),
|
||||
match edited_account.is_none() {
|
||||
true => Some("Could not find requested user!".to_string()),
|
||||
false => None,
|
||||
@@ -208,6 +361,7 @@ pub async fn edit_user(
|
||||
),
|
||||
u: edited_account.unwrap_or_default(),
|
||||
clients: clients.cloned(),
|
||||
providers: providers.cloned(),
|
||||
}
|
||||
.render()
|
||||
.unwrap(),
|
||||
|
@@ -1,7 +1,7 @@
|
||||
use std::path::Path;
|
||||
|
||||
use actix_web::{web, HttpResponse};
|
||||
use include_dir::{include_dir, Dir};
|
||||
use actix_web::{HttpResponse, web};
|
||||
use include_dir::{Dir, include_dir};
|
||||
|
||||
/// Assets directory
|
||||
static ASSETS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/assets");
|
||||
|
@@ -1,9 +1,10 @@
|
||||
use crate::actors::users_actor;
|
||||
use crate::actors::users_actor::UsersActor;
|
||||
use crate::data::remote_ip::RemoteIP;
|
||||
use crate::data::action_logger::{Action, ActionLogger};
|
||||
use actix::Addr;
|
||||
use actix_identity::Identity;
|
||||
use actix_web::{web, HttpRequest, HttpResponse, Responder};
|
||||
use actix_remote_ip::RemoteIP;
|
||||
use actix_web::{HttpRequest, HttpResponse, Responder, web};
|
||||
use webauthn_rs::prelude::PublicKeyCredential;
|
||||
|
||||
use crate::data::session_identity::{SessionIdentity, SessionStatus};
|
||||
@@ -22,25 +23,35 @@ pub async fn auth_webauthn(
|
||||
http_req: HttpRequest,
|
||||
remote_ip: RemoteIP,
|
||||
users: web::Data<Addr<UsersActor>>,
|
||||
logger: ActionLogger,
|
||||
) -> impl Responder {
|
||||
if !SessionIdentity(Some(&id)).need_2fa_auth() {
|
||||
return HttpResponse::Unauthorized().json("No 2FA required!");
|
||||
}
|
||||
|
||||
let user_id = SessionIdentity(Some(&id)).user_id();
|
||||
|
||||
match manager.finish_authentication(&user_id, &req.opaque_state, &req.credential) {
|
||||
Ok(_) => {
|
||||
users
|
||||
.send(users_actor::AddSuccessful2FALogin(user_id, remote_ip.0))
|
||||
.send(users_actor::AddSuccessful2FALogin(
|
||||
user_id.clone(),
|
||||
remote_ip.0,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
SessionIdentity(Some(&id)).set_status(&http_req, SessionStatus::SignedIn);
|
||||
let session = SessionIdentity(Some(&id));
|
||||
session.record_2fa_auth(&http_req);
|
||||
session.set_status(&http_req, SessionStatus::SignedIn);
|
||||
logger.log(Action::LoginWebauthnAttempt {
|
||||
success: true,
|
||||
user_id,
|
||||
});
|
||||
HttpResponse::Ok().body("You are authenticated!")
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("Failed to authenticate user using webauthn! {:?}", e);
|
||||
log::error!("Failed to authenticate user using webauthn! {e:?}");
|
||||
logger.log(Action::LoginWebauthnAttempt {
|
||||
success: false,
|
||||
user_id,
|
||||
});
|
||||
HttpResponse::InternalServerError().body("Failed to validate security key!")
|
||||
}
|
||||
}
|
||||
|
@@ -1,60 +1,66 @@
|
||||
use actix::Addr;
|
||||
use actix_identity::Identity;
|
||||
use actix_web::{web, HttpRequest, HttpResponse, Responder};
|
||||
use actix_remote_ip::RemoteIP;
|
||||
use actix_web::{HttpRequest, HttpResponse, Responder, web};
|
||||
use askama::Template;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::actors::bruteforce_actor::BruteForceActor;
|
||||
use crate::actors::users_actor::{ChangePasswordResult, LoginResult, UsersActor};
|
||||
use crate::actors::users_actor::{LoginResult, UsersActor};
|
||||
use crate::actors::{bruteforce_actor, users_actor};
|
||||
use crate::constants::{APP_NAME, MAX_FAILED_LOGIN_ATTEMPTS, MIN_PASS_LEN};
|
||||
use crate::controllers::base_controller::{
|
||||
build_fatal_error_page, redirect_user, redirect_user_for_login,
|
||||
};
|
||||
use crate::data::login_redirect::LoginRedirect;
|
||||
use crate::data::remote_ip::RemoteIP;
|
||||
use crate::data::action_logger::{Action, ActionLogger};
|
||||
use crate::data::force_2fa_auth::Force2FAAuth;
|
||||
use crate::data::login_redirect::{LoginRedirect, get_2fa_url};
|
||||
use crate::data::provider::{Provider, ProvidersManager};
|
||||
use crate::data::session_identity::{SessionIdentity, SessionStatus};
|
||||
use crate::data::user::User;
|
||||
use crate::data::webauthn_manager::WebAuthManagerReq;
|
||||
use crate::utils::string_utils;
|
||||
|
||||
struct BaseLoginPage<'a> {
|
||||
danger: Option<String>,
|
||||
success: Option<String>,
|
||||
page_title: &'static str,
|
||||
app_name: &'static str,
|
||||
redirect_uri: &'a LoginRedirect,
|
||||
pub struct BaseLoginPage<'a> {
|
||||
pub danger: Option<String>,
|
||||
pub success: Option<String>,
|
||||
pub page_title: &'static str,
|
||||
pub app_name: &'static str,
|
||||
pub redirect_uri: &'a LoginRedirect,
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "login/login.html")]
|
||||
struct LoginTemplate<'a> {
|
||||
_p: BaseLoginPage<'a>,
|
||||
p: BaseLoginPage<'a>,
|
||||
login: String,
|
||||
providers: Vec<Provider>,
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "login/password_reset.html")]
|
||||
struct PasswordResetTemplate<'a> {
|
||||
_p: BaseLoginPage<'a>,
|
||||
p: BaseLoginPage<'a>,
|
||||
min_pass_len: usize,
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "login/choose_second_factor.html")]
|
||||
struct ChooseSecondFactorTemplate<'a> {
|
||||
_p: BaseLoginPage<'a>,
|
||||
p: BaseLoginPage<'a>,
|
||||
user: &'a User,
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "login/otp_input.html")]
|
||||
struct LoginWithOTPTemplate<'a> {
|
||||
_p: BaseLoginPage<'a>,
|
||||
p: BaseLoginPage<'a>,
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "login/webauthn_input.html")]
|
||||
struct LoginWithWebauthnTemplate<'a> {
|
||||
_p: BaseLoginPage<'a>,
|
||||
p: BaseLoginPage<'a>,
|
||||
opaque_state: String,
|
||||
challenge_json: String,
|
||||
}
|
||||
@@ -73,14 +79,17 @@ pub struct LoginRequestQuery {
|
||||
}
|
||||
|
||||
/// Authenticate user
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn login_route(
|
||||
remote_ip: RemoteIP,
|
||||
providers: web::Data<Arc<ProvidersManager>>,
|
||||
users: web::Data<Addr<UsersActor>>,
|
||||
bruteforce: web::Data<Addr<BruteForceActor>>,
|
||||
query: web::Query<LoginRequestQuery>,
|
||||
req: Option<web::Form<LoginRequestBody>>,
|
||||
id: Option<Identity>,
|
||||
http_req: HttpRequest,
|
||||
logger: ActionLogger,
|
||||
) -> impl Responder {
|
||||
let mut danger = None;
|
||||
let mut success = None;
|
||||
@@ -102,6 +111,7 @@ pub async fn login_route(
|
||||
// Check if user session must be closed
|
||||
if let Some(true) = query.logout {
|
||||
if let Some(id) = id {
|
||||
logger.log(Action::Signout);
|
||||
id.logout();
|
||||
}
|
||||
success = Some("Goodbye!".to_string());
|
||||
@@ -117,18 +127,25 @@ pub async fn login_route(
|
||||
query.redirect.get_encoded()
|
||||
));
|
||||
}
|
||||
// Check if the user has to valide a second factor
|
||||
// Check if the user has to validate a second factor
|
||||
else if SessionIdentity(id.as_ref()).need_2fa_auth() {
|
||||
return redirect_user(&format!(
|
||||
"/2fa_auth?redirect={}",
|
||||
query.redirect.get_encoded()
|
||||
));
|
||||
return redirect_user(&get_2fa_url(&query.redirect, false));
|
||||
}
|
||||
// Check if given login is not acceptable
|
||||
else if req
|
||||
.as_ref()
|
||||
.map(|r| string_utils::is_acceptable_login(&r.login))
|
||||
== Some(false)
|
||||
{
|
||||
danger = Some(
|
||||
"Given login could not be processed, because it has an invalid format!".to_string(),
|
||||
);
|
||||
}
|
||||
// Try to authenticate user
|
||||
else if let Some(req) = &req {
|
||||
login = req.login.clone();
|
||||
login.clone_from(&req.login);
|
||||
let response: LoginResult = users
|
||||
.send(users_actor::LoginRequest {
|
||||
.send(users_actor::LocalLoginRequest {
|
||||
login: login.clone(),
|
||||
password: req.password.clone(),
|
||||
})
|
||||
@@ -138,11 +155,14 @@ pub async fn login_route(
|
||||
match response {
|
||||
LoginResult::Success(user) => {
|
||||
let status = if user.need_reset_password {
|
||||
logger.log(Action::UserNeedNewPasswordOnLogin(&user));
|
||||
SessionStatus::NeedNewPassword
|
||||
} else if user.has_two_factor() && !user.can_bypass_two_factors_for_ip(remote_ip.0)
|
||||
{
|
||||
logger.log(Action::UserNeed2FAOnLogin(&user));
|
||||
SessionStatus::Need2FA
|
||||
} else {
|
||||
logger.log(Action::UserSuccessfullyAuthenticated(&user));
|
||||
SessionStatus::SignedIn
|
||||
};
|
||||
|
||||
@@ -151,17 +171,27 @@ pub async fn login_route(
|
||||
}
|
||||
|
||||
LoginResult::AccountDisabled => {
|
||||
log::warn!("Failed login for username {} : account is disabled", login);
|
||||
log::warn!("Failed login for username {} : account is disabled", &login);
|
||||
logger.log(Action::TryLoginWithDisabledAccount(&login));
|
||||
danger = Some("Your account is disabled!".to_string());
|
||||
}
|
||||
|
||||
c => {
|
||||
LoginResult::LocalAuthForbidden => {
|
||||
log::warn!(
|
||||
"Failed login for ip {:?} / username {}: {:?}",
|
||||
remote_ip,
|
||||
login,
|
||||
c
|
||||
"Failed login for username {} : attempted to use local auth, but it is forbidden",
|
||||
&login
|
||||
);
|
||||
logger.log(Action::TryLocalLoginFromUnauthorizedAccount(&login));
|
||||
danger = Some("You cannot login from local auth with your account!".to_string());
|
||||
}
|
||||
|
||||
LoginResult::Error => {
|
||||
danger = Some("An unkown error occured while trying to sign you in!".to_string());
|
||||
}
|
||||
|
||||
c => {
|
||||
log::warn!("Failed login for ip {remote_ip:?} / username {login}: {c:?}");
|
||||
logger.log(Action::FailedLoginWithBadCredentials(&login));
|
||||
danger = Some("Login failed.".to_string());
|
||||
|
||||
bruteforce
|
||||
@@ -176,7 +206,7 @@ pub async fn login_route(
|
||||
|
||||
HttpResponse::Ok().content_type("text/html").body(
|
||||
LoginTemplate {
|
||||
_p: BaseLoginPage {
|
||||
p: BaseLoginPage {
|
||||
page_title: "Login",
|
||||
danger,
|
||||
success,
|
||||
@@ -184,6 +214,7 @@ pub async fn login_route(
|
||||
redirect_uri: &query.redirect,
|
||||
},
|
||||
login,
|
||||
providers: providers.cloned(),
|
||||
}
|
||||
.render()
|
||||
.unwrap(),
|
||||
@@ -213,6 +244,7 @@ pub async fn reset_password_route(
|
||||
req: Option<web::Form<ChangePasswordRequestBody>>,
|
||||
users: web::Data<Addr<UsersActor>>,
|
||||
http_req: HttpRequest,
|
||||
logger: ActionLogger,
|
||||
) -> impl Responder {
|
||||
let mut danger = None;
|
||||
|
||||
@@ -220,24 +252,27 @@ pub async fn reset_password_route(
|
||||
return redirect_user_for_login(query.redirect.get());
|
||||
}
|
||||
|
||||
// Check if user is setting a new password
|
||||
let user_id = SessionIdentity(id.as_ref()).user_id();
|
||||
|
||||
// Check if user is setting a new password
|
||||
if let Some(req) = &req {
|
||||
if req.password.len() < MIN_PASS_LEN {
|
||||
danger = Some("Password is too short!".to_string());
|
||||
} else {
|
||||
let res: ChangePasswordResult = users
|
||||
let res: bool = users
|
||||
.send(users_actor::ChangePasswordRequest {
|
||||
user_id: SessionIdentity(id.as_ref()).user_id(),
|
||||
user_id: user_id.clone(),
|
||||
new_password: req.password.clone(),
|
||||
temporary: false,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
if !res.0 {
|
||||
if !res {
|
||||
danger = Some("Failed to change password!".to_string());
|
||||
} else {
|
||||
SessionIdentity(id.as_ref()).set_status(&http_req, SessionStatus::SignedIn);
|
||||
logger.log(Action::UserChangedPasswordOnLogin(&user_id));
|
||||
return redirect_user(query.redirect.get());
|
||||
}
|
||||
}
|
||||
@@ -245,7 +280,7 @@ pub async fn reset_password_route(
|
||||
|
||||
HttpResponse::Ok().content_type("text/html").body(
|
||||
PasswordResetTemplate {
|
||||
_p: BaseLoginPage {
|
||||
p: BaseLoginPage {
|
||||
page_title: "Password reset",
|
||||
danger,
|
||||
success: None,
|
||||
@@ -272,8 +307,9 @@ pub async fn choose_2fa_method(
|
||||
id: Option<Identity>,
|
||||
query: web::Query<ChooseSecondFactorQuery>,
|
||||
users: web::Data<Addr<UsersActor>>,
|
||||
force2faauth: Force2FAAuth,
|
||||
) -> impl Responder {
|
||||
if !SessionIdentity(id.as_ref()).need_2fa_auth() {
|
||||
if !SessionIdentity(id.as_ref()).need_2fa_auth() && !force2faauth.force {
|
||||
log::trace!("User does not require 2fa auth, redirecting");
|
||||
return redirect_user_for_login(query.redirect.get());
|
||||
}
|
||||
@@ -290,12 +326,12 @@ pub async fn choose_2fa_method(
|
||||
// Automatically choose factor if there is only one factor
|
||||
if user.get_distinct_factors_types().len() == 1 && !query.force_display {
|
||||
log::trace!("User has only one factor, using it by default");
|
||||
return redirect_user(&user.two_factor[0].login_url(&query.redirect));
|
||||
return redirect_user(&user.two_factor[0].login_url(&query.redirect, true));
|
||||
}
|
||||
|
||||
HttpResponse::Ok().content_type("text/html").body(
|
||||
ChooseSecondFactorTemplate {
|
||||
_p: BaseLoginPage {
|
||||
p: BaseLoginPage {
|
||||
page_title: "Two factor authentication",
|
||||
danger: None,
|
||||
success: None,
|
||||
@@ -321,6 +357,7 @@ pub struct LoginWithOTPForm {
|
||||
}
|
||||
|
||||
/// Login with OTP
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn login_with_otp(
|
||||
id: Option<Identity>,
|
||||
query: web::Query<LoginWithOTPQuery>,
|
||||
@@ -328,10 +365,12 @@ pub async fn login_with_otp(
|
||||
users: web::Data<Addr<UsersActor>>,
|
||||
http_req: HttpRequest,
|
||||
remote_ip: RemoteIP,
|
||||
logger: ActionLogger,
|
||||
force2faauth: Force2FAAuth,
|
||||
) -> impl Responder {
|
||||
let mut danger = None;
|
||||
|
||||
if !SessionIdentity(id.as_ref()).need_2fa_auth() {
|
||||
if !SessionIdentity(id.as_ref()).need_2fa_auth() && !force2faauth.force {
|
||||
return redirect_user_for_login(query.redirect.get());
|
||||
}
|
||||
|
||||
@@ -354,21 +393,34 @@ pub async fn login_with_otp(
|
||||
.iter()
|
||||
.any(|k| k.check_code(&form.code).unwrap_or(false))
|
||||
{
|
||||
logger.log(Action::OTPLoginAttempt {
|
||||
success: false,
|
||||
user: &user,
|
||||
});
|
||||
danger = Some("Specified code is invalid!".to_string());
|
||||
} else {
|
||||
users
|
||||
.send(users_actor::AddSuccessful2FALogin(user.uid, remote_ip.0))
|
||||
.send(users_actor::AddSuccessful2FALogin(
|
||||
user.uid.clone(),
|
||||
remote_ip.0,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
SessionIdentity(id.as_ref()).set_status(&http_req, SessionStatus::SignedIn);
|
||||
let session = SessionIdentity(id.as_ref());
|
||||
session.record_2fa_auth(&http_req);
|
||||
session.set_status(&http_req, SessionStatus::SignedIn);
|
||||
logger.log(Action::OTPLoginAttempt {
|
||||
success: true,
|
||||
user: &user,
|
||||
});
|
||||
return redirect_user(query.redirect.get());
|
||||
}
|
||||
}
|
||||
|
||||
HttpResponse::Ok().body(
|
||||
LoginWithOTPTemplate {
|
||||
_p: BaseLoginPage {
|
||||
p: BaseLoginPage {
|
||||
danger,
|
||||
success: None,
|
||||
page_title: "Two-Factor Auth",
|
||||
@@ -393,8 +445,9 @@ pub async fn login_with_webauthn(
|
||||
query: web::Query<LoginWithWebauthnQuery>,
|
||||
manager: WebAuthManagerReq,
|
||||
users: web::Data<Addr<UsersActor>>,
|
||||
force2faauth: Force2FAAuth,
|
||||
) -> impl Responder {
|
||||
if !SessionIdentity(id.as_ref()).need_2fa_auth() {
|
||||
if !SessionIdentity(id.as_ref()).need_2fa_auth() && !force2faauth.force {
|
||||
return redirect_user_for_login(query.redirect.get());
|
||||
}
|
||||
|
||||
@@ -416,7 +469,7 @@ pub async fn login_with_webauthn(
|
||||
let challenge = match manager.start_authentication(&user.uid, &pub_keys) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
log::error!("Failed to generate webauthn challenge! {:?}", e);
|
||||
log::error!("Failed to generate webauthn challenge! {e:?}");
|
||||
return HttpResponse::InternalServerError().body(build_fatal_error_page(
|
||||
"Failed to generate webauthn challenge",
|
||||
));
|
||||
@@ -426,14 +479,14 @@ pub async fn login_with_webauthn(
|
||||
let challenge_json = match serde_json::to_string(&challenge.login_challenge) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
log::error!("Failed to serialize challenge! {:?}", e);
|
||||
log::error!("Failed to serialize challenge! {e:?}");
|
||||
return HttpResponse::InternalServerError().body("Failed to serialize challenge!");
|
||||
}
|
||||
};
|
||||
|
||||
HttpResponse::Ok().body(
|
||||
LoginWithWebauthnTemplate {
|
||||
_p: BaseLoginPage {
|
||||
p: BaseLoginPage {
|
||||
danger: None,
|
||||
success: None,
|
||||
page_title: "Two-Factor Auth",
|
||||
|
@@ -5,6 +5,7 @@ pub mod base_controller;
|
||||
pub mod login_api;
|
||||
pub mod login_controller;
|
||||
pub mod openid_controller;
|
||||
pub mod providers_controller;
|
||||
pub mod settings_controller;
|
||||
pub mod two_factor_api;
|
||||
pub mod two_factors_controller;
|
||||
|
@@ -1,23 +1,28 @@
|
||||
use std::fmt::Debug;
|
||||
use std::sync::Arc;
|
||||
|
||||
use actix::Addr;
|
||||
use actix_identity::Identity;
|
||||
use actix_web::error::ErrorUnauthorized;
|
||||
use actix_web::{web, HttpRequest, HttpResponse, Responder};
|
||||
use actix_web::{HttpRequest, HttpResponse, Responder, web};
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
|
||||
use light_openid::primitives::{OpenIDConfig, OpenIDTokenResponse, OpenIDUserInfo};
|
||||
|
||||
use crate::actors::openid_sessions_actor::{OpenIDSessionsActor, Session, SessionID};
|
||||
use crate::actors::users_actor::UsersActor;
|
||||
use crate::actors::{openid_sessions_actor, users_actor};
|
||||
use crate::constants::*;
|
||||
use crate::controllers::base_controller::build_fatal_error_page;
|
||||
use crate::controllers::base_controller::{build_fatal_error_page, redirect_user};
|
||||
use crate::data::action_logger::{Action, ActionLogger};
|
||||
use crate::data::app_config::AppConfig;
|
||||
use crate::data::client::{ClientID, ClientManager};
|
||||
use crate::data::client::{AdditionalClaims, ClientID, ClientManager};
|
||||
use crate::data::code_challenge::CodeChallenge;
|
||||
use crate::data::current_user::CurrentUser;
|
||||
use crate::data::id_token::IdToken;
|
||||
use crate::data::jwt_signer::{JWTSigner, JsonWebKey};
|
||||
use crate::data::open_id_user_info::OpenIDUserInfo;
|
||||
use crate::data::openid_config::OpenIDConfig;
|
||||
use crate::data::login_redirect::{LoginRedirect, get_2fa_url};
|
||||
|
||||
use crate::data::session_identity::SessionIdentity;
|
||||
use crate::data::user::User;
|
||||
use crate::utils::string_utils::rand_str;
|
||||
@@ -27,6 +32,7 @@ pub async fn get_configuration(req: HttpRequest) -> impl Responder {
|
||||
let is_secure_request = req
|
||||
.headers()
|
||||
.get("HTTP_X_FORWARDED_PROTO")
|
||||
.or_else(|| req.headers().get("X-Forwarded-Proto"))
|
||||
.map(|v| v.to_str().unwrap_or_default().to_lowercase().eq("https"))
|
||||
.unwrap_or(false);
|
||||
|
||||
@@ -44,20 +50,39 @@ pub async fn get_configuration(req: HttpRequest) -> impl Responder {
|
||||
host
|
||||
);
|
||||
|
||||
HttpResponse::Ok().json(OpenIDConfig {
|
||||
issuer: AppConfig::get().website_origin.clone(),
|
||||
authorization_endpoint: AppConfig::get().full_url(AUTHORIZE_URI),
|
||||
token_endpoint: curr_origin.clone() + TOKEN_URI,
|
||||
userinfo_endpoint: curr_origin.clone() + USERINFO_URI,
|
||||
jwks_uri: curr_origin + CERT_URI,
|
||||
scopes_supported: vec!["openid", "profile", "email"],
|
||||
response_types_supported: vec!["code", "id_token", "token id_token"],
|
||||
subject_types_supported: vec!["public"],
|
||||
id_token_signing_alg_values_supported: vec!["RS256"],
|
||||
token_endpoint_auth_methods_supported: vec!["client_secret_post", "client_secret_basic"],
|
||||
claims_supported: vec!["sub", "name", "given_name", "family_name", "email"],
|
||||
code_challenge_methods_supported: vec!["plain", "S256"],
|
||||
})
|
||||
HttpResponse::Ok()
|
||||
.insert_header(("access-control-allow-origin", "*"))
|
||||
.json(OpenIDConfig {
|
||||
issuer: AppConfig::get().website_origin.clone(),
|
||||
authorization_endpoint: AppConfig::get().full_url(AUTHORIZE_URI),
|
||||
token_endpoint: curr_origin.clone() + TOKEN_URI,
|
||||
userinfo_endpoint: Some(curr_origin.clone() + USERINFO_URI),
|
||||
jwks_uri: curr_origin + CERT_URI,
|
||||
scopes_supported: Some(vec![
|
||||
"openid".to_string(),
|
||||
"profile".to_string(),
|
||||
"email".to_string(),
|
||||
]),
|
||||
response_types_supported: vec![
|
||||
"code".to_string(),
|
||||
"id_token".to_string(),
|
||||
"token id_token".to_string(),
|
||||
],
|
||||
subject_types_supported: vec!["public".to_string()],
|
||||
id_token_signing_alg_values_supported: vec!["RS256".to_string()],
|
||||
token_endpoint_auth_methods_supported: Some(vec![
|
||||
"client_secret_post".to_string(),
|
||||
"client_secret_basic".to_string(),
|
||||
]),
|
||||
claims_supported: Some(vec![
|
||||
"sub".to_string(),
|
||||
"name".to_string(),
|
||||
"given_name".to_string(),
|
||||
"family_name".to_string(),
|
||||
"email".to_string(),
|
||||
]),
|
||||
code_challenge_methods_supported: Some(vec!["plain".to_string(), "S256".to_string()]),
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, Debug)]
|
||||
@@ -75,7 +100,7 @@ pub struct AuthorizeQuery {
|
||||
redirect_uri: String,
|
||||
|
||||
/// RECOMMENDED. Opaque value used to maintain state between the request and the callback. Typically, Cross-Site Request Forgery (CSRF, XSRF) mitigation is done by cryptographically binding the value of this parameter with a browser cookie.
|
||||
state: String,
|
||||
state: Option<String>,
|
||||
|
||||
/// OPTIONAL. String value used to associate a Client session with an ID Token, and to mitigate replay attacks. The value is passed through unmodified from the Authentication Request to the ID Token. Sufficient entropy MUST be present in the nonce values used to prevent attackers from guessing values.
|
||||
nonce: Option<String>,
|
||||
@@ -86,70 +111,83 @@ pub struct AuthorizeQuery {
|
||||
}
|
||||
|
||||
fn error_redirect(query: &AuthorizeQuery, error: &str, description: &str) -> HttpResponse {
|
||||
log::warn!(
|
||||
"Failed to process sign in request ({} => {}): {:?}",
|
||||
error,
|
||||
description,
|
||||
query
|
||||
);
|
||||
log::warn!("Failed to process sign in request ({error} => {description}): {query:?}");
|
||||
HttpResponse::Found()
|
||||
.append_header((
|
||||
"Location",
|
||||
format!(
|
||||
"{}?error={}?error_description={}&state={}",
|
||||
"{}?error={}?error_description={}{}",
|
||||
query.redirect_uri,
|
||||
urlencoding::encode(error),
|
||||
urlencoding::encode(description),
|
||||
urlencoding::encode(&query.state)
|
||||
match &query.state {
|
||||
Some(s) => format!("&state={}", urlencoding::encode(s)),
|
||||
None => "".to_string(),
|
||||
}
|
||||
),
|
||||
))
|
||||
.finish()
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn authorize(
|
||||
req: HttpRequest,
|
||||
user: CurrentUser,
|
||||
id: Identity,
|
||||
query: web::Query<AuthorizeQuery>,
|
||||
clients: web::Data<ClientManager>,
|
||||
clients: web::Data<Arc<ClientManager>>,
|
||||
sessions: web::Data<Addr<OpenIDSessionsActor>>,
|
||||
) -> impl Responder {
|
||||
logger: ActionLogger,
|
||||
jwt_signer: web::Data<JWTSigner>,
|
||||
) -> actix_web::Result<HttpResponse> {
|
||||
let client = match clients.find_by_id(&query.client_id) {
|
||||
None => {
|
||||
return HttpResponse::BadRequest().body(build_fatal_error_page("Client is invalid!"));
|
||||
return Ok(
|
||||
HttpResponse::BadRequest().body(build_fatal_error_page("Client is invalid!"))
|
||||
);
|
||||
}
|
||||
Some(c) => c,
|
||||
};
|
||||
|
||||
// Check if 2FA is required
|
||||
if client.enforce_2fa_auth && user.should_request_2fa_for_critical_functions() {
|
||||
let uri = get_2fa_url(&LoginRedirect::from_req(&req), true);
|
||||
return Ok(redirect_user(&uri));
|
||||
}
|
||||
|
||||
// Validate specified redirect URI
|
||||
let redirect_uri = query.redirect_uri.trim().to_string();
|
||||
if !redirect_uri.starts_with(&client.redirect_uri) {
|
||||
return HttpResponse::BadRequest().body(build_fatal_error_page("Redirect URI is invalid!"));
|
||||
}
|
||||
|
||||
if !query.scope.split(' ').any(|x| x == "openid") {
|
||||
return error_redirect(&query, "invalid_request", "openid scope missing!");
|
||||
}
|
||||
|
||||
if !query.response_type.eq("code") {
|
||||
return error_redirect(
|
||||
&query,
|
||||
"invalid_request",
|
||||
"Only code response type is supported!",
|
||||
return Ok(
|
||||
HttpResponse::BadRequest().body(build_fatal_error_page("Redirect URI is invalid!"))
|
||||
);
|
||||
}
|
||||
|
||||
if query.state.is_empty() {
|
||||
return error_redirect(&query, "invalid_request", "State is empty!");
|
||||
if !query.scope.split(' ').any(|x| x == "openid") {
|
||||
return Ok(error_redirect(
|
||||
&query,
|
||||
"invalid_request",
|
||||
"openid scope missing!",
|
||||
));
|
||||
}
|
||||
|
||||
if query.state.as_ref().map(String::is_empty).unwrap_or(false) {
|
||||
return Ok(error_redirect(
|
||||
&query,
|
||||
"invalid_request",
|
||||
"State is specified but empty!",
|
||||
));
|
||||
}
|
||||
|
||||
let code_challenge = match query.0.code_challenge.clone() {
|
||||
Some(chal) => {
|
||||
let meth = query.0.code_challenge_method.as_deref().unwrap_or("plain");
|
||||
if !meth.eq("S256") && !meth.eq("plain") {
|
||||
return error_redirect(
|
||||
return Ok(error_redirect(
|
||||
&query,
|
||||
"invalid_request",
|
||||
"Only S256 and plain code challenge methods are supported!",
|
||||
);
|
||||
));
|
||||
}
|
||||
Some(CodeChallenge {
|
||||
code_challenge: chal,
|
||||
@@ -160,49 +198,113 @@ pub async fn authorize(
|
||||
};
|
||||
|
||||
// Check if user is authorized to access the application
|
||||
if !user.can_access_app(&client.id) {
|
||||
return error_redirect(
|
||||
if !user.can_access_app(&client) {
|
||||
return Ok(error_redirect(
|
||||
&query,
|
||||
"invalid_request",
|
||||
"User is not authorized to access this application!",
|
||||
);
|
||||
));
|
||||
}
|
||||
|
||||
// Save all authentication information in memory
|
||||
let session = Session {
|
||||
session_id: SessionID(rand_str(OPEN_ID_SESSION_LEN)),
|
||||
client: client.id,
|
||||
user: user.uid.clone(),
|
||||
auth_time: SessionIdentity(Some(&id)).auth_time(),
|
||||
redirect_uri,
|
||||
authorization_code: rand_str(OPEN_ID_AUTHORIZATION_CODE_LEN),
|
||||
authorization_code_expire_at: time() + OPEN_ID_AUTHORIZATION_CODE_TIMEOUT,
|
||||
access_token: None,
|
||||
access_token_expire_at: time() + OPEN_ID_ACCESS_TOKEN_TIMEOUT,
|
||||
refresh_token: "".to_string(),
|
||||
refresh_token_expire_at: 0,
|
||||
nonce: query.0.nonce,
|
||||
code_challenge,
|
||||
};
|
||||
sessions
|
||||
.send(openid_sessions_actor::PushNewSession(session.clone()))
|
||||
.await
|
||||
.unwrap();
|
||||
// Check that requested authorization flow is supported
|
||||
if query.response_type != "code" && query.response_type != "id_token" {
|
||||
return Ok(error_redirect(
|
||||
&query,
|
||||
"invalid_request",
|
||||
"Unsupported authorization flow!",
|
||||
));
|
||||
}
|
||||
|
||||
log::trace!("New OpenID session: {:#?}", session);
|
||||
match (client.has_secret(), query.response_type.as_str()) {
|
||||
(_, "code") => {
|
||||
// Save all authentication information in memory
|
||||
let session = Session {
|
||||
session_id: SessionID(rand_str(OPEN_ID_SESSION_LEN)),
|
||||
client: client.id.clone(),
|
||||
user: user.uid.clone(),
|
||||
auth_time: SessionIdentity(Some(&id)).auth_time(),
|
||||
redirect_uri,
|
||||
authorization_code: rand_str(OPEN_ID_AUTHORIZATION_CODE_LEN),
|
||||
authorization_code_expire_at: time() + OPEN_ID_AUTHORIZATION_CODE_TIMEOUT,
|
||||
access_token: None,
|
||||
access_token_expire_at: time() + OPEN_ID_ACCESS_TOKEN_TIMEOUT,
|
||||
refresh_token: "".to_string(),
|
||||
refresh_token_expire_at: 0,
|
||||
nonce: query.0.nonce,
|
||||
code_challenge,
|
||||
};
|
||||
sessions
|
||||
.send(openid_sessions_actor::PushNewSession(session.clone()))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
HttpResponse::Found()
|
||||
.append_header((
|
||||
"Location",
|
||||
format!(
|
||||
"{}?state={}&session_state={}&code={}",
|
||||
session.redirect_uri,
|
||||
urlencoding::encode(&query.0.state),
|
||||
urlencoding::encode(&session.session_id.0),
|
||||
urlencoding::encode(&session.authorization_code)
|
||||
),
|
||||
))
|
||||
.finish()
|
||||
log::trace!("New OpenID session: {session:#?}");
|
||||
logger.log(Action::NewOpenIDSession { client: &client });
|
||||
|
||||
Ok(HttpResponse::Found()
|
||||
.append_header((
|
||||
"Location",
|
||||
format!(
|
||||
"{}?{}session_state={}&code={}",
|
||||
session.redirect_uri,
|
||||
match &query.0.state {
|
||||
Some(state) => format!("state={}&", urlencoding::encode(state)),
|
||||
None => "".to_string(),
|
||||
},
|
||||
urlencoding::encode(&session.session_id.0),
|
||||
urlencoding::encode(&session.authorization_code)
|
||||
),
|
||||
))
|
||||
.finish())
|
||||
}
|
||||
|
||||
// id_token is available only if user has no secret configured
|
||||
(false, "id_token") => {
|
||||
let id_token = IdToken {
|
||||
issuer: AppConfig::get().website_origin.to_string(),
|
||||
subject_identifier: user.uid.0.clone(),
|
||||
audience: client.id.0.to_string(),
|
||||
expiration_time: time() + OPEN_ID_ID_TOKEN_TIMEOUT,
|
||||
issued_at: time(),
|
||||
auth_time: SessionIdentity(Some(&id)).auth_time(),
|
||||
nonce: query.nonce.clone(),
|
||||
email: user.email.clone(),
|
||||
additional_claims: client.claims_id_token(&user),
|
||||
};
|
||||
|
||||
log::trace!("New OpenID id token: {:#?}", &id_token);
|
||||
logger.log(Action::NewOpenIDSuccessfulImplicitAuth { client: &client });
|
||||
|
||||
Ok(HttpResponse::Found()
|
||||
.append_header((
|
||||
"Location",
|
||||
format!(
|
||||
"{}?{}token_type=bearer&id_token={}&expires_in={OPEN_ID_ID_TOKEN_TIMEOUT}",
|
||||
client.redirect_uri,
|
||||
match &query.0.state {
|
||||
Some(state) => format!("state={}&", urlencoding::encode(state)),
|
||||
None => "".to_string(),
|
||||
},
|
||||
jwt_signer.sign_token(id_token.to_jwt_claims())?
|
||||
),
|
||||
))
|
||||
.finish())
|
||||
}
|
||||
|
||||
(secret, code) => {
|
||||
log::warn!(
|
||||
"For client {:?}, configured with secret {:?}, made request with code {}",
|
||||
client.id,
|
||||
secret,
|
||||
code
|
||||
);
|
||||
Ok(error_redirect(
|
||||
&query,
|
||||
"invalid_request",
|
||||
"Requested authentication flow is unsupported / not configured for this client!",
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
@@ -212,12 +314,7 @@ struct ErrorResponse {
|
||||
}
|
||||
|
||||
pub fn error_response<D: Debug>(query: &D, error: &str, description: &str) -> HttpResponse {
|
||||
log::warn!(
|
||||
"request failed: {} - {} => '{:#?}'",
|
||||
error,
|
||||
description,
|
||||
query
|
||||
);
|
||||
log::warn!("request failed: {error} - {description} => '{query:#?}'");
|
||||
HttpResponse::BadRequest().json(ErrorResponse {
|
||||
error: error.to_string(),
|
||||
error_description: description.to_string(),
|
||||
@@ -249,20 +346,10 @@ pub struct TokenQuery {
|
||||
refresh_token_query: Option<TokenRefreshTokenQuery>,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Serialize)]
|
||||
pub struct TokenResponse {
|
||||
access_token: String,
|
||||
token_type: &'static str,
|
||||
refresh_token: String,
|
||||
expires_in: u64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
id_token: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn token(
|
||||
req: HttpRequest,
|
||||
query: web::Form<TokenQuery>,
|
||||
clients: web::Data<ClientManager>,
|
||||
clients: web::Data<Arc<ClientManager>>,
|
||||
sessions: web::Data<Addr<OpenIDSessionsActor>>,
|
||||
users: web::Data<Addr<UsersActor>>,
|
||||
jwt_signer: web::Data<JWTSigner>,
|
||||
@@ -272,30 +359,27 @@ pub async fn token(
|
||||
let (client_id, client_secret) =
|
||||
match (&query.client_id, &query.client_secret, authorization_header) {
|
||||
// post authentication
|
||||
(Some(client_id), Some(client_secret), None) => {
|
||||
(client_id.clone(), client_secret.to_string())
|
||||
}
|
||||
(Some(client_id), client_secret, None) => (client_id.clone(), client_secret.clone()),
|
||||
|
||||
// Basic authentication
|
||||
(None, None, Some(v)) => {
|
||||
(_, None, Some(v)) => {
|
||||
let token = match v.to_str().unwrap_or_default().strip_prefix("Basic ") {
|
||||
None => {
|
||||
return Ok(error_response(
|
||||
&query,
|
||||
"invalid_request",
|
||||
&format!(
|
||||
"Authorization header does not start with 'Basic ', got '{:#?}'",
|
||||
v
|
||||
"Authorization header does not start with 'Basic ', got '{v:#?}'"
|
||||
),
|
||||
));
|
||||
}
|
||||
Some(v) => v,
|
||||
};
|
||||
|
||||
let decode = String::from_utf8_lossy(&match base64::decode(token) {
|
||||
let decode = String::from_utf8_lossy(&match BASE64_STANDARD.decode(token) {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
log::error!("Failed to decode authorization header: {:?}", e);
|
||||
log::error!("Failed to decode authorization header: {e:?}");
|
||||
return Ok(error_response(
|
||||
&query,
|
||||
"invalid_request",
|
||||
@@ -306,8 +390,8 @@ pub async fn token(
|
||||
.to_string();
|
||||
|
||||
match decode.split_once(':') {
|
||||
None => (ClientID(decode), "".to_string()),
|
||||
Some((id, secret)) => (ClientID(id.to_string()), secret.to_string()),
|
||||
None => (ClientID(decode), None),
|
||||
Some((id, secret)) => (ClientID(id.to_string()), Some(secret.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -315,7 +399,7 @@ pub async fn token(
|
||||
return Ok(error_response(
|
||||
&query,
|
||||
"invalid_request",
|
||||
"Authentication method unknown!",
|
||||
"Client authentication method on token endpoint unsupported!",
|
||||
));
|
||||
}
|
||||
};
|
||||
@@ -324,7 +408,8 @@ pub async fn token(
|
||||
.find_by_id(&client_id)
|
||||
.ok_or_else(|| ErrorUnauthorized("Client not found"))?;
|
||||
|
||||
if !client.secret.eq(&client_secret) {
|
||||
// Retrieving token requires the client to have a defined secret
|
||||
if client.secret != client_secret {
|
||||
return Ok(error_response(
|
||||
&query,
|
||||
"invalid_request",
|
||||
@@ -441,14 +526,15 @@ pub async fn token(
|
||||
issued_at: time(),
|
||||
auth_time: session.auth_time,
|
||||
nonce: session.nonce,
|
||||
email: user.email,
|
||||
email: user.email.to_string(),
|
||||
additional_claims: client.claims_id_token(&user),
|
||||
};
|
||||
|
||||
TokenResponse {
|
||||
OpenIDTokenResponse {
|
||||
access_token: session.access_token.expect("Missing access token!"),
|
||||
token_type: "Bearer",
|
||||
refresh_token: session.refresh_token,
|
||||
expires_in: session.access_token_expire_at - time(),
|
||||
token_type: "Bearer".to_string(),
|
||||
refresh_token: Some(session.refresh_token),
|
||||
expires_in: Some(session.access_token_expire_at - time()),
|
||||
id_token: Some(jwt_signer.sign_token(id_token.to_jwt_claims())?),
|
||||
}
|
||||
}
|
||||
@@ -494,11 +580,11 @@ pub async fn token(
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
TokenResponse {
|
||||
OpenIDTokenResponse {
|
||||
access_token: session.access_token.expect("Missing access token!"),
|
||||
token_type: "Bearer",
|
||||
refresh_token: session.refresh_token,
|
||||
expires_in: session.access_token_expire_at - time(),
|
||||
token_type: "Bearer".to_string(),
|
||||
refresh_token: Some(session.refresh_token),
|
||||
expires_in: Some(session.access_token_expire_at - time()),
|
||||
id_token: None,
|
||||
}
|
||||
}
|
||||
@@ -513,8 +599,9 @@ pub async fn token(
|
||||
};
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.append_header(("Cache-Control", "no-store"))
|
||||
.append_header(("Pragam", "no-cache"))
|
||||
.insert_header(("Cache-Control", "no-store"))
|
||||
.insert_header(("Pragma", "no-cache"))
|
||||
.insert_header(("access-control-allow-origin", "*"))
|
||||
.json(token_response))
|
||||
}
|
||||
|
||||
@@ -533,10 +620,7 @@ fn user_info_error(err: &str, description: &str) -> HttpResponse {
|
||||
HttpResponse::Unauthorized()
|
||||
.insert_header((
|
||||
"WWW-Authenticate",
|
||||
format!(
|
||||
"Bearer error=\"{}\", error_description=\"{}\"",
|
||||
err, description
|
||||
),
|
||||
format!("Bearer error=\"{err}\", error_description=\"{description}\""),
|
||||
))
|
||||
.finish()
|
||||
}
|
||||
@@ -552,6 +636,7 @@ pub async fn user_info_post(
|
||||
query: web::Query<UserInfoQuery>,
|
||||
sessions: web::Data<Addr<OpenIDSessionsActor>>,
|
||||
users: web::Data<Addr<UsersActor>>,
|
||||
clients: web::Data<Arc<ClientManager>>,
|
||||
) -> impl Responder {
|
||||
user_info(
|
||||
req,
|
||||
@@ -560,6 +645,7 @@ pub async fn user_info_post(
|
||||
.or(query.0.access_token),
|
||||
sessions,
|
||||
users,
|
||||
clients,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -569,8 +655,18 @@ pub async fn user_info_get(
|
||||
query: web::Query<UserInfoQuery>,
|
||||
sessions: web::Data<Addr<OpenIDSessionsActor>>,
|
||||
users: web::Data<Addr<UsersActor>>,
|
||||
clients: web::Data<Arc<ClientManager>>,
|
||||
) -> impl Responder {
|
||||
user_info(req, query.0.access_token, sessions, users).await
|
||||
user_info(req, query.0.access_token, sessions, users, clients).await
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
pub struct UserInfoWithCustomClaims {
|
||||
#[serde(flatten)]
|
||||
info: OpenIDUserInfo,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(flatten)]
|
||||
additional_claims: Option<AdditionalClaims>,
|
||||
}
|
||||
|
||||
/// Authenticate request using RFC6750 <https://datatracker.ietf.org/doc/html/rfc6750>///
|
||||
@@ -579,6 +675,7 @@ async fn user_info(
|
||||
token: Option<String>,
|
||||
sessions: web::Data<Addr<OpenIDSessionsActor>>,
|
||||
users: web::Data<Addr<UsersActor>>,
|
||||
clients: web::Data<Arc<ClientManager>>,
|
||||
) -> impl Responder {
|
||||
let token = match token {
|
||||
Some(t) => t,
|
||||
@@ -598,7 +695,7 @@ async fn user_info(
|
||||
return user_info_error(
|
||||
"invalid_request",
|
||||
"Header token does not start with 'Bearer '!",
|
||||
)
|
||||
);
|
||||
}
|
||||
Some(t) => t,
|
||||
};
|
||||
@@ -622,6 +719,10 @@ async fn user_info(
|
||||
return user_info_error("invalid_request", "Access token has expired!");
|
||||
}
|
||||
|
||||
let client = clients
|
||||
.find_by_id(&session.client)
|
||||
.expect("Could not extract client information!");
|
||||
|
||||
let user: Option<User> = users
|
||||
.send(users_actor::GetUserRequest(session.user))
|
||||
.await
|
||||
@@ -634,13 +735,16 @@ async fn user_info(
|
||||
Some(u) => u,
|
||||
};
|
||||
|
||||
HttpResponse::Ok().json(OpenIDUserInfo {
|
||||
name: user.full_name(),
|
||||
sub: user.uid.0,
|
||||
given_name: user.first_name,
|
||||
family_name: user.last_name,
|
||||
preferred_username: user.username,
|
||||
email: user.email,
|
||||
email_verified: true,
|
||||
HttpResponse::Ok().json(UserInfoWithCustomClaims {
|
||||
info: OpenIDUserInfo {
|
||||
name: Some(user.full_name()),
|
||||
sub: user.uid.0.to_string(),
|
||||
given_name: Some(user.first_name.to_string()),
|
||||
family_name: Some(user.last_name.to_string()),
|
||||
preferred_username: Some(user.username.to_string()),
|
||||
email: Some(user.email.to_string()),
|
||||
email_verified: Some(true),
|
||||
},
|
||||
additional_claims: client.claims_user_info(&user),
|
||||
})
|
||||
}
|
||||
|
373
src/controllers/providers_controller.rs
Normal file
373
src/controllers/providers_controller.rs
Normal file
@@ -0,0 +1,373 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use actix::Addr;
|
||||
use actix_identity::Identity;
|
||||
use actix_remote_ip::RemoteIP;
|
||||
use actix_web::{HttpRequest, HttpResponse, Responder, web};
|
||||
use askama::Template;
|
||||
|
||||
use crate::actors::bruteforce_actor::BruteForceActor;
|
||||
use crate::actors::providers_states_actor::{ProviderLoginState, ProvidersStatesActor};
|
||||
use crate::actors::users_actor::{LoginResult, UsersActor};
|
||||
use crate::actors::{bruteforce_actor, providers_states_actor, users_actor};
|
||||
use crate::constants::{APP_NAME, MAX_FAILED_LOGIN_ATTEMPTS};
|
||||
use crate::controllers::base_controller::{build_fatal_error_page, redirect_user};
|
||||
use crate::controllers::login_controller::BaseLoginPage;
|
||||
use crate::data::action_logger::{Action, ActionLogger};
|
||||
use crate::data::login_redirect::LoginRedirect;
|
||||
use crate::data::provider::{ProviderID, ProvidersManager};
|
||||
use crate::data::provider_configuration::ProviderConfigurationHelper;
|
||||
use crate::data::session_identity::{SessionIdentity, SessionStatus};
|
||||
|
||||
#[derive(askama::Template)]
|
||||
#[template(path = "login/prov_login_error.html")]
|
||||
struct ProviderLoginError<'a> {
|
||||
p: BaseLoginPage<'a>,
|
||||
message: &'a str,
|
||||
}
|
||||
|
||||
impl<'a> ProviderLoginError<'a> {
|
||||
pub fn get(message: &'a str, redirect_uri: &'a LoginRedirect) -> HttpResponse {
|
||||
let body = Self {
|
||||
p: BaseLoginPage {
|
||||
danger: None,
|
||||
success: None,
|
||||
page_title: "Upstream login",
|
||||
app_name: APP_NAME,
|
||||
redirect_uri,
|
||||
},
|
||||
message,
|
||||
}
|
||||
.render()
|
||||
.unwrap();
|
||||
|
||||
HttpResponse::Unauthorized()
|
||||
.content_type("text/html")
|
||||
.body(body)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
pub struct StartLoginQuery {
|
||||
#[serde(default)]
|
||||
redirect: LoginRedirect,
|
||||
id: ProviderID,
|
||||
}
|
||||
|
||||
/// Start user authentication using a provider
|
||||
pub async fn start_login(
|
||||
remote_ip: RemoteIP,
|
||||
providers: web::Data<Arc<ProvidersManager>>,
|
||||
states: web::Data<Addr<ProvidersStatesActor>>,
|
||||
query: web::Query<StartLoginQuery>,
|
||||
logger: ActionLogger,
|
||||
id: Option<Identity>,
|
||||
) -> impl Responder {
|
||||
// Check if user is already authenticated
|
||||
if SessionIdentity(id.as_ref()).is_authenticated() {
|
||||
return redirect_user(query.redirect.get());
|
||||
}
|
||||
|
||||
// Get provider information
|
||||
let provider = match providers.find_by_id(&query.id) {
|
||||
None => {
|
||||
return HttpResponse::NotFound()
|
||||
.body(build_fatal_error_page("Login provider not found!"));
|
||||
}
|
||||
Some(p) => p,
|
||||
};
|
||||
|
||||
// Generate & save state
|
||||
let state = ProviderLoginState::new(&provider.id, query.redirect.clone());
|
||||
states
|
||||
.send(providers_states_actor::RecordState {
|
||||
ip: remote_ip.0,
|
||||
state: state.clone(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
logger.log(Action::StartLoginAttemptWithOpenIDProvider {
|
||||
provider_id: &provider.id,
|
||||
state: &state.state_id,
|
||||
});
|
||||
|
||||
// Get provider configuration
|
||||
let config = match ProviderConfigurationHelper::get_configuration(&provider).await {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
log::error!("Failed to load provider configuration! {e}");
|
||||
return HttpResponse::InternalServerError().body(build_fatal_error_page(
|
||||
"Failed to load provider configuration!",
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
log::debug!("Provider configuration: {config:?}");
|
||||
|
||||
let url = config.auth_url(&provider, &state);
|
||||
log::debug!("Redirect user on {url} for authentication",);
|
||||
|
||||
// Redirect user
|
||||
redirect_user(&url)
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
pub struct FinishLoginSuccess {
|
||||
code: String,
|
||||
state: String,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
pub struct FinishLoginError {
|
||||
error: String,
|
||||
error_description: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
pub struct FinishLoginQuery {
|
||||
#[serde(flatten)]
|
||||
success: Option<FinishLoginSuccess>,
|
||||
#[serde(flatten)]
|
||||
error: Option<FinishLoginError>,
|
||||
}
|
||||
|
||||
/// Finish user authentication using a provider
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn finish_login(
|
||||
remote_ip: RemoteIP,
|
||||
providers: web::Data<Arc<ProvidersManager>>,
|
||||
users: web::Data<Addr<UsersActor>>,
|
||||
states: web::Data<Addr<ProvidersStatesActor>>,
|
||||
bruteforce: web::Data<Addr<BruteForceActor>>,
|
||||
query: web::Query<FinishLoginQuery>,
|
||||
logger: ActionLogger,
|
||||
id: Option<Identity>,
|
||||
http_req: HttpRequest,
|
||||
) -> impl Responder {
|
||||
// Check if user is already authenticated
|
||||
if SessionIdentity(id.as_ref()).is_authenticated() {
|
||||
return redirect_user("/");
|
||||
}
|
||||
|
||||
let query = match query.0.success {
|
||||
Some(q) => q,
|
||||
None => {
|
||||
let error_message = query
|
||||
.0
|
||||
.error
|
||||
.map(|e| e.error_description.unwrap_or(e.error))
|
||||
.unwrap_or("Authentication failed (unspecified error)!".to_string());
|
||||
|
||||
logger.log(Action::ProviderError {
|
||||
message: error_message.as_str(),
|
||||
});
|
||||
|
||||
return ProviderLoginError::get(&error_message, &LoginRedirect::default());
|
||||
}
|
||||
};
|
||||
|
||||
// Get & consume state
|
||||
let state = states
|
||||
.send(providers_states_actor::ConsumeState {
|
||||
ip: remote_ip.0,
|
||||
state_id: query.state.clone(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let state = match state {
|
||||
Some(s) => s,
|
||||
None => {
|
||||
logger.log(Action::ProviderCBInvalidState {
|
||||
state: query.state.as_str(),
|
||||
});
|
||||
log::warn!("User returned invalid state!");
|
||||
return ProviderLoginError::get("Invalid state!", &LoginRedirect::default());
|
||||
}
|
||||
};
|
||||
|
||||
// We perform rate limiting before attempting to use authorization code
|
||||
let failed_attempts = bruteforce
|
||||
.send(bruteforce_actor::CountFailedAttempt {
|
||||
ip: remote_ip.into(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
if failed_attempts > MAX_FAILED_LOGIN_ATTEMPTS {
|
||||
logger.log(Action::ProviderRateLimited);
|
||||
return HttpResponse::TooManyRequests().body(build_fatal_error_page(
|
||||
"Too many failed login attempts, please try again later!",
|
||||
));
|
||||
}
|
||||
|
||||
// Retrieve provider information & configuration
|
||||
let provider = providers
|
||||
.find_by_id(&state.provider_id)
|
||||
.expect("Unable to retrieve provider information!");
|
||||
|
||||
let provider_config = match ProviderConfigurationHelper::get_configuration(&provider).await {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
log::error!("Failed to load provider configuration! {e}");
|
||||
return HttpResponse::InternalServerError().body(build_fatal_error_page(
|
||||
"Failed to load provider configuration!",
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
// Get access token & user information
|
||||
let token = provider_config.get_token(&provider, &query.code).await;
|
||||
let token = match token {
|
||||
Ok(t) => t,
|
||||
Err(e) => {
|
||||
log::error!("Failed to retrieve login token! {e:?}");
|
||||
|
||||
bruteforce
|
||||
.send(bruteforce_actor::RecordFailedAttempt {
|
||||
ip: remote_ip.into(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
logger.log(Action::ProviderFailedGetToken {
|
||||
state: &state,
|
||||
code: query.code.as_str(),
|
||||
});
|
||||
|
||||
return ProviderLoginError::get(
|
||||
"Failed to retrieve login token from identity provider!",
|
||||
&state.redirect,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// Use access token to get user information
|
||||
let user_info = match provider_config.get_userinfo(&token).await {
|
||||
Ok(info) => info,
|
||||
Err(e) => {
|
||||
log::error!("Failed to retrieve user information! {e:?}");
|
||||
|
||||
logger.log(Action::ProviderFailedGetUserInfo {
|
||||
provider: &provider,
|
||||
});
|
||||
|
||||
return ProviderLoginError::get(
|
||||
"Failed to retrieve user information from identity provider!",
|
||||
&state.redirect,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// Check if user email is validated
|
||||
if user_info.email_verified == Some(false) {
|
||||
logger.log(Action::ProviderEmailNotValidated {
|
||||
provider: &provider,
|
||||
});
|
||||
return ProviderLoginError::get(
|
||||
&format!(
|
||||
"{} indicated that your email address has not been validated!",
|
||||
provider.name
|
||||
),
|
||||
&state.redirect,
|
||||
);
|
||||
}
|
||||
|
||||
// Check if email was provided by the userinfo endpoint
|
||||
let email = match user_info.email {
|
||||
Some(e) => e,
|
||||
None => {
|
||||
logger.log(Action::ProviderMissingEmailInResponse {
|
||||
provider: &provider,
|
||||
});
|
||||
return ProviderLoginError::get(
|
||||
&format!(
|
||||
"{} did not provide your email address in its reply, so we could not identify you!",
|
||||
provider.name
|
||||
),
|
||||
&state.redirect,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// Get user from local database
|
||||
let result: LoginResult = users
|
||||
.send(users_actor::ProviderLoginRequest {
|
||||
email: email.clone(),
|
||||
provider: provider.clone(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let user = match result {
|
||||
LoginResult::Success(u) => u,
|
||||
LoginResult::AccountNotFound => {
|
||||
logger.log(Action::ProviderAccountNotFound {
|
||||
provider: &provider,
|
||||
email: email.as_str(),
|
||||
});
|
||||
|
||||
return ProviderLoginError::get(
|
||||
&format!("The email address {email} was not found in the database!"),
|
||||
&state.redirect,
|
||||
);
|
||||
}
|
||||
LoginResult::AccountDisabled => {
|
||||
logger.log(Action::ProviderAccountDisabled {
|
||||
provider: &provider,
|
||||
email: email.as_str(),
|
||||
});
|
||||
|
||||
return ProviderLoginError::get(
|
||||
&format!("The account associated with the email address {email} is disabled!"),
|
||||
&state.redirect,
|
||||
);
|
||||
}
|
||||
|
||||
LoginResult::AuthFromProviderForbidden => {
|
||||
logger.log(Action::ProviderAccountNotAllowedToLoginWithProvider {
|
||||
provider: &provider,
|
||||
email: email.as_str(),
|
||||
});
|
||||
|
||||
return ProviderLoginError::get(
|
||||
&format!(
|
||||
"The account associated with the email address {email} is not allowed to sign in using this provider!"
|
||||
),
|
||||
&state.redirect,
|
||||
);
|
||||
}
|
||||
|
||||
c => {
|
||||
log::error!(
|
||||
"Login from provider {} failed with error {:?}",
|
||||
provider.id.0,
|
||||
c
|
||||
);
|
||||
|
||||
logger.log(Action::ProviderLoginFailed {
|
||||
provider: &provider,
|
||||
email: email.as_str(),
|
||||
});
|
||||
|
||||
return ProviderLoginError::get("Failed to complete login!", &state.redirect);
|
||||
}
|
||||
};
|
||||
|
||||
logger.log(Action::ProviderLoginSuccessful {
|
||||
provider: &provider,
|
||||
user: &user,
|
||||
});
|
||||
|
||||
let status = if user.has_two_factor() && !user.can_bypass_two_factors_for_ip(remote_ip.0) {
|
||||
logger.log(Action::UserNeed2FAOnLogin(&user));
|
||||
SessionStatus::Need2FA
|
||||
} else {
|
||||
logger.log(Action::UserSuccessfullyAuthenticated(&user));
|
||||
SessionStatus::SignedIn
|
||||
};
|
||||
|
||||
SessionIdentity(id.as_ref()).set_user(&http_req, &user, status);
|
||||
redirect_user(&format!("/login?redirect={}", state.redirect.get_encoded()))
|
||||
}
|
@@ -1,41 +1,41 @@
|
||||
use actix::Addr;
|
||||
use actix_web::{web, HttpResponse, Responder};
|
||||
use actix_remote_ip::RemoteIP;
|
||||
use actix_web::{HttpResponse, Responder, web};
|
||||
use askama::Template;
|
||||
|
||||
use crate::actors::bruteforce_actor::BruteForceActor;
|
||||
use crate::actors::users_actor::UsersActor;
|
||||
use crate::actors::{bruteforce_actor, users_actor};
|
||||
use crate::constants::{APP_NAME, MAX_FAILED_LOGIN_ATTEMPTS, MIN_PASS_LEN};
|
||||
use crate::data::action_logger::{Action, ActionLogger};
|
||||
use crate::data::app_config::AppConfig;
|
||||
use crate::data::current_user::CurrentUser;
|
||||
use crate::data::remote_ip::RemoteIP;
|
||||
|
||||
use crate::data::user::User;
|
||||
|
||||
pub(crate) struct BaseSettingsPage {
|
||||
pub(crate) struct BaseSettingsPage<'a> {
|
||||
pub danger_message: Option<String>,
|
||||
pub success_message: Option<String>,
|
||||
pub page_title: &'static str,
|
||||
pub app_name: &'static str,
|
||||
pub is_admin: bool,
|
||||
pub user_name: String,
|
||||
pub user: &'a User,
|
||||
pub version: &'static str,
|
||||
pub ip_location_api: Option<&'static str>,
|
||||
}
|
||||
|
||||
impl BaseSettingsPage {
|
||||
impl<'a> BaseSettingsPage<'a> {
|
||||
pub fn get(
|
||||
page_title: &'static str,
|
||||
user: &User,
|
||||
user: &'a User,
|
||||
danger_message: Option<String>,
|
||||
success_message: Option<String>,
|
||||
) -> BaseSettingsPage {
|
||||
) -> BaseSettingsPage<'a> {
|
||||
Self {
|
||||
danger_message,
|
||||
success_message,
|
||||
page_title,
|
||||
app_name: APP_NAME,
|
||||
is_admin: user.admin,
|
||||
user_name: user.username.to_string(),
|
||||
user,
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
ip_location_api: AppConfig::get().ip_location_service.as_deref(),
|
||||
}
|
||||
@@ -44,25 +44,25 @@ impl BaseSettingsPage {
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "settings/account_details.html")]
|
||||
struct AccountDetailsPage {
|
||||
_p: BaseSettingsPage,
|
||||
u: User,
|
||||
struct AccountDetailsPage<'a> {
|
||||
p: BaseSettingsPage<'a>,
|
||||
remote_ip: String,
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "settings/change_password.html")]
|
||||
struct ChangePasswordPage {
|
||||
_p: BaseSettingsPage,
|
||||
struct ChangePasswordPage<'a> {
|
||||
p: BaseSettingsPage<'a>,
|
||||
min_pwd_len: usize,
|
||||
}
|
||||
|
||||
/// Account details page
|
||||
pub async fn account_settings_details_route(user: CurrentUser) -> impl Responder {
|
||||
pub async fn account_settings_details_route(user: CurrentUser, ip: RemoteIP) -> impl Responder {
|
||||
let user = user.into();
|
||||
HttpResponse::Ok().body(
|
||||
AccountDetailsPage {
|
||||
_p: BaseSettingsPage::get("Account details", &user, None, None),
|
||||
u: user,
|
||||
p: BaseSettingsPage::get("Account details", &user, None, None),
|
||||
remote_ip: ip.0.to_string(),
|
||||
}
|
||||
.render()
|
||||
.unwrap(),
|
||||
@@ -82,6 +82,7 @@ pub async fn change_password_route(
|
||||
req: Option<web::Form<PassChangeRequest>>,
|
||||
bruteforce: web::Data<Addr<BruteForceActor>>,
|
||||
remote_ip: RemoteIP,
|
||||
logger: ActionLogger,
|
||||
) -> impl Responder {
|
||||
let mut danger = None;
|
||||
let mut success = None;
|
||||
@@ -101,7 +102,14 @@ pub async fn change_password_route(
|
||||
);
|
||||
} else if let Some(req) = req {
|
||||
// Invalid password
|
||||
if !user.verify_password(&req.old_pass) {
|
||||
if !users
|
||||
.send(users_actor::VerifyUserPasswordRequest(
|
||||
user.uid.clone(),
|
||||
req.old_pass.clone(),
|
||||
))
|
||||
.await
|
||||
.unwrap()
|
||||
{
|
||||
danger = Some("Old password is invalid!".to_string());
|
||||
bruteforce
|
||||
.send(bruteforce_actor::RecordFailedAttempt {
|
||||
@@ -123,13 +131,13 @@ pub async fn change_password_route(
|
||||
temporary: false,
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.0;
|
||||
.unwrap();
|
||||
|
||||
if !res {
|
||||
danger =
|
||||
Some("An error occurred while trying to change your password!".to_string());
|
||||
} else {
|
||||
logger.log(Action::ChangedHisPassword);
|
||||
success = Some("Your password was successfully changed!".to_string());
|
||||
}
|
||||
}
|
||||
@@ -137,7 +145,7 @@ pub async fn change_password_route(
|
||||
|
||||
HttpResponse::Ok().body(
|
||||
ChangePasswordPage {
|
||||
_p: BaseSettingsPage::get("Change password", &user, danger, success),
|
||||
p: BaseSettingsPage::get("Change password", &user, danger, success),
|
||||
min_pwd_len: MIN_PASS_LEN,
|
||||
}
|
||||
.render()
|
||||
|
@@ -1,15 +1,27 @@
|
||||
use actix::Addr;
|
||||
use actix_web::{web, HttpResponse, Responder};
|
||||
use actix_web::{HttpResponse, Responder, web};
|
||||
use uuid::Uuid;
|
||||
use webauthn_rs::prelude::RegisterPublicKeyCredential;
|
||||
|
||||
use crate::actors::users_actor;
|
||||
use crate::actors::users_actor::UsersActor;
|
||||
use crate::constants::MAX_SECOND_FACTOR_NAME_LEN;
|
||||
use crate::data::action_logger::{Action, ActionLogger};
|
||||
use crate::data::critical_route::CriticalRoute;
|
||||
use crate::data::current_user::CurrentUser;
|
||||
use crate::data::totp_key::TotpKey;
|
||||
use crate::data::user::{FactorID, TwoFactor, TwoFactorType, User};
|
||||
use crate::data::user::{FactorID, TwoFactor, TwoFactorType};
|
||||
use crate::data::webauthn_manager::WebAuthManagerReq;
|
||||
|
||||
fn preprocess_factor_name(name: &str) -> String {
|
||||
name.replace('<', "<")
|
||||
.replace('>', ">")
|
||||
.chars()
|
||||
.take(MAX_SECOND_FACTOR_NAME_LEN)
|
||||
.filter(|c| *c != '\n' && *c != '\t' && *c != '\r' && c.is_ascii())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
pub struct AddTOTPRequest {
|
||||
factor_name: String,
|
||||
@@ -18,35 +30,39 @@ pub struct AddTOTPRequest {
|
||||
}
|
||||
|
||||
pub async fn save_totp_factor(
|
||||
_critical: CriticalRoute,
|
||||
user: CurrentUser,
|
||||
form: web::Json<AddTOTPRequest>,
|
||||
users: web::Data<Addr<UsersActor>>,
|
||||
logger: ActionLogger,
|
||||
) -> impl Responder {
|
||||
let key = TotpKey::from_encoded_secret(&form.secret);
|
||||
|
||||
if !key.check_code(&form.first_code).unwrap_or(false) {
|
||||
return HttpResponse::BadRequest().body(format!(
|
||||
"Given code is invalid (expected {} or {})!",
|
||||
"Given code is invalid (expected {}, {} or {})!",
|
||||
key.previous_code().unwrap_or_default(),
|
||||
key.current_code().unwrap_or_default(),
|
||||
key.previous_code().unwrap_or_default()
|
||||
key.following_code().unwrap_or_default(),
|
||||
));
|
||||
}
|
||||
|
||||
if form.factor_name.is_empty() {
|
||||
return HttpResponse::BadRequest().body("Please give a name to the factor!");
|
||||
let factor_name = preprocess_factor_name(&form.factor_name);
|
||||
if factor_name.is_empty() {
|
||||
return HttpResponse::BadRequest().body("Please give a valid name to the factor!");
|
||||
}
|
||||
|
||||
let mut user = User::from(user);
|
||||
user.add_factor(TwoFactor {
|
||||
let factor = TwoFactor {
|
||||
id: FactorID(Uuid::new_v4().to_string()),
|
||||
name: form.0.factor_name,
|
||||
name: factor_name,
|
||||
kind: TwoFactorType::TOTP(key),
|
||||
});
|
||||
};
|
||||
logger.log(Action::AddNewFactor(&factor));
|
||||
|
||||
let res = users
|
||||
.send(users_actor::UpdateUserRequest(user))
|
||||
.send(users_actor::Add2FAFactor(user.uid.clone(), factor))
|
||||
.await
|
||||
.unwrap()
|
||||
.0;
|
||||
.unwrap();
|
||||
|
||||
if !res {
|
||||
HttpResponse::InternalServerError().body("Failed to update user information!")
|
||||
@@ -63,30 +79,37 @@ pub struct AddWebauthnRequest {
|
||||
}
|
||||
|
||||
pub async fn save_webauthn_factor(
|
||||
_critical: CriticalRoute,
|
||||
user: CurrentUser,
|
||||
form: web::Json<AddWebauthnRequest>,
|
||||
users: web::Data<Addr<UsersActor>>,
|
||||
manager: WebAuthManagerReq,
|
||||
logger: ActionLogger,
|
||||
) -> impl Responder {
|
||||
let factor_name = preprocess_factor_name(&form.factor_name);
|
||||
if factor_name.is_empty() {
|
||||
return HttpResponse::BadRequest().body("Please give a valid name to the factor!");
|
||||
}
|
||||
|
||||
let key = match manager.finish_registration(&user, &form.0.opaque_state, form.0.credential) {
|
||||
Ok(k) => k,
|
||||
Err(e) => {
|
||||
log::error!("Failed to register security key! {:?}", e);
|
||||
log::error!("Failed to register security key! {e:?}");
|
||||
return HttpResponse::InternalServerError().body("Failed to register key!");
|
||||
}
|
||||
};
|
||||
|
||||
let mut user = User::from(user);
|
||||
user.add_factor(TwoFactor {
|
||||
let factor = TwoFactor {
|
||||
id: FactorID(Uuid::new_v4().to_string()),
|
||||
name: form.0.factor_name,
|
||||
name: factor_name,
|
||||
kind: TwoFactorType::WEBAUTHN(Box::new(key)),
|
||||
});
|
||||
};
|
||||
logger.log(Action::AddNewFactor(&factor));
|
||||
|
||||
let res = users
|
||||
.send(users_actor::UpdateUserRequest(user))
|
||||
.send(users_actor::Add2FAFactor(user.uid.clone(), factor))
|
||||
.await
|
||||
.unwrap()
|
||||
.0;
|
||||
.unwrap();
|
||||
|
||||
if !res {
|
||||
HttpResponse::InternalServerError().body("Failed to update user information!")
|
||||
@@ -101,34 +124,41 @@ pub struct DeleteFactorRequest {
|
||||
}
|
||||
|
||||
pub async fn delete_factor(
|
||||
_critical: CriticalRoute,
|
||||
user: CurrentUser,
|
||||
form: web::Json<DeleteFactorRequest>,
|
||||
users: web::Data<Addr<UsersActor>>,
|
||||
logger: ActionLogger,
|
||||
) -> impl Responder {
|
||||
let mut user = User::from(user);
|
||||
user.remove_factor(form.0.id);
|
||||
|
||||
let res = users
|
||||
.send(users_actor::UpdateUserRequest(user))
|
||||
.send(users_actor::Remove2FAFactor(
|
||||
user.uid.clone(),
|
||||
form.id.clone(),
|
||||
))
|
||||
.await
|
||||
.unwrap()
|
||||
.0;
|
||||
.unwrap();
|
||||
|
||||
if !res {
|
||||
HttpResponse::InternalServerError().body("Failed to update user information!")
|
||||
} else {
|
||||
logger.log(Action::Removed2FAFactor {
|
||||
factor_id: &form.0.id,
|
||||
});
|
||||
HttpResponse::Ok().body("Removed factor!")
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn clear_login_history(
|
||||
_critical: CriticalRoute,
|
||||
user: CurrentUser,
|
||||
users: web::Data<Addr<UsersActor>>,
|
||||
logger: ActionLogger,
|
||||
) -> impl Responder {
|
||||
users
|
||||
.send(users_actor::Clear2FALoginHistory(user.uid.clone()))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
logger.log(Action::ClearedHisLoginHistory);
|
||||
HttpResponse::Ok().body("History successfully cleared")
|
||||
}
|
||||
|
@@ -2,45 +2,54 @@ use std::ops::Deref;
|
||||
|
||||
use actix_web::{HttpResponse, Responder};
|
||||
use askama::Template;
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
|
||||
use qrcode_generator::QrCodeEcc;
|
||||
|
||||
use crate::constants::MAX_SECOND_FACTOR_NAME_LEN;
|
||||
use crate::controllers::settings_controller::BaseSettingsPage;
|
||||
use crate::data::app_config::AppConfig;
|
||||
use crate::data::critical_route::CriticalRoute;
|
||||
use crate::data::current_user::CurrentUser;
|
||||
use crate::data::totp_key::TotpKey;
|
||||
use crate::data::user::User;
|
||||
use crate::data::webauthn_manager::WebAuthManagerReq;
|
||||
use crate::utils::time::fmt_time;
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "settings/two_factors_page.html")]
|
||||
struct TwoFactorsPage<'a> {
|
||||
_p: BaseSettingsPage,
|
||||
p: BaseSettingsPage<'a>,
|
||||
user: &'a User,
|
||||
last_2fa_auth: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "settings/add_2fa_totp_page.html")]
|
||||
struct AddTotpPage {
|
||||
_p: BaseSettingsPage,
|
||||
struct AddTotpPage<'a> {
|
||||
p: BaseSettingsPage<'a>,
|
||||
qr_code: String,
|
||||
account_name: String,
|
||||
secret_key: String,
|
||||
max_name_len: usize,
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "settings/add_webauthn_page.html")]
|
||||
struct AddWebauhtnPage {
|
||||
_p: BaseSettingsPage,
|
||||
struct AddWebauhtnPage<'a> {
|
||||
p: BaseSettingsPage<'a>,
|
||||
opaque_state: String,
|
||||
challenge_json: String,
|
||||
max_name_len: usize,
|
||||
}
|
||||
|
||||
/// Manage two factors authentication methods route
|
||||
pub async fn two_factors_route(user: CurrentUser) -> impl Responder {
|
||||
pub async fn two_factors_route(_critical: CriticalRoute, user: CurrentUser) -> impl Responder {
|
||||
HttpResponse::Ok().body(
|
||||
TwoFactorsPage {
|
||||
_p: BaseSettingsPage::get("Two factor auth", &user, None, None),
|
||||
p: BaseSettingsPage::get("Two factor auth", &user, None, None),
|
||||
user: user.deref(),
|
||||
last_2fa_auth: user.last_2fa_auth.map(fmt_time),
|
||||
}
|
||||
.render()
|
||||
.unwrap(),
|
||||
@@ -48,7 +57,7 @@ pub async fn two_factors_route(user: CurrentUser) -> impl Responder {
|
||||
}
|
||||
|
||||
/// Configure a new TOTP authentication factor
|
||||
pub async fn add_totp_factor_route(user: CurrentUser) -> impl Responder {
|
||||
pub async fn add_totp_factor_route(_critical: CriticalRoute, user: CurrentUser) -> impl Responder {
|
||||
let key = TotpKey::new_random();
|
||||
|
||||
let qr_code = qrcode_generator::to_png_to_vec(
|
||||
@@ -59,17 +68,18 @@ pub async fn add_totp_factor_route(user: CurrentUser) -> impl Responder {
|
||||
let qr_code = match qr_code {
|
||||
Ok(q) => q,
|
||||
Err(e) => {
|
||||
log::error!("Failed to generate QrCode! {:?}", e);
|
||||
log::error!("Failed to generate QrCode! {e:?}");
|
||||
return HttpResponse::InternalServerError().body("Failed to generate QrCode!");
|
||||
}
|
||||
};
|
||||
|
||||
HttpResponse::Ok().body(
|
||||
AddTotpPage {
|
||||
_p: BaseSettingsPage::get("New authenticator app", &user, None, None),
|
||||
qr_code: base64::encode(qr_code),
|
||||
p: BaseSettingsPage::get("New authenticator app", &user, None, None),
|
||||
qr_code: BASE64_STANDARD.encode(qr_code),
|
||||
account_name: key.account_name(&user, AppConfig::get()),
|
||||
secret_key: key.get_secret(),
|
||||
max_name_len: MAX_SECOND_FACTOR_NAME_LEN,
|
||||
}
|
||||
.render()
|
||||
.unwrap(),
|
||||
@@ -78,13 +88,14 @@ pub async fn add_totp_factor_route(user: CurrentUser) -> impl Responder {
|
||||
|
||||
/// Configure a new security key factor
|
||||
pub async fn add_webauthn_factor_route(
|
||||
_critical: CriticalRoute,
|
||||
user: CurrentUser,
|
||||
manager: WebAuthManagerReq,
|
||||
) -> impl Responder {
|
||||
let registration_request = match manager.start_register(&user) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
log::error!("Failed to request new key! {:?}", e);
|
||||
log::error!("Failed to request new key! {e:?}");
|
||||
return HttpResponse::InternalServerError()
|
||||
.body("Failed to generate request for registration!");
|
||||
}
|
||||
@@ -93,17 +104,18 @@ pub async fn add_webauthn_factor_route(
|
||||
let challenge_json = match serde_json::to_string(®istration_request.creation_challenge) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
log::error!("Failed to serialize challenge! {:?}", e);
|
||||
log::error!("Failed to serialize challenge! {e:?}");
|
||||
return HttpResponse::InternalServerError().body("Failed to serialize challenge!");
|
||||
}
|
||||
};
|
||||
|
||||
HttpResponse::Ok().body(
|
||||
AddWebauhtnPage {
|
||||
_p: BaseSettingsPage::get("New security key", &user, None, None),
|
||||
p: BaseSettingsPage::get("New security key", &user, None, None),
|
||||
|
||||
opaque_state: registration_request.opaque_state,
|
||||
challenge_json: urlencoding::encode(&challenge_json).to_string(),
|
||||
max_name_len: MAX_SECOND_FACTOR_NAME_LEN,
|
||||
}
|
||||
.render()
|
||||
.unwrap(),
|
||||
|
312
src/data/action_logger.rs
Normal file
312
src/data/action_logger.rs
Normal file
@@ -0,0 +1,312 @@
|
||||
use std::future::Future;
|
||||
use std::net::IpAddr;
|
||||
use std::pin::Pin;
|
||||
|
||||
use actix::Addr;
|
||||
use actix_identity::Identity;
|
||||
use actix_remote_ip::RemoteIP;
|
||||
use actix_web::dev::Payload;
|
||||
use actix_web::{Error, FromRequest, HttpRequest, web};
|
||||
|
||||
use crate::actors::providers_states_actor::ProviderLoginState;
|
||||
use crate::actors::users_actor;
|
||||
use crate::actors::users_actor::{AuthorizedAuthenticationSources, UsersActor};
|
||||
use crate::data::client::Client;
|
||||
use crate::data::provider::{Provider, ProviderID};
|
||||
|
||||
use crate::data::session_identity::SessionIdentity;
|
||||
use crate::data::user::{FactorID, GrantedClients, TwoFactor, User, UserID};
|
||||
|
||||
pub enum Action<'a> {
|
||||
AdminCreateUser(&'a User),
|
||||
AdminUpdateUser(&'a User),
|
||||
AdminDeleteUser(&'a User),
|
||||
AdminResetUserPassword(&'a User),
|
||||
AdminRemoveUserFactor(&'a User, &'a TwoFactor),
|
||||
AdminSetAuthorizedAuthenticationSources(&'a User, &'a AuthorizedAuthenticationSources),
|
||||
AdminSetNewGrantedClientsList(&'a User, &'a GrantedClients),
|
||||
AdminClear2FAHistory(&'a User),
|
||||
LoginWebauthnAttempt {
|
||||
success: bool,
|
||||
user_id: UserID,
|
||||
},
|
||||
StartLoginAttemptWithOpenIDProvider {
|
||||
provider_id: &'a ProviderID,
|
||||
state: &'a str,
|
||||
},
|
||||
ProviderError {
|
||||
message: &'a str,
|
||||
},
|
||||
ProviderCBInvalidState {
|
||||
state: &'a str,
|
||||
},
|
||||
ProviderRateLimited,
|
||||
ProviderFailedGetToken {
|
||||
state: &'a ProviderLoginState,
|
||||
code: &'a str,
|
||||
},
|
||||
ProviderFailedGetUserInfo {
|
||||
provider: &'a Provider,
|
||||
},
|
||||
ProviderEmailNotValidated {
|
||||
provider: &'a Provider,
|
||||
},
|
||||
ProviderMissingEmailInResponse {
|
||||
provider: &'a Provider,
|
||||
},
|
||||
ProviderAccountNotFound {
|
||||
provider: &'a Provider,
|
||||
email: &'a str,
|
||||
},
|
||||
ProviderAccountDisabled {
|
||||
provider: &'a Provider,
|
||||
email: &'a str,
|
||||
},
|
||||
|
||||
ProviderAccountNotAllowedToLoginWithProvider {
|
||||
provider: &'a Provider,
|
||||
email: &'a str,
|
||||
},
|
||||
ProviderLoginFailed {
|
||||
provider: &'a Provider,
|
||||
email: &'a str,
|
||||
},
|
||||
ProviderLoginSuccessful {
|
||||
provider: &'a Provider,
|
||||
user: &'a User,
|
||||
},
|
||||
Signout,
|
||||
UserNeed2FAOnLogin(&'a User),
|
||||
UserSuccessfullyAuthenticated(&'a User),
|
||||
UserNeedNewPasswordOnLogin(&'a User),
|
||||
TryLoginWithDisabledAccount(&'a str),
|
||||
TryLocalLoginFromUnauthorizedAccount(&'a str),
|
||||
FailedLoginWithBadCredentials(&'a str),
|
||||
UserChangedPasswordOnLogin(&'a UserID),
|
||||
OTPLoginAttempt {
|
||||
user: &'a User,
|
||||
success: bool,
|
||||
},
|
||||
NewOpenIDSession {
|
||||
client: &'a Client,
|
||||
},
|
||||
NewOpenIDSuccessfulImplicitAuth {
|
||||
client: &'a Client,
|
||||
},
|
||||
ChangedHisPassword,
|
||||
ClearedHisLoginHistory,
|
||||
AddNewFactor(&'a TwoFactor),
|
||||
Removed2FAFactor {
|
||||
factor_id: &'a FactorID,
|
||||
},
|
||||
}
|
||||
|
||||
impl Action<'_> {
|
||||
pub fn as_string(&self) -> String {
|
||||
match self {
|
||||
Action::AdminDeleteUser(user) => {
|
||||
format!("deleted account of {}", user.quick_identity())
|
||||
}
|
||||
Action::AdminCreateUser(user) => {
|
||||
format!("created account of {}", user.quick_identity())
|
||||
}
|
||||
Action::AdminUpdateUser(user) => {
|
||||
format!("updated account of {}", user.quick_identity())
|
||||
}
|
||||
Action::AdminResetUserPassword(user) => {
|
||||
format!(
|
||||
"set a temporary password for the account of {}",
|
||||
user.quick_identity()
|
||||
)
|
||||
}
|
||||
Action::AdminRemoveUserFactor(user, factor) => format!(
|
||||
"removed 2 factor ({}) of user ({})",
|
||||
factor.quick_description(),
|
||||
user.quick_identity()
|
||||
),
|
||||
Action::AdminClear2FAHistory(user) => {
|
||||
format!("cleared 2FA history of {}", user.quick_identity())
|
||||
}
|
||||
Action::AdminSetAuthorizedAuthenticationSources(user, sources) => format!(
|
||||
"update authorized authentication sources ({:?}) for user ({})",
|
||||
sources,
|
||||
user.quick_identity()
|
||||
),
|
||||
Action::AdminSetNewGrantedClientsList(user, clients) => format!(
|
||||
"set new granted clients list ({:?}) for user ({})",
|
||||
clients,
|
||||
user.quick_identity()
|
||||
),
|
||||
Action::LoginWebauthnAttempt { success, user_id } => match success {
|
||||
true => format!("successfully performed webauthn attempt for user {user_id:?}"),
|
||||
false => format!("performed FAILED webauthn attempt for user {user_id:?}"),
|
||||
},
|
||||
Action::StartLoginAttemptWithOpenIDProvider { provider_id, state } => format!(
|
||||
"started new authentication attempt through an OpenID provider (prov={} / state={state})",
|
||||
provider_id.0
|
||||
),
|
||||
Action::ProviderError { message } => {
|
||||
format!("failed provider authentication with message '{message}'")
|
||||
}
|
||||
Action::ProviderCBInvalidState { state } => {
|
||||
format!("provided invalid callback state after provider authentication: '{state}'")
|
||||
}
|
||||
Action::ProviderRateLimited => {
|
||||
"could not complete OpenID login because it has reached failed attempts rate limit!"
|
||||
.to_string()
|
||||
}
|
||||
Action::ProviderFailedGetToken { state, code } => format!(
|
||||
"could not complete login from provider because the id_token could not be retrieved! (state={state:?} code = {code})"
|
||||
),
|
||||
Action::ProviderFailedGetUserInfo { provider } => format!(
|
||||
"could not get user information from userinfo endpoint of provider {}!",
|
||||
provider.id.0
|
||||
),
|
||||
Action::ProviderEmailNotValidated { provider } => format!(
|
||||
"could not login using provider {} because its email was marked as not validated!",
|
||||
provider.id.0
|
||||
),
|
||||
Action::ProviderMissingEmailInResponse { provider } => format!(
|
||||
"could not login using provider {} because the email was not provided by userinfo endpoint!",
|
||||
provider.id.0
|
||||
),
|
||||
Action::ProviderAccountNotFound { provider, email } => format!(
|
||||
"could not login using provider {} because the email {email} could not be associated to any account!",
|
||||
&provider.id.0
|
||||
),
|
||||
Action::ProviderAccountDisabled { provider, email } => format!(
|
||||
"could not login using provider {} because the account associated to the email {email} is disabled!",
|
||||
&provider.id.0
|
||||
),
|
||||
Action::ProviderAccountNotAllowedToLoginWithProvider { provider, email } => format!(
|
||||
"could not login using provider {} because the account associated to the email {email} is not allowed to authenticate using this provider!",
|
||||
&provider.id.0
|
||||
),
|
||||
Action::ProviderLoginFailed { provider, email } => format!(
|
||||
"could not login using provider {} with the email {email} for an unknown reason!",
|
||||
&provider.id.0
|
||||
),
|
||||
Action::ProviderLoginSuccessful { provider, user } => format!(
|
||||
"successfully authenticated using provider {} as {}",
|
||||
provider.id.0,
|
||||
user.quick_identity()
|
||||
),
|
||||
Action::Signout => "signed out".to_string(),
|
||||
Action::UserNeed2FAOnLogin(user) => {
|
||||
format!(
|
||||
"successfully authenticated as user {:?} but need to do 2FA authentication",
|
||||
user.quick_identity()
|
||||
)
|
||||
}
|
||||
Action::UserSuccessfullyAuthenticated(user) => {
|
||||
format!("successfully authenticated as {}", user.quick_identity())
|
||||
}
|
||||
Action::UserNeedNewPasswordOnLogin(user) => format!(
|
||||
"successfully authenticated as {}, but need to set a new password",
|
||||
user.quick_identity()
|
||||
),
|
||||
Action::TryLoginWithDisabledAccount(login) => {
|
||||
format!("successfully authenticated as {login}, but this is a DISABLED ACCOUNT")
|
||||
}
|
||||
Action::TryLocalLoginFromUnauthorizedAccount(login) => {
|
||||
format!(
|
||||
"successfully locally authenticated as {login}, but this is a FORBIDDEN for this account!"
|
||||
)
|
||||
}
|
||||
Action::FailedLoginWithBadCredentials(login) => {
|
||||
format!("attempted to authenticate as {login} but with a WRONG PASSWORD")
|
||||
}
|
||||
Action::UserChangedPasswordOnLogin(user_id) => {
|
||||
format!("set a new password at login as user {user_id:?}")
|
||||
}
|
||||
Action::OTPLoginAttempt { user, success } => match success {
|
||||
true => format!(
|
||||
"successfully performed OTP attempt for user {}",
|
||||
user.quick_identity()
|
||||
),
|
||||
false => format!(
|
||||
"performed FAILED OTP attempt for user {}",
|
||||
user.quick_identity()
|
||||
),
|
||||
},
|
||||
Action::NewOpenIDSession { client } => {
|
||||
format!("opened a new OpenID session with {:?}", client.id)
|
||||
}
|
||||
Action::NewOpenIDSuccessfulImplicitAuth { client } => format!(
|
||||
"finished an implicit flow connection for client {:?}",
|
||||
client.id
|
||||
),
|
||||
Action::ChangedHisPassword => "changed his password".to_string(),
|
||||
Action::ClearedHisLoginHistory => "cleared his login history".to_string(),
|
||||
Action::AddNewFactor(factor) => format!(
|
||||
"added a new factor to his account : {}",
|
||||
factor.quick_description(),
|
||||
),
|
||||
Action::Removed2FAFactor { factor_id } => format!("Removed his factor {factor_id:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ActionLogger {
|
||||
ip: IpAddr,
|
||||
user: Option<User>,
|
||||
}
|
||||
|
||||
impl ActionLogger {
|
||||
pub fn log(&self, action: Action) {
|
||||
log::info!(
|
||||
"{} from {} has {}",
|
||||
match &self.user {
|
||||
None => "Anonymous user".to_string(),
|
||||
Some(u) => u.quick_identity(),
|
||||
},
|
||||
self.ip,
|
||||
action.as_string()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl FromRequest for ActionLogger {
|
||||
type Error = Error;
|
||||
type Future = Pin<Box<dyn Future<Output = Result<Self, Self::Error>>>>;
|
||||
|
||||
#[inline]
|
||||
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
||||
let req = req.clone();
|
||||
|
||||
Box::pin(async move {
|
||||
let user_actor: &web::Data<Addr<UsersActor>> =
|
||||
req.app_data().expect("UserActor undefined!");
|
||||
|
||||
let user_actor: Addr<UsersActor> = user_actor.as_ref().clone();
|
||||
|
||||
let user_id = Identity::from_request(&req, &mut Payload::None)
|
||||
.into_inner()
|
||||
.ok()
|
||||
.and_then(|id| {
|
||||
let sess = SessionIdentity(Some(&id));
|
||||
match sess.is_authenticated() {
|
||||
true => Some(sess.user_id()),
|
||||
false => None,
|
||||
}
|
||||
});
|
||||
|
||||
Ok(Self {
|
||||
ip: RemoteIP::from_request(&req, &mut Payload::None)
|
||||
.await
|
||||
.unwrap()
|
||||
.0,
|
||||
user: match user_id {
|
||||
None => None,
|
||||
Some(u) => {
|
||||
user_actor
|
||||
.send(users_actor::GetUserRequest(u))
|
||||
.await
|
||||
.unwrap()
|
||||
.0
|
||||
}
|
||||
},
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
@@ -2,7 +2,9 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use clap::Parser;
|
||||
|
||||
use crate::constants::{APP_NAME, CLIENTS_LIST_FILE, USERS_LIST_FILE};
|
||||
use crate::constants::{
|
||||
APP_NAME, CLIENTS_LIST_FILE, OIDC_PROVIDER_CB_URI, PROVIDERS_LIST_FILE, USERS_LIST_FILE,
|
||||
};
|
||||
|
||||
/// Basic OIDC provider
|
||||
#[derive(Parser, Debug, Clone)]
|
||||
@@ -72,6 +74,10 @@ impl AppConfig {
|
||||
self.storage_path().join(CLIENTS_LIST_FILE)
|
||||
}
|
||||
|
||||
pub fn providers_file(&self) -> PathBuf {
|
||||
self.storage_path().join(PROVIDERS_LIST_FILE)
|
||||
}
|
||||
|
||||
pub fn full_url(&self, uri: &str) -> String {
|
||||
if uri.starts_with('/') {
|
||||
format!("{}{}", self.website_origin, uri)
|
||||
@@ -80,9 +86,21 @@ impl AppConfig {
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the URL where a upstream OpenID provider should redirect
|
||||
/// the user after an authentication
|
||||
pub fn oidc_provider_redirect_url(&self) -> String {
|
||||
AppConfig::get().full_url(OIDC_PROVIDER_CB_URI)
|
||||
}
|
||||
|
||||
pub fn domain_name(&self) -> &str {
|
||||
self.website_origin.split('/').nth(2).unwrap_or(APP_NAME)
|
||||
}
|
||||
|
||||
/// Get the domain without the port
|
||||
pub fn domain_name_without_port(&self) -> &str {
|
||||
let domain = self.domain_name();
|
||||
domain.split_once(':').map(|i| i.0).unwrap_or(domain)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
@@ -1,16 +1,49 @@
|
||||
use crate::data::entity_manager::EntityManager;
|
||||
use crate::data::user::User;
|
||||
use crate::utils::string_utils::apply_env_vars;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq)]
|
||||
pub struct ClientID(pub String);
|
||||
|
||||
pub type AdditionalClaims = HashMap<String, Value>;
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Client {
|
||||
/// The ID of the client
|
||||
pub id: ClientID,
|
||||
|
||||
/// The human-readable name of the client
|
||||
pub name: String,
|
||||
|
||||
/// A short description of the service provided by the client
|
||||
pub description: String,
|
||||
pub secret: String,
|
||||
|
||||
/// The secret used by the client to retrieve authenticated users information
|
||||
/// This value is absent if implicit authentication flow is used
|
||||
pub secret: Option<String>,
|
||||
|
||||
/// The URI where the users should be redirected once authenticated
|
||||
pub redirect_uri: String,
|
||||
|
||||
/// Specify if the client must be allowed by default for new account
|
||||
#[serde(default = "bool::default")]
|
||||
pub default: bool,
|
||||
|
||||
/// Specify whether a client is granted to all users
|
||||
#[serde(default = "bool::default")]
|
||||
pub granted_to_all_users: bool,
|
||||
|
||||
/// Specify whether recent Second Factor Authentication is required to access this client
|
||||
#[serde(default = "bool::default")]
|
||||
pub enforce_2fa_auth: bool,
|
||||
|
||||
/// Additional claims to return with the id token
|
||||
claims_id_token: Option<AdditionalClaims>,
|
||||
|
||||
/// Additional claims to return through the user info endpoint
|
||||
claims_user_info: Option<AdditionalClaims>,
|
||||
}
|
||||
|
||||
impl PartialEq for Client {
|
||||
@@ -21,6 +54,75 @@ impl PartialEq for Client {
|
||||
|
||||
impl Eq for Client {}
|
||||
|
||||
impl Client {
|
||||
/// Check if the client has a secret defined
|
||||
pub fn has_secret(&self) -> bool {
|
||||
self.secret.is_some()
|
||||
}
|
||||
|
||||
/// Process a single claim value
|
||||
fn process_claim_string(&self, user: &User, str: &str) -> String {
|
||||
str.replace("{username}", &user.username)
|
||||
.replace("{mail}", &user.email)
|
||||
.replace("{first_name}", &user.first_name)
|
||||
.replace("{last_name}", &user.last_name)
|
||||
.replace("{uid}", &user.uid.0)
|
||||
}
|
||||
|
||||
/// Recurse claims processing
|
||||
fn recurse_claims_processing(&self, user: &User, value: &Value) -> Value {
|
||||
match value {
|
||||
Value::String(s) => Value::String(self.process_claim_string(user, s)),
|
||||
Value::Array(arr) => Value::Array(
|
||||
arr.iter()
|
||||
.map(|v| self.recurse_claims_processing(user, v))
|
||||
.collect(),
|
||||
),
|
||||
Value::Object(obj) => obj
|
||||
.iter()
|
||||
.map(|(k, v)| {
|
||||
(
|
||||
self.process_claim_string(user, k),
|
||||
self.recurse_claims_processing(user, v),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
v => v.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Process additional claims, processing placeholders
|
||||
fn process_additional_claims(
|
||||
&self,
|
||||
user: &User,
|
||||
claims: &Option<AdditionalClaims>,
|
||||
) -> Option<AdditionalClaims> {
|
||||
let claims = claims.as_ref()?;
|
||||
|
||||
let res = claims
|
||||
.iter()
|
||||
.map(|(k, v)| {
|
||||
(
|
||||
self.process_claim_string(user, k),
|
||||
self.recurse_claims_processing(user, v),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
Some(res)
|
||||
}
|
||||
|
||||
/// Get additional claims for id_token for a successful authentication
|
||||
pub fn claims_id_token(&self, user: &User) -> Option<AdditionalClaims> {
|
||||
self.process_additional_claims(user, &self.claims_id_token)
|
||||
}
|
||||
|
||||
/// Get additional claims for user info for a successful authentication
|
||||
pub fn claims_user_info(&self, user: &User) -> Option<AdditionalClaims> {
|
||||
self.process_additional_claims(user, &self.claims_user_info)
|
||||
}
|
||||
}
|
||||
|
||||
pub type ClientManager = EntityManager<Client>;
|
||||
|
||||
impl EntityManager<Client> {
|
||||
@@ -33,12 +135,19 @@ impl EntityManager<Client> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Get the list of default clients.
|
||||
///
|
||||
/// i.e. the clients that are granted to new accounts by default
|
||||
pub fn get_default_clients(&self) -> Vec<&Client> {
|
||||
self.iter().filter(|u| u.default).collect()
|
||||
}
|
||||
|
||||
pub fn apply_environment_variables(&mut self) {
|
||||
for c in self.iter_mut() {
|
||||
c.id = ClientID(apply_env_vars(&c.id.0));
|
||||
c.name = apply_env_vars(&c.name);
|
||||
c.description = apply_env_vars(&c.description);
|
||||
c.secret = apply_env_vars(&c.secret);
|
||||
c.secret = c.secret.as_deref().map(apply_env_vars);
|
||||
c.redirect_uri = apply_env_vars(&c.redirect_uri);
|
||||
}
|
||||
}
|
||||
|
@@ -1,4 +1,5 @@
|
||||
use base64::URL_SAFE_NO_PAD;
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD as BASE64_URL_SAFE_NO_PAD;
|
||||
|
||||
use crate::utils::crypt_utils::sha256;
|
||||
|
||||
@@ -16,13 +17,12 @@ impl CodeChallenge {
|
||||
match self.code_challenge_method.as_str() {
|
||||
"plain" => code_verifer.eq(&self.code_challenge),
|
||||
"S256" => {
|
||||
let encoded =
|
||||
base64::encode_config(sha256(code_verifer.as_bytes()), URL_SAFE_NO_PAD);
|
||||
let encoded = BASE64_URL_SAFE_NO_PAD.encode(sha256(code_verifer.as_bytes()));
|
||||
|
||||
encoded.eq(&self.code_challenge)
|
||||
}
|
||||
s => {
|
||||
log::error!("Unknown code challenge method: {}", s);
|
||||
log::error!("Unknown code challenge method: {s}");
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -40,8 +40,8 @@ mod test {
|
||||
code_challenge: "text1".to_string(),
|
||||
};
|
||||
|
||||
assert_eq!(true, chal.verify_code("text1"));
|
||||
assert_eq!(false, chal.verify_code("text2"));
|
||||
assert!(chal.verify_code("text1"));
|
||||
assert!(!chal.verify_code("text2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -51,8 +51,8 @@ mod test {
|
||||
code_challenge: "uSOvC48D8TMh6RgW-36XppMlMgys-6KAE_wEIev9W2g".to_string(),
|
||||
};
|
||||
|
||||
assert_eq!(true, chal.verify_code("HIwht3lCHfnsruA+7Sq8NP2mPj5cBZe0Ewf23eK9UQhK4TdCIt3SK7Fr/giCdnfjxYQILOPG2D562emggAa2lA=="));
|
||||
assert_eq!(false, chal.verify_code("text1"));
|
||||
assert!(chal.verify_code("HIwht3lCHfnsruA+7Sq8NP2mPj5cBZe0Ewf23eK9UQhK4TdCIt3SK7Fr/giCdnfjxYQILOPG2D562emggAa2lA=="));
|
||||
assert!(!chal.verify_code("text1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -62,10 +62,7 @@ mod test {
|
||||
code_challenge: "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM".to_string(),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
true,
|
||||
chal.verify_code("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk")
|
||||
);
|
||||
assert_eq!(false, chal.verify_code("text1"));
|
||||
assert!(chal.verify_code("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"));
|
||||
assert!(!chal.verify_code("text1"));
|
||||
}
|
||||
}
|
||||
|
32
src/data/critical_route.rs
Normal file
32
src/data/critical_route.rs
Normal file
@@ -0,0 +1,32 @@
|
||||
use crate::data::current_user::CurrentUser;
|
||||
use crate::data::from_request_redirect::FromRequestRedirect;
|
||||
use crate::data::login_redirect::{LoginRedirect, get_2fa_url};
|
||||
use actix_web::dev::Payload;
|
||||
use actix_web::{FromRequest, HttpRequest};
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
|
||||
pub struct CriticalRoute;
|
||||
|
||||
impl FromRequest for CriticalRoute {
|
||||
type Error = FromRequestRedirect;
|
||||
type Future = Pin<Box<dyn Future<Output = Result<Self, Self::Error>>>>;
|
||||
|
||||
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
||||
let req = req.clone();
|
||||
|
||||
Box::pin(async move {
|
||||
let current_user = CurrentUser::from_request(&req, &mut Payload::None)
|
||||
.await
|
||||
.expect("Failed to extract user identity!");
|
||||
|
||||
if current_user.should_request_2fa_for_critical_functions() {
|
||||
let uri = get_2fa_url(&LoginRedirect::from_req(&req), true);
|
||||
|
||||
return Err(FromRequestRedirect::new(uri));
|
||||
}
|
||||
|
||||
Ok(Self)
|
||||
})
|
||||
}
|
||||
}
|
@@ -1,96 +0,0 @@
|
||||
use std::io::ErrorKind;
|
||||
|
||||
use aes_gcm::aead::{Aead, OsRng};
|
||||
use aes_gcm::{Aes256Gcm, Key, KeyInit, Nonce};
|
||||
use rand::Rng;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::utils::err::Res;
|
||||
|
||||
const NONCE_LEN: usize = 12;
|
||||
|
||||
pub struct CryptoWrapper {
|
||||
key: Key<Aes256Gcm>,
|
||||
}
|
||||
|
||||
impl CryptoWrapper {
|
||||
/// Generate a new memory wrapper
|
||||
pub fn new_random() -> Self {
|
||||
Self {
|
||||
key: Aes256Gcm::generate_key(&mut OsRng),
|
||||
}
|
||||
}
|
||||
|
||||
/// Encrypt some data
|
||||
pub fn encrypt<T: Serialize + DeserializeOwned>(&self, data: &T) -> Res<String> {
|
||||
let aes_key = Aes256Gcm::new(&self.key);
|
||||
let nonce_bytes = rand::thread_rng().gen::<[u8; NONCE_LEN]>();
|
||||
|
||||
let serialized_data = bincode::serialize(data)?;
|
||||
|
||||
let mut enc = aes_key
|
||||
.encrypt(Nonce::from_slice(&nonce_bytes), serialized_data.as_slice())
|
||||
.unwrap();
|
||||
enc.extend_from_slice(&nonce_bytes);
|
||||
|
||||
Ok(base64::encode(enc))
|
||||
}
|
||||
|
||||
/// Decrypt some data previously encrypted using the [`CryptoWrapper::encrypt`] method
|
||||
pub fn decrypt<T: DeserializeOwned>(&self, input: &str) -> Res<T> {
|
||||
let bytes = base64::decode(input)?;
|
||||
|
||||
if bytes.len() < NONCE_LEN {
|
||||
return Err(Box::new(std::io::Error::new(
|
||||
ErrorKind::Other,
|
||||
"Input string is smaller than nonce!",
|
||||
)));
|
||||
}
|
||||
|
||||
let (enc, nonce) = bytes.split_at(bytes.len() - NONCE_LEN);
|
||||
assert_eq!(nonce.len(), NONCE_LEN);
|
||||
|
||||
let aes_key = Aes256Gcm::new(&self.key);
|
||||
|
||||
let dec = match aes_key.decrypt(Nonce::from_slice(nonce), enc) {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
log::error!("Failed to decrypt wrapped data! {:#?}", e);
|
||||
return Err(Box::new(std::io::Error::new(
|
||||
ErrorKind::Other,
|
||||
"Failed to decrypt wrapped data!",
|
||||
)));
|
||||
}
|
||||
};
|
||||
|
||||
Ok(bincode::deserialize(&dec)?)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::data::crypto_wrapper::CryptoWrapper;
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug)]
|
||||
struct Message(String);
|
||||
|
||||
#[test]
|
||||
fn encrypt_and_decrypt() {
|
||||
let wrapper = CryptoWrapper::new_random();
|
||||
let msg = Message("Pierre was here".to_string());
|
||||
let enc = wrapper.encrypt(&msg).unwrap();
|
||||
let dec: Message = wrapper.decrypt(&enc).unwrap();
|
||||
|
||||
assert_eq!(dec, msg)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encrypt_and_decrypt_invalid() {
|
||||
let wrapper_1 = CryptoWrapper::new_random();
|
||||
let wrapper_2 = CryptoWrapper::new_random();
|
||||
let msg = Message("Pierre was here".to_string());
|
||||
let enc = wrapper_1.encrypt(&msg).unwrap();
|
||||
wrapper_2.decrypt::<Message>(&enc).unwrap_err();
|
||||
}
|
||||
}
|
@@ -6,18 +6,34 @@ use actix::Addr;
|
||||
use actix_identity::Identity;
|
||||
use actix_web::dev::Payload;
|
||||
use actix_web::error::ErrorInternalServerError;
|
||||
use actix_web::{web, Error, FromRequest, HttpRequest};
|
||||
use actix_web::{Error, FromRequest, HttpRequest, web};
|
||||
|
||||
use crate::actors::users_actor;
|
||||
use crate::actors::users_actor::UsersActor;
|
||||
use crate::constants::SECOND_FACTOR_EXPIRATION_FOR_CRITICAL_OPERATIONS;
|
||||
use crate::data::session_identity::SessionIdentity;
|
||||
use crate::data::user::User;
|
||||
use crate::utils::time::time;
|
||||
|
||||
pub struct CurrentUser(User);
|
||||
pub struct CurrentUser {
|
||||
user: User,
|
||||
pub auth_time: u64,
|
||||
pub last_2fa_auth: Option<u64>,
|
||||
}
|
||||
|
||||
impl CurrentUser {
|
||||
pub fn should_request_2fa_for_critical_functions(&self) -> bool {
|
||||
self.user.has_two_factor()
|
||||
&& self
|
||||
.last_2fa_auth
|
||||
.map(|t| t + SECOND_FACTOR_EXPIRATION_FOR_CRITICAL_OPERATIONS < time())
|
||||
.unwrap_or(true)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CurrentUser> for User {
|
||||
fn from(user: CurrentUser) -> Self {
|
||||
user.0
|
||||
user.user
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,7 +41,7 @@ impl Deref for CurrentUser {
|
||||
type Target = User;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
&self.user
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,7 +56,10 @@ impl FromRequest for CurrentUser {
|
||||
let identity: Identity = Identity::from_request(req, payload)
|
||||
.into_inner()
|
||||
.expect("Failed to get identity!");
|
||||
let user_id = SessionIdentity(Some(&identity)).user_id();
|
||||
let id = SessionIdentity(Some(&identity));
|
||||
let user_id = id.user_id();
|
||||
let last_2fa_auth = id.last_2fa_auth();
|
||||
let auth_time = id.auth_time();
|
||||
|
||||
Box::pin(async move {
|
||||
let user = match user_actor
|
||||
@@ -57,7 +76,11 @@ impl FromRequest for CurrentUser {
|
||||
}
|
||||
};
|
||||
|
||||
Ok(CurrentUser(user))
|
||||
Ok(CurrentUser {
|
||||
user,
|
||||
auth_time,
|
||||
last_2fa_auth,
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
@@ -20,7 +20,10 @@ where
|
||||
/// Open entity
|
||||
pub fn open_or_create<A: AsRef<Path>>(path: A) -> Res<Self> {
|
||||
if !path.as_ref().is_file() {
|
||||
log::warn!("Entities at {:?} does not point to a file, creating a new empty entity container...", path.as_ref());
|
||||
log::warn!(
|
||||
"Entities at {:?} does not point to a file, creating a new empty entity container...",
|
||||
path.as_ref()
|
||||
);
|
||||
return Ok(Self {
|
||||
file_path: path.as_ref().to_path_buf(),
|
||||
list: vec![],
|
||||
|
45
src/data/force_2fa_auth.rs
Normal file
45
src/data/force_2fa_auth.rs
Normal file
@@ -0,0 +1,45 @@
|
||||
use crate::data::current_user::CurrentUser;
|
||||
use crate::data::session_identity::SessionIdentity;
|
||||
use actix_identity::Identity;
|
||||
use actix_web::dev::Payload;
|
||||
use actix_web::{Error, FromRequest, HttpRequest, web};
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
pub struct Force2FAAuthQuery {
|
||||
#[serde(default)]
|
||||
force_2fa: bool,
|
||||
}
|
||||
|
||||
pub struct Force2FAAuth {
|
||||
pub force: bool,
|
||||
}
|
||||
|
||||
impl FromRequest for Force2FAAuth {
|
||||
type Error = Error;
|
||||
type Future = Pin<Box<dyn Future<Output = Result<Self, Self::Error>>>>;
|
||||
|
||||
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
||||
let req = req.clone();
|
||||
|
||||
Box::pin(async move {
|
||||
// It is impossible to force authentication for an unauthenticated user
|
||||
let identity = Identity::from_request(&req, &mut Payload::None)
|
||||
.into_inner()
|
||||
.ok();
|
||||
if !SessionIdentity(identity.as_ref()).is_authenticated() {
|
||||
return Ok(Self { force: false });
|
||||
}
|
||||
|
||||
let query = web::Query::<Force2FAAuthQuery>::from_request(&req, &mut Payload::None)
|
||||
.into_inner()?;
|
||||
|
||||
let user = CurrentUser::from_request(&req, &mut Payload::None).await?;
|
||||
|
||||
Ok(Self {
|
||||
force: query.force_2fa && user.has_two_factor(),
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
32
src/data/from_request_redirect.rs
Normal file
32
src/data/from_request_redirect.rs
Normal file
@@ -0,0 +1,32 @@
|
||||
use actix_web::body::BoxBody;
|
||||
use actix_web::http::StatusCode;
|
||||
use actix_web::{HttpResponse, ResponseError};
|
||||
use std::fmt::{Debug, Display, Formatter};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct FromRequestRedirect {
|
||||
url: String,
|
||||
}
|
||||
|
||||
impl FromRequestRedirect {
|
||||
pub fn new(url: String) -> Self {
|
||||
Self { url }
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for FromRequestRedirect {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "Redirect to {}", self.url)
|
||||
}
|
||||
}
|
||||
|
||||
impl ResponseError for FromRequestRedirect {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
StatusCode::FOUND
|
||||
}
|
||||
fn error_response(&self) -> HttpResponse<BoxBody> {
|
||||
HttpResponse::Found()
|
||||
.insert_header(("Location", self.url.as_str()))
|
||||
.body("Redirecting...")
|
||||
}
|
||||
}
|
@@ -1,7 +1,8 @@
|
||||
use crate::data::client::AdditionalClaims;
|
||||
use jwt_simple::claims::Audiences;
|
||||
use jwt_simple::prelude::{Duration, JWTClaims};
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
#[derive(serde::Serialize, Debug)]
|
||||
pub struct IdToken {
|
||||
/// REQUIRED. Issuer Identifier for the Issuer of the response. The iss value is a case sensitive URL using the https scheme that contains scheme, host, and optionally, port number and path components and no query or fragment components.
|
||||
#[serde(rename = "iss")]
|
||||
@@ -24,12 +25,19 @@ pub struct IdToken {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub nonce: Option<String>,
|
||||
pub email: String,
|
||||
/// Additional claims
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(flatten)]
|
||||
pub additional_claims: Option<AdditionalClaims>,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
pub struct CustomIdTokenClaims {
|
||||
auth_time: u64,
|
||||
email: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(flatten)]
|
||||
additional_claims: Option<AdditionalClaims>,
|
||||
}
|
||||
|
||||
impl IdToken {
|
||||
@@ -46,6 +54,7 @@ impl IdToken {
|
||||
custom: CustomIdTokenClaims {
|
||||
auth_time: self.auth_time,
|
||||
email: self.email,
|
||||
additional_claims: self.additional_claims,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
@@ -1,14 +1,20 @@
|
||||
use jwt_simple::algorithms::RSAKeyPairLike;
|
||||
use jwt_simple::claims::JWTClaims;
|
||||
use jwt_simple::prelude::RS256KeyPair;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::URL_SAFE as BASE64_URL_URL_SAFE;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD as BASE64_URL_SAFE_NO_PAD;
|
||||
|
||||
use crate::utils::err::Res;
|
||||
use crate::utils::string_utils::rand_str;
|
||||
|
||||
const JWK_USE_SIGN: &str = "sig";
|
||||
|
||||
/// Json Web Key <https://datatracker.ietf.org/doc/html/rfc7517>
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct JsonWebKey {
|
||||
#[serde(rename = "alg")]
|
||||
algorithm: String,
|
||||
@@ -20,6 +26,8 @@ pub struct JsonWebKey {
|
||||
modulus: String,
|
||||
#[serde(rename = "e")]
|
||||
public_exponent: String,
|
||||
#[serde(rename = "use", skip_serializing_if = "Option::is_none")]
|
||||
usage: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -38,8 +46,9 @@ impl JWTSigner {
|
||||
algorithm: "RS256".to_string(),
|
||||
key_type: "RSA".to_string(),
|
||||
key_id: self.0.key_id().as_ref().unwrap().to_string(),
|
||||
public_exponent: base64::encode_config(components.e, base64::URL_SAFE),
|
||||
modulus: base64::encode_config(components.n, base64::URL_SAFE_NO_PAD),
|
||||
public_exponent: BASE64_URL_URL_SAFE.encode(components.e),
|
||||
modulus: BASE64_URL_SAFE_NO_PAD.encode(components.n),
|
||||
usage: Some(JWK_USE_SIGN.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -1,7 +1,13 @@
|
||||
use actix_web::HttpRequest;
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize, Debug, Eq, PartialEq, Clone)]
|
||||
pub struct LoginRedirect(String);
|
||||
|
||||
impl LoginRedirect {
|
||||
pub fn from_req(req: &HttpRequest) -> Self {
|
||||
Self(req.uri().to_string())
|
||||
}
|
||||
|
||||
pub fn get(&self) -> &str {
|
||||
match self.0.starts_with('/') && !self.0.starts_with("//") {
|
||||
true => self.0.as_str(),
|
||||
@@ -19,3 +25,11 @@ impl Default for LoginRedirect {
|
||||
Self("/".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the URL for 2FA authentication
|
||||
pub fn get_2fa_url(redir: &LoginRedirect, force_2fa: bool) -> String {
|
||||
format!(
|
||||
"/2fa_auth?redirect={}&force_2fa={force_2fa}",
|
||||
redir.get_encoded()
|
||||
)
|
||||
}
|
||||
|
@@ -1,17 +1,20 @@
|
||||
pub mod access_token;
|
||||
pub mod action_logger;
|
||||
pub mod app_config;
|
||||
pub mod client;
|
||||
pub mod code_challenge;
|
||||
pub mod crypto_wrapper;
|
||||
pub mod critical_route;
|
||||
pub mod current_user;
|
||||
pub mod entity_manager;
|
||||
pub mod force_2fa_auth;
|
||||
pub mod from_request_redirect;
|
||||
pub mod id_token;
|
||||
pub mod jwt_signer;
|
||||
pub mod login_redirect;
|
||||
pub mod open_id_user_info;
|
||||
pub mod openid_config;
|
||||
pub mod remote_ip;
|
||||
pub mod provider;
|
||||
pub mod provider_configuration;
|
||||
pub mod session_identity;
|
||||
pub mod totp_key;
|
||||
pub mod user;
|
||||
pub mod users_file_entity;
|
||||
pub mod webauthn_manager;
|
||||
|
@@ -1,24 +0,0 @@
|
||||
/// Refer to <https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims> for more information
|
||||
#[derive(Debug, serde::Serialize)]
|
||||
pub struct OpenIDUserInfo {
|
||||
/// Subject - Identifier for the End-User at the Issuer
|
||||
pub sub: String,
|
||||
|
||||
/// End-User's full name in displayable form including all name parts, possibly including titles and suffixes, ordered according to the End-User's locale and preferences.
|
||||
pub name: String,
|
||||
|
||||
/// Given name(s) or first name(s) of the End-User. Note that in some cultures, people can have multiple given names; all can be present, with the names being separated by space characters.
|
||||
pub given_name: String,
|
||||
|
||||
/// Surname(s) or last name(s) of the End-User. Note that in some cultures, people can have multiple family names or no family name; all can be present, with the names being separated by space characters.
|
||||
pub family_name: String,
|
||||
|
||||
/// Shorthand name by which the End-User wishes to be referred to at the RP, such as janedoe or j.doe. This value MAY be any valid JSON string including special characters such as @, /, or whitespace. The RP MUST NOT rely upon this value being unique, as discussed in
|
||||
pub preferred_username: String,
|
||||
|
||||
/// End-User's preferred e-mail address. Its value MUST conform to the RFC 5322 RFC5322 addr-spec syntax. The RP MUST NOT rely upon this value being unique, as discussed in Section 5.7.
|
||||
pub email: String,
|
||||
|
||||
/// True if the End-User's e-mail address has been verified; otherwise false. When this Claim Value is true, this means that the OP took affirmative steps to ensure that this e-mail address was controlled by the End-User at the time the verification was performed. The means by which an e-mail address is verified is context-specific, and dependent upon the trust framework or contractual agreements within which the parties are operating.
|
||||
pub email_verified: bool,
|
||||
}
|
@@ -1,37 +0,0 @@
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct OpenIDConfig {
|
||||
/// URL using the https scheme with no query or fragment component that the OP asserts as its Issuer Identifier. If Issuer discovery is supported (see Section 2), this value MUST be identical to the issuer value returned by WebFinger. This also MUST be identical to the iss Claim value in ID Tokens issued from this Issuer
|
||||
pub issuer: String,
|
||||
|
||||
/// REQUIRED. URL of the OP's OAuth 2.0 Authorization Endpoint `OpenID.Core`
|
||||
pub authorization_endpoint: String,
|
||||
|
||||
/// URL of the OP's OAuth 2.0 Token Endpoint `OpenID.Core`. This is REQUIRED unless only the Implicit Flow is used.
|
||||
pub token_endpoint: String,
|
||||
|
||||
/// RECOMMENDED. URL of the OP's UserInfo Endpoint `[`OpenID.Core`]`. This URL MUST use the https scheme and MAY contain port, path, and query parameter components
|
||||
pub userinfo_endpoint: String,
|
||||
|
||||
/// REQUIRED. URL of the OP's JSON Web Key Set `[`JWK`]` document. This contains the signing key(s) the RP uses to validate signatures from the OP. The JWK Set MAY also contain the Server's encryption key(s), which are used by RPs to encrypt requests to the Server. When both signing and encryption keys are made available, a use (Key Use) parameter value is REQUIRED for all keys in the referenced JWK Set to indicate each key's intended usage. Although some algorithms allow the same key to be used for both signatures and encryption, doing so is NOT RECOMMENDED, as it is less secure. The JWK x5c parameter MAY be used to provide X.509 representations of keys provided. When used, the bare key values MUST still be present and MUST match those in the certificate.
|
||||
pub jwks_uri: String,
|
||||
|
||||
/// RECOMMENDED. JSON array containing a list of the OAuth 2.0 `[`RFC6749`]` scope values that this server supports. The server MUST support the openid scope value. Servers MAY choose not to advertise some supported scope values even when this parameter is used, although those defined in `[`OpenID.Core`]` SHOULD be listed, if supported.
|
||||
pub scopes_supported: Vec<&'static str>,
|
||||
|
||||
/// REQUIRED. JSON array containing a list of the OAuth 2.0 response_type values that this OP supports. Dynamic OpenID Providers MUST support the code, id_token, and the token id_token Response Type values.
|
||||
pub response_types_supported: Vec<&'static str>,
|
||||
|
||||
/// REQUIRED. JSON array containing a list of the Subject Identifier types that this OP supports. Valid types include pairwise and public.
|
||||
pub subject_types_supported: Vec<&'static str>,
|
||||
|
||||
/// REQUIRED. JSON array containing a list of the JWS signing algorithms (alg values) supported by the OP for the ID Token to encode the Claims in a JWT `[`JWT`. The algorithm RS256 MUST be included. The value none MAY be supported, but MUST NOT be used unless the Response Type used returns no ID Token from the Authorization Endpoint (such as when using the Authorization Code Flow).
|
||||
pub id_token_signing_alg_values_supported: Vec<&'static str>,
|
||||
|
||||
/// OPTIONAL. JSON array containing a list of Client Authentication methods supported by this Token Endpoint. The options are client_secret_post, client_secret_basic, client_secret_jwt, and private_key_jwt
|
||||
pub token_endpoint_auth_methods_supported: Vec<&'static str>,
|
||||
|
||||
/// RECOMMENDED. JSON array containing a list of the Claim Names of the Claims that the OpenID Provider MAY be able to supply values for. Note that for privacy or other reasons, this might not be an exhaustive list.
|
||||
pub claims_supported: Vec<&'static str>,
|
||||
|
||||
pub code_challenge_methods_supported: Vec<&'static str>,
|
||||
}
|
89
src/data/provider.rs
Normal file
89
src/data/provider.rs
Normal file
@@ -0,0 +1,89 @@
|
||||
use crate::data::entity_manager::EntityManager;
|
||||
use crate::data::login_redirect::LoginRedirect;
|
||||
use crate::utils::string_utils::apply_env_vars;
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq)]
|
||||
pub struct ProviderID(pub String);
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Provider {
|
||||
/// The ID of the provider
|
||||
pub id: ProviderID,
|
||||
|
||||
/// The human-readable name of the client
|
||||
pub name: String,
|
||||
|
||||
/// A logo presented to the users of the provider
|
||||
pub logo: String,
|
||||
|
||||
/// The registration id of BasicOIDC on the provider
|
||||
pub client_id: String,
|
||||
|
||||
/// The registration secret of BasicOIDC on the provider
|
||||
pub client_secret: String,
|
||||
|
||||
/// Specify the URL of the OpenID configuration URL
|
||||
///
|
||||
/// (.well-known/openid-configuration endpoint)
|
||||
pub configuration_url: String,
|
||||
}
|
||||
|
||||
impl Provider {
|
||||
/// Get URL-encoded provider id
|
||||
pub fn id_encoded(&self) -> String {
|
||||
urlencoding::encode(&self.id.0).to_string()
|
||||
}
|
||||
|
||||
/// Get the URL where the logo can be located
|
||||
pub fn logo_url(&self) -> &str {
|
||||
match self.logo.as_str() {
|
||||
"gitea" => "/assets/img/brands/gitea.svg",
|
||||
"gitlab" => "/assets/img/brands/gitlab.svg",
|
||||
"github" => "/assets/img/brands/github.svg",
|
||||
"microsoft" => "/assets/img/brands/microsoft.svg",
|
||||
"google" => "/assets/img/brands/google.svg",
|
||||
s => s,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the URL to use to login with the provider
|
||||
pub fn login_url(&self, redirect_url: &LoginRedirect) -> String {
|
||||
format!(
|
||||
"/login_with_prov?id={}&redirect={}",
|
||||
self.id_encoded(),
|
||||
redirect_url.get_encoded()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Provider {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.id.eq(&other.id)
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for Provider {}
|
||||
|
||||
pub type ProvidersManager = EntityManager<Provider>;
|
||||
|
||||
impl EntityManager<Provider> {
|
||||
pub fn find_by_id(&self, u: &ProviderID) -> Option<Provider> {
|
||||
for entry in self.iter() {
|
||||
if entry.id.eq(u) {
|
||||
return Some(entry.clone());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn apply_environment_variables(&mut self) {
|
||||
for c in self.iter_mut() {
|
||||
c.id = ProviderID(apply_env_vars(&c.id.0));
|
||||
c.name = apply_env_vars(&c.name);
|
||||
c.logo = apply_env_vars(&c.logo);
|
||||
c.client_id = apply_env_vars(&c.client_id);
|
||||
c.client_secret = apply_env_vars(&c.client_secret);
|
||||
c.configuration_url = apply_env_vars(&c.configuration_url);
|
||||
}
|
||||
}
|
||||
}
|
93
src/data/provider_configuration.rs
Normal file
93
src/data/provider_configuration.rs
Normal file
@@ -0,0 +1,93 @@
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use light_openid::primitives::{OpenIDConfig, OpenIDTokenResponse, OpenIDUserInfo};
|
||||
|
||||
use crate::actors::providers_states_actor::ProviderLoginState;
|
||||
use crate::constants::OIDC_PROVIDERS_LIFETIME;
|
||||
use crate::data::app_config::AppConfig;
|
||||
|
||||
use crate::data::provider::Provider;
|
||||
use crate::utils::err::Res;
|
||||
use crate::utils::time::time;
|
||||
|
||||
/// Provider configuration
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ProviderConfiguration {
|
||||
pub discovery: OpenIDConfig,
|
||||
pub expire: u64,
|
||||
}
|
||||
|
||||
impl ProviderConfiguration {
|
||||
/// Get the URL where a user should be redirected to authenticate
|
||||
pub fn auth_url(&self, provider: &Provider, state: &ProviderLoginState) -> String {
|
||||
let authorization_url = &self.discovery.authorization_endpoint;
|
||||
let client_id = urlencoding::encode(&provider.client_id).to_string();
|
||||
let state = urlencoding::encode(&state.state_id).to_string();
|
||||
let callback_url = AppConfig::get().oidc_provider_redirect_url();
|
||||
|
||||
format!(
|
||||
"{authorization_url}?response_type=code&scope=openid%20profile%20email&client_id={client_id}&state={state}&redirect_uri={callback_url}"
|
||||
)
|
||||
}
|
||||
|
||||
/// Retrieve the authorization token after a successful authentication, using an authorization code
|
||||
pub async fn get_token(
|
||||
&self,
|
||||
provider: &Provider,
|
||||
authorization_code: &str,
|
||||
) -> Res<OpenIDTokenResponse> {
|
||||
let (token, _) = self
|
||||
.discovery
|
||||
.request_token(
|
||||
&provider.client_id,
|
||||
&provider.client_secret,
|
||||
authorization_code,
|
||||
&AppConfig::get().oidc_provider_redirect_url(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(token)
|
||||
}
|
||||
|
||||
/// Retrieve information about the user, using a given [OpenIDTokenResponse]
|
||||
pub async fn get_userinfo(&self, token: &OpenIDTokenResponse) -> Res<OpenIDUserInfo> {
|
||||
Ok(self.discovery.request_user_info(token).await?.0)
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static THREAD_CACHE: RefCell<HashMap<String, ProviderConfiguration>> = RefCell::new(Default::default());
|
||||
}
|
||||
|
||||
pub struct ProviderConfigurationHelper {}
|
||||
|
||||
impl ProviderConfigurationHelper {
|
||||
/// Get or refresh the configuration for a provider
|
||||
pub async fn get_configuration(provider: &Provider) -> Res<ProviderConfiguration> {
|
||||
let config = THREAD_CACHE.with(|i| i.borrow().get(&provider.configuration_url).cloned());
|
||||
|
||||
// Refresh config cache if needed
|
||||
if config.is_none() || config.as_ref().unwrap().expire < time() {
|
||||
let conf = Self::fetch_configuration(provider).await?;
|
||||
|
||||
THREAD_CACHE.with(|i| {
|
||||
i.borrow_mut()
|
||||
.insert(provider.configuration_url.clone(), conf.clone())
|
||||
});
|
||||
|
||||
return Ok(conf);
|
||||
}
|
||||
|
||||
// We can return immediately previously extracted value
|
||||
Ok(config.unwrap())
|
||||
}
|
||||
|
||||
/// Get fresh configuration from provider
|
||||
async fn fetch_configuration(provider: &Provider) -> Res<ProviderConfiguration> {
|
||||
Ok(ProviderConfiguration {
|
||||
discovery: OpenIDConfig::load_from_url(&provider.configuration_url).await?,
|
||||
expire: time() + OIDC_PROVIDERS_LIFETIME,
|
||||
})
|
||||
}
|
||||
}
|
@@ -1,30 +0,0 @@
|
||||
use std::net::IpAddr;
|
||||
|
||||
use actix_web::dev::Payload;
|
||||
use actix_web::{Error, FromRequest, HttpRequest};
|
||||
use futures_util::future::{ready, Ready};
|
||||
|
||||
use crate::data::app_config::AppConfig;
|
||||
use crate::utils::network_utils::get_remote_ip;
|
||||
|
||||
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
|
||||
pub struct RemoteIP(pub IpAddr);
|
||||
|
||||
impl From<RemoteIP> for IpAddr {
|
||||
fn from(i: RemoteIP) -> Self {
|
||||
i.0
|
||||
}
|
||||
}
|
||||
|
||||
impl FromRequest for RemoteIP {
|
||||
type Error = Error;
|
||||
type Future = Ready<Result<Self, Error>>;
|
||||
|
||||
#[inline]
|
||||
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
||||
ready(Ok(RemoteIP(get_remote_ip(
|
||||
req,
|
||||
AppConfig::get().proxy_ip.as_deref(),
|
||||
))))
|
||||
}
|
||||
}
|
@@ -24,12 +24,13 @@ pub struct SessionIdentityData {
|
||||
pub id: Option<UserID>,
|
||||
pub is_admin: bool,
|
||||
pub auth_time: u64,
|
||||
pub last_2fa_auth: Option<u64>,
|
||||
pub status: SessionStatus,
|
||||
}
|
||||
|
||||
pub struct SessionIdentity<'a>(pub Option<&'a Identity>);
|
||||
|
||||
impl<'a> SessionIdentity<'a> {
|
||||
impl SessionIdentity<'_> {
|
||||
fn get_session_data(&self) -> Option<SessionIdentityData> {
|
||||
if let Some(id) = self.0 {
|
||||
Self::deserialize_session_data(id.id().ok())
|
||||
@@ -45,7 +46,7 @@ impl<'a> SessionIdentity<'a> {
|
||||
.map(|f| match f {
|
||||
Ok(d) => Some(d),
|
||||
Err(e) => {
|
||||
log::warn!("Failed to deserialize session data! {:?}", e);
|
||||
log::warn!("Failed to deserialize session data! {e:?}");
|
||||
None
|
||||
}
|
||||
})
|
||||
@@ -64,7 +65,7 @@ impl<'a> SessionIdentity<'a> {
|
||||
|
||||
log::debug!("Will set user session data.");
|
||||
if let Err(e) = Identity::login(&req.extensions(), s) {
|
||||
log::error!("Failed to set session data! {}", e);
|
||||
log::error!("Failed to set session data! {e}");
|
||||
}
|
||||
log::debug!("Did set user session data.");
|
||||
}
|
||||
@@ -75,6 +76,7 @@ impl<'a> SessionIdentity<'a> {
|
||||
&SessionIdentityData {
|
||||
id: Some(user.uid.clone()),
|
||||
is_admin: user.admin,
|
||||
last_2fa_auth: None,
|
||||
auth_time: time(),
|
||||
status,
|
||||
},
|
||||
@@ -87,6 +89,12 @@ impl<'a> SessionIdentity<'a> {
|
||||
self.set_session_data(req, &sess);
|
||||
}
|
||||
|
||||
pub fn record_2fa_auth(&self, req: &HttpRequest) {
|
||||
let mut sess = self.get_session_data().unwrap_or_default();
|
||||
sess.last_2fa_auth = Some(time());
|
||||
self.set_session_data(req, &sess);
|
||||
}
|
||||
|
||||
pub fn is_authenticated(&self) -> bool {
|
||||
self.get_session_data()
|
||||
.map(|s| s.status == SessionStatus::SignedIn)
|
||||
@@ -119,4 +127,8 @@ impl<'a> SessionIdentity<'a> {
|
||||
pub fn auth_time(&self) -> u64 {
|
||||
self.get_session_data().unwrap_or_default().auth_time
|
||||
}
|
||||
|
||||
pub fn last_2fa_auth(&self) -> Option<u64> {
|
||||
self.get_session_data().unwrap_or_default().last_2fa_auth
|
||||
}
|
||||
}
|
||||
|
@@ -1,5 +1,3 @@
|
||||
use std::io::ErrorKind;
|
||||
|
||||
use base32::Alphabet;
|
||||
use rand::Rng;
|
||||
use totp_rfc6238::{HashAlgorithm, TotpGenerator};
|
||||
@@ -9,7 +7,7 @@ use crate::data::user::User;
|
||||
use crate::utils::err::Res;
|
||||
use crate::utils::time::time;
|
||||
|
||||
const BASE32_ALPHABET: Alphabet = Alphabet::RFC4648 { padding: true };
|
||||
const BASE32_ALPHABET: Alphabet = Alphabet::Rfc4648 { padding: true };
|
||||
const NUM_DIGITS: usize = 6;
|
||||
const PERIOD: u64 = 30;
|
||||
|
||||
@@ -21,7 +19,7 @@ pub struct TotpKey {
|
||||
impl TotpKey {
|
||||
/// Generate a new TOTP key
|
||||
pub fn new_random() -> Self {
|
||||
let random_bytes = rand::thread_rng().gen::<[u8; 10]>();
|
||||
let random_bytes = rand::rng().random::<[u8; 20]>();
|
||||
Self {
|
||||
encoded: base32::encode(BASE32_ALPHABET, &random_bytes),
|
||||
}
|
||||
@@ -40,10 +38,10 @@ impl TotpKey {
|
||||
pub fn url_for_user(&self, u: &User, conf: &AppConfig) -> String {
|
||||
format!(
|
||||
"otpauth://totp/{}:{}?secret={}&issuer={}&algorithm=SHA1&digits={}&period={}",
|
||||
urlencoding::encode(conf.domain_name()),
|
||||
urlencoding::encode(conf.domain_name_without_port()),
|
||||
urlencoding::encode(&u.username),
|
||||
self.encoded,
|
||||
urlencoding::encode(conf.domain_name()),
|
||||
urlencoding::encode(conf.domain_name_without_port()),
|
||||
NUM_DIGITS,
|
||||
PERIOD,
|
||||
)
|
||||
@@ -53,7 +51,7 @@ impl TotpKey {
|
||||
pub fn account_name(&self, u: &User, conf: &AppConfig) -> String {
|
||||
format!(
|
||||
"{}:{}",
|
||||
urlencoding::encode(conf.domain_name()),
|
||||
urlencoding::encode(conf.domain_name_without_port()),
|
||||
urlencoding::encode(&u.username)
|
||||
)
|
||||
}
|
||||
@@ -73,9 +71,14 @@ impl TotpKey {
|
||||
self.get_code_at(|| time() - PERIOD)
|
||||
}
|
||||
|
||||
/// Get following code
|
||||
pub fn following_code(&self) -> Res<String> {
|
||||
self.get_code_at(|| time() + PERIOD)
|
||||
}
|
||||
|
||||
/// Get the code at a specific time
|
||||
fn get_code_at<F: Fn() -> u64>(&self, get_time: F) -> Res<String> {
|
||||
let gen = TotpGenerator::new()
|
||||
let generator = TotpGenerator::new()
|
||||
.set_digit(NUM_DIGITS)
|
||||
.unwrap()
|
||||
.set_step(PERIOD)
|
||||
@@ -85,20 +88,21 @@ impl TotpKey {
|
||||
|
||||
let key = match base32::decode(BASE32_ALPHABET, &self.encoded) {
|
||||
None => {
|
||||
return Err(Box::new(std::io::Error::new(
|
||||
ErrorKind::Other,
|
||||
return Err(Box::new(std::io::Error::other(
|
||||
"Failed to decode base32 secret!",
|
||||
)));
|
||||
}
|
||||
Some(k) => k,
|
||||
};
|
||||
|
||||
Ok(gen.get_code_with(&key, get_time))
|
||||
Ok(generator.get_code_with(&key, get_time))
|
||||
}
|
||||
|
||||
/// Check a code's validity
|
||||
pub fn check_code(&self, code: &str) -> Res<bool> {
|
||||
Ok(self.current_code()?.eq(code) || self.previous_code()?.eq(code))
|
||||
Ok(self.previous_code()?.eq(code)
|
||||
|| self.current_code()?.eq(code)
|
||||
|| self.following_code()?.eq(code))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,7 +115,10 @@ mod test {
|
||||
let key = TotpKey::new_random();
|
||||
let code = key.current_code().unwrap();
|
||||
let old_code = key.previous_code().unwrap();
|
||||
let following_code = key.following_code().unwrap();
|
||||
assert_ne!(code, old_code);
|
||||
assert_ne!(code, following_code);
|
||||
assert_ne!(old_code, following_code);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
222
src/data/user.rs
222
src/data/user.rs
@@ -1,18 +1,48 @@
|
||||
use bincode::{Decode, Encode};
|
||||
use std::collections::HashMap;
|
||||
use std::net::IpAddr;
|
||||
|
||||
use crate::actors::users_actor::AuthorizedAuthenticationSources;
|
||||
use crate::constants::SECOND_FACTOR_EXEMPTION_AFTER_SUCCESSFUL_LOGIN;
|
||||
use crate::data::client::ClientID;
|
||||
use crate::data::entity_manager::EntityManager;
|
||||
use crate::data::client::{Client, ClientID};
|
||||
use crate::data::login_redirect::LoginRedirect;
|
||||
use crate::data::provider::{Provider, ProviderID};
|
||||
use crate::data::totp_key::TotpKey;
|
||||
use crate::data::webauthn_manager::WebauthnPubKey;
|
||||
use crate::utils::err::Res;
|
||||
use crate::utils::time::{fmt_time, time};
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Encode, Decode)]
|
||||
pub struct UserID(pub String);
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct GeneralSettings {
|
||||
pub uid: UserID,
|
||||
pub username: String,
|
||||
pub first_name: String,
|
||||
pub last_name: String,
|
||||
pub email: String,
|
||||
pub enabled: bool,
|
||||
pub two_factor_exemption_after_successful_login: bool,
|
||||
pub is_admin: bool,
|
||||
}
|
||||
|
||||
#[derive(Eq, PartialEq, Clone, Debug)]
|
||||
pub enum GrantedClients {
|
||||
AllClients,
|
||||
SomeClients(Vec<ClientID>),
|
||||
NoClient,
|
||||
}
|
||||
|
||||
impl GrantedClients {
|
||||
pub fn to_user(self) -> Option<Vec<ClientID>> {
|
||||
match self {
|
||||
GrantedClients::AllClients => None,
|
||||
GrantedClients::SomeClients(users) => Some(users),
|
||||
GrantedClients::NoClient => Some(vec![]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct FactorID(pub String);
|
||||
|
||||
@@ -30,6 +60,15 @@ pub struct TwoFactor {
|
||||
}
|
||||
|
||||
impl TwoFactor {
|
||||
pub fn quick_description(&self) -> String {
|
||||
format!(
|
||||
"#{} of type {} and name '{}'",
|
||||
self.id.0,
|
||||
self.type_str(),
|
||||
self.name
|
||||
)
|
||||
}
|
||||
|
||||
pub fn type_str(&self) -> &'static str {
|
||||
match self.kind {
|
||||
TwoFactorType::TOTP(_) => "Authenticator app",
|
||||
@@ -51,11 +90,17 @@ impl TwoFactor {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn login_url(&self, redirect_uri: &LoginRedirect) -> String {
|
||||
pub fn login_url(&self, redirect_uri: &LoginRedirect, force_2fa: bool) -> String {
|
||||
match self.kind {
|
||||
TwoFactorType::TOTP(_) => format!("/2fa_otp?redirect={}", redirect_uri.get_encoded()),
|
||||
TwoFactorType::TOTP(_) => format!(
|
||||
"/2fa_otp?redirect={}&force_2fa={force_2fa}",
|
||||
redirect_uri.get_encoded()
|
||||
),
|
||||
TwoFactorType::WEBAUTHN(_) => {
|
||||
format!("/2fa_webauthn?redirect={}", redirect_uri.get_encoded())
|
||||
format!(
|
||||
"/2fa_webauthn?redirect={}&force_2fa={force_2fa}",
|
||||
redirect_uri.get_encoded()
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -78,6 +123,10 @@ impl Successful2FALogin {
|
||||
}
|
||||
}
|
||||
|
||||
fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct User {
|
||||
pub uid: UserID,
|
||||
@@ -106,6 +155,14 @@ pub struct User {
|
||||
/// None = all services
|
||||
/// Some([]) = no service
|
||||
pub authorized_clients: Option<Vec<ClientID>>,
|
||||
|
||||
/// Authorize connection through local login
|
||||
#[serde(default = "default_true")]
|
||||
pub allow_local_login: bool,
|
||||
|
||||
/// Allowed third party providers
|
||||
#[serde(default)]
|
||||
pub allow_login_from_providers: Vec<ProviderID>,
|
||||
}
|
||||
|
||||
impl User {
|
||||
@@ -113,15 +170,50 @@ impl User {
|
||||
format!("{} {}", self.first_name, self.last_name)
|
||||
}
|
||||
|
||||
pub fn can_access_app(&self, id: &ClientID) -> bool {
|
||||
match &self.authorized_clients {
|
||||
None => true,
|
||||
Some(c) => c.contains(id),
|
||||
pub fn quick_identity(&self) -> String {
|
||||
format!(
|
||||
"{} {} {} ({:?})",
|
||||
match self.admin {
|
||||
true => "admin",
|
||||
false => "user",
|
||||
},
|
||||
self.username,
|
||||
self.email,
|
||||
self.uid
|
||||
)
|
||||
}
|
||||
|
||||
/// Get the list of sources from which a user can authenticate from
|
||||
pub fn authorized_authentication_sources(&self) -> AuthorizedAuthenticationSources {
|
||||
AuthorizedAuthenticationSources {
|
||||
local: self.allow_local_login,
|
||||
upstream: self.allow_login_from_providers.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn verify_password<P: AsRef<[u8]>>(&self, pass: P) -> bool {
|
||||
verify_password(pass, &self.password)
|
||||
/// Check if a user can authenticate using a givne provider or not
|
||||
pub fn can_login_from_provider(&self, provider: &Provider) -> bool {
|
||||
self.allow_login_from_providers.contains(&provider.id)
|
||||
}
|
||||
|
||||
pub fn granted_clients(&self) -> GrantedClients {
|
||||
match self.authorized_clients.as_deref() {
|
||||
None => GrantedClients::AllClients,
|
||||
Some(&[]) => GrantedClients::NoClient,
|
||||
Some(clients) => GrantedClients::SomeClients(clients.to_vec()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn can_access_app(&self, client: &Client) -> bool {
|
||||
if client.granted_to_all_users {
|
||||
return true;
|
||||
}
|
||||
|
||||
match self.granted_clients() {
|
||||
GrantedClients::AllClients => true,
|
||||
GrantedClients::SomeClients(c) => c.contains(&client.id),
|
||||
GrantedClients::NoClient => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn has_two_factor(&self) -> bool {
|
||||
@@ -135,12 +227,19 @@ impl User {
|
||||
> time()
|
||||
}
|
||||
|
||||
pub fn add_factor(&mut self, factor: TwoFactor) {
|
||||
self.two_factor.push(factor);
|
||||
pub fn update_general_settings(&mut self, settings: GeneralSettings) {
|
||||
self.username = settings.username;
|
||||
self.first_name = settings.first_name;
|
||||
self.last_name = settings.last_name;
|
||||
self.email = settings.email;
|
||||
self.enabled = settings.enabled;
|
||||
self.two_factor_exemption_after_successful_login =
|
||||
settings.two_factor_exemption_after_successful_login;
|
||||
self.admin = settings.is_admin;
|
||||
}
|
||||
|
||||
pub fn remove_factor(&mut self, factor_id: FactorID) {
|
||||
self.two_factor.retain(|f| f.id != factor_id);
|
||||
pub fn add_factor(&mut self, factor: TwoFactor) {
|
||||
self.two_factor.push(factor);
|
||||
}
|
||||
|
||||
pub fn find_factor(&self, factor_id: &FactorID) -> Option<&TwoFactor> {
|
||||
@@ -231,93 +330,8 @@ impl Default for User {
|
||||
two_factor_exemption_after_successful_login: false,
|
||||
last_successful_2fa: Default::default(),
|
||||
authorized_clients: Some(Vec::new()),
|
||||
allow_local_login: true,
|
||||
allow_login_from_providers: vec![],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn hash_password<P: AsRef<[u8]>>(pwd: P) -> Res<String> {
|
||||
Ok(bcrypt::hash(pwd, bcrypt::DEFAULT_COST)?)
|
||||
}
|
||||
|
||||
pub fn verify_password<P: AsRef<[u8]>>(pwd: P, hash: &str) -> bool {
|
||||
match bcrypt::verify(pwd, hash) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
log::warn!("Failed to verify password! {:?}", e);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EntityManager<User> {
|
||||
pub fn find_by_username_or_email(&self, u: &str) -> Option<User> {
|
||||
for entry in self.iter() {
|
||||
if entry.username.eq(u) || entry.email.eq(u) {
|
||||
return Some(entry.clone());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn find_by_user_id(&self, id: &UserID) -> Option<User> {
|
||||
for entry in self.iter() {
|
||||
if entry.uid.eq(id) {
|
||||
return Some(entry.clone());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Update user information
|
||||
fn update_user<F>(&mut self, id: &UserID, update: F) -> bool
|
||||
where
|
||||
F: FnOnce(User) -> User,
|
||||
{
|
||||
let user = match self.find_by_user_id(id) {
|
||||
None => return false,
|
||||
Some(user) => user,
|
||||
};
|
||||
|
||||
if let Err(e) = self.replace_entries(|u| u.uid.eq(id), &update(user)) {
|
||||
log::error!("Failed to update user information! {:?}", e);
|
||||
return false;
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
pub fn change_user_password(&mut self, id: &UserID, password: &str, temporary: bool) -> bool {
|
||||
let new_hash = match hash_password(password) {
|
||||
Ok(h) => h,
|
||||
Err(e) => {
|
||||
log::error!("Failed to hash user password! {}", e);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
self.update_user(id, |mut user| {
|
||||
user.password = new_hash;
|
||||
user.need_reset_password = temporary;
|
||||
user.two_factor_exemption_after_successful_login = Default::default();
|
||||
user
|
||||
})
|
||||
}
|
||||
|
||||
pub fn save_new_successful_2fa_authentication(&mut self, id: &UserID, ip: IpAddr) -> bool {
|
||||
self.update_user(id, |mut user| {
|
||||
user.last_successful_2fa.insert(ip, time());
|
||||
|
||||
// Remove outdated successful attempts
|
||||
user.remove_outdated_successful_2fa_attempts();
|
||||
|
||||
user
|
||||
})
|
||||
}
|
||||
|
||||
pub fn clear_2fa_login_history(&mut self, id: &UserID) -> bool {
|
||||
self.update_user(id, |mut user| {
|
||||
user.last_successful_2fa = Default::default();
|
||||
user
|
||||
})
|
||||
}
|
||||
}
|
||||
|
173
src/data/users_file_entity.rs
Normal file
173
src/data/users_file_entity.rs
Normal file
@@ -0,0 +1,173 @@
|
||||
use std::net::IpAddr;
|
||||
|
||||
use crate::actors::users_actor::{AuthorizedAuthenticationSources, UsersSyncBackend};
|
||||
use crate::data::entity_manager::EntityManager;
|
||||
use crate::data::user::{FactorID, GeneralSettings, GrantedClients, TwoFactor, User, UserID};
|
||||
use crate::utils::err::{Res, new_error};
|
||||
use crate::utils::time::time;
|
||||
|
||||
impl EntityManager<User> {
|
||||
/// Update user information
|
||||
fn update_user<F>(&mut self, id: &UserID, update: F) -> Res
|
||||
where
|
||||
F: FnOnce(User) -> User,
|
||||
{
|
||||
let user = match self.find_by_user_id(id)? {
|
||||
None => return new_error(format!("Failed to find user {id:?}")),
|
||||
Some(user) => user,
|
||||
};
|
||||
|
||||
if let Err(e) = self.replace_entries(|u| u.uid.eq(id), &update(user)) {
|
||||
log::error!("Failed to update user information! {e:?}");
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn hash_password<P: AsRef<[u8]>>(pwd: P) -> Res<String> {
|
||||
Ok(bcrypt::hash(pwd, bcrypt::DEFAULT_COST)?)
|
||||
}
|
||||
|
||||
fn verify_password<P: AsRef<[u8]>>(pwd: P, hash: &str) -> bool {
|
||||
match bcrypt::verify(pwd, hash) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
log::warn!("Failed to verify password! {e:?}");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl UsersSyncBackend for EntityManager<User> {
|
||||
fn find_by_email(&self, u: &str) -> Res<Option<User>> {
|
||||
for entry in self.iter() {
|
||||
if entry.email.eq(u) {
|
||||
return Ok(Some(entry.clone()));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn find_by_username_or_email(&self, u: &str) -> Res<Option<User>> {
|
||||
for entry in self.iter() {
|
||||
if entry.username.eq(u) || entry.email.eq(u) {
|
||||
return Ok(Some(entry.clone()));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn find_by_user_id(&self, id: &UserID) -> Res<Option<User>> {
|
||||
for entry in self.iter() {
|
||||
if entry.uid.eq(id) {
|
||||
return Ok(Some(entry.clone()));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn get_entire_users_list(&self) -> Res<Vec<User>> {
|
||||
Ok(self.cloned())
|
||||
}
|
||||
|
||||
fn create_user_account(&mut self, settings: GeneralSettings) -> Res<UserID> {
|
||||
let mut user = User {
|
||||
uid: UserID(uuid::Uuid::new_v4().to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
user.update_general_settings(settings);
|
||||
self.insert(user.clone())?;
|
||||
Ok(user.uid)
|
||||
}
|
||||
|
||||
fn set_general_user_settings(&mut self, settings: GeneralSettings) -> Res {
|
||||
self.update_user(&settings.uid.clone(), |mut user| {
|
||||
user.update_general_settings(settings);
|
||||
user
|
||||
})
|
||||
}
|
||||
|
||||
fn change_user_password(&mut self, id: &UserID, password: &str, temporary: bool) -> Res {
|
||||
let new_hash = hash_password(password)?;
|
||||
|
||||
self.update_user(id, |mut user| {
|
||||
user.password = new_hash;
|
||||
user.need_reset_password = temporary;
|
||||
user.two_factor_exemption_after_successful_login = Default::default();
|
||||
user
|
||||
})
|
||||
}
|
||||
|
||||
fn verify_user_password(&self, user: &UserID, password: &str) -> Res<bool> {
|
||||
Ok(self
|
||||
.find_by_user_id(user)?
|
||||
.map(|u| verify_password(password, &u.password))
|
||||
.unwrap_or(false))
|
||||
}
|
||||
|
||||
fn add_2fa_factor(&mut self, id: &UserID, factor: TwoFactor) -> Res {
|
||||
self.update_user(id, |mut user| {
|
||||
user.two_factor.push(factor);
|
||||
user
|
||||
})
|
||||
}
|
||||
|
||||
fn remove_2fa_factor(&mut self, id: &UserID, factor_id: FactorID) -> Res {
|
||||
self.update_user(id, |mut user| {
|
||||
user.two_factor.retain(|f| f.id != factor_id);
|
||||
user
|
||||
})
|
||||
}
|
||||
|
||||
fn save_new_successful_2fa_authentication(&mut self, id: &UserID, ip: IpAddr) -> Res {
|
||||
self.update_user(id, |mut user| {
|
||||
user.last_successful_2fa.insert(ip, time());
|
||||
|
||||
// Remove outdated successful attempts
|
||||
user.remove_outdated_successful_2fa_attempts();
|
||||
|
||||
user
|
||||
})
|
||||
}
|
||||
|
||||
fn clear_2fa_login_history(&mut self, id: &UserID) -> Res {
|
||||
self.update_user(id, |mut user| {
|
||||
user.last_successful_2fa = Default::default();
|
||||
user
|
||||
})
|
||||
}
|
||||
|
||||
fn delete_account(&mut self, id: &UserID) -> Res {
|
||||
let user = match self.find_by_user_id(id)? {
|
||||
None => {
|
||||
return new_error(format!(
|
||||
"Could not delete account {id:?} because it was not found!"
|
||||
));
|
||||
}
|
||||
Some(s) => s,
|
||||
};
|
||||
|
||||
self.remove(&user)
|
||||
}
|
||||
|
||||
fn set_authorized_authentication_sources(
|
||||
&mut self,
|
||||
id: &UserID,
|
||||
sources: AuthorizedAuthenticationSources,
|
||||
) -> Res {
|
||||
self.update_user(id, |mut user| {
|
||||
user.allow_local_login = sources.local;
|
||||
user.allow_login_from_providers = sources.upstream;
|
||||
user
|
||||
})
|
||||
}
|
||||
|
||||
fn set_granted_2fa_clients(&mut self, id: &UserID, clients: GrantedClients) -> Res {
|
||||
self.update_user(id, |mut user| {
|
||||
user.authorized_clients = clients.to_user();
|
||||
user
|
||||
})
|
||||
}
|
||||
}
|
@@ -1,7 +1,8 @@
|
||||
use std::io::ErrorKind;
|
||||
use std::sync::Arc;
|
||||
|
||||
use actix_web::web;
|
||||
use bincode::{Decode, Encode};
|
||||
use light_openid::crypto_wrapper::CryptoWrapper;
|
||||
use uuid::Uuid;
|
||||
use webauthn_rs::prelude::{
|
||||
CreationChallengeResponse, Passkey, PublicKeyCredential, RegisterPublicKeyCredential,
|
||||
@@ -13,7 +14,6 @@ use crate::constants::{
|
||||
APP_NAME, WEBAUTHN_LOGIN_CHALLENGE_EXPIRE, WEBAUTHN_REGISTER_CHALLENGE_EXPIRE,
|
||||
};
|
||||
use crate::data::app_config::AppConfig;
|
||||
use crate::data::crypto_wrapper::CryptoWrapper;
|
||||
use crate::data::user::{User, UserID};
|
||||
use crate::utils::err::Res;
|
||||
use crate::utils::time::time;
|
||||
@@ -28,7 +28,7 @@ pub struct RegisterKeyRequest {
|
||||
pub creation_challenge: CreationChallengeResponse,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize, Encode, Decode)]
|
||||
struct RegisterKeyOpaqueData {
|
||||
registration_state: String,
|
||||
user_id: UserID,
|
||||
@@ -40,7 +40,7 @@ pub struct AuthRequest {
|
||||
pub login_challenge: RequestChallengeResponse,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Debug, Encode, Decode)]
|
||||
struct AuthStateOpaqueData {
|
||||
authentication_state: String,
|
||||
user_id: UserID,
|
||||
@@ -56,19 +56,28 @@ pub struct WebAuthManager {
|
||||
|
||||
impl WebAuthManager {
|
||||
pub fn init(conf: &AppConfig) -> Self {
|
||||
let rp_id = conf
|
||||
.domain_name()
|
||||
.split_once(':')
|
||||
.map(|s| s.0)
|
||||
.unwrap_or_else(|| conf.domain_name());
|
||||
|
||||
let rp_origin =
|
||||
url::Url::parse(&conf.website_origin).expect("Failed to parse configuration origin!");
|
||||
|
||||
log::debug!(
|
||||
"rp_id={} rp_origin={} rp_origin_domain={:?}",
|
||||
rp_id,
|
||||
rp_origin,
|
||||
rp_origin.domain()
|
||||
);
|
||||
|
||||
Self {
|
||||
core: WebauthnBuilder::new(
|
||||
conf.domain_name()
|
||||
.split_once(':')
|
||||
.map(|s| s.0)
|
||||
.unwrap_or_else(|| conf.domain_name()),
|
||||
&url::Url::parse(&conf.website_origin)
|
||||
.expect("Failed to parse configuration origin!"),
|
||||
)
|
||||
.expect("Invalid Webauthn configuration")
|
||||
.rp_name(APP_NAME)
|
||||
.build()
|
||||
.expect("Failed to build webauthn"),
|
||||
core: WebauthnBuilder::new(rp_id, &rp_origin)
|
||||
.expect("Invalid Webauthn configuration")
|
||||
.rp_name(APP_NAME)
|
||||
.build()
|
||||
.expect("Failed to build webauthn"),
|
||||
crypto_wrapper: CryptoWrapper::new_random(),
|
||||
}
|
||||
}
|
||||
@@ -99,17 +108,11 @@ impl WebAuthManager {
|
||||
) -> Res<WebauthnPubKey> {
|
||||
let state: RegisterKeyOpaqueData = self.crypto_wrapper.decrypt(opaque_state)?;
|
||||
if state.user_id != user.uid {
|
||||
return Err(Box::new(std::io::Error::new(
|
||||
ErrorKind::Other,
|
||||
"Invalid user for pubkey!",
|
||||
)));
|
||||
return Err(Box::new(std::io::Error::other("Invalid user for pubkey!")));
|
||||
}
|
||||
|
||||
if state.expire < time() {
|
||||
return Err(Box::new(std::io::Error::new(
|
||||
ErrorKind::Other,
|
||||
"Challenge has expired!",
|
||||
)));
|
||||
return Err(Box::new(std::io::Error::other("Challenge has expired!")));
|
||||
}
|
||||
|
||||
let res = self.core.finish_passkey_registration(
|
||||
@@ -147,17 +150,11 @@ impl WebAuthManager {
|
||||
) -> Res {
|
||||
let state: AuthStateOpaqueData = self.crypto_wrapper.decrypt(opaque_state)?;
|
||||
if &state.user_id != user_id {
|
||||
return Err(Box::new(std::io::Error::new(
|
||||
ErrorKind::Other,
|
||||
"Invalid user for pubkey!",
|
||||
)));
|
||||
return Err(Box::new(std::io::Error::other("Invalid user for pubkey!")));
|
||||
}
|
||||
|
||||
if state.expire < time() {
|
||||
return Err(Box::new(std::io::Error::new(
|
||||
ErrorKind::Other,
|
||||
"Challenge has expired!",
|
||||
)));
|
||||
return Err(Box::new(std::io::Error::other("Challenge has expired!")));
|
||||
}
|
||||
|
||||
self.core.finish_passkey_authentication(
|
||||
|
63
src/main.rs
63
src/main.rs
@@ -2,17 +2,19 @@ use core::time::Duration;
|
||||
use std::sync::Arc;
|
||||
|
||||
use actix::Actor;
|
||||
use actix_identity::config::LogoutBehaviour;
|
||||
use actix_identity::IdentityMiddleware;
|
||||
use actix_session::storage::CookieSessionStore;
|
||||
use actix_identity::config::LogoutBehaviour;
|
||||
use actix_remote_ip::RemoteIPConfig;
|
||||
use actix_session::SessionMiddleware;
|
||||
use actix_session::storage::CookieSessionStore;
|
||||
use actix_web::cookie::{Key, SameSite};
|
||||
use actix_web::middleware::Logger;
|
||||
use actix_web::{get, middleware, web, App, HttpResponse, HttpServer};
|
||||
use actix_web::{App, HttpResponse, HttpServer, get, middleware, web};
|
||||
|
||||
use basic_oidc::actors::bruteforce_actor::BruteForceActor;
|
||||
use basic_oidc::actors::openid_sessions_actor::OpenIDSessionsActor;
|
||||
use basic_oidc::actors::users_actor::UsersActor;
|
||||
use basic_oidc::actors::providers_states_actor::ProvidersStatesActor;
|
||||
use basic_oidc::actors::users_actor::{UsersActor, UsersSyncBackend};
|
||||
use basic_oidc::constants::*;
|
||||
use basic_oidc::controllers::assets_controller::assets_route;
|
||||
use basic_oidc::controllers::*;
|
||||
@@ -20,7 +22,8 @@ use basic_oidc::data::app_config::AppConfig;
|
||||
use basic_oidc::data::client::ClientManager;
|
||||
use basic_oidc::data::entity_manager::EntityManager;
|
||||
use basic_oidc::data::jwt_signer::JWTSigner;
|
||||
use basic_oidc::data::user::{hash_password, User};
|
||||
use basic_oidc::data::provider::ProvidersManager;
|
||||
use basic_oidc::data::user::User;
|
||||
use basic_oidc::data::webauthn_manager::WebAuthManager;
|
||||
use basic_oidc::middlewares::auth_middleware::AuthMiddleware;
|
||||
|
||||
@@ -48,35 +51,45 @@ async fn main() -> std::io::Result<()> {
|
||||
|
||||
// Create initial user if required
|
||||
if users.is_empty() {
|
||||
log::info!("Create default {} user", DEFAULT_ADMIN_USERNAME);
|
||||
log::info!("Create default {DEFAULT_ADMIN_USERNAME} user");
|
||||
let default_admin = User {
|
||||
username: DEFAULT_ADMIN_USERNAME.to_string(),
|
||||
password: hash_password(DEFAULT_ADMIN_PASSWORD).unwrap(),
|
||||
need_reset_password: true,
|
||||
authorized_clients: None,
|
||||
admin: true,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
users
|
||||
.insert(default_admin)
|
||||
.insert(default_admin.clone())
|
||||
.expect("Failed to create initial user!");
|
||||
|
||||
// Set default admin password
|
||||
users
|
||||
.change_user_password(&default_admin.uid, DEFAULT_ADMIN_PASSWORD, true)
|
||||
.expect("Failed to change default admin password!");
|
||||
}
|
||||
|
||||
let users_actor = UsersActor::new(users).start();
|
||||
let bruteforce_actor = BruteForceActor::default().start();
|
||||
let providers_states_actor = ProvidersStatesActor::default().start();
|
||||
let openid_sessions_actor = OpenIDSessionsActor::default().start();
|
||||
let jwt_signer = JWTSigner::gen_from_memory().expect("Failed to generate JWKS key");
|
||||
let webauthn_manager = Arc::new(WebAuthManager::init(config));
|
||||
|
||||
let mut clients =
|
||||
ClientManager::open_or_create(config.clients_file()).expect("Failed to load clients list!");
|
||||
clients.apply_environment_variables();
|
||||
let clients = Arc::new(clients);
|
||||
|
||||
let mut providers = ProvidersManager::open_or_create(config.providers_file())
|
||||
.expect("Failed to load providers list!");
|
||||
providers.apply_environment_variables();
|
||||
let providers = Arc::new(providers);
|
||||
|
||||
log::info!("Server will listen on {}", config.listen_address);
|
||||
let listen_address = config.listen_address.to_string();
|
||||
|
||||
HttpServer::new(move || {
|
||||
let mut clients = ClientManager::open_or_create(config.clients_file())
|
||||
.expect("Failed to load clients list!");
|
||||
clients.apply_environment_variables();
|
||||
|
||||
let session_mw = SessionMiddleware::builder(
|
||||
CookieSessionStore::default(),
|
||||
Key::from(config.token_key.as_bytes()),
|
||||
@@ -95,10 +108,15 @@ async fn main() -> std::io::Result<()> {
|
||||
App::new()
|
||||
.app_data(web::Data::new(users_actor.clone()))
|
||||
.app_data(web::Data::new(bruteforce_actor.clone()))
|
||||
.app_data(web::Data::new(providers_states_actor.clone()))
|
||||
.app_data(web::Data::new(openid_sessions_actor.clone()))
|
||||
.app_data(web::Data::new(clients))
|
||||
.app_data(web::Data::new(clients.clone()))
|
||||
.app_data(web::Data::new(providers.clone()))
|
||||
.app_data(web::Data::new(jwt_signer.clone()))
|
||||
.app_data(web::Data::new(webauthn_manager.clone()))
|
||||
.app_data(web::Data::new(RemoteIPConfig {
|
||||
proxy: AppConfig::get().proxy_ip.clone(),
|
||||
}))
|
||||
.wrap(
|
||||
middleware::DefaultHeaders::new().add(("Permissions-Policy", "interest-cohort=()")),
|
||||
)
|
||||
@@ -106,7 +124,7 @@ async fn main() -> std::io::Result<()> {
|
||||
.wrap(AuthMiddleware {})
|
||||
.wrap(identity_middleware)
|
||||
.wrap(session_mw)
|
||||
// main route
|
||||
// Main route
|
||||
.route(
|
||||
"/",
|
||||
web::get().to(|| async {
|
||||
@@ -116,7 +134,7 @@ async fn main() -> std::io::Result<()> {
|
||||
}),
|
||||
)
|
||||
.route("/robots.txt", web::get().to(assets_controller::robots_txt))
|
||||
// health route
|
||||
// Health route
|
||||
.service(health)
|
||||
// Assets serving
|
||||
.route("/assets/{path:.*}", web::get().to(assets_route))
|
||||
@@ -147,6 +165,15 @@ async fn main() -> std::io::Result<()> {
|
||||
"/login/api/auth_webauthn",
|
||||
web::post().to(login_api::auth_webauthn),
|
||||
)
|
||||
// Providers controller
|
||||
.route(
|
||||
"/login_with_prov",
|
||||
web::get().to(providers_controller::start_login),
|
||||
)
|
||||
.route(
|
||||
OIDC_PROVIDER_CB_URI,
|
||||
web::get().to(providers_controller::finish_login),
|
||||
)
|
||||
// Settings routes
|
||||
.route(
|
||||
"/settings",
|
||||
@@ -203,6 +230,10 @@ async fn main() -> std::io::Result<()> {
|
||||
"/admin/clients",
|
||||
web::get().to(admin_controller::clients_route),
|
||||
)
|
||||
.route(
|
||||
"/admin/providers",
|
||||
web::get().to(admin_controller::providers_route),
|
||||
)
|
||||
.route("/admin/users", web::get().to(admin_controller::users_route))
|
||||
.route(
|
||||
"/admin/users",
|
||||
|
@@ -1,15 +1,15 @@
|
||||
//! # Authentication middleware
|
||||
|
||||
use std::future::{ready, Future, Ready};
|
||||
use std::future::{Future, Ready, ready};
|
||||
use std::pin::Pin;
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_identity::IdentityExt;
|
||||
use actix_web::body::EitherBody;
|
||||
use actix_web::http::{header, Method};
|
||||
use actix_web::http::{Method, header};
|
||||
use actix_web::{
|
||||
dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
|
||||
Error, HttpResponse,
|
||||
dev::{Service, ServiceRequest, ServiceResponse, Transform, forward_ready},
|
||||
};
|
||||
|
||||
use crate::constants::{
|
||||
@@ -97,10 +97,7 @@ where
|
||||
.unwrap_or("bad")
|
||||
.eq(&AppConfig::get().website_origin)
|
||||
{
|
||||
log::warn!(
|
||||
"Blocked POST request from invalid origin! Origin given {:?}",
|
||||
o
|
||||
);
|
||||
log::warn!("Blocked POST request from invalid origin! Origin given {o:?}");
|
||||
return Ok(req.into_response(
|
||||
HttpResponse::Unauthorized()
|
||||
.body("POST request from invalid origin!")
|
||||
@@ -133,8 +130,8 @@ where
|
||||
_ => ConnStatus::SignedOut,
|
||||
};
|
||||
|
||||
log::trace!("Connection data: {:#?}", session_data);
|
||||
log::debug!("Connection status: {:?}", session);
|
||||
log::trace!("Connection data: {session_data:#?}");
|
||||
log::debug!("Connection status: {session:?}");
|
||||
|
||||
// Redirect user to login page
|
||||
if !session.is_auth()
|
||||
|
@@ -1,2 +1,34 @@
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::fmt::{Display, Formatter};
|
||||
|
||||
pub type Res<A = ()> = Result<A, Box<dyn Error>>;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ExecError(pub String);
|
||||
|
||||
impl ExecError {
|
||||
pub fn new(msg: &str) -> ExecError {
|
||||
ExecError(msg.to_string())
|
||||
}
|
||||
|
||||
pub fn boxed_new<D: Display>(msg: D) -> Box<ExecError> {
|
||||
Box::new(ExecError(msg.to_string()))
|
||||
}
|
||||
|
||||
pub fn boxed_string(msg: String) -> Box<ExecError> {
|
||||
Box::new(ExecError(msg))
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for ExecError {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "Encountered error: {}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for ExecError {}
|
||||
|
||||
pub fn new_error<D: Display>(msg: D) -> Res {
|
||||
Err(ExecError::boxed_new(msg))
|
||||
}
|
||||
|
@@ -1,5 +1,4 @@
|
||||
pub mod crypt_utils;
|
||||
pub mod err;
|
||||
pub mod network_utils;
|
||||
pub mod string_utils;
|
||||
pub mod time;
|
||||
|
@@ -1,178 +0,0 @@
|
||||
use std::net::{IpAddr, Ipv6Addr};
|
||||
use std::str::FromStr;
|
||||
|
||||
use actix_web::HttpRequest;
|
||||
|
||||
/// Check if two ips matches
|
||||
pub fn match_ip(pattern: &str, ip: &str) -> bool {
|
||||
if pattern.eq(ip) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if pattern.ends_with('*') && ip.starts_with(&pattern.replace('*', "")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
/// Get the remote IP address
|
||||
pub fn get_remote_ip(req: &HttpRequest, proxy_ip: Option<&str>) -> IpAddr {
|
||||
let mut ip = req.peer_addr().unwrap().ip();
|
||||
|
||||
// We check if the request comes from a trusted reverse proxy
|
||||
if let Some(proxy) = proxy_ip.as_ref() {
|
||||
if match_ip(proxy, &ip.to_string()) {
|
||||
if let Some(header) = req.headers().get("X-Forwarded-For") {
|
||||
let header = header.to_str().unwrap();
|
||||
|
||||
let remote_ip = if let Some((upstream_ip, _)) = header.split_once(',') {
|
||||
upstream_ip
|
||||
} else {
|
||||
header
|
||||
};
|
||||
|
||||
if let Some(upstream_ip) = parse_ip(remote_ip) {
|
||||
ip = upstream_ip;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ip
|
||||
}
|
||||
|
||||
/// Parse an IP address
|
||||
pub fn parse_ip(ip: &str) -> Option<IpAddr> {
|
||||
let mut ip = match IpAddr::from_str(ip) {
|
||||
Ok(ip) => ip,
|
||||
Err(e) => {
|
||||
log::warn!("Failed to parse an IP address: {}", e);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
if let IpAddr::V6(ipv6) = &mut ip {
|
||||
let mut octets = ipv6.octets();
|
||||
for o in octets.iter_mut().skip(8) {
|
||||
*o = 0;
|
||||
}
|
||||
ip = IpAddr::V6(Ipv6Addr::from(octets));
|
||||
}
|
||||
|
||||
Some(ip)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
|
||||
use std::str::FromStr;
|
||||
|
||||
use actix_web::test::TestRequest;
|
||||
|
||||
use crate::utils::network_utils::{get_remote_ip, parse_ip};
|
||||
|
||||
#[test]
|
||||
fn test_get_remote_ip() {
|
||||
let req = TestRequest::default()
|
||||
.peer_addr(SocketAddr::from_str("192.168.1.1:1000").unwrap())
|
||||
.to_http_request();
|
||||
assert_eq!(
|
||||
get_remote_ip(&req, None),
|
||||
"192.168.1.1".parse::<IpAddr>().unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_remote_ip_from_proxy() {
|
||||
let req = TestRequest::default()
|
||||
.peer_addr(SocketAddr::from_str("192.168.1.1:1000").unwrap())
|
||||
.insert_header(("X-Forwarded-For", "1.1.1.1"))
|
||||
.to_http_request();
|
||||
assert_eq!(
|
||||
get_remote_ip(&req, Some("192.168.1.1")),
|
||||
"1.1.1.1".parse::<IpAddr>().unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_remote_ip_from_proxy_2() {
|
||||
let req = TestRequest::default()
|
||||
.peer_addr(SocketAddr::from_str("192.168.1.1:1000").unwrap())
|
||||
.insert_header(("X-Forwarded-For", "1.1.1.1, 1.2.2.2"))
|
||||
.to_http_request();
|
||||
assert_eq!(
|
||||
get_remote_ip(&req, Some("192.168.1.1")),
|
||||
"1.1.1.1".parse::<IpAddr>().unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_remote_ip_from_proxy_ipv6() {
|
||||
let req = TestRequest::default()
|
||||
.peer_addr(SocketAddr::from_str("192.168.1.1:1000").unwrap())
|
||||
.insert_header(("X-Forwarded-For", "10::1, 1.2.2.2"))
|
||||
.to_http_request();
|
||||
assert_eq!(
|
||||
get_remote_ip(&req, Some("192.168.1.1")),
|
||||
"10::".parse::<IpAddr>().unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_remote_ip_from_no_proxy() {
|
||||
let req = TestRequest::default()
|
||||
.peer_addr(SocketAddr::from_str("192.168.1.1:1000").unwrap())
|
||||
.insert_header(("X-Forwarded-For", "1.1.1.1, 1.2.2.2"))
|
||||
.to_http_request();
|
||||
assert_eq!(
|
||||
get_remote_ip(&req, None),
|
||||
"192.168.1.1".parse::<IpAddr>().unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_remote_ip_from_other_proxy() {
|
||||
let req = TestRequest::default()
|
||||
.peer_addr(SocketAddr::from_str("192.168.1.1:1000").unwrap())
|
||||
.insert_header(("X-Forwarded-For", "1.1.1.1, 1.2.2.2"))
|
||||
.to_http_request();
|
||||
assert_eq!(
|
||||
get_remote_ip(&req, Some("192.168.1.2")),
|
||||
"192.168.1.1".parse::<IpAddr>().unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_bad_ip() {
|
||||
let ip = parse_ip("badbad");
|
||||
assert_eq!(None, ip);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_ip_v4_address() {
|
||||
let ip = parse_ip("192.168.1.1").unwrap();
|
||||
assert_eq!(ip, IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_ip_v6_address() {
|
||||
let ip = parse_ip("2a00:1450:4007:813::200e").unwrap();
|
||||
assert_eq!(
|
||||
ip,
|
||||
IpAddr::V6(Ipv6Addr::new(0x2a00, 0x1450, 0x4007, 0x813, 0, 0, 0, 0))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_ip_v6_address_2() {
|
||||
let ip = parse_ip("::1").unwrap();
|
||||
assert_eq!(ip, IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_ip_v6_address_3() {
|
||||
let ip = parse_ip("a::1").unwrap();
|
||||
assert_eq!(ip, IpAddr::V6(Ipv6Addr::new(0xa, 0, 0, 0, 0, 0, 0, 0)));
|
||||
}
|
||||
}
|
@@ -1,14 +1,9 @@
|
||||
use lazy_regex::regex_find;
|
||||
use rand::distributions::Alphanumeric;
|
||||
use rand::Rng;
|
||||
use rand::distr::{Alphanumeric, SampleString};
|
||||
|
||||
/// Generate a random string of a given size
|
||||
pub fn rand_str(len: usize) -> String {
|
||||
rand::thread_rng()
|
||||
.sample_iter(&Alphanumeric)
|
||||
.map(char::from)
|
||||
.take(len)
|
||||
.collect()
|
||||
Alphanumeric.sample_string(&mut rand::rng(), len)
|
||||
}
|
||||
|
||||
/// Parse environment variables
|
||||
@@ -24,8 +19,8 @@ pub fn apply_env_vars(val: &str) -> String {
|
||||
let value = match std::env::var(varname) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
log::error!("Failed to find environment variable {}!", varname);
|
||||
eprintln!("Failed to find environment variable! {:?}", e);
|
||||
log::error!("Failed to find environment variable {varname}!");
|
||||
eprintln!("Failed to find environment variable! {e:?}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
@@ -36,16 +31,23 @@ pub fn apply_env_vars(val: &str) -> String {
|
||||
val
|
||||
}
|
||||
|
||||
/// Check out whether a given login is acceptable or not
|
||||
pub fn is_acceptable_login(login: &str) -> bool {
|
||||
mailchecker::is_valid(login) || lazy_regex::regex!("^[a-zA-Z0-9-+]+$").is_match(login)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::utils::string_utils::apply_env_vars;
|
||||
use crate::utils::string_utils::{apply_env_vars, is_acceptable_login};
|
||||
use std::env;
|
||||
|
||||
const VAR_ONE: &str = "VAR_ONE";
|
||||
#[test]
|
||||
fn test_apply_env_var() {
|
||||
env::set_var(VAR_ONE, "good");
|
||||
let src = format!("This is ${{{}}}", VAR_ONE);
|
||||
unsafe {
|
||||
env::set_var(VAR_ONE, "good");
|
||||
}
|
||||
let src = format!("This is ${{{VAR_ONE}}}");
|
||||
assert_eq!("This is good", apply_env_vars(&src));
|
||||
}
|
||||
|
||||
@@ -53,7 +55,15 @@ mod test {
|
||||
|
||||
#[test]
|
||||
fn test_invalid_var_syntax() {
|
||||
let src = format!("This is ${{{}}}", VAR_INVALID);
|
||||
let src = format!("This is ${{{VAR_INVALID}}}");
|
||||
assert_eq!(src, apply_env_vars(&src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_acceptable_login() {
|
||||
assert!(is_acceptable_login("admin"));
|
||||
assert!(is_acceptable_login("someone@somewhere.fr"));
|
||||
assert!(!is_acceptable_login("someone@somewhere.#fr"));
|
||||
assert!(!is_acceptable_login("bad bad"));
|
||||
}
|
||||
}
|
||||
|
@@ -1,4 +1,4 @@
|
||||
use chrono::{DateTime, NaiveDateTime, Utc};
|
||||
use chrono::DateTime;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
/// Get the current time since epoch
|
||||
@@ -11,13 +11,25 @@ pub fn time() -> u64 {
|
||||
|
||||
/// Format unix timestamp to a human-readable string
|
||||
pub fn fmt_time(timestamp: u64) -> String {
|
||||
// Create a NaiveDateTime from the timestamp
|
||||
let naive =
|
||||
NaiveDateTime::from_timestamp_opt(timestamp as i64, 0).expect("Failed to parse timestamp!");
|
||||
|
||||
// Create a normal DateTime from the NaiveDateTime
|
||||
let datetime: DateTime<Utc> = DateTime::from_utc(naive, Utc);
|
||||
// Create a DateTime from the timestamp
|
||||
let datetime =
|
||||
DateTime::from_timestamp(timestamp as i64, 0).expect("Failed to parse timestamp!");
|
||||
|
||||
// Format the datetime how you want
|
||||
datetime.format("%Y-%m-%d %H:%M:%S").to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::utils::time::{fmt_time, time};
|
||||
|
||||
#[test]
|
||||
fn test_time() {
|
||||
assert!(time() > 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_fmt_time() {
|
||||
assert_eq!(fmt_time(1693475465), "2023-08-31 09:51:05");
|
||||
}
|
||||
}
|
||||
|
@@ -8,7 +8,7 @@
|
||||
<!-- No indexing -->
|
||||
<meta name="robots" content="noindex, nofollow">
|
||||
|
||||
<title>{{ _p.app_name }} - {{ _p.page_title }}</title>
|
||||
<title>{{ p.app_name }} - {{ p.page_title }}</title>
|
||||
|
||||
<!-- Bootstrap core CSS -->
|
||||
<link href="/assets/css/bootstrap.css" rel="stylesheet" crossorigin="anonymous"/>
|
||||
@@ -30,8 +30,6 @@
|
||||
font-size: 3.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
</style>
|
||||
|
||||
|
||||
@@ -45,15 +43,15 @@
|
||||
|
||||
<main class="form-signin">
|
||||
|
||||
<h1 class="h3 mb-3 fw-normal">{{ _p.page_title }}</h1>
|
||||
<h1 class="h3 mb-3 fw-normal" style="margin-bottom: 2rem !important;">{{ p.page_title }}</h1>
|
||||
|
||||
{% if let Some(danger) = _p.danger %}
|
||||
{% if let Some(danger) = p.danger %}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
{{ danger }}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{% if let Some(success) = _p.success %}
|
||||
{% if let Some(success) = p.success %}
|
||||
<div class="alert alert-success" role="alert">
|
||||
{{ success }}
|
||||
</div>
|
||||
|
@@ -5,14 +5,16 @@
|
||||
<p>You need to validate a second factor to complete your login.</p>
|
||||
|
||||
{% for factor in user.get_distinct_factors_types() %}
|
||||
<a class="btn btn-primary btn-lg" href="{{ factor.login_url(_p.redirect_uri) }}" style="width: 100%; display: flex;">
|
||||
<img src="{{ factor.type_image() }}" alt="Factor icon" style="margin-right: 1em;" />
|
||||
<!-- We can ask to force 2FA, because once we are here, it means 2FA is required anyway... -->
|
||||
<a class="btn btn-primary btn-lg" href="{{ factor.login_url(p.redirect_uri, true) }}"
|
||||
style="width: 100%; display: flex;">
|
||||
<img src="{{ factor.type_image() }}" alt="Factor icon" style="margin-right: 1em;"/>
|
||||
<div style="text-align: left;">
|
||||
{{ factor.type_str() }} <br/>
|
||||
<small style="font-size: 0.7em;">{{ factor.description_str() }}</small>
|
||||
</div>
|
||||
</a>
|
||||
<br />
|
||||
<br/>
|
||||
{% endfor %}
|
||||
</div>
|
||||
|
||||
|
@@ -1,6 +1,24 @@
|
||||
{% extends "base_login_page.html" %}
|
||||
{% block content %}
|
||||
<form action="/login?redirect={{ _p.redirect_uri.get_encoded() }}" method="post">
|
||||
<style>
|
||||
#providers {
|
||||
margin-top: 40px;
|
||||
}
|
||||
|
||||
.provider-button {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.provider-button img {
|
||||
margin-right: 1em;
|
||||
width: 1em;
|
||||
}
|
||||
|
||||
</style>
|
||||
|
||||
<form action="/login?redirect={{ p.redirect_uri.get_encoded() }}" method="post">
|
||||
<div>
|
||||
<div class="form-floating">
|
||||
<input name="login" type="text" required class="form-control" id="floatingName" placeholder="unsername"
|
||||
@@ -19,4 +37,18 @@
|
||||
|
||||
</form>
|
||||
|
||||
<!-- Upstream providers -->
|
||||
{% if !providers.is_empty() %}
|
||||
<div id="providers">
|
||||
{% for prov in providers %}
|
||||
<a class="btn btn-secondary btn-lg provider-button" href="{{ prov.login_url(p.redirect_uri) }}">
|
||||
<img src="{{ prov.logo_url() }}" alt="Provider icon"/>
|
||||
<div style="text-align: left;">
|
||||
Login using {{ prov.name }} <br/>
|
||||
</div>
|
||||
</a>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{% endblock content %}
|
||||
|
@@ -28,7 +28,7 @@
|
||||
|
||||
|
||||
<div style="margin-top: 10px;">
|
||||
<a href="/2fa_auth?force_display=true&redirect={{ _p.redirect_uri.get_encoded() }}">Sign in using another factor</a><br/>
|
||||
<a href="/2fa_auth?force_display=true&redirect={{ p.redirect_uri.get_encoded() }}&force_2fa=true">Sign in using another factor</a><br/>
|
||||
<a href="/logout">Sign out</a>
|
||||
</div>
|
||||
|
||||
|
@@ -1,6 +1,6 @@
|
||||
{% extends "base_login_page.html" %}
|
||||
{% block content %}
|
||||
<form action="/reset_password?redirect={{ _p.redirect_uri.get_encoded() }}" method="post" id="reset_password_form">
|
||||
<form action="/reset_password?redirect={{ p.redirect_uri.get_encoded() }}" method="post" id="reset_password_form">
|
||||
<div>
|
||||
<p>You need to configure a new password:</p>
|
||||
|
||||
|
13
templates/login/prov_login_error.html
Normal file
13
templates/login/prov_login_error.html
Normal file
@@ -0,0 +1,13 @@
|
||||
{% extends "base_login_page.html" %}
|
||||
{% block content %}
|
||||
|
||||
<div class="alert alert-danger" style="margin-bottom: 10px;">
|
||||
<strong>Authentication failed!</strong>
|
||||
|
||||
<p style="margin-top: 10px; text-align: justify;">{{ message }}</p>
|
||||
</div>
|
||||
|
||||
<a href="/login?redirect={{ p.redirect_uri.get_encoded() }}">Go back to login</a>
|
||||
|
||||
|
||||
{% endblock content %}
|
@@ -12,13 +12,13 @@
|
||||
</div>
|
||||
|
||||
<div style="margin-top: 10px;">
|
||||
<a href="/2fa_auth?force_display=true&redirect={{ _p.redirect_uri.get_encoded() }}">Sign in using another factor</a><br/>
|
||||
<a href="/2fa_auth?force_display=true&redirect={{ p.redirect_uri.get_encoded() }}&force_2fa=true">Sign in using another factor</a><br/>
|
||||
<a href="/logout">Sign out</a>
|
||||
</div>
|
||||
|
||||
<script src="/assets/js/base64_lib.js"></script>
|
||||
<script>
|
||||
const REDIRECT_URI = decodeURIComponent("{{ _p.redirect_uri.get_encoded() }}");
|
||||
const REDIRECT_URI = decodeURIComponent("{{ p.redirect_uri.get_encoded() }}");
|
||||
const OPAQUE_STATE = "{{ opaque_state }}";
|
||||
const AUTH_CHALLENGE = JSON.parse(decodeURIComponent("{{ challenge_json }}"));
|
||||
// Decode data
|
||||
|
@@ -5,29 +5,31 @@
|
||||
<tbody>
|
||||
<tr>
|
||||
<th scope="row">User ID</th>
|
||||
<td>{{ u.uid.0 }}</td>
|
||||
<td>{{ p.user.uid.0 }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row">First name</th>
|
||||
<td>{{ u.first_name }}</td>
|
||||
<td>{{ p.user.first_name }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row">Last name</th>
|
||||
<td>{{ u.last_name }}</td>
|
||||
<td>{{ p.user.last_name }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row">Username</th>
|
||||
<td>{{ u.username }}</td>
|
||||
<td>{{ p.user.username }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row">Email</th>
|
||||
<td>{{ u.email }}</td>
|
||||
<td>{{ p.user.email }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row">Account type</th>
|
||||
<td>{% if u.admin %}Admin{% else %}Regular user{% endif %}</td>
|
||||
<td>{% if p.user.admin %}Admin{% else %}Regular user{% endif %}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<p>Your IP address: {{ remote_ip }}</p>
|
||||
|
||||
{% endblock content %}
|
||||
|
@@ -28,8 +28,8 @@
|
||||
<label for="inputDevName" class="form-label mt-4">Device name</label>
|
||||
<input type="text" class="form-control" id="inputDevName"
|
||||
placeholder="Device / Authenticator app name"
|
||||
value="Authenticator app" minlength="1" required/>
|
||||
<small class="form-text text-muted">Please give a name to your device to identity it more easily
|
||||
value="Authenticator app" minlength="1" maxlength="{{ max_name_len }}" required/>
|
||||
<small class="form-text text-muted">Please give a name to your device to identify it more easily
|
||||
later.</small>
|
||||
<div class="invalid-feedback">Please give a name to this authenticator app</div>
|
||||
</div>
|
||||
|
@@ -9,7 +9,7 @@
|
||||
<label for="inputKeyName" class="form-label mt-4">Key name</label>
|
||||
<input type="text" class="form-control" id="inputKeyName"
|
||||
placeholder="Device / Authenticator app name"
|
||||
value="Security key" minlength="1" required/>
|
||||
value="Security key" minlength="1" maxlength="{{ max_name_len }}" required/>
|
||||
<small class="form-text text-muted">Please give a name to your key to identify it more easily later.</small>
|
||||
<div class="invalid-feedback">Please give a name to this security key</div>
|
||||
</div>
|
||||
|
@@ -2,7 +2,7 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>{{ _p.page_title }} - {{ _p.app_name }}</title>
|
||||
<title>{{ p.page_title }} - {{ p.app_name }}</title>
|
||||
|
||||
<!-- Bootstrap core CSS -->
|
||||
<link href="/assets/css/bootstrap.css" rel="stylesheet" crossorigin="anonymous"/>
|
||||
@@ -12,10 +12,10 @@
|
||||
<body>
|
||||
<div class="d-flex flex-column flex-shrink-0 p-3 bg-light" style="width: 280px;">
|
||||
<a href="/" class="d-flex align-items-center mb-3 mb-md-0 me-md-auto link-dark text-decoration-none">
|
||||
<span class="fs-4">{{ _p.app_name }}</span>
|
||||
<span class="fs-4">{{ p.app_name }}</span>
|
||||
</a>
|
||||
{% if _p.is_admin %}
|
||||
<span>Version {{ _p.version }}</span>
|
||||
{% if p.user.admin %}
|
||||
<span>Version {{ p.version }}</span>
|
||||
{% endif %}
|
||||
<hr>
|
||||
<ul class="nav nav-pills flex-column mb-auto">
|
||||
@@ -24,24 +24,31 @@
|
||||
Account details
|
||||
</a>
|
||||
</li>
|
||||
{% if p.user.allow_local_login %}
|
||||
<li>
|
||||
<a href="/settings/change_password" class="nav-link link-dark">
|
||||
Change password
|
||||
</a>
|
||||
</li>
|
||||
{% endif %}
|
||||
<li>
|
||||
<a href="/settings/two_factors" class="nav-link link-dark">
|
||||
Two-factor authentication
|
||||
</a>
|
||||
</li>
|
||||
|
||||
{% if _p.is_admin %}
|
||||
{% if p.user.admin %}
|
||||
<hr/>
|
||||
<li>
|
||||
<a href="/admin/clients" class="nav-link link-dark">
|
||||
Clients
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="/admin/providers" class="nav-link link-dark">
|
||||
Providers
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="/admin/users" class="nav-link link-dark">
|
||||
Users
|
||||
@@ -54,7 +61,7 @@
|
||||
<a href="#" class="d-flex align-items-center link-dark text-decoration-none dropdown-toggle" id="dropdownUser"
|
||||
data-bs-toggle="dropdown" aria-expanded="false">
|
||||
<img src="/assets/img/account.png" alt="" width="32" height="32" class="rounded-circle me-2">
|
||||
<strong>{{ _p.user_name }}</strong>
|
||||
<strong>{{ p.user.username }}</strong>
|
||||
</a>
|
||||
<ul class="dropdown-menu text-small shadow" aria-labelledby="dropdownUser">
|
||||
<li><a class="dropdown-item" href="/logout">Sign out</a></li>
|
||||
@@ -63,14 +70,14 @@
|
||||
</div>
|
||||
|
||||
<div class="page_body" style="flex: 1">
|
||||
{% if let Some(msg) = _p.danger_message %}
|
||||
{% if let Some(msg) = p.danger_message %}
|
||||
<div class="alert alert-danger">{{ msg }}</div>
|
||||
{% endif %}
|
||||
{% if let Some(msg) = _p.success_message %}
|
||||
{% if let Some(msg) = p.success_message %}
|
||||
<div class="alert alert-success">{{ msg }}</div>
|
||||
{% endif %}
|
||||
|
||||
<h2 class="bd-title mt-0" style="margin-bottom: 40px;">{{ _p.page_title }}</h2>
|
||||
<h2 class="bd-title mt-0" style="margin-bottom: 40px;">{{ p.page_title }}</h2>
|
||||
|
||||
{% block content %}
|
||||
TO_REPLACE
|
||||
@@ -83,9 +90,10 @@
|
||||
if(el.href === location.href) el.classList.add("active");
|
||||
else el.classList.remove("active")
|
||||
})
|
||||
|
||||
</script>
|
||||
{% if _p.ip_location_api.is_some() %}
|
||||
<script>const IP_LOCATION_API = "{{ _p.ip_location_api.unwrap() }}"</script>
|
||||
{% if p.ip_location_api.is_some() %}
|
||||
<script>const IP_LOCATION_API = "{{ p.ip_location_api.unwrap() }}"</script>
|
||||
{% endif %}
|
||||
<script src="/assets/js/ip_location_service.js"></script>
|
||||
</body>
|
||||
|
@@ -8,6 +8,8 @@
|
||||
<th scope="col">Name</th>
|
||||
<th scope="col">Description</th>
|
||||
<th scope="col">Redirect URI</th>
|
||||
<th scope="col">Default</th>
|
||||
<th scope="col">Granted to all users</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -17,6 +19,8 @@
|
||||
<td>{{ c.name }}</td>
|
||||
<td>{{ c.description }}</td>
|
||||
<td>{{ c.redirect_uri }}</td>
|
||||
<td>{% if c.default %}YES{% else %}NO{% endif %}</td>
|
||||
<td>{% if c.granted_to_all_users %}YES{% else %}NO{% endif %}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
|
@@ -112,28 +112,61 @@
|
||||
</div>
|
||||
|
||||
<ul>
|
||||
{% for e in u.get_formatted_2fa_successful_logins() %}
|
||||
{% if e.can_bypass_2fa %}<li style="font-weight: bold;">{{ e.ip }} - {{ e.fmt_time() }} - BYPASS 2FA</li>
|
||||
{% else %}<li>{{ e.ip }} - {{ e.fmt_time() }}</li>{% endif %}
|
||||
{% endfor %}
|
||||
{% for e in u.get_formatted_2fa_successful_logins() %}
|
||||
{% if e.can_bypass_2fa %}
|
||||
<li style="font-weight: bold;">{{ e.ip }} - {{ e.fmt_time() }} - BYPASS 2FA</li>
|
||||
{% else %}
|
||||
<li>{{ e.ip }} - {{ e.fmt_time() }}</li>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</ul>
|
||||
</fieldset>
|
||||
{% endif %}
|
||||
|
||||
<!-- Authorized authentication sources -->
|
||||
<fieldset class="form-group">
|
||||
<legend class="mt-4">Authorized authentication sources</legend>
|
||||
|
||||
<!-- Local login -->
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="checkbox" name="allow_local_login" id="allow_local_login"
|
||||
{% if u.allow_local_login %} checked="" {% endif %}>
|
||||
<label class="form-check-label" for="allow_local_login">
|
||||
Allow local login
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<!-- Upstream providers -->
|
||||
<input type="hidden" name="authorized_sources" id="authorized_sources"/>
|
||||
{% for prov in providers %}
|
||||
<div class="form-check">
|
||||
<input class="form-check-input authorized_provider" type="checkbox" name="prov-{{ prov.id.0 }}"
|
||||
id="prov-{{ prov.id.0 }}"
|
||||
data-id="{{ prov.id.0 }}"
|
||||
{% if u.can_login_from_provider(prov) %} checked="" {% endif %}>
|
||||
<label class="form-check-label" for="prov-{{ prov.id.0 }}">
|
||||
Allow login from {{ prov.name }}
|
||||
</label>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</fieldset>
|
||||
|
||||
<!-- Granted clients -->
|
||||
<fieldset class="form-group">
|
||||
<legend class="mt-4">Granted clients</legend>
|
||||
<div class="form-check">
|
||||
<label class="form-check-label">
|
||||
<input type="radio" class="form-check-input" name="grant_type"
|
||||
value="all_clients" {% if u.authorized_clients== None %} checked="" {% endif %}>
|
||||
value="all_clients" {% if u.granted_clients()== GrantedClients::AllClients %} checked="" {% endif
|
||||
%}>
|
||||
Grant all clients
|
||||
</label>
|
||||
</div>
|
||||
<div class="form-check">
|
||||
<label class="form-check-label">
|
||||
<input type="radio" class="form-check-input" name="grant_type"
|
||||
value="custom_clients" {% if u.authorized_clients !=None %} checked="checked" {% endif %}>
|
||||
value="custom_clients" {% if matches!(self.u.granted_clients(), GrantedClients::SomeClients(_))
|
||||
%} checked="checked" {% endif %}>
|
||||
Manually specify allowed clients
|
||||
</label>
|
||||
</div>
|
||||
@@ -144,16 +177,25 @@
|
||||
<div class="form-check">
|
||||
<input id="client-{{ c.id.0 }}" class="form-check-input authorize_client_checkbox" type="checkbox"
|
||||
data-id="{{ c.id.0 }}"
|
||||
{% if u.can_access_app(c.id) %} checked="" {% endif %}>
|
||||
{% if u.can_access_app(c) %} checked="" {% endif %}>
|
||||
<label class="form-check-label" for="client-{{ c.id.0 }}">
|
||||
{{ c.name }}
|
||||
</label>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
|
||||
<div class="form-check">
|
||||
<label class="form-check-label">
|
||||
<input type="radio" class="form-check-input" name="grant_type"
|
||||
value="no_client" {% if u.granted_clients()== GrantedClients::NoClient %} checked="checked" {%
|
||||
endif %}>
|
||||
Do not grant any client
|
||||
</label>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<input type="submit" class="btn btn-primary mt-4" value="{{ _p.page_title }}">
|
||||
<input type="submit" class="btn btn-primary mt-4" value="{{ p.page_title }}">
|
||||
</form>
|
||||
|
||||
<script>
|
||||
@@ -207,6 +249,13 @@
|
||||
form.addEventListener("submit", (ev) => {
|
||||
ev.preventDefault();
|
||||
|
||||
const authorized_sources = [...document.querySelectorAll(".authorized_provider")]
|
||||
.filter(e => e.checked)
|
||||
.map(e => e.getAttribute("data-id")).join(",")
|
||||
|
||||
document.querySelector("input[name=authorized_sources]").value = authorized_sources;
|
||||
|
||||
|
||||
const authorized_clients = [...document.querySelectorAll(".authorize_client_checkbox")]
|
||||
.filter(e => e.checked)
|
||||
.map(e => e.getAttribute("data-id")).join(",")
|
||||
@@ -223,6 +272,9 @@
|
||||
form.submit();
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
</script>
|
||||
|
||||
{% endblock content %}
|
39
templates/settings/providers_list.html
Normal file
39
templates/settings/providers_list.html
Normal file
@@ -0,0 +1,39 @@
|
||||
{% extends "base_settings_page.html" %}
|
||||
{% block content %}
|
||||
|
||||
<style>
|
||||
#providers td {
|
||||
vertical-align: middle;
|
||||
}
|
||||
</style>
|
||||
|
||||
<table id="providers" class="table table-hover" style="max-width: 800px;" aria-describedby="OpenID providers list">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col"></th>
|
||||
<th scope="col">ID</th>
|
||||
<th scope="col">Name</th>
|
||||
<th scope="col">Configuration URL</th>
|
||||
<th scope="col">Client ID</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for c in providers %}
|
||||
<tr>
|
||||
<td>
|
||||
<img src="{{ c.logo_url() }}" alt="{{ c.name }} logo" width="30px"/>
|
||||
</td>
|
||||
<td>{{ c.id.0 }}</td>
|
||||
<td>{{ c.name }}</td>
|
||||
<td><a href="{{ c.configuration_url }}" target="_blank" rel="noreferrer">
|
||||
{{ c.configuration_url }}
|
||||
</a></td>
|
||||
<td>{{ c.client_id }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<p>Redirect URL for new clients: {{ redirect_url }}</p>
|
||||
|
||||
{% endblock content %}
|
@@ -26,7 +26,9 @@
|
||||
<tbody>
|
||||
{% for f in user.two_factor %}
|
||||
<tr id="factor-{{ f.id.0 }}">
|
||||
<td><img src="{{ f.type_image() }}" alt="Factor icon" style="height: 1.5em; margin-right: 0.5em;" />{{ f.type_str() }}</td>
|
||||
<td><img src="{{ f.type_image() }}" alt="Factor icon" style="height: 1.5em; margin-right: 0.5em;"/>{{
|
||||
f.type_str() }}
|
||||
</td>
|
||||
<td>{{ f.name }}</td>
|
||||
<td><a href="javascript:delete_factor('{{ f.id.0 }}');">Delete</a></td>
|
||||
</tr>
|
||||
@@ -53,7 +55,9 @@
|
||||
{% for e in user.get_formatted_2fa_successful_logins() %}
|
||||
<tr>
|
||||
<td>{{ e.ip }}</td>
|
||||
<td><locateip ip="{{ e.ip }}"></locateip></td>
|
||||
<td>
|
||||
<locateip ip="{{ e.ip }}"></locateip>
|
||||
</td>
|
||||
<td>{{ e.fmt_time() }}</td>
|
||||
<td>{% if e.can_bypass_2fa %}YES{% else %}NO{% endif %}</td>
|
||||
</tr>
|
||||
@@ -63,6 +67,10 @@
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
{% if let Some(last_2fa_auth) = last_2fa_auth %}
|
||||
<p>Last successful 2FA authentication on this browser: {{ last_2fa_auth }}</p>
|
||||
{% endif %}
|
||||
|
||||
<script>
|
||||
async function delete_factor(id) {
|
||||
if (!confirm("Do you really want to remove this factor?"))
|
||||
@@ -72,7 +80,7 @@
|
||||
const res = await fetch("/settings/api/two_factor/delete_factor", {
|
||||
method: "post",
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
id: id,
|
||||
@@ -84,7 +92,7 @@
|
||||
|
||||
if (res.status == 200)
|
||||
document.getElementById("factor-" + id).remove();
|
||||
} catch(e) {
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
alert("Failed to remove factor!");
|
||||
}
|
||||
@@ -104,7 +112,7 @@
|
||||
|
||||
if (res.status == 200)
|
||||
document.getElementById("2fa_history_container").remove();
|
||||
} catch(e) {
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
alert("Failed to clear 2FA history!");
|
||||
}
|
||||
|
Reference in New Issue
Block a user