feat: added add user by email

This commit is contained in:
Fu Zi Xiang 2023-10-11 17:47:34 +08:00
parent 66ac3adb16
commit bf6f010b90
No known key found for this signature in database
GPG Key ID: 7AE0884D237CEE16
9 changed files with 70 additions and 21 deletions

1
Cargo.lock generated
View File

@ -344,6 +344,7 @@ dependencies = [
"tower-http",
"tower-service",
"tracing",
"tracing-subscriber",
"uuid",
]

View File

@ -25,3 +25,4 @@ tower-service = "0.3.2"
tower-http = { version = "0.4.4", features = ["cors"] }
tower = "0.4.13"
tracing = "0.1.37"
tracing-subscriber = { version = "0.3.17", features = ["env-filter"] }

View File

@ -1,2 +1,3 @@
GOTRUE_URL=http://localhost:9998
REDIS_URL=redis://localhost:6380
RUST_LOG=trace

View File

@ -16,6 +16,11 @@ async fn main() {
// load from .env
dotenv::dotenv().ok();
// set up tracing
tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.init();
let gotrue_client = gotrue::api::Client::new(
reqwest::Client::new(),
&std::env::var("GOTRUE_URL").unwrap_or("http://gotrue:9999".to_string()),

View File

@ -6,6 +6,11 @@ pub struct LoginRequest {
pub password: String,
}
#[derive(Deserialize)]
pub struct AddUserRequest {
pub email: String,
}
#[derive(Serialize)]
pub struct LoginResponse {
pub access_token: String,

View File

@ -31,3 +31,12 @@ where
Json(self).into_response()
}
}
impl<T> From<T> for WebApiResponse<T>
where
T: serde::Serialize,
{
fn from(data: T) -> Self {
Self::new(data)
}
}

View File

@ -1,5 +1,7 @@
use crate::error::WebApiError;
use crate::session;
use crate::models::AddUserRequest;
use crate::response::WebApiResponse;
use crate::session::{self, UserSession};
use crate::{models::LoginRequest, AppState};
use axum::http::status;
use axum::response::Result;
@ -7,12 +9,31 @@ use axum::Json;
use axum::{extract::State, routing::post, Router};
use axum_extra::extract::cookie::Cookie;
use axum_extra::extract::CookieJar;
use gotrue::params::AdminUserParams;
use gotrue_entity::User;
pub fn router() -> Router<AppState> {
Router::new()
// TODO
.route("/login", post(login_handler))
.route("/logout", post(logout_handler))
.route("/add_user", post(add_user_handler))
}
pub async fn add_user_handler(
State(state): State<AppState>,
session: UserSession,
Json(param): Json<AddUserRequest>,
) -> Result<WebApiResponse<User>, WebApiError<'static>> {
let add_user_params = AdminUserParams {
email: param.email.to_owned(),
..Default::default()
};
let user = state
.gotrue_client
.admin_add_user(&session.access_token, &add_user_params)
.await?;
Ok(user.into())
}
// TODO: Support OAuth2 login

View File

@ -29,26 +29,32 @@
document.getElementById('createUserBtn').addEventListener('click', function() {
// Get the email from the user
const email = prompt('Please enter the new user email:');
// TODO: Validate the email, if valid, send to server and update UI
if (email) {
// Assuming you will use fetch API or another method to send the data to the server
// Example:
// fetch('/createUser', {
// method: 'POST',
// body: JSON.stringify({ email: email }),
// headers: {
// 'Content-Type': 'application/json',
// }
// })
// .then(response => response.json())
// .then(data => {
// // Update the UI as needed, e.g., add a new row to the table
// console.log('User created:', data);
// })
// .catch((error) => {
// console.error('Error:', error);
// });
fetch("/web-api/add_user", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: email,
}),
})
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok' + response.statusText);
}
return response.json();
})
.then((data) => {
if (data.code === 0) {
window.location.href = "/web/admin/users/" + data.data.id;
} else {
throw new Error('Error creating user: ' + data.message);
}
})
.catch((error) => {
console.error("Error:", error);
});
}
});
</script>

View File

@ -3,7 +3,7 @@ use std::collections::btree_map::BTreeMap;
use gotrue_entity::{Factor, Identity};
use serde::{Deserialize, Serialize};
#[derive(Default, Deserialize, Serialize)]
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct AdminUserParams {
pub aud: String,
pub role: String,