mirror of
https://github.com/ChronosX88/yat-server.git
synced 2024-11-12 18:21:00 +00:00
Initialize project, create initial migrations, implement user registration
This commit is contained in:
commit
26f5959dac
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
/target
|
||||
db/db.sqlite
|
8
.idea/.gitignore
vendored
Normal file
8
.idea/.gitignore
vendored
Normal file
@ -0,0 +1,8 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
||||
# Editor-based HTTP Client requests
|
||||
/httpRequests/
|
12
.idea/dataSources.xml
Normal file
12
.idea/dataSources.xml
Normal file
@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
|
||||
<data-source source="LOCAL" name="db.sqlite" uuid="0e4a79d2-dba8-4598-9783-6472b3a3e303">
|
||||
<driver-ref>sqlite.xerial</driver-ref>
|
||||
<synchronize>true</synchronize>
|
||||
<jdbc-driver>org.sqlite.JDBC</jdbc-driver>
|
||||
<jdbc-url>jdbc:sqlite:$PROJECT_DIR$/db/db.sqlite</jdbc-url>
|
||||
<working-dir>$ProjectFileDir$</working-dir>
|
||||
</data-source>
|
||||
</component>
|
||||
</project>
|
6
.idea/inspectionProfiles/Project_Default.xml
Normal file
6
.idea/inspectionProfiles/Project_Default.xml
Normal file
@ -0,0 +1,6 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<profile version="1.0">
|
||||
<option name="myName" value="Project Default" />
|
||||
<inspection_tool class="SqlNoDataSourceInspection" enabled="false" level="WARNING" enabled_by_default="false" />
|
||||
</profile>
|
||||
</component>
|
8
.idea/modules.xml
Normal file
8
.idea/modules.xml
Normal file
@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/yat-backend.iml" filepath="$PROJECT_DIR$/.idea/yat-backend.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
6
.idea/sqldialects.xml
Normal file
6
.idea/sqldialects.xml
Normal file
@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="SqlDialectMappings">
|
||||
<file url="PROJECT" dialect="SQLite" />
|
||||
</component>
|
||||
</project>
|
6
.idea/vcs.xml
Normal file
6
.idea/vcs.xml
Normal file
@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
11
.idea/yat-backend.iml
Normal file
11
.idea/yat-backend.iml
Normal file
@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="CPP_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/target" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
2084
Cargo.lock
generated
Normal file
2084
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
22
Cargo.toml
Normal file
22
Cargo.toml
Normal file
@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "yat-backend"
|
||||
version = "0.1.0"
|
||||
authors = ["ChronosX88 <chronosx88@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
actix-web = "3"
|
||||
env_logger = "0.7.1"
|
||||
diesel = { version = "1.4.4", features = ["sqlite", "chrono"] }
|
||||
diesel_migrations = "1.4.0"
|
||||
dotenv = "0.15.0"
|
||||
r2d2 = "0.8.9"
|
||||
r2d2-diesel = "1.0.0"
|
||||
chrono = { version = "0.4", features = ["serde"]}
|
||||
argon2 = "0.2"
|
||||
rand_core = { version = "0.6", features = ["std"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
custom_error = "1.9.2"
|
0
db/.gitkeep
Normal file
0
db/.gitkeep
Normal file
5
diesel.toml
Normal file
5
diesel.toml
Normal file
@ -0,0 +1,5 @@
|
||||
# For documentation on how to configure this file,
|
||||
# see diesel.rs/guides/configuring-diesel-cli
|
||||
|
||||
[print_schema]
|
||||
file = "src/schema.rs"
|
2
migrations/2021-10-07-113254_create_tasks/down.sql
Normal file
2
migrations/2021-10-07-113254_create_tasks/down.sql
Normal file
@ -0,0 +1,2 @@
|
||||
-- This file should undo anything in `up.sql`
|
||||
drop table tasks;
|
11
migrations/2021-10-07-113254_create_tasks/up.sql
Normal file
11
migrations/2021-10-07-113254_create_tasks/up.sql
Normal file
@ -0,0 +1,11 @@
|
||||
create table if not exists tasks (
|
||||
id integer primary key,
|
||||
name text not null,
|
||||
user_id integer not null,
|
||||
created_at timestamp not null,
|
||||
updated_at timestamp,
|
||||
description text,
|
||||
due_date timestamp,
|
||||
reminders text,
|
||||
foreign key (user_id) references users(id) on delete cascade
|
||||
);
|
2
migrations/2021-10-07-114229_create_lists/down.sql
Normal file
2
migrations/2021-10-07-114229_create_lists/down.sql
Normal file
@ -0,0 +1,2 @@
|
||||
-- This file should undo anything in `up.sql`
|
||||
drop table lists;
|
8
migrations/2021-10-07-114229_create_lists/up.sql
Normal file
8
migrations/2021-10-07-114229_create_lists/up.sql
Normal file
@ -0,0 +1,8 @@
|
||||
-- Your SQL goes here
|
||||
create table if not exists lists (
|
||||
id integer primary key,
|
||||
user_id integer not null,
|
||||
name text not null,
|
||||
description text,
|
||||
foreign key (user_id) references users(id) on delete cascade
|
||||
);
|
2
migrations/2021-10-07-114611_create_lists_tasks/down.sql
Normal file
2
migrations/2021-10-07-114611_create_lists_tasks/down.sql
Normal file
@ -0,0 +1,2 @@
|
||||
-- This file should undo anything in `up.sql`
|
||||
drop table lists_tasks;
|
8
migrations/2021-10-07-114611_create_lists_tasks/up.sql
Normal file
8
migrations/2021-10-07-114611_create_lists_tasks/up.sql
Normal file
@ -0,0 +1,8 @@
|
||||
-- Your SQL goes here
|
||||
create table if not exists lists_tasks (
|
||||
id integer primary key,
|
||||
list_id integer,
|
||||
task_id integer not null,
|
||||
foreign key (list_id) references lists(id) on delete set null,
|
||||
foreign key (task_id) references tasks(id) on delete cascade
|
||||
);
|
2
migrations/2021-10-07-123207_create_users/down.sql
Normal file
2
migrations/2021-10-07-123207_create_users/down.sql
Normal file
@ -0,0 +1,2 @@
|
||||
-- This file should undo anything in `up.sql`
|
||||
drop table users;
|
9
migrations/2021-10-07-123207_create_users/up.sql
Normal file
9
migrations/2021-10-07-123207_create_users/up.sql
Normal file
@ -0,0 +1,9 @@
|
||||
-- Your SQL goes here
|
||||
create table if not exists users (
|
||||
id integer primary key,
|
||||
created_at timestamp not null,
|
||||
updated_at timestamp,
|
||||
username text unique not null,
|
||||
email text unique not null,
|
||||
password text not null
|
||||
);
|
41
src/controller.rs
Normal file
41
src/controller.rs
Normal file
@ -0,0 +1,41 @@
|
||||
use actix_web::{HttpResponse, Responder};
|
||||
use actix_web::web::{Data, Json, ServiceConfig};
|
||||
use crate::db::DbPool;
|
||||
use crate::user::{User, UserCreationError};
|
||||
use serde::{Serialize, Deserialize};
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct NewUser {
|
||||
email: String,
|
||||
username: String,
|
||||
password: String
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct HttpError {
|
||||
err: String
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct HttpResult {
|
||||
text: String
|
||||
}
|
||||
|
||||
#[post("/register")]
|
||||
async fn register(user_form: Json<NewUser>, pool: Data<DbPool>) -> impl Responder {
|
||||
let conn = pool.get().unwrap();
|
||||
|
||||
match User::create(user_form.email.clone(), user_form.username.clone(), user_form.password.clone(), &conn) {
|
||||
Ok(_) => HttpResponse::Ok().json(HttpResult{text:"User has been created successfully!".to_string()}),
|
||||
Err(e) => match e {
|
||||
UserCreationError::DuplicatedUsername | UserCreationError::DuplicatedEmail => {
|
||||
HttpResponse::BadRequest().json(HttpError{err: e.to_string()})
|
||||
}
|
||||
_ => {HttpResponse::InternalServerError().json(HttpError{err: e.to_string()})}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_routes(cfg: &mut ServiceConfig) {
|
||||
cfg.service(register);
|
||||
}
|
26
src/db.rs
Normal file
26
src/db.rs
Normal file
@ -0,0 +1,26 @@
|
||||
use dotenv::dotenv;
|
||||
use std::env;
|
||||
use diesel::SqliteConnection;
|
||||
use r2d2::{Pool};
|
||||
use r2d2_diesel::ConnectionManager;
|
||||
|
||||
embed_migrations!();
|
||||
|
||||
pub type DbPool = Pool<ConnectionManager<SqliteConnection>>;
|
||||
|
||||
pub fn run_migrations(conn: &SqliteConnection) {
|
||||
let _ = diesel_migrations::run_pending_migrations(&*conn);
|
||||
}
|
||||
|
||||
no_arg_sql_function!(last_insert_rowid, diesel::sql_types::Integer);
|
||||
|
||||
pub fn establish_connection() -> DbPool {
|
||||
dotenv().ok();
|
||||
|
||||
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
|
||||
let manager = ConnectionManager::<SqliteConnection>::new(&database_url);
|
||||
|
||||
let pool = r2d2::Pool::builder().build(manager).expect("Failed to create DB pool.");
|
||||
run_migrations(&pool.get().unwrap());
|
||||
return pool;
|
||||
}
|
36
src/main.rs
Normal file
36
src/main.rs
Normal file
@ -0,0 +1,36 @@
|
||||
#[macro_use] extern crate actix_web;
|
||||
#[macro_use] extern crate diesel;
|
||||
#[macro_use] extern crate diesel_migrations;
|
||||
|
||||
mod schema;
|
||||
mod db;
|
||||
mod user;
|
||||
mod controller;
|
||||
|
||||
use std::env;
|
||||
use actix_web::{get, App, HttpResponse, HttpServer, Responder};
|
||||
use actix_web::middleware::Logger;
|
||||
use crate::db::establish_connection;
|
||||
|
||||
#[get("/")]
|
||||
async fn hello() -> impl Responder {
|
||||
HttpResponse::Ok().body("Hello world!")
|
||||
}
|
||||
|
||||
#[actix_web::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
env::set_var("RUST_LOG", "actix_web=debug,actix_server=info");
|
||||
env_logger::init();
|
||||
|
||||
let pool = establish_connection();
|
||||
|
||||
HttpServer::new(move || {
|
||||
App::new()
|
||||
.wrap(Logger::default())
|
||||
.data(pool.clone())
|
||||
.configure(controller::init_routes)
|
||||
})
|
||||
.bind("127.0.0.1:8080")?
|
||||
.run()
|
||||
.await
|
||||
}
|
52
src/schema.rs
Normal file
52
src/schema.rs
Normal file
@ -0,0 +1,52 @@
|
||||
table! {
|
||||
lists (id) {
|
||||
id -> Nullable<Integer>,
|
||||
user_id -> Integer,
|
||||
name -> Text,
|
||||
description -> Nullable<Text>,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
lists_tasks (id) {
|
||||
id -> Nullable<Integer>,
|
||||
list_id -> Nullable<Integer>,
|
||||
task_id -> Integer,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
tasks (id) {
|
||||
id -> Nullable<Integer>,
|
||||
name -> Text,
|
||||
user_id -> Integer,
|
||||
created_at -> Timestamp,
|
||||
updated_at -> Nullable<Timestamp>,
|
||||
description -> Nullable<Text>,
|
||||
due_date -> Nullable<Timestamp>,
|
||||
reminders -> Nullable<Text>,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
users (id) {
|
||||
id -> Nullable<Integer>,
|
||||
created_at -> Timestamp,
|
||||
updated_at -> Nullable<Timestamp>,
|
||||
username -> Text,
|
||||
email -> Text,
|
||||
password -> Text,
|
||||
}
|
||||
}
|
||||
|
||||
joinable!(lists -> users (user_id));
|
||||
joinable!(lists_tasks -> lists (list_id));
|
||||
joinable!(lists_tasks -> tasks (task_id));
|
||||
joinable!(tasks -> users (user_id));
|
||||
|
||||
allow_tables_to_appear_in_same_query!(
|
||||
lists,
|
||||
lists_tasks,
|
||||
tasks,
|
||||
users,
|
||||
);
|
91
src/user.rs
Normal file
91
src/user.rs
Normal file
@ -0,0 +1,91 @@
|
||||
use argon2::{
|
||||
password_hash::{
|
||||
rand_core::OsRng,
|
||||
PasswordHasher, SaltString
|
||||
},
|
||||
Argon2
|
||||
};
|
||||
use diesel::{RunQueryDsl, SqliteConnection};
|
||||
use crate::schema::users;
|
||||
use crate::schema::users::dsl::users as users_dsl;
|
||||
use serde::{Serialize, Deserialize};
|
||||
use diesel::prelude::*;
|
||||
use diesel::result::{DatabaseErrorKind, Error as DieselError};
|
||||
use crate::db::last_insert_rowid;
|
||||
use custom_error::custom_error;
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Insertable, Queryable)]
|
||||
#[table_name = "users"]
|
||||
pub struct User {
|
||||
pub id: Option<i32>,
|
||||
pub created_at: chrono::NaiveDateTime,
|
||||
pub updated_at: Option<chrono::NaiveDateTime>,
|
||||
pub username: String,
|
||||
pub email: String,
|
||||
pub password: String
|
||||
}
|
||||
|
||||
|
||||
custom_error!{ #[derive(Serialize)] pub UserCreationError
|
||||
DuplicatedEmail = "duplicated email",
|
||||
DuplicatedUsername = "duplicated username",
|
||||
EmptyData = "empty data",
|
||||
UnknownError{text: String} = "{text}"
|
||||
}
|
||||
|
||||
impl From<DieselError> for UserCreationError {
|
||||
fn from(err: DieselError) -> UserCreationError {
|
||||
if let DieselError::DatabaseError(DatabaseErrorKind::UniqueViolation, info) = &err {
|
||||
return match info.message() {
|
||||
"UNIQUE constraint failed: users.username" => UserCreationError::DuplicatedUsername,
|
||||
"UNIQUE constraint failed: users.email" => UserCreationError::DuplicatedEmail,
|
||||
_ => UserCreationError::UnknownError { text: err.to_string() }
|
||||
}
|
||||
}
|
||||
return UserCreationError::UnknownError{ text: err.to_string() }
|
||||
}
|
||||
}
|
||||
|
||||
impl User {
|
||||
pub fn by_id(id: i32, conn: &SqliteConnection) -> Option<Self> {
|
||||
users_dsl.find(id).get_result::<User>(conn).ok()
|
||||
}
|
||||
|
||||
pub fn create(email: String, username: String, password: String, conn: &SqliteConnection) -> Result<Self, UserCreationError> {
|
||||
if email.is_empty() || username.is_empty() || password.is_empty() {
|
||||
return Result::Err(UserCreationError::EmptyData.into())
|
||||
}
|
||||
|
||||
match Self::insert_user(email, username, password, conn) {
|
||||
Err(e) => return Err(e.into()),
|
||||
_ => {}
|
||||
}
|
||||
|
||||
let r = diesel::select(last_insert_rowid).first(conn).unwrap();
|
||||
Result::Ok(Self::by_id(r, conn).unwrap())
|
||||
}
|
||||
|
||||
fn insert_user(email: String, username: String, password: String, conn: &SqliteConnection) -> Result<usize, UserCreationError> {
|
||||
let salt = SaltString::generate(&mut OsRng);
|
||||
let argon2 = Argon2::default();
|
||||
let password_hash = argon2.hash_password_simple(password.as_bytes(), &salt).unwrap();
|
||||
|
||||
let new_user = Self::new_user_struct(email, username, password_hash.to_string());
|
||||
|
||||
diesel::insert_into(users_dsl)
|
||||
.values(&new_user)
|
||||
.execute(conn)
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
fn new_user_struct(email: String, username: String, password: String) -> Self {
|
||||
User {
|
||||
id: None,
|
||||
email,
|
||||
username,
|
||||
password,
|
||||
created_at: chrono::Local::now().naive_local(),
|
||||
updated_at: Option::from(chrono::Local::now().naive_local())
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user