Skip to content

Commit 4f11452

Browse files
committed
- gave up from uploading the log periodically to the database
- now we get trusted IPs from user register information
1 parent b1e8cca commit 4f11452

File tree

7 files changed

+54
-121
lines changed

7 files changed

+54
-121
lines changed

controllers/controller.go

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package controllers
22

33
import (
44
"errors"
5+
"fmt"
56
"github.com/Darklabel91/API_Names/database"
67
"github.com/Darklabel91/API_Names/models"
78
Metaphone "github.com/Darklabel91/metaphone-br"
@@ -36,7 +37,7 @@ func Signup(c *gin.Context) {
3637
}
3738

3839
//create the user
39-
user := models.User{Email: body.Email, Password: string(hash)}
40+
user := models.User{Email: body.Email, Password: string(hash), IP: c.ClientIP()}
4041
result := database.Db.Create(&user)
4142

4243
if result.Error != nil {
@@ -195,6 +196,34 @@ func GetName(c *gin.Context) {
195196
return
196197
}
197198

199+
//GetTrustedIPs return all IPS from user's on the database
200+
func GetTrustedIPs() []string {
201+
var users []models.User
202+
if err := database.Db.Find(&users).Error; err != nil {
203+
return nil
204+
}
205+
206+
var ips []string
207+
for _, user := range users {
208+
ips = append(ips, user.IP)
209+
}
210+
211+
fmt.Println(ips)
212+
213+
return ips
214+
}
215+
216+
//SetLogger creates a .txt file to store API logs
217+
func SetLogger(fileName string) gin.HandlerFunc {
218+
// Create a file to store the logs
219+
file, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE, 0666)
220+
if err != nil {
221+
return nil
222+
}
223+
224+
return gin.LoggerWithWriter(file)
225+
}
226+
198227
//SearchSimilarNames search for all similar names by metaphone and Levenshtein method
199228
func SearchSimilarNames(c *gin.Context) {
200229
var metaphoneNames []models.NameType

database/db.go

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ import (
1111
"gorm.io/driver/mysql"
1212
"gorm.io/gorm"
1313
"io"
14+
"log"
15+
"net"
1416
"os"
1517
"time"
1618
)
@@ -82,13 +84,6 @@ func connectDB() *gorm.DB {
8284
return nil
8385
}
8486

85-
//create table log
86-
err = db.AutoMigrate(&models.Log{})
87-
if err != nil {
88-
fmt.Printf("Error on gorm auto migrate to database : error=%v\n", err)
89-
return nil
90-
}
91-
9287
return db
9388
}
9489

@@ -132,6 +127,7 @@ func createRoot() error {
132127
userRoot := models.User{
133128
134129
Password: string(hash),
130+
IP: getOutboundIP(),
135131
}
136132

137133
Db.Create(&userRoot)
@@ -143,6 +139,20 @@ func createRoot() error {
143139
return nil
144140
}
145141

142+
//getOutboundIP get preferred outbound ip of the server
143+
func getOutboundIP() string {
144+
conn, err := net.Dial("udp", "8.8.8.8:80")
145+
if err != nil {
146+
log.Fatal(err)
147+
}
148+
defer conn.Close()
149+
150+
localAddr := conn.LocalAddr().(*net.UDPAddr)
151+
152+
return localAddr.IP.String()
153+
}
154+
155+
//uploadCSVNameTypes
146156
func uploadCSVNameTypes() error {
147157
var name models.NameType
148158
Db.Raw("SELECT * FROM name_types WHERE id = 1").Find(&name)

log/log.go

Lines changed: 0 additions & 82 deletions
This file was deleted.

main.go

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,15 @@ package main
33
import (
44
"fmt"
55
"github.com/Darklabel91/API_Names/database"
6-
"github.com/Darklabel91/API_Names/log"
76
"github.com/Darklabel91/API_Names/routes"
87
)
98

10-
const FILENAME = "logs.txt"
11-
129
func main() {
1310
r := database.InitDb()
1411
if r == nil {
1512
return
1613
}
1714

1815
fmt.Println("- Listening and serving")
19-
go log.StartExportLog(FILENAME)
2016
routes.HandleRequests()
2117
}

middleware/requireAuth.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,15 @@ import (
1212
"time"
1313
)
1414

15-
const MaxThreadsByToken = 10
15+
const MaxThreadsByToken = 5
1616

17-
// RequireAuth returns a Gin middleware function that checks for a valid JWT token in the request header or cookie, and limits the rate of requests to prevent DDoS attacks.
17+
// RequireAuth returns a Gin middleware function that checks for a valid JWT token in the request header or cookie, and limits the rate of requests to`prevent DDoS attacks.
1818
// - The rate limit is enforced using a token bucket algorithm.
1919
// - The rate limit and queue capacity can be adjusted by modifying the constants in the function.
2020
// - If the token is invalid or has expired, or if the request cannot be processed due to an error, the middleware function aborts the request with a 401 Unauthorized HTTP status code.
2121
func RequireAuth() gin.HandlerFunc {
2222
// Create a new rate limiter to limit the number of requests per second
23-
limiter := rate.NewLimiter(1000, MaxThreadsByToken)
23+
limiter := rate.NewLimiter(20000, MaxThreadsByToken)
2424

2525
return func(c *gin.Context) {
2626
// Check if the request has exceeded the rate limit

models/modelsGrom.go

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,5 @@ type User struct {
1818
gorm.Model
1919
Email string `gorm:"unique"`
2020
Password string
21-
}
22-
23-
//Log is the struct used to register the log file
24-
// Define a struct to hold the log data
25-
type Log struct {
26-
gorm.Model
27-
Time string
28-
Status string
29-
Latency string
30-
IP string
31-
Method string
32-
Path string
21+
IP string
3322
}

routes/routes.go

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,31 +6,24 @@ import (
66
"github.com/Darklabel91/API_Names/middleware"
77
"github.com/Darklabel91/API_Names/models"
88
"github.com/gin-gonic/gin"
9-
"os"
109
"sync"
1110
)
1211

1312
const DOOR = ":8080"
1413
const FILENAME = "logs.txt"
1514

16-
var allowedIPs = []string{"127.0.0.1", "::1"} // List of allowed IP addresses
17-
1815
func HandleRequests() {
1916
gin.SetMode(gin.ReleaseMode)
2017
r := gin.Default()
2118

2219
//use the OnlyAllowIPs middleware on all routes
23-
err := r.SetTrustedProxies(allowedIPs)
20+
err := r.SetTrustedProxies(controllers.GetTrustedIPs())
2421
if err != nil {
2522
return
2623
}
2724

2825
// Create a file to store the logs
29-
file, err := os.OpenFile(FILENAME, os.O_RDWR|os.O_CREATE, 0666)
30-
if err != nil {
31-
return
32-
}
33-
r.Use(gin.LoggerWithWriter(file))
26+
r.Use(controllers.SetLogger(FILENAME))
3427

3528
//set up routes
3629
r.POST("/signup", controllers.Signup)
@@ -45,9 +38,7 @@ func HandleRequests() {
4538
r.PATCH("/:id", middleware.ValidateIDParam(), controllers.UpdateName)
4639
r.POST("/name", controllers.CreateName)
4740
r.GET("/name/:name", middleware.ValidateNameParam(), waitGroupName)
48-
r.GET("/metaphone/:name", middleware.ValidateNameParam(), preloadNameTypes(), middleware.ValidateNameParam(), waitGroupMetaphone)
49-
50-
gin.Logger()
41+
r.GET("/metaphone/:name", middleware.ValidateNameParam(), preloadNameTypes(), waitGroupMetaphone)
5142

5243
// run
5344
err = r.Run(DOOR)

0 commit comments

Comments
 (0)