Add command line interface

Add a command line interface to the binary and remove parts
that were hardcoded.

new --help is:

```
pslink 0.1.0
Dietrich <dietrich@teilgedanken.de>
A simple webservice that allows registered users to create short links including qr-codes.
Anyone can visit the shortened links. This is an ideal setup for small busines or for publishing papers.

USAGE:
    pslink [OPTIONS] [SUBCOMMAND]

FLAGS:
    -h, --help       Prints help information
    -V, --version    Prints version information

OPTIONS:
        --db <database>              The path of the sqlite database [env: PSLINK_DATABASE=]  [default: links.db]
    -i, --hostip <internal_ip>       The host (ip) that will run the pslink service [env: PSLINK_IP=]  [default:
                                     localhost]
    -p, --port <port>                The port the pslink service will run on [env: PSLINK_PORT=]  [default: 8080]
    -t, --protocol <protocol>        The protocol that is used in the qr-codes (http results in slightly smaller codes
                                     in some cases) [env: PSLINK_PROTOCOL=]  [default: http]  [possible values: http,
                                     https]
    -u, --public-url <public_url>    The host url or the page that will be part of the short urls. [env:
                                     PSLINK_PUBLIC_URL=]  [default: localhost:8080]
        --secret <secret>            The secret that is used to encrypt the password database keep this as inacessable
                                     as possible. As commandlineparameters are visible to all users it is not wise to
                                     use this as a commandline parameter but rather as an environment variable. [env:
                                     PSLINK_SECRET=]  [default: ]

SUBCOMMANDS:
    runserver           Run the server
    create-admin        Create an admin user.
    generate-env        Generate an .env file template using default settings and exit
    migrate-database    Apply any pending migrations and exit
    help                Prints this message or the help of the given subcommand(s)
```
This commit is contained in:
2021-03-07 19:14:34 +01:00
parent 0553aaa935
commit 9512807eb3
10 changed files with 899 additions and 260 deletions
+59 -49
View File
@@ -6,7 +6,6 @@ use actix_web::{
web, HttpResponse,
};
use argonautica::Verifier;
use dotenv::dotenv;
use image::{DynamicImage, ImageOutputFormat, Luma};
use qrcode::{render::svg, QrCode};
use tera::{Context, Tera};
@@ -24,16 +23,17 @@ fn redirect_builder(target: &str) -> HttpResponse {
CacheDirective::MustRevalidate,
]))
.set(Expires(SystemTime::now().into()))
.set_header(actix_web::http::header::LOCATION, target.clone())
.body(format!("Redirect to {}", target.clone()))
.set_header(actix_web::http::header::LOCATION, target)
.body(format!("Redirect to {}", target))
}
/// Show the list of all available links if a user is authenticated
pub(crate) async fn index(
tera: web::Data<Tera>,
config: web::Data<crate::ServerConfig>,
id: Identity,
) -> Result<HttpResponse, ServerError> {
if let Ok(links) = queries::list_all_allowed(id) {
if let Ok(links) = queries::list_all_allowed(&id, &config) {
let mut data = Context::new();
data.insert("user", &links.user);
data.insert("title", "Links der Freien Hochschule Stuttgart");
@@ -48,9 +48,10 @@ pub(crate) async fn index(
/// Show the list of all available links if a user is authenticated
pub(crate) async fn index_users(
tera: web::Data<Tera>,
config: web::Data<crate::ServerConfig>,
id: Identity,
) -> Result<HttpResponse, ServerError> {
if let Ok(users) = queries::list_users(id) {
if let Ok(users) = queries::list_users(&id, &config) {
let mut data = Context::new();
data.insert("user", &users.user);
data.insert("title", "Benutzer der Freien Hochschule Stuttgart");
@@ -64,28 +65,29 @@ pub(crate) async fn index_users(
}
pub(crate) async fn view_link_fhs(
tera: web::Data<Tera>,
config: web::Data<crate::ServerConfig>,
id: Identity,
) -> Result<HttpResponse, ServerError> {
view_link(tera, id, web::Path::from("".to_owned())).await
view_link(tera, config, id, web::Path::from("".to_owned())).await
}
pub(crate) async fn view_link(
tera: web::Data<Tera>,
config: web::Data<crate::ServerConfig>,
id: Identity,
link_id: web::Path<String>,
) -> Result<HttpResponse, ServerError> {
if let Ok(link) = queries::get_link(id, &link_id.0) {
dotenv().ok();
let host = std::env::var("SLINK_HOST")?;
let protocol = std::env::var("SLINK_PROTOCOL")?;
if let Ok(link) = queries::get_link(&id, &link_id.0, &config) {
let host = config.public_url.to_string();
let protocol = config.protocol.to_string();
let qr = QrCode::with_error_correction_level(
&format!("http://{}/{}", &host, &link.item.id),
&format!("http://{}/{}", &host, &link.item.code),
qrcode::EcLevel::L,
)?;
let svg = qr
.render()
.min_dimensions(200, 200)
.min_dimensions(100, 100)
.dark_color(svg::Color("#000000"))
.light_color(svg::Color("#ffffff"))
.build();
@@ -94,7 +96,7 @@ pub(crate) async fn view_link(
data.insert("user", &link.user);
data.insert(
"title",
&format!("Links {} der Freien Hochschule Stuttgart", &link.item.id),
&format!("Links {} der Freien Hochschule Stuttgart", &link.item.code),
);
data.insert("link", &link.item);
data.insert("qr", &svg);
@@ -110,11 +112,12 @@ pub(crate) async fn view_link(
pub(crate) async fn view_profile(
tera: web::Data<Tera>,
config: web::Data<crate::ServerConfig>,
id: Identity,
user_id: web::Path<String>,
) -> Result<HttpResponse, ServerError> {
info!("Viewing Profile!");
if let Ok(query) = queries::get_user(id, &user_id.0) {
slog_info!(config.log, "Viewing Profile!");
if let Ok(query) = queries::get_user(&id, &user_id.0, &config) {
let mut data = Context::new();
data.insert("user", &query.user);
data.insert(
@@ -136,11 +139,12 @@ pub(crate) async fn view_profile(
pub(crate) async fn edit_profile(
tera: web::Data<Tera>,
config: web::Data<crate::ServerConfig>,
id: Identity,
user_id: web::Path<String>,
) -> Result<HttpResponse, ServerError> {
info!("Editing Profile!");
if let Ok(query) = queries::get_user(id, &user_id.0) {
slog_info!(config.log, "Editing Profile!");
if let Ok(query) = queries::get_user(&id, &user_id.0, &config) {
let mut data = Context::new();
data.insert("user", &query.user);
data.insert(
@@ -161,10 +165,11 @@ pub(crate) async fn edit_profile(
pub(crate) async fn process_edit_profile(
data: web::Form<NewUser>,
config: web::Data<crate::ServerConfig>,
id: Identity,
user_id: web::Path<String>,
) -> Result<HttpResponse, ServerError> {
if let Ok(query) = queries::update_user(id, &user_id.0, data) {
if let Ok(query) = queries::update_user(&id, &user_id.0, &config, &data) {
Ok(redirect_builder(&format!(
"admin/view/profile/{}",
query.user.username
@@ -176,17 +181,13 @@ pub(crate) async fn process_edit_profile(
pub(crate) async fn download_png(
id: Identity,
config: web::Data<crate::ServerConfig>,
link_code: web::Path<String>,
) -> Result<HttpResponse, ServerError> {
match queries::get_link(id, &link_code.0) {
match queries::get_link(&id, &link_code.0, &config) {
Ok(query) => {
dotenv().ok();
let qr = QrCode::with_error_correction_level(
&format!(
"http://{}/{}",
std::env::var("SLINK_HOST")?,
&query.item.code
),
&format!("http://{}/{}", config.public_url, &query.item.code),
qrcode::EcLevel::L,
)
.unwrap();
@@ -204,9 +205,10 @@ pub(crate) async fn download_png(
pub(crate) async fn signup(
tera: web::Data<Tera>,
config: web::Data<crate::ServerConfig>,
id: Identity,
) -> Result<HttpResponse, ServerError> {
match queries::authenticate(id)? {
match queries::authenticate(&id, &config)? {
queries::Role::Admin { user } => {
let mut data = Context::new();
data.insert("title", "Ein Benutzerkonto erstellen");
@@ -223,10 +225,11 @@ pub(crate) async fn signup(
pub(crate) async fn process_signup(
data: web::Form<NewUser>,
config: web::Data<crate::ServerConfig>,
id: Identity,
) -> Result<HttpResponse, ServerError> {
info!("Creating a User: {:?}", &data);
if let Ok(item) = queries::create_user(id, data) {
slog_info!(config.log, "Creating a User: {:?}", &data);
if let Ok(item) = queries::create_user(&id, &data, &config) {
Ok(HttpResponse::Ok().body(format!("Successfully saved user: {}", item.item.username)))
} else {
Ok(redirect_builder("/admin/login/"))
@@ -235,9 +238,10 @@ pub(crate) async fn process_signup(
pub(crate) async fn toggle_admin(
data: web::Path<String>,
config: web::Data<crate::ServerConfig>,
id: Identity,
) -> Result<HttpResponse, ServerError> {
let update = queries::toggle_admin(id, &data.0)?;
let update = queries::toggle_admin(&id, &data.0, &config)?;
Ok(redirect_builder(&format!(
"/admin/view/profile/{}",
update.item.id
@@ -261,22 +265,22 @@ pub(crate) async fn login(
pub(crate) async fn process_login(
data: web::Form<LoginUser>,
config: web::Data<crate::ServerConfig>,
id: Identity,
) -> Result<HttpResponse, ServerError> {
let user = queries::get_user_by_name(&data.username);
let user = queries::get_user_by_name(&data.username, &config);
match user {
Ok(u) => {
dotenv().ok();
let secret = std::env::var("SECRET_KEY")?;
let secret = &config.secret;
let valid = Verifier::default()
.with_hash(&u.password)
.with_password(&data.password)
.with_secret_key(&secret)
.with_secret_key(secret)
.verify()?;
if valid {
info!("Log-in of user: {}", &u.username);
slog_info!(config.log, "Log-in of user: {}", &u.username);
let session_token = u.username;
id.remember(session_token);
Ok(redirect_builder("/admin/index/"))
@@ -285,7 +289,7 @@ pub(crate) async fn process_login(
}
}
Err(e) => {
info!("Failed to login: {}", e);
slog_info!(config.log, "Failed to login: {}", e);
Ok(redirect_builder("/admin/login/"))
}
}
@@ -298,30 +302,31 @@ pub(crate) async fn logout(id: Identity) -> Result<HttpResponse, ServerError> {
pub(crate) async fn redirect(
tera: web::Data<Tera>,
config: web::Data<crate::ServerConfig>,
data: web::Path<String>,
) -> Result<HttpResponse, ServerError> {
info!("Redirecting to {:?}", data);
let link = queries::get_link_simple(&data.0);
info!("link: {:?}", link);
slog_info!(config.log, "Redirecting to {:?}", data);
let link = queries::get_link_simple(&data.0, &config);
slog_info!(config.log, "link: {:?}", link);
match link {
Ok(link) => {
queries::click_link(link.id)?;
queries::click_link(link.id, &config)?;
Ok(redirect_builder(&link.target))
}
Err(ServerError::Diesel(e)) => {
dotenv().ok();
info!(
slog_info!(
config.log,
"Link was not found: http://{}/{} \n {}",
std::env::var("SLINK_HOST")?,
&config.public_url,
&data.0,
e
);
let mut data = Context::new();
data.insert("title", "Wurde gelöscht");
data.insert("title", "Wurde gel\u{f6}scht");
let rendered = tera.render("not_found.html", &data)?;
Ok(HttpResponse::NotFound().body(rendered))
}
Err(e) => Err(e.into()),
Err(e) => Err(e),
}
}
@@ -333,9 +338,10 @@ pub(crate) async fn redirect_fhs() -> Result<HttpResponse, ServerError> {
pub(crate) async fn create_link(
tera: web::Data<Tera>,
config: web::Data<crate::ServerConfig>,
id: Identity,
) -> Result<HttpResponse, ServerError> {
match queries::authenticate(id)? {
match queries::authenticate(&id, &config)? {
queries::Role::Admin { user } | queries::Role::Regular { user } => {
let mut data = Context::new();
data.insert("title", "Einen Kurzlink erstellen");
@@ -352,9 +358,10 @@ pub(crate) async fn create_link(
pub(crate) async fn process_link_creation(
data: web::Form<LinkForm>,
config: web::Data<crate::ServerConfig>,
id: Identity,
) -> Result<HttpResponse, ServerError> {
let new_link = queries::create_link(id, data)?;
let new_link = queries::create_link(&id, data, &config)?;
Ok(redirect_builder(&format!(
"/admin/view/link/{}",
new_link.item.code
@@ -363,10 +370,11 @@ pub(crate) async fn process_link_creation(
pub(crate) async fn edit_link(
tera: web::Data<Tera>,
config: web::Data<crate::ServerConfig>,
id: Identity,
link_id: web::Path<String>,
) -> Result<HttpResponse, ServerError> {
if let Ok(query) = queries::get_link(id, &link_id.0) {
if let Ok(query) = queries::get_link(&id, &link_id.0, &config) {
let mut data = Context::new();
data.insert("title", "Submit a Post");
data.insert("link", &query.item);
@@ -379,10 +387,11 @@ pub(crate) async fn edit_link(
}
pub(crate) async fn process_link_edit(
data: web::Form<LinkForm>,
config: web::Data<crate::ServerConfig>,
id: Identity,
link_code: web::Path<String>,
) -> Result<HttpResponse, ServerError> {
match queries::update_link(id, &link_code.0, data) {
match queries::update_link(&id, &link_code.0, &data, &config) {
Ok(query) => Ok(redirect_builder(&format!(
"/admin/view/link/{}",
&query.item.code
@@ -393,8 +402,9 @@ pub(crate) async fn process_link_edit(
pub(crate) async fn process_link_delete(
id: Identity,
config: web::Data<crate::ServerConfig>,
link_code: web::Path<String>,
) -> Result<HttpResponse, ServerError> {
queries::delete_link(id, link_code.0)?;
queries::delete_link(&id, &link_code.0, &config)?;
Ok(redirect_builder("/admin/login/"))
}