Implement Authorization

This commit is contained in:
Julian Mutter 2023-05-07 18:00:27 +02:00
parent b91b022cbb
commit b33795b4e0
5 changed files with 45 additions and 7 deletions

6
Readme.md Normal file
View File

@ -0,0 +1,6 @@
# Example NATS chat application
## Users
- admin is allowed everything
- client may pusblish and subscribe to the chat channel
- guest may only read chat messages

View File

@ -17,14 +17,25 @@ fn main() {
eprintln!("Connection to server is refused. Please check if it is really running.");
exit(1);
}
_ => panic!("{}", e),
io::ErrorKind::InvalidData => {
if e.to_string().contains("Authorization Violation") {
eprintln!("Invalid login credentials.");
exit(1);
} else {
panic!("NATS response was invalid: {}", e);
}
}
_ => panic!("{:?}", e),
}
}
}
fn run_chat_program() -> io::Result<()> {
let nc = nats_cli::connect_to_nats()?;
let username = ask_user_name();
// TODO: Ask password from user
let password = username.clone();
let nc = nats_cli::connect_to_nats(&username, &password)?;
println!(
"Hello {}, please write your message. Use q to quit:",
username

View File

@ -5,10 +5,12 @@ use nats::{Connection, Handler};
use crate::chat_message::ChatMessage;
const SERVER: &str = "127.0.0.1";
const SUBJECT_MESSAGES: &str = "here.happens.messaging";
const SUBJECT_MESSAGES: &str = "telestion.chat";
pub fn connect_to_nats() -> io::Result<Connection> {
nats::connect(SERVER)
pub fn connect_to_nats(username: &str, password: &str) -> io::Result<Connection> {
nats::Options::with_user_pass(username, password)
.with_name("Chat Application")
.connect(SERVER)
}
pub fn subscribe_to_chat_messages(username: String, nc: &Connection) -> io::Result<Handler> {
@ -23,7 +25,7 @@ pub fn subscribe_to_chat_messages(username: String, nc: &Connection) -> io::Resu
println!("Received {}", message);
}
}
Err(e) => eprintln!("{}", e),
Err(e) => eprintln!("Error from NATS: {}", e),
};
Ok(())
});

View File

@ -0,0 +1,19 @@
authorization {
default_permissions = {
subscribe = "telestion.chat"
publish: { deny: ">" }
}
ADMIN = {
publish = ">"
subscribe = ">"
}
CHAT_CLIENT = {
publish = "telestion.chat"
subscribe = "telestion.chat"
}
users = [
{user: admin, password: admin, permissions: $ADMIN}
{user: client, password: client, permissions: $CHAT_CLIENT}
{user: guest, password: guest}
]
}

View File

@ -1,3 +1,3 @@
#!/usr/bin/env sh
docker run -p 4222:4222 -t nats:latest
docker run -p 4222:4222 -v ./config:/config -t nats:latest -c /config/server.conf