1use std::net::SocketAddr;
2
3use rustio_core::admin;
4use rustio_core::auth::authenticate;
5use rustio_core::defaults::with_defaults;
6use rustio_core::{Db, Error, Model, Router, Row, RustioAdmin, Server, Value};
7
8#[derive(Debug, RustioAdmin)]
9struct User {
10 id: i64,
11 name: String,
12 is_admin: bool,
13}
14
15impl Model for User {
16 const TABLE: &'static str = "users";
17 const COLUMNS: &'static [&'static str] = &["id", "name", "is_admin"];
18 const INSERT_COLUMNS: &'static [&'static str] = &["name", "is_admin"];
19
20 fn id(&self) -> i64 {
21 self.id
22 }
23
24 fn from_row(row: Row<'_>) -> Result<Self, Error> {
25 Ok(Self {
26 id: row.get_i64("id")?,
27 name: row.get_string("name")?,
28 is_admin: row.get_bool("is_admin")?,
29 })
30 }
31
32 fn insert_values(&self) -> Vec<Value> {
33 vec![self.name.clone().into(), self.is_admin.into()]
34 }
35}
36
37#[tokio::main]
38async fn main() -> std::io::Result<()> {
39 let db = Db::memory().await.expect("db connect");
40 db.execute(
41 "CREATE TABLE users (
42 id INTEGER PRIMARY KEY AUTOINCREMENT,
43 name TEXT NOT NULL,
44 is_admin INTEGER NOT NULL
45 )",
46 )
47 .await
48 .expect("create schema");
49
50 User {
51 id: 0,
52 name: "Alice".into(),
53 is_admin: false,
54 }
55 .create(&db)
56 .await
57 .expect("seed alice");
58 User {
59 id: 0,
60 name: "Bob".into(),
61 is_admin: true,
62 }
63 .create(&db)
64 .await
65 .expect("seed bob");
66
67 let router = with_defaults(Router::new()).wrap(authenticate);
68 let router = admin::register::<User>(router, &db);
69
70 let addr: SocketAddr = ([127, 0, 0, 1], 3000).into();
71 eprintln!("admin demo: hit /admin/users with `Authorization: Bearer dev-admin` header");
72 Server::bind(addr).serve_router(router).await
73}