Compare commits

..

No commits in common. "2cd4cf784edfb51ca240059bf2d6fc365b46040d" and "57d558e254909dfa71c344f8f1c28f0d1e7cfccb" have entirely different histories.

2 changed files with 99 additions and 121 deletions

View File

@ -53,42 +53,33 @@ async fn createuser(
mut db: Connection<Db>, mut db: Connection<Db>,
info: Json<LoginInfo>, info: Json<LoginInfo>,
cookies: &CookieJar<'_>, cookies: &CookieJar<'_>,
) -> status::Custom<String> { ) -> status::Custom<&'static str> {
let token = cookies.get_private("token"); let token = cookies.get_private("token");
match token.is_some() { match token.is_some() {
true => status::Custom( true => {
Status::Forbidden, status::Custom(Status::Forbidden,
"You're already logged in. Log out before trying to create a new account.".to_string(), "You're already logged in. Log out before trying to create a new account.")
), }
false => match User::get_by_username(&mut db, &info.username).await { false => match User::get_by_username(&mut db, &info.username).await {
Some(_) => status::Custom( Some(_) => "Username already taken. Please try again.".to_string(),
Status::Forbidden,
"Username already taken. Please try again.".to_string(),
),
None => match User::create(&mut db, &info.username, &info.password).await { None => match User::create(&mut db, &info.username, &info.password).await {
Ok(_) => match User::get_by_username(&mut db, &info.username).await { Ok(_) => match User::get_by_username(&mut db, &info.username).await {
Some(user) => match user.set_new_token(&mut db).await { Some(user) => match user.set_new_token(&mut db).await {
Ok(t) => { Ok(t) => {
cookies.add_private(("token", t)); cookies.add_private(("token", t));
status::Custom(Status::Ok, "Your account has been created and you've been automatically logged in.".to_string()) "Your account has been created and you've been automatically logged in."
.to_string()
} }
Err(why) => { Err(why) => {
eprintln!("{why:?}"); eprintln!("{why:?}");
status::Custom( "Couldn't log you in. Your account has been created, though."
Status::Created, .to_string()
"Couldn't log you in. Your account has been created, though."
.to_string(),
)
} }
}, },
None => status::Custom( None => "Something went really wrong. I don't know what.".to_string(),
Status::InternalServerError,
"Something went really wrong. I don't know what.".to_string(),
),
}, },
Err(why) => { Err(why) => {
format!("Couldn't create user: {}", why); format!("Couldn't create user: {}", why)
status::Custom(Status::InternalServerError, format!("{why}"))
} }
}, },
}, },
@ -96,20 +87,17 @@ async fn createuser(
} }
#[get("/account")] #[get("/account")]
async fn account(mut db: Connection<Db>, cookies: &CookieJar<'_>) -> status::Custom<String> { async fn account(mut db: Connection<Db>, cookies: &CookieJar<'_>) -> String {
let token = cookies.get_private("token"); let token = cookies.get_private("token");
match token { match token {
Some(t) => match User::get_by_token(&mut db, t).await { Some(t) => match User::get_by_token(&mut db, t).await {
Some(user) => status::Custom( Some(user) => format!(
Status::Ok, "Username: {}\nAdmin: {}\nMake Posts: {}\nComment: {}",
format!( user.username, user.admin, user.make_posts, user.comment
"Username: {}\nAdmin: {}\nMake Posts: {}\nComment: {}",
user.username, user.admin, user.make_posts, user.comment
),
), ),
None => status::Custom(Status::NotFound, "User doesn't exist.".to_string()), None => "User doesn't exist.".to_string(),
}, },
None => status::Custom(Status::Unauthorized, "Not logged in".to_string()), None => "Not logged in".to_string(),
} }
} }
@ -147,59 +135,44 @@ async fn login(mut db: Connection<Db>, info: Json<LoginInfo>, cookies: &CookieJa
} }
} }
#[post("/logout")] #[post("/logout")]
async fn logout(cookies: &CookieJar<'_>) -> status::Custom<&'static str> { async fn logout(cookies: &CookieJar<'_>) -> &'static str {
match cookies.get_private("token") { match cookies.get_private("token") {
Some(_) => { Some(_) => {
cookies.remove_private("token"); cookies.remove_private("token");
status::Custom(Status::Ok, "Logged out.") "Logged out."
} }
None => status::Custom(Status::Unauthorized, "Not logged in."), None => "Not logged in.",
} }
} }
#[get("/adminpanel")] #[get("/adminpanel")]
async fn adminpanel( async fn adminpanel(mut db: Connection<Db>, cookies: &CookieJar<'_>) -> RawHtml<String> {
mut db: Connection<Db>,
cookies: &CookieJar<'_>,
) -> status::Custom<RawHtml<String>> {
let token = cookies.get_private("token"); let token = cookies.get_private("token");
match token { match token {
Some(t) => match User::get_by_token(&mut db, t).await { Some(t) => match User::get_by_token(&mut db, t).await {
Some(user) => match user.admin { Some(user) => match user.admin {
true => status::Custom( true => RawHtml(
Status::Ok, fs::read_to_string("/srv/web/adminpanel.html")
RawHtml(
fs::read_to_string("/srv/web/adminpanel.html")
.unwrap()
.replace("{{username}}", &user.username[..]),
),
),
false => status::Custom(
Status::Unauthorized,
RawHtml(fs::read_to_string("/srv/web/invalidperms.html").unwrap()),
),
},
None => status::Custom(
Status::Unauthorized,
RawHtml(
fs::read_to_string("/srv/web/error.html")
.unwrap() .unwrap()
.replace("{{errorcode}}", "401"), .replace("{{username}}", &user.username[..]),
), ),
false => RawHtml(fs::read_to_string("/srv/web/invalidperms.html").unwrap()),
},
None => RawHtml(
fs::read_to_string("/srv/web/error.html")
.unwrap()
.replace("{{errorcode}}", "498"),
), ),
}, },
None => status::Custom( None => RawHtml(fs::read_to_string("/srv/web/invalidperms.html").unwrap()),
Status::Unauthorized,
RawHtml(fs::read_to_string("/srv/web/invalidperms.html").unwrap()),
),
} }
} }
// #[derive(Deserialize, Serialize)] #[derive(Deserialize, Serialize)]
// #[serde(crate = "rocket::serde")] #[serde(crate = "rocket::serde")]
// struct ApiPermsResult { struct ApiPermsResult {
// perms: Result<Perms, String>, perms: Result<Perms, String>,
// } }
#[derive(Deserialize, Serialize)] #[derive(Deserialize, Serialize)]
#[serde(crate = "rocket::serde")] #[serde(crate = "rocket::serde")]
struct Perms { struct Perms {
@ -212,29 +185,33 @@ async fn api_perms(
mut db: Connection<Db>, mut db: Connection<Db>,
username: String, username: String,
cookies: &CookieJar<'_>, cookies: &CookieJar<'_>,
) -> status::Custom<Json<Result<Perms, &'static str>>> { ) -> Json<ApiPermsResult> {
match cookies.get_private("token") { match cookies.get_private("token") {
Some(t) => match User::get_by_token(&mut db, t).await { Some(t) => match User::get_by_token(&mut db, t).await {
Some(user) => match user.admin { Some(user) => match user.admin {
true => match User::get_by_username(&mut db, &username).await { true => match User::get_by_username(&mut db, &username).await {
Some(user) => status::Custom( Some(user) => Json(ApiPermsResult {
Status::Ok, perms: Ok(Perms {
Json(Ok(Perms {
admin: user.admin, admin: user.admin,
make_posts: user.make_posts, make_posts: user.make_posts,
comment: user.comment, comment: user.comment,
})), }),
), }),
None => status::Custom(Status::NotFound, Json(Err("User doesn't exist"))), None => Json(ApiPermsResult {
perms: Err("User doesn't exist".to_string()),
}),
}, },
false => status::Custom( false => Json(ApiPermsResult {
Status::Unauthorized, perms: Err("You don't have the permission to do this".to_string()),
Json(Err("You don't have the permission to do this")), }),
),
}, },
None => status::Custom(Status::Unauthorized, Json(Err("Invalid token"))), None => Json(ApiPermsResult {
perms: Err("Invalid token".to_string()),
}),
}, },
None => status::Custom(Status::Unauthorized, Json(Err("Not logged in"))), None => Json(ApiPermsResult {
perms: Err("Not logged in".to_string()),
}),
} }
} }
@ -251,58 +228,59 @@ async fn toggleperms(
mut db: Connection<Db>, mut db: Connection<Db>,
info: Json<TogglePerms>, info: Json<TogglePerms>,
cookies: &CookieJar<'_>, cookies: &CookieJar<'_>,
) -> status::Custom<String> { ) -> String {
match cookies.get_private("token") { match cookies.get_private("token") {
Some(t) => match User::get_by_token(&mut db, t).await { Some(t) => {
Some(user) => match user.admin { match User::get_by_token(&mut db, t).await {
true => match User::get_by_username(&mut db, &info.username).await { Some(user) => {
Some(toggled_user) => { match user.admin {
match toggled_user.username == user.username && info.perm == "admin" { true => {
true => status::Custom( match User::get_by_username(&mut db, &info.username).await {
Status::Forbidden, Some(toggled_user) => {
"You can't change your own admin status".to_string(), if toggled_user.username == user.username
), && info.perm == "admin".to_string()
false => { {
let admin_username = std::env::var("ADMIN_USERNAME") "You can't change your own admin status".to_string()
.expect("set ADMIN_USERNAME env var"); } else {
match toggled_user.username == admin_username { let admin_username = std::env::var("ADMIN_USERNAME")
true => status::Custom( .expect("set ADMIN_USERNAME env var");
Status::Forbidden, if toggled_user.username == admin_username {
"You can't change the system admin's perms.".to_string(), "You can't change the system admin's perms.".to_string()
), } else {
false => { if info.perm == "admin"
match info.perm == "admin" && user.username != admin_username
&& user.username != admin_username {
{
true => status::Custom(
Status::Forbidden,
"You can't change other people's admin status." "You can't change other people's admin status."
.to_string(), .to_string()
), } else {
false => { // how deep is this shit
match toggled_user.set_role(&mut db,&info.perm,&info.value).await { // i counted. 12.
Ok(_) => status::Custom(Status::Ok, "Done".to_string()), // NOW we can actually do the thing :D
Err(why) => status::Custom(Status::InternalServerError, format!( let res = match toggled_user
.set_role(&mut db, &info.perm, &info.value)
.await
{
Ok(_) => "Done".to_string(),
Err(why) => format!(
"Couldn't update the user's role: {why}" "Couldn't update the user's role: {why}"
)), ),
} };
res
} }
} }
} }
} }
None => "The user you're trying to toggle perms for doesn't exist."
.to_string(),
} }
} }
false => "You aren't an admin.".to_string(),
} }
None => status::Custom( }
Status::NotFound, None => "Invalid user".to_string(),
"The user you're trying to toggle perms for doesn't exist.".to_string(), }
), }
}, None => "Not logged in".to_string(),
false => status::Custom(Status::Unauthorized, "You aren't an admin.".to_string()),
},
None => status::Custom(Status::Unauthorized, "Invalid login token".to_string()),
},
None => status::Custom(Status::Unauthorized, "Not logged in".to_string()),
} }
} }

View File

@ -235,7 +235,7 @@ impl Image {
VALUES ($1, $2); VALUES ($1, $2);
"#, "#,
) )
.bind(uuid) .bind(&uuid)
.bind(user.username), .bind(user.username),
) )
.await .await
@ -263,7 +263,7 @@ impl Image {
} }
} }
pub async fn is_owned_by(db: &mut Connection<Db>, uuid: &String, username: &String) -> Result<bool, String> { pub async fn is_owned_by(db: &mut Connection<Db>, uuid: &String, username: &String) -> Result<bool, String> {
match Image::get_by_uuid(db, uuid).await { match Image::get_by_uuid(db, &uuid).await {
Ok(img) => { Ok(img) => {
Ok(&img.owner_name == username) Ok(&img.owner_name == username)
}, },