-3

I want to make a sign-up server using go where the users are stored in a JSON file called users.json with this format:

[
    {
        "email": "email",
        "password": "password"
    },
    {
        "email": "email",
        "password": "password"
    },
    ...
]

Right now I'm using this code:

func signup(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()

    type User struct {
        Email    string
        Password string
    }

    user := User{}
    user.Email = r.Form["email"][0]
    user.Password = r.Form["password"][0]

    content, err := json.Marshal(user)
    if err != nil {
        fmt.Println(err)
    }
    err = ioutil.WriteFile("users.json", content, 0644)
    if err != nil {
        log.Fatal(err)
    }
}

The issue with it is that if a new user signed up it deletes the old data in the JSON file and it stores the informations in this format:

{
    "Email": "email",
    "Password": "password"
}

I'm new to go and have no idea on how to do it.

NVSS
  • 66
  • 1
  • 7
  • 2
    (1) [Do not store passwords in plain text](https://owasp.org/www-community/vulnerabilities/Password_Plaintext_Storage). (2) To prevent an attacker from causing server panic, replace `r.Form[key][0]` with `r.Form.Get(key)`. – Charlie Tumahai Aug 30 '22 at 19:42
  • 1
    if you have a fatal error, make sure you're interrupting program execution . if `json.Marshal` fails in your code, you stil write out the content to the file – erik258 Aug 30 '22 at 19:43
  • 2
    this implementation doesn't make sense without some sort of lock on the file (otherwise concurrent requests will writ to the file at the same time, almost certainly munging up the content). If you want to preserve existing file content, you need to read the file, parse it, append a new User to the resultant list, and then marshal and write the file out again. Json files do not a database make. – erik258 Aug 30 '22 at 19:45
  • 1
    you might also want to ask yourself, what happens if somebody submits the same email address twice? Gets 2 entries in the file? – erik258 Aug 30 '22 at 19:45

1 Answers1

0

Doc says : WriteFile writes data to the named file, creating it if necessary. If the file does not exist, WriteFile creates it with permissions perm (before umask); otherwise WriteFile truncates it before writing, without changing permissions.

https://pkg.go.dev/os#WriteFile

You must append to the JSON file. Follow this thread to see how you can perform JSON file append. https://stackoverflow.com/a/44642209/9787555