Skip to content

Commit

Permalink
Merge pull request #4 from dhruvdabhi101/develop
Browse files Browse the repository at this point in the history
feat: added new route
  • Loading branch information
dhruvdabhi101 authored Jan 25, 2024
2 parents 68364b0 + 47a8ed8 commit 84998a5
Show file tree
Hide file tree
Showing 6 changed files with 56 additions and 42 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,6 @@ To run this project you need to install
- `GET /user/<username>`
- `POST /user` - to create new user ( registering )
- `POST /login` - to login into the account ( gets JWT Token back as response )
- `POST pages/create-page` - to create page, it will require JWT Token
- `GET pages/get-page/<username>/<slug>` - to get the page

16 changes: 11 additions & 5 deletions src/api/page_api.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
use mongodb::bson::extjson::de::Error;
use mongodb::results::InsertOneResult;
use rocket::{get, http::Status, post, serde::json::Json, State};
use rocket_authorization::oauth::OAuth;
use rocket_authorization::{AuthError, Credential};
use rocket_authorization::Credential;

use crate::config::jwt::decode_jwt;
use crate::{
models::{user_model::{LoginResponse, LoginUser, User, UserFromMongo}, page_model::{PageCreateRequest, PageCreateResponse, Page}},
models::page_model::{PageCreateRequest, PageCreateResponse, Page},
repository::mongodb_repo::MongoRepo,
};

Expand All @@ -27,3 +24,12 @@ pub fn create_page(auth: Credential<OAuth>, db: &State<MongoRepo>, new_page: Jso
Ok(Json(page))
}

#[get("/get-page/<username>/<slug>")]
pub fn get_page(db: &State<MongoRepo>, slug: &str, username: &str) -> Result<Json<Page>, Status> {
let page: Page = db.get_page(slug, username).unwrap();
if page.published == true {
Ok(Json(page))
} else {
Err(Status::Unauthorized)
}
}
32 changes: 0 additions & 32 deletions src/config/auth.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,3 @@
use rocket::{
outcome::Outcome,
http::Status,
request::{self, FromRequest, Request},
};

use super::jwt::decode_jwt;

pub const SECRET: &str = "secrets";

#[derive(Debug, serde::Serialize, serde::Deserialize)]
Expand All @@ -21,27 +13,3 @@ pub fn hash_password(password: String) -> String {
pub fn verify_password(password: &str, hash: &str) -> bool {
bcrypt::verify(password, hash).unwrap()
}

// pub struct Token(pub String);
//
// #[derive(Debug)]
// enum ApiTokenError {
// Missing,
// Invalid,
// }
//
// #[shuttle_runtime::async_trait]
// impl<'a, 'r> FromRequest<'a> for Token {
// type Error = ApiTokenError;
//
// fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
// let token = request.headers().get_one("Authorization");
// match token {
// Some(token) => {
// let token_str = decode_jwt(token).unwrap();
// Outcome::Success(Token(token_str.sub))
// }
// None => Outcome::Error((Status::Unauthorized, ApiTokenError::Missing)),
// }
// }
// }
4 changes: 2 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ pub mod api;
pub mod config;
pub mod models;
pub mod repository;
use api::{user_api::{create_user, get_user, login}, page_api::create_page};
use api::{user_api::{create_user, get_user, login}, page_api::{create_page, get_page}};
use repository::mongodb_repo::MongoRepo;
use rocket::{get, http::Status, routes, serde::json::Json, Rocket};

Expand All @@ -17,6 +17,6 @@ async fn main() -> shuttle_rocket::ShuttleRocket {
let rocket: Rocket<rocket::Build> = rocket::build()
.manage(db)
.mount("/", routes![index, create_user, get_user, login])
.mount("/pages", routes![create_page]);
.mount("/pages", routes![create_page, get_page]);
Ok(rocket.into())
}
7 changes: 7 additions & 0 deletions src/models/page_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,10 @@ pub struct PageCreateResponse {
pub published: bool,
pub user_id: ObjectId
}

pub struct PageGetResponse {
pub title: String,
pub content: String,
pub slug: String,
pub published: bool,
}
37 changes: 34 additions & 3 deletions src/repository/mongodb_repo.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::config::auth::{hash_password, verify_password};
use darkdown::converter::converter::Converter;
use crate::config::jwt::decode_jwt;
use crate::models::page_model::{Page, PageCreateRequest, PageCreateResponse};
use crate::models::user_model::{User, UserFromMongo};
Expand All @@ -12,7 +13,7 @@ use mongodb::{
use std::env;
use std::str::FromStr;

use super::error::UserError;
use super::error::{UserError, PageError};

pub struct MongoRepo {
col: Collection<UserFromMongo>,
Expand Down Expand Up @@ -92,10 +93,16 @@ impl MongoRepo {

let user_id = ObjectId::from_str(user_id.as_str()).unwrap();
// create page

// convert content from darkdown to html

let darkdown_content = new_page.content.clone();
let html_content:String = Converter::new().convert_to_html(darkdown_content.as_str());

let page = Page {
_id: ObjectId::new(),
title: new_page.title.clone(),
content: new_page.content.clone(),
content: html_content.clone(),
published: new_page.published.clone(),
slug: new_page.slug.clone(),
user_id: user_id.clone()
Expand All @@ -108,11 +115,35 @@ impl MongoRepo {

let page_response = PageCreateResponse {
title: new_page.title,
content: new_page.content,
content: html_content.clone(),
published: new_page.published,
slug: new_page.slug,
user_id,
};
Ok(page_response)
}

pub fn get_page(&self, slug: &str, username: &str) -> Result<Page, PageError> {
let filer = doc! { "username": username };
let user = self
.col
.find_one(filer, None)
.ok()
.expect("Error Finding User");

if user.is_some() {
let user: UserFromMongo = user.unwrap();
let user_id = user._id;
let filter = doc! {"slug": slug, "user_id": user_id};
let page = self
.page
.find_one(filter, None)
.ok()
.expect("Error Finding Page");
return Ok(page.unwrap());
} else {
return Err(PageError::NotFound);
}
}

}

0 comments on commit 84998a5

Please sign in to comment.