|
| 1 | +use crate::auth::user::Claims; |
| 2 | +use crate::db; |
| 3 | +use crate::models::user::{NewUser, User}; |
| 4 | +use crate::schema::users::dsl::*; |
| 5 | +use bcrypt::{hash, verify, DEFAULT_COST}; |
| 6 | +use diesel::prelude::*; |
| 7 | +use jsonwebtoken::{encode, EncodingKey, Header}; |
| 8 | +use rocket::http::Status; |
| 9 | +use rocket::serde::json::Json; |
| 10 | +use serde::{Deserialize, Serialize}; |
| 11 | +#[derive(Deserialize)] |
| 12 | +pub struct RegisterInfo { |
| 13 | + username: String, |
| 14 | + password: String, |
| 15 | +} |
| 16 | + |
| 17 | +#[derive(Deserialize)] |
| 18 | +pub struct LoginInfo { |
| 19 | + username: String, |
| 20 | + password: String, |
| 21 | +} |
| 22 | +#[derive(Serialize)] |
| 23 | +pub struct TokenResponse { |
| 24 | + token: String, |
| 25 | +} |
| 26 | + |
| 27 | +#[post("/register", data = "<info>")] |
| 28 | +pub fn register(info: Json<RegisterInfo>) -> Result<Json<User>, Status> { |
| 29 | + let conn = &mut db::establish_connection(); |
| 30 | + let hashed_password = hash(&info.password, DEFAULT_COST) |
| 31 | + .map_err(|_| Status::InternalServerError)?; |
| 32 | + |
| 33 | + let new_user = NewUser { |
| 34 | + username: info.username.clone(), |
| 35 | + password_hash: hashed_password, |
| 36 | + role: "user".to_string(), |
| 37 | + }; |
| 38 | + |
| 39 | + diesel::insert_into(users) |
| 40 | + .values(new_user) |
| 41 | + .get_result::<User>(conn) |
| 42 | + .map(Json) |
| 43 | + .map_err(|_| Status::InternalServerError) |
| 44 | +} |
| 45 | + |
| 46 | +#[post("/login", data = "<info>")] |
| 47 | +pub fn login(info: Json<LoginInfo>) -> Result<Json<TokenResponse>, Status> { |
| 48 | + let conn = &mut db::establish_connection(); |
| 49 | + let user = users |
| 50 | + .filter(username.eq(&info.username)) |
| 51 | + .first::<User>(conn) |
| 52 | + .map_err(|_| Status::Unauthorized)?; |
| 53 | + if verify(&info.password, &user.password_hash).map_err(|_| Status::InternalServerError)? { |
| 54 | + let claims = Claims { |
| 55 | + sub: user.id, |
| 56 | + role: user.role.clone(), |
| 57 | + exp: 10000000000, |
| 58 | + }; |
| 59 | + let token = encode( |
| 60 | + &Header::default(), |
| 61 | + &claims, |
| 62 | + &EncodingKey::from_secret("SECRET".as_ref()), |
| 63 | + ) |
| 64 | + .map_err(|_| Status::InternalServerError)?; |
| 65 | + Ok(Json(TokenResponse { token })) |
| 66 | + } else { |
| 67 | + Err(Status::Unauthorized) |
| 68 | + } |
| 69 | +} |
0 commit comments