Populating byte array field (Cloud Firestore) to interface with []bytes field

Hi guys

I am learning web development with golang and trying to get my head around storing a password in Cloud Firestore database.

The password has been saved like so:

hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 12)
docRef, _, err := m.Client.Collection("users").Add(context.Background(), map[string]interface{}{
        "name":     name,
        "email":    email,
        "password": hashedPassword, // this is a []byte
        "created":  time.Now(),
    })

then when I get the user data from Firestore, and print the data, the password seems to be casted to []uint8, maybe by firestore driver. So this command:

log.Printf("> Document data: %#v", ds.Data())

outputs:

> Document data: map[string]interface {}{"created":time.Date(2022, time.April, 3, 17, 33, 36, 270361000, time.UTC), "email":"test@test.com", "name":"Junior", "password":[]uint8{0x24, 0x32, 0x61, 0x24, 0x31, 0x32, 0x24, 0x37, 0x68, 0x6b, 0x43, 0x38, 0x39, 0x54, 0x68, 0x31, 0x77, 0x63, 0x31, 0x52, 0x69, 0x57, 0x4e, 0x37, 0x6d, 0x31, 0x6b, 0x7a, 0x75, 0x64, 0x72, 0x6c, 0x38, 0x45, 0x71, 0x71, 0x54, 0x62, 0x30, 0x44, 0x6b, 0x4c, 0x65, 0x63, 0x51, 0x4c, 0x45, 0x35, 0x42, 0x45, 0x55, 0x61, 0x77, 0x4a, 0x54, 0x48, 0x2e, 0x62, 0x61, 0x32}}

Next when I try to map to my User interface somehow the HashedPassword is always empty []:

type User struct {
    Id             string
    Name           string
    Email          string
    HashedPassword []byte
    Created        time.Time
}

user := &models.User{}
user.Id = ds.Ref.ID
ds.DataTo(&user) // this wont fill HashedPassword field
log.Printf("\n>>>> hashed: %+v\n", user.HashedPassword) 

outputs:

>>>> hashed: []

the workaround I did to get my User interface with HashPassword field filled was

func ToByteSlice(b []byte) []byte {
    return b
}

user := &models.User{}
user.Id = ds.Ref.ID
user.HashedPassword = ToByteSlice(ds.Data()["password"].([]uint8))
ds.DataTo(&user)
log.Printf("\n>>>> hashed: %+v\n", user.HashedPassword) // now we have []byte filled

outputs:

>>>> hashed: [36 50 97 36 49 50 36 68 111 105 109 80 84 113 57 73 112 102 111 97 86 104 54 88 85 77 72 100 46 51 55 116 110 49 100 81 49 89 83 113 53 82 71 122 112 114 106 100 82 47 90 51 118 55 122 77 116 81 100 54]

I would like to know if anyone here faced a similar case, and what are the recommendations when saving and retrieving hashed passwords. Thanks

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.