1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
|
/**
* Comments generator
* POST /comment - submits a comment
*
* GET /form - generate html comment form
* GET /comment - gets html fragment with comments
* both accept a query parameter ?page=<url>
*/
use askama::Template;
use axum::{
extract::{Query, Form, State},
response::{Redirect,Html},
http::StatusCode,
routing::get,
Router,
};
use serde::Deserialize;
use sqlx::{
postgres::{PgPool, PgPoolOptions},
types::{
time::OffsetDateTime,
uuid::Uuid,
},
};
use std::{net::SocketAddr, time::Duration};
// Useful global thingies
#[derive(Clone)]
struct Ctx {
pool: PgPool,
base_path: String,
}
#[tokio::main]
async fn main() {
let base_path = std::env::var("BASE_PATH")
.unwrap_or_else(|_| "/api".to_string());
let db_connection_str = std::env::var("DATABASE_URL")
.unwrap_or_else(|_| "postgres://postgres:password@localhost".to_string());
let pool = PgPoolOptions::new()
.max_connections(5)
.connect_timeout(Duration::from_secs(3))
.connect(&db_connection_str)
.await
.expect("can't connect to database");
sqlx::migrate!()
.run(&pool)
.await
.expect("failed to run migrations");
let ctx = Ctx {pool, base_path: base_path.clone()};
let app = Router::new()
.nest(&base_path, Router::new()
.route(
"/form",
get(get_form),
)
.route(
"/comment",
get(get_comments).post(post_comments),
)
.with_state(ctx));
let addr = SocketAddr::from(([127, 0, 0, 1], 5678));
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
#[derive(Deserialize)]
struct UrlQuery {
url: String
}
#[derive(Template)]
#[template(path = "form.html")]
struct CommentForm {
url: String,
capcha_question: String,
capcha_id: Uuid,
base_path: String,
}
async fn get_form(
State(ctx): State<Ctx>,
Query(uq): Query<UrlQuery>
) -> Result<Html<String>, (StatusCode, String)> {
let capcha = sqlx::query!("select id, question from capchas order by random() limit 1")
.fetch_one(&ctx.pool)
.await
.map_err(internal_error)?;
let c = CommentForm{url: uq.url, capcha_question: capcha.question, capcha_id: capcha.id, base_path: ctx.base_path};
let res = c.render().map_err(internal_error)?;
Ok(Html(res))
}
#[derive(Template)]
#[template(path = "comments.html")]
struct Comments {
comments: Vec<Comment>,
}
struct Comment {
author: String,
comment: String,
ts: OffsetDateTime,
}
async fn get_comments(
State(ctx): State<Ctx>,
Query(uq): Query<UrlQuery>) -> Result<Html<String>, (StatusCode,String)> {
let comments = sqlx::query!("select author,comment,ts from comments where url = $1 order by ts", uq.url)
.fetch_all(&ctx.pool)
.await
.map_err(internal_error)?;
let render_comments: Vec<Comment> = comments.into_iter().map(|comment| {
Comment {
author: comment.author,
comment: comment.comment,
ts: comment.ts,
}
}).collect();
let c = Comments{comments: render_comments};
let res = c.render().map_err(internal_error)?;
Ok(Html(res))
}
#[derive(Deserialize)]
struct PostComment {
url: String,
author: String,
comment: String,
capcha_id: String,
capcha_answer: String,
}
struct CapchaAnswer {
answer:String
}
async fn post_comments(
State(ctx): State<Ctx>,
Form(post_comment): Form<PostComment>) -> Result<Redirect,(StatusCode,String)> {
let capcha_id: Uuid = post_comment.capcha_id.parse()
.map_err(|_| {(StatusCode::BAD_REQUEST, "Invalid capcha_id".to_string())})?;
let ans: CapchaAnswer = sqlx::query_as!(CapchaAnswer, "select answer from capchas where id = $1", capcha_id)
.fetch_one(&ctx.pool)
.await
.map_err(internal_error)?;
if post_comment.capcha_answer != ans.answer {
return Err((StatusCode::BAD_REQUEST, "Capcha was wrong!".to_string()));
}
sqlx::query!("insert into comments(url,author,comment) values($1, $2, $3)", post_comment.url, post_comment.author, post_comment.comment)
.execute(&ctx.pool)
.await
.map_err(internal_error)?;
Ok(Redirect::temporary(&post_comment.url))
}
fn internal_error<E>(err: E) -> (StatusCode, String)
where
E: std::error::Error,
{
(StatusCode::INTERNAL_SERVER_ERROR, err.to_string())
}
|