Skip to content

Commit

Permalink
Merge pull request #22 from snamiki1212/chore/remove-secret-file
Browse files Browse the repository at this point in the history
chore: remove secret key file
  • Loading branch information
snamiki1212 committed Jun 16, 2023
2 parents 7113f8b + c39a947 commit ea8a07e
Show file tree
Hide file tree
Showing 6 changed files with 20 additions and 9 deletions.
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@
DATABASE_URL=postgres://postgres:postgres@0.0.0.0:5432/realworld-rust-actix-web

FRONTEND_ORIGIN=http://localhost:3000

SECRET_KEY=0123456789012345
3 changes: 1 addition & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/target

.env
secret.key
.env
3 changes: 0 additions & 3 deletions scripts/copy-env.sh
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
#!/bin/sh

# Create secrey.key
cp secret.key.example secret.key

# Create .env
cp .env.example .env
1 change: 0 additions & 1 deletion secret.key.example

This file was deleted.

1 change: 1 addition & 0 deletions src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ pub const BIND: &str = "0.0.0.0:8080";
pub mod env_key {
pub const DATABASE_URL: &str = "DATABASE_URL";
pub const FRONTEND_ORIGIN: &str = "FRONTEND_ORIGIN";
pub const SECRET_KEY: &str = "SECRET_KEY";
}
19 changes: 16 additions & 3 deletions src/utils/token.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,34 @@
use crate::constants::env_key;
use jsonwebtoken::{errors::Error, DecodingKey, EncodingKey, Header, TokenData, Validation};
use serde::{Deserialize, Serialize};
use std::env;
use uuid::Uuid;

static KEY: [u8; 16] = *include_bytes!("../../secret.key");
static ONE_DAY: i64 = 60 * 60 * 24; // in seconds

fn get_secret_key() -> String {
env::var(env_key::SECRET_KEY).expect("SECRET_KEY must be set")
}

pub fn decode(token: &str) -> jsonwebtoken::errors::Result<TokenData<Claims>> {
let binding = get_secret_key();
let secret_key = binding.as_bytes();
jsonwebtoken::decode::<Claims>(
token,
&DecodingKey::from_secret(&KEY),
&DecodingKey::from_secret(secret_key),
&Validation::default(),
)
}

pub fn generate(user_id: Uuid, now: i64) -> Result<String, Error> {
let claims = Claims::new(user_id, now);
jsonwebtoken::encode(&Header::default(), &claims, &EncodingKey::from_secret(&KEY))
let binding = get_secret_key();
let secret_key = binding.as_bytes();
jsonwebtoken::encode(
&Header::default(),
&claims,
&EncodingKey::from_secret(secret_key),
)
}

#[derive(Debug, Serialize, Deserialize)]
Expand Down

0 comments on commit ea8a07e

Please sign in to comment.