Add onboarding and FromRequest for User.
This commit is contained in:
52
src/routes/onboard/complete.rs
Normal file
52
src/routes/onboard/complete.rs
Normal file
@@ -0,0 +1,52 @@
|
||||
use mongodb::options::{Collation, FindOneOptions};
|
||||
use crate::util::result::{Error, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use crate::database::entities::User;
|
||||
use crate::database::get_collection;
|
||||
use rocket_contrib::json::Json;
|
||||
use rauth::auth::Session;
|
||||
use validator::Validate;
|
||||
use mongodb::bson::doc;
|
||||
|
||||
#[derive(Validate, Serialize, Deserialize)]
|
||||
pub struct Data {
|
||||
#[validate(length(min = 2, max = 32))]
|
||||
username: String
|
||||
}
|
||||
|
||||
#[post("/complete", data = "<data>")]
|
||||
pub async fn req(session: Session, user: Option<User>, data: Json<Data>) -> Result<()> {
|
||||
if user.is_some() {
|
||||
Err(Error::AlreadyOnboarded)?
|
||||
}
|
||||
|
||||
data.validate()
|
||||
.map_err(|error| Error::FailedValidation { error })?;
|
||||
|
||||
let col = get_collection("users");
|
||||
if col.find_one(
|
||||
doc! {
|
||||
"username": &data.username
|
||||
},
|
||||
FindOneOptions::builder()
|
||||
.collation(Collation::builder().locale("en").strength(2).build())
|
||||
.build()
|
||||
)
|
||||
.await
|
||||
.map_err(|_| Error::DatabaseError { operation: "find_one", with: "user" })?
|
||||
.is_some() {
|
||||
Err(Error::UsernameTaken)?
|
||||
}
|
||||
|
||||
col.insert_one(
|
||||
doc! {
|
||||
"_id": session.user_id,
|
||||
"username": &data.username
|
||||
},
|
||||
None
|
||||
)
|
||||
.await
|
||||
.map_err(|_| Error::DatabaseError { operation: "insert_one", with: "user" })?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
use crate::util::result::Result;
|
||||
use rocket_contrib::json::JsonValue;
|
||||
use crate::database::entities::User;
|
||||
use rauth::auth::Session;
|
||||
|
||||
#[get("/hello")]
|
||||
pub async fn req(session: Session) -> Result<String> {
|
||||
Ok("try onboard user".to_string())
|
||||
pub async fn req(_session: Session, user: Option<User>) -> JsonValue {
|
||||
json!({
|
||||
"onboarding": user.is_none()
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
use rocket::Route;
|
||||
|
||||
mod hello;
|
||||
mod complete;
|
||||
|
||||
pub fn routes() -> Vec<Route> {
|
||||
routes! [
|
||||
hello::req
|
||||
hello::req,
|
||||
complete::req
|
||||
]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user