users and passwords

This commit is contained in:
ntr 2018-09-13 20:00:21 +10:00
parent 2996082209
commit 9fe0caeab5
4 changed files with 50 additions and 13 deletions

View File

@ -7,7 +7,7 @@ ws.binaryType = 'arraybuffer';
// Connection opened
ws.addEventListener('open', function (event) {
ws.send(cbor.encode({ method: 'cryp_generate', params: { level: 64 }}));
ws.send(cbor.encode({ method: 'account_create', params: { name: 'ntr' }}));
ws.send(cbor.encode({ method: 'account_create', params: { name: 'ntr', password: 'grep' }}));
});
// Listen for messages

View File

@ -26,9 +26,17 @@ impl Handler for Server {
fn on_message(&mut self, msg: Message) -> Result<()> {
let db = self.db.get().expect("unable to get db connection");
let reply = self.rpc.receive(msg, db);
println!("{:?}", reply);
self.out.send(reply.unwrap())
match self.rpc.receive(msg, db) {
Ok(reply) => {
println!("{:?}", reply);
self.out.send(reply)
},
Err(_e) => {
let response = to_vec(&"there was an error")
.expect("failed to serialize error response");
self.out.send(response)
}
}
}
fn on_close(&mut self, code: CloseCode, reason: &str) {

View File

@ -23,20 +23,20 @@ impl Rpc {
"cryp_generate" => {
match from_slice::<GenerateMsg>(&data) {
Ok(v) => Ok(generate(v.params)),
Err(_) => Err(RpcError::Parse),
Err(e) => Err(RpcError::Parse),
}
},
"account_create" => {
match from_slice::<AccountCreateMsg>(&data) {
Ok(v) => Ok(create(v.params, db)),
Err(_) => Err(RpcError::Parse),
Err(e) => Err(RpcError::Parse),
}
},
_ => Err(RpcError::UnknownMethod),
}
},
Err(_) => Err(RpcError::Parse),
Err(e) => Err(RpcError::Parse),
}
}
}

View File

@ -1,5 +1,11 @@
use serde_cbor::to_vec;
use uuid::Uuid;
use bcrypt::{DEFAULT_COST, hash};
use rand::{thread_rng, Rng};
use rand::distributions::Alphanumeric;
use std::iter;
use std::str;
use net::Db;
use rpc::{AccountCreateParams};
@ -8,27 +14,50 @@ use rpc::{AccountCreateParams};
struct User {
id: Uuid,
name: String,
token: String,
}
struct UserEntry {
id: Uuid,
name: String,
password: String,
token: String,
}
pub fn create(params: AccountCreateParams, db: Db) -> Vec<u8> {
let id = Uuid::new_v4();
let user = User {
let password = hash(&params.password, DEFAULT_COST)
.expect("unable to hash password");
let mut rng = thread_rng();
let token: String = iter::repeat(())
.map(|()| rng.sample(Alphanumeric))
.take(64)
.collect();
let user = UserEntry {
name: params.name,
id,
name: "heeeya".to_string(),
password,
token,
};
let query = "
INSERT INTO users (id, name)
VALUES ($1, $2)
RETURNING *;
INSERT INTO users (id, name, password, token)
VALUES ($1, $2, $3, $4)
RETURNING id, name, token;
";
let result = db.query(query, &[&user.id, &user.name]).expect("user insert failed");
let result = db
.query(query, &[&user.id, &user.name, &user.password, &user.token])
.expect("user insert failed");
let returned = result.iter().next().expect("no row returned");
let entry = User {
id: returned.get(0),
name: returned.get(1),
token: returned.get(2),
};
println!("{:?}", entry);