store user info after login

Signed-off-by: fufesou <shuanglongchen@yeah.net>
This commit is contained in:
fufesou 2023-06-21 23:58:13 +08:00
parent 23389ef140
commit 8dd218235d
5 changed files with 54 additions and 9 deletions

View File

@ -14,6 +14,8 @@ class HttpType {
static const kAuthResTypeEmailCheck = "email_check"; static const kAuthResTypeEmailCheck = "email_check";
} }
// to-do: The UserPayload does not contain all the fields of the user.
// Is all the fields of the user needed?
class UserPayload { class UserPayload {
String id = ''; String id = '';
String name = ''; String name = '';
@ -29,6 +31,16 @@ class UserPayload {
note = json['note'] ?? '', note = json['note'] ?? '',
status = json['status'], status = json['status'],
isAdmin = json['is_admin'] == true; isAdmin = json['is_admin'] == true;
Map<String, dynamic> toJson() {
final Map<String, dynamic> map = {
'name': name,
};
if (status != null) {
map['status'] = status!;
}
return map;
}
} }
class PeerPayload { class PeerPayload {

View File

@ -424,6 +424,8 @@ Future<bool?> loginDialog() async {
if (resp.access_token != null) { if (resp.access_token != null) {
await bind.mainSetLocalOption( await bind.mainSetLocalOption(
key: 'access_token', value: resp.access_token!); key: 'access_token', value: resp.access_token!);
await bind.mainSetLocalOption(
key: 'user_info', value: jsonEncode(resp.user ?? {}));
close(true); close(true);
return; return;
} }
@ -482,12 +484,8 @@ Future<bool?> loginDialog() async {
curOP: curOP, curOP: curOP,
cbLogin: (Map<String, dynamic> authBody) { cbLogin: (Map<String, dynamic> authBody) {
try { try {
final loginResp = // access_token is already stored in the rust side.
gFFI.userModel.getLoginResponseFromAuthBody(authBody); gFFI.userModel.getLoginResponseFromAuthBody(authBody);
if (loginResp.access_token != null) {
bind.mainSetLocalOption(
key: 'access_token', value: loginResp.access_token!);
}
} catch (e) { } catch (e) {
debugPrint('Failed too parse oidc login body: "$authBody"'); debugPrint('Failed too parse oidc login body: "$authBody"');
} }

View File

@ -75,6 +75,7 @@ class UserModel {
Future<void> reset() async { Future<void> reset() async {
await bind.mainSetLocalOption(key: 'access_token', value: ''); await bind.mainSetLocalOption(key: 'access_token', value: '');
await bind.mainSetLocalOption(key: 'user_info', value: '');
await gFFI.abModel.reset(); await gFFI.abModel.reset();
await gFFI.groupModel.reset(); await gFFI.groupModel.reset();
userName.value = ''; userName.value = '';

View File

@ -4,6 +4,7 @@ use hbb_common::{
log, ResultType, log, ResultType,
}; };
use reqwest::blocking::Client; use reqwest::blocking::Client;
use serde::ser::SerializeStruct;
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};
use serde_repr::{Deserialize_repr, Serialize_repr}; use serde_repr::{Deserialize_repr, Serialize_repr};
use std::{ use std::{
@ -90,7 +91,7 @@ pub enum UserRole {
Member = 0, Member = 0,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Deserialize)]
pub struct UserPayload { pub struct UserPayload {
pub name: String, pub name: String,
pub email: Option<String>, pub email: Option<String>,
@ -99,6 +100,9 @@ pub struct UserPayload {
pub info: UserInfo, pub info: UserInfo,
pub role: UserRole, pub role: UserRole,
pub is_admin: bool, pub is_admin: bool,
// helper field for serialize
#[serde(default)]
pub ser_store_local: bool,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
@ -127,6 +131,30 @@ pub struct AuthResult {
pub auth_body: Option<AuthBody>, pub auth_body: Option<AuthBody>,
} }
impl serde::Serialize for UserPayload {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
if self.ser_store_local {
let mut state = serializer.serialize_struct("UserPayload", 1)?;
state.serialize_field("name", &self.name)?;
state.serialize_field("status", &self.status)?;
state.end()
} else {
let mut state = serializer.serialize_struct("UserPayload", 7)?;
state.serialize_field("name", &self.name)?;
state.serialize_field("email", &self.email)?;
state.serialize_field("note", &self.note)?;
state.serialize_field("status", &self.status)?;
state.serialize_field("info", &self.info)?;
state.serialize_field("role", &self.role)?;
state.serialize_field("is_admin", &self.is_admin)?;
state.end()
}
}
}
impl OidcSession { impl OidcSession {
fn new() -> Self { fn new() -> Self {
Self { Self {
@ -226,16 +254,18 @@ impl OidcSession {
let query_timeout = OIDC_SESSION.read().unwrap().query_timeout; let query_timeout = OIDC_SESSION.read().unwrap().query_timeout;
while OIDC_SESSION.read().unwrap().keep_querying && begin.elapsed() < query_timeout { while OIDC_SESSION.read().unwrap().keep_querying && begin.elapsed() < query_timeout {
match Self::query(&code_url.code, &id, &uuid) { match Self::query(&code_url.code, &id, &uuid) {
Ok(HbbHttpResponse::<_>::Data(auth_body)) => { Ok(HbbHttpResponse::<_>::Data(mut auth_body)) => {
if remember_me { if remember_me {
LocalConfig::set_option( LocalConfig::set_option(
"access_token".to_owned(), "access_token".to_owned(),
auth_body.access_token.clone(), auth_body.access_token.clone(),
); );
auth_body.user.ser_store_local = true;
LocalConfig::set_option( LocalConfig::set_option(
"user_info".to_owned(), "user_info".to_owned(),
serde_json::to_string(&auth_body.user).unwrap_or_default(), serde_json::to_string(&auth_body.user).unwrap_or_default(),
); );
auth_body.user.ser_store_local = false;
} }
OIDC_SESSION OIDC_SESSION
.write() .write()

View File

@ -822,7 +822,11 @@ pub fn account_auth_cancel() {
#[cfg(feature = "flutter")] #[cfg(feature = "flutter")]
pub fn account_auth_result() -> String { pub fn account_auth_result() -> String {
serde_json::to_string(&account::OidcSession::get_result()).unwrap_or_default() let mut auth_result = account::OidcSession::get_result();
if let Some(auth) = auth_result.auth_body.as_mut() {
auth.user.ser_store_local = false;
}
serde_json::to_string(&auth_result).unwrap_or_default()
} }
#[cfg(feature = "flutter")] #[cfg(feature = "flutter")]