Compare commits
24 Commits
ffd93c5435
...
20251204
| Author | SHA1 | Date | |
|---|---|---|---|
| 054fc0c4cc | |||
| 3d19a0eba2 | |||
| 944e7dd00d | |||
| cb739ebe6d | |||
| a2af039759 | |||
| aac82d3415 | |||
| 259695c660 | |||
| d0a94d9e59 | |||
| e717b44ebc | |||
| 1901238f87 | |||
| 088d682b31 | |||
| 02c7f764f5 | |||
| 7b8412682d | |||
| 5a05b547a8 | |||
| da2aa8aac2 | |||
| bc453cfd26 | |||
| 4b26a0ea12 | |||
| 242d725ad0 | |||
| ce4317299e | |||
| 14ede196c4 | |||
| 6d341069a0 | |||
| d4de81f1fb | |||
| 9a599fdde2 | |||
| 764ad3d5a1 |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -1,3 +1,3 @@
|
|||||||
/target
|
/target
|
||||||
.idea
|
.idea
|
||||||
storage
|
/storage
|
||||||
|
|||||||
1326
Cargo.lock
generated
1326
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
22
Cargo.toml
22
Cargo.toml
@@ -8,27 +8,27 @@ edition = "2024"
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
actix = "0.13.5"
|
actix = "0.13.5"
|
||||||
actix-identity = "0.9.0"
|
actix-identity = "0.9.0"
|
||||||
actix-web = "4.11.0"
|
actix-web = "4.12.1"
|
||||||
actix-session = { version = "0.11.0", features = ["cookie-session"] }
|
actix-session = { version = "0.11.0", features = ["cookie-session", "redis-session"] }
|
||||||
actix-remote-ip = "0.1.0"
|
actix-remote-ip = "0.1.0"
|
||||||
clap = { version = "4.5.50", features = ["derive", "env"] }
|
clap = { version = "4.5.53", features = ["derive", "env"] }
|
||||||
include_dir = "0.7.4"
|
include_dir = "0.7.4"
|
||||||
log = "0.4.28"
|
log = "0.4.29"
|
||||||
serde_json = "1.0.145"
|
serde_json = "1.0.145"
|
||||||
serde_yaml = "0.9.34"
|
serde_yaml = "0.9.34"
|
||||||
env_logger = "0.11.8"
|
env_logger = "0.11.8"
|
||||||
serde = { version = "1.0.228", features = ["derive"] }
|
serde = { version = "1.0.228", features = ["derive"] }
|
||||||
bcrypt = "0.17.1"
|
bcrypt = "0.17.1"
|
||||||
uuid = { version = "1.18.1", features = ["v4"] }
|
uuid = { version = "1.19.0", features = ["v4"] }
|
||||||
mime_guess = "2.0.5"
|
mime_guess = "2.0.5"
|
||||||
askama = "0.14.0"
|
askama = "0.14.0"
|
||||||
urlencoding = "2.1.3"
|
urlencoding = "2.1.3"
|
||||||
rand = "0.9.2"
|
rand = "0.10.0-rc.5"
|
||||||
base64 = "0.22.1"
|
base64 = "0.22.1"
|
||||||
jwt-simple = { version = "0.12.12", default-features = false, features = ["pure-rust"] }
|
jwt-simple = { version = "0.12.13", default-features = false, features = ["pure-rust"] }
|
||||||
digest = "0.10.7"
|
digest = "0.11.0-rc.4"
|
||||||
sha2 = "0.10.9"
|
sha2 = "0.11.0-rc.3"
|
||||||
lazy-regex = "3.4.1"
|
lazy-regex = "3.4.2"
|
||||||
totp_rfc6238 = "0.6.1"
|
totp_rfc6238 = "0.6.1"
|
||||||
base32 = "0.5.1"
|
base32 = "0.5.1"
|
||||||
qrcode-generator = "5.0.0"
|
qrcode-generator = "5.0.0"
|
||||||
@@ -39,3 +39,5 @@ bincode = "2.0.1"
|
|||||||
chrono = "0.4.42"
|
chrono = "0.4.42"
|
||||||
lazy_static = "1.5.0"
|
lazy_static = "1.5.0"
|
||||||
mailchecker = "6.0.19"
|
mailchecker = "6.0.19"
|
||||||
|
httpdate = "1.0.3"
|
||||||
|
build-time = "0.1.3"
|
||||||
|
|||||||
18
README.md
18
README.md
@@ -67,10 +67,11 @@ You can add as much upstream provider as you want, using the following syntax in
|
|||||||
```yaml
|
```yaml
|
||||||
- id: gitlab
|
- id: gitlab
|
||||||
name: GitLab
|
name: GitLab
|
||||||
logo: gitlab # Can be either gitea, gitlab, github, microsoft, google or a full URL
|
logo: gitlab # Can be either openid, gitea, gitlab, github, microsoft, google or a full URL
|
||||||
client_id: CLIENT_ID_GIVEN_BY_PROVIDER
|
client_id: CLIENT_ID_GIVEN_BY_PROVIDER
|
||||||
client_secret: CLIENT_SECRET_GIVEN_BY_PROVIDER
|
client_secret: CLIENT_SECRET_GIVEN_BY_PROVIDER
|
||||||
configuration_url: https://gitlab.com/.well-known/openid-configuration
|
configuration_url: https://gitlab.com/.well-known/openid-configuration
|
||||||
|
allow_auto_account_creation: true
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -108,5 +109,20 @@ Corresponding client configuration:
|
|||||||
|
|
||||||
OAuth proxy can then be access on this URL: http://192.168.2.103:4180/
|
OAuth proxy can then be access on this URL: http://192.168.2.103:4180/
|
||||||
|
|
||||||
|
## Testing with upstream identity provider
|
||||||
|
The folder [sample_upstream_provider](sample_upstream_provider) contains a working scenario of authentication with an upstream provider.
|
||||||
|
|
||||||
|
Run the following command to run the scenario:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd sample_upstream_provider
|
||||||
|
docker compose up
|
||||||
|
```
|
||||||
|
|
||||||
|
- Upstream provider (not to be directly used): http://localhost:9001
|
||||||
|
- BasicOIDC: http://localhost:8000
|
||||||
|
- Client 2: http://localhost:8012
|
||||||
|
- Client 1: http://localhost:8011
|
||||||
|
|
||||||
## Contributing
|
## 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 :)
|
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 :)
|
||||||
|
|||||||
@@ -20,4 +20,8 @@ body {
|
|||||||
|
|
||||||
.form-control::placeholder {
|
.form-control::placeholder {
|
||||||
color: #555;
|
color: #555;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table-break-works td {
|
||||||
|
word-break: break-all;
|
||||||
}
|
}
|
||||||
2
assets/css/bootstrap.css
vendored
2
assets/css/bootstrap.css
vendored
@@ -11,7 +11,7 @@
|
|||||||
* Copyright 2011-2024 The Bootstrap Authors
|
* Copyright 2011-2024 The Bootstrap Authors
|
||||||
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
|
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
|
||||||
*/
|
*/
|
||||||
@import url("https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap");
|
@import url("/assets/robotfont/font.css");
|
||||||
:root,
|
:root,
|
||||||
[data-bs-theme=light] {
|
[data-bs-theme=light] {
|
||||||
--bs-blue: #2a9fd6;
|
--bs-blue: #2a9fd6;
|
||||||
|
|||||||
1
assets/img/brands/openid.svg
Normal file
1
assets/img/brands/openid.svg
Normal file
@@ -0,0 +1 @@
|
|||||||
|
<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>OpenID</title><path d="M14.54.889l-3.63 1.773v18.17c-4.15-.52-7.27-2.78-7.27-5.5 0-2.58 2.8-4.75 6.63-5.41v-2.31C4.42 8.322 0 11.502 0 15.332c0 3.96 4.74 7.24 10.91 7.78l3.63-1.71V.888m.64 6.724v2.31c1.43.25 2.71.7 3.76 1.31l-1.97 1.11 7.03 1.53-.5-5.21-1.87 1.06c-1.74-1.06-3.96-1.81-6.45-2.11z"/></svg>
|
||||||
|
After Width: | Height: | Size: 382 B |
26
sample_upstream_provider/dex-provider/dex.config.yaml
Normal file
26
sample_upstream_provider/dex-provider/dex.config.yaml
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
issuer: http://127.0.0.1:9001/dex
|
||||||
|
|
||||||
|
storage:
|
||||||
|
type: memory
|
||||||
|
|
||||||
|
web:
|
||||||
|
http: 0.0.0.0:9001
|
||||||
|
|
||||||
|
oauth2:
|
||||||
|
# Automate some clicking
|
||||||
|
# Note: this might actually make some tests pass that otherwise wouldn't.
|
||||||
|
skipApprovalScreen: false
|
||||||
|
|
||||||
|
connectors:
|
||||||
|
# Note: this might actually make some tests pass that otherwise wouldn't.
|
||||||
|
- type: mockCallback
|
||||||
|
id: mock
|
||||||
|
name: Example
|
||||||
|
|
||||||
|
# Basic OP test suite requires two clients.
|
||||||
|
staticClients:
|
||||||
|
- id: foo
|
||||||
|
secret: bar
|
||||||
|
redirectURIs:
|
||||||
|
- http://localhost:8000/prov_cb
|
||||||
|
name: Auth
|
||||||
63
sample_upstream_provider/docker-compose.yaml
Normal file
63
sample_upstream_provider/docker-compose.yaml
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
services:
|
||||||
|
redis:
|
||||||
|
image: redis
|
||||||
|
network_mode: host
|
||||||
|
volumes:
|
||||||
|
- ./redis/redis.conf:/redis.conf:ro
|
||||||
|
command: [ "redis-server", "/redis.conf" ]
|
||||||
|
healthcheck:
|
||||||
|
test: [ "CMD", "redis-cli", "ping" ]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 30s
|
||||||
|
retries: 3
|
||||||
|
upstream:
|
||||||
|
image: dexidp/dex
|
||||||
|
user: "1000"
|
||||||
|
network_mode: host
|
||||||
|
volumes:
|
||||||
|
- ./dex-provider:/conf:ro
|
||||||
|
command: [ "dex", "serve", "/conf/dex.config.yaml" ]
|
||||||
|
|
||||||
|
client1:
|
||||||
|
image: pierre42100/oidc_test_client
|
||||||
|
user: "1000"
|
||||||
|
network_mode: host
|
||||||
|
environment:
|
||||||
|
- LISTEN_ADDR=0.0.0.0:8011
|
||||||
|
- PUBLIC_URL=http://127.0.0.1:8011
|
||||||
|
- CONFIGURATION_URL=http://localhost:8000/.well-known/openid-configuration
|
||||||
|
- CLIENT_ID=testclient1
|
||||||
|
- CLIENT_SECRET=secretone
|
||||||
|
|
||||||
|
client2:
|
||||||
|
image: pierre42100/oidc_test_client
|
||||||
|
user: "1000"
|
||||||
|
network_mode: host
|
||||||
|
environment:
|
||||||
|
- LISTEN_ADDR=0.0.0.0:8012
|
||||||
|
- PUBLIC_URL=http://127.0.0.1:8012
|
||||||
|
- CONFIGURATION_URL=http://localhost:8000/.well-known/openid-configuration
|
||||||
|
- CLIENT_ID=testclient2
|
||||||
|
- CLIENT_SECRET=secrettwo
|
||||||
|
|
||||||
|
basicoidc:
|
||||||
|
image: rust
|
||||||
|
user: "1000"
|
||||||
|
network_mode: host
|
||||||
|
depends_on:
|
||||||
|
redis:
|
||||||
|
condition: service_healthy
|
||||||
|
environment:
|
||||||
|
- STORAGE_PATH=/storage
|
||||||
|
- DISABLE_LOCAL_LOGIN=true
|
||||||
|
- USE_REDIS=true
|
||||||
|
- REDIS_PASSWORD=secretsecret
|
||||||
|
#- RUST_LOG=debug
|
||||||
|
volumes:
|
||||||
|
- ../:/app
|
||||||
|
- ./storage:/storage
|
||||||
|
- ~/.cargo/registry:/usr/local/cargo/registry
|
||||||
|
command:
|
||||||
|
- bash
|
||||||
|
- -c
|
||||||
|
- cd /app && cargo run
|
||||||
3
sample_upstream_provider/redis/redis.conf
Normal file
3
sample_upstream_provider/redis/redis.conf
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
maxmemory 256mb
|
||||||
|
maxmemory-policy allkeys-lru
|
||||||
|
requirepass secretsecret
|
||||||
1
sample_upstream_provider/storage/.gitignore
vendored
Normal file
1
sample_upstream_provider/storage/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
users.json
|
||||||
11
sample_upstream_provider/storage/clients.yaml
Normal file
11
sample_upstream_provider/storage/clients.yaml
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
- id: testclient1
|
||||||
|
name: Client 1
|
||||||
|
description: client1
|
||||||
|
secret: secretone
|
||||||
|
redirect_uri: http://127.0.0.1:8011/
|
||||||
|
granted_to_all_users: true
|
||||||
|
- id: testclient2
|
||||||
|
name: Client 2
|
||||||
|
description: client2
|
||||||
|
secret: secrettwo
|
||||||
|
redirect_uri: http://127.0.0.1:8012/
|
||||||
7
sample_upstream_provider/storage/providers.yaml
Normal file
7
sample_upstream_provider/storage/providers.yaml
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
- id: upstream
|
||||||
|
name: Upstream
|
||||||
|
logo: openid
|
||||||
|
client_id: foo
|
||||||
|
client_secret: bar
|
||||||
|
configuration_url: http://127.0.0.1:9001/dex/.well-known/openid-configuration
|
||||||
|
allow_auto_account_creation: true
|
||||||
@@ -5,7 +5,7 @@ use std::net::IpAddr;
|
|||||||
use actix::{Actor, AsyncContext, Context, Handler, Message};
|
use actix::{Actor, AsyncContext, Context, Handler, Message};
|
||||||
|
|
||||||
use crate::constants::{FAIL_LOGIN_ATTEMPT_CLEANUP_INTERVAL, KEEP_FAILED_LOGIN_ATTEMPTS_FOR};
|
use crate::constants::{FAIL_LOGIN_ATTEMPT_CLEANUP_INTERVAL, KEEP_FAILED_LOGIN_ATTEMPTS_FOR};
|
||||||
use crate::utils::time::time;
|
use crate::utils::time_utils::time;
|
||||||
|
|
||||||
#[derive(Message)]
|
#[derive(Message)]
|
||||||
#[rtype(result = "()")]
|
#[rtype(result = "()")]
|
||||||
@@ -87,7 +87,7 @@ mod test {
|
|||||||
use std::net::{IpAddr, Ipv4Addr};
|
use std::net::{IpAddr, Ipv4Addr};
|
||||||
|
|
||||||
use crate::actors::bruteforce_actor::BruteForceActor;
|
use crate::actors::bruteforce_actor::BruteForceActor;
|
||||||
use crate::utils::time::time;
|
use crate::utils::time_utils::time;
|
||||||
|
|
||||||
const IP_1: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1));
|
const IP_1: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1));
|
||||||
const IP_2: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 2));
|
const IP_2: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 2));
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ use crate::data::jwt_signer::JWTSigner;
|
|||||||
use crate::data::user::UserID;
|
use crate::data::user::UserID;
|
||||||
use crate::utils::err::Res;
|
use crate::utils::err::Res;
|
||||||
use crate::utils::string_utils::rand_str;
|
use crate::utils::string_utils::rand_str;
|
||||||
use crate::utils::time::time;
|
use crate::utils::time_utils::time;
|
||||||
|
|
||||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq)]
|
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq)]
|
||||||
pub struct SessionID(pub String);
|
pub struct SessionID(pub String);
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ use std::net::IpAddr;
|
|||||||
use crate::data::login_redirect::LoginRedirect;
|
use crate::data::login_redirect::LoginRedirect;
|
||||||
use crate::data::provider::ProviderID;
|
use crate::data::provider::ProviderID;
|
||||||
use crate::utils::string_utils::rand_str;
|
use crate::utils::string_utils::rand_str;
|
||||||
use crate::utils::time::time;
|
use crate::utils::time_utils::time;
|
||||||
|
|
||||||
#[derive(Debug, Clone, serde::Serialize)]
|
#[derive(Debug, Clone, serde::Serialize)]
|
||||||
pub struct ProviderLoginState {
|
pub struct ProviderLoginState {
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
use std::net::IpAddr;
|
use std::net::IpAddr;
|
||||||
|
|
||||||
use crate::data::provider::{Provider, ProviderID};
|
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::data::user::{FactorID, GeneralSettings, GrantedClients, TwoFactor, User, UserID};
|
||||||
use crate::utils::err::Res;
|
use crate::utils::err::Res;
|
||||||
|
use crate::utils::string_utils::is_acceptable_login;
|
||||||
|
use actix::{Actor, Context, Handler, Message, MessageResult};
|
||||||
|
use light_openid::primitives::OpenIDUserInfo;
|
||||||
|
|
||||||
/// User storage interface
|
/// User storage interface
|
||||||
pub trait UsersSyncBackend {
|
pub trait UsersSyncBackend {
|
||||||
@@ -38,6 +39,8 @@ pub enum LoginResult {
|
|||||||
LocalAuthForbidden,
|
LocalAuthForbidden,
|
||||||
AuthFromProviderForbidden,
|
AuthFromProviderForbidden,
|
||||||
Success(Box<User>),
|
Success(Box<User>),
|
||||||
|
AccountAutoCreated(Box<User>),
|
||||||
|
CannotAutoCreateAccount(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Message)]
|
#[derive(Message)]
|
||||||
@@ -51,6 +54,7 @@ pub struct LocalLoginRequest {
|
|||||||
#[rtype(LoginResult)]
|
#[rtype(LoginResult)]
|
||||||
pub struct ProviderLoginRequest {
|
pub struct ProviderLoginRequest {
|
||||||
pub email: String,
|
pub email: String,
|
||||||
|
pub user_info: OpenIDUserInfo,
|
||||||
pub provider: Provider,
|
pub provider: Provider,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -187,7 +191,86 @@ impl Handler<ProviderLoginRequest> for UsersActor {
|
|||||||
log::error!("Failed to find user! {e}");
|
log::error!("Failed to find user! {e}");
|
||||||
MessageResult(LoginResult::Error)
|
MessageResult(LoginResult::Error)
|
||||||
}
|
}
|
||||||
Ok(None) => MessageResult(LoginResult::AccountNotFound),
|
Ok(None) => {
|
||||||
|
// Check if automatic account creation is enabled for this provider
|
||||||
|
if !msg.provider.allow_auto_account_creation {
|
||||||
|
return MessageResult(LoginResult::AccountNotFound);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract username for account creation
|
||||||
|
let mut username = msg
|
||||||
|
.user_info
|
||||||
|
.preferred_username
|
||||||
|
.unwrap_or(msg.email.to_string());
|
||||||
|
|
||||||
|
// Determine username from email, if necessary
|
||||||
|
if !is_acceptable_login(&username)
|
||||||
|
|| matches!(
|
||||||
|
self.manager.find_by_username_or_email(&username),
|
||||||
|
Ok(Some(_))
|
||||||
|
)
|
||||||
|
{
|
||||||
|
username = msg.email.clone();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if username is already taken
|
||||||
|
if matches!(
|
||||||
|
self.manager.find_by_username_or_email(&username),
|
||||||
|
Ok(Some(_))
|
||||||
|
) {
|
||||||
|
return MessageResult(LoginResult::CannotAutoCreateAccount(format!(
|
||||||
|
"username {username} is already taken!"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
if !is_acceptable_login(&username) {
|
||||||
|
return MessageResult(LoginResult::CannotAutoCreateAccount(
|
||||||
|
"could not determine acceptable login for user!".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Automatic account creation
|
||||||
|
let user_id = match self.manager.create_user_account(GeneralSettings {
|
||||||
|
uid: UserID::random(),
|
||||||
|
username,
|
||||||
|
first_name: msg.user_info.given_name.unwrap_or_default(),
|
||||||
|
last_name: msg.user_info.family_name.unwrap_or_default(),
|
||||||
|
email: msg.email.to_string(),
|
||||||
|
enabled: true,
|
||||||
|
two_factor_exemption_after_successful_login: false,
|
||||||
|
is_admin: false,
|
||||||
|
}) {
|
||||||
|
Ok(u) => u,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("Failed to create user account! {e}");
|
||||||
|
return MessageResult(LoginResult::CannotAutoCreateAccount(
|
||||||
|
"missing some user information".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Mark the provider as the only authorized source
|
||||||
|
if let Err(e) = self.manager.set_authorized_authentication_sources(
|
||||||
|
&user_id,
|
||||||
|
AuthorizedAuthenticationSources {
|
||||||
|
local: false,
|
||||||
|
upstream: vec![msg.provider.id],
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
log::error!(
|
||||||
|
"Failed to set authorized authentication sources for newly created account! {e}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract user information to return them
|
||||||
|
let Ok(Some(user)) = self.manager.find_by_user_id(&user_id) else {
|
||||||
|
return MessageResult(LoginResult::CannotAutoCreateAccount(
|
||||||
|
"failed to get created user information".to_string(),
|
||||||
|
));
|
||||||
|
};
|
||||||
|
|
||||||
|
MessageResult(LoginResult::AccountAutoCreated(Box::new(user)))
|
||||||
|
}
|
||||||
Ok(Some(user)) => {
|
Ok(Some(user)) => {
|
||||||
if !user.can_login_from_provider(&msg.provider) {
|
if !user.can_login_from_provider(&msg.provider) {
|
||||||
return MessageResult(LoginResult::AuthFromProviderForbidden);
|
return MessageResult(LoginResult::AuthFromProviderForbidden);
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
use std::path::Path;
|
use crate::utils::crypt_utils::sha256;
|
||||||
|
use crate::utils::time_utils;
|
||||||
use actix_web::{HttpResponse, web};
|
use actix_web::http::header;
|
||||||
|
use actix_web::{HttpRequest, HttpResponse, web};
|
||||||
use include_dir::{Dir, include_dir};
|
use include_dir::{Dir, include_dir};
|
||||||
|
use std::ops::Add;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
/// Assets directory
|
/// Assets directory
|
||||||
static ASSETS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/assets");
|
static ASSETS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/assets");
|
||||||
@@ -12,14 +16,39 @@ pub async fn robots_txt() -> HttpResponse {
|
|||||||
.body(include_str!("../../assets/robots.txt"))
|
.body(include_str!("../../assets/robots.txt"))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn assets_route(path: web::Path<String>) -> HttpResponse {
|
pub async fn assets_route(req: HttpRequest, path: web::Path<String>) -> HttpResponse {
|
||||||
let path: &Path = path.as_ref().as_ref();
|
let path: &Path = path.as_ref().as_ref();
|
||||||
match ASSETS_DIR.get_file(path) {
|
match ASSETS_DIR.get_file(path) {
|
||||||
None => HttpResponse::NotFound().body("404 Not found"),
|
None => HttpResponse::NotFound().body("404 Not found"),
|
||||||
Some(file) => {
|
Some(file) => {
|
||||||
let res = mime_guess::from_path(path).first_or_octet_stream();
|
let res = mime_guess::from_path(path).first_or_octet_stream();
|
||||||
|
let digest = format!("{:x?}", sha256(file.contents()));
|
||||||
|
|
||||||
|
// Check if the browser already knows the file by date
|
||||||
|
if let Some(c) = req.headers().get(header::IF_MODIFIED_SINCE) {
|
||||||
|
let date_str = c.to_str().unwrap_or("");
|
||||||
|
if let Ok(date) = httpdate::parse_http_date(date_str)
|
||||||
|
&& date.add(Duration::from_secs(1))
|
||||||
|
>= time_utils::unix_to_system_time(time_utils::build_time())
|
||||||
|
{
|
||||||
|
return HttpResponse::NotModified().finish();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if the browser already knows the etag
|
||||||
|
if let Some(c) = req.headers().get(header::IF_NONE_MATCH)
|
||||||
|
&& c.to_str().unwrap_or("") == digest
|
||||||
|
{
|
||||||
|
return HttpResponse::NotModified().finish();
|
||||||
|
}
|
||||||
|
|
||||||
HttpResponse::Ok()
|
HttpResponse::Ok()
|
||||||
.content_type(res.to_string())
|
.content_type(res.to_string())
|
||||||
|
.insert_header(("etag", digest))
|
||||||
|
.insert_header((
|
||||||
|
"last-modified",
|
||||||
|
time_utils::unix_to_http_date(time_utils::build_time()),
|
||||||
|
))
|
||||||
.body(file.contents())
|
.body(file.contents())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ impl Default for BaseLoginPage {
|
|||||||
struct LoginTemplate {
|
struct LoginTemplate {
|
||||||
p: BaseLoginPage,
|
p: BaseLoginPage,
|
||||||
login: String,
|
login: String,
|
||||||
|
show_local_login: bool,
|
||||||
providers: Vec<Provider>,
|
providers: Vec<Provider>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -156,8 +157,10 @@ pub async fn login_route(
|
|||||||
"Given login could not be processed, because it has an invalid format!".to_string(),
|
"Given login could not be processed, because it has an invalid format!".to_string(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
// Try to authenticate user
|
// Try to authenticate user (local login)
|
||||||
else if let Some(req) = &req {
|
else if let Some(req) = &req
|
||||||
|
&& !AppConfig::get().disable_local_login
|
||||||
|
{
|
||||||
login.clone_from(&req.login);
|
login.clone_from(&req.login);
|
||||||
let response: LoginResult = users
|
let response: LoginResult = users
|
||||||
.send(users_actor::LocalLoginRequest {
|
.send(users_actor::LocalLoginRequest {
|
||||||
@@ -224,6 +227,10 @@ pub async fn login_route(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// If there is only a single provider, trigger auto-login
|
||||||
|
else if AppConfig::get().disable_local_login && providers.len() == 1 {
|
||||||
|
return redirect_user(&providers.cloned()[0].login_url(&query.redirect));
|
||||||
|
}
|
||||||
|
|
||||||
HttpResponse::Ok().content_type("text/html").body(
|
HttpResponse::Ok().content_type("text/html").body(
|
||||||
LoginTemplate {
|
LoginTemplate {
|
||||||
@@ -235,6 +242,7 @@ pub async fn login_route(
|
|||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
login,
|
login,
|
||||||
|
show_local_login: !AppConfig::get().disable_local_login,
|
||||||
providers: providers.cloned(),
|
providers: providers.cloned(),
|
||||||
}
|
}
|
||||||
.render()
|
.render()
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ use crate::data::login_redirect::{LoginRedirect, get_2fa_url};
|
|||||||
use crate::data::session_identity::SessionIdentity;
|
use crate::data::session_identity::SessionIdentity;
|
||||||
use crate::data::user::User;
|
use crate::data::user::User;
|
||||||
use crate::utils::string_utils::rand_str;
|
use crate::utils::string_utils::rand_str;
|
||||||
use crate::utils::time::time;
|
use crate::utils::time_utils::time;
|
||||||
|
|
||||||
pub async fn get_configuration(req: HttpRequest) -> impl Responder {
|
pub async fn get_configuration(req: HttpRequest) -> impl Responder {
|
||||||
let is_secure_request = req
|
let is_secure_request = req
|
||||||
|
|||||||
@@ -1,11 +1,5 @@
|
|||||||
use std::sync::Arc;
|
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::bruteforce_actor::BruteForceActor;
|
||||||
use crate::actors::providers_states_actor::{ProviderLoginState, ProvidersStatesActor};
|
use crate::actors::providers_states_actor::{ProviderLoginState, ProvidersStatesActor};
|
||||||
use crate::actors::users_actor::{LoginResult, UsersActor};
|
use crate::actors::users_actor::{LoginResult, UsersActor};
|
||||||
@@ -18,6 +12,11 @@ use crate::data::login_redirect::LoginRedirect;
|
|||||||
use crate::data::provider::{ProviderID, ProvidersManager};
|
use crate::data::provider::{ProviderID, ProvidersManager};
|
||||||
use crate::data::provider_configuration::ProviderConfigurationHelper;
|
use crate::data::provider_configuration::ProviderConfigurationHelper;
|
||||||
use crate::data::session_identity::{SessionIdentity, SessionStatus};
|
use crate::data::session_identity::{SessionIdentity, SessionStatus};
|
||||||
|
use actix::Addr;
|
||||||
|
use actix_identity::Identity;
|
||||||
|
use actix_remote_ip::RemoteIP;
|
||||||
|
use actix_web::{HttpRequest, HttpResponse, Responder, web};
|
||||||
|
use askama::Template;
|
||||||
|
|
||||||
#[derive(askama::Template)]
|
#[derive(askama::Template)]
|
||||||
#[template(path = "login/prov_login_error.html")]
|
#[template(path = "login/prov_login_error.html")]
|
||||||
@@ -273,7 +272,7 @@ pub async fn finish_login(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Check if email was provided by the userinfo endpoint
|
// Check if email was provided by the userinfo endpoint
|
||||||
let email = match user_info.email {
|
let email = match &user_info.email {
|
||||||
Some(e) => e,
|
Some(e) => e,
|
||||||
None => {
|
None => {
|
||||||
logger.log(Action::ProviderMissingEmailInResponse {
|
logger.log(Action::ProviderMissingEmailInResponse {
|
||||||
@@ -293,6 +292,7 @@ pub async fn finish_login(
|
|||||||
let result: LoginResult = users
|
let result: LoginResult = users
|
||||||
.send(users_actor::ProviderLoginRequest {
|
.send(users_actor::ProviderLoginRequest {
|
||||||
email: email.clone(),
|
email: email.clone(),
|
||||||
|
user_info: user_info.clone(),
|
||||||
provider: provider.clone(),
|
provider: provider.clone(),
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
@@ -300,6 +300,13 @@ pub async fn finish_login(
|
|||||||
|
|
||||||
let user = match result {
|
let user = match result {
|
||||||
LoginResult::Success(u) => u,
|
LoginResult::Success(u) => u,
|
||||||
|
LoginResult::AccountAutoCreated(u) => {
|
||||||
|
logger.log(Action::ProviderAccountAutoCreated {
|
||||||
|
provider: &provider,
|
||||||
|
user: u.loggable(),
|
||||||
|
});
|
||||||
|
u
|
||||||
|
}
|
||||||
LoginResult::AccountNotFound => {
|
LoginResult::AccountNotFound => {
|
||||||
logger.log(Action::ProviderAccountNotFound {
|
logger.log(Action::ProviderAccountNotFound {
|
||||||
provider: &provider,
|
provider: &provider,
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ pub(crate) struct BaseSettingsPage<'a> {
|
|||||||
pub success_message: Option<String>,
|
pub success_message: Option<String>,
|
||||||
pub page_title: &'static str,
|
pub page_title: &'static str,
|
||||||
pub app_name: &'static str,
|
pub app_name: &'static str,
|
||||||
|
pub local_login_enabled: bool,
|
||||||
pub user: &'a User,
|
pub user: &'a User,
|
||||||
pub version: &'static str,
|
pub version: &'static str,
|
||||||
pub ip_location_api: Option<&'static str>,
|
pub ip_location_api: Option<&'static str>,
|
||||||
@@ -37,6 +38,7 @@ impl<'a> BaseSettingsPage<'a> {
|
|||||||
app_name: APP_NAME,
|
app_name: APP_NAME,
|
||||||
user,
|
user,
|
||||||
version: env!("CARGO_PKG_VERSION"),
|
version: env!("CARGO_PKG_VERSION"),
|
||||||
|
local_login_enabled: !AppConfig::get().disable_local_login,
|
||||||
ip_location_api: AppConfig::get().ip_location_service.as_deref(),
|
ip_location_api: AppConfig::get().ip_location_service.as_deref(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
use actix::Addr;
|
use actix::Addr;
|
||||||
use actix_web::{HttpResponse, Responder, web};
|
use actix_web::{HttpResponse, Responder, web};
|
||||||
use uuid::Uuid;
|
|
||||||
use webauthn_rs::prelude::RegisterPublicKeyCredential;
|
use webauthn_rs::prelude::RegisterPublicKeyCredential;
|
||||||
|
|
||||||
use crate::actors::users_actor;
|
use crate::actors::users_actor;
|
||||||
@@ -53,7 +52,7 @@ pub async fn save_totp_factor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
let factor = TwoFactor {
|
let factor = TwoFactor {
|
||||||
id: FactorID(Uuid::new_v4().to_string()),
|
id: FactorID::random(),
|
||||||
name: factor_name,
|
name: factor_name,
|
||||||
kind: TwoFactorType::TOTP(key),
|
kind: TwoFactorType::TOTP(key),
|
||||||
};
|
};
|
||||||
@@ -102,7 +101,7 @@ pub async fn save_webauthn_factor(
|
|||||||
};
|
};
|
||||||
|
|
||||||
let factor = TwoFactor {
|
let factor = TwoFactor {
|
||||||
id: FactorID(Uuid::new_v4().to_string()),
|
id: FactorID::random(),
|
||||||
name: factor_name,
|
name: factor_name,
|
||||||
kind: TwoFactorType::WEBAUTHN(Box::new(key)),
|
kind: TwoFactorType::WEBAUTHN(Box::new(key)),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ use crate::data::current_user::CurrentUser;
|
|||||||
use crate::data::totp_key::TotpKey;
|
use crate::data::totp_key::TotpKey;
|
||||||
use crate::data::user::User;
|
use crate::data::user::User;
|
||||||
use crate::data::webauthn_manager::WebAuthManagerReq;
|
use crate::data::webauthn_manager::WebAuthManagerReq;
|
||||||
use crate::utils::time::fmt_time;
|
use crate::utils::time_utils::fmt_time;
|
||||||
|
|
||||||
#[derive(Template)]
|
#[derive(Template)]
|
||||||
#[template(path = "settings/two_factors_page.html")]
|
#[template(path = "settings/two_factors_page.html")]
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ use crate::data::provider::{Provider, ProviderID};
|
|||||||
|
|
||||||
use crate::data::session_identity::SessionIdentity;
|
use crate::data::session_identity::SessionIdentity;
|
||||||
use crate::data::user::{FactorID, GrantedClients, TwoFactor, TwoFactorType, User, UserID};
|
use crate::data::user::{FactorID, GrantedClients, TwoFactor, TwoFactorType, User, UserID};
|
||||||
use crate::utils::time::time;
|
use crate::utils::time_utils::time;
|
||||||
|
|
||||||
#[derive(serde::Serialize)]
|
#[derive(serde::Serialize)]
|
||||||
pub struct LoggableUser {
|
pub struct LoggableUser {
|
||||||
@@ -150,6 +150,10 @@ pub enum Action<'a> {
|
|||||||
provider: &'a Provider,
|
provider: &'a Provider,
|
||||||
email: &'a str,
|
email: &'a str,
|
||||||
},
|
},
|
||||||
|
ProviderAccountAutoCreated {
|
||||||
|
provider: &'a Provider,
|
||||||
|
user: LoggableUser,
|
||||||
|
},
|
||||||
ProviderAccountDisabled {
|
ProviderAccountDisabled {
|
||||||
provider: &'a Provider,
|
provider: &'a Provider,
|
||||||
email: &'a str,
|
email: &'a str,
|
||||||
@@ -282,6 +286,11 @@ impl Action<'_> {
|
|||||||
"could not login using provider {} because the email {email} could not be associated to any account!",
|
"could not login using provider {} because the email {email} could not be associated to any account!",
|
||||||
&provider.id.0
|
&provider.id.0
|
||||||
),
|
),
|
||||||
|
Action::ProviderAccountAutoCreated { provider, user } => format!(
|
||||||
|
"triggered automatic account creation for {} from provider {} because it was not found in local accounts list!",
|
||||||
|
user.quick_identity(),
|
||||||
|
&provider.id.0
|
||||||
|
),
|
||||||
Action::ProviderAccountDisabled { provider, email } => format!(
|
Action::ProviderAccountDisabled { provider, email } => format!(
|
||||||
"could not login using provider {} because the account associated to the email {email} is disabled!",
|
"could not login using provider {} because the account associated to the email {email} is disabled!",
|
||||||
&provider.id.0
|
&provider.id.0
|
||||||
|
|||||||
@@ -62,6 +62,35 @@ pub struct AppConfig {
|
|||||||
/// Login background image
|
/// Login background image
|
||||||
#[arg(long, env, default_value = "/assets/img/forest.jpg")]
|
#[arg(long, env, default_value = "/assets/img/forest.jpg")]
|
||||||
pub login_background_image: String,
|
pub login_background_image: String,
|
||||||
|
|
||||||
|
/// Disable local login. If this option is set without any upstream providers set, it will be impossible
|
||||||
|
/// to authenticate
|
||||||
|
#[arg(long, env)]
|
||||||
|
pub disable_local_login: bool,
|
||||||
|
|
||||||
|
/// Use Redis to store cookie sessions
|
||||||
|
#[arg(long, env)]
|
||||||
|
pub use_redis: bool,
|
||||||
|
|
||||||
|
/// Redis connection hostname
|
||||||
|
#[clap(long, env, default_value = "localhost")]
|
||||||
|
redis_hostname: String,
|
||||||
|
|
||||||
|
/// Redis connection port
|
||||||
|
#[clap(long, env, default_value_t = 6379)]
|
||||||
|
redis_port: u16,
|
||||||
|
|
||||||
|
/// Redis database number
|
||||||
|
#[clap(long, env, default_value_t = 0)]
|
||||||
|
redis_db_number: i64,
|
||||||
|
|
||||||
|
/// Redis username
|
||||||
|
#[clap(long, env)]
|
||||||
|
redis_username: Option<String>,
|
||||||
|
|
||||||
|
/// Redis password
|
||||||
|
#[clap(long, env, default_value = "secretredis")]
|
||||||
|
redis_password: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
lazy_static::lazy_static! {
|
lazy_static::lazy_static! {
|
||||||
@@ -132,6 +161,21 @@ impl AppConfig {
|
|||||||
let domain = self.domain_name();
|
let domain = self.domain_name();
|
||||||
domain.split_once(':').map(|i| i.0).unwrap_or(domain)
|
domain.split_once(':').map(|i| i.0).unwrap_or(domain)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Get Redis connection configuration
|
||||||
|
pub fn redis_connection_string(&self) -> Option<String> {
|
||||||
|
match self.use_redis {
|
||||||
|
true => Some(format!(
|
||||||
|
"redis://{}:{}@{}:{}/{}",
|
||||||
|
self.redis_username.as_deref().unwrap_or(""),
|
||||||
|
self.redis_password,
|
||||||
|
self.redis_hostname,
|
||||||
|
self.redis_port,
|
||||||
|
self.redis_db_number
|
||||||
|
)),
|
||||||
|
false => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ use crate::actors::users_actor::UsersActor;
|
|||||||
use crate::constants::SECOND_FACTOR_EXPIRATION_FOR_CRITICAL_OPERATIONS;
|
use crate::constants::SECOND_FACTOR_EXPIRATION_FOR_CRITICAL_OPERATIONS;
|
||||||
use crate::data::session_identity::SessionIdentity;
|
use crate::data::session_identity::SessionIdentity;
|
||||||
use crate::data::user::User;
|
use crate::data::user::User;
|
||||||
use crate::utils::time::time;
|
use crate::utils::time_utils::time;
|
||||||
|
|
||||||
pub struct CurrentUser {
|
pub struct CurrentUser {
|
||||||
user: User,
|
user: User,
|
||||||
|
|||||||
@@ -26,6 +26,10 @@ pub struct Provider {
|
|||||||
///
|
///
|
||||||
/// (.well-known/openid-configuration endpoint)
|
/// (.well-known/openid-configuration endpoint)
|
||||||
pub configuration_url: String,
|
pub configuration_url: String,
|
||||||
|
|
||||||
|
/// Set to true if accounts on BasicOIDC should be automatically created from this provider
|
||||||
|
#[serde(default)]
|
||||||
|
pub allow_auto_account_creation: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Provider {
|
impl Provider {
|
||||||
@@ -42,6 +46,7 @@ impl Provider {
|
|||||||
"github" => "/assets/img/brands/github.svg",
|
"github" => "/assets/img/brands/github.svg",
|
||||||
"microsoft" => "/assets/img/brands/microsoft.svg",
|
"microsoft" => "/assets/img/brands/microsoft.svg",
|
||||||
"google" => "/assets/img/brands/google.svg",
|
"google" => "/assets/img/brands/google.svg",
|
||||||
|
"openid" => "/assets/img/brands/openid.svg",
|
||||||
s => s,
|
s => s,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ use crate::data::app_config::AppConfig;
|
|||||||
|
|
||||||
use crate::data::provider::Provider;
|
use crate::data::provider::Provider;
|
||||||
use crate::utils::err::Res;
|
use crate::utils::err::Res;
|
||||||
use crate::utils::time::time;
|
use crate::utils::time_utils::time;
|
||||||
|
|
||||||
/// Provider configuration
|
/// Provider configuration
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
|
|||||||
@@ -3,22 +3,17 @@ use actix_web::{HttpMessage, HttpRequest};
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::data::user::{User, UserID};
|
use crate::data::user::{User, UserID};
|
||||||
use crate::utils::time::time;
|
use crate::utils::time_utils::time;
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
|
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Default)]
|
||||||
pub enum SessionStatus {
|
pub enum SessionStatus {
|
||||||
|
#[default]
|
||||||
Invalid,
|
Invalid,
|
||||||
SignedIn,
|
SignedIn,
|
||||||
NeedNewPassword,
|
NeedNewPassword,
|
||||||
Need2FA,
|
Need2FA,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for SessionStatus {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self::Invalid
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize, Default)]
|
#[derive(Debug, Serialize, Deserialize, Default)]
|
||||||
pub struct SessionIdentityData {
|
pub struct SessionIdentityData {
|
||||||
pub id: Option<UserID>,
|
pub id: Option<UserID>,
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use totp_rfc6238::{HashAlgorithm, TotpGenerator};
|
|||||||
use crate::data::app_config::AppConfig;
|
use crate::data::app_config::AppConfig;
|
||||||
use crate::data::user::User;
|
use crate::data::user::User;
|
||||||
use crate::utils::err::Res;
|
use crate::utils::err::Res;
|
||||||
use crate::utils::time::time;
|
use crate::utils::time_utils::time;
|
||||||
|
|
||||||
const BASE32_ALPHABET: Alphabet = Alphabet::Rfc4648 { padding: true };
|
const BASE32_ALPHABET: Alphabet = Alphabet::Rfc4648 { padding: true };
|
||||||
const NUM_DIGITS: usize = 6;
|
const NUM_DIGITS: usize = 6;
|
||||||
|
|||||||
@@ -9,11 +9,17 @@ use crate::data::login_redirect::LoginRedirect;
|
|||||||
use crate::data::provider::{Provider, ProviderID};
|
use crate::data::provider::{Provider, ProviderID};
|
||||||
use crate::data::totp_key::TotpKey;
|
use crate::data::totp_key::TotpKey;
|
||||||
use crate::data::webauthn_manager::WebauthnPubKey;
|
use crate::data::webauthn_manager::WebauthnPubKey;
|
||||||
use crate::utils::time::{fmt_time, time};
|
use crate::utils::time_utils::{fmt_time, time};
|
||||||
|
|
||||||
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Encode, Decode)]
|
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Encode, Decode)]
|
||||||
pub struct UserID(pub String);
|
pub struct UserID(pub String);
|
||||||
|
|
||||||
|
impl UserID {
|
||||||
|
pub fn random() -> Self {
|
||||||
|
Self(uuid::Uuid::new_v4().to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct GeneralSettings {
|
pub struct GeneralSettings {
|
||||||
pub uid: UserID,
|
pub uid: UserID,
|
||||||
@@ -46,6 +52,12 @@ impl GrantedClients {
|
|||||||
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
|
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||||
pub struct FactorID(pub String);
|
pub struct FactorID(pub String);
|
||||||
|
|
||||||
|
impl FactorID {
|
||||||
|
pub fn random() -> Self {
|
||||||
|
Self(uuid::Uuid::new_v4().to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||||
pub enum TwoFactorType {
|
pub enum TwoFactorType {
|
||||||
TOTP(TotpKey),
|
TOTP(TotpKey),
|
||||||
@@ -295,7 +307,7 @@ impl Eq for User {}
|
|||||||
impl Default for User {
|
impl Default for User {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
uid: UserID(uuid::Uuid::new_v4().to_string()),
|
uid: UserID::random(),
|
||||||
first_name: "".to_string(),
|
first_name: "".to_string(),
|
||||||
last_name: "".to_string(),
|
last_name: "".to_string(),
|
||||||
username: "".to_string(),
|
username: "".to_string(),
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use crate::actors::users_actor::{AuthorizedAuthenticationSources, UsersSyncBacke
|
|||||||
use crate::data::entity_manager::EntityManager;
|
use crate::data::entity_manager::EntityManager;
|
||||||
use crate::data::user::{FactorID, GeneralSettings, GrantedClients, TwoFactor, User, UserID};
|
use crate::data::user::{FactorID, GeneralSettings, GrantedClients, TwoFactor, User, UserID};
|
||||||
use crate::utils::err::{Res, new_error};
|
use crate::utils::err::{Res, new_error};
|
||||||
use crate::utils::time::time;
|
use crate::utils::time_utils::time;
|
||||||
|
|
||||||
impl EntityManager<User> {
|
impl EntityManager<User> {
|
||||||
/// Update user information
|
/// Update user information
|
||||||
@@ -71,7 +71,7 @@ impl UsersSyncBackend for EntityManager<User> {
|
|||||||
|
|
||||||
fn create_user_account(&mut self, settings: GeneralSettings) -> Res<UserID> {
|
fn create_user_account(&mut self, settings: GeneralSettings) -> Res<UserID> {
|
||||||
let mut user = User {
|
let mut user = User {
|
||||||
uid: UserID(uuid::Uuid::new_v4().to_string()),
|
uid: UserID::random(),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
user.update_general_settings(settings);
|
user.update_general_settings(settings);
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ use crate::constants::{
|
|||||||
use crate::data::app_config::AppConfig;
|
use crate::data::app_config::AppConfig;
|
||||||
use crate::data::user::{User, UserID};
|
use crate::data::user::{User, UserID};
|
||||||
use crate::utils::err::Res;
|
use crate::utils::err::Res;
|
||||||
use crate::utils::time::time;
|
use crate::utils::time_utils::time;
|
||||||
|
|
||||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||||
pub struct WebauthnPubKey {
|
pub struct WebauthnPubKey {
|
||||||
|
|||||||
35
src/main.rs
35
src/main.rs
@@ -1,12 +1,12 @@
|
|||||||
use core::time::Duration;
|
use core::time::Duration;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use actix::Actor;
|
use actix::{Actor, Addr};
|
||||||
use actix_identity::IdentityMiddleware;
|
use actix_identity::IdentityMiddleware;
|
||||||
use actix_identity::config::LogoutBehavior;
|
use actix_identity::config::LogoutBehavior;
|
||||||
use actix_remote_ip::RemoteIPConfig;
|
use actix_remote_ip::RemoteIPConfig;
|
||||||
use actix_session::SessionMiddleware;
|
use actix_session::SessionMiddleware;
|
||||||
use actix_session::storage::CookieSessionStore;
|
use actix_session::storage::{CookieSessionStore, RedisSessionStore};
|
||||||
use actix_web::cookie::{Key, SameSite};
|
use actix_web::cookie::{Key, SameSite};
|
||||||
use actix_web::middleware::Logger;
|
use actix_web::middleware::Logger;
|
||||||
use actix_web::{App, HttpResponse, HttpServer, get, middleware, web};
|
use actix_web::{App, HttpResponse, HttpServer, get, middleware, web};
|
||||||
@@ -14,6 +14,7 @@ use actix_web::{App, HttpResponse, HttpServer, get, middleware, web};
|
|||||||
use basic_oidc::actors::bruteforce_actor::BruteForceActor;
|
use basic_oidc::actors::bruteforce_actor::BruteForceActor;
|
||||||
use basic_oidc::actors::openid_sessions_actor::OpenIDSessionsActor;
|
use basic_oidc::actors::openid_sessions_actor::OpenIDSessionsActor;
|
||||||
use basic_oidc::actors::providers_states_actor::ProvidersStatesActor;
|
use basic_oidc::actors::providers_states_actor::ProvidersStatesActor;
|
||||||
|
use basic_oidc::actors::users_actor;
|
||||||
use basic_oidc::actors::users_actor::{UsersActor, UsersSyncBackend};
|
use basic_oidc::actors::users_actor::{UsersActor, UsersSyncBackend};
|
||||||
use basic_oidc::constants::*;
|
use basic_oidc::constants::*;
|
||||||
use basic_oidc::controllers::assets_controller::assets_route;
|
use basic_oidc::controllers::assets_controller::assets_route;
|
||||||
@@ -26,9 +27,20 @@ use basic_oidc::data::provider::ProvidersManager;
|
|||||||
use basic_oidc::data::user::User;
|
use basic_oidc::data::user::User;
|
||||||
use basic_oidc::data::webauthn_manager::WebAuthManager;
|
use basic_oidc::data::webauthn_manager::WebAuthManager;
|
||||||
use basic_oidc::middlewares::auth_middleware::AuthMiddleware;
|
use basic_oidc::middlewares::auth_middleware::AuthMiddleware;
|
||||||
|
use basic_oidc::middlewares::multi_session_store::MultiSessionStore;
|
||||||
|
|
||||||
#[get("/health")]
|
#[get("/health")]
|
||||||
async fn health() -> &'static str {
|
async fn health(users: web::Data<Addr<UsersActor>>) -> &'static str {
|
||||||
|
// Check users list is working
|
||||||
|
let users = users
|
||||||
|
.send(users_actor::GetAllUsers)
|
||||||
|
.await
|
||||||
|
.expect("Could not retrieve users list!");
|
||||||
|
if users.is_empty() {
|
||||||
|
log::error!("Got empty list of users!");
|
||||||
|
panic!("Got empty list of users!");
|
||||||
|
}
|
||||||
|
|
||||||
"Running"
|
"Running"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,6 +81,18 @@ async fn main() -> std::io::Result<()> {
|
|||||||
.expect("Failed to change default admin password!");
|
.expect("Failed to change default admin password!");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let redis_store = match AppConfig::get().redis_connection_string() {
|
||||||
|
Some(s) => {
|
||||||
|
log::info!("Connect to Redis session store...");
|
||||||
|
Some(
|
||||||
|
RedisSessionStore::new(s)
|
||||||
|
.await
|
||||||
|
.expect("Failed to connect to Redis!"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
|
||||||
let users_actor = UsersActor::new(users).start();
|
let users_actor = UsersActor::new(users).start();
|
||||||
let bruteforce_actor = BruteForceActor::default().start();
|
let bruteforce_actor = BruteForceActor::default().start();
|
||||||
let providers_states_actor = ProvidersStatesActor::default().start();
|
let providers_states_actor = ProvidersStatesActor::default().start();
|
||||||
@@ -91,7 +115,10 @@ async fn main() -> std::io::Result<()> {
|
|||||||
|
|
||||||
HttpServer::new(move || {
|
HttpServer::new(move || {
|
||||||
let session_mw = SessionMiddleware::builder(
|
let session_mw = SessionMiddleware::builder(
|
||||||
CookieSessionStore::default(),
|
match redis_store.clone() {
|
||||||
|
None => MultiSessionStore::Cookie(CookieSessionStore::default()),
|
||||||
|
Some(s) => MultiSessionStore::Redis(s),
|
||||||
|
},
|
||||||
Key::from(config.token_key.as_bytes()),
|
Key::from(config.token_key.as_bytes()),
|
||||||
)
|
)
|
||||||
.cookie_name(SESSION_COOKIE_NAME.to_string())
|
.cookie_name(SESSION_COOKIE_NAME.to_string())
|
||||||
|
|||||||
@@ -1 +1,2 @@
|
|||||||
pub mod auth_middleware;
|
pub mod auth_middleware;
|
||||||
|
pub mod multi_session_store;
|
||||||
|
|||||||
63
src/middlewares/multi_session_store.rs
Normal file
63
src/middlewares/multi_session_store.rs
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
use actix_session::storage::{
|
||||||
|
CookieSessionStore, LoadError, RedisSessionStore, SaveError, SessionKey, SessionStore,
|
||||||
|
UpdateError,
|
||||||
|
};
|
||||||
|
use actix_web::cookie::time::Duration;
|
||||||
|
use jwt_simple::Error;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
type SessionState = HashMap<String, String>;
|
||||||
|
|
||||||
|
/// Session store multiplexer.
|
||||||
|
///
|
||||||
|
/// Allows to easily support different store without having a lot of duplicate code
|
||||||
|
pub enum MultiSessionStore {
|
||||||
|
Cookie(CookieSessionStore),
|
||||||
|
Redis(RedisSessionStore),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SessionStore for MultiSessionStore {
|
||||||
|
async fn load(&self, session_key: &SessionKey) -> Result<Option<SessionState>, LoadError> {
|
||||||
|
match self {
|
||||||
|
MultiSessionStore::Cookie(c) => c.load(session_key).await,
|
||||||
|
MultiSessionStore::Redis(r) => r.load(session_key).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn save(
|
||||||
|
&self,
|
||||||
|
session_state: SessionState,
|
||||||
|
ttl: &Duration,
|
||||||
|
) -> Result<SessionKey, SaveError> {
|
||||||
|
match self {
|
||||||
|
MultiSessionStore::Cookie(c) => c.save(session_state, ttl).await,
|
||||||
|
MultiSessionStore::Redis(r) => r.save(session_state, ttl).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn update(
|
||||||
|
&self,
|
||||||
|
session_key: SessionKey,
|
||||||
|
session_state: SessionState,
|
||||||
|
ttl: &Duration,
|
||||||
|
) -> Result<SessionKey, UpdateError> {
|
||||||
|
match self {
|
||||||
|
MultiSessionStore::Cookie(c) => c.update(session_key, session_state, ttl).await,
|
||||||
|
MultiSessionStore::Redis(r) => r.update(session_key, session_state, ttl).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn update_ttl(&self, session_key: &SessionKey, ttl: &Duration) -> Result<(), Error> {
|
||||||
|
match self {
|
||||||
|
MultiSessionStore::Cookie(c) => c.update_ttl(session_key, ttl).await,
|
||||||
|
MultiSessionStore::Redis(r) => r.update_ttl(session_key, ttl).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn delete(&self, session_key: &SessionKey) -> Result<(), Error> {
|
||||||
|
match self {
|
||||||
|
MultiSessionStore::Cookie(c) => c.delete(session_key).await,
|
||||||
|
MultiSessionStore::Redis(r) => r.delete(session_key).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
pub mod crypt_utils;
|
pub mod crypt_utils;
|
||||||
pub mod err;
|
pub mod err;
|
||||||
pub mod string_utils;
|
pub mod string_utils;
|
||||||
pub mod time;
|
pub mod time_utils;
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use chrono::DateTime;
|
use chrono::DateTime;
|
||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
/// Get the current time since epoch
|
/// Get the current time since epoch
|
||||||
pub fn time() -> u64 {
|
pub fn time() -> u64 {
|
||||||
@@ -19,9 +19,27 @@ pub fn fmt_time(timestamp: u64) -> String {
|
|||||||
datetime.format("%Y-%m-%d %H:%M:%S").to_string()
|
datetime.format("%Y-%m-%d %H:%M:%S").to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Convert UNIX time to system time
|
||||||
|
pub fn unix_to_system_time(time: u64) -> SystemTime {
|
||||||
|
UNIX_EPOCH + Duration::from_secs(time)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Format UNIX time to HTTP date
|
||||||
|
pub fn unix_to_http_date(time: u64) -> String {
|
||||||
|
httpdate::fmt_http_date(unix_to_system_time(time))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get build time in UNIX format
|
||||||
|
pub fn build_time() -> u64 {
|
||||||
|
let build_time = build_time::build_time_local!();
|
||||||
|
let date =
|
||||||
|
chrono::DateTime::parse_from_rfc3339(build_time).expect("Failed to parse compile date");
|
||||||
|
date.timestamp() as u64
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
use crate::utils::time::{fmt_time, time};
|
use crate::utils::time_utils::{fmt_time, time};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_time() {
|
fn test_time() {
|
||||||
@@ -18,6 +18,8 @@
|
|||||||
|
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
|
<!-- Local login -->
|
||||||
|
{% if show_local_login %}
|
||||||
<form action="/login?redirect={{ p.redirect_uri.get_encoded() }}" method="post">
|
<form action="/login?redirect={{ p.redirect_uri.get_encoded() }}" method="post">
|
||||||
<div>
|
<div>
|
||||||
<div class="form-floating">
|
<div class="form-floating">
|
||||||
@@ -36,6 +38,7 @@
|
|||||||
<button class="w-100 btn btn-lg btn-primary" type="submit">Sign in</button>
|
<button class="w-100 btn btn-lg btn-primary" type="submit">Sign in</button>
|
||||||
|
|
||||||
</form>
|
</form>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
<!-- Upstream providers -->
|
<!-- Upstream providers -->
|
||||||
{% if !providers.is_empty() %}
|
{% if !providers.is_empty() %}
|
||||||
|
|||||||
@@ -24,7 +24,7 @@
|
|||||||
Account details
|
Account details
|
||||||
</a>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
{% if p.user.allow_local_login %}
|
{% if p.user.allow_local_login && p.local_login_enabled %}
|
||||||
<li>
|
<li>
|
||||||
<a href="/settings/change_password" class="nav-link link-dark">
|
<a href="/settings/change_password" class="nav-link link-dark">
|
||||||
Change password
|
Change password
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{% extends "base_settings_page.html" %}
|
{% extends "base_settings_page.html" %}
|
||||||
{% block content %}
|
{% block content %}
|
||||||
|
|
||||||
<table class="table table-hover" style="max-width: 800px;" aria-describedby="Clients list">
|
<table class="table table-hover table-break-works" style="max-width: 800px;" aria-describedby="Clients list">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th scope="col">ID</th>
|
<th scope="col">ID</th>
|
||||||
|
|||||||
Reference in New Issue
Block a user