forked from globocom/secDevLabs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
96 lines (72 loc) · 2.06 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"errors"
"fmt"
"os"
apiContext "github.com/globocom/secDevLabs/owasp-top10-2017-apps/a5/ecommerce-api/context"
"github.com/globocom/secDevLabs/owasp-top10-2017-apps/a5/ecommerce-api/db"
"github.com/globocom/secDevLabs/owasp-top10-2017-apps/a5/ecommerce-api/handlers"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
func main() {
configAPI := apiContext.GetAPIConfig()
if err := checkRequirements(configAPI); err != nil {
os.Exit(1)
}
echoInstance := echo.New()
echoInstance.HideBanner = true
echoInstance.Use(middleware.Logger())
echoInstance.Use(middleware.Recover())
echoInstance.Use(middleware.RequestID())
echoInstance.GET("/healthcheck", handlers.HealthCheck)
echoInstance.GET("/ticket/:id", handlers.GetTicket)
echoInstance.POST("/register", handlers.RegisterUser)
echoInstance.POST("/login", handlers.Login)
APIport := fmt.Sprintf(":%d", configAPI.APIPort)
echoInstance.Logger.Fatal(echoInstance.Start(APIport))
}
func checkRequirements(configAPI *apiContext.APIConfig) error {
// check if all environment variables are properly set.
if err := checkEnvVars(); err != nil {
return err
}
// check if MongoDB is acessible and credentials received are working.
if err := checkMongoDB(); err != nil {
return err
}
return nil
}
func checkEnvVars() error {
envVars := []string{
"MONGO_HOST",
"MONGO_DATABASE_NAME",
"MONGO_DATABASE_USERNAME",
"MONGO_DATABASE_PASSWORD",
}
var envIsSet bool
var allEnvIsSet bool
var errorString string
env := make(map[string]string)
allEnvIsSet = true
for i := 0; i < len(envVars); i++ {
env[envVars[i]], envIsSet = os.LookupEnv(envVars[i])
if !envIsSet {
errorString = errorString + envVars[i] + " "
allEnvIsSet = false
}
}
if allEnvIsSet == false {
finalError := fmt.Sprintf("check environment variables: %s", errorString)
return errors.New(finalError)
}
return nil
}
func checkMongoDB() error {
_, err := db.Connect()
if err != nil {
mongoError := fmt.Sprintf("check mongoDB: %s", err)
return errors.New(mongoError)
}
return nil
}