-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtoken.rs
1554 lines (1432 loc) · 82.6 KB
/
token.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::HashMap;
use std::fs;
use std::thread;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use std::path::{Path, PathBuf};
use serde_json::{self, json};
use base58::{ToBase58, FromBase58};
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine;
use tracing::{error, warn, info, debug, trace};
use tracing_subscriber::EnvFilter;
use qrcode::{QrCode, Version, EcLevel};
use qrcode::render::svg;
use pyo3::prelude::*;
use crate::token_utils;
use crate::{exchange_key, issue_key};
use crate::error::TokenError;
use crate::env_data::EnvData;
use crate::claims::{GlobalClaims, IdClaim, UserContext};
use crate::systeminfo::SystemInfo;
use crate::cert_center::GlobalCerts;
pub(crate) static TOKEN_API_VERSION: &str = "v1.1.1";
#[derive(Clone, Debug)]
#[pyclass]
pub struct SimpleAI {
pub sys_name: String,
pub did: String,
token_db: Arc<Mutex<sled::Db>>,
// 用户绑定授权的缓存,来自user_{did}.token
pub authorized: Arc<Mutex<sled::Tree>>, //HashMap<String, UserContext>,
pub user_sessions: Arc<Mutex<sled::Tree>>, //HashMap<sessionid_key, String>,
pub sysinfo: SystemInfo,
// 留存本地的身份自证, 用根密钥签
claims: Arc<Mutex<GlobalClaims>>,
// 专项密钥,源自pk.pem的派生,避免交互时对phrase的依赖,key={did}_{用途},value={key}|{time}|{sig}, 用途=['exchange', 'issue']
crypt_secrets: HashMap<String, String>,
// 授权给本系统的他证, key={issue_did}|{for_did}|{用途},value={encrypted_key}|{memo}|{time}|{sig},
// encrypted_key由for_did交换派生密钥加密, sig由证书密钥签,用途=['Member']
certificates: Arc<Mutex<GlobalCerts>>, // HashMap<String, String>,
// 颁发的certificate,key={issue_did}|{for_did}|{用途},value=encrypt_with_for_sys_did({issue_did}|{for_did}|{用途}|{encrypted_key}|{memo}|{time}|{sig})
// encrypted_key由for_did交换派生密钥加密, sig由证书密钥签, 整体由接受系统did的交换派生密钥加密
// issued_certs: HashMap<String, String>,
admin: String,
device: String,
guest: String,
guest_phrase: String,
ready_users: Arc<Mutex<sled::Tree>>, //HashMap<String, serde_json::Value>,
blacklist: Vec<String>, // 黑名单
upstream_did: String,
user_base_dir: String,
global_local_vars: Arc<Mutex<sled::Tree>>, //HashMap<global|admin|{did}_{key}, String>,
}
#[pymethods]
impl SimpleAI {
#[new]
pub fn new(
sys_name: String,
) -> Self {
let _ = tracing_subscriber::fmt()
.with_env_filter(EnvFilter::from_default_env())
.try_init();
let sysbaseinfo = token_utils::SYSTEM_BASE_INFO.clone();
let sysinfo_handle = token_utils::TOKIO_RUNTIME.spawn(async move {
SystemInfo::generate().await
});
let (system_name, sys_phrase, device_name, device_phrase, guest_name, guest_phrase)
= GlobalClaims::get_system_vars();
debug!("system_name:{}, device_name:{}, guest_name:{}", system_name, device_name, guest_name);
let claims = GlobalClaims::instance();
let (local_did, local_claim, device_did, device_claim, guest_did, guest_claim) = {
let mut claims = claims.lock().unwrap();
claims.init_sys_dev_guest_did()
};
let mut crypt_secrets = HashMap::new();
let admin = token_utils::load_token_by_authorized2system(&local_did, &mut crypt_secrets);
let blacklist = token_utils::load_did_blacklist_from_file();
debug!("get admin and blacklist: admin={}, blacklist={:?}", admin, blacklist);
let crypt_secrets_len = crypt_secrets.len();
token_utils::init_user_crypt_secret(&mut crypt_secrets, &local_claim, &sys_phrase);
token_utils::init_user_crypt_secret(&mut crypt_secrets, &device_claim, &device_phrase);
let root_dir = sysbaseinfo.root_dir.clone();
let disk_uuid = sysbaseinfo.disk_uuid.clone();
let guest_symbol_hash = IdClaim::get_symbol_hash_by_source(&guest_name, None, Some(format!("{}:{}", root_dir.clone(), disk_uuid.clone())));
debug!("guest_symbol_hash=by_source{}, by_claim({})", URL_SAFE_NO_PAD.encode(guest_symbol_hash), URL_SAFE_NO_PAD.encode(guest_claim.get_symbol_hash()));
let (guest_hash_id, guest_phrase) = token_utils::get_key_hash_id_and_phrase("User", &guest_claim.get_symbol_hash());
debug!("guest_name({}): guest_symbol_hash={}, guest_hash_id={}, guest_phrase={}", guest_claim.nickname, URL_SAFE_NO_PAD.encode(guest_claim.get_symbol_hash()), guest_hash_id, guest_phrase);
token_utils::init_user_crypt_secret(&mut crypt_secrets, &guest_claim, &guest_phrase);
if crypt_secrets.len() > crypt_secrets_len {
token_utils::save_secret_to_system_token_file(&mut crypt_secrets, &local_did, &admin);
}
let certificates = GlobalCerts::instance();
let token_db = {
let mut certificates = certificates.lock().unwrap();
let _ = certificates.load_certificates_from_local(&local_did);
certificates.get_token_db()
};
let (authorized_tree, ready_users_tree, user_sessions_tree, global_local_vars_tree) = {
let token_db = token_db.lock().unwrap();
(token_db.open_tree("authorized").unwrap(), token_db.open_tree("ready_users").unwrap(),
token_db.open_tree("user_sessions").unwrap(), token_db.open_tree("global_local_vars").unwrap())
};
let authorized = Arc::new(Mutex::new(authorized_tree));
let ready_users = Arc::new(Mutex::new(ready_users_tree));
let user_sessions = Arc::new(Mutex::new(user_sessions_tree));
let global_local_vars = Arc::new(Mutex::new(global_local_vars_tree));
let sysinfo = token_utils::TOKIO_RUNTIME.block_on(async {
sysinfo_handle.await.expect("Sysinfo Task panicked")
});
let sys_did = local_did.clone();
let dev_did = device_did.clone();
let sysinfo_clone = sysinfo.clone();
let _logging_handle = token_utils::TOKIO_RUNTIME.spawn(async move {
submit_uncompleted_request_files(&sys_did, &dev_did).await
});
let upstream_did = if admin == token_utils::TOKEN_TM_DID {
token_utils::TOKEN_TM_DID.to_string()
} else { "".to_string() };
debug!("upstream_did: {}", upstream_did);
debug!("init context finished: crypt_secrets.len={}", crypt_secrets.len());
let admin = if !admin.is_empty() {
if guest_did != admin {
let mut claims = claims.lock().unwrap();
claims.set_admin_did(&admin);
admin
} else { "".to_string() }
} else { admin };
Self {
sys_name,
did: local_did,
device: device_did,
admin,
token_db,
authorized,
user_sessions,
sysinfo,
claims,
crypt_secrets,
certificates,
guest: guest_did,
guest_phrase,
ready_users,
blacklist,
upstream_did,
user_base_dir: String::new(),
global_local_vars,
}
}
pub fn get_sys_name(&self) -> String { self.sys_name.clone() }
pub fn get_sys_did(&self) -> String { self.did.clone() }
pub fn get_upstream_did(&mut self) -> String {
if self.admin == token_utils::TOKEN_TM_DID {
return token_utils::TOKEN_TM_DID.to_string()
}
let start_time = Instant::now();
let timeout = Duration::from_secs(30);
loop {
if !self.upstream_did.is_empty() && !self.upstream_did.starts_with("Unknown"){
return self.upstream_did.clone();
}
let (local_claim, device_claim) = {
let mut claims = self.claims.lock().unwrap();
(claims.get_claim_from_local(&self.did), claims.get_claim_from_local(&self.device))
};
let result_string = SimpleAI::request_token_api_register(&local_claim, &device_claim);
let mut global_vars = serde_json::from_str(&result_string).unwrap_or(HashMap::new());
self.upstream_did = global_vars.get("upstream_did").cloned().unwrap_or("Unknown".to_string());
global_vars.insert("upstream_did".to_string(), self.did.clone());
if !self.upstream_did.is_empty() && !self.upstream_did.starts_with("Unknown") {
let global_local_vars = self.global_local_vars.lock().unwrap();
for (var, value) in global_vars.iter() {
let ivec_data = sled::IVec::from(value.as_bytes());
let _ = global_local_vars.insert(&format!("global_{}", var), ivec_data);
}
debug!("[UserBase] obtain upstream: upstream_did={}, self_did={}", self.upstream_did, self.did);
}
if start_time.elapsed() >= timeout {
debug!("[UserBase] Unable to obtain upstream address: self_did={}", self.did);
return "".to_string();
}
std::thread::sleep(Duration::from_secs(2));
}
}
pub fn get_sysinfo(&self) -> SystemInfo {
self.sysinfo.clone()
}
pub fn get_device_did(&self) -> String {
self.device.clone()
}
pub fn get_guest_did(&self) -> String {
self.guest.clone()
}
pub(crate) fn get_admin_did(&self) -> String {
self.admin.clone()
}
//pub fn get_token_db(&self) -> Arc<Mutex<sled::Db>> { self.token_db.clone() }
pub fn get_global_vars(&mut self, key: &str, default: &str) -> String {
let key = format!("global_{}", key);
let global_local_vars = self.global_local_vars.lock().unwrap();
match global_local_vars.get(&key) {
Ok(Some(context)) => {
String::from_utf8(context.to_vec()).unwrap()
},
_ => default.to_string()
}
}
fn load_global_vars(&mut self) {
let upstream_did = self.get_upstream_did();
if upstream_did == self.admin && upstream_did == token_utils::TOKEN_TM_DID {
let mut global_vars: HashMap<String, String> = HashMap::new();
let sysinfo = token_utils::SYSTEM_BASE_INFO.clone();
let root_dir = sysinfo.root_dir.clone();
let global_vars_path = PathBuf::from(root_dir.clone()).join("global_vars.json");
if global_vars_path.exists() {
let global_vars_string = fs::read_to_string(&global_vars_path).unwrap_or("".to_string());
let local_global_vars: HashMap<String, String> = serde_json::from_str(&global_vars_string).unwrap_or(HashMap::new());
global_vars.extend(local_global_vars.into_iter());
}
global_vars.insert("upstream_did".to_string(), self.did.clone());
let global_local_vars = self.global_local_vars.lock().unwrap();
for (var, value) in global_vars.iter() {
let ivec_data = sled::IVec::from(value.as_bytes());
let _ = global_local_vars.insert(&format!("global_{}", var), ivec_data);
}
}
}
pub fn get_global_vars_json(&mut self, reload: Option<bool>) -> String {
let reload = reload.unwrap_or(false);
if reload {
self.load_global_vars();
}
let prefix = "global_";
let mut global_vars: HashMap<String, String> = HashMap::new();
let global_local_vars = self.global_local_vars.lock().unwrap();
for result in global_local_vars.scan_prefix(prefix) {
match result {
Ok((key, value)) => {
if let (Ok(key_str), Ok(value_str)) = (
std::str::from_utf8(&key).map(|s| s.to_string()),
std::str::from_utf8(&value).map(|s| s.to_string()),
) {
global_vars.insert(key_str, value_str);
} else {
eprintln!("Failed to convert key or value to UTF-8");
}
}
Err(e) => {
eprintln!("Error reading key-value pair: {}", e);
}
}
}
serde_json::to_string(&global_vars).unwrap()
}
pub fn get_local_vars(&mut self, key: &str, default: &str, user_session: &str, ua_hash: &str) -> String {
let user_did = self.check_sstoken_and_get_did(user_session, ua_hash);
self.get_local_vars_base(key, default, &user_did)
}
pub fn get_local_admin_vars(&mut self, key: &str) -> String {
let admin_key = format!("admin_{}", key);
let default = token_utils::ADMIN_DEFAULT.lock().unwrap().get(key).to_string();
let admin = self.admin.clone();
self.get_local_vars_base(&admin_key, &default, &admin)
}
fn get_local_vars_base(&mut self, key: &str, default: &str, user_did: &str) -> String {
let (local_did, local_key) = if key.starts_with("admin_") {
(self.admin.clone(), key.to_string())
} else {
(user_did.to_string(), format!("{}_{}", user_did, key))
};
let value = {
let mut global_local_vars = self.global_local_vars.lock().unwrap();
match global_local_vars.get(&local_key) {
Ok(Some(var_value)) => {
String::from_utf8(var_value.to_vec()).unwrap()
},
_ => "Default".to_string()
}
};
if local_key.starts_with("admin_") && value != "Default"{
self.decrypt_by_did(&value, &local_did, 0)
} else {
if value == "Default" {
if local_key.starts_with("admin_") {
let local_key = local_key.replace("admin_", "");
let admin_default = token_utils::ADMIN_DEFAULT.lock().unwrap().get(&local_key).to_string();
admin_default
} else {
default.to_string()
}
} else { value }
}
}
pub fn set_local_vars(&mut self, key: &str, value: &str, user_session: &str, ua_hash: &str) {
let user_did = self.check_sstoken_and_get_did(user_session, ua_hash);
let admin = self.admin.clone();
let (local_key, local_value) = if key.starts_with("admin_") && admin == user_did {
(key.to_string(), self.encrypt_for_did(&value.as_bytes(), &admin, 0))
} else {
if key.starts_with("admin_") {
return;
}
(format!("{}_{}", user_did, key), value.to_string())
};
let global_local_vars = self.global_local_vars.lock().unwrap();
let ivec_data = sled::IVec::from(local_value.as_bytes());
let _ = global_local_vars.insert(&local_key, ivec_data);
}
pub fn set_local_vars_for_guest(&mut self, key: &str, value: &str, user_session: &str, ua_hash: &str) {
let user_did = self.check_sstoken_and_get_did(user_session, ua_hash);
let admin = self.admin.clone();
let guest = self.guest.clone();
if admin == user_did {
let local_key = format!("{}_{}", guest, key);
let local_value = value.to_string();
let global_local_vars = self.global_local_vars.lock().unwrap();
let ivec_data = sled::IVec::from(local_value.as_bytes());
let _ = global_local_vars.insert(&local_key, ivec_data);
}
}
pub fn is_guest(&self, did: &str) -> bool {
did == self.guest.as_str()
}
pub fn is_admin(&self, did: &str) -> bool {
did == self.admin.as_str()
}
pub fn set_admin(&mut self, did: &str) {
self.admin = {
let mut claims = self.claims.lock().unwrap();
claims.set_admin_did(did);
did.to_string()
};
token_utils::save_secret_to_system_token_file(&self.crypt_secrets, &self.did, &self.admin);
}
pub fn absent_admin(&self) -> bool {
self.admin.is_empty()
}
pub fn push_claim(&mut self, claim: &IdClaim) {
let mut claims = self.claims.lock().unwrap();
claims.push_claim(claim);
}
pub fn pop_claim(&mut self, did: &str) -> IdClaim {
let mut claims = self.claims.lock().unwrap();
claims.pop_claim(did)
}
pub fn get_claim(&mut self, for_did: &str) -> IdClaim {
let mut claims = self.claims.lock().unwrap();
if self.admin == token_utils::TOKEN_TM_DID {
claims.get_claim_from_local(for_did)
} else {
claims.get_claim_from_global(for_did)
}
}
pub fn get_claim_from_local(&mut self, for_did: &str) -> IdClaim {
let mut claims = self.claims.lock().unwrap();
claims.get_claim_from_local(for_did)
}
pub fn get_register_cert(&mut self, user_did: &str) -> String {
let register_cert = {
let certificates = self.certificates.lock().unwrap();
certificates.get_register_cert(user_did)
};
if register_cert != "Unknown".to_string() {
return register_cert;
}
if user_did == self.guest {
let system_did = self.did.clone();
let (_issue_cert_key, issue_cert) = self.sign_and_issue_cert_by_system("Member", &user_did, &system_did, "User");
let register_cert = {
let mut certificates = self.certificates.lock().unwrap();
let _ = certificates.push_user_cert_text(&issue_cert);
certificates.get_register_cert(user_did)
};
register_cert
} else {
"Unknown".to_string()
}
}
pub fn is_registered(&mut self, user_did: &str) -> bool {
if user_did == "Unknown" {
return false;
}
let cert_str = self.get_register_cert(user_did);
if cert_str.is_empty() || cert_str == "Unknown" {
return false;
}
let parts: Vec<&str> = cert_str.split('|').collect();
if parts.len() != 4 {
return false;
}
let encrypt_item_key = parts[0].to_string();
let memo_base64 = parts[1].to_string();
let timestamp = parts[2].to_string();
let signature_str = parts[3].to_string();
let text = format!("{}|{}|{}|{}|{}|{}", token_utils::TOKEN_TM_DID, user_did, "Member", encrypt_item_key, memo_base64, timestamp);
let claim = GlobalClaims::load_claim_from_local(token_utils::TOKEN_TM_DID);
debug!("did({}), cert_str({}), cert_text({}), sign_did({})", user_did, cert_str, text, claim.gen_did());
token_utils::verify_signature(&text, &signature_str, &claim.get_cert_verify_key())
}
pub(crate) fn create_user(&mut self, nickname: &str, telephone: &str, id_card: Option<String>, phrase: Option<String>)
-> (String, String) {
let nickname = token_utils::truncate_nickname(nickname);
if !token_utils::is_valid_telephone(telephone) {
return ("Unknown".to_string(), "Unknown".to_string());
}
let user_telephone = telephone.to_string();
let user_symbol_hash = IdClaim::get_symbol_hash_by_source(&nickname, Some(user_telephone.clone()), None);
let (user_hash_id, user_phrase) = token_utils::get_key_hash_id_and_phrase("User", &user_symbol_hash);
let phrase = phrase.unwrap_or(user_phrase);
let user_claim = GlobalClaims::generate_did_claim("User", &nickname, Some(user_telephone.clone()), id_card, &phrase);
self.push_claim(&user_claim);
let user_did = user_claim.gen_did();
let crypt_secrets_len = self.crypt_secrets.len();
token_utils::init_user_crypt_secret(&mut self.crypt_secrets, &user_claim, &phrase);
if self.crypt_secrets.len() > crypt_secrets_len {
token_utils::save_secret_to_system_token_file(&mut self.crypt_secrets, &self.did, &self.admin);
}
let identity = self.export_user(&nickname, &user_telephone, &phrase);
let identity_file = token_utils::get_path_in_sys_key_dir(&format!("user_identity_{}.token", user_hash_id));
fs::write(identity_file.clone(), identity).expect(&format!("Unable to write file: {}", identity_file.display()));
println!("{} [UserBase] Create user and save identity_file: {}", token_utils::now_string(), identity_file.display());
(user_did, phrase)
}
pub fn remove_user(&mut self, user_symbol_hash_base64: &str) -> String {
let user_symbol_hash = token_utils::convert_base64_to_key(user_symbol_hash_base64);
let (user_hash_id, _user_phrase) = token_utils::get_key_hash_id_and_phrase("User", &user_symbol_hash);
let (user_did, claim) = {
let mut claims = self.claims.lock().unwrap();
let user_did = claims.reverse_lookup_did_by_symbol(&user_symbol_hash);
let claim = claims.get_claim_from_local(&user_did);
(user_did, claim)
};
println!("{} [UserBase] Remove user: {}, {}, {}", token_utils::now_string(), user_hash_id, user_did, claim.nickname);
if user_did != "Unknown" {
if !claim.is_default() {
let user_key_file = token_utils::get_path_in_sys_key_dir(&format!(".token_user_{}.pem", user_hash_id));
if let Err(e) = fs::remove_file(user_key_file.clone()) {
debug!("delete user_key_file error: {}", e);
} else {
debug!("user_key_file was deleted: {}", user_key_file.display());
}
self.pop_claim(&user_did);
let identity_file = token_utils::get_path_in_sys_key_dir(&format!("user_identity_{}.token", user_hash_id));
if identity_file.exists() {
if let Err(e) = fs::remove_file(identity_file.clone()) {
debug!("delete identity_file error: {}", e);
} else {
debug!("identity_file was deleted: {}", identity_file.display());
}
}
let exchange_key_value = self.crypt_secrets.remove(&exchange_key!(user_did));
let issue_key_value = self.crypt_secrets.remove(&issue_key!(user_did));
if exchange_key_value.is_some() || issue_key_value.is_some() {
let _ = token_utils::save_secret_to_system_token_file(&mut self.crypt_secrets, &self.did, &self.admin);
}
}
}
user_did
}
pub fn import_user(&mut self, symbol_hash_base64: &str, encrypted_identity: &str, phrase: &str) -> String {
let user_claim = token_utils::import_identity(symbol_hash_base64, &URL_SAFE_NO_PAD.decode(encrypted_identity).unwrap(), phrase);
if user_claim.is_default() {
return "Unknown".to_string();
}
self.push_claim(&user_claim);
let user_did = user_claim.gen_did();
let crypt_secrets_len = self.crypt_secrets.len();
token_utils::init_user_crypt_secret(&mut self.crypt_secrets, &user_claim, &phrase);
if self.crypt_secrets.len() > crypt_secrets_len {
token_utils::save_secret_to_system_token_file(&mut self.crypt_secrets, &self.did, &self.admin);
}
println!("{} [UserBase] Import user: {}", token_utils::now_string(), user_did);
user_did
}
pub fn export_user(&self, nickname: &str, telephone: &str, phrase: &str) -> String {
let nickname = token_utils::truncate_nickname(nickname);
let symbol_hash = IdClaim::get_symbol_hash_by_source(&nickname, Some(telephone.to_string()), None);
let (user_did, claim) = {
let mut claims = self.claims.lock().unwrap();
let user_did = claims.reverse_lookup_did_by_symbol(&symbol_hash);
let claim = claims.get_claim_from_local(&user_did);
(user_did, claim)
};
println!("{} [UserBase] Export user: {}", token_utils::now_string(), user_did);
URL_SAFE_NO_PAD.encode(token_utils::export_identity(&nickname, telephone, claim.timestamp, phrase))
}
#[staticmethod]
pub fn export_user_qrcode_svg(user_did: &str) -> String {
let claim = {
let claims = GlobalClaims::instance();
let mut claims = claims.lock().unwrap();
claims.get_claim_from_local(user_did)
};
if !claim.is_default() {
let user_symbol_hash = claim.get_symbol_hash();
let (user_hash_id, _user_phrase) = token_utils::get_key_hash_id_and_phrase("User", &user_symbol_hash);
let identity_file = token_utils::get_path_in_sys_key_dir(&format!("user_identity_{}.token", user_hash_id));
match identity_file.exists() {
true => {
let identity = fs::read_to_string(identity_file.clone()).expect(&format!("Unable to read file: {}", identity_file.display()));
let encrypted_identity = URL_SAFE_NO_PAD.decode(identity.clone()).unwrap();
let did_bytes = user_did.from_base58().unwrap();
let user_cert = {
let certificates = GlobalCerts::instance();
let certificates = certificates.lock().unwrap();
certificates.get_register_cert(user_did)
};
let user_cert_bytes = token_utils::get_slim_user_cert(&user_cert);
if user_cert_bytes.len() < 120 {
return "".to_string()
}
let mut encrypted_identity_qr = Vec::with_capacity(encrypted_identity.len() + did_bytes.len() + user_cert_bytes.len());
encrypted_identity_qr.extend_from_slice(&did_bytes);
encrypted_identity_qr.extend_from_slice(&user_cert_bytes);
encrypted_identity_qr.extend_from_slice(&encrypted_identity);
let encrypted_identity_qr_base64 = URL_SAFE_NO_PAD.encode(encrypted_identity_qr.clone());
debug!("encrypted_identity_qr: did={}, user_cert={}, identity={}, total.len={}", user_did, user_cert, identity, encrypted_identity_qr.len());
debug!("encrypted_identity({})_qr_base64: len={}, {}", user_did, encrypted_identity_qr_base64.len(), encrypted_identity_qr_base64);
let qrcode = QrCode::with_version(encrypted_identity_qr_base64, Version::Normal(12), EcLevel::L).unwrap();
let image = qrcode.render()
.min_dimensions(400, 400)
.dark_color(svg::Color("#800000"))
.light_color(svg::Color("#ffff80"))
.build();
image
}
false => "".to_string()
}
} else { "".to_string() }
}
#[staticmethod]
pub fn import_identity_qrcode(encrypted_identity: &str) -> (String, String, String) {
let identity = URL_SAFE_NO_PAD.decode(encrypted_identity).unwrap();
let (user_did, nickname, telephone, user_cert) = token_utils::import_identity_qrcode(&identity);
if user_did != "Unknown" && user_cert != "Unknown" {
debug!("import_identity_qrcode, ready to push user cert: did={}", user_did);
let certificates = GlobalCerts::instance();
let mut certificates = certificates.lock().unwrap();
certificates.push_user_cert_text(&format!("{}|{}|{}|{}", token_utils::TOKEN_TM_DID, user_did, "Member", user_cert));
}
(user_did, nickname, telephone)
}
pub fn sign_and_issue_cert_by_admin(&mut self, item: &str, for_did: &str, for_sys_did: &str, memo: &str)
-> (String, String) {
self.sign_and_issue_cert_by_did(&self.admin.clone(), item, for_did, for_sys_did, memo)
}
pub fn sign_and_issue_cert_by_system(&mut self, item: &str, for_did: &str, for_sys_did: &str, memo: &str)
-> (String, String) {
self.sign_and_issue_cert_by_did(&self.did.clone(), item, for_did, for_sys_did, memo)
}
pub fn sign_and_issue_cert_by_did(&mut self, issuer_did: &str, item: &str, for_did: &str, for_sys_did: &str, memo: &str)
-> (String, String) {
if !issuer_did.is_empty() && !for_did.is_empty() && !for_sys_did.is_empty() && !item.is_empty() && !memo.is_empty() &&
IdClaim::validity(issuer_did) && IdClaim::validity(for_did) && IdClaim::validity(for_sys_did) &&
item.len() < 32 && memo.len() < 256 {
let unknown = "Unknown".to_string();
let cert_secret_base64 = self.crypt_secrets.get(&issue_key!(issuer_did)).unwrap_or(&unknown);
if cert_secret_base64 != "Unknown" {
let cert_secret = token_utils::convert_base64_to_key(cert_secret_base64);
if cert_secret != [0u8; 32] {
let item_key = token_utils::derive_key(item.as_bytes(), &token_utils::calc_sha256(&cert_secret)).unwrap_or([0u8; 32]);
if item_key != [0u8; 32] {
let encrypt_item_key = self.encrypt_for_did(&item_key, for_did, 0);
debug!("encrypt_item_key: cert_secret.len={}, item_key.len={}, encrypt_item_key.len={}",
cert_secret.len(), item_key.len(), URL_SAFE_NO_PAD.decode(encrypt_item_key.clone()).unwrap().len());
let memo_base64 = URL_SAFE_NO_PAD.encode(memo.as_bytes());
let timestamp = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_else(|_| std::time::Duration::from_secs(0)).as_secs();
let cert_text = format!("{}|{}|{}|{}|{}|{}", issuer_did, for_did, item, encrypt_item_key, memo_base64, timestamp);
let sig = URL_SAFE_NO_PAD.encode(self.sign_by_issuer_key(&cert_text, &URL_SAFE_NO_PAD.encode(cert_secret)));
println!("{} [UserBase] Sign and issue a cert by did: issuer({}), item({}), owner({}), sys({})", token_utils::now_string(), issuer_did, item, for_did, for_sys_did);
if for_sys_did == self.did {
return (format!("{}|{}|{}", issuer_did, for_did, item), format!("{}|{}", cert_text, sig))
} else {
return (format!("{}|{}|{}", issuer_did, for_did, item), self.encrypt_for_did(format!("{}|{}", cert_text, sig).as_bytes(), for_sys_did, 0))
}
}
}
}
}
println!("{} [UserBase] Sign and issue a cert by did: invalid params", token_utils::now_string());
("Unknown".to_string(), "Unknown".to_string())
}
pub fn sign(&mut self, text: &str) -> Vec<u8> {
self.sign_by_did(text, &self.did.clone(),"not required")
}
pub fn sign_by_did(&mut self, text: &str, did: &str, phrase: &str) -> Vec<u8> {
let claim = self.get_claim(did);
token_utils::get_signature(text, &claim.id_type, &claim.get_symbol_hash(), phrase)
}
pub fn sign_by_issuer_key(&mut self, text: &str, issuer_key: &str) -> Vec<u8> {
let issuer_key = token_utils::convert_base64_to_key(issuer_key);
token_utils::get_signature_by_key(text, &issuer_key)
}
pub fn verify(&mut self, text: &str, signature: &str) -> bool {
self.verify_by_did(text, signature, &self.did.clone())
}
pub fn verify_by_did(&mut self, text: &str, signature_str: &str, did: &str) -> bool {
let claim = self.get_claim(did);
token_utils::verify_signature(text, signature_str, &claim.get_verify_key())
}
pub fn cert_verify_by_did(&mut self, text: &str, signature_str: &str, did: &str) -> bool {
let claim = self.get_claim(did);
token_utils::verify_signature(text, signature_str, &claim.get_cert_verify_key())
}
pub fn encrypt_for_did(&mut self, text: &[u8], for_did: &str, period:u64) -> String {
let self_crypt_secret = token_utils::convert_base64_to_key(self.crypt_secrets.get(&exchange_key!(self.did)).unwrap());
let for_did_public = self.get_claim(for_did).get_crypt_key();
let shared_key = token_utils::get_diffie_hellman_key(for_did_public, self_crypt_secret);
let ctext = token_utils::encrypt(text, &shared_key, period);
URL_SAFE_NO_PAD.encode(ctext)
}
pub fn decrypt_by_did(&mut self, ctext: &str, by_did: &str, period:u64) -> String {
let self_crypt_secret = token_utils::convert_base64_to_key(self.crypt_secrets.get(&exchange_key!(self.did)).unwrap());
let by_did_public = self.get_claim(by_did).get_crypt_key();
let shared_key = token_utils::get_diffie_hellman_key(by_did_public, self_crypt_secret);
let text = token_utils::decrypt(URL_SAFE_NO_PAD.decode(ctext).unwrap().as_slice(), &shared_key, period);
String::from_utf8_lossy(text.as_slice()).to_string()
}
pub fn get_entry_point(&self, user_did: &str, entry_point_id: &str) -> String {
if user_did==self.admin {
token_utils::gen_entry_point_of_service(entry_point_id)
} else { "".to_string() }
}
pub fn get_guest_sstoken(&mut self, ua_hash: &str) -> String {
let guest_did = self.guest.clone();
self.get_user_sstoken(&guest_did, ua_hash)
}
pub fn get_user_sstoken(&mut self, did: &str, ua_hash: &str) -> String {
if IdClaim::validity(did) {
let now_sec = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_else(|_| std::time::Duration::from_secs(0)).as_secs();
let context = self.get_user_context(did);
if context.is_default() || context.is_expired(){
debug!("[UserBase] debug: get_user_sstoken, context is default or expired: did={}", did);
return String::from("Unknown")
}
let text1 = token_utils::calc_sha256(
format!("{}|{}|{}", ua_hash, self.crypt_secrets[&exchange_key!(self.did)],
self.crypt_secrets[&exchange_key!(self.device)]).as_bytes());
let text2 = token_utils::calc_sha256(format!("{}",now_sec/2000000).as_bytes());
let mut text_bytes: [u8; 64] = [0; 64];
text_bytes[..32].copy_from_slice(&text1);
text_bytes[32..].copy_from_slice(&text2);
let text_hash = token_utils::calc_sha256(&text_bytes);
let did_bytes = did.from_base58().unwrap_or("Unknown".to_string().into_bytes());
let mut padded_did_bytes: [u8; 32] = [0; 32];
padded_did_bytes[..11].copy_from_slice(&did_bytes[10..]);
padded_did_bytes[11..].copy_from_slice(&did_bytes);
let result: [u8; 32] = text_hash.iter()
.zip(padded_did_bytes.iter())
.map(|(&a, &b)| a ^ b)
.collect::<Vec<u8>>()
.try_into()
.expect("get_user_sstoken, Failed to convert Vec<u8> to [u8; 32]");
result.to_base58()
} else {
debug!("[UserBase] debug: get_user_sstoken, did is incorrect format: {}", did);
String::from("Unknown")
}
}
pub fn check_sstoken_and_get_did(&mut self, sstoken: &str, ua_hash: &str) -> String {
let sstoken_bytes = sstoken.from_base58().unwrap_or([0; 32].to_vec());
if sstoken_bytes.len() != 32 || sstoken_bytes==[0; 32] {
println!("{} [UserBase] The sstoken in browser is incorrect format: {}", token_utils::now_string(), sstoken);
return String::from("Unknown")
}
let mut padded_sstoken_bytes: [u8; 32] = [0; 32];
padded_sstoken_bytes.copy_from_slice(&sstoken_bytes);
let now_sec = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_else(|_| std::time::Duration::from_secs(0)).as_secs();
let text1 = token_utils::calc_sha256(
format!("{}|{}|{}", ua_hash, self.crypt_secrets[&exchange_key!(self.did)],
self.crypt_secrets[&exchange_key!(self.device)]).as_bytes());
let text2 = token_utils::calc_sha256(format!("{}",now_sec/2000000).as_bytes());
let mut text_bytes: [u8; 64] = [0; 64];
text_bytes[..32].copy_from_slice(&text1);
text_bytes[32..].copy_from_slice(&text2);
let text_hash = token_utils::calc_sha256(&text_bytes);
let result: [u8; 32] = text_hash.iter()
.zip(padded_sstoken_bytes.iter())
.map(|(&a, &b)| a ^ b)
.collect::<Vec<u8>>()
.try_into()
.expect("check_sstoken_and_get_did, 1, Failed to convert Vec<u8> to [u8; 32]");
let mut did_bytes: [u8; 21] = [0; 21];
let mut padded: [u8; 11] = [0; 11];
padded.copy_from_slice(&result[..11]);
did_bytes.copy_from_slice(&result[11..]);
let did_bytes_slice = &did_bytes[10..];
if padded.iter().zip(did_bytes_slice.iter()).all(|(a, b)| a == b) {
let user_did = did_bytes.to_base58();
let context = self.get_user_context(&user_did);
if context.is_default() || context.is_expired(){
println!("{} [UserBase] The context of the sstoken in browser is expired: did={}", token_utils::now_string(), user_did);
String::from("Unknown")
} else {
user_did
}
} else {
let text2 = token_utils::calc_sha256(format!("{}",now_sec/2000000 -1).as_bytes());
let mut text_bytes: [u8; 64] = [0; 64];
text_bytes[..32].copy_from_slice(&text1);
text_bytes[32..].copy_from_slice(&text2);
let text_hash = token_utils::calc_sha256(&text_bytes);
let result: [u8; 32] = text_hash.iter()
.zip(padded_sstoken_bytes.iter())
.map(|(&a, &b)| a ^ b)
.collect::<Vec<u8>>()
.try_into()
.expect("check_sstoken_and_get_did, 2, Failed to convert Vec<u8> to [u8; 32]");
padded.copy_from_slice(&result[..11]);
did_bytes.copy_from_slice(&result[11..]);
let did_bytes_slice = &did_bytes[10..];
if padded.iter().zip(did_bytes_slice.iter()).all(|(a, b)| a == b) {
let user_did = did_bytes.to_base58();
let context = self.get_user_context(&user_did);
if context.is_default() || context.is_expired(){
println!("{} [UserBase] The context2 of the sstoken in browser is expired: did={}", token_utils::now_string(), user_did);
String::from("Unknown")
} else {
user_did
}
} else {
println!("{} [UserBase] The sstoken in browser is not validity: sstoken={}, ua={}", token_utils::now_string(), sstoken, ua_hash);
String::from("Unknown")
}
}
}
#[staticmethod]
pub fn get_path_in_root_dir(did: &str, catalog: &str) -> String {
let path_file = token_utils::get_path_in_root_dir(did, catalog);
path_file.to_string_lossy().to_string()
}
pub fn set_user_base_dir(&mut self, user_base_dir: &str) {
self.user_base_dir = {
let mut claims = self.claims.lock().unwrap();
claims.set_user_base_dir(user_base_dir);
user_base_dir.to_string()
};
}
pub fn get_user_path_in_root(&self, root: &str, user_did: &str) -> String {
let root_dir = PathBuf::from(root);
let did_path =
self.device.from_base58().expect("Failed to decode base58").iter()
.zip(user_did.from_base58().expect("Failed to decode base58").iter())
.map(|(&x, &y)| x ^ y).collect::<Vec<_>>().to_base58();
if !IdClaim::validity(user_did) || self.is_guest(user_did) {
root_dir.join("guest_user").to_string_lossy().to_string()
} else if self.is_admin(user_did) {
root_dir.join(format!("admin_{}", did_path)).to_string_lossy().to_string()
} else {
root_dir.join(did_path).to_string_lossy().to_string()
}
}
pub fn get_path_in_user_dir(&self, did: &str, catalog: &str) -> String {
let claims = self.claims.lock().unwrap();
claims.get_path_in_user_dir(did, catalog)
}
pub fn get_private_paths_list(&self, did: &str, catalog: &str) -> Vec<String> {
let catalog_paths = self.get_path_in_user_dir(did, catalog);
let filters = &[];
let suffixes = &[".json"];
token_utils::filter_files(&Path::new(&catalog_paths), filters, suffixes)
}
pub fn get_private_paths_datas(&self, user_context: &UserContext, catalog: &str, filename: &str) -> String {
let file_paths = Path::new(&self.get_path_in_user_dir(&user_context.get_did(), catalog)).join(filename);
match file_paths.exists() {
true => {
let crypt_key = user_context.get_crypt_key();
match fs::read(file_paths) {
Ok(raw_data) => {
let data = token_utils::decrypt(&raw_data, &crypt_key, 0);
let private_datas = serde_json::from_slice(&data).unwrap_or(serde_json::json!({}));
private_datas.to_string()
},
Err(_) => "Unknowns".to_string(),
}
}
false => "Unknowns".to_string(),
}
}
pub fn get_guest_user_context(&mut self) -> UserContext {
let guest_did = self.get_guest_did();
self.get_user_context(&guest_did)
}
pub fn check_local_user_token(&mut self, nickname: &str, telephone: &str) -> String {
let nickname = token_utils::truncate_nickname(nickname);
if !token_utils::is_valid_telephone(telephone) {
return "unknown".to_string();
}
if nickname.to_lowercase().starts_with("guest") {
return "unknown".to_string();
}
let symbol_hash = IdClaim::get_symbol_hash_by_source(&nickname, Some(telephone.to_string()), None);
let symbol_hash_base64 = URL_SAFE_NO_PAD.encode(symbol_hash);
let (user_hash_id, _user_phrase) = token_utils::get_key_hash_id_and_phrase("User", &symbol_hash);
match token_utils::exists_key_file("User", &symbol_hash) {
true => {
if token_utils::is_original_user_key(&symbol_hash) {
let ready_data = {
let ready_users = self.ready_users.lock().unwrap();
match ready_users.get(&user_hash_id) {
Ok(Some(ready_data)) => String::from_utf8(ready_data.to_vec()).unwrap(),
_ => "Unknown".to_string(),
}
};
if ready_data != "Unknown" {
let parts: Vec<&str> = ready_data.split('|').collect();
let old_user_did = match parts.len() >= 3 {
true => parts[1].to_string(),
false => "Unknown".to_string(),
};
if old_user_did == "Unknown" { // 身份预备数据格式错误
self.remove_user(&symbol_hash_base64);
debug!("user_key is exist but the ready data is error: {}, {}", nickname, user_hash_id);
return "re_input".to_string();
} else if !self.is_registered(&old_user_did) { // 没有经过身份验证
self.remove_user(&symbol_hash_base64);
debug!("user_key is exist but the vcode is not verified : {}, {}", nickname, user_hash_id);
return "re_input".to_string();
} // 已经过身份验证
debug!("user_key is exist and the phrase hasn't been updated: {}, {}", nickname, user_hash_id);
"immature".to_string()
} else { // 身份预备数据丢失的处理
self.remove_user(&symbol_hash_base64);
debug!("user_key is exist but the ready data is empty: {}, {}", nickname, user_hash_id);
"re_input".to_string()
}
} else {
"local".to_string()
}
},
false => {
let identity_file = token_utils::get_path_in_sys_key_dir(&format!("user_identity_{}.token", user_hash_id));
match identity_file.exists() {
true => "local".to_string(),
false => {
println!("{} [UserBase] The identity is not in local and generate ready_data for new user: {}, {}, {}, {}",
token_utils::now_string(), nickname, telephone, user_hash_id, symbol_hash_base64);
let (user_did, _user_phrase) = self.create_user(&nickname, telephone, None, None);
let new_claim = self.get_claim_from_local(&user_did);
println!("{} [UserBase] Create new claim for new user: user_did={}, claim_symbol={}",
token_utils::now_string(), user_did, URL_SAFE_NO_PAD.encode(new_claim.get_symbol_hash()));
let mut request: serde_json::Value = json!({});
request["telephone"] = serde_json::to_value(telephone).unwrap_or(json!(""));
request["claim"] = serde_json::to_value(new_claim.clone()).unwrap_or(json!(""));
let apply_result = self.request_token_api(
"apply",
&serde_json::to_string(&request).unwrap_or("{}".to_string()),);
println!("{} [UserBase] Apply to verify user: symbol({})", token_utils::now_string(), symbol_hash_base64);
if !apply_result.starts_with("Unknown") {
let parts: Vec<&str> = apply_result.split('|').collect();
if parts[0] == "user_claim" {
self.remove_user(&symbol_hash_base64);
match serde_json::from_str::<IdClaim>(&parts[1]) {
Ok(return_claim) => {
let return_did = return_claim.gen_did();
println!("{} [UserBase] The decoding the claim from Root is correct: user_did({}), nickname={}, claim_symbol({})",
token_utils::now_string(), return_did, return_claim.nickname, URL_SAFE_NO_PAD.encode(return_claim.get_symbol_hash()));
debug!("return_claim: {}", parts[1]);
if user_did != return_claim.gen_did() {
println!("{} [UserBase] Identity confirmed to recall user from root: local_did({}), remote_did({})",
token_utils::now_string(), user_did, return_did);
self.push_claim(&return_claim);
return "recall".to_string();
} else {
println!("{} [UserBase] Identity confirmed to recall user from root is same the new before: local_did({}), remote_did({})",
token_utils::now_string(), user_did, return_did);
self.remove_user(&symbol_hash_base64);
return "unknown".to_string();
}
}
Err(e) => {
println!("{} [UserBase] The decoding the claim from Root is fail: did({}), error({})", token_utils::now_string(), user_did, e);
self.remove_user(&symbol_hash_base64);
return "unknown".to_string();
}
}
} else if parts[0] == "user_cert" {
let ready_data = format!("{}|{}|{}", 3, user_did, parts[1]);
let ivec_data = sled::IVec::from(ready_data.as_bytes());
{
let ready_users = self.ready_users.lock().unwrap();
let _ = ready_users.insert(&user_hash_id, ivec_data);
}
debug!("ready_data: {}", ready_data);
println!("{} [UserBase] User apply is ok, ready to verify user_cert with vcode: did({})", token_utils::now_string(), user_did);
return "create".to_string();
} else {
self.remove_user(&symbol_hash_base64);
println!("{} [UserBase] User apply is ok, but the feedback is undefined: {}", token_utils::now_string(), apply_result);
return "unknown".to_string();
}
} else if apply_result.starts_with("Unknown_Repeat") {
println!("{} [UserBase] User apply is failure({}): did({}), symbol({})", token_utils::now_string(), apply_result, user_did, symbol_hash_base64);
self.remove_user(&symbol_hash_base64);
return "unknown_repeat".to_string();
} else if apply_result.starts_with("Unknown_Exceeded") {
println!("{} [UserBase] User apply is failure({}): did({}), symbol({})", token_utils::now_string(), apply_result, user_did, symbol_hash_base64);
self.remove_user(&symbol_hash_base64);
return "unknown_exceeded".to_string();
} else {
println!("{} [UserBase] User apply is failure({}): sys_did({}), user_did({}), user_symbol({})", token_utils::now_string(), apply_result, self.did, user_did, symbol_hash_base64);
self.remove_user(&symbol_hash_base64);
return "unknown".to_string();
}
}
}
}
}
}