DEVELOPMENT ENVIRONMENT

~liljamo/ulairi

ref: e78be1f39347874c13c8ff1c08025ec375b5e928 ulairi/ulairi-client/src/app/api.rs -rw-r--r-- 12.0 KiB
e78be1f3Jonni Liljamo I lost the old commit history... 1 year, 11 months ago
                                                                                
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
use reqwest;

use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
pub struct AuthInput {
    pub username: String,
    pub password: String,
}

#[derive(Serialize, Deserialize)]
pub struct RegisterInput {
    pub username: String,
    pub email: String,
    pub password: String,
}

#[derive(Serialize, Deserialize)]
pub struct AuthResponse {
    pub success: bool,
    pub message: String,
}

impl Default for AuthResponse {
    fn default() -> Self {
        AuthResponse {
            success: false,
            message: String::new(),
        }
    }
}

#[derive(Serialize, Deserialize)]
pub struct HourEntryInsertInput {
    pub email: String,
    pub hours: i32,
    pub date_worked: String,
}

#[derive(Serialize, Deserialize)]
pub struct HourEntryDeleteInput {
    pub email: String,
    pub id: i32,
}

#[derive(Serialize, Deserialize, Clone)]
pub struct HourEntry {
    pub id: i32,
    pub user_id: i32,
    pub hours: i32,
    pub date_worked: String,
    pub date_entered: String,
}

impl Default for HourEntry {
    fn default() -> Self {
        HourEntry {
            id: 0,
            user_id: 0,
            hours: 0,
            date_worked: String::new(),
            date_entered: String::new(),
        }
    }
}

#[derive(Serialize, Deserialize, Clone)]
pub struct UserInfoInput {
    pub email: String,
}

#[derive(Serialize, Deserialize, Clone)]
pub struct UserInfoResponse {
    pub success: bool,
    pub message: String,
}

impl Default for UserInfoResponse {
    fn default() -> Self {
        UserInfoResponse {
            success: false,
            message: String::new(),
        }
    }
}

pub async fn auth(username: String, password: String, api_address: String) -> AuthResponse {
    // Connect to env!("WEB_API_ADDRESS")/api/auth/login and return AuthResponse
    let client = reqwest::Client::new();
    let response = client
        .post(&format!("{}/api/auth/login", api_address))
        .json(&AuthInput {
            username: username.to_string(),
            password: password.to_string(),
        })
        .send()
        .await
        .unwrap();
    response.json().await.unwrap()
}

pub async fn register(
    username: String,
    email: String,
    password: String,
    api_address: String,
) -> AuthResponse {
    // Connect to env!("WEB_API_ADDRESS")/api/auth/register and return AuthResponse
    let client = reqwest::Client::new();
    let response = client
        .post(&format!("{}/api/auth/register", api_address))
        .json(&RegisterInput {
            username: username.to_string(),
            email: email.to_string(),
            password: password.to_string(),
        })
        .send()
        .await
        .unwrap();
    response.json().await.unwrap()
}

pub async fn get_user_info(api_key: String, api_address: String) -> UserInfoResponse {
    // Connect to env!("WEB_API_ADDRESS")/api/user/info and return UserInfo
    let client = reqwest::Client::new();
    let response = client
        .get(&format!("{}/api/user/info", api_address))
        .header("Authentication", api_key)
        .send()
        .await
        .unwrap();
    response.json().await.unwrap()
}

pub async fn get_hour_entries(api_key: String, api_address: String) -> Vec<HourEntry> {
    // Connect to env!("WEB_API_ADDRESS")/api/hours/all and return Vec<HourEntry>
    let email = get_user_info(api_key.clone(), api_address.clone())
        .await
        .message;

    let client = reqwest::Client::new();

    let response = client
        .post(&format!("{}/api/hours/all", api_address))
        .header("Authentication", api_key)
        .json(&UserInfoInput {
            email: email.to_string(),
        })
        .send()
        .await
        .unwrap();
    response.json().await.unwrap()
}

pub async fn insert_hour_entry(
    hours: i32,
    date_worked: String,
    api_key: String,
    api_address: String,
) -> HourEntry {
    // Connect to env!("WEB_API_ADDRESS")/api/hours/insert and return HourEntry
    let email = get_user_info(api_key.clone(), api_address.clone())
        .await
        .message;

    let client = reqwest::Client::new();

    let response = client
        .post(&format!("{}/api/hours/insert", api_address))
        .header("Authentication", api_key)
        .json(&HourEntryInsertInput {
            email: email.to_string(),
            hours: hours,
            date_worked: date_worked.to_string(),
        })
        .send()
        .await
        .unwrap();
    response.json().await.unwrap()
}

pub async fn delete_hour_entry(id: i32, api_key: String, api_address: String) {
    // Connect to env!("WEB_API_ADDRESS")/api/hours/delete and return ()
    let email = get_user_info(api_key.clone(), api_address.clone())
        .await
        .message;

    let client = reqwest::Client::new();

    client
        .post(&format!("{}/api/hours/delete", api_address))
        .header("Authentication", api_key)
        .json(&HourEntryDeleteInput {
            email: email.to_string(),
            id: id,
        })
        .send()
        .await
        .unwrap();
}
/* All the nice old things!
use mysql::prelude::*;
use mysql::*;

use argon2::{
    password_hash::{rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
    Argon2,
};

// Different exit contituons for verify_user
#[derive(Debug, PartialEq, Eq)]
pub enum VerifyExit {
    EmptyArg,
    Success,
    WrongPassword,
    UserNotFound,
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct User {
    pub id: i32,
    pub username: String,
    pub password: String,
}

impl User {
    pub fn new() -> User {
        User {
            id: 0,
            username: "".to_owned(),
            password: "".to_owned(),
        }
    }
}

// Time entry struct
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct TimeEntry {
    pub id: i32,
    pub user_id: i32,
    pub hours: i32,
    pub date_worked: String,
    pub date_entered: String,
}

// Role struct
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Role {
    pub id: i32,
    pub name: String,
}

#[derive(Debug, PartialEq, Eq)]
pub enum Roles {
    Member,
    Leader,
}

// UserRole struct
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct UserRole {
    pub user_id: i32,
    pub role_id: i32,
}

pub struct DatabaseManager {
    pub pool: Pool,
}

impl DatabaseManager {
    pub fn new() -> DatabaseManager {
        DatabaseManager {
            pool: Pool::new(Opts::from_url("mysql://root:QXSrgXhclUKrC6jl37qQ5ytRVbthtyJSCvFR23ZhYvlbAGwysvqecSsg1eeLPkLP3J9YrSinM192JmcgjrIPdLAhDc5wpU1im1ocNV7oU01CWL4GYgfNdMFx9mMlKZOc@172.104.253.237:3306/tuntikirjanpito").unwrap()).unwrap(),
        }
    }

    pub fn init_connection(&mut self) {
        println!("Connected to mysql");
    }

    pub fn register_user(&mut self, username: &str, password: &str) -> bool {
        if username.is_empty() || password.is_empty() {
            println!("Username or password is empty");
            return false;
        }

        let password = password.as_bytes();
        let salt = SaltString::generate(&mut OsRng);

        // Argon2 with default params (Argon2id v19)
        let argon2 = Argon2::default();

        // Hash password to PHC string
        let password_hash = argon2.hash_password(password, &salt).unwrap().to_string();

        self.pool
            .get_conn()
            .ok()
            .unwrap()
            .exec_drop(
                "INSERT INTO users (username, password) values (:username, :password)",
                params! {
                    "username" => username,
                    "password" => password_hash,
                },
            )
            .unwrap();

        println!("User {} registered", username);
        return true;
    }

    pub fn verify_user(&mut self, username: &str, password: &str) -> VerifyExit {
        if username.is_empty() || password.is_empty() {
            println!("Username or password is empty");
            return VerifyExit::EmptyArg;
        }

        let res = self
            .pool
            .get_conn()
            .ok()
            .unwrap()
            .query_first(format!(
                "SELECT id, username, password FROM users WHERE username='{un}'",
                un = username
            ))
            //Unpack Result
            .map(|row| {
                //Unpack Option
                row.map(|(id, username, password)| User {
                    id: id,
                    username: username,
                    password: password,
                })
            });

        match res.unwrap() {
            Some(user) => {
                let parsed_hash = PasswordHash::new(&user.password);

                if Argon2::default()
                    .verify_password(password.as_bytes(), &parsed_hash.unwrap())
                    .is_ok()
                {
                    println!("Password verified");
                    return VerifyExit::Success;
                } else {
                    println!("Password not verified");
                    return VerifyExit::WrongPassword;
                }
            }
            None => return VerifyExit::UserNotFound,
        }
    }

    pub fn get_user(&mut self, username: &str) -> User {
        let res = self
            .pool
            .get_conn()
            .ok()
            .unwrap()
            .query_first(format!(
                "SELECT id, username, password FROM users WHERE username='{un}'",
                un = username
            ))
            //Unpack Result
            .map(|row| {
                //Unpack Option
                row.map(|(id, username, password)| User {
                    id: id,
                    username: username,
                    password: password,
                })
            });

        match res.unwrap() {
            Some(mut user) => {
                println!("User {} found", user.username);
                user.password = "".to_owned();
                return user.clone();
            }
            None => {
                return User {
                    id: -1,
                    username: "".to_owned(),
                    password: "".to_owned(),
                }
            }
        }
    }

    pub fn add_time_entry(&mut self, user_id: i32, hours: i32, date_worked: &str) {
        self.pool
            .get_conn()
            .ok()
            .unwrap()
            .exec_drop(
                "INSERT INTO entries (user_id, hours, date_worked, date_entered) values (:user_id, :hours, :date_worked, CURDATE())",
                params! {
                    "user_id" => user_id,
                    "hours" => hours,
                    "date_worked" => date_worked,
                },
            )
            .unwrap();
    }

    pub fn delete_time_entry(&mut self, id: i32) {
        self.pool
            .get_conn()
            .ok()
            .unwrap()
            .exec_drop(
                "DELETE FROM entries WHERE id=:id",
                params! {
                    "id" => id,
                },
            )
            .unwrap();
    }

    pub fn get_time_entries(&mut self, user_id: i32) -> Vec<TimeEntry> {
        self.pool
            .get_conn()
            .ok()
            .unwrap()
            .query_map(
                format!(
                    "SELECT id, user_id, hours, date_worked, date_entered FROM entries WHERE user_id={uid}",
                    uid = user_id
                ),
                |(id, user_id, hours, date_worked, date_entered)| TimeEntry {
                    id,
                    user_id,
                    hours,
                    date_worked,
                    date_entered,
                },
            )
            .unwrap()
    }

    pub fn get_roles(&mut self) -> Vec<Role> {
        self.pool
            .get_conn()
            .ok()
            .unwrap()
            .query_map("SELECT id, name FROM roles", |(id, name)| Role { id, name })
            .unwrap()
    }

    pub fn get_user_role_pairs(&mut self) -> Vec<UserRole> {
        self.pool
            .get_conn()
            .ok()
            .unwrap()
            .query_map(
                "SELECT user_id, role_id FROM users_roles",
                |(user_id, role_id)| UserRole { user_id, role_id },
            )
            .unwrap()
    }
}
*/