Compare commits

..

No commits in common. "13c5b2baafd737c3258e1668371c9526634f13cb" and "e8f955220aaf77f1ff3aaf1dca7951378728dcb5" have entirely different histories.

19 changed files with 641 additions and 928 deletions

1
.gitignore vendored
View File

@ -4,4 +4,3 @@ links.db
launch.json
settings.json
links.session.sql
sqltemplates

685
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
[package]
name = "pslink"
version = "0.3.0"
version = "0.2.2"
description = "A simple webservice that allows registered users to create short links including qr-codes.\nAnyone can visit the shortened links. This is an ideal setup for small busines or for publishing papers."
authors = ["Dietrich <dietrich@teilgedanken.de>"]
edition = "2018"
@ -8,7 +8,7 @@ license = "MIT OR Apache-2.0"
keywords = ["url", "link", "webpage", "actix", "web"]
categories = ["web-programming", "network-programming", "web-programming::http-server", "command-line-utilities"]
readme = "README.md"
repository = "https://github.com/enaut/pslink/"
repository = "https://git.teilgedanken.de/dietrich/Pslink"
build = "build.rs"
@ -20,8 +20,11 @@ actix-web-static-files = "3.0"
actix-slog = "0.2"
tera = "1.6"
serde = "1.0"
sqlx={version="0.4", features = [ "sqlite", "macros", "runtime-actix-rustls", "chrono", "migrate" ]}
dotenv = "0.15.0"
diesel = { version = "1.4", features = ["sqlite", "chrono"] }
#diesel_codegen = { version = "0.16.1", features = ["sqlite"] }
diesel_migrations = "1.4"
#libsqlite3-sys = { version = "0.8", features = ["bundled"] }
dotenv = "0.10.1"
actix-identity = "0.3"
chrono = { version = "0.4", features = ["serde"] }
argonautica = "0.2"
@ -40,4 +43,4 @@ actix-web-static-files = "3.0"
# optimize for size at cost of compilation speed.
[profile.release]
lto = true
#codegen-units = 1
codegen-units = 1

View File

@ -2,8 +2,6 @@
The target audience of this tool are small entities that need a url shortener. The shortened urls can be publicly resolved but only registered users can create short urls. Every registered user can see all shorted urls but ownly modify its own. Admin users can invite other accounts and edit everything that can be edited (also urls created by other accounts).
So in general this is more a shared short url bookmark webpage than a shorturl service.
![Screenshot](./doc/img/pslinkscreenshot.png)
The Page comes with a basic commandline interface to setup the environment. If it is built with `cargo build release --target=x86_64-unknown-linux-musl` everything is embedded and it should be portable to any 64bit linux system.

5
diesel.toml Normal file
View File

@ -0,0 +1,5 @@
# For documentation on how to configure this file,
# see diesel.rs/guides/configuring-diesel-cli
[print_schema]
file = "src/schema.rs"

View File

@ -0,0 +1,3 @@
-- This file should undo anything in `up.sql`
DROP TABLE users;
DROP TABLE links;

View File

@ -0,0 +1,29 @@
-- Your SQL goes here
CREATE TABLE users
(
id INTEGER PRIMARY KEY NOT NULL,
username VARCHAR NOT NULL,
email VARCHAR NOT NULL,
password VARCHAR NOT NULL,
UNIQUE(username, email)
);
CREATE TABLE links
(
id INTEGER PRIMARY KEY NOT NULL,
title VARCHAR NOT NULL,
target VARCHAR NOT NULL,
code VARCHAR NOT NULL,
author INT NOT NULL,
created_at TIMESTAMP NOT NULL,
FOREIGN KEY
(author)
REFERENCES users
(id),
UNIQUE
(code)
);

View File

@ -0,0 +1,3 @@
-- This file should undo anything in `up.sql`
DROP TABLE clicks;

View File

@ -0,0 +1,13 @@
-- Your SQL goes here
CREATE TABLE clicks
(
id INTEGER PRIMARY KEY NOT NULL,
link INT NOT NULL,
created_at TIMESTAMP NOT NULL,
FOREIGN KEY
(link)
REFERENCES links
(id)
);

View File

@ -0,0 +1,20 @@
-- This file should undo anything in `up.sql`
CREATE TABLE usersold
(
id INTEGER PRIMARY KEY NOT NULL,
username VARCHAR NOT NULL,
email VARCHAR NOT NULL,
password VARCHAR NOT NULL,
UNIQUE(username, email)
);
INSERT INTO usersold
SELECT id,username,email,password
FROM users;
DROP TABLE users;
ALTER TABLE usersold
RENAME TO users;

View File

@ -0,0 +1,6 @@
-- Your SQL goes here
ALTER TABLE users ADD COLUMN role INTEGER DEFAULT 1 NOT NULL;
UPDATE users SET role=2 where id is 1;

View File

@ -1,31 +0,0 @@
-- Add up migration script here
DROP TABLE IF EXISTS __diesel_schema_migrations;
-- Add migration script here
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY NOT NULL,
username VARCHAR NOT NULL,
email VARCHAR NOT NULL,
password VARCHAR NOT NULL,
role INTEGER DEFAULT 1 NOT NULL,
UNIQUE(username),
UNIQUE(email)
);
CREATE TABLE IF NOT EXISTS links (
id INTEGER PRIMARY KEY NOT NULL,
title VARCHAR NOT NULL,
target VARCHAR NOT NULL,
code VARCHAR NOT NULL,
author INT NOT NULL,
created_at TIMESTAMP NOT NULL,
FOREIGN KEY (author) REFERENCES users (id),
UNIQUE (code)
);
CREATE TABLE IF NOT EXISTS clicks (
id INTEGER PRIMARY KEY NOT NULL,
link INT NOT NULL,
created_at TIMESTAMP NOT NULL,
FOREIGN KEY (link) REFERENCES links (id)
);

View File

@ -2,20 +2,18 @@ use clap::{
app_from_crate, crate_authors, crate_description, crate_name, crate_version, App, Arg,
ArgMatches, SubCommand,
};
use diesel::prelude::*;
use dotenv::dotenv;
use sqlx::{migrate::Migrator, Pool, Sqlite};
use std::{
fs::File,
io::{self, BufRead, Write},
path::PathBuf,
};
use crate::{models::NewUser, models::User, ServerConfig, ServerError};
use crate::{models::NewUser, ServerConfig, ServerError};
use crate::{queries, schema};
use slog::{Drain, Logger};
static MIGRATOR: Migrator = sqlx::migrate!();
#[allow(clippy::clippy::too_many_lines)]
fn generate_cli() -> App<'static, 'static> {
app_from_crate!()
@ -122,7 +120,7 @@ fn generate_cli() -> App<'static, 'static> {
)
}
async fn parse_args_to_config(config: ArgMatches<'_>, log: Logger) -> ServerConfig {
fn parse_args_to_config(config: &ArgMatches, log: &Logger) -> ServerConfig {
let secret = config
.value_of("secret")
.expect("Failed to read the secret")
@ -165,9 +163,6 @@ async fn parse_args_to_config(config: ArgMatches<'_>, log: Logger) -> ServerConf
))
.parse::<PathBuf>()
.expect("Failed to parse Database path.");
let db_pool = Pool::<Sqlite>::connect(&db.display().to_string())
.await
.expect("Error: Failed to connect to database!");
let public_url = config
.value_of("public_url")
.expect("Failed to read the host value")
@ -200,7 +195,6 @@ async fn parse_args_to_config(config: ArgMatches<'_>, log: Logger) -> ServerConf
crate::ServerConfig {
secret,
db,
db_pool,
public_url,
internal_ip,
port,
@ -211,53 +205,22 @@ async fn parse_args_to_config(config: ArgMatches<'_>, log: Logger) -> ServerConf
}
}
pub(crate) async fn setup() -> Result<Option<crate::ServerConfig>, ServerError> {
pub(crate) fn setup() -> Result<Option<crate::ServerConfig>, ServerError> {
dotenv().ok();
// initiallize the logger
let decorator = slog_term::TermDecorator::new().build();
let drain = slog_term::FullFormat::new(decorator).build().fuse();
let drain = slog_async::Async::new(drain).build().fuse();
let log = slog::Logger::root(drain, slog_o!("name" => "Pslink"));
// Print launch info
slog_info!(log, "Launching Pslink a 'Private short link generator'");
slog_info!(log, "logging initialized");
slog_info!(log, ".env file setup, logging initialized");
let app = generate_cli();
let config = app.get_matches();
let db = config
.value_of("database")
.expect(concat!(
"Neither the DATABASE_URL environment variable",
" nor the commandline parameters",
" contain a valid database location."
))
.parse::<PathBuf>()
.expect("Failed to parse Database path.");
if !db.exists() {
if config.subcommand_matches("migrate-database").is_none() {
let msg = format!(
concat!(
"Database not found at {}!",
" Create a new database with: `pslink migrate-database`",
"or adjust the databasepath."
),
db.display()
);
slog_error!(log, "{}", msg);
eprintln!("{}", msg);
return Ok(None);
}
// create an empty database file the if above makes sure that this file does not exist.
File::create(db)?;
};
let server_config: crate::ServerConfig = parse_args_to_config(config.clone(), log).await;
let server_config: crate::ServerConfig = parse_args_to_config(&config, &log);
if let Some(_migrate_config) = config.subcommand_matches("generate-env") {
return match generate_env_file(&server_config) {
@ -266,26 +229,45 @@ pub(crate) async fn setup() -> Result<Option<crate::ServerConfig>, ServerError>
};
}
if let Some(_migrate_config) = config.subcommand_matches("migrate-database") {
return match apply_migrations(&server_config).await {
return match apply_migrations(&server_config) {
Ok(_) => Ok(None),
Err(e) => Err(e),
};
}
if let Some(_create_config) = config.subcommand_matches("create-admin") {
return match create_admin(&server_config).await {
return match create_admin(&server_config) {
Ok(_) => Ok(None),
Err(e) => Err(e),
};
}
if let Some(_runserver_config) = config.subcommand_matches("runserver") {
let num_users = User::count_admins(&server_config).await?;
let connection = if server_config.db.exists() {
queries::establish_connection(&server_config.db)?
} else {
let msg = format!(
concat!(
"Database not found at {}!",
" Create a new database with: `pslink migrate-database`",
"or adjust the databasepath."
),
server_config.db.display()
);
slog_error!(&server_config.log, "{}", msg);
eprintln!("{}", msg);
return Ok(None);
};
let num_users: i64 = schema::users::dsl::users
.filter(schema::users::dsl::role.eq(2))
.select(diesel::dsl::count_star())
.first(&connection)
.expect("Failed to count the users");
if num_users.number < 1 {
if num_users < 1 {
slog_warn!(
&server_config.log,
concat!(
"No admin user created you will not be",
"No user created you will not be",
" able to do anything as the service is invite only.",
" Create a user with `pslink create-admin`"
)
@ -303,10 +285,14 @@ pub(crate) async fn setup() -> Result<Option<crate::ServerConfig>, ServerError>
}
/// Interactively create a new admin user.
async fn create_admin(config: &ServerConfig) -> Result<(), ServerError> {
fn create_admin(config: &ServerConfig) -> Result<(), ServerError> {
use schema::users;
use schema::users::dsl::{email, role, username};
slog_info!(&config.log, "Creating an admin user.");
let sin = io::stdin();
let connection = queries::establish_connection(&config.db)?;
// wait for logging:
std::thread::sleep(std::time::Duration::from_millis(100));
@ -330,22 +316,30 @@ async fn create_admin(config: &ServerConfig) -> Result<(), ServerError> {
let new_admin = NewUser::new(new_username.clone(), new_email.clone(), &password, config)?;
new_admin.insert_user(config).await?;
let created_user = User::get_user_by_name(&new_username, config).await?;
created_user.toggle_admin(config).await?;
diesel::insert_into(users::table)
.values(&new_admin)
.execute(&connection)?;
slog_info!(&config.log, "Admin user created: {}", new_username);
let created_user = users::table
.filter(username.eq(new_username))
.filter(email.eq(new_email));
// Add admin rights to the user identified by (username, email) this should be unique according to sqlite constraints
diesel::update(created_user)
.set((role.eq(2),))
.execute(&connection)?;
slog_info!(&config.log, "Admin user created: {}", &new_admin.username);
Ok(())
}
async fn apply_migrations(config: &ServerConfig) -> Result<(), ServerError> {
fn apply_migrations(config: &ServerConfig) -> Result<(), ServerError> {
slog_info!(
config.log,
"Creating a database file and running the migrations in the file {}:",
&config.db.display()
);
MIGRATOR.run(&config.db_pool).await?;
let connection = queries::establish_connection(&config.db)?;
crate::embedded_migrations::run_with_output(&connection, &mut std::io::stdout())?;
Ok(())
}

View File

@ -1,4 +1,7 @@
extern crate sqlx;
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate diesel_migrations;
#[allow(unused_imports)]
#[macro_use(
slog_o,
@ -18,6 +21,7 @@ mod cli;
mod forms;
pub mod models;
mod queries;
pub mod schema;
mod views;
use std::{fmt::Display, path::PathBuf, str::FromStr};
@ -26,14 +30,13 @@ use actix_identity::{CookieIdentityPolicy, IdentityService};
use actix_web::{web, App, HttpResponse, HttpServer};
use qrcode::types::QrError;
use sqlx::{Pool, Sqlite};
use tera::Tera;
#[derive(Debug)]
pub enum ServerError {
Argonautic,
Database(sqlx::Error),
DatabaseMigration(sqlx::migrate::MigrateError),
Diesel(diesel::result::Error),
Migration(diesel_migrations::RunMigrationsError),
Environment,
Template(tera::Error),
Qr(QrError),
@ -45,14 +48,12 @@ impl std::fmt::Display for ServerError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Argonautic => write!(f, "Argonautica Error"),
Self::Database(e) => write!(f, "Database Error: {}", e),
Self::DatabaseMigration(e) => {
write!(f, "Migration Error: {}", e)
}
Self::Diesel(e) => write!(f, "Diesel Error: {}", e),
Self::Environment => write!(f, "Environment Error"),
Self::Template(e) => write!(f, "Template Error: {:?}", e),
Self::Qr(e) => write!(f, "Qr Code Error: {:?}", e),
Self::Io(e) => write!(f, "IO Error: {:?}", e),
Self::Migration(e) => write!(f, "Migration Error: {:?}", e),
Self::User(data) => write!(f, "{}", data),
}
}
@ -62,12 +63,9 @@ impl actix_web::error::ResponseError for ServerError {
fn error_response(&self) -> HttpResponse {
match self {
Self::Argonautic => HttpResponse::InternalServerError().json("Argonautica Error"),
Self::Database(e) => {
Self::Diesel(e) => {
HttpResponse::InternalServerError().json(format!("Diesel Error: {:?}", e))
}
Self::DatabaseMigration(_) => {
unimplemented!("A migration error should never be rendered")
}
Self::Environment => HttpResponse::InternalServerError().json("Environment Error"),
Self::Template(e) => {
HttpResponse::InternalServerError().json(format!("Template Error: {:?}", e))
@ -76,6 +74,9 @@ impl actix_web::error::ResponseError for ServerError {
HttpResponse::InternalServerError().json(format!("Qr Code Error: {:?}", e))
}
Self::Io(e) => HttpResponse::InternalServerError().json(format!("IO Error: {:?}", e)),
Self::Migration(e) => {
HttpResponse::InternalServerError().json(format!("Migration Error: {:?}", e))
}
Self::User(data) => HttpResponse::InternalServerError().json(data),
}
}
@ -88,16 +89,16 @@ impl From<std::env::VarError> for ServerError {
}
}
impl From<sqlx::Error> for ServerError {
fn from(err: sqlx::Error) -> Self {
eprintln!("Database error {:?}", err);
Self::Database(err)
impl From<diesel_migrations::RunMigrationsError> for ServerError {
fn from(e: diesel_migrations::RunMigrationsError) -> Self {
Self::Migration(e)
}
}
impl From<sqlx::migrate::MigrateError> for ServerError {
fn from(err: sqlx::migrate::MigrateError) -> Self {
impl From<diesel::result::Error> for ServerError {
fn from(err: diesel::result::Error) -> Self {
eprintln!("Database error {:?}", err);
Self::DatabaseMigration(err)
Self::Diesel(err)
}
}
@ -157,7 +158,6 @@ impl FromStr for Protocol {
pub(crate) struct ServerConfig {
secret: String,
db: PathBuf,
db_pool: Pool<Sqlite>,
public_url: String,
internal_ip: String,
port: u32,
@ -188,6 +188,8 @@ impl ServerConfig {
}
include!(concat!(env!("OUT_DIR"), "/generated.rs"));
embed_migrations!("migrations/");
fn build_tera() -> Tera {
let mut tera = Tera::default();
@ -337,7 +339,7 @@ async fn webservice(server_config: ServerConfig) -> std::io::Result<()> {
#[actix_web::main]
async fn main() -> Result<(), std::io::Error> {
match cli::setup().await {
match cli::setup() {
Ok(Some(server_config)) => webservice(server_config).await,
Ok(None) => {
std::thread::sleep(std::time::Duration::from_millis(100));

View File

@ -1,87 +1,22 @@
use crate::{forms::LinkForm, ServerConfig, ServerError};
use super::schema::{clicks, links, users};
use argonautica::Hasher;
use diesel::{Identifiable, Insertable, Queryable};
use dotenv::dotenv;
use serde::{Deserialize, Serialize};
#[derive(PartialEq, Serialize, Clone, Debug)]
#[derive(Identifiable, Queryable, PartialEq, Serialize, Clone, Debug)]
pub struct User {
pub id: i64,
pub id: i32,
pub username: String,
pub email: String,
pub password: String,
pub role: i64,
pub role: i32,
}
impl User {
pub(crate) async fn get_user(
id: i64,
server_config: &ServerConfig,
) -> Result<Self, ServerError> {
let user = sqlx::query_as!(Self, "Select * from users where id = ? ", id)
.fetch_one(&server_config.db_pool)
.await;
user.map_err(ServerError::Database)
}
pub(crate) async fn get_user_by_name(
name: &str,
server_config: &ServerConfig,
) -> Result<Self, ServerError> {
let user = sqlx::query_as!(Self, "Select * from users where username = ? ", name)
.fetch_one(&server_config.db_pool)
.await;
user.map_err(ServerError::Database)
}
pub(crate) async fn get_all_users(
server_config: &ServerConfig,
) -> Result<Vec<Self>, ServerError> {
let user = sqlx::query_as!(Self, "Select * from users")
.fetch_all(&server_config.db_pool)
.await;
user.map_err(ServerError::Database)
}
pub(crate) async fn update_user(
&self,
server_config: &ServerConfig,
) -> Result<(), ServerError> {
sqlx::query!(
"UPDATE users SET
username = ?,
email = ?,
password = ?,
role = ? where id = ?",
self.username,
self.email,
self.password,
self.role,
self.id
)
.execute(&server_config.db_pool)
.await?;
Ok(())
}
pub(crate) async fn toggle_admin(
self,
server_config: &ServerConfig,
) -> Result<(), ServerError> {
let new_role = 2 - (self.role + 1) % 2;
sqlx::query!("UPDATE users SET role = ? where id = ?", new_role, self.id)
.execute(&server_config.db_pool)
.await?;
Ok(())
}
pub(crate) async fn count_admins(server_config: &ServerConfig) -> Result<Count, ServerError> {
let num = sqlx::query_as!(Count, "select count(*) as number from users where role = 2")
.fetch_one(&server_config.db_pool)
.await?;
Ok(num)
}
}
#[derive(Debug, Deserialize)]
#[derive(Debug, Deserialize, Insertable)]
#[table_name = "users"]
pub struct NewUser {
pub username: String,
pub email: String,
@ -119,24 +54,6 @@ impl NewUser {
Ok(hash)
}
pub(crate) async fn insert_user(
&self,
server_config: &ServerConfig,
) -> Result<(), ServerError> {
sqlx::query!(
"Insert into users (
username,
email,
password,
role) VALUES (?,?,?,1)",
self.username,
self.email,
self.password,
)
.execute(&server_config.db_pool)
.await?;
Ok(())
}
}
#[derive(Debug, Deserialize)]
@ -145,72 +62,28 @@ pub struct LoginUser {
pub password: String,
}
#[derive(Serialize, Debug)]
#[derive(Serialize, Debug, Queryable)]
pub struct Link {
pub id: i64,
pub id: i32,
pub title: String,
pub target: String,
pub code: String,
pub author: i64,
pub author: i32,
pub created_at: chrono::NaiveDateTime,
}
impl Link {
pub(crate) async fn get_link_by_code(
code: &str,
server_config: &ServerConfig,
) -> Result<Self, ServerError> {
let link = sqlx::query_as!(Self, "Select * from links where code = ? ", code)
.fetch_one(&server_config.db_pool)
.await;
slog_info!(server_config.log, "Found link: {:?}", &link);
link.map_err(ServerError::Database)
}
pub(crate) async fn delete_link_by_code(
code: &str,
server_config: &ServerConfig,
) -> Result<(), ServerError> {
sqlx::query!("DELETE from links where code = ? ", code)
.execute(&server_config.db_pool)
.await?;
Ok(())
}
pub(crate) async fn update_link(
&self,
server_config: &ServerConfig,
) -> Result<(), ServerError> {
sqlx::query!(
"UPDATE links SET
title = ?,
target = ?,
code = ?,
author = ?,
created_at = ? where id = ?",
self.title,
self.target,
self.code,
self.author,
self.created_at,
self.id
)
.execute(&server_config.db_pool)
.await?;
Ok(())
}
}
#[derive(Serialize, Debug)]
#[derive(Serialize, Insertable)]
#[table_name = "links"]
pub struct NewLink {
pub title: String,
pub target: String,
pub code: String,
pub author: i64,
pub author: i32,
pub created_at: chrono::NaiveDateTime,
}
impl NewLink {
pub(crate) fn from_link_form(form: LinkForm, uid: i64) -> Self {
pub(crate) fn from_link_form(form: LinkForm, uid: i32) -> Self {
Self {
title: form.title,
target: form.target,
@ -219,67 +92,33 @@ impl NewLink {
created_at: chrono::Local::now().naive_utc(),
}
}
pub(crate) async fn insert(self, server_config: &ServerConfig) -> Result<(), ServerError> {
sqlx::query!(
"Insert into links (
title,
target,
code,
author,
created_at) VALUES (?,?,?,?,?)",
self.title,
self.target,
self.code,
self.author,
self.created_at,
)
.execute(&server_config.db_pool)
.await?;
Ok(())
}
}
#[derive(Serialize, Debug)]
#[derive(Serialize, Debug, Queryable)]
pub struct Click {
pub id: i64,
pub link: i64,
pub id: i32,
pub link: i32,
pub created_at: chrono::NaiveDateTime,
}
#[derive(Serialize)]
#[derive(Serialize, Insertable)]
#[table_name = "clicks"]
pub struct NewClick {
pub link: i64,
pub link: i32,
pub created_at: chrono::NaiveDateTime,
}
impl NewClick {
#[must_use]
pub fn new(link_id: i64) -> Self {
pub fn new(link_id: i32) -> Self {
Self {
link: link_id,
created_at: chrono::Local::now().naive_utc(),
}
}
pub(crate) async fn insert_click(
self,
server_config: &ServerConfig,
) -> Result<(), ServerError> {
sqlx::query!(
"Insert into clicks (
link,
created_at) VALUES (?,?)",
self.link,
self.created_at,
)
.execute(&server_config.db_pool)
.await?;
Ok(())
}
}
#[derive(Serialize, Debug)]
#[derive(Serialize, Debug, Queryable)]
pub struct Count {
pub number: i32,
count: i32,
}

View File

@ -1,5 +1,8 @@
use std::path::Path;
use actix_identity::Identity;
use actix_web::web;
use diesel::{prelude::*, sqlite::SqliteConnection};
use serde::Serialize;
use super::models::{Count, Link, NewUser, User};
@ -9,6 +12,23 @@ use crate::{
ServerConfig, ServerError,
};
/// Create a connection to the database
pub(super) fn establish_connection(database_url: &Path) -> Result<SqliteConnection, ServerError> {
match SqliteConnection::establish(&database_url.display().to_string()) {
Ok(c) => Ok(c),
Err(e) => {
eprintln!(
"Error connecting to database: {}, {}",
database_url.display(),
e
);
Err(ServerError::User(
"Error connecting to Database".to_string(),
))
}
}
}
/// The possible roles a user could have.
#[derive(Debug, Clone)]
pub enum Role {
@ -20,7 +40,7 @@ pub enum Role {
impl Role {
/// Determin if the user is admin or the given user id is his own. This is used for things where users can edit or view their own entries, whereas admins can do so for all entries.
const fn admin_or_self(&self, id: i64) -> bool {
const fn admin_or_self(&self, id: i32) -> bool {
match self {
Self::Admin { .. } => true,
Self::Regular { user } => user.id == id,
@ -30,12 +50,17 @@ impl Role {
}
/// queries the user matching the given [`actix_identity::Identity`] and determins its authentication and permission level. Returns a [`Role`] containing the user if it is authenticated.
pub(crate) async fn authenticate(
pub(crate) fn authenticate(
id: &Identity,
server_config: &ServerConfig,
) -> Result<Role, ServerError> {
if let Some(username) = id.identity() {
let user = User::get_user_by_name(&username, server_config).await?;
use super::schema::users::dsl;
let connection = establish_connection(&server_config.db)?;
let user = dsl::users
.filter(dsl::username.eq(&username))
.first::<User>(&connection)?;
return Ok(match user.role {
0 => Role::Disabled,
@ -62,58 +87,52 @@ pub struct FullLink {
}
/// Returns a List of `FullLink` meaning `Links` enriched by their author and statistics. This returns all links if the user is either Admin or Regular user.
pub(crate) async fn list_all_allowed(
pub(crate) fn list_all_allowed(
id: &Identity,
server_config: &ServerConfig,
) -> Result<List<FullLink>, ServerError> {
use crate::sqlx::Row;
match authenticate(id, server_config).await? {
use super::schema::clicks;
use super::schema::links;
use super::schema::users;
// query to select all users could be const but typespecification is too complex. A filter can be added in the match below.
let query = links::dsl::links
.inner_join(users::dsl::users)
.left_join(clicks::dsl::clicks)
.group_by(links::id)
.select((
(
links::id,
links::title,
links::target,
links::code,
links::author,
links::created_at,
),
(
users::id,
users::username,
users::email,
users::password,
users::role,
),
(diesel::dsl::sql::<diesel::sql_types::Integer>(
"COUNT(clicks.id)",
),),
));
match authenticate(id, server_config)? {
Role::Admin { user } | Role::Regular { user } => {
let links = sqlx::query(
"select
links.id as lid,
links.title as ltitle,
links.target as ltarget,
links.code as lcode,
links.author as lauthor,
links.created_at as ldate,
users.id as usid,
users.username as usern,
users.email as uemail,
users.role as urole,
count(clicks.id) as counter
from
links
join users on links.author = users.id
left join clicks on links.id = clicks.link
group by
links.id",
)
.fetch_all(&server_config.db_pool)
.await?
.into_iter()
.map(|v| FullLink {
link: Link {
id: v.get("lid"),
title: v.get("ltitle"),
target: v.get("ltarget"),
code: v.get("lcode"),
author: v.get("lauthor"),
created_at: v.get("ldate"),
},
user: User {
id: v.get("usid"),
username: v.get("usern"),
email: v.get("uemail"),
password: "invalid".to_owned(),
role: v.get("urole"),
},
clicks: Count {
number: v.get("counter"), /* count is never None */
},
});
// show all links
let all_links: Vec<FullLink> = links.collect();
let connection = establish_connection(&server_config.db)?;
let all_links: Vec<FullLink> = query
.load(&connection)?
.into_iter()
.map(|l: (Link, User, Count)| FullLink {
link: l.0,
user: l.1,
clicks: l.2,
})
.collect();
Ok(List {
user,
list: all_links,
@ -124,13 +143,15 @@ pub(crate) async fn list_all_allowed(
}
/// Only admins can list all users
pub(crate) async fn list_users(
pub(crate) fn list_users(
id: &Identity,
server_config: &ServerConfig,
) -> Result<List<User>, ServerError> {
match authenticate(id, server_config).await? {
use super::schema::users::dsl::users;
match authenticate(id, server_config)? {
Role::Admin { user } => {
let all_users: Vec<User> = User::get_all_users(server_config).await?;
let connection = establish_connection(&server_config.db)?;
let all_users: Vec<User> = users.load(&connection)?;
Ok(List {
user,
list: all_users,
@ -149,18 +170,23 @@ pub struct Item<T> {
}
/// Get a user if permissions are accordingly
pub(crate) async fn get_user(
pub(crate) fn get_user(
id: &Identity,
user_id: &str,
server_config: &ServerConfig,
) -> Result<Item<User>, ServerError> {
if let Ok(uid) = user_id.parse::<i64>() {
use super::schema::users;
if let Ok(uid) = user_id.parse::<i32>() {
slog_info!(server_config.log, "Getting user {}", uid);
let auth = authenticate(id, server_config).await?;
let auth = authenticate(id, server_config)?;
slog_info!(server_config.log, "{:?}", &auth);
if auth.admin_or_self(uid) {
match auth {
Role::Admin { user } | Role::Regular { user } => {
let viewed_user = User::get_user(uid as i64, server_config).await?;
let connection = establish_connection(&server_config.db)?;
let viewed_user = users::dsl::users
.filter(users::dsl::id.eq(&uid))
.first::<User>(&connection)?;
Ok(Item {
user,
item: viewed_user,
@ -179,23 +205,31 @@ pub(crate) async fn get_user(
}
/// Get a user **without permission checks** (needed for login)
pub(crate) async fn get_user_by_name(
pub(crate) fn get_user_by_name(
username: &str,
server_config: &ServerConfig,
) -> Result<User, ServerError> {
let user = User::get_user_by_name(username, server_config).await?;
use super::schema::users;
let connection = establish_connection(&server_config.db)?;
let user = users::dsl::users
.filter(users::dsl::username.eq(username))
.first::<User>(&connection)?;
Ok(user)
}
pub(crate) async fn create_user(
pub(crate) fn create_user(
id: &Identity,
data: &web::Form<NewUser>,
server_config: &ServerConfig,
) -> Result<Item<User>, ServerError> {
slog_info!(server_config.log, "Creating a User: {:?}", &data);
let auth = authenticate(id, server_config).await?;
let auth = authenticate(id, server_config)?;
match auth {
Role::Admin { user } => {
use super::schema::users;
let connection = establish_connection(&server_config.db)?;
let new_user = NewUser::new(
data.username.clone(),
data.email.clone(),
@ -203,10 +237,11 @@ pub(crate) async fn create_user(
server_config,
)?;
new_user.insert_user(server_config).await?;
diesel::insert_into(users::table)
.values(&new_user)
.execute(&connection)?;
// querry the new user
let new_user = get_user_by_name(&data.username, server_config).await?;
let new_user = get_user_by_name(&data.username, server_config)?;
Ok(Item {
user,
item: new_user,
@ -220,33 +255,37 @@ pub(crate) async fn create_user(
/// Take a [`actix_web::web::Form<NewUser>`] and update the corresponding entry in the database.
/// The password is only updated if a new password of at least 4 characters is provided.
/// The `user_id` is never changed.
pub(crate) async fn update_user(
pub(crate) fn update_user(
id: &Identity,
user_id: &str,
server_config: &ServerConfig,
data: &web::Form<NewUser>,
) -> Result<Item<User>, ServerError> {
if let Ok(uid) = user_id.parse::<i64>() {
let auth = authenticate(id, server_config).await?;
let unmodified_user = User::get_user(uid, server_config).await?;
if let Ok(uid) = user_id.parse::<i32>() {
let auth = authenticate(id, server_config)?;
if auth.admin_or_self(uid) {
match auth {
Role::Admin { .. } | Role::Regular { .. } => {
use super::schema::users::dsl::{email, id, password, username, users};
slog_info!(server_config.log, "Updating userinfo: ");
let password = if data.password.len() > 3 {
NewUser::hash_password(&data.password, server_config)?
} else {
unmodified_user.password
};
let new_user = User {
id: uid,
username: data.username.clone(),
email: data.email.clone(),
password,
role: unmodified_user.role,
};
new_user.update_user(server_config).await?;
let changed_user = User::get_user(uid, server_config).await?;
let connection = establish_connection(&server_config.db)?;
// Update username and email - if they have not been changed their values will be replaced by the old ones.
diesel::update(users.filter(id.eq(&uid)))
.set((
username.eq(data.username.clone()),
email.eq(data.email.clone()),
))
.execute(&connection)?;
// Update the password only if the user entered something.
if data.password.len() > 3 {
let hash = NewUser::hash_password(&data.password, server_config)?;
diesel::update(users.filter(id.eq(&uid)))
.set((password.eq(hash),))
.execute(&connection)?;
}
let changed_user = users.filter(id.eq(&uid)).first::<User>(&connection)?;
Ok(Item {
user: changed_user.clone(),
item: changed_user,
@ -264,30 +303,36 @@ pub(crate) async fn update_user(
}
}
pub(crate) async fn toggle_admin(
pub(crate) fn toggle_admin(
id: &Identity,
user_id: &str,
server_config: &ServerConfig,
) -> Result<Item<User>, ServerError> {
if let Ok(uid) = user_id.parse::<i64>() {
let auth = authenticate(id, server_config).await?;
if let Ok(uid) = user_id.parse::<i32>() {
let auth = authenticate(id, server_config)?;
match auth {
Role::Admin { .. } => {
use super::schema::users::dsl::{id, role, users};
slog_info!(server_config.log, "Changing administrator priviledges: ");
let connection = establish_connection(&server_config.db)?;
let unchanged_user = User::get_user(uid, server_config).await?;
let unchanged_user = users.filter(id.eq(&uid)).first::<User>(&connection)?;
let old = unchanged_user.role;
unchanged_user.toggle_admin(server_config).await?;
slog_info!(server_config.log, "Toggling role: old was {}", old);
let changed_user = User::get_user(uid, server_config).await?;
let new_role = 2 - (unchanged_user.role + 1) % 2;
slog_info!(
server_config.log,
"Toggled role: new is {}",
changed_user.role
"Assigning new role: {} - old was {}",
new_role,
unchanged_user.role
);
// Update the role eg. admin vs. normal vs. disabled
diesel::update(users.filter(id.eq(&uid)))
.set((role.eq(new_role),))
.execute(&connection)?;
let changed_user = users.filter(id.eq(&uid)).first::<User>(&connection)?;
Ok(Item {
user: changed_user.clone(),
item: changed_user,
@ -303,14 +348,18 @@ pub(crate) async fn toggle_admin(
}
/// Get one link if permissions are accordingly.
pub(crate) async fn get_link(
pub(crate) fn get_link(
id: &Identity,
link_code: &str,
server_config: &ServerConfig,
) -> Result<Item<Link>, ServerError> {
match authenticate(id, server_config).await? {
use super::schema::links::dsl::{code, links};
match authenticate(id, server_config)? {
Role::Admin { user } | Role::Regular { user } => {
let link = Link::get_link_by_code(link_code, server_config).await?;
let connection = establish_connection(&server_config.db)?;
let link: Link = links
.filter(code.eq(&link_code))
.first::<Link>(&connection)?;
Ok(Item { user, item: link })
}
Role::Disabled | Role::NotAuthenticated => Err(ServerError::User("Not Allowed".to_owned())),
@ -318,72 +367,75 @@ pub(crate) async fn get_link(
}
/// Get link **without authentication**
pub(crate) async fn get_link_simple(
pub(crate) fn get_link_simple(
link_code: &str,
server_config: &ServerConfig,
) -> Result<Link, ServerError> {
use super::schema::links::dsl::{code, links};
slog_info!(server_config.log, "Getting link for {:?}", link_code);
let link = Link::get_link_by_code(link_code, server_config).await?;
slog_info!(server_config.log, "Foun d link for {:?}", link);
let connection = establish_connection(&server_config.db)?;
let link: Link = links
.filter(code.eq(&link_code))
.first::<Link>(&connection)?;
Ok(link)
}
/// Click on a link
pub(crate) async fn click_link(
link_id: i64,
server_config: &ServerConfig,
) -> Result<(), ServerError> {
slog_info!(server_config.log, "Clicking on {:?}", link_id);
pub(crate) fn click_link(link_id: i32, server_config: &ServerConfig) -> Result<(), ServerError> {
use super::schema::clicks;
let new_click = NewClick::new(link_id);
new_click.insert_click(server_config).await?;
let connection = establish_connection(&server_config.db)?;
diesel::insert_into(clicks::table)
.values(&new_click)
.execute(&connection)?;
Ok(())
}
/// Click on a link
pub(crate) async fn delete_link(
pub(crate) fn delete_link(
id: &Identity,
link_code: &str,
server_config: &ServerConfig,
) -> Result<(), ServerError> {
let auth = authenticate(id, server_config).await?;
let link = get_link_simple(link_code, server_config).await?;
use super::schema::links::dsl::{code, links};
let connection = establish_connection(&server_config.db)?;
let auth = authenticate(id, server_config)?;
let link = get_link_simple(link_code, server_config)?;
if auth.admin_or_self(link.author) {
Link::delete_link_by_code(link_code, server_config).await?;
diesel::delete(links.filter(code.eq(&link_code))).execute(&connection)?;
Ok(())
} else {
Err(ServerError::User("Permission denied!".to_owned()))
}
}
/// Update a link if the user is admin or it is its own link.
pub(crate) async fn update_link(
pub(crate) fn update_link(
id: &Identity,
link_code: &str,
data: web::Form<LinkForm>,
data: &web::Form<LinkForm>,
server_config: &ServerConfig,
) -> Result<Item<Link>, ServerError> {
use super::schema::links::dsl::{code, links, target, title};
slog_info!(
server_config.log,
"Changing link to: {:?} {:?}",
&data,
&link_code
);
let auth = authenticate(id, server_config).await?;
let auth = authenticate(id, server_config)?;
match auth {
Role::Admin { .. } | Role::Regular { .. } => {
let query = get_link(id, link_code, server_config).await?;
let query = get_link(id, link_code, server_config)?;
if auth.admin_or_self(query.item.author) {
let mut link = query.item;
let LinkForm {
title,
target,
code,
} = data.into_inner();
link.code = code.clone();
link.target = target;
link.title = title;
link.update_link(server_config).await?;
get_link(id, &code, server_config).await
let connection = establish_connection(&server_config.db)?;
diesel::update(links.filter(code.eq(&query.item.code)))
.set((
code.eq(&data.code),
target.eq(&data.target),
title.eq(&data.title),
))
.execute(&connection)?;
get_link(id, &data.code, server_config)
} else {
Err(ServerError::User("Not Allowed".to_owned()))
}
@ -392,21 +444,23 @@ pub(crate) async fn update_link(
}
}
pub(crate) async fn create_link(
pub(crate) fn create_link(
id: &Identity,
data: web::Form<LinkForm>,
server_config: &ServerConfig,
) -> Result<Item<Link>, ServerError> {
let auth = authenticate(id, server_config).await?;
let auth = authenticate(id, server_config)?;
match auth {
Role::Admin { user } | Role::Regular { user } => {
let code = data.code.clone();
slog_info!(server_config.log, "Creating link for: {}", &code);
let new_link = NewLink::from_link_form(data.into_inner(), user.id);
slog_info!(server_config.log, "Creating link for: {:?}", &new_link);
use super::schema::links;
new_link.insert(server_config).await?;
let new_link = get_link_simple(&code, server_config).await?;
let connection = establish_connection(&server_config.db)?;
let new_link = NewLink::from_link_form(data.into_inner(), user.id);
diesel::insert_into(links::table)
.values(&new_link)
.execute(&connection)?;
let new_link = get_link_simple(&new_link.code, server_config)?;
Ok(Item {
user,
item: new_link,

37
src/schema.rs Normal file
View File

@ -0,0 +1,37 @@
table! {
clicks (id) {
id -> Integer,
link -> Integer,
created_at -> Timestamp,
}
}
table! {
links (id) {
id -> Integer,
title -> Text,
target -> Text,
code -> Text,
author -> Integer,
created_at -> Timestamp,
}
}
table! {
users (id) {
id -> Integer,
username -> Text,
email -> Text,
password -> Text,
role -> Integer,
}
}
joinable!(clicks -> links (link));
joinable!(links -> users (author));
allow_tables_to_appear_in_same_query!(
clicks,
links,
users,
);

View File

@ -33,7 +33,7 @@ pub(crate) async fn index(
config: web::Data<crate::ServerConfig>,
id: Identity,
) -> Result<HttpResponse, ServerError> {
if let Ok(links) = queries::list_all_allowed(&id, &config).await {
if let Ok(links) = queries::list_all_allowed(&id, &config) {
let mut data = Context::new();
data.insert("user", &links.user);
data.insert("title", &format!("Links der {}", &config.brand_name,));
@ -51,7 +51,7 @@ pub(crate) async fn index_users(
config: web::Data<crate::ServerConfig>,
id: Identity,
) -> Result<HttpResponse, ServerError> {
if let Ok(users) = queries::list_users(&id, &config).await {
if let Ok(users) = queries::list_users(&id, &config) {
let mut data = Context::new();
data.insert("user", &users.user);
data.insert("title", &format!("Benutzer der {}", &config.brand_name,));
@ -77,7 +77,7 @@ pub(crate) async fn view_link(
id: Identity,
link_id: web::Path<String>,
) -> Result<HttpResponse, ServerError> {
if let Ok(link) = queries::get_link(&id, &link_id.0, &config).await {
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(
@ -117,7 +117,7 @@ pub(crate) async fn view_profile(
user_id: web::Path<String>,
) -> Result<HttpResponse, ServerError> {
slog_info!(config.log, "Viewing Profile!");
if let Ok(query) = queries::get_user(&id, &user_id.0, &config).await {
if let Ok(query) = queries::get_user(&id, &user_id.0, &config) {
let mut data = Context::new();
data.insert("user", &query.user);
data.insert(
@ -144,7 +144,7 @@ pub(crate) async fn edit_profile(
user_id: web::Path<String>,
) -> Result<HttpResponse, ServerError> {
slog_info!(config.log, "Editing Profile!");
if let Ok(query) = queries::get_user(&id, &user_id.0, &config).await {
if let Ok(query) = queries::get_user(&id, &user_id.0, &config) {
let mut data = Context::new();
data.insert("user", &query.user);
data.insert(
@ -169,7 +169,7 @@ pub(crate) async fn process_edit_profile(
id: Identity,
user_id: web::Path<String>,
) -> Result<HttpResponse, ServerError> {
if let Ok(query) = queries::update_user(&id, &user_id.0, &config, &data).await {
if let Ok(query) = queries::update_user(&id, &user_id.0, &config, &data) {
Ok(redirect_builder(&format!(
"admin/view/profile/{}",
query.user.username
@ -184,7 +184,7 @@ pub(crate) async fn download_png(
config: web::Data<crate::ServerConfig>,
link_code: web::Path<String>,
) -> Result<HttpResponse, ServerError> {
match queries::get_link(&id, &link_code.0, &config).await {
match queries::get_link(&id, &link_code.0, &config) {
Ok(query) => {
let qr = QrCode::with_error_correction_level(
&format!("http://{}/{}", config.public_url, &query.item.code),
@ -208,7 +208,7 @@ pub(crate) async fn signup(
config: web::Data<crate::ServerConfig>,
id: Identity,
) -> Result<HttpResponse, ServerError> {
match queries::authenticate(&id, &config).await? {
match queries::authenticate(&id, &config)? {
queries::Role::Admin { user } => {
let mut data = Context::new();
data.insert("title", "Ein Benutzerkonto erstellen");
@ -229,7 +229,7 @@ pub(crate) async fn process_signup(
id: Identity,
) -> Result<HttpResponse, ServerError> {
slog_info!(config.log, "Creating a User: {:?}", &data);
if let Ok(item) = queries::create_user(&id, &data, &config).await {
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/"))
@ -241,7 +241,7 @@ pub(crate) async fn toggle_admin(
config: web::Data<crate::ServerConfig>,
id: Identity,
) -> Result<HttpResponse, ServerError> {
let update = queries::toggle_admin(&id, &data.0, &config).await?;
let update = queries::toggle_admin(&id, &data.0, &config)?;
Ok(redirect_builder(&format!(
"/admin/view/profile/{}",
update.item.id
@ -268,7 +268,7 @@ pub(crate) async fn process_login(
config: web::Data<crate::ServerConfig>,
id: Identity,
) -> Result<HttpResponse, ServerError> {
let user = queries::get_user_by_name(&data.username, &config).await;
let user = queries::get_user_by_name(&data.username, &config);
match user {
Ok(u) => {
@ -306,14 +306,14 @@ pub(crate) async fn redirect(
data: web::Path<String>,
) -> Result<HttpResponse, ServerError> {
slog_info!(config.log, "Redirecting to {:?}", data);
let link = queries::get_link_simple(&data.0, &config).await;
let link = queries::get_link_simple(&data.0, &config);
slog_info!(config.log, "link: {:?}", link);
match link {
Ok(link) => {
queries::click_link(link.id, &config).await?;
queries::click_link(link.id, &config)?;
Ok(redirect_builder(&link.target))
}
Err(ServerError::Database(e)) => {
Err(ServerError::Diesel(e)) => {
slog_info!(
config.log,
"Link was not found: http://{}/{} \n {}",
@ -341,7 +341,7 @@ pub(crate) async fn create_link(
config: web::Data<crate::ServerConfig>,
id: Identity,
) -> Result<HttpResponse, ServerError> {
match queries::authenticate(&id, &config).await? {
match queries::authenticate(&id, &config)? {
queries::Role::Admin { user } | queries::Role::Regular { user } => {
let mut data = Context::new();
data.insert("title", "Einen Kurzlink erstellen");
@ -361,7 +361,7 @@ pub(crate) async fn process_link_creation(
config: web::Data<crate::ServerConfig>,
id: Identity,
) -> Result<HttpResponse, ServerError> {
let new_link = queries::create_link(&id, data, &config).await?;
let new_link = queries::create_link(&id, data, &config)?;
Ok(redirect_builder(&format!(
"/admin/view/link/{}",
new_link.item.code
@ -374,7 +374,7 @@ pub(crate) async fn edit_link(
id: Identity,
link_id: web::Path<String>,
) -> Result<HttpResponse, ServerError> {
if let Ok(query) = queries::get_link(&id, &link_id.0, &config).await {
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);
@ -391,7 +391,7 @@ pub(crate) async fn process_link_edit(
id: Identity,
link_code: web::Path<String>,
) -> Result<HttpResponse, ServerError> {
match queries::update_link(&id, &link_code.0, data, &config).await {
match queries::update_link(&id, &link_code.0, &data, &config) {
Ok(query) => Ok(redirect_builder(&format!(
"/admin/view/link/{}",
&query.item.code
@ -405,6 +405,6 @@ pub(crate) async fn process_link_delete(
config: web::Data<crate::ServerConfig>,
link_code: web::Path<String>,
) -> Result<HttpResponse, ServerError> {
queries::delete_link(&id, &link_code.0, &config).await?;
queries::delete_link(&id, &link_code.0, &config)?;
Ok(redirect_builder("/admin/login/"))
}

View File

@ -45,7 +45,7 @@
{% endif %}
</td>
<td>
{{ c.number }}
{{ c.count }}
</td>
</tr>
{% endfor %}