-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
829 lines (642 loc) · 20.2 KB
/
main.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
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"math/rand"
"net/http"
"os"
"strings"
"sync"
"time"
firebase "firebase.google.com/go"
"firebase.google.com/go/messaging"
"github.com/golang-jwt/jwt/v4"
"github.com/gorilla/mux"
"github.com/joho/godotenv"
"github.com/rs/cors"
"golang.org/x/crypto/bcrypt"
"google.golang.org/api/option"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func generateJwtSecret() string {
letterRunes := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
b := make([]rune, 32)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return string(b)
}
func CheckEnv() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
dbHost := os.Getenv("DB_HOST")
dbUsername := os.Getenv("DB_USERNAME")
dbPassword := os.Getenv("DB_PASSWORD")
dbName := os.Getenv("DB_NAME")
serverPort := os.Getenv("SERVER_PORT")
jwtSecret := os.Getenv("JWT_SECRET")
adminUsername := os.Getenv("ADMIN_USERNAME")
adminPassword := os.Getenv("ADMIN_PASSWORD")
serviceAccountFile := os.Getenv("SERVICE_ACCOUNT_FILE")
if serverPort == "" {
serverPort = "8000"
}
if jwtSecret == "" {
jwtSecret = generateJwtSecret()
}
if adminUsername == "" {
panic("Admin username cannot be empty!")
}
if adminPassword == "" {
panic("Admin password cannot be empty!")
}
godotenv.Write(map[string]string{
"DB_HOST": dbHost,
"DB_USERNAME": dbUsername,
"DB_PASSWORD": dbPassword,
"DB_NAME": dbName,
"SERVER_PORT": serverPort,
"JWT_SECRET": jwtSecret,
"ADMIN_USERNAME": adminUsername,
"ADMIN_PASSWORD": adminPassword,
"SERVICE_ACCOUNT_FILE": serviceAccountFile,
}, "./.env")
}
type GormModel struct {
ID uint `gorm:"primary_key" json:"id"`
UUID string `json:"uuid"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt *time.Time `json:"deletedAt"`
}
type User struct {
GormModel
Name string `json:"name"`
Username string `json:"username"`
Password string `json:"password"`
FcmToken string `json:"fcmToken"`
}
type UserBody struct {
ID uint `json:"id"`
Name string `json:"name"`
Username string `json:"username"`
ChangePassword bool `json:"changePassword"`
NewPassword string `json:"newPassword"`
}
func userToUserBody(user User) UserBody {
return UserBody{
ID: user.ID,
Name: user.Name,
Username: user.Username,
ChangePassword: false,
NewPassword: "",
}
}
type UserRole struct {
GormModel
UserID uint `json:"userId"`
User User `json:"user"`
RoleID uint `json:"roleId"`
Role Role `json:"role"`
}
type Role struct {
GormModel
Name string `json:"name"`
}
type Article struct {
GormModel
Date time.Time `json:"date"`
Title string `json:"title"`
Content string `json:"content"`
}
type AdminConfig struct {
GormModel
FacebookUrl string `json:"facebookURL"`
InstagramUrl string `json:"instagramURL"`
WhatsappNumber string `json:"whatsappNumber"`
}
type Complaint struct {
GormModel
Name string `json:"name"`
Phone string `json:"phone"`
Address string `json:"address"`
Answer string `json:"answer"`
Complaint string `json:"complaint"`
}
type ManpowerCategory struct {
GormModel
Name string `json:"name"`
}
type ManpowerStatus struct {
GormModel
Name string `json:"name"`
}
type ManpowerStatusAmount struct {
GormModel
Value int `json:"value"`
ManpowerCategoryID *uint `json:"manpowerCategoryId"`
ManpowerCategoryUuid string `json:"manpowerCategoryUuid"`
ManpowerCategory ManpowerCategory `json:"manpowerCategory"`
ManpowerStatusID *uint `json:"manpowerStatusId"`
ManpowerStatusUuid string `json:"manpowerStatusUuid"`
ManpowerStatus ManpowerStatus `json:"manpowerStatus"`
}
func main() {
CheckEnv()
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
dbHost := os.Getenv("DB_HOST")
dbUsername := os.Getenv("DB_USERNAME")
dbPassword := os.Getenv("DB_PASSWORD")
dbName := os.Getenv("DB_NAME")
// Setup database
dsn := dbUsername + ":" + dbPassword + "@tcp(" + dbHost + ":3306)/" + dbName + "?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
app, err := firebase.NewApp(context.Background(), nil, option.WithCredentialsFile("service-account.json"))
if err != nil {
log.Fatalf("error initializing app: %v\n", err)
}
fmt.Println(app)
tables :=
[]interface{}{
User{},
UserRole{},
Role{},
Article{},
AdminConfig{},
Complaint{},
ManpowerCategory{},
ManpowerStatus{},
ManpowerStatusAmount{},
}
for _, table := range tables {
db.AutoMigrate(table)
}
if err != nil {
fmt.Println("Opening DB error", err)
fmt.Println(db)
return
}
r := mux.NewRouter()
r.Use(AuthMiddleware)
fcmSendMulti := func(tokens []string, title string, body string) {
// Obtain a messaging.Client from the App.
ctx := context.Background()
client, err := app.Messaging(ctx)
if err != nil {
log.Fatalf("error getting Messaging client: %v\n", err)
}
// See documentation on defining a message payload.
message := &messaging.MulticastMessage{
Notification: &messaging.Notification{
Title: title,
Body: body,
},
Tokens: tokens,
}
br, err := client.SendMulticast(context.Background(), message)
if err != nil {
log.Fatalln(err)
}
// See the BatchResponse reference documentation
// for the contents of response.
fmt.Printf("%d messages were sent successfully\n", br.SuccessCount)
}
r.HandleFunc("/fcm-test", func(w http.ResponseWriter, r *http.Request) {
// Obtain a messaging.Client from the App.
ctx := context.Background()
client, err := app.Messaging(ctx)
if err != nil {
log.Fatalf("error getting Messaging client: %v\n", err)
}
// See documentation on defining a message payload.
message := &messaging.Message{
Notification: &messaging.Notification{
Title: "Price drop",
Body: "5% off all electronics",
},
Token: "eWvUQpXgQem462q6qtJljm:APA91bFH6eDlMqPzLWolT6HwO-4HueRbD-xxIYEE9WQeIc0af4vwdKD78qv4BEo1EJFQHOFp3behskz1opTces-dpMIo5-20iwAOHs8Kjkp8ldtDIoL2L5zaCyzSk8Q-ZnsYEV2wdzIY",
}
// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
response, err := client.Send(ctx, message)
if err != nil {
log.Fatalln(err)
}
// Response is a message ID string.
fmt.Println("Successfully sent message:", response)
})
r.HandleFunc("/complaints", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
w.Header().Set("content-type", "application/json")
fmt.Println("GET")
var complaints []Complaint
db.Find(&complaints)
json.NewEncoder(w).Encode(&complaints)
case http.MethodPost:
var complaint Complaint
json.NewDecoder(r.Body).Decode(&complaint)
db.Save(&complaint)
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(&complaint)
tokens := func() []string {
var users []User
db.Find(&users)
tokens := []string{}
for _, user := range users {
if user.FcmToken != "" {
tokens = append(tokens, user.FcmToken)
}
}
return tokens
}()
if len(tokens) > 0 {
fcmSendMulti(tokens, "Aduan Baru", complaint.Name+": "+complaint.Complaint)
}
default:
fmt.Println("[complaints] method irrelevant")
}
}).Methods("GET", "POST")
CheckAdmin := func(auth string) bool {
fmt.Println("Auth token:", auth)
token, err := jwt.ParseWithClaims(auth, jwt.MapClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(os.Getenv("JWT_SECRET")), nil
})
if err != nil {
return false
}
// Cast
admin, ok := token.Claims.(jwt.MapClaims)["admin"].(bool)
if !ok {
return false
}
fmt.Println("Is admin:", admin)
fmt.Println(token.Claims)
return admin
}
// r.PathPrefix("/admin").Handler(http.StripPrefix("/admin", http.FileServer(http.Dir("./admin"))))
r.HandleFunc("/authorize-admin", func(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("authorization")
admin := CheckAdmin(auth)
if !admin {
fmt.Println(err)
fmt.Fprintf(w, "Error decoding token. Not admin")
w.WriteHeader(http.StatusUnauthorized)
return
}
})
r.HandleFunc("/complaints-save", func(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("authorization")
admin := CheckAdmin(auth)
if !admin {
fmt.Println(err)
fmt.Fprintf(w, "Error decoding token. Not admin")
w.WriteHeader(http.StatusUnauthorized)
return
}
var complaint Complaint
json.NewDecoder(r.Body).Decode(&complaint)
db.Save(&complaint)
json.NewEncoder(w).Encode(complaint)
w.WriteHeader(http.StatusCreated)
})
r.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("authorization")
fmt.Println("Auth token:", auth)
token, err := jwt.ParseWithClaims(auth, jwt.MapClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(os.Getenv("JWT_SECRET")), nil
})
fmt.Println(token.Claims)
if err != nil {
fmt.Println(err)
fmt.Fprintf(w, "Error decoding token")
w.WriteHeader(http.StatusUnauthorized)
return
}
})
// r.HandleFunc("/complaints-save", func(w http.ResponseWriter, r *http.Request) {
// auth := r.Header.Get("authorization")
// fmt.Println("Auth token:", auth)
// token, err := jwt.ParseWithClaims(auth, jwt.MapClaims{}, func(token *jwt.Token) (interface{}, error) {
// return []byte(os.Getenv("JWT_SECRET")), nil
// })
// if err != nil {
// fmt.Println(err)
// fmt.Fprintf(w, "Error decoding token")
// w.WriteHeader(http.StatusUnauthorized)
// }
// fmt.Println(token.Claims)
// })
getTokenId := func(auth string) (float64, error) {
claims := jwt.MapClaims{}
_, err := jwt.ParseWithClaims(auth, claims, func(token *jwt.Token) (interface{}, error) {
return []byte(os.Getenv("JWT_SECRET")), nil
})
if err != nil {
return 0, err
}
fmt.Println(claims["jti"])
// fmt.Println(claims["jti"].(string))
fmt.Println(claims["jti"].(float64))
claimsFloat, ok := claims["jti"].(float64)
if ok {
return claimsFloat, nil
}
return 0, err
}
type FcmTokenBody struct {
Token string `json:"token"`
}
r.HandleFunc("/save-fcm-token", func(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("authorization")
var fcmToken FcmTokenBody
json.NewDecoder(r.Body).Decode(&fcmToken)
fmt.Println("Auth token:", auth)
id, err := getTokenId(auth)
fmt.Println(err, id)
var user User
if db.Where("id = ?", id).First(&user).Error != nil {
fmt.Println("Error fetching user")
return
}
fmt.Println(user.Name)
user.FcmToken = fcmToken.Token
db.Save(&user)
})
r.HandleFunc("/users-jwt", func(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("authorization")
var fcmToken FcmTokenBody
json.NewDecoder(r.Body).Decode(&fcmToken)
fmt.Println("Auth token:", auth)
id, err := getTokenId(auth)
fmt.Println(err, id)
var user User
if db.Where("id = ?", id).First(&user).Error != nil {
fmt.Println("Error fetching user")
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "User not found")
return
}
json.NewEncoder(w).Encode(userToUserBody(user))
})
type ManpowerData struct {
ManpowerCategories []ManpowerCategory `json:"manpowerCategories"`
ManpowerCategoryDeleteIds []uint `json:"manpowerCategoryDeleteIds"`
ManpowerStatuses []ManpowerStatus `json:"manpowerStatuses"`
ManpowerStatusDeleteIds []uint `json:"manpowerStatusDeleteIds"`
ManpowerStatusAmounts []ManpowerStatusAmount `json:"manpowerStatusAmounts"`
ManpowerStatusAmountDeleteIds []uint `json:"manpowerStatusAmountDeleteIds"`
}
r.HandleFunc("/manpowers-save", func(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("authorization")
fmt.Println("Auth token:", auth)
admin := CheckAdmin(auth)
if !admin {
fmt.Println(err)
fmt.Fprintf(w, "Error decoding token. Not admin")
w.WriteHeader(http.StatusUnauthorized)
return
}
w.Header().Set("content-type", "application/json")
var manpowerData ManpowerData
json.NewDecoder(r.Body).Decode(&manpowerData)
fmt.Println("\n\n[MANPOWER DELETE ID]\n\n:", manpowerData.ManpowerCategoryDeleteIds)
for _, manpowerCategory := range manpowerData.ManpowerCategories {
db.Save(&manpowerCategory)
}
for _, id := range manpowerData.ManpowerCategoryDeleteIds {
fmt.Println("\n\n[DELETE]]\n\n", id)
db.Delete(&ManpowerCategory{}, id)
}
for _, manpowerStatus := range manpowerData.ManpowerStatuses {
db.Save(&manpowerStatus)
}
for _, id := range manpowerData.ManpowerStatusDeleteIds {
db.Delete(&ManpowerStatus{}, id)
}
for _, manpowerStatusAmount := range manpowerData.ManpowerStatusAmounts {
db.Save(&manpowerStatusAmount)
}
for _, id := range manpowerData.ManpowerStatusAmountDeleteIds {
db.Delete(&ManpowerStatusAmount{}, id)
}
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(manpowerData)
}).Methods("POST")
r.HandleFunc("/manpowercategories", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "application/json")
switch r.Method {
case "GET":
var manpowerCategories []ManpowerCategory
db.Find(&manpowerCategories)
json.NewEncoder(w).Encode(manpowerCategories)
case "POST":
auth := r.Header.Get("authorization")
fmt.Println("Auth token:", auth)
admin := CheckAdmin(auth)
if !admin {
fmt.Println(err)
fmt.Fprintf(w, "Error decoding token. Not admin")
w.WriteHeader(http.StatusUnauthorized)
return
}
fmt.Println("POST detect")
var manpowerCategory []ManpowerCategory
db.Save(&manpowerCategory)
json.NewEncoder(w).Encode(&manpowerCategory)
}
}).Methods("GET", "POST")
r.HandleFunc("/manpowerstatuses", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "application/json")
var manpowerStatuses []ManpowerStatus
db.Find(&manpowerStatuses)
json.NewEncoder(w).Encode(manpowerStatuses)
}).Methods("GET")
r.HandleFunc("/manpowerstatusamounts", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "application/json")
var manpowerStatusAmounts []ManpowerStatusAmount
db.Find(&manpowerStatusAmounts)
json.NewEncoder(w).Encode(manpowerStatusAmounts)
}).Methods("GET")
r.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
type LoginStruct struct {
Username string `json:"username"`
Password string `json:"password"`
}
var loginData LoginStruct
json.NewDecoder(r.Body).Decode(&loginData)
tokenString := ""
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
if loginData.Username != os.Getenv("ADMIN_USERNAME") {
var foundUser User
if db.Where("lower(username) = ?", strings.ToLower(loginData.Username)).First(&foundUser).Error != nil {
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "Username tidak ditemukan!")
return
}
err := bcrypt.CompareHashAndPassword([]byte(foundUser.Password), []byte(loginData.Password))
if err != nil {
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "Password salah!")
return
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"exp": time.Now().Unix() + 86400*365*30,
"admin": false,
"jti": foundUser.ID,
})
// Sign and get the complete encoded token as a string using the secret
tokenString, err = token.SignedString([]byte(os.Getenv("JWT_SECRET")))
fmt.Println(tokenString, err)
} else {
if loginData.Password != os.Getenv("ADMIN_PASSWORD") {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "Password salah!")
return
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"exp": time.Now().Unix() + 86400*365*30,
"admin": true,
"jti": 0,
})
// Sign and get the complete encoded token as a string using the secret
var err error
tokenString, err = token.SignedString([]byte(os.Getenv("JWT_SECRET")))
fmt.Println(tokenString, err)
}
fmt.Fprintf(w, "%s", tokenString)
}).Methods("POST")
r.HandleFunc("/users-view", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "application/json")
var users []User
db.Find(&users)
usersMapped := []UserBody{}
for _, user := range users {
usersMapped = append(usersMapped, userToUserBody(user))
}
json.NewEncoder(w).Encode(usersMapped)
}).Methods("GET")
type UserSave struct {
UserBody []UserBody `json:"userBody"`
UserDeleteIds []uint `json:"userDeleteIds"`
}
r.HandleFunc("/duplicate-remove", func(w http.ResponseWriter, r *http.Request) {
var manpowerCategories []ManpowerCategory
db.Find(&manpowerCategories)
newCategories := []ManpowerCategory{}
// Delete duplicate categories
for _, category := range manpowerCategories {
found := false
for _, newCategory := range newCategories {
if newCategory.Name == category.Name {
found = true
break
}
}
if !found {
newCategories = append(newCategories, category)
}
}
for _, category := range newCategories {
fmt.Println(category.Name)
var foundCategories []ManpowerCategory
db.Where("name = ?", category.Name).Find(&foundCategories)
var wg sync.WaitGroup
for _, foundCategory := range foundCategories {
wg.Add(1)
go func(foundCategory ManpowerCategory, mainCategory ManpowerCategory) {
defer wg.Done()
if foundCategory.ID != mainCategory.ID {
db.Delete(ManpowerCategory{}, foundCategory.ID)
}
}(foundCategory, category)
}
wg.Wait()
}
var wg sync.WaitGroup
for _, category := range manpowerCategories {
// fmt.Println(category)
wg.Add(1)
go func(category ManpowerCategory) {
defer wg.Done()
var foundManpowerAmounts []ManpowerStatusAmount
db.Where("manpower_category_uuid = ?", category.UUID).Find(&foundManpowerAmounts)
if len(foundManpowerAmounts) > 1 {
for i, manpowerStatusAmount := range foundManpowerAmounts {
if i > 0 {
fmt.Println(category.Name, manpowerStatusAmount.ID, manpowerStatusAmount.Value)
db.Delete(&ManpowerStatusAmount{}, manpowerStatusAmount.ID)
}
}
}
}(category)
wg.Wait()
}
})
r.HandleFunc("/users-save", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "application/json")
var userSave UserSave
json.NewDecoder(r.Body).Decode(&userSave)
fmt.Println(userSave.UserDeleteIds)
for _, user := range userSave.UserBody {
var foundUser User
if db.Where("username = ?", user.Username).Find(&foundUser).Error != nil {
newUser := User{
Username: user.Username,
Name: user.Name,
}
newUser.ID = user.ID
if user.ChangePassword {
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(user.NewPassword), bcrypt.DefaultCost)
if err != nil {
fmt.Println("Error gen password")
}
newUser.Password = string(hashedPassword)
}
db.Save(&newUser)
} else {
fmt.Println(user.Name, user.Username, foundUser.Username)
foundUser.ID = user.ID
foundUser.Name = user.Name
foundUser.Username = user.Username
if user.ChangePassword {
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(user.NewPassword), bcrypt.DefaultCost)
if err != nil {
fmt.Println("Error gen password")
}
foundUser.Password = string(hashedPassword)
}
fmt.Println(foundUser)
db.Save(&foundUser)
}
}
for _, userDeleteId := range userSave.UserDeleteIds {
fmt.Println(userDeleteId)
db.Delete(&User{}, userDeleteId)
}
json.NewEncoder(w).Encode(userSave)
}).Methods("POST")
r.PathPrefix("/").Handler(http.FileServer(http.Dir("./landing/")))
serverPort := os.Getenv("SERVER_PORT")
fmt.Println("Running on ", "http://localhost:"+serverPort)
// Bind to a port and pass our router in
log.Fatal(http.ListenAndServe(":"+serverPort, cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedHeaders: []string{"*"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowCredentials: true,
// Enable Debugging for testing, consider disabling in production
Debug: true,
}).Handler(r)))
}