-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdb.go
More file actions
781 lines (621 loc) · 19.3 KB
/
db.go
File metadata and controls
781 lines (621 loc) · 19.3 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
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
// Database operations for varuh
package varuh
import (
"database/sql"
"errors"
"fmt"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
// Structure representing an entry in the db
type Entry struct {
ID int `gorm:"column:id;autoIncrement;primaryKey"`
Title string `gorm:"column:title"` // For card type this -> Card Name
User string `gorm:"column:user"` // For card type this -> Card Holder Name
Url string `gorm:"column:url"` // For card type this -> Card Number
Password string `gorm:"column:password"` // For card type this -> CVV number
Pin string `gorm:"column:pin"` // For card type this -> card pin
ExpiryDate string `gorm:"colum:expiry_date"` // For card type this -> Card expiry date
Issuer string `gorm:"column:issuer"` // For card type this -> Issuing bank
Class string `gorm:"column:class"` // For card type this -> visa/mastercard/amex etc
Notes string `gorm:"column:notes"`
Tags string `gorm:"column:tags"`
Type string `gorm:"column:type"` // Entry type, default/card/ID
Timestamp time.Time `gorm:"type:timestamp;default:(datetime('now','localtime'))"` // sqlite3
// ID int `gorm:"column:id;autoIncrement;primaryKey"`
// Type string `gorm:"column:type"` // Type of entry - password (default), card, identity etc
// Title string `gorm:"column:title"`
// Name string `gorm:"column:name"` // Card holder name/ID card name - for types cards/identity
// Company string `gorm:"column:company"` // Company name of person - for type identity and
// // Credit card company for type CC
// Number string `gorm:"column:number"` // Number type - CC number for credit cards
// // ID card number for identity types
// SecurityCode string `gorm:"security_code"` // CVV number/security code for CC type
// ExpiryMonth string `gorm:"expiry_month"` // CC or Identity document expiry month
// ExpiryDay string `gorm:"expiry_day"` // Identity document expiry day
// ExpiryYear string `gorm:"expiry_year"` // CC or Identity document expiry year
// FirstName string `gorm:"column:first_name"` // first name - for ID card types
// MiddleName string `gorm:"column:middle_name"` // middle name - for ID card types
// LastName string `gorm:"column:last_name"` // last name - for ID card types
// Email string `gorm:"email"` // Email - for ID card types
// PhoneNumber string `gorm:"phone_number"` // Phone number - for ID card types
// Active bool `gorm:"active;default:true"` // Is the id card/CC active ?
// User string `gorm:"column:user"`
// Url string `gorm:"column:url"`
// Password string `gorm:"column:password"`
// Notes string `gorm:"column:notes"`
// Tags string `gorm:"column:tags"`
// Timestamp time.Time `gorm:"type:timestamp;default:(datetime('now','localtime'))"` // sqlite3
}
func (e *Entry) TableName() string {
return "entries"
}
// Structure representing an extended entry in the db - for custom fields
type ExtendedEntry struct {
ID int `gorm:"column:id;autoIncrement;primaryKey"`
FieldName string `gorm:"column:field_name"`
FieldValue string `gorm:"column:field_value"`
Timestamp time.Time `gorm:"type:timestamp;default:(datetime('now','localtime'))"` // sqlite3
Entry Entry `gorm:"foreignKey:EntryID"`
EntryID int
}
func (ex *ExtendedEntry) TableName() string {
return "exentries"
}
type Address struct {
ID int `gorm:"column:id;autoIncrement;primaryKey"`
Number string `gorm:"column:number"` // Flat or building number
Building string `gorm:"column:building"` // Apartment or building or society name
Street string `gorm:"column:street"` // Street address
Locality string `gorm:"column:locality"` // Name of the locality e.g: Whitefield
Area string `gorm:"column:area"` // Name of the larger area e.g: East Bangalore
City string `gorm:"column:city"` // Name of the city e.g: Bangalore
State string `gorm:"column:state"` // Name of the state e.g: Karnataka
Country string `gorm:"column:country"` // Name of the country e.g: India
Landmark string `gorm:"column:landmark"` // Name of landmark if any
ZipCode string `gorm:"column:zipcode"` // PIN/ZIP code
Type string `gorm:"column:type"` // Type of address: Home/Work/Business
Entry Entry `gorm:"foreignKey:EntryID"`
EntryID int
}
func (ad *Address) TableName() string {
return "address"
}
// Clone an entry
func (e1 *Entry) Copy(e2 *Entry) {
if e2 != nil {
switch e2.Type {
case "password":
e1.Title = e2.Title
e1.User = e2.User
e1.Url = e2.Url
e1.Password = e2.Password
e1.Notes = e2.Notes
e1.Tags = e2.Tags
e1.Type = e2.Type
case "card":
e1.Title = e2.Title
e1.User = e2.User // card holder name
e1.Issuer = e2.Issuer
e1.Url = e2.Url
e1.Password = e2.Password
e1.ExpiryDate = e2.ExpiryDate
e1.Tags = e2.Tags
e1.Notes = e2.Notes
e1.Type = e2.Type
// case "identity":
// e1.Title = e2.Title
// e1.Name = e2.Name
// e1.Company = e2.Company
// e1.FirstName = e2.FirstName
// e1.LastName = e2.LastName
// e1.MiddleName = e2.MiddleName
// e1.User = e2.User
// e1.Email = e2.Email
// e1.PhoneNumber = e2.PhoneNumber
// e1.Number = e2.Number
// e1.Notes = e2.Notes
// e1.Tags = e2.Tags
// e1.Type = e2.Type
}
}
}
// Clone an entry
func (e1 *ExtendedEntry) Copy(e2 *ExtendedEntry) {
if e2 != nil {
e1.FieldName = e2.FieldName
e1.FieldValue = e2.FieldValue
e1.EntryID = e2.EntryID
}
}
// Create a new database
func OpenDatabase(filePath string) (error, *gorm.DB) {
// Check if file exists first
if filePath == "" {
return errors.New("database path cannot be empty"), nil
}
if _, err := os.Stat(filePath); os.IsNotExist(err) {
return fmt.Errorf("database file does not exist: %s", filePath), nil
}
db, err := gorm.Open(sqlite.Open(filePath), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})
return err, db
}
// Create a new table for Entries in the database
func CreateNewEntry(db *gorm.DB) error {
return db.AutoMigrate(&Entry{})
}
// Create a new table for Extended Entries in the database
func CreateNewExEntry(db *gorm.DB) error {
return db.AutoMigrate(&ExtendedEntry{})
}
// Init new database including tables
func InitNewDatabase(dbPath string) error {
var err error
var db *gorm.DB
var absPath string
if dbPath == "" {
return errors.New("database path cannot be empty")
}
if HasActiveDatabase() {
// Has an active database - encrypt it before creating new one
_, activeDbPath := GetActiveDatabase()
absPath, _ = filepath.Abs(dbPath)
if absPath == activeDbPath {
fmt.Printf("Database already exists and is active - %s\n", dbPath)
return nil
} else {
// TBD
fmt.Printf("Encrytping current database - %s\n", activeDbPath)
EncryptDatabase(activeDbPath, nil)
}
}
if _, err = os.Stat(dbPath); err == nil {
// filePath exists, remove it
os.Remove(dbPath)
}
err, db = OpenDatabase(dbPath)
if err != nil {
fmt.Printf("Error creating new database - \"%s\"\n", err.Error())
return err
}
err = CreateNewEntry(db)
if err != nil {
fmt.Printf("Error creating schema - \"%s\"\n", err.Error())
return err
}
err = CreateNewExEntry(db)
if err != nil {
fmt.Printf("Error creating schema - \"%s\"\n", err.Error())
return err
}
fmt.Printf("Created new database - %s\n", dbPath)
// Update config
absPath, err = filepath.Abs(dbPath)
// Chmod it
os.Chmod(absPath, 0600)
if err == nil {
fmt.Printf("Updating active db path - %s\n", absPath)
UpdateActiveDbPath(absPath)
} else {
fmt.Printf("Error - %s\n", err.Error())
return err
}
return nil
}
// Open currently active database
func openActiveDatabase() (error, *gorm.DB) {
var dbPath string
var err error
err, dbPath = GetActiveDatabase()
if err != nil {
fmt.Printf("Error getting active database path - %s\n", err.Error())
return err, nil
}
err, db := OpenDatabase(dbPath)
if err != nil {
fmt.Printf("Error opening active database path - %s: %s\n", dbPath, err.Error())
return err, nil
}
return nil, db
}
// Add custom entries to a database entry
func AddCustomEntries(db *gorm.DB, entry *Entry, customEntries []CustomEntry) error {
var count int
var err error
err = CreateNewExEntry(db)
if err != nil {
fmt.Printf("Error creating schema - \"%s\"\n", err.Error())
return err
}
for _, customEntry := range customEntries {
var exEntry ExtendedEntry
exEntry = ExtendedEntry{FieldName: customEntry.FieldName, FieldValue: customEntry.FieldValue,
EntryID: entry.ID}
resultEx := db.Create(&exEntry)
if resultEx.Error == nil && resultEx.RowsAffected == 1 {
count += 1
}
}
fmt.Printf("Created %d custom entries for entry: %d.\n", count, entry.ID)
return nil
}
// Replace custom entries to a database entry (Drop existing and add fresh)
func ReplaceCustomEntries(db *gorm.DB, entry *Entry, updatedEntries []CustomEntry) error {
var count int
var err error
var customEntries []ExtendedEntry
err = CreateNewExEntry(db)
if err != nil {
fmt.Printf("Error creating schema - \"%s\"\n", err.Error())
return err
}
db.Where("entry_id = ?", entry.ID).Delete(&customEntries)
for _, customEntry := range updatedEntries {
var exEntry ExtendedEntry
exEntry = ExtendedEntry{FieldName: customEntry.FieldName, FieldValue: customEntry.FieldValue,
EntryID: entry.ID}
resultEx := db.Create(&exEntry)
if resultEx.Error == nil && resultEx.RowsAffected == 1 {
count += 1
}
}
fmt.Printf("Created %d custom entries for entry: %d.\n", count, entry.ID)
return nil
}
// Add a new entry to current database
func AddNewDatabaseEntry(title, userName, url, passwd, tags string,
notes string, customEntries []CustomEntry) error {
var entry Entry
var err error
var db *gorm.DB
entry = Entry{Title: title, User: userName, Url: url, Password: passwd, Tags: strings.TrimSpace(tags),
Notes: notes}
err, db = openActiveDatabase()
if err == nil && db != nil {
// result := db.Debug().Create(&entry)
result := db.Create(&entry)
if result.Error == nil && result.RowsAffected == 1 {
// Add custom fields if given
fmt.Printf("Created new entry with id: %d.\n", entry.ID)
if len(customEntries) > 0 {
return AddCustomEntries(db, &entry, customEntries)
}
return nil
} else if result.Error != nil {
return result.Error
}
}
return err
}
func UpdateDatabaseCardEntry(entry *Entry, cardName, cardNumber, cardHolder, cardClass,
cardCvv, cardPin, cardExpiry, notes, tags string, customEntries []CustomEntry,
flag bool) error {
var updateMap map[string]interface{}
updateMap = make(map[string]interface{})
keyValMap := map[string]string{
"title": cardName,
"user": cardHolder,
"url": cardNumber,
"password": cardCvv,
"pin": cardPin,
// Issuer has to be the same
"class": cardClass,
"expiry_date": cardExpiry,
"tags": tags,
"notes": notes,
}
for key, val := range keyValMap {
val := strings.TrimSpace(val)
if len(val) > 0 {
updateMap[key] = val
}
}
// fmt.Printf("%+v\n", updateMap)
if len(updateMap) == 0 && !flag {
fmt.Printf("Nothing to update\n")
return nil
}
// Update timestamp also
updateMap["timestamp"] = time.Now()
err, db := openActiveDatabase()
if err == nil && db != nil {
result := db.Model(entry).Updates(updateMap)
if result.Error != nil {
return result.Error
}
if flag {
ReplaceCustomEntries(db, entry, customEntries)
}
fmt.Println("Updated entry.")
return nil
}
return err
}
// Add a new card entry to current database
func AddNewDatabaseCardEntry(cardName, cardNumber, cardHolder, cardIssuer, cardClass,
cardCvv, cardPin, cardExpiry, notes, tags string, customEntries []CustomEntry) error {
var entry Entry
var err error
var db *gorm.DB
fields := MapString([]string{cardName, cardHolder, cardNumber, cardCvv,
cardPin, cardIssuer, cardClass, cardExpiry, tags, notes},
strings.TrimSpace)
entry = Entry{
Title: fields[0],
User: fields[1],
Url: fields[2],
Password: fields[3],
Pin: fields[4],
Issuer: fields[5],
Class: fields[6],
ExpiryDate: fields[7],
Type: "card",
Tags: fields[8],
Notes: fields[9],
}
err, db = openActiveDatabase()
if err == nil && db != nil {
// result := db.Debug().Create(&entry)
result := db.Create(&entry)
if result.Error == nil && result.RowsAffected == 1 {
// Add custom fields if given
fmt.Printf("Created new entry with id: %d.\n", entry.ID)
if len(customEntries) > 0 {
return AddCustomEntries(db, &entry, customEntries)
}
return nil
} else if result.Error != nil {
return result.Error
}
}
return err
}
// Update current database entry with new values
func UpdateDatabaseEntry(entry *Entry, title, userName, url, passwd, tags string,
notes string, customEntries []CustomEntry, flag bool) error {
var updateMap map[string]interface{}
updateMap = make(map[string]interface{})
keyValMap := map[string]string{
"title": title,
"user": userName,
"url": url,
"password": passwd,
"notes": notes,
"tags": tags}
for key, val := range keyValMap {
if len(val) > 0 {
updateMap[key] = val
}
}
if len(updateMap) == 0 && !flag {
fmt.Printf("Nothing to update\n")
return nil
}
// Update timestamp also
updateMap["timestamp"] = time.Now()
err, db := openActiveDatabase()
if err == nil && db != nil {
result := db.Model(entry).Updates(updateMap)
if result.Error != nil {
return result.Error
}
if flag {
ReplaceCustomEntries(db, entry, customEntries)
}
fmt.Println("Updated entry.")
return nil
}
return err
}
// Find entry given the id
func GetEntryById(id int) (error, *Entry) {
var entry Entry
var err error
var db *gorm.DB
err, db = openActiveDatabase()
if err == nil && db != nil {
result := db.First(&entry, id)
if result.Error == nil {
return nil, &entry
} else {
return result.Error, nil
}
}
return err, nil
}
// Search database for the given string and return all matches
func SearchDatabaseEntry(term string) (error, []Entry) {
var entries []Entry
var err error
var db *gorm.DB
var searchTerm string
err, db = openActiveDatabase()
if err == nil && db != nil {
searchTerm = fmt.Sprintf("%%%s%%", term)
// Search on fields title, user, url and notes and tags.
query := db.Where(fmt.Sprintf("title like \"%s\"", searchTerm))
for _, field := range []string{"user", "url", "notes", "tags"} {
query = query.Or(fmt.Sprintf("%s like \"%s\"", field, searchTerm))
}
res := query.Find(&entries)
if res.Error != nil {
return res.Error, nil
}
return nil, entries
}
return err, entries
}
// Union of two entry arrays
func union(entry1 []Entry, entry2 []Entry) []Entry {
m := make(map[int]bool)
for _, item := range entry1 {
m[item.ID] = true
}
for _, item := range entry2 {
if _, ok := m[item.ID]; !ok {
entry1 = append(entry1, item)
}
}
return entry1
}
// Intersection of two entry arrays
func intersection(entry1 []Entry, entry2 []Entry) []Entry {
var common []Entry
m := make(map[int]bool)
for _, item := range entry1 {
m[item.ID] = true
}
for _, item := range entry2 {
if _, ok := m[item.ID]; ok {
common = append(common, item)
}
}
return common
}
// Search database for the given terms and returns matches according to operator
func SearchDatabaseEntries(terms []string, operator string) (error, []Entry) {
var err error
var finalEntries []Entry
for idx, term := range terms {
var entries []Entry
err, entries = SearchDatabaseEntry(term)
if err != nil {
fmt.Printf("Error searching for term: %s - \"%s\"\n", term, err.Error())
return err, entries
}
if idx == 0 {
finalEntries = entries
} else {
if operator == "AND" {
finalEntries = intersection(finalEntries, entries)
} else if operator == "OR" {
finalEntries = union(finalEntries, entries)
}
}
}
return nil, finalEntries
}
// Remove a given database entry
func RemoveDatabaseEntry(entry *Entry) error {
var err error
var db *gorm.DB
err, db = openActiveDatabase()
if err == nil && db != nil {
var exEntries []ExtendedEntry
res := db.Delete(entry)
if res.Error != nil {
return res.Error
}
// Delete extended entries if any
exEntries = GetExtendedEntries(entry)
if len(exEntries) > 0 {
res = db.Delete(exEntries)
if res.Error != nil {
return res.Error
}
}
return nil
}
return err
}
// Clone an entry and return cloned entry
func CloneEntry(entry *Entry) (error, *Entry) {
var entryNew Entry
var err error
var db *gorm.DB
err, db = openActiveDatabase()
if err == nil && db != nil {
entryNew.Copy(entry)
result := db.Create(&entryNew)
if result.Error == nil && result.RowsAffected == 1 {
fmt.Printf("Cloned to new entry, id: %d.\n", entryNew.ID)
return nil, &entryNew
} else if result.Error != nil {
return result.Error, nil
}
}
return err, nil
}
// Clone extended entries for an entry and return error code
func CloneExtendedEntries(entry *Entry, exEntries []ExtendedEntry) error {
var err error
var db *gorm.DB
err, db = openActiveDatabase()
if err == nil && db != nil {
for _, exEntry := range exEntries {
var exEntryNew ExtendedEntry
exEntryNew.Copy(&exEntry)
// Update the ID!
exEntryNew.EntryID = entry.ID
result := db.Create(&exEntryNew)
if result.Error != nil {
return result.Error
}
}
}
return err
}
// Return an iterator over all entries using the given order query keys
func IterateEntries(orderKey string, order string) (error, []Entry) {
var err error
var db *gorm.DB
var entries []Entry
err, db = openActiveDatabase()
if err == nil && db != nil {
var rows *sql.Rows
rows, err = db.Model(&Entry{}).Order(fmt.Sprintf("%s %s", orderKey, order)).Rows()
for rows.Next() {
var entry Entry
db.ScanRows(rows, &entry)
entries = append(entries, entry)
}
return nil, entries
}
return err, nil
}
// Export all entries to string array
func EntriesToStringArray(skipLongFields bool) (error, [][]string) {
var err error
var db *gorm.DB
var dataArray [][]string
err, db = openActiveDatabase()
if err == nil && db != nil {
var rows *sql.Rows
var count int64
db.Model(&Entry{}).Count(&count)
dataArray = make([][]string, 0, count)
rows, err = db.Model(&Entry{}).Order("id asc").Rows()
for rows.Next() {
var entry Entry
var entryData []string
db.ScanRows(rows, &entry)
if skipLongFields {
// Skip Notes
entryData = []string{strconv.Itoa(entry.ID), entry.Title, entry.User, entry.Password, entry.Timestamp.Format("2006-06-02 15:04:05")}
} else {
entryData = []string{strconv.Itoa(entry.ID), entry.Title, entry.User, entry.Url, entry.Password, entry.Notes, entry.Timestamp.Format("2006-06-02 15:04:05")}
}
dataArray = append(dataArray, entryData)
}
}
return err, dataArray
}
// Get extended entries associated to an entry
func GetExtendedEntries(entry *Entry) []ExtendedEntry {
var err error
var db *gorm.DB
var customEntries []ExtendedEntry
err, db = openActiveDatabase()
if err == nil && db != nil {
db.Where("entry_id = ?", entry.ID).Find(&customEntries)
}
return customEntries
}