Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use salts for passwords in account creation and validation #70

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion api/database.sql
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ CREATE TABLE Accounts (
email VARCHAR(50) PRIMARY KEY,
firstName VARCHAR(50),
lastName VARCHAR(50),
password CHAR(64) NOT NULL
password CHAR(64) NOT NULL,
salt CHAR(16) NOT NULL
);
CREATE TABLE Chats (
id INTEGER PRIMARY KEY,
Expand Down
32 changes: 30 additions & 2 deletions api/login/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package login
import (
"api/auth"
"api/database"
"crypto/rand"
"os"

"encoding/json"
Expand Down Expand Up @@ -33,8 +34,12 @@ func createAccount(response http.ResponseWriter, request *http.Request) {
return
}

result, err := database.Execute("INSERT INTO Accounts (email, password) VALUES (?, SHA2(?, 256))", acc.Email, acc.Password)
salt := generateSalt()
saltedPassword := acc.Password + salt

result, err := database.Execute("INSERT INTO Accounts (email, password, salt) VALUES (?, SHA2(?, 256), ?)", acc.Email, saltedPassword, salt)
if err != nil {
log.Println(err)
return
}

Expand All @@ -59,7 +64,14 @@ func validateAccount(response http.ResponseWriter, request *http.Request) {
return
}

token, err := auth.GetToken(acc.Email, acc.Password)
salt, err := getSalt(acc.Email)
if err != nil {
fmt.Fprint(response, FAILURE_RESPONSE)
return
}
saltedPassword := acc.Password + salt

token, err := auth.GetToken(acc.Email, saltedPassword)

if err != nil {
fmt.Fprint(response, FAILURE_RESPONSE)
Expand All @@ -76,6 +88,22 @@ func validateAccount(response http.ResponseWriter, request *http.Request) {
fmt.Fprint(response, tokenString)
}

// Returns a secure random salt that is 16 characters long.
func generateSalt() string {
b := make([]byte, 8)
rand.Read(b)
return fmt.Sprintf("%x", b)
}

func getSalt(email string) (string, error) {
salt := ""
err := database.QueryValue(&salt, "SELECT salt FROM Accounts WHERE email = ?", email)
if err != nil || salt == "" {
return "", err
}
return salt, nil
}

func HandleLoginRoutes(r *mux.Router) {
r.HandleFunc("/login/createAccount", createAccount).Methods("POST")
r.HandleFunc("/login/validateAccount", validateAccount).Methods("POST")
Expand Down