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
|
use crate::models::{Customer, NewCustomer, Rating, Transaction};
use crate::schema::customer::dsl::*;
use crate::schema::rating::dsl as rs;
use crate::schema::transaction::dsl as ts;
use crate::TPool;
use actix_identity::Identity;
use actix_web::{web, HttpResponse, Responder};
use bcrypt::{hash, verify, DEFAULT_COST};
use diesel::prelude::*;
use log::{error, info};
use serde::{Deserialize, Serialize};
pub async fn new_user(
pool: web::Data<TPool>,
item: web::Json<NewCustomer>,
) -> impl Responder {
info!("Creating ... {:?}", item.username);
let conn = pool.get().unwrap();
let hashed_item = NewCustomer {
password: hash(&item.password, DEFAULT_COST).unwrap(),
..(item.into_inner())
};
diesel::insert_into(customer)
.values(hashed_item)
.execute(&conn)
.expect("Coundn't connect to DB");
HttpResponse::Ok().body("Inserted successfully!")
}
pub async fn name_exists(
pool: web::Data<TPool>,
item: String,
) -> impl Responder {
let conn = pool.get().unwrap();
info!("target: {:?}", item);
if (customer
.filter(username.eq(&item))
.limit(1)
.load::<Customer>(&conn)
.expect("Coundn't connect to DB"))
.len()
> 0
{
HttpResponse::Ok().body("true")
} else {
HttpResponse::Ok().body("false")
}
}
#[derive(Deserialize)]
pub struct Login {
username: String,
password: String,
}
pub async fn login(
pool: web::Data<TPool>,
cookie: Identity,
login_details: web::Json<Login>,
) -> impl Responder {
info!("Login hit");
if cookie.identity().is_some() {
info!("Found existing cookie: {:?}", cookie.identity());
return HttpResponse::Ok().finish();
}
let conn = pool.get().unwrap();
let entered_pass = &login_details.password;
let selected_user = customer
.filter(username.eq(&login_details.username))
.limit(1)
.first::<Customer>(&conn)
.expect("Couldn't connect to DB");
let hashed_pass = selected_user.password;
if verify(entered_pass, &hashed_pass).unwrap() {
cookie.remember(login_details.username.clone());
info!(
"Successful login: {} {}",
selected_user.username, selected_user.email_id
);
HttpResponse::Ok().finish()
} else {
HttpResponse::Unauthorized().finish()
}
}
pub async fn logout(cookie: Identity) -> impl Responder {
cookie.forget();
HttpResponse::Ok().body("Successful logout.")
}
pub async fn user_details(
uname: web::Path<String>,
pool: web::Data<TPool>,
) -> impl Responder {
let conn = pool.get().unwrap();
let uname = uname.into_inner();
info!("Fetching info for: \"{}\"", uname);
let selected_user = customer
.filter(username.eq(&uname))
.limit(1)
.first::<Customer>(&conn);
match selected_user {
Ok(m) => {
info!("Found user: {}", uname);
HttpResponse::Ok().json(m)
}
Err(_) => {
error!("User not found: {}", uname);
HttpResponse::NotFound().finish()
}
}
}
#[derive(Deserialize, Debug)]
pub struct ChangePassword {
old_password: String,
new_password: String,
}
pub async fn change_password(
cookie: Identity,
password_details: web::Json<ChangePassword>,
pool: web::Data<TPool>,
) -> impl Responder {
info!("Change password request: {:?}", password_details);
let conn = pool.get().unwrap();
if let Some(uname) = cookie.identity() {
let entered_pass = &password_details.old_password;
let new_password = &password_details.new_password;
let selected_user = customer
.filter(username.eq(&uname))
.limit(1)
.first::<Customer>(&conn)
.expect("Couldn't connect to DB");
let hashed_pass = selected_user.password;
if verify(entered_pass, &hashed_pass).unwrap() {
let hashed_new_password =
hash(&new_password, DEFAULT_COST).unwrap();
diesel::update(customer.filter(id.eq(selected_user.id)))
.set(password.eq(hashed_new_password))
.execute(&conn)
.unwrap();
return HttpResponse::Ok().body("Changed password successfully");
} else {
return HttpResponse::Ok().body("Invalid password");
}
}
return HttpResponse::Unauthorized().body("Login first");
}
#[derive(Serialize)]
struct UserProfile {
pub username: String,
pub email_id: String,
pub address: Option<String>,
pub transactions: Vec<Transaction>,
pub ratings_given: i32,
pub phone_number: String,
}
pub async fn user_profile(
cookie: Identity,
pool: web::Data<TPool>,
) -> impl Responder {
info!("Fetching user profile for {:?}", cookie.identity());
let conn = pool.get().unwrap();
if let Some(uname) = cookie.identity() {
let selected_user = customer
.filter(username.eq(&uname))
.limit(1)
.first::<Customer>(&conn)
.expect("Couldn't connect to DB");
let user_transactions = ts::transaction
.filter(ts::customer_id.eq(selected_user.id))
.load(&conn)
.expect("Couldn't connect to DB");
let user_ratings = rs::rating
.filter(rs::customer_id.eq(selected_user.id))
.load::<Rating>(&conn)
.expect("Couldn't connect to DB")
.len() as i32;
let profile = UserProfile {
username: selected_user.username,
email_id: selected_user.email_id,
address: selected_user.address,
transactions: user_transactions,
ratings_given: user_ratings,
phone_number: selected_user.phone_number,
};
return HttpResponse::Ok().json(&profile);
} else {
return HttpResponse::Unauthorized()
.body("Need to be logged in to view profile!");
}
}
|