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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
|
package main
import (
"crypto/rsa"
"crypto/x509"
"database/sql"
"encoding/hex"
"encoding/pem"
"log"
"os"
"time"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/template/html/v2"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
"golang.org/x/crypto/sha3"
_ "github.com/lib/pq"
)
type User struct {
Username string `json:"username"`
Password string `json:"password"`
}
func main() {
engine := html.New("./views", ".html")
app := fiber.New(fiber.Config{
Views: engine,
})
privateKey, err := readPrivateKeyFromFile("keys/id_rsa")
if err != nil {
panic(err)
}
app.Use(jwtMiddleware(privateKey))
app.Get("/", func(c *fiber.Ctx) error {
return c.Render("index", fiber.Map{
"Title": "JWT Auth",
"Year": time.Now().Year(),
"Username": c.Locals("username"),
"IsAuthenticated": c.Locals("username") != nil,
}, "layouts/main")
})
app.Get("/login", func(c *fiber.Ctx) error {
return c.Render("login", fiber.Map{
"Title": "Login",
"Year": time.Now().Year(),
"IsAuthenticated": c.Locals("username") != nil,
}, "layouts/main")
})
app.Get("/register", func(c *fiber.Ctx) error {
return c.Render("register", fiber.Map{
"Title": "Register",
"Year": time.Now().Year(),
"IsAuthenticated": c.Locals("username") != nil,
}, "layouts/main")
})
app.Get("/logout", logout)
app.Post("/login", login(privateKey))
app.Post("/register", register)
if err := app.Listen(":3001"); err != nil {
panic(err)
}
}
func jwtMiddleware(privateKey *rsa.PrivateKey) fiber.Handler {
return func(c *fiber.Ctx) error {
jwtCookie := c.Cookies("jwt")
if jwtCookie != "" {
token, err := jwt.Parse(jwtCookie, func(token *jwt.Token) (interface{}, error) {
return privateKey.Public(), nil
})
if err == nil {
sub, err := token.Claims.GetSubject()
if err != nil {
return c.Next()
}
c.Locals("username", sub)
}
}
return c.Next()
}
}
func login(privateKey *rsa.PrivateKey) fiber.Handler {
return func(c *fiber.Ctx) error {
username := c.FormValue("username")
password := c.FormValue("password")
if username == "" || password == "" {
log.Println("Missing username or password")
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"message": "Missing username or password",
})
}
hash := hash(password)
db, err := connectoToDB()
if err != nil {
log.Printf("Database error. Error: %v\n", err)
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"message": "Database error",
})
}
defer db.Close()
var user User
err = db.QueryRow("SELECT username, password FROM users WHERE username=$1", username).Scan(&user.Username, &user.Password)
if err != nil {
log.Printf("Database error. Error: %v\n", err)
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"message": "Database error",
})
}
if user.Password != hash {
log.Println("Invalid username or password")
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
"message": "Invalid username or password",
})
}
expires := time.Now().Add(time.Hour)
claims := jwt.MapClaims{
"iss": "admin",
"sub": user.Username,
"aud": "users",
"exp": expires.Unix(),
"nbf": time.Now().Unix(),
"iat": time.Now().Unix(),
"jti": uuid.NewString(),
}
token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
t, err := token.SignedString(privateKey)
if err != nil {
log.Printf("Error signing token. Error: %v\n", err)
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"message": "Error signing token",
})
}
c.Cookie(&fiber.Cookie{
Name: "jwt",
Value: t,
Expires: expires,
})
return c.Redirect("/")
}
}
func logout(c *fiber.Ctx) error {
c.Cookie(&fiber.Cookie{
Name: "jwt",
Value: "",
Expires: time.Now().Add(-time.Hour),
})
return c.Redirect("/")
}
func register(c *fiber.Ctx) error {
username := c.FormValue("username")
password := c.FormValue("password")
if username == "" || password == "" {
log.Println("Missing username or password")
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"message": "Missing username or password",
})
}
hash := hash(password)
db, err := connectoToDB()
if err != nil {
log.Printf("Database error. Error: %v\n", err)
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"message": "Database error",
})
}
defer db.Close()
_, err = db.Exec("INSERT INTO users (username, password) VALUES ($1, $2)", username, hash)
if err != nil {
log.Printf("Database error. Error: %v\n", err)
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"message": "Database error",
})
}
return c.Redirect("/")
}
func connectoToDB() (*sql.DB, error) {
connection := os.Getenv("DATABASE_URL")
if connection == "" {
connection = "host=localhost port=5432 user=postgres password=postgres dbname=postgres sslmode=disable"
}
return sql.Open("postgres", connection)
}
func hash(str string) string {
hash := sha3.Sum256([]byte(str))
doubleHash := sha3.Sum256(hash[:])
return hex.EncodeToString(doubleHash[:])
}
func readPrivateKeyFromFile(filename string) (*rsa.PrivateKey, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
fileInfo, _ := file.Stat()
fileSize := fileInfo.Size()
buffer := make([]byte, fileSize)
_, err = file.Read(buffer)
if err != nil {
return nil, err
}
data, _ := pem.Decode(buffer)
privateKey, err := x509.ParsePKCS1PrivateKey(data.Bytes)
if err != nil {
return nil, err
}
return privateKey, ni
}
|