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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
|
#[macro_use]
mod actix_ructe;
use std::time::{Duration, SystemTime};
use actix_web::body::{BoxBody, EitherBody, MessageBody};
use actix_web::dev::ServiceResponse;
use actix_web::http::{header, StatusCode};
use actix_web::middleware::{ErrorHandlerResponse, ErrorHandlers};
use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder, ResponseError};
use bcrypt::{hash, verify, DEFAULT_COST};
use serde::Deserialize;
use sqlx::postgres::PgDatabaseError;
use sqlx::{postgres::PgPoolOptions, Pool, Postgres};
use templates::statics::StaticFile;
static FAR: Duration = Duration::from_secs(180 * 24 * 60 * 60);
type Result<T> = std::result::Result<T, PinussyError>;
#[derive(Clone)]
struct Pinussy {
db: Pool<Postgres>,
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let pool = PgPoolOptions::new()
.max_connections(5)
.connect("postgres://pinussy:pinussy@localhost/pinussy")
.await
.unwrap();
sqlx::migrate!("./migrations").run(&pool).await.unwrap();
let pinussy = Pinussy { db: pool };
HttpServer::new(move || {
App::new()
.wrap(
ErrorHandlers::new()
.handler(StatusCode::NOT_FOUND, render_404)
.handler(StatusCode::INTERNAL_SERVER_ERROR, render_500),
)
.app_data(web::Data::new(pinussy.clone()))
.service(web::resource("/static/{filename}").to(static_file))
.service(home)
.service(get_login)
.service(post_login)
.service(get_signup)
.service(post_signup)
.service(get_users)
// .service(get_pins)
// .service(post_pin)
// .service(get_pin)
// .service(post_board)
// .service(get_board)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
#[get("/")]
async fn home() -> HttpResponse {
HttpResponse::Ok().body("Hello world!")
}
#[get("/signup")]
async fn get_signup() -> HttpResponse {
HttpResponse::Ok().body(render!(templates::signup_html, None).unwrap())
}
#[derive(Deserialize)]
struct SignupForm {
username: String,
password: String,
}
#[post("/signup")]
async fn post_signup(
state: web::Data<Pinussy>,
form: web::Form<SignupForm>,
) -> Result<HttpResponse> {
let password_hash = hash(&form.password, DEFAULT_COST)?;
match sqlx::query!(
"insert into users(username, password) values ($1, $2)",
&form.username,
password_hash
)
.execute(&state.db)
.await
{
Ok(_) => {
return Ok(HttpResponse::Ok().body(
render!(
templates::signup_html,
Some(Notification {
kind: NotificationKind::Info,
message: format!("you have successfully registered as {}", &form.username)
})
)
.unwrap(),
))
}
Err(e) => {
match e {
sqlx::Error::Database(e) => {
if e.is_unique_violation() {
return Ok(HttpResponse::Conflict().body(
render!(
templates::signup_html,
Some(Notification {
kind: NotificationKind::Error,
message: format!(
"error: the username \"{}\" already exists",
&form.username
)
})
)
.unwrap(),
));
}
}
// TODO: log error
_ => {}
}
return Ok(HttpResponse::InternalServerError().body(
render!(
templates::signup_html,
Some(Notification {
kind: NotificationKind::Error,
message: "there was an internal server error. please try again later."
.to_owned()
})
)
.unwrap(),
));
}
};
}
#[get("/login")]
async fn get_login() -> HttpResponse {
HttpResponse::Ok().body(render!(templates::login_html, None).unwrap())
}
#[derive(Deserialize)]
struct LoginForm {
username: String,
password: String,
rememberme: Option<String>,
}
#[post("/login")]
async fn post_login(form: web::Form<LoginForm>) -> Result<HttpResponse> {
Ok(HttpResponse::Ok().body(render!(templates::login_html, None).unwrap()))
}
#[derive(sqlx::Type)]
#[sqlx(type_name = "privacy", rename_all = "lowercase")]
enum Privacy {
Private,
Unlisted,
Public,
}
#[derive(sqlx::FromRow)]
pub struct User {
id: i32,
username: String,
password: String,
email: Option<String>,
bio: Option<String>,
site: Option<String>,
privacy: Privacy,
admin: bool,
}
pub enum NotificationKind {
Info,
Warning,
Error,
}
impl std::fmt::Display for NotificationKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
NotificationKind::Info => f.write_str("info"),
NotificationKind::Warning => f.write_str("warning"),
NotificationKind::Error => f.write_str("error"),
}
}
}
pub struct Notification {
kind: NotificationKind,
message: String,
}
#[get("/users")]
async fn get_users(state: web::Data<Pinussy>) -> Result<HttpResponse> {
let users: Vec<User> = sqlx::query_as("select * from users")
.fetch_all(&state.db)
.await
.unwrap();
println!("lol");
Ok(HttpResponse::Ok().body(render!(templates::users_html, users).unwrap()))
}
async fn static_file(path: web::Path<String>) -> HttpResponse {
let name = &path.into_inner();
if let Some(data) = StaticFile::get(name) {
let far_expires = SystemTime::now() + FAR;
HttpResponse::Ok()
.insert_header(header::Expires(far_expires.into()))
.insert_header(header::ContentType(data.mime.clone()))
.body(data.content)
} else {
HttpResponse::NotFound()
.reason("No such static file.")
.finish()
}
}
fn render_404(res: ServiceResponse) -> actix_web::Result<ErrorHandlerResponse<BoxBody>> {
Ok(error_response(
res,
StatusCode::NOT_FOUND,
"The resource you requested can't be found.",
))
}
fn render_500(res: ServiceResponse) -> actix_web::Result<ErrorHandlerResponse<BoxBody>> {
Ok(error_response(
res,
StatusCode::INTERNAL_SERVER_ERROR,
"Sorry, Something went wrong. This is probably not your fault.",
))
}
fn error_response(
mut res: ServiceResponse,
status_code: StatusCode,
message: &str,
) -> ErrorHandlerResponse<BoxBody> {
res.headers_mut().insert(
header::CONTENT_TYPE,
header::HeaderValue::from_static(mime::TEXT_HTML_UTF_8.as_ref()),
);
ErrorHandlerResponse::Response(res.map_body(|_head, _body| {
EitherBody::right(MessageBody::boxed(
render!(templates::error_html, status_code, message).unwrap(),
))
}))
}
#[derive(Debug)]
enum PinussyError {
Database(sqlx::Error),
Bcrypt,
}
impl From<sqlx::Error> for PinussyError {
fn from(e: sqlx::Error) -> Self {
Self::Database(e)
}
}
impl From<bcrypt::BcryptError> for PinussyError {
fn from(e: bcrypt::BcryptError) -> Self {
Self::Bcrypt
}
}
impl std::fmt::Display for PinussyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}
impl std::error::Error for PinussyError {}
impl ResponseError for PinussyError {
fn error_response(&self) -> HttpResponse<BoxBody> {
HttpResponse::new(self.status_code())
}
}
include!(concat!(env!("OUT_DIR"), "/templates.rs"));
|