postgres=# INSERT INTO users (username, password) VALUES (‘hpscript’, ‘$2b$08$bKVELv/My0WaKvoyTltoLe3pOp7VJ4UxtxuA3C5qurnAblnqXbcfi’);
INSERT 0 1
postgres=# select * from users;
id | username | password
—-+———-+————————————————————–
1 | hpscript | $2b$08$bKVELv/My0WaKvoyTltoLe3pOp7VJ4UxtxuA3C5qurnAblnqXbcfi
DBに入っているパスワードハッシュ値と、Postされてきたpasswordの一致を検証する。
asyncでpsqlを使う場合は、postgresではなく、tokio_postgres出ないとエラーになる。
参考: https://docs.rs/tokio-postgres/latest/tokio_postgres/
async fn handle_signup(form: Form<SignUp>)-> axum::response::Html<String> {
let signup: SignUp = form.0;
let hash = db_check(&signup.username.to_string()).await.unwrap();
println!("{}", &hash);
let password = &signup.password;
println!("{}", verify(password, &hash));
println!("{:?}", signup);
// 省略
}
fn verify(password: &String, hash: &String) -> bool {
bcrypt::verify(password, hash)
}
async fn db_check(name: &String) -> Result<String, Box<dyn std::error::Error>> {
let (client, connection) = tokio_postgres::connect("host=localhost user=postgres password=password", NoTls).await?;
tokio::spawn(async move {
if let Err(e) = connection.await {
eprintln!("connection error: {}", e);
}
});
let row = client.query("SELECT * From users where username=$1", &[&name]).await?;
let hash: String = row[0].get(2);
println!("{}",hash);
Ok(hash)
}
Finished `dev` profile [unoptimized + debuginfo] target(s) in 3.44s
Running `target/debug/login`
$2b$08$bKVELv/My0WaKvoyTltoLe3pOp7VJ4UxtxuA3C5qurnAblnqXbcfi
$2b$08$bKVELv/My0WaKvoyTltoLe3pOp7VJ4UxtxuA3C5qurnAblnqXbcfi
true
SignUp { username: “hpscript”, password: “asdf1234” }
よしよしよーし。セッションは後からやるとして、先にpsqlへのinsertとregister画面から作ります。