-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.go
More file actions
executable file
·265 lines (223 loc) · 7.65 KB
/
app.go
File metadata and controls
executable file
·265 lines (223 loc) · 7.65 KB
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
package main
import (
"www.github.com/goid/modules/Code"
"database/sql"
//"crypto/tls"
"net/http"
"encoding/json"
"golang.org/x/crypto/bcrypt"
"github.com/go-chi/chi/v5"
"time"
//"github.com/go-chi/chi/v5/middleware"
"fmt"
//"io"
_ "github.com/go-sql-driver/mysql"
"os"
)
// Main function to start the server
func main() {
// cfg := map[string] string {
// User: os.Getenv("DBUSER"),
// Passwd: os.Getenv("DBPASS"),
// Addr: os.Getenv("DBHOST"),
// SSHPort: os.Getenv("DBPORT"),
// DBName: os.Getenv("DBNAME"),
// }
// Connect to the database
db, err := sql.Open("mysql", "root:password@tcp(127.0.0.1:3306)/digital_tool_box")
if err != nil {
panic(err)
}
// pingErr := db.Ping()
// if pingErr != nil {
// fmt.Println(pingErr)
// }
// fmt.Println("Connected!")
defer db.Close()
if os.Getenv("APP_LIVE") == "1" {
// Create a new http.Transport with TLS settings
// tr := &http.Transport{
// TLSClientConfig: &tls.Config{
// InsecureSkipVerify: false, // InsecureSkipVerify should be set to false in production
// },
// }
// // Create a new http.Client using the transport
// client := &http.Client{
// Transport: tr,
// }
}
// Initialize the Chi router
router := chi.NewRouter()
// Middlewares
//router.Use(goid.VerifyCertificateMiddleware())
router.Use(goid.AuthorizationMiddleware)
// Define a handler function for a GET request to the root URL
router.Get("/", goid.HomeCheck)
router.Get("/check-user", func(w http.ResponseWriter, r *http.Request) {
var user goid.User
err := db.QueryRow("SELECT id, name, email, password, token FROM users WHERE email = ?", "anthony@mail.com").Scan(&user.ID, &user.Name, &user.Email, &user.Password, &user.Token)
if err != nil {
fmt.Println(err)
}
fmt.Println("Collected User Record...")
fmt.Println("ID:", user.ID)
fmt.Println("Name:", user.Name)
fmt.Println("Email:", user.Email)
fmt.Println("Password:", user.Password)
fmt.Println("Token:", user.Token)
})
router.Post("/reset-token", func(w http.ResponseWriter, r *http.Request) {
fmt.Println("/reset-token")
var tokenRequest goid.GenrateTokenRequest
err := json.NewDecoder(r.Body).Decode(&tokenRequest)
if err != nil {
// TODO
fmt.Println("Error:", err)
}
fmt.Println("Resetting Token for UID:", tokenRequest.UID)
goid.GenerateAccessToken(db, tokenRequest.UID)
})
/**
Login
Requires JSON body, no query params
*/
router.Post("/users/login", func (w http.ResponseWriter, r *http.Request) {
var login goid.LoginRequest
err := json.NewDecoder(r.Body).Decode(&login)
fmt.Println(login.Email)
fmt.Println(login.Password)
// Authenticate the user and perform necessary checks
token, err := goid.AuthenticateUser(db, login.Email, login.Password)
if err != nil {
fmt.Println("Error:", err)
return
}
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
// Return the access token in the response
response := struct {
Token string `json:"token"`
}{
Token: token,
}
/**
* In production the Id-P is responsible for the Set-Cookie headers
*/
cookie := http.Cookie{
Name: "goid_token",
Value: "example value",
HttpOnly: true,
Domain: "localhost",
Secure: false,
Path: "/",
MaxAge: 0,
Expires: time.Now().Add(10000),
SameSite: http.SameSiteLaxMode,
}
http.SetCookie(w, &cookie)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
})
router.Post("/getCookies", func(w http.ResponseWriter, r *http.Request) {
cookie := http.Cookie{
Name: "goid_token",
Value: "example value",
HttpOnly: true,
Domain: "127.0.0.1",
Secure: false,
Path: "/",
MaxAge: 1,
Expires: time.Now().Add(10000),
SameSite: http.SameSiteLaxMode,
}
http.SetCookie(w, &cookie)
})
router.Get("/getCookies", func(w http.ResponseWriter, r *http.Request) {
cookie := http.Cookie{
Name: "goid_token",
Value: "example value",
HttpOnly: true,
Domain: "127.0.0.1",
Secure: false,
Path: "/",
MaxAge: 1,
Expires: time.Now().Add(10000),
SameSite: http.SameSiteLaxMode,
}
http.SetCookie(w, &cookie)
w.Write([]byte(fmt.Sprintf("Hello")))
})
router.Post("/verifyToken", func(w http.ResponseWriter, r *http.Request) {
var verify goid.VerifyRequest
err := json.NewDecoder(r.Body).Decode(&verify)
user, err := goid.VerifyToken(db, verify.Email, verify.Token)
if err != nil {
http.Error(w, "Failed to retrieve user", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
response := struct {
User_id int `json:"user_id"`
Token string `json:"token"`
}{
User_id: user.ID,
Token: user.Token,
}
json.NewEncoder(w).Encode(response)
})
router.Post("/bcrypt", func (w http.ResponseWriter, r *http.Request) {
// Extract username and password from the request
message := r.FormValue("pass")
hashedBytes, err := bcrypt.GenerateFromPassword([]byte(message), bcrypt.DefaultCost)
if err != nil {
fmt.Println("Error:",err)
}
w.Write([]byte(fmt.Sprintf("hashed:%s", hashedBytes)))
})
router.Post("/securekey", func (w http.ResponseWriter, r *http.Request) {
key, err := goid.GenerateSecureKey(128)
if err != nil {
//
}
w.Write([]byte(fmt.Sprintf("key:%s", key)))
})
router.Post("/users/register", func(w http.ResponseWriter, r *http.Request) {
if (os.Getenv("APP_LIVE") == "1"){
// Check the authorization header
authHeader := r.Header.Get("Authorization")
if !goid.IsAuthorized(authHeader) {
w.WriteHeader(http.StatusUnauthorized)
return
}
}
// Parse the request body
var userRequest goid.UserCreateRequest
err := json.NewDecoder(r.Body).Decode(&userRequest)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if _, err = goid.IsValidUserCreateRequest(userRequest); err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "Invalid userRequest. Registration with error:")
fmt.Fprintf(w, err.Error())
return
}
goid.CreateUser(db, userRequest)
// Registration successful
w.WriteHeader(http.StatusCreated)
fmt.Fprintf(w, "User registered successfully")
})
/**
Logout
*/
router.Get("/users/logout", func(w http.ResponseWriter, r *http.Request) {
// TODO: Invalidate the access token for the current user
//c.JSON(200, gin.H{})
})
// Start the server
fmt.Println("we're back, baby!")
http.ListenAndServe(":8081", router)
//http.ListenAndServeTLS(":8081", "/home/yoshi/.ssh/newcert.pem", "/home/yoshi/.ssh/newkey.pem", router)
}