-
公共模块
在src目录新建common文件夹
在common文件夹里依次新建db.rs、jwt.rs、mistake.rs、utils.rs、mod.rs
目录结构如下:
project
|—src
|—params //封装参数结构体模块
|—req.rs //封装请求参数结构体
|—resp.rs //封装返回数据结构体
|—result_parse.rs //解析返回参数结构体
|—mod.rs //导出模块
|—common //公共模块
|—db.rs //构造数据库连接池
|—jwt.rs //处理token
|—mistake.rs //处理错误
|—util.rs //工具函数
|—mod.rs //导出模块
db.rs代码:
use rocket_db_pools::Database;
use rocket_db_pools::sqlx;
//构造连接池
#[derive(Database,Clone)]
//prodb为postgresql里创建的数据库名
#[database("prodb")]
pub struct Prodb(sqlx::PgPool);
jwt.rs代码:
use rocket::serde::{Deserialize,Serialize};
use jsonwebtoken::{encode, EncodingKey, Header,decode, DecodingKey, Validation};
use rocket::http::Status;
use rocket::request::{FromRequest, Outcome};
use rocket::serde::json::{Json,Value,json};
use std::time::{SystemTime, UNIX_EPOCH};
use rocket::post;
use crate::params::req::Userparam;
#[derive(Deserialize, Serialize)]
#[serde(crate = "rocket::serde")]
pub struct Claims {
pub sub: String,
pub exp: u64,
pub user: Userparam
}
pub const KEY: &[u8] = b"secret";
#[derive(Debug)]
pub struct Token{
pub uname: String,
pub id:String
}
// Bearer Token
impl Token {
fn from_request(header: &str) -> Option<Token> {
let split_vec = header.split_whitespace().collect::<Vec<_>>();
if split_vec.len() != 2 {
return None;
}
if split_vec[0] != "Bearer" {
return None;
}
Self::from_jwt(split_vec[1])
}
fn from_jwt(token_string: &str) -> Option<Token> {
let mut val = Validation::default();
val.sub = Some("1qaz2wsx@2024.com!qaz@wsx".to_string());
match decode::<Claims>(token_string, &DecodingKey::from_secret(KEY), &val) {
Ok(c) => {
// println!("==c.claims.user=={:?}",c.claims.user);
//解析token获取用户信息
let user=Token{
uname:c.claims.user.uname,
id:c.claims.user.id
};
return Some(user);
}
Err(_) => None,
}
}
}
#[rocket::async_trait]
impl<'r> FromRequest<'r> for Token {
type Error = ();
async fn from_request(request: &'r rocket::Request<'_>) -> Outcome<Self, Self::Error> {
let header_auth = request.headers().get_one("Authorization");
if let Some(header_auth) = header_auth {
if let Some(auth) = Self::from_request(header_auth) {
return Outcome::Success(auth);
}
}
Outcome::Error((Status::Unauthorized, ()))
}
}
#[post("/gettoken",data="<userparam>")]
//生成token
pub async fn get_token(userparam : Json<Userparam>) -> Value {
let user = userparam.into_inner();
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
let token = match encode(
&Header::default(),
&Claims {
sub: String::from("1qaz2wsx@2024.com!qaz@wsx"),
exp: timestamp + 21600000,
user:user
},
&EncodingKey::from_secret(KEY),
) {
Ok(t) => t,
Err(_) => panic!(),
};
json!({ "token": token })
}
mistake.rs代码:
use rocket::serde::json::Json;
use rocket::catch;
use crate::params::resp;
#[catch(401)]
pub fn un_auth()->Json<resp::Resp>{
Json(
resp::Resp { code:0,
message:"未获授权!".to_string(),
})
}
#[catch(404)]
pub fn un_find()->Json<resp::Resp>{
Json(
resp::Resp { code:0,
message:"接口未找到!".to_string(),
})
}
#[catch(500)]
pub fn on_error()->Json<resp::Resp>{
Json(
resp::Resp { code:0,
message:"内部服务器错误!".to_string(),
})
}
#[catch(400)]
pub fn bad_request()->Json<resp::Resp>{
Json(
resp::Resp { code:0,
message:"请求缺少参数或请求方式错误!".to_string(),
})
}
#[catch(422)]
pub fn un_processable()->Json<resp::Resp>{
Json(
resp::Resp { code:0,
message:"请求参数不全!".to_string(),
})
}
utils.rs代码:
use uuid::Uuid;
use chrono::{NaiveDateTime,DateTime,Local,ParseError,NaiveDate};
//获取uuid
pub fn get_uuid() -> String {
let my_uuid = Uuid::new_v4();
my_uuid.to_string()
}
//获取当前日期时间(日期格式)
pub fn get_datetime()->Result<DateTime<Local>,ParseError>{
Ok(Local::now())
}
//获取当前日期(字符串格式)
pub fn get_date()->String{
Local::now().format("%Y-%m-%d").to_string()
}
//字符串转日期时间
pub fn str_to_datetime(str:&str)->Result<NaiveDateTime,ParseError>{
let format="%Y-%m-%d %H:%M:%S.3f";
let datetime=NaiveDateTime::parse_from_str(str, format)?;
Ok(datetime)
}
//字符串转日期
pub fn str_to_date(str:&str)->Result<NaiveDate,ParseError>{
let format="%Y-%m-%d";
let date=NaiveDate::parse_from_str(str, format)?;
Ok(date)
}
//日期转字符串
pub fn date_to_str(date:NaiveDate)->String{
date.format("%Y-%m-%d").to_string()
}
//日期时间转字符串
pub fn datetime_to_str(date:NaiveDateTime)->String{
date.format("%Y-%m-%d %H:%M:%S.3f").to_string()
}
mod.rs代码:
//数据库
pub mod db;
//工具
pub mod utils;
//jsonwebtoken
pub mod jwt;
//错误
pub mod mistake;