Skip to content

Commit

Permalink
feat: add env support
Browse files Browse the repository at this point in the history
  • Loading branch information
Dorian committed Sep 22, 2024
1 parent 73dd98d commit bb215b3
Show file tree
Hide file tree
Showing 19 changed files with 79 additions and 36 deletions.
8 changes: 8 additions & 0 deletions .env.dev
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
APP_HOST=http://localhost

DATABASE_HOST=redis
DATABASE_PORT=6379

TOKEN_SECRET="7;2IKHuT2.rB"

CRYPTO_KEY="E2lfBstY1u'N&TV£s{7U/o98;\t*z`q{"
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,4 @@ go.work
go.work.sum

# env file
.env
.env.prod
2 changes: 2 additions & 0 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ services:
build:
dockerfile: ./.docker/go/Dockerfile
context: ./
environment:
- APP_ENV=dev
ports:
- 80:80
volumes:
Expand Down
6 changes: 6 additions & 0 deletions esbuild.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import * as esbuild from "esbuild";
import stylePlugin from "esbuild-style-plugin";
import dotenv from "dotenv";
import { createRequire } from "module";

const require = createRequire(import.meta.url);

dotenv.config({ path: `.env.${process.env.NODE_ENV}` });

let ctx = await esbuild.context({
logLevel: "info",
entryPoints: ["web/src/app.tsx", "web/src/main.scss"],
Expand All @@ -18,6 +21,9 @@ let ctx = await esbuild.context({
},
}),
],
define: {
"process.env.APP_HOST": JSON.stringify(process.env.APP_HOST),
},
});

console.log("⚡ Build complete! ⚡");
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go 1.23.1
require (
github.com/golang-jwt/jwt/v5 v5.2.1
github.com/google/uuid v1.6.0
github.com/joho/godotenv v1.5.1
github.com/redis/go-redis/v9 v9.6.1
golang.org/x/crypto v0.27.0
)
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17w
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/redis/go-redis/v9 v9.6.1 h1:HHDteefn6ZkTtY5fGUE8tj8uy85AHk6zP7CpzIAM0y4=
github.com/redis/go-redis/v9 v9.6.1/go.mod h1:0C0c6ycQsdpVNQpxb1njEQIqkx5UcsM8FJCQLgE9+RA=
golang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A=
Expand Down
4 changes: 3 additions & 1 deletion internal/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package internal

import (
"context"
"fmt"
"log/slog"
"os"

"github.com/redis/go-redis/v9"
)
Expand All @@ -16,7 +18,7 @@ type redisClient struct {

func NewDatabase(logger *slog.Logger) (*redisClient, error) {
rdb := redis.NewClient(&redis.Options{
Addr: "redis:6379",
Addr: fmt.Sprintf("%s:%s", os.Getenv("DATABASE_HOST"), os.Getenv("DATABASE_PORT")),
Username: "",
Password: "",
DB: 0,
Expand Down
3 changes: 2 additions & 1 deletion internal/handlers/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"log/slog"
"net/http"
"os"
"time"

"github.com/dorianneto/burn-secret/internal/interfaces"
Expand Down Expand Up @@ -66,7 +67,7 @@ func (ah *authHandlers) Login(w http.ResponseWriter, r *http.Request) {

token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims, nil)

tokenString, err := token.SignedString([]byte("7;2IKHuT2.rB"))
tokenString, err := token.SignedString([]byte(os.Getenv("TOKEN_SECRET")))
if err != nil {
ah.logger.Error("error on creating token")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
Expand Down
3 changes: 2 additions & 1 deletion internal/middleware/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package middleware
import (
"fmt"
"net/http"
"os"
"strings"
"time"

Expand All @@ -25,7 +26,7 @@ func EnsureToken(next func(http.ResponseWriter, *http.Request)) func(http.Respon
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}

return []byte("7;2IKHuT2.rB"), nil
return []byte(os.Getenv("TOKEN_SECRET")), nil
})
if err != nil {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
Expand Down
7 changes: 3 additions & 4 deletions internal/utils/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,9 @@ import (
"crypto/rand"
"encoding/base64"
"io"
"os"
)

var key []byte = []byte("E2lfBstY1u'N&TV£s{7U/o98;\t*z`q{")

type cipherData struct {
Code string
Nonce []byte
Expand All @@ -20,7 +19,7 @@ func NewCipherData(code string, nonce []byte) *cipherData {
}

func EncryptIt(data string) (*cipherData, error) {
block, err := aes.NewCipher(key)
block, err := aes.NewCipher([]byte(os.Getenv("CRYPTO_KEY")))
if err != nil {
return &cipherData{}, err
}
Expand All @@ -46,7 +45,7 @@ func DecryptIt(data *cipherData) (string, error) {
return "", err
}

block, err := aes.NewCipher(key)
block, err := aes.NewCipher([]byte(os.Getenv("CRYPTO_KEY")))
if err != nil {
return "", err
}
Expand Down
3 changes: 3 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,12 @@ import (

"github.com/dorianneto/burn-secret/cmd/api"
"github.com/dorianneto/burn-secret/internal"
"github.com/joho/godotenv"
)

func main() {
godotenv.Load(".env." + os.Getenv("APP_ENV"))

logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
database, err := internal.NewDatabase(logger)
if err != nil {
Expand Down
13 changes: 13 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
"main": "./web/index.js",
"type": "module",
"scripts": {
"build": "node esbuild.js",
"dev": "node esbuild.js --watch",
"dev": "NODE_ENV=dev node esbuild.js --watch",
"prod": "NODE_ENV=prod node esbuild.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
Expand All @@ -30,6 +30,7 @@
"@types/react": "^18.3.5",
"@types/react-dom": "^18.3.0",
"axios": "^1.7.7",
"dotenv": "^16.4.5",
"framer-motion": "^11.5.4",
"react": "^18.3.1",
"react-dom": "^18.3.1",
Expand Down
36 changes: 18 additions & 18 deletions public/app.js

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions public/app.js.map

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions web/src/config/api.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const API_URL = process.env.APP_HOST;
3 changes: 2 additions & 1 deletion web/src/pages/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
import { Card, CardBody } from "@chakra-ui/react";
import { Form, json, Link, useActionData, useNavigate } from "react-router-dom";
import axios from "axios";
import { API_URL } from "../config/api"

export async function action({ request, params }) {
const { toast } = createStandaloneToast();
Expand All @@ -26,7 +27,7 @@ export async function action({ request, params }) {
}

const { status, data } = await axios.post(
"http://localhost/api/v1/secret/new",
`${API_URL}/api/v1/secret/new`,
{
secret,
}
Expand Down
3 changes: 2 additions & 1 deletion web/src/pages/NewSecret.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
import { Card, CardBody } from "@chakra-ui/react";
import { CopyIcon } from "@chakra-ui/icons";
import { useLocation } from "react-router-dom";
import { API_URL } from "../config/api";

export const NewSecret = () => {
const { state } = useLocation()
Expand All @@ -20,7 +21,7 @@ export const NewSecret = () => {
placement="top"
>
<p id="secret-link" className="text-xl my-8">
{`http://localhost/secret/${state.data}/reveal`}
{`${API_URL}/secret/${state.data}/reveal`}
</p>
</Tooltip>
<Button
Expand Down
5 changes: 3 additions & 2 deletions web/src/pages/RevealSecret.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Card, CardBody } from "@chakra-ui/react";
import { CopyIcon, UnlockIcon } from "@chakra-ui/icons";
import axios from "axios";
import { useNavigate, useParams } from "react-router-dom";
import { API_URL } from "../config/api";

export const RevealSecret = () => {
const [secret, setSecret] = useState(null);
Expand All @@ -16,7 +17,7 @@ export const RevealSecret = () => {
useEffect(() => {
const fetchData = async () => {
const { data, status } = await axios.get(
`http://localhost/api/v1/secret/${id}`
`${API_URL}/api/v1/secret/${id}`
);

if (status != 200) {
Expand All @@ -43,7 +44,7 @@ export const RevealSecret = () => {
}

const fetchData = async () => {
await axios.delete(`http://localhost/api/v1/secret/${id}/burn`);
await axios.delete(`${API_URL}/api/v1/secret/${id}/burn`);
};

fetchData().catch(console.error);
Expand Down

0 comments on commit bb215b3

Please sign in to comment.