2021-08-20 06:38:03 +00:00
|
|
|
use crate::{
|
2021-09-04 08:53:58 +00:00
|
|
|
entities::{SignInParams, SignUpParams, UpdateUserParams, UserProfile},
|
2021-08-30 14:44:17 +00:00
|
|
|
errors::{ErrorBuilder, ErrorCode, UserError},
|
2021-09-01 08:37:46 +00:00
|
|
|
services::user::{construct_user_server, database::UserDB},
|
2021-08-20 06:38:03 +00:00
|
|
|
sql_tables::{UserTable, UserTableChangeset},
|
|
|
|
};
|
2021-08-29 14:00:42 +00:00
|
|
|
|
2021-09-07 15:30:43 +00:00
|
|
|
use crate::{observable::*, services::server::Server};
|
2021-07-11 07:33:19 +00:00
|
|
|
use flowy_database::{
|
|
|
|
query_dsl::*,
|
|
|
|
schema::{user_table, user_table::dsl},
|
|
|
|
DBConnection,
|
|
|
|
ExpressionMethods,
|
2021-07-13 15:08:20 +00:00
|
|
|
UserDatabaseConnection,
|
2021-07-10 08:27:20 +00:00
|
|
|
};
|
2021-09-03 04:44:48 +00:00
|
|
|
use flowy_infra::kv::KV;
|
2021-08-31 15:01:46 +00:00
|
|
|
use flowy_sqlite::ConnectionPool;
|
2021-09-01 03:21:42 +00:00
|
|
|
use parking_lot::RwLock;
|
|
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
use std::sync::Arc;
|
2021-07-10 08:27:20 +00:00
|
|
|
|
|
|
|
pub struct UserSessionConfig {
|
|
|
|
root_dir: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl UserSessionConfig {
|
|
|
|
pub fn new(root_dir: &str) -> Self {
|
|
|
|
Self {
|
|
|
|
root_dir: root_dir.to_owned(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct UserSession {
|
|
|
|
database: UserDB,
|
|
|
|
config: UserSessionConfig,
|
2021-08-30 08:18:58 +00:00
|
|
|
#[allow(dead_code)]
|
2021-09-01 08:08:32 +00:00
|
|
|
server: Server,
|
2021-09-01 03:21:42 +00:00
|
|
|
session: RwLock<Option<Session>>,
|
2021-07-10 08:27:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl UserSession {
|
2021-08-31 15:01:46 +00:00
|
|
|
pub fn new(config: UserSessionConfig) -> Self {
|
2021-07-10 08:27:20 +00:00
|
|
|
let db = UserDB::new(&config.root_dir);
|
2021-08-31 15:01:46 +00:00
|
|
|
let server = construct_user_server();
|
2021-07-10 08:27:20 +00:00
|
|
|
Self {
|
|
|
|
database: db,
|
|
|
|
config,
|
2021-07-14 15:00:58 +00:00
|
|
|
server,
|
2021-09-01 03:21:42 +00:00
|
|
|
session: RwLock::new(None),
|
2021-07-10 08:27:20 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-05 05:50:23 +00:00
|
|
|
pub fn db_conn(&self) -> Result<DBConnection, UserError> {
|
2021-09-01 03:21:42 +00:00
|
|
|
let user_id = self.get_session()?.user_id;
|
2021-07-16 15:18:12 +00:00
|
|
|
self.database.get_connection(&user_id)
|
|
|
|
}
|
|
|
|
|
2021-09-01 03:21:42 +00:00
|
|
|
// The caller will be not 'Sync' before of the return value,
|
|
|
|
// PooledConnection<ConnectionManager> is not sync. You can use
|
|
|
|
// db_connection_pool function to require the ConnectionPool that is 'Sync'.
|
|
|
|
//
|
|
|
|
// let pool = self.db_connection_pool()?;
|
|
|
|
// let conn: PooledConnection<ConnectionManager> = pool.get()?;
|
2021-09-04 09:26:04 +00:00
|
|
|
pub fn db_pool(&self) -> Result<Arc<ConnectionPool>, UserError> {
|
2021-09-01 03:21:42 +00:00
|
|
|
let user_id = self.get_session()?.user_id;
|
2021-08-31 15:01:46 +00:00
|
|
|
self.database.get_pool(&user_id)
|
|
|
|
}
|
|
|
|
|
2021-09-06 08:18:34 +00:00
|
|
|
#[tracing::instrument(level = "debug", skip(self))]
|
2021-09-04 08:53:58 +00:00
|
|
|
pub async fn sign_in(&self, params: SignInParams) -> Result<UserProfile, UserError> {
|
2021-09-03 08:43:03 +00:00
|
|
|
if self.is_login(¶ms.email) {
|
2021-09-04 08:53:58 +00:00
|
|
|
self.user_profile().await
|
2021-09-03 08:43:03 +00:00
|
|
|
} else {
|
|
|
|
let resp = self.server.sign_in(params).await?;
|
2021-09-08 10:25:32 +00:00
|
|
|
let session = Session::new(&resp.user_id, &resp.token, &resp.email);
|
2021-09-03 08:43:03 +00:00
|
|
|
let _ = self.set_session(Some(session))?;
|
|
|
|
let user_table = self.save_user(resp.into()).await?;
|
2021-09-04 08:53:58 +00:00
|
|
|
let user_profile = UserProfile::from(user_table);
|
|
|
|
Ok(user_profile)
|
2021-09-03 08:43:03 +00:00
|
|
|
}
|
2021-07-11 07:33:19 +00:00
|
|
|
}
|
|
|
|
|
2021-09-06 08:18:34 +00:00
|
|
|
#[tracing::instrument(level = "debug", skip(self))]
|
2021-09-04 08:53:58 +00:00
|
|
|
pub async fn sign_up(&self, params: SignUpParams) -> Result<UserProfile, UserError> {
|
2021-09-04 01:00:15 +00:00
|
|
|
if self.is_login(¶ms.email) {
|
2021-09-04 08:53:58 +00:00
|
|
|
self.user_profile().await
|
2021-09-04 01:00:15 +00:00
|
|
|
} else {
|
|
|
|
let resp = self.server.sign_up(params).await?;
|
|
|
|
let session = Session::new(&resp.user_id, &resp.token, &resp.email);
|
|
|
|
let _ = self.set_session(Some(session))?;
|
|
|
|
let user_table = self.save_user(resp.into()).await?;
|
2021-09-04 08:53:58 +00:00
|
|
|
let user_profile = UserProfile::from(user_table);
|
|
|
|
Ok(user_profile)
|
2021-09-04 01:00:15 +00:00
|
|
|
}
|
2021-07-11 07:33:19 +00:00
|
|
|
}
|
|
|
|
|
2021-09-06 08:18:34 +00:00
|
|
|
#[tracing::instrument(level = "debug", skip(self))]
|
2021-08-31 09:25:08 +00:00
|
|
|
pub async fn sign_out(&self) -> Result<(), UserError> {
|
2021-09-01 08:08:32 +00:00
|
|
|
let session = self.get_session()?;
|
2021-09-05 05:50:23 +00:00
|
|
|
let _ = diesel::delete(dsl::user_table.filter(dsl::id.eq(&session.user_id))).execute(&*(self.db_conn()?))?;
|
2021-09-01 08:08:32 +00:00
|
|
|
let _ = self.database.close_user_db(&session.user_id)?;
|
2021-09-01 03:21:42 +00:00
|
|
|
let _ = self.set_session(None)?;
|
2021-09-04 09:26:04 +00:00
|
|
|
let _ = self.sign_out_on_server(&session.token).await?;
|
2021-07-11 09:38:03 +00:00
|
|
|
|
|
|
|
Ok(())
|
2021-07-11 07:33:19 +00:00
|
|
|
}
|
|
|
|
|
2021-09-06 08:18:34 +00:00
|
|
|
#[tracing::instrument(level = "debug", skip(self))]
|
2021-08-31 15:01:46 +00:00
|
|
|
pub async fn update_user(&self, params: UpdateUserParams) -> Result<(), UserError> {
|
2021-09-01 09:57:06 +00:00
|
|
|
let session = self.get_session()?;
|
2021-09-04 09:26:04 +00:00
|
|
|
let changeset = UserTableChangeset::new(params.clone());
|
2021-09-07 09:12:03 +00:00
|
|
|
diesel_update_table!(user_table, changeset, &*self.db_conn()?);
|
2021-09-01 09:57:06 +00:00
|
|
|
|
2021-09-04 09:26:04 +00:00
|
|
|
let _ = self.update_user_on_server(&session.token, params).await?;
|
2021-08-31 15:01:46 +00:00
|
|
|
Ok(())
|
2021-07-14 13:12:52 +00:00
|
|
|
}
|
|
|
|
|
2021-09-04 08:53:58 +00:00
|
|
|
pub async fn user_profile(&self) -> Result<UserProfile, UserError> {
|
2021-09-07 15:30:43 +00:00
|
|
|
let (user_id, token) = self.get_session()?.into_part();
|
2021-09-01 08:37:46 +00:00
|
|
|
let user = dsl::user_table
|
2021-09-07 15:30:43 +00:00
|
|
|
.filter(user_table::id.eq(&user_id))
|
2021-09-05 05:50:23 +00:00
|
|
|
.first::<UserTable>(&*(self.db_conn()?))?;
|
2021-09-01 08:37:46 +00:00
|
|
|
|
2021-09-08 10:25:32 +00:00
|
|
|
let _ = self.read_user_profile_on_server(&token).await?;
|
2021-09-04 08:53:58 +00:00
|
|
|
Ok(UserProfile::from(user))
|
2021-07-11 07:33:19 +00:00
|
|
|
}
|
2021-07-10 08:27:20 +00:00
|
|
|
|
2021-08-29 14:00:42 +00:00
|
|
|
pub fn user_dir(&self) -> Result<String, UserError> {
|
2021-09-01 03:21:42 +00:00
|
|
|
let session = self.get_session()?;
|
|
|
|
Ok(format!("{}/{}", self.config.root_dir, session.user_id))
|
2021-07-23 09:30:33 +00:00
|
|
|
}
|
|
|
|
|
2021-09-01 08:08:32 +00:00
|
|
|
pub fn user_id(&self) -> Result<String, UserError> { Ok(self.get_session()?.user_id) }
|
|
|
|
|
2021-09-01 14:50:22 +00:00
|
|
|
pub fn token(&self) -> Result<String, UserError> { Ok(self.get_session()?.token) }
|
2021-09-01 08:08:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl UserSession {
|
2021-09-08 10:25:32 +00:00
|
|
|
async fn read_user_profile_on_server(&self, token: &str) -> Result<(), UserError> {
|
2021-09-04 09:26:04 +00:00
|
|
|
let server = self.server.clone();
|
|
|
|
let token = token.to_owned();
|
2021-09-07 15:30:43 +00:00
|
|
|
tokio::spawn(async move {
|
2021-09-04 09:26:04 +00:00
|
|
|
match server.get_user(&token).await {
|
|
|
|
Ok(profile) => {
|
2021-09-08 10:25:32 +00:00
|
|
|
observable(&token, UserObservable::UserProfileUpdated).payload(profile).build();
|
2021-09-04 09:26:04 +00:00
|
|
|
},
|
|
|
|
Err(e) => {
|
2021-09-07 15:30:43 +00:00
|
|
|
log::error!("{:?}", e);
|
2021-09-08 10:25:32 +00:00
|
|
|
observable(&token, UserObservable::UserProfileUpdated).error(e).build();
|
2021-09-04 09:26:04 +00:00
|
|
|
},
|
|
|
|
}
|
|
|
|
});
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn update_user_on_server(&self, token: &str, params: UpdateUserParams) -> Result<(), UserError> {
|
|
|
|
let server = self.server.clone();
|
|
|
|
let token = token.to_owned();
|
2021-09-06 08:18:34 +00:00
|
|
|
let _ = tokio::spawn(async move {
|
2021-09-04 09:26:04 +00:00
|
|
|
match server.update_user(&token, params).await {
|
|
|
|
Ok(_) => {},
|
|
|
|
Err(e) => {
|
|
|
|
// TODO: retry?
|
|
|
|
log::error!("update user profile failed: {:?}", e);
|
|
|
|
},
|
|
|
|
}
|
2021-09-05 05:50:23 +00:00
|
|
|
})
|
|
|
|
.await;
|
2021-09-04 09:26:04 +00:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn sign_out_on_server(&self, token: &str) -> Result<(), UserError> {
|
|
|
|
let server = self.server.clone();
|
|
|
|
let token = token.to_owned();
|
2021-09-06 08:18:34 +00:00
|
|
|
let _ = tokio::spawn(async move {
|
2021-09-04 09:26:04 +00:00
|
|
|
match server.sign_out(&token).await {
|
|
|
|
Ok(_) => {},
|
|
|
|
Err(e) => log::error!("Sign out failed: {:?}", e),
|
|
|
|
}
|
2021-09-05 05:50:23 +00:00
|
|
|
})
|
|
|
|
.await;
|
2021-09-04 09:26:04 +00:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2021-09-01 08:08:32 +00:00
|
|
|
async fn save_user(&self, user: UserTable) -> Result<UserTable, UserError> {
|
2021-09-05 05:50:23 +00:00
|
|
|
let conn = self.db_conn()?;
|
2021-09-02 06:47:39 +00:00
|
|
|
let _ = diesel::insert_into(user_table::table).values(user.clone()).execute(&*conn)?;
|
2021-09-01 08:08:32 +00:00
|
|
|
Ok(user)
|
|
|
|
}
|
|
|
|
|
2021-09-01 03:21:42 +00:00
|
|
|
fn set_session(&self, session: Option<Session>) -> Result<(), UserError> {
|
2021-09-07 15:30:43 +00:00
|
|
|
log::debug!("Set user session: {:?}", session);
|
2021-09-01 03:21:42 +00:00
|
|
|
match &session {
|
2021-09-08 05:50:20 +00:00
|
|
|
None => KV::remove(SESSION_CACHE_KEY).map_err(|e| UserError::new(ErrorCode::InternalError, &e))?,
|
2021-09-03 04:44:48 +00:00
|
|
|
Some(session) => KV::set_str(SESSION_CACHE_KEY, session.clone().into()),
|
2021-09-01 03:21:42 +00:00
|
|
|
}
|
2021-09-03 04:44:48 +00:00
|
|
|
*self.session.write() = session;
|
2021-09-01 03:21:42 +00:00
|
|
|
Ok(())
|
|
|
|
}
|
2021-09-03 08:43:03 +00:00
|
|
|
|
2021-09-01 03:21:42 +00:00
|
|
|
fn get_session(&self) -> Result<Session, UserError> {
|
2021-09-03 04:44:48 +00:00
|
|
|
let mut session = { (*self.session.read()).clone() };
|
2021-09-01 03:21:42 +00:00
|
|
|
if session.is_none() {
|
2021-09-03 04:44:48 +00:00
|
|
|
match KV::get_str(SESSION_CACHE_KEY) {
|
2021-09-01 03:21:42 +00:00
|
|
|
None => {},
|
|
|
|
Some(s) => {
|
|
|
|
session = Some(Session::from(s));
|
|
|
|
let _ = self.set_session(session.clone())?;
|
|
|
|
},
|
|
|
|
}
|
2021-07-18 15:56:36 +00:00
|
|
|
}
|
|
|
|
|
2021-09-01 03:21:42 +00:00
|
|
|
match session {
|
2021-09-08 05:50:20 +00:00
|
|
|
None => Err(ErrorBuilder::new(ErrorCode::UserUnauthorized).build()),
|
2021-09-01 03:21:42 +00:00
|
|
|
Some(session) => Ok(session),
|
2021-07-18 15:56:36 +00:00
|
|
|
}
|
|
|
|
}
|
2021-09-03 08:43:03 +00:00
|
|
|
|
|
|
|
fn is_login(&self, email: &str) -> bool {
|
|
|
|
match self.get_session() {
|
|
|
|
Ok(session) => session.email == email,
|
|
|
|
Err(_) => false,
|
|
|
|
}
|
|
|
|
}
|
2021-08-31 15:01:46 +00:00
|
|
|
}
|
|
|
|
|
2021-09-02 06:47:39 +00:00
|
|
|
pub async fn update_user(_server: Server, pool: Arc<ConnectionPool>, params: UpdateUserParams) -> Result<(), UserError> {
|
2021-08-31 15:01:46 +00:00
|
|
|
let changeset = UserTableChangeset::new(params);
|
|
|
|
let conn = pool.get()?;
|
2021-09-07 09:12:03 +00:00
|
|
|
diesel_update_table!(user_table, changeset, &*conn);
|
2021-08-31 15:01:46 +00:00
|
|
|
Ok(())
|
2021-07-16 15:18:12 +00:00
|
|
|
}
|
2021-07-11 09:38:03 +00:00
|
|
|
|
2021-07-13 15:08:20 +00:00
|
|
|
impl UserDatabaseConnection for UserSession {
|
2021-09-05 05:50:23 +00:00
|
|
|
fn get_connection(&self) -> Result<DBConnection, String> { self.db_conn().map_err(|e| format!("{:?}", e)) }
|
2021-07-13 15:08:20 +00:00
|
|
|
}
|
|
|
|
|
2021-09-01 03:21:42 +00:00
|
|
|
const SESSION_CACHE_KEY: &str = "session_cache_key";
|
|
|
|
|
|
|
|
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
|
|
|
struct Session {
|
|
|
|
user_id: String,
|
|
|
|
token: String,
|
2021-09-03 08:43:03 +00:00
|
|
|
email: String,
|
2021-09-01 03:21:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Session {
|
2021-09-03 08:43:03 +00:00
|
|
|
pub fn new(user_id: &str, token: &str, email: &str) -> Self {
|
2021-09-01 03:21:42 +00:00
|
|
|
Self {
|
|
|
|
user_id: user_id.to_owned(),
|
|
|
|
token: token.to_owned(),
|
2021-09-03 08:43:03 +00:00
|
|
|
email: email.to_owned(),
|
2021-09-01 03:21:42 +00:00
|
|
|
}
|
|
|
|
}
|
2021-09-07 15:30:43 +00:00
|
|
|
|
2021-09-08 05:50:20 +00:00
|
|
|
pub fn into_part(self) -> (String, String) { (self.user_id, self.token) }
|
2021-09-01 03:21:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl std::convert::From<String> for Session {
|
|
|
|
fn from(s: String) -> Self {
|
|
|
|
match serde_json::from_str(&s) {
|
|
|
|
Ok(s) => s,
|
|
|
|
Err(e) => {
|
2021-09-01 08:08:32 +00:00
|
|
|
log::error!("Deserialize string to Session failed: {:?}", e);
|
2021-09-01 03:21:42 +00:00
|
|
|
Session::default()
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl std::convert::Into<String> for Session {
|
|
|
|
fn into(self) -> String {
|
|
|
|
match serde_json::to_string(&self) {
|
|
|
|
Ok(s) => s,
|
|
|
|
Err(e) => {
|
2021-09-01 08:08:32 +00:00
|
|
|
log::error!("Serialize session to string failed: {:?}", e);
|
2021-09-01 03:21:42 +00:00
|
|
|
"".to_string()
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|