Compare commits
7 commits
e6bed3dc65
...
6ff16702f6
Author | SHA1 | Date | |
---|---|---|---|
6ff16702f6 | |||
1057907f6f | |||
2151957760 | |||
c1b1fcb9a5 | |||
f74fbde379 | |||
d17713eff9 | |||
dee7b5c1d7 |
15 changed files with 2581 additions and 71 deletions
1
.env
Normal file
1
.env
Normal file
|
@ -0,0 +1 @@
|
||||||
|
DATABASE_URL=postgres://alisa:alisa@localhost/alisa
|
2328
Cargo.lock
generated
2328
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
|
@ -1,3 +1,3 @@
|
||||||
[workspace]
|
[workspace]
|
||||||
resolver = "2"
|
resolver = "2"
|
||||||
members = ["crates/backend"]
|
members = ["crates/backend", "crates/migration", "crates/entity"]
|
||||||
|
|
|
@ -4,5 +4,16 @@ version = "0.1.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
argon2 = { version = "0.5" }
|
||||||
actix-web = "4"
|
actix-web = "4"
|
||||||
actix-cors = "0.7"
|
actix-cors = "0.7"
|
||||||
|
entity = { path = "../entity" }
|
||||||
|
migration = { path = "../migration" }
|
||||||
|
uuid = { version = "*", features = ["v4"] }
|
||||||
|
serde = { version = "*", features = ["derive"] }
|
||||||
|
sea-orm = { version = "0.12", features = [
|
||||||
|
"sqlx-postgres",
|
||||||
|
"runtime-tokio-rustls",
|
||||||
|
"with-uuid",
|
||||||
|
] }
|
||||||
|
dotenvy = "*"
|
||||||
|
|
3
crates/backend/src/controller.rs
Normal file
3
crates/backend/src/controller.rs
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
mod user;
|
||||||
|
|
||||||
|
pub use user::UserController;
|
79
crates/backend/src/controller/user.rs
Normal file
79
crates/backend/src/controller/user.rs
Normal file
|
@ -0,0 +1,79 @@
|
||||||
|
use actix_web::{error::ErrorInternalServerError, web, Responder};
|
||||||
|
use argon2::{
|
||||||
|
password_hash::{rand_core::OsRng, PasswordHasher, SaltString},
|
||||||
|
Argon2,
|
||||||
|
};
|
||||||
|
use sea_orm::{ActiveModelTrait, ActiveValue, DatabaseConnection, EntityTrait};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use crate::AppState;
|
||||||
|
|
||||||
|
pub struct UserController;
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct UserWithoutPassword {
|
||||||
|
id: Uuid,
|
||||||
|
name: String,
|
||||||
|
email: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct CreateUserDto {
|
||||||
|
name: String,
|
||||||
|
email: String,
|
||||||
|
password: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<entity::user::Model> for UserWithoutPassword {
|
||||||
|
fn from(value: entity::user::Model) -> Self {
|
||||||
|
Self {
|
||||||
|
id: value.id,
|
||||||
|
name: value.name,
|
||||||
|
email: value.email,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UserController {
|
||||||
|
pub async fn list_users(state: web::Data<AppState>) -> actix_web::Result<impl Responder> {
|
||||||
|
let db = &state.db;
|
||||||
|
let users = entity::prelude::User::find()
|
||||||
|
.all(db)
|
||||||
|
.await
|
||||||
|
.map_err(ErrorInternalServerError)?;
|
||||||
|
Ok(web::Json(
|
||||||
|
users
|
||||||
|
.into_iter()
|
||||||
|
.map(UserWithoutPassword::from)
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create_user(
|
||||||
|
state: web::Data<AppState>,
|
||||||
|
user: web::Json<CreateUserDto>,
|
||||||
|
) -> actix_web::Result<impl Responder> {
|
||||||
|
let db = &state.db;
|
||||||
|
let user = user.into_inner();
|
||||||
|
|
||||||
|
let salt = SaltString::generate(&mut OsRng);
|
||||||
|
let argon2 = Argon2::default();
|
||||||
|
|
||||||
|
let password_hash = argon2
|
||||||
|
.hash_password(user.password.as_bytes(), &salt)
|
||||||
|
.map_err(ErrorInternalServerError)?;
|
||||||
|
|
||||||
|
let user = entity::user::ActiveModel {
|
||||||
|
id: ActiveValue::NotSet,
|
||||||
|
name: ActiveValue::Set(user.name),
|
||||||
|
email: ActiveValue::Set(user.email),
|
||||||
|
hash: ActiveValue::Set(password_hash.to_string()),
|
||||||
|
salt: ActiveValue::Set(salt.to_string()),
|
||||||
|
};
|
||||||
|
|
||||||
|
let result = user.insert(db).await.map_err(ErrorInternalServerError)?;
|
||||||
|
|
||||||
|
Ok(web::Json(UserWithoutPassword::from(result)))
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,17 +1,41 @@
|
||||||
use actix_web::{web, App, HttpResponse, HttpServer, Responder};
|
use actix_web::{web, App, HttpResponse, HttpServer, Responder};
|
||||||
|
use sea_orm::{Database, DatabaseConnection};
|
||||||
|
use std::env;
|
||||||
|
|
||||||
|
use routes::config;
|
||||||
|
mod controller;
|
||||||
|
mod routes;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct AppState {
|
||||||
|
db: DatabaseConnection,
|
||||||
|
}
|
||||||
|
|
||||||
#[actix_web::main]
|
#[actix_web::main]
|
||||||
async fn main() -> std::io::Result<()> {
|
async fn main() -> std::io::Result<()> {
|
||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
println!("Running debug build -> enabling permissive CORS");
|
println!("Running debug build -> enabling permissive CORS");
|
||||||
|
|
||||||
|
dotenvy::dotenv().ok();
|
||||||
|
|
||||||
|
let db_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
|
||||||
|
|
||||||
|
let conn = Database::connect(&db_url)
|
||||||
|
.await
|
||||||
|
.expect("Connecting to Database failed");
|
||||||
|
|
||||||
|
let state = AppState { db: conn };
|
||||||
|
|
||||||
HttpServer::new(move || {
|
HttpServer::new(move || {
|
||||||
let cors = if cfg!(debug_assertions) {
|
let cors = if cfg!(debug_assertions) {
|
||||||
actix_cors::Cors::permissive()
|
actix_cors::Cors::permissive()
|
||||||
} else {
|
} else {
|
||||||
actix_cors::Cors::default()
|
actix_cors::Cors::default()
|
||||||
};
|
};
|
||||||
App::new().wrap(cors).route("/", web::get().to(index))
|
App::new()
|
||||||
|
.wrap(cors)
|
||||||
|
.app_data(web::Data::new(state.clone()))
|
||||||
|
.configure(config)
|
||||||
})
|
})
|
||||||
.bind(("127.0.0.1", 8080))?
|
.bind(("127.0.0.1", 8080))?
|
||||||
.run()
|
.run()
|
||||||
|
|
14
crates/backend/src/routes.rs
Normal file
14
crates/backend/src/routes.rs
Normal file
|
@ -0,0 +1,14 @@
|
||||||
|
use crate::controller::UserController;
|
||||||
|
use actix_web::web;
|
||||||
|
|
||||||
|
pub fn config(cfg: &mut web::ServiceConfig) {
|
||||||
|
cfg.service(
|
||||||
|
web::scope("/api/v1")
|
||||||
|
.service(
|
||||||
|
web::resource("/users")
|
||||||
|
.get(UserController::list_users)
|
||||||
|
.post(UserController::create_user),
|
||||||
|
)
|
||||||
|
.service(web::resource("/users/{user_id}")),
|
||||||
|
);
|
||||||
|
}
|
|
@ -0,0 +1,5 @@
|
||||||
|
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.15
|
||||||
|
|
||||||
|
pub mod prelude;
|
||||||
|
|
||||||
|
pub mod user;
|
3
crates/entity/src/prelude.rs
Normal file
3
crates/entity/src/prelude.rs
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.15
|
||||||
|
|
||||||
|
pub use super::user::Entity as User;
|
66
crates/entity/src/user.rs
Normal file
66
crates/entity/src/user.rs
Normal file
|
@ -0,0 +1,66 @@
|
||||||
|
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.15
|
||||||
|
|
||||||
|
use sea_orm::entity::prelude::*;
|
||||||
|
|
||||||
|
#[derive(Copy, Clone, Default, Debug, DeriveEntity)]
|
||||||
|
pub struct Entity;
|
||||||
|
|
||||||
|
impl EntityName for Entity {
|
||||||
|
fn table_name(&self) -> &str {
|
||||||
|
"user"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, DeriveModel, DeriveActiveModel, Eq)]
|
||||||
|
pub struct Model {
|
||||||
|
pub id: Uuid,
|
||||||
|
pub name: String,
|
||||||
|
pub email: String,
|
||||||
|
pub hash: String,
|
||||||
|
pub salt: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
|
||||||
|
pub enum Column {
|
||||||
|
Id,
|
||||||
|
Name,
|
||||||
|
Email,
|
||||||
|
Hash,
|
||||||
|
Salt,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Copy, Clone, Debug, EnumIter, DerivePrimaryKey)]
|
||||||
|
pub enum PrimaryKey {
|
||||||
|
Id,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PrimaryKeyTrait for PrimaryKey {
|
||||||
|
type ValueType = Uuid;
|
||||||
|
fn auto_increment() -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Copy, Clone, Debug, EnumIter)]
|
||||||
|
pub enum Relation {}
|
||||||
|
|
||||||
|
impl ColumnTrait for Column {
|
||||||
|
type EntityName = Entity;
|
||||||
|
fn def(&self) -> ColumnDef {
|
||||||
|
match self {
|
||||||
|
Self::Id => ColumnType::Uuid.def(),
|
||||||
|
Self::Name => ColumnType::String(None).def(),
|
||||||
|
Self::Email => ColumnType::String(None).def().unique(),
|
||||||
|
Self::Hash => ColumnType::String(None).def(),
|
||||||
|
Self::Salt => ColumnType::String(None).def(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RelationTrait for Relation {
|
||||||
|
fn def(&self) -> RelationDef {
|
||||||
|
panic!("No RelationDef")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ActiveModelBehavior for ActiveModel {}
|
|
@ -1,12 +1,12 @@
|
||||||
pub use sea_orm_migration::prelude::*;
|
pub use sea_orm_migration::prelude::*;
|
||||||
|
|
||||||
mod m20220101_000001_create_table;
|
|
||||||
|
|
||||||
pub struct Migrator;
|
pub struct Migrator;
|
||||||
|
|
||||||
|
mod m20240705_100914_create_user;
|
||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl MigratorTrait for Migrator {
|
impl MigratorTrait for Migrator {
|
||||||
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
|
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
|
||||||
vec![Box::new(m20220101_000001_create_table::Migration)]
|
vec![Box::new(m20240705_100914_create_user::Migration)]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,47 +0,0 @@
|
||||||
use sea_orm_migration::prelude::*;
|
|
||||||
|
|
||||||
#[derive(DeriveMigrationName)]
|
|
||||||
pub struct Migration;
|
|
||||||
|
|
||||||
#[async_trait::async_trait]
|
|
||||||
impl MigrationTrait for Migration {
|
|
||||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
|
||||||
// Replace the sample below with your own migration scripts
|
|
||||||
todo!();
|
|
||||||
|
|
||||||
manager
|
|
||||||
.create_table(
|
|
||||||
Table::create()
|
|
||||||
.table(Post::Table)
|
|
||||||
.if_not_exists()
|
|
||||||
.col(
|
|
||||||
ColumnDef::new(Post::Id)
|
|
||||||
.integer()
|
|
||||||
.not_null()
|
|
||||||
.auto_increment()
|
|
||||||
.primary_key(),
|
|
||||||
)
|
|
||||||
.col(ColumnDef::new(Post::Title).string().not_null())
|
|
||||||
.col(ColumnDef::new(Post::Text).string().not_null())
|
|
||||||
.to_owned(),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
|
||||||
// Replace the sample below with your own migration scripts
|
|
||||||
todo!();
|
|
||||||
|
|
||||||
manager
|
|
||||||
.drop_table(Table::drop().table(Post::Table).to_owned())
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(DeriveIden)]
|
|
||||||
enum Post {
|
|
||||||
Table,
|
|
||||||
Id,
|
|
||||||
Title,
|
|
||||||
Text,
|
|
||||||
}
|
|
45
crates/migration/src/m20240705_100914_create_user.rs
Normal file
45
crates/migration/src/m20240705_100914_create_user.rs
Normal file
|
@ -0,0 +1,45 @@
|
||||||
|
use sea_orm_migration::prelude::*;
|
||||||
|
|
||||||
|
#[derive(DeriveMigrationName)]
|
||||||
|
pub struct Migration;
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl MigrationTrait for Migration {
|
||||||
|
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||||
|
manager
|
||||||
|
.create_table(
|
||||||
|
Table::create()
|
||||||
|
.table(User::Table)
|
||||||
|
.if_not_exists()
|
||||||
|
.col(
|
||||||
|
ColumnDef::new(User::Id)
|
||||||
|
.uuid()
|
||||||
|
.extra("DEFAULT gen_random_uuid()")
|
||||||
|
.primary_key()
|
||||||
|
.not_null(),
|
||||||
|
)
|
||||||
|
.col(ColumnDef::new(User::Name).string().not_null())
|
||||||
|
.col(ColumnDef::new(User::Email).string().not_null().unique_key())
|
||||||
|
.col(ColumnDef::new(User::Hash).string().not_null())
|
||||||
|
.col(ColumnDef::new(User::Salt).string().not_null())
|
||||||
|
.to_owned(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||||
|
manager
|
||||||
|
.drop_table(Table::drop().table(User::Table).to_owned())
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(DeriveIden)]
|
||||||
|
enum User {
|
||||||
|
Table,
|
||||||
|
Id,
|
||||||
|
Name,
|
||||||
|
Email,
|
||||||
|
Hash,
|
||||||
|
Salt,
|
||||||
|
}
|
16
docker-compose.yml
Normal file
16
docker-compose.yml
Normal file
|
@ -0,0 +1,16 @@
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres
|
||||||
|
restart: always
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: alisa
|
||||||
|
POSTGRES_USER: alisa
|
||||||
|
POSTGRES_PASSWORD: alisa
|
||||||
|
ports:
|
||||||
|
- 5432:5432
|
||||||
|
volumes:
|
||||||
|
- postgres:/var/lib/postgresql/data
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
postgres:
|
||||||
|
|
Loading…
Reference in a new issue