Compare commits

...

6 Commits

Author SHA1 Message Date
SadlyNotSappho 2cd4cf784e update POST /upload error messages, fix a few other things 2024-03-19 13:46:43 -07:00
SadlyNotSappho ab7b102045 update GET /perms/<username> error messages 2024-03-19 13:23:38 -07:00
SadlyNotSappho c5934c6fb8 update GET /adminpanel error messages 2024-03-19 13:19:24 -07:00
SadlyNotSappho 68e18b89a1 update POST /logout error messages 2024-03-19 13:17:06 -07:00
SadlyNotSappho 2c128a1e1f update GET /account error messages 2024-03-19 13:15:15 -07:00
SadlyNotSappho 6e69be35b8 update POST /createuser error messages 2024-03-19 13:13:58 -07:00
2 changed files with 121 additions and 99 deletions

View File

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