mod.rs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. pub mod user;
  2. pub mod area;
  3. pub mod auth;
  4. pub mod device;
  5. pub mod flow_task;
  6. pub mod ability;
  7. #[cfg(target_arch = "x86_64")]
  8. #[cfg(target_os = "windows")]
  9. mod code_helper;
  10. use rand::Rng;
  11. use crate::{datasource::Datasource, log, LogLevel::*};
  12. #[derive(serde::Deserialize)]
  13. pub struct Ident{
  14. token: String
  15. }
  16. #[derive(serde::Serialize)]
  17. pub struct JsonBack{
  18. pub errcode: i16,
  19. #[serde(skip_serializing_if = "Option::is_none")]
  20. pub errmsg: Option<String>
  21. }
  22. #[derive(serde::Serialize)]
  23. pub struct DataBack<T>{
  24. pub errcode: i16,
  25. #[serde(skip_serializing_if = "Option::is_none")]
  26. pub errmsg: Option<String>,
  27. #[serde(skip_serializing_if = "Option::is_none")]
  28. pub data: Option<T>
  29. }
  30. #[derive(serde::Deserialize)]
  31. pub struct Page{
  32. page: usize,
  33. size: usize
  34. }
  35. pub fn token_fail() ->axum::Json<JsonBack> {axum::Json(JsonBack{
  36. errcode: 2000,
  37. errmsg: Some("鉴权失败: token无效".to_string())
  38. })}
  39. pub fn errcode0() ->axum::Json<JsonBack> {axum::Json(JsonBack{
  40. errcode: 0,
  41. errmsg: None
  42. })}
  43. #[allow(dead_code)]
  44. pub async fn example(axum::extract::State(_): axum::extract::State<crate::AppState>) -> axum::Json<JsonBack> {
  45. axum::Json(JsonBack{
  46. errcode: 0,
  47. errmsg: None
  48. })
  49. }
  50. pub async fn check_token(state: &crate::AppState, token: String) -> Result<(u64,String),()>{
  51. state.db_lite.query(
  52. "select id,mqid from user where token=? and isdelete=0",
  53. [token.clone()], // 这里不能写作 rusqlite::params![token]
  54. |r|{Ok((r.get::<usize,u64>(0)?,r.get::<usize,String>(1)?))}).await.map_err(|e| log(Warning,format!("{token},{e}")))
  55. }
  56. pub async fn check_openid(state: &crate::AppState, openid: String) -> Result<(u64,String),()>{
  57. state.db_lite.query(
  58. "select id,mqid from user where openid=? and isdelete=0",
  59. [openid], // 这里不能写作 rusqlite::params![token]
  60. |r|{Ok((r.get::<usize,u64>(0)?,r.get::<usize,String>(1)?))}).await.map_err(|e| println!("{e}"))
  61. }
  62. pub fn token(s: usize) -> String{
  63. rand::rng().sample_iter(&rand::distr::Alphanumeric).take(s).map(char::from).collect()
  64. }
  65. pub fn md5(payload: String) -> String{
  66. format!("{:x}",md5::compute(payload))
  67. }
  68. #[cfg(test)]
  69. mod tests{
  70. #[test]
  71. fn test_token(){
  72. use super::token;
  73. println!("{}",token(32));
  74. }
  75. #[test]
  76. fn test_md5(){
  77. use super::md5;
  78. println!("{}",md5("123456".to_string()));
  79. }
  80. }