Add onboarding and FromRequest for User.
This commit is contained in:
@@ -1,4 +1,9 @@
|
|||||||
pub mod channel;
|
mod channel;
|
||||||
pub mod message;
|
mod message;
|
||||||
pub mod guild;
|
mod guild;
|
||||||
pub mod user;
|
mod user;
|
||||||
|
|
||||||
|
pub use channel::*;
|
||||||
|
pub use message::*;
|
||||||
|
pub use guild::*;
|
||||||
|
pub use user::*;
|
||||||
|
|||||||
@@ -1,4 +1,9 @@
|
|||||||
|
use mongodb::bson::{doc, from_bson, Bson};
|
||||||
|
use rauth::auth::Session;
|
||||||
|
use rocket::http::Status;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use crate::database::get_collection;
|
||||||
|
use rocket::request::{self, FromRequest, Outcome, Request};
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
pub struct Relationship {
|
pub struct Relationship {
|
||||||
@@ -10,6 +15,63 @@ pub struct Relationship {
|
|||||||
pub struct User {
|
pub struct User {
|
||||||
#[serde(rename = "_id")]
|
#[serde(rename = "_id")]
|
||||||
pub id: String,
|
pub id: String,
|
||||||
pub username: Option<String>,
|
pub username: String,
|
||||||
pub relations: Option<Vec<Relationship>>,
|
pub relations: Option<Vec<Relationship>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[rocket::async_trait]
|
||||||
|
impl<'a, 'r> FromRequest<'a, 'r> for User {
|
||||||
|
type Error = rauth::util::Error;
|
||||||
|
|
||||||
|
async fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
|
||||||
|
let session: Session = try_outcome!(request.guard::<Session>().await);
|
||||||
|
|
||||||
|
if let Ok(result) = get_collection("users")
|
||||||
|
.find_one(
|
||||||
|
doc! {
|
||||||
|
"_id": &session.user_id
|
||||||
|
}, None
|
||||||
|
)
|
||||||
|
.await {
|
||||||
|
if let Some(doc) = result {
|
||||||
|
Outcome::Success(
|
||||||
|
from_bson(Bson::Document(doc)).unwrap()
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
Outcome::Failure((Status::Forbidden, rauth::util::Error::InvalidSession))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Outcome::Failure((Status::InternalServerError, rauth::util::Error::DatabaseError))
|
||||||
|
}
|
||||||
|
|
||||||
|
/*Outcome::Success(
|
||||||
|
User {
|
||||||
|
id: "gaming".to_string(),
|
||||||
|
username: None,
|
||||||
|
relations: None
|
||||||
|
}
|
||||||
|
)*/
|
||||||
|
|
||||||
|
/*match (
|
||||||
|
request.managed_state::<Auth>(),
|
||||||
|
header_user_id,
|
||||||
|
header_session_token,
|
||||||
|
) {
|
||||||
|
(Some(auth), Some(user_id), Some(session_token)) => {
|
||||||
|
let session = Session {
|
||||||
|
id: None,
|
||||||
|
user_id,
|
||||||
|
session_token,
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Ok(session) = auth.verify_session(session).await {
|
||||||
|
Outcome::Success(session)
|
||||||
|
} else {
|
||||||
|
Outcome::Failure((Status::Forbidden, Error::InvalidSession))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(None, _, _) => Outcome::Failure((Status::InternalServerError, Error::InternalError)),
|
||||||
|
(_, _, _) => Outcome::Failure((Status::Forbidden, Error::MissingHeaders)),
|
||||||
|
}*/
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
/**
|
pub mod user;
|
||||||
|
pub mod reference;
|
||||||
|
|
||||||
|
/*
|
||||||
// ! FIXME
|
// ! FIXME
|
||||||
impl<'r> FromParam<'r> for User {
|
impl<'r> FromParam<'r> for User {
|
||||||
type Error = &'r RawStr;
|
type Error = &'r RawStr;
|
||||||
|
|||||||
0
src/database/guards/reference.rs
Normal file
0
src/database/guards/reference.rs
Normal file
0
src/database/guards/user.rs
Normal file
0
src/database/guards/user.rs
Normal file
@@ -43,6 +43,28 @@ pub async fn create_database() {
|
|||||||
.await
|
.await
|
||||||
.expect("Failed to create pubsub collection.");
|
.expect("Failed to create pubsub collection.");
|
||||||
|
|
||||||
|
db.run_command(
|
||||||
|
doc! {
|
||||||
|
"createIndexes": "users",
|
||||||
|
"indexes": [
|
||||||
|
{
|
||||||
|
"key": {
|
||||||
|
"username": 1
|
||||||
|
},
|
||||||
|
"name": "username",
|
||||||
|
"unique": true,
|
||||||
|
"collation": {
|
||||||
|
"locale": "en",
|
||||||
|
"strength": 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
None
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("Failed to create username index.");
|
||||||
|
|
||||||
db.collection("migrations")
|
db.collection("migrations")
|
||||||
.insert_one(
|
.insert_one(
|
||||||
doc! {
|
doc! {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use super::super::get_collection;
|
use super::super::{get_db, get_collection};
|
||||||
|
|
||||||
use log::info;
|
use log::info;
|
||||||
use mongodb::options::FindOptions;
|
use mongodb::options::FindOptions;
|
||||||
@@ -12,7 +12,7 @@ struct MigrationInfo {
|
|||||||
revision: i32,
|
revision: i32,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub const LATEST_REVISION: i32 = 2;
|
pub const LATEST_REVISION: i32 = 3;
|
||||||
|
|
||||||
pub async fn migrate_database() {
|
pub async fn migrate_database() {
|
||||||
let migrations = get_collection("migrations");
|
let migrations = get_collection("migrations");
|
||||||
@@ -121,6 +121,32 @@ pub async fn run_migrations(revision: i32) -> i32 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if revision <= 2 {
|
||||||
|
info!("Running migration [revision 2]: Add username index to users.");
|
||||||
|
|
||||||
|
get_db().run_command(
|
||||||
|
doc! {
|
||||||
|
"createIndexes": "users",
|
||||||
|
"indexes": [
|
||||||
|
{
|
||||||
|
"key": {
|
||||||
|
"username": 1
|
||||||
|
},
|
||||||
|
"name": "username",
|
||||||
|
"unique": true,
|
||||||
|
"collation": {
|
||||||
|
"locale": "en",
|
||||||
|
"strength": 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
None
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("Failed to create username index.");
|
||||||
|
}
|
||||||
|
|
||||||
// Reminder to update LATEST_REVISION when adding new migrations.
|
// Reminder to update LATEST_REVISION when adding new migrations.
|
||||||
LATEST_REVISION
|
LATEST_REVISION
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,3 +28,4 @@ pub fn get_collection(collection: &str) -> Collection {
|
|||||||
|
|
||||||
pub mod migrations;
|
pub mod migrations;
|
||||||
pub mod entities;
|
pub mod entities;
|
||||||
|
pub mod guards;
|
||||||
|
|||||||
@@ -15,56 +15,4 @@ pub fn mount(rocket: Rocket) -> Rocket {
|
|||||||
.mount("/users", users::routes())
|
.mount("/users", users::routes())
|
||||||
.mount("/channels", channels::routes())
|
.mount("/channels", channels::routes())
|
||||||
.mount("/guild", guild::routes())
|
.mount("/guild", guild::routes())
|
||||||
|
|
||||||
/*.mount(
|
|
||||||
"/users",
|
|
||||||
routes![
|
|
||||||
user::me,
|
|
||||||
user::user,
|
|
||||||
user::query,
|
|
||||||
user::dms,
|
|
||||||
user::dm,
|
|
||||||
user::get_friends,
|
|
||||||
user::get_friend,
|
|
||||||
user::add_friend,
|
|
||||||
user::remove_friend,
|
|
||||||
user::block_user,
|
|
||||||
user::unblock_user,
|
|
||||||
],
|
|
||||||
)
|
|
||||||
.mount(
|
|
||||||
"/channels",
|
|
||||||
routes![
|
|
||||||
channel::create_group,
|
|
||||||
channel::channel,
|
|
||||||
channel::add_member,
|
|
||||||
channel::remove_member,
|
|
||||||
channel::delete,
|
|
||||||
channel::messages,
|
|
||||||
channel::get_message,
|
|
||||||
channel::send_message,
|
|
||||||
channel::edit_message,
|
|
||||||
channel::delete_message,
|
|
||||||
],
|
|
||||||
)
|
|
||||||
.mount(
|
|
||||||
"/guild",
|
|
||||||
routes![
|
|
||||||
guild::my_guilds,
|
|
||||||
guild::guild,
|
|
||||||
guild::remove_guild,
|
|
||||||
guild::create_channel,
|
|
||||||
guild::create_invite,
|
|
||||||
guild::remove_invite,
|
|
||||||
guild::fetch_invites,
|
|
||||||
guild::fetch_invite,
|
|
||||||
guild::use_invite,
|
|
||||||
guild::create_guild,
|
|
||||||
guild::fetch_members,
|
|
||||||
guild::fetch_member,
|
|
||||||
guild::kick_member,
|
|
||||||
guild::ban_member,
|
|
||||||
guild::unban_member,
|
|
||||||
],
|
|
||||||
)*/
|
|
||||||
}
|
}
|
||||||
|
|||||||
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;
|
use rauth::auth::Session;
|
||||||
|
|
||||||
#[get("/hello")]
|
#[get("/hello")]
|
||||||
pub async fn req(session: Session) -> Result<String> {
|
pub async fn req(_session: Session, user: Option<User>) -> JsonValue {
|
||||||
Ok("try onboard user".to_string())
|
json!({
|
||||||
|
"onboarding": user.is_none()
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
use rocket::Route;
|
use rocket::Route;
|
||||||
|
|
||||||
mod hello;
|
mod hello;
|
||||||
|
mod complete;
|
||||||
|
|
||||||
pub fn routes() -> Vec<Route> {
|
pub fn routes() -> Vec<Route> {
|
||||||
routes! [
|
routes! [
|
||||||
hello::req
|
hello::req,
|
||||||
|
complete::req
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
use rocket::response::{self, Responder, Response};
|
use rocket::response::{self, Responder, Response};
|
||||||
use rocket::http::{ContentType, Status};
|
use rocket::http::{ContentType, Status};
|
||||||
|
use validator::ValidationErrors;
|
||||||
use rocket::request::Request;
|
use rocket::request::Request;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use std::io::Cursor;
|
use std::io::Cursor;
|
||||||
@@ -12,6 +13,25 @@ pub enum Error {
|
|||||||
#[snafu(display("This error has not been labelled."))]
|
#[snafu(display("This error has not been labelled."))]
|
||||||
#[serde(rename = "unlabelled_error")]
|
#[serde(rename = "unlabelled_error")]
|
||||||
LabelMe,
|
LabelMe,
|
||||||
|
|
||||||
|
// ? Onboarding related errors.
|
||||||
|
#[snafu(display("Already finished onboarding."))]
|
||||||
|
#[serde(rename = "already_onboarded")]
|
||||||
|
AlreadyOnboarded,
|
||||||
|
|
||||||
|
// ? User related errors.
|
||||||
|
#[snafu(display("Username has already been taken."))]
|
||||||
|
#[serde(rename = "username_taken")]
|
||||||
|
UsernameTaken,
|
||||||
|
|
||||||
|
// ? General errors.
|
||||||
|
#[snafu(display("Failed to validate fields."))]
|
||||||
|
#[serde(rename = "failed_validation")]
|
||||||
|
FailedValidation { error: ValidationErrors },
|
||||||
|
#[snafu(display("Encountered a database error."))]
|
||||||
|
#[serde(rename = "database_error")]
|
||||||
|
DatabaseError { operation: &'static str, with: &'static str },
|
||||||
|
|
||||||
/* #[snafu(display("Failed to validate fields."))]
|
/* #[snafu(display("Failed to validate fields."))]
|
||||||
#[serde(rename = "failed_validation")]
|
#[serde(rename = "failed_validation")]
|
||||||
FailedValidation { error: ValidationErrors },
|
FailedValidation { error: ValidationErrors },
|
||||||
@@ -50,7 +70,11 @@ pub type Result<T, E = Error> = std::result::Result<T, E>;
|
|||||||
impl<'r> Responder<'r, 'static> for Error {
|
impl<'r> Responder<'r, 'static> for Error {
|
||||||
fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static> {
|
fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static> {
|
||||||
let status = match self {
|
let status = match self {
|
||||||
Error::LabelMe => Status::InternalServerError
|
Error::AlreadyOnboarded => Status::Forbidden,
|
||||||
|
Error::DatabaseError { .. } => Status::InternalServerError,
|
||||||
|
Error::FailedValidation { .. } => Status::UnprocessableEntity,
|
||||||
|
Error::LabelMe => Status::InternalServerError,
|
||||||
|
Error::UsernameTaken => Status::Conflict,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Serialize the error data structure into JSON.
|
// Serialize the error data structure into JSON.
|
||||||
|
|||||||
Reference in New Issue
Block a user