summaryrefslogtreecommitdiffstats
path: root/src/admin.rs
blob: 912d0a39efa83109491f779a4d13261cef0473d3 (plain) (blame)
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
use std::str::FromStr;

use actix::Addr;
use actix_http::error::ResponseError;
use actix_identity::Identity;
use actix_web::{http::header, web, HttpResponse};
use askama::Template;
use serde::{Serialize, Deserialize};

use crate::error::ServiceError;
use crate::model::{DbExecutor, NewUser};
use crate::user::LoginData;
use crate::util::UserRequest;
use crate::Secret;

pub mod user_creation;
use user_creation::{ChangePasswordRequest, PassHashExecutor, PassHashRequest, SaveUserRequest};

#[derive(Template)]
#[template(path = "admin.htm")]
struct AdminTemplate {
    success: OperationResult,
}

#[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "kebab-case")]
pub enum OperationResult {
    ChangePassword,
    CreateUser,
    Empty,
}

pub async fn handle_index(ident: Identity, db: web::Data<Addr<DbExecutor>>) -> HttpResponse {
    if let Some(name) = ident.identity() {
        ident.remember(name.clone());
        let user = match db.send(UserRequest(name.clone())).await.unwrap() {
            Ok(v) => v,
            Err(_) => {
                ident.forget();
                return HttpResponse::Found()
                    .header(header::LOCATION, "/login")
                    .finish();
            }
        };
        if user.power_level != 9001 {
            return ServiceError::Unauthorized.error_response();
        }

        let page = AdminTemplate {
            success: OperationResult::Empty,
        }
        .render()
        .unwrap();

        HttpResponse::Ok().content_type("text/html").body(page)
    } else {
        HttpResponse::Found()
            .header(header::LOCATION, "/user/login")
            .finish()
    }
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct UserData {
    pub user: String,
    pub balance: String,
    pub password: String,
}

pub async fn handle_create_user(
    ident: Identity,
    params: web::Form<UserData>,
    db: web::Data<Addr<DbExecutor>>,
    hasher: web::Data<Addr<PassHashExecutor>>,
    sec: web::Data<Secret>,
) -> HttpResponse {
    if let Some(name) = ident.identity() {
        ident.remember(name.clone());
        let user = match db.send(UserRequest(name.clone())).await.unwrap() {
            Ok(v) => v,
            Err(_) => {
                ident.forget();
                return HttpResponse::Found()
                    .header(header::LOCATION, "/login")
                    .finish();
            }
        };
        if user.power_level != 9001 {
            return ServiceError::Unauthorized.error_response();
        }
        let new_login = params.into_inner();

        let balance = match u64::from_str(&new_login.balance) {
            Ok(v) => v,
            Err(e) => {
                return HttpResponse::Ok()
                    .content_type("text/html")
                    .body(e.to_string())
            }
        };

        let hash = hasher
            .send(PassHashRequest::new(new_login.password, sec.0.clone()))
            .await
            .unwrap()
            .unwrap();

        let new_user = NewUser {
            name: new_login.user,
            // TODO Let the admin pick
            power_level: 0,
            balance,
        };

        db.send(SaveUserRequest::new(new_user, hash))
            .await
            .unwrap()
            .unwrap();

        HttpResponse::Found()
            .header(header::LOCATION, "/admin")
            .finish()
    } else {
        HttpResponse::Found()
            .header(header::LOCATION, "/login")
            .finish()
    }
}

pub async fn handle_change_password(
    ident: Identity,
    params: web::Form<LoginData>,
    db: web::Data<Addr<DbExecutor>>,
    hasher: web::Data<Addr<PassHashExecutor>>,
    sec: web::Data<Secret>,
) -> HttpResponse {
    if let Some(name) = ident.identity() {
        ident.remember(name.clone());
        let user = db.send(UserRequest(name.clone())).await.unwrap().unwrap();
        if user.power_level != 9001 {
            return ServiceError::Unauthorized.error_response();
        }

        change_password(params.into_inner(), &db, &hasher, sec.0.clone()).await;

        let page = AdminTemplate {
            success: OperationResult::ChangePassword,
        }
        .render()
        .unwrap();

        HttpResponse::Ok().content_type("text/html").body(page)
    } else {
        HttpResponse::Found()
            .header(header::LOCATION, "/user/login")
            .finish()
    }
}

pub async fn change_password(
    login: LoginData,
    db: &Addr<DbExecutor>,
    hasher: &Addr<PassHashExecutor>,
    secret: String,
) {
    let hash = hasher
        .send(PassHashRequest::new(login.password, secret))
        .await
        .unwrap()
        .unwrap();

    db.send(ChangePasswordRequest(login.user, hash))
        .await
        .unwrap()
        .unwrap();
}