move web app to examples
This commit is contained in:
parent
08130f12fe
commit
c0245fd5c5
4
example/.env
Normal file
4
example/.env
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
DATABASE_URL=sqlite://database.db
|
||||||
|
OAUTH2_CLIENT_SECRET=
|
||||||
|
OAUTH2_CLIENT_ID=
|
||||||
|
OAUTH2_SERVER=
|
29
example/Cargo.toml
Normal file
29
example/Cargo.toml
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
[package]
|
||||||
|
name = "actix-web-sample-app"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
actix-web = "4.0.1"
|
||||||
|
actix-rt = "2.7.0"
|
||||||
|
actix-session = { version = "0.7.1", features = ["cookie-session"] }
|
||||||
|
tera = "1.15.0"
|
||||||
|
itertools = "0.10.3"
|
||||||
|
oauth2 = "4.1"
|
||||||
|
base64 = "0.13.0"
|
||||||
|
async-trait = "0.1.53"
|
||||||
|
rand = "0.8.5"
|
||||||
|
url = "2.2.2"
|
||||||
|
http = "0.2.6"
|
||||||
|
dotenv = "0.15"
|
||||||
|
futures = "0.3.21"
|
||||||
|
serde = "1.0.136"
|
||||||
|
serde_json = "1.0.79"
|
||||||
|
serde_derive = "1.0.136"
|
||||||
|
quote = "1.0"
|
||||||
|
sea-orm = { version = "^0.9.1", features = [ "sqlx-sqlite", "runtime-actix-native-tls", "macros" ], default-features = true }
|
||||||
|
syn = "1.0.91"
|
||||||
|
actix_admin = { path = "../" }
|
||||||
|
azure_auth = { path = "../azure_auth" }
|
24
example/src/entity/comment.rs
Normal file
24
example/src/entity/comment.rs
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
use sea_orm::entity::prelude::*;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use actix_admin::prelude::*;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Deserialize, Serialize, DeriveActixAdminModel)]
|
||||||
|
#[sea_orm(table_name = "comment")]
|
||||||
|
pub struct Model {
|
||||||
|
#[sea_orm(primary_key)]
|
||||||
|
#[serde(skip_deserializing)]
|
||||||
|
#[actix_admin(primary_key)]
|
||||||
|
pub id: i32,
|
||||||
|
pub comment: String,
|
||||||
|
#[sea_orm(column_type = "Text")]
|
||||||
|
#[actix_admin(html_input_type = "email")]
|
||||||
|
pub user: String,
|
||||||
|
#[sea_orm(column_type = "DateTime")]
|
||||||
|
pub insert_date: DateTime,
|
||||||
|
pub is_visible: bool
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||||
|
pub enum Relation {}
|
||||||
|
|
||||||
|
impl ActiveModelBehavior for ActiveModel {}
|
52
example/src/entity/mod.rs
Normal file
52
example/src/entity/mod.rs
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
// setup
|
||||||
|
use sea_orm::sea_query::{ColumnDef, TableCreateStatement};
|
||||||
|
use sea_orm::{error::*, sea_query, ConnectionTrait, DbConn, ExecResult};
|
||||||
|
pub mod comment;
|
||||||
|
pub mod post;
|
||||||
|
pub use comment::Entity as Comment;
|
||||||
|
pub use post::Entity as Post;
|
||||||
|
|
||||||
|
// setup
|
||||||
|
async fn create_table(db: &DbConn, stmt: &TableCreateStatement) -> Result<ExecResult, DbErr> {
|
||||||
|
let builder = db.get_database_backend();
|
||||||
|
db.execute(builder.build(stmt)).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create_post_table(db: &DbConn) -> Result<ExecResult, DbErr> {
|
||||||
|
let stmt = sea_query::Table::create()
|
||||||
|
.table(post::Entity)
|
||||||
|
.if_not_exists()
|
||||||
|
.col(
|
||||||
|
ColumnDef::new(post::Column::Id)
|
||||||
|
.integer()
|
||||||
|
.not_null()
|
||||||
|
.auto_increment()
|
||||||
|
.primary_key(),
|
||||||
|
)
|
||||||
|
.col(ColumnDef::new(post::Column::Title).string().not_null())
|
||||||
|
.col(ColumnDef::new(post::Column::Text).string().not_null())
|
||||||
|
.col(ColumnDef::new(post::Column::TeaMandatory).string().not_null())
|
||||||
|
.col(ColumnDef::new(post::Column::TeaOptional).string())
|
||||||
|
.col(ColumnDef::new(post::Column::InsertDate).date())
|
||||||
|
.to_owned();
|
||||||
|
|
||||||
|
let _result = create_table(db, &stmt).await;
|
||||||
|
|
||||||
|
let stmt = sea_query::Table::create()
|
||||||
|
.table(comment::Entity)
|
||||||
|
.if_not_exists()
|
||||||
|
.col(
|
||||||
|
ColumnDef::new(post::Column::Id)
|
||||||
|
.integer()
|
||||||
|
.not_null()
|
||||||
|
.auto_increment()
|
||||||
|
.primary_key(),
|
||||||
|
)
|
||||||
|
.col(ColumnDef::new(comment::Column::Comment).string().not_null())
|
||||||
|
.col(ColumnDef::new(comment::Column::User).string().not_null())
|
||||||
|
.col(ColumnDef::new(comment::Column::InsertDate).date_time().not_null())
|
||||||
|
.col(ColumnDef::new(comment::Column::IsVisible).boolean().not_null())
|
||||||
|
.to_owned();
|
||||||
|
|
||||||
|
create_table(db, &stmt).await
|
||||||
|
}
|
60
example/src/entity/post.rs
Normal file
60
example/src/entity/post.rs
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
use sea_orm::entity::prelude::*;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use actix_admin::prelude::*;
|
||||||
|
use std::fmt;
|
||||||
|
use std::fmt::Display;
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Deserialize, Serialize, DeriveActixAdminModel)]
|
||||||
|
#[sea_orm(table_name = "post")]
|
||||||
|
pub struct Model {
|
||||||
|
#[sea_orm(primary_key)]
|
||||||
|
#[serde(skip_deserializing)]
|
||||||
|
#[actix_admin(primary_key)]
|
||||||
|
pub id: i32,
|
||||||
|
#[actix_admin(searchable)]
|
||||||
|
pub title: String,
|
||||||
|
#[sea_orm(column_type = "Text")]
|
||||||
|
#[actix_admin(searchable)]
|
||||||
|
pub text: String,
|
||||||
|
#[actix_admin(select_list="Tea")]
|
||||||
|
pub tea_mandatory: Tea,
|
||||||
|
#[actix_admin(select_list="Tea")]
|
||||||
|
pub tea_optional: Option<Tea>,
|
||||||
|
pub insert_date: Date,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||||
|
pub enum Relation {}
|
||||||
|
|
||||||
|
impl ActiveModelBehavior for ActiveModel {}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, EnumIter, DeriveActiveEnum, Deserialize, Serialize, DeriveActixAdminSelectList)]
|
||||||
|
#[sea_orm(rs_type = "String", db_type = "Enum", enum_name = "tea")]
|
||||||
|
pub enum Tea {
|
||||||
|
#[sea_orm(string_value = "EverydayTea")]
|
||||||
|
EverydayTea,
|
||||||
|
#[sea_orm(string_value = "BreakfastTea")]
|
||||||
|
BreakfastTea,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromStr for Tea {
|
||||||
|
type Err = ();
|
||||||
|
|
||||||
|
fn from_str(input: &str) -> Result<Tea, Self::Err> {
|
||||||
|
match input {
|
||||||
|
"EverydayTea" => Ok(Tea::EverydayTea),
|
||||||
|
"BreakfastTea" => Ok(Tea::BreakfastTea),
|
||||||
|
_ => Err(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for Tea {
|
||||||
|
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
match &*self {
|
||||||
|
Tea::EverydayTea => write!(formatter, "{}", String::from("EverydayTea")),
|
||||||
|
Tea::BreakfastTea => write!(formatter, "{}", String::from("BreakfastTea")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
124
example/src/main.rs
Normal file
124
example/src/main.rs
Normal file
@ -0,0 +1,124 @@
|
|||||||
|
extern crate serde_derive;
|
||||||
|
|
||||||
|
use actix_admin::prelude::*;
|
||||||
|
use actix_session::{Session, SessionMiddleware, storage::CookieSessionStore};
|
||||||
|
use actix_web::{cookie::Key, web, App, HttpResponse, HttpServer, middleware};
|
||||||
|
use azure_auth::{AppDataTrait as AzureAuthAppDataTrait, AzureAuth, UserInfo};
|
||||||
|
use oauth2::basic::BasicClient;
|
||||||
|
use oauth2::RedirectUrl;
|
||||||
|
use sea_orm::{ConnectOptions, DatabaseConnection};
|
||||||
|
use std::env;
|
||||||
|
use std::time::Duration;
|
||||||
|
use tera::{Context, Tera};
|
||||||
|
|
||||||
|
mod entity;
|
||||||
|
use entity::{Post, Comment};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct AppState {
|
||||||
|
pub oauth: BasicClient,
|
||||||
|
pub tmpl: Tera,
|
||||||
|
pub db: DatabaseConnection,
|
||||||
|
pub actix_admin: ActixAdmin,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ActixAdminAppDataTrait for AppState {
|
||||||
|
fn get_db(&self) -> &DatabaseConnection {
|
||||||
|
&self.db
|
||||||
|
}
|
||||||
|
fn get_actix_admin(&self) -> &ActixAdmin {
|
||||||
|
&self.actix_admin
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AzureAuthAppDataTrait for AppState {
|
||||||
|
fn get_oauth(&self) -> &BasicClient {
|
||||||
|
&self.oauth
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn index(session: Session, data: web::Data<AppState>) -> HttpResponse {
|
||||||
|
let login = session.get::<UserInfo>("user_info").unwrap();
|
||||||
|
let web_auth_link = if login.is_some() {
|
||||||
|
"/auth/logout"
|
||||||
|
} else {
|
||||||
|
"/auth/login"
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut ctx = Context::new();
|
||||||
|
ctx.insert("web_auth_link", web_auth_link);
|
||||||
|
let rendered = data.tmpl.render("index.html", &ctx).unwrap();
|
||||||
|
HttpResponse::Ok().body(rendered)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_actix_admin_builder() -> ActixAdminBuilder {
|
||||||
|
let post_view_model = ActixAdminViewModel::from(Post);
|
||||||
|
let comment_view_model = ActixAdminViewModel::from(Comment);
|
||||||
|
|
||||||
|
let mut admin_builder = ActixAdminBuilder::new();
|
||||||
|
admin_builder.add_entity::<AppState, Post>(&post_view_model);
|
||||||
|
admin_builder.add_entity::<AppState, Comment>(&comment_view_model);
|
||||||
|
|
||||||
|
admin_builder
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_rt::main]
|
||||||
|
async fn main() {
|
||||||
|
dotenv::dotenv().ok();
|
||||||
|
let oauth2_client_id =
|
||||||
|
env::var("OAUTH2_CLIENT_ID").expect("Missing the OAUTH2_CLIENT_ID environment variable.");
|
||||||
|
let oauth2_client_secret = env::var("OAUTH2_CLIENT_SECRET")
|
||||||
|
.expect("Missing the OAUTH2_CLIENT_SECRET environment variable.");
|
||||||
|
let oauth2_server =
|
||||||
|
env::var("OAUTH2_SERVER").expect("Missing the OAUTH2_SERVER environment variable.");
|
||||||
|
let azure_auth = AzureAuth::new(&oauth2_server, &oauth2_client_id, &oauth2_client_secret);
|
||||||
|
|
||||||
|
// Set up the config for the OAuth2 process.
|
||||||
|
let client = azure_auth
|
||||||
|
.clone()
|
||||||
|
.get_oauth_client()
|
||||||
|
// This example will be running its own server at 127.0.0.1:5000.
|
||||||
|
.set_redirect_uri(
|
||||||
|
RedirectUrl::new("http://localhost:5000/auth".to_string())
|
||||||
|
.expect("Invalid redirect URL"),
|
||||||
|
);
|
||||||
|
|
||||||
|
let tera = Tera::new(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*")).unwrap();
|
||||||
|
|
||||||
|
let db_url = env::var("DATABASE_URL").expect("DATABASE_URL is not set in .env file");
|
||||||
|
let mut opt = ConnectOptions::new(db_url);
|
||||||
|
opt.max_connections(100)
|
||||||
|
.min_connections(5)
|
||||||
|
.connect_timeout(Duration::from_secs(8))
|
||||||
|
.idle_timeout(Duration::from_secs(8))
|
||||||
|
.sqlx_logging(true);
|
||||||
|
|
||||||
|
let conn = sea_orm::Database::connect(opt).await.unwrap();
|
||||||
|
let _ = entity::create_post_table(&conn).await;
|
||||||
|
|
||||||
|
let actix_admin = create_actix_admin_builder().get_actix_admin();
|
||||||
|
|
||||||
|
let app_state = AppState {
|
||||||
|
oauth: client,
|
||||||
|
tmpl: tera,
|
||||||
|
db: conn,
|
||||||
|
actix_admin: actix_admin,
|
||||||
|
};
|
||||||
|
|
||||||
|
HttpServer::new(move || {
|
||||||
|
App::new()
|
||||||
|
.app_data(web::Data::new(app_state.clone()))
|
||||||
|
.wrap(SessionMiddleware::new(CookieSessionStore::default(), Key::generate()))
|
||||||
|
.route("/", web::get().to(index))
|
||||||
|
.service(azure_auth.clone().create_scope::<AppState>())
|
||||||
|
.service(
|
||||||
|
create_actix_admin_builder().get_scope::<AppState>()
|
||||||
|
)
|
||||||
|
.wrap(middleware::Logger::default())
|
||||||
|
})
|
||||||
|
.bind("127.0.0.1:5000")
|
||||||
|
.expect("Can not bind to port 5000")
|
||||||
|
.run()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
14
example/templates/base.html
Normal file
14
example/templates/base.html
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Actix Web</title>
|
||||||
|
|
||||||
|
<link rel="stylesheet" href="https://unpkg.com/@picocss/pico@latest/css/pico.classless.min.css">
|
||||||
|
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
{% block content %}
|
||||||
|
{% endblock content %}
|
||||||
|
</body>
|
||||||
|
</html>
|
5
example/templates/index.html
Normal file
5
example/templates/index.html
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<a href="/{{ web_auth_link }}">{{ web_auth_link }}</a>
|
||||||
|
{% endblock content %}
|
8
example/templates/list.html
Normal file
8
example/templates/list.html
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<p>posts: {{ posts }}</p>
|
||||||
|
<p>page: {{ page }}</p>
|
||||||
|
<p>posts_per_page: {{ posts_per_page }}</p>
|
||||||
|
<p>num_pages: {{ num_pages }}</p>
|
||||||
|
{% endblock content %}
|
Loading…
Reference in New Issue
Block a user