/
server.go
153 lines (135 loc) · 3.67 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/addetz/secure-code-go/demo4/db"
"github.com/addetz/secure-code-go/demo4/handlers"
echojwt "github.com/labstack/echo-jwt/v4"
"github.com/golang-jwt/jwt/v5"
echo "github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
_ "github.com/lib/pq"
)
const TIMEOUT = 3 * time.Second
type Response struct {
Message string `json:"message"`
}
func main() {
// Read paths to certificate & private key from environment variables
certFile, ok := os.LookupEnv("SERVER_CERT_FILE")
if !ok {
log.Fatal("SERVER_CERT_FILE variable must be set")
}
keyFile, ok := os.LookupEnv("SERVER_KEY_FILE")
if !ok {
log.Fatal("SERVER_KEY_FILE variable must be set")
}
signingKey, ok := os.LookupEnv("SIGNING_KEY")
if !ok {
log.Fatal("SIGNING_KEY variable must be set")
}
// Read port if one is set
port := readPort()
// Connect to database
dbConn := connectDatabase()
// Shut down connection when server shuts down
defer func() {
dbConn.Close()
}()
dbService := db.NewDatabaseService(dbConn)
// Set up internal services
userAuthService := handlers.NewUserAuthService(signingKey, dbService)
// Initialise echo
e := echo.New()
e.Use(middleware.Logger())
e.Use(middleware.Recover())
// Configure server
s := http.Server{
Addr: fmt.Sprintf(":%s", port),
Handler: e,
ReadTimeout: TIMEOUT,
ReadHeaderTimeout: TIMEOUT,
WriteTimeout: TIMEOUT,
IdleTimeout: TIMEOUT,
}
// Set up the root route
e.GET("/", func(c echo.Context) error {
return c.JSON(http.StatusOK, &Response{
Message: "Hello, Gophers!",
})
})
// Set up authentication routes
e.POST("/signup", func(c echo.Context) error {
return userAuthService.SignUp(c)
})
e.POST("/login", func(c echo.Context) error {
return userAuthService.Login(c)
})
// Restricted route only for logged in users
r := e.Group("/restricted")
config := echojwt.Config{
NewClaimsFunc: func(c echo.Context) jwt.Claims {
return new(handlers.JWTCustomClaims)
},
SigningKey: []byte(signingKey),
}
r.Use(echojwt.WithConfig(config))
r.GET("", func(c echo.Context) error {
return userAuthService.RestrictedPath(c)
})
// Get all user's notes
r.GET("/secretNotes/:id", func(c echo.Context) error {
return userAuthService.GetUserNotes(c)
})
// Add new note for user
r.POST("/secretNotes/:id", func(c echo.Context) error {
return userAuthService.AddUserNote(c)
})
log.Printf("Listening on :%s...\n", port)
if err := s.ListenAndServeTLS(certFile, keyFile); err != http.ErrServerClosed {
log.Fatal(err)
}
}
func readPort() string {
port, ok := os.LookupEnv("SERVER_PORT")
if !ok {
return "1323"
}
return port
}
func connectDatabase() *sql.DB {
user, ok := os.LookupEnv("POSTGRES_USER")
if !ok {
log.Fatal("POSTGRES_USER variable must be set")
}
pwd, ok := os.LookupEnv("POSTGRES_PWD")
if !ok {
log.Fatal("POSTGRES_PWD variable must be set")
}
db, ok := os.LookupEnv("POSTGRES_DB")
if !ok {
log.Fatal("POSTGRES_DB variable must be set")
}
connectionStr := fmt.Sprintf("user=%s password=%s dbname=%s", user, pwd, db)
conn, err := sql.Open("postgres", connectionStr)
if err != nil {
log.Fatal("connection error", err)
}
if err := conn.Ping(); err != nil {
log.Fatal("ping error", err)
}
_, err = conn.Exec("CREATE TABLE IF NOT EXISTS users (username VARCHAR(50) PRIMARY KEY, pwd VARCHAR(100) NOT NULL)")
if err != nil {
log.Fatal("create users", err)
}
_, err = conn.Exec("CREATE TABLE IF NOT EXISTS notes ( id VARCHAR (50) PRIMARY KEY," +
"username VARCHAR(50) REFERENCES users (username), noteText VARCHAR (500) NOT NULL)")
if err != nil {
panic(err)
}
return conn
}