Skip to content

Commit 77c91b2

Browse files
committed
- improve comments all around
- minor change on requireAuth, now there is a specific function to deal with the rate limit - minor bug fix on UpdateName in crud file
1 parent 5b44fc6 commit 77c91b2

File tree

15 files changed

+391
-300
lines changed

15 files changed

+391
-300
lines changed

controllers/crud.go

Lines changed: 63 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -9,57 +9,62 @@ import (
99
"sync"
1010
)
1111

12-
//CreateName create new name on database of type NameType
12+
//CreateName creates a new name in the database of type NameType
1313
func CreateName(c *gin.Context) {
14-
//name is passed by middlewares
14+
// The name is passed by middlewares
1515
nameValue, ok := c.Get("name")
1616
if !ok {
1717
c.JSON(http.StatusBadRequest, gin.H{"Message": "name is not present on middlewares"})
1818
return
1919
}
2020

21-
//parse nameValue into models.NameTypeInput
21+
// Parse nameValue into models.NameTypeInput
2222
var input models.NameType
2323
input, ok = nameValue.(models.NameType)
2424
if !ok {
2525
c.JSON(http.StatusBadRequest, gin.H{"Message": "failed to parse name"})
2626
return
2727
}
2828

29-
//Check the cache
29+
// Check the cache
3030
preloadTable := checkCache(c)
3131

32-
//Check if there's an exact name on the database
32+
// Check if there's an exact name on the database
3333
for _, name := range preloadTable {
3434
if name.Name == input.Name {
3535
c.JSON(http.StatusBadRequest, gin.H{"Message": " Duplicate entry " + name.Name})
3636
return
3737
}
3838
}
3939

40-
//create name
40+
// Create name
4141
n, err := input.CreateName()
4242
if err != nil {
4343
c.JSON(http.StatusInternalServerError, gin.H{"Error": err.Error()})
4444
return
4545
}
4646

47+
// Clear cache
4748
clearCache(c)
49+
50+
// Return successful response
4851
c.JSON(http.StatusOK, n)
4952
return
5053
}
5154

52-
//GetID read name by id
55+
//GetID reads a name by id
5356
func GetID(c *gin.Context) {
5457
var name models.NameType
5558

59+
// Convert id string into int
5660
param := c.Params.ByName("id")
5761
id, err := strconv.Atoi(param)
5862
if err != nil {
5963
c.JSON(http.StatusBadRequest, gin.H{"Id": "error on converting id"})
6064
return
6165
}
6266

67+
// Get the name by id
6368
n, _, err := name.GetNameById(id)
6469
if err != nil {
6570
c.JSON(http.StatusNotFound, gin.H{"Not found": "name id not found"})
@@ -70,14 +75,19 @@ func GetID(c *gin.Context) {
7075
return
7176
}
7277

78+
// Return successful response
7379
c.JSON(http.StatusOK, n)
80+
return
7481
}
7582

76-
//GetName read name by name
83+
//GetName reads a name by name
7784
func GetName(c *gin.Context) {
7885
var name models.NameType
7986

87+
// Get name to be searched
8088
param := c.Params.ByName("name")
89+
90+
// Search for name
8191
n, err := name.GetNameByName(strings.ToUpper(param))
8292
if err != nil {
8393
c.JSON(http.StatusNotFound, gin.H{"Not found": "name not found"})
@@ -88,42 +98,43 @@ func GetName(c *gin.Context) {
8898
return
8999
}
90100

101+
// Return successful response
91102
c.JSON(http.StatusOK, n)
92103
return
93104
}
94105

95-
//GetMetaphoneMatch read name by metaphone
106+
//GetMetaphoneMatch reads a name by metaphone
96107
func GetMetaphoneMatch(c *gin.Context) {
97108
var nameType models.NameType
98109

99-
//name to be searched
110+
// Get name to be searched
100111
name := c.Params.ByName("name")
101112

102-
//Check the cache
113+
// Check the cache
103114
preloadTable := checkCache(c)
104115

105-
//search similar names
116+
// Search for similar names
106117
canonicalEntity, err := nameType.GetSimilarMatch(name, preloadTable)
107118
if err != nil {
108119
c.JSON(http.StatusNotFound, gin.H{"Message": "Couldn't find canonical entity"})
109120
return
110-
} else {
111-
c.JSON(200, canonicalEntity)
112-
return
113121
}
122+
123+
// Return successful response
124+
c.JSON(200, canonicalEntity)
125+
return
114126
}
115127

116-
//UpdateName update name by id
128+
// UpdateName updates name by id
117129
func UpdateName(c *gin.Context) {
118-
//convert id string into int
130+
// Convert id string into int
119131
param := c.Params.ByName("id")
120132
id, err := strconv.Atoi(param)
121133
if err != nil {
122134
c.JSON(http.StatusBadRequest, gin.H{"Id": "error on converting id"})
123135
return
124136
}
125-
126-
//get the name by id
137+
// Get the name by id
127138
var n models.NameType
128139
name, db, err := n.GetNameById(id)
129140
if err != nil {
@@ -135,62 +146,68 @@ func UpdateName(c *gin.Context) {
135146
return
136147
}
137148

138-
//name is passed by middlewares
149+
// Name is passed by middlewares
139150
nameValue, ok := c.Get("name")
140151
if !ok {
141152
c.JSON(http.StatusBadRequest, gin.H{"Message": "name is not present on middlewares"})
142153
return
143154
}
144155

145-
//parse nameValue into models.NameTypeInput
156+
// Parse nameValue into models.NameTypeInput
146157
var input models.NameType
147158
input, ok = nameValue.(models.NameType)
148159
if !ok {
149160
c.JSON(http.StatusBadRequest, gin.H{"Message": "failed to parse name"})
150161
return
151162
}
152163

164+
// Check if input is the same as the name in the database
153165
if input.Name == name.Name && input.Classification == name.Classification && input.Metaphone == name.Metaphone && input.NameVariations == name.NameVariations {
154166
c.JSON(http.StatusBadRequest, gin.H{"Message": "Every item on json is the same on the database id " + param})
155167
return
156168
} else {
157-
if input.Name != "" && input.Name == name.Name {
169+
// Update the name properties if they have changed
170+
if input.Name != "" && input.Name != name.Name {
158171
name.Name = input.Name
159172
}
160-
if input.Classification != "" && input.Classification == name.Classification {
173+
if input.Classification != "" && input.Classification != name.Classification {
161174
name.Classification = input.Classification
162175
}
163-
if input.Metaphone != "" && input.Metaphone == name.Metaphone {
176+
if input.Metaphone != "" && input.Metaphone != name.Metaphone {
164177
name.Metaphone = input.Metaphone
165178
}
166-
if input.NameVariations != "" && input.NameVariations == name.NameVariations {
179+
if input.NameVariations != "" && input.NameVariations != name.NameVariations {
167180
name.NameVariations = input.NameVariations
168181
}
169182

170-
r := db.Save(name)
171-
if r.Error != nil {
172-
c.JSON(http.StatusBadRequest, gin.H{"Error": r.Error})
183+
// Save the updated name to the database
184+
if err := db.Save(name).Error; err != nil {
185+
c.JSON(http.StatusBadRequest, gin.H{"Error": err})
173186
return
174187
}
175188

189+
// Return the updated name
176190
c.JSON(http.StatusOK, name)
191+
192+
// Clear the cache
177193
clearCache(c)
194+
178195
return
179196
}
180-
181197
}
182198

183-
//DeleteName delete name off database by id
199+
// DeleteName deletes name off database by id
184200
func DeleteName(c *gin.Context) {
185201
var name models.NameType
186-
202+
// Convert id string into int
187203
param := c.Params.ByName("id")
188204
id, err := strconv.Atoi(param)
189205
if err != nil {
190206
c.JSON(http.StatusInternalServerError, gin.H{"Error": "error on converting id"})
191207
return
192208
}
193209

210+
// Check if the name with given id exists
194211
n, _, err := name.GetNameById(id)
195212
if err != nil {
196213
c.JSON(http.StatusNotFound, gin.H{"Not found": "name id not found"})
@@ -201,40 +218,48 @@ func DeleteName(c *gin.Context) {
201218
return
202219
}
203220

204-
_, err = name.DeleteNameById(id)
205-
if err != nil {
221+
// Delete the name from the database
222+
if _, err = name.DeleteNameById(id); err != nil {
206223
c.JSON(http.StatusNotFound, gin.H{"Not found": "name id not found"})
207224
return
208225
}
209-
210-
c.JSON(http.StatusOK, gin.H{"Delete": "id " + param + " was deleted"})
211-
clearCache(c)
212-
return
213226
}
214227

228+
// checkCache retrieves the cached name types from the context if they exist, otherwise it retrieves them from the database
215229
func checkCache(c *gin.Context) []models.NameType {
230+
// Initialize a variable for the NameType type
216231
var nameType models.NameType
232+
// Initialize a variable for the cached name types
217233
var preloadTable []models.NameType
218-
234+
// Get the cached name types from the context
219235
cache, existKey := c.Get("nameTypes")
236+
// If the name types are found in the cache, set them to the `preloadTable` variable
220237
if existKey {
221238
preloadTable = cache.([]models.NameType)
222239
} else {
240+
// If the name types are not found in the cache, retrieve them from the database
223241
allNames, err := nameType.GetAllNames()
224242
if err != nil {
243+
// If there is an error retrieving the name types from the database, return nil
225244
c.JSON(http.StatusInternalServerError, gin.H{"Message": "Error on caching all name types"})
226245
return nil
227246
}
247+
// Set the retrieved name types in the cache
228248
preloadTable = allNames
229249
c.Set("nameTypes", preloadTable)
230250
}
231251

252+
// Return the cached name types
232253
return preloadTable
233254
}
234255

256+
// clearCache deletes the cached name types from the context if they exist
235257
func clearCache(c *gin.Context) {
258+
// Get the cached name types from the context
236259
cache, exist := c.Get("nameTypes")
260+
// If the name types are found in the cache, delete them
237261
if exist {
262+
// Convert the cache to a sync.Map so that we can delete the cached name types
238263
if cm, ok := cache.(sync.Map); ok {
239264
cm.Delete("preloadTable")
240265
}

controllers/login.go

Lines changed: 17 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,50 +2,49 @@ package controllers
22

33
import (
44
"errors"
5-
"github.com/Darklabel91/API_Names/models"
6-
"github.com/gin-gonic/gin"
7-
"github.com/golang-jwt/jwt/v5"
8-
"golang.org/x/crypto/bcrypt"
95
"net/http"
106
"os"
117
"strconv"
128
"time"
9+
10+
"github.com/Darklabel91/API_Names/models"
11+
"github.com/gin-gonic/gin"
12+
"github.com/golang-jwt/jwt/v4"
13+
"golang.org/x/crypto/bcrypt"
1314
)
1415

15-
//Login verifies cookie session for login
16+
// Login verifies email and password and sets a JWT token as a cookie for authentication
1617
func Login(c *gin.Context) {
17-
// Get the email and password from request body
18+
// Get email and password from request body
1819
var body models.UserInputBody
19-
20-
if c.Bind(&body) != nil {
20+
if err := c.Bind(&body); err != nil {
2121
c.JSON(http.StatusBadRequest, gin.H{"Message": "Failed to read body"})
2222
return
2323
}
2424

25-
// Look up requested user
25+
// Look up user by email
2626
var user models.User
2727
u, err := user.GetUserByEmail(body.Email)
2828
if err != nil {
2929
c.JSON(http.StatusBadRequest, gin.H{"Message": "Invalid email or password"})
3030
return
3131
}
3232

33-
// Compare sent-in password with saved user password hash
34-
err = bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(body.Password))
35-
if err != nil {
33+
// Compare password from request body with user's hashed password
34+
if err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(body.Password)); err != nil {
3635
c.JSON(http.StatusBadRequest, gin.H{"Message": "Invalid email or password"})
3736
return
3837
}
3938

4039
// Generate JWT token
41-
token, err := generateJWTToken(u.ID, 1)
40+
token, err := generateJWTToken(u.ID, 1*time.Hour*24)
4241
if err != nil {
4342
c.JSON(http.StatusInternalServerError, gin.H{"Message": "Failed to generate token"})
4443
return
4544
}
4645

4746
// Set token as a cookie
48-
c.SetCookie("token", token, 60*60, "/", "", false, true)
47+
c.SetCookie("token", token, int(1*time.Hour.Seconds()), "/", "", false, true)
4948

5049
// Return success response
5150
c.JSON(http.StatusOK, gin.H{"Message": "Login successful"})
@@ -57,10 +56,10 @@ func generateJWTToken(userID uint, amountDays time.Duration) (string, error) {
5756
expirationTime := time.Now().Add(amountDays * 24 * time.Hour)
5857

5958
// Create JWT claims
60-
claims := jwt.RegisteredClaims{
61-
ExpiresAt: jwt.NewNumericDate(expirationTime),
62-
IssuedAt: jwt.NewNumericDate(time.Now()),
63-
Subject: strconv.Itoa(int(userID)),
59+
claims := jwt.MapClaims{
60+
"exp": expirationTime.Unix(),
61+
"iat": time.Now().Unix(),
62+
"sub": strconv.Itoa(int(userID)),
6463
}
6564

6665
// Create token using claims and signing method

0 commit comments

Comments
 (0)