mirror of
https://github.com/Floriansylvain/RenewCMS.git
synced 2026-08-19 11:43:22 +02:00
feat: env variables introduction
This commit is contained in:
@@ -7,3 +7,6 @@
|
|||||||
|
|
||||||
# Build
|
# Build
|
||||||
*.exe
|
*.exe
|
||||||
|
|
||||||
|
# Environment
|
||||||
|
.env
|
||||||
@@ -10,11 +10,7 @@ Don't forget to setup the [Environment variables](#environment-variables)!
|
|||||||
|
|
||||||
### Use with Docker
|
### Use with Docker
|
||||||
|
|
||||||
To **run** the app, run the command
|
TODO (or is it...)
|
||||||
|
|
||||||
```shell
|
|
||||||
docker-compose up
|
|
||||||
```
|
|
||||||
|
|
||||||
### Build and run it yourself
|
### Build and run it yourself
|
||||||
|
|
||||||
@@ -23,9 +19,9 @@ TODO
|
|||||||
### Environment variables
|
### Environment variables
|
||||||
|
|
||||||
| Name | Type | Description | Comment |
|
| Name | Type | Description | Comment |
|
||||||
|------|------|-------------|---------|
|
|-------------|--------|---------------------------------------|-----------------------------------------|
|
||||||
| | | | |
|
| PORT | int | The port the API will use | required |
|
||||||
|
| ENVIRONMENT | string | The environment the API is running in | required, `development` or `production` |
|
||||||
|
|
||||||
## API Usage
|
## API Usage
|
||||||
|
|
||||||
|
|||||||
+6
-4
@@ -7,6 +7,7 @@ import (
|
|||||||
"github.com/go-chi/jwtauth/v5"
|
"github.com/go-chi/jwtauth/v5"
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"os"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -21,6 +22,7 @@ type UserLogin struct {
|
|||||||
Password string `json:"password" validate:"required,min=8"`
|
Password string `json:"password" validate:"required,min=8"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var shouldCookieBeSecure = os.Getenv("ENVIRONMENT") == "production"
|
||||||
var TokenAuth *jwtauth.JWTAuth
|
var TokenAuth *jwtauth.JWTAuth
|
||||||
|
|
||||||
// TODO Move into its own file or package that handles api errors
|
// TODO Move into its own file or package that handles api errors
|
||||||
@@ -36,14 +38,14 @@ func SetJwtCookie(w *http.ResponseWriter, userId uint32) error {
|
|||||||
Name: "jwt",
|
Name: "jwt",
|
||||||
Value: tokenString,
|
Value: tokenString,
|
||||||
Expires: time.Now().Add(24 * time.Hour),
|
Expires: time.Now().Add(24 * time.Hour),
|
||||||
Secure: false, // TODO false in dev, true in prod
|
Secure: shouldCookieBeSecure,
|
||||||
HttpOnly: true,
|
HttpOnly: true,
|
||||||
Path: "/",
|
Path: "/",
|
||||||
})
|
})
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func isAllowedToCreateUser() bool {
|
func isUserTableEmpty() bool {
|
||||||
users := container.ListUsersUseCase.ListUsers()
|
users := container.ListUsersUseCase.ListUsers()
|
||||||
return len(users) == 0
|
return len(users) == 0
|
||||||
}
|
}
|
||||||
@@ -92,7 +94,7 @@ func login(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func register(w http.ResponseWriter, r *http.Request) {
|
func register(w http.ResponseWriter, r *http.Request) {
|
||||||
if !IsLoggedIn(r) && !isAllowedToCreateUser() {
|
if !IsLoggedIn(r) && !isUserTableEmpty() {
|
||||||
http.Error(w, "You are not allowed to create a user. Log in or reset database.", http.StatusForbidden)
|
http.Error(w, "You are not allowed to create a user. Log in or reset database.", http.StatusForbidden)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -132,7 +134,7 @@ func removeJwtCookie(w http.ResponseWriter) {
|
|||||||
Value: "",
|
Value: "",
|
||||||
Expires: time.Now(),
|
Expires: time.Now(),
|
||||||
MaxAge: -1,
|
MaxAge: -1,
|
||||||
Secure: false, // TODO false in dev, true in prod
|
Secure: shouldCookieBeSecure,
|
||||||
HttpOnly: true,
|
HttpOnly: true,
|
||||||
Path: "/",
|
Path: "/",
|
||||||
})
|
})
|
||||||
|
|||||||
+6
-3
@@ -6,6 +6,7 @@ import (
|
|||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
"html/template"
|
"html/template"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
@@ -78,9 +79,11 @@ func postLoginPage(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO replace url with som env variable
|
response, err := http.Post(
|
||||||
response, err := http.Post("http://localhost:8080/v1/auth/login", "application/json", bytes.NewBuffer(credentials))
|
"http://localhost:"+os.Getenv("PORT")+"/v1/auth/login",
|
||||||
// TODO handle possible errors in separate file (api package)
|
"application/json",
|
||||||
|
bytes.NewBuffer(credentials))
|
||||||
|
|
||||||
if err != nil || response.StatusCode != http.StatusOK {
|
if err != nil || response.StatusCode != http.StatusOK {
|
||||||
r.Method = http.MethodGet
|
r.Method = http.MethodGet
|
||||||
getLoginPageHandler(NewLoginPage("Invalid username or password.", r.FormValue("username")))(w, r)
|
getLoginPageHandler(NewLoginPage("Invalid username or password.", r.FormValue("username")))(w, r)
|
||||||
|
|||||||
+20
-3
@@ -8,9 +8,14 @@ import (
|
|||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
"github.com/go-chi/cors"
|
"github.com/go-chi/cors"
|
||||||
"github.com/go-chi/jwtauth/v5"
|
"github.com/go-chi/jwtauth/v5"
|
||||||
|
"github.com/joho/godotenv"
|
||||||
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var envVarsToLoad = []string{"PORT", "ENVIRONMENT"}
|
||||||
|
|
||||||
func jsonContentTypeMiddleware(next http.Handler) http.Handler {
|
func jsonContentTypeMiddleware(next http.Handler) http.Handler {
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
@@ -80,15 +85,27 @@ func initRoutes() *chi.Mux {
|
|||||||
return apiRouter
|
return apiRouter
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func initEnvVariables() {
|
||||||
|
err := godotenv.Load()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal("Error loading .env file")
|
||||||
|
}
|
||||||
|
for _, envVar := range envVarsToLoad {
|
||||||
|
if _, ok := os.LookupEnv(envVar); !ok {
|
||||||
|
panic(fmt.Sprintf("Environment variable %s is not set", envVar))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
initEnvVariables()
|
||||||
api.InitContainer()
|
api.InitContainer()
|
||||||
api.InitValidator()
|
api.InitValidator()
|
||||||
initJwt()
|
initJwt()
|
||||||
|
|
||||||
router := initRoutes()
|
router := initRoutes()
|
||||||
|
|
||||||
fmt.Println("Server starting on port 8080")
|
fmt.Println("Server starting on port " + os.Getenv("PORT"))
|
||||||
err := http.ListenAndServe(":8080", router)
|
err := http.ListenAndServe(":"+os.Getenv("PORT"), router)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ require (
|
|||||||
github.com/google/uuid v1.3.0 // indirect
|
github.com/google/uuid v1.3.0 // indirect
|
||||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||||
github.com/jinzhu/now v1.1.5 // indirect
|
github.com/jinzhu/now v1.1.5 // indirect
|
||||||
|
github.com/joho/godotenv v1.5.1 // indirect
|
||||||
github.com/leodido/go-urn v1.2.4 // indirect
|
github.com/leodido/go-urn v1.2.4 // indirect
|
||||||
github.com/lestrrat-go/blackmagic v1.0.1 // indirect
|
github.com/lestrrat-go/blackmagic v1.0.1 // indirect
|
||||||
github.com/lestrrat-go/httpcc v1.0.1 // indirect
|
github.com/lestrrat-go/httpcc v1.0.1 // indirect
|
||||||
|
|||||||
@@ -41,6 +41,8 @@ github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD
|
|||||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||||
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||||
|
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||||
|
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||||
github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
|
github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
|
||||||
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
|
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
|
||||||
github.com/lestrrat-go/blackmagic v1.0.1 h1:lS5Zts+5HIC/8og6cGHb0uCcNCa3OUt1ygh3Qz2Fe80=
|
github.com/lestrrat-go/blackmagic v1.0.1 h1:lS5Zts+5HIC/8og6cGHb0uCcNCa3OUt1ygh3Qz2Fe80=
|
||||||
|
|||||||
Reference in New Issue
Block a user