Passwords are now stored as bcrypt hashes

This commit is contained in:
Maciej Krzyżanowski 2024-03-22 18:12:44 +01:00
parent 90b837fe5c
commit fffd687641
3 changed files with 22 additions and 12 deletions

2
go.mod
View File

@ -1,3 +1,5 @@
module krzyzanowski.dev/p2pchat
go 1.21.7
require golang.org/x/crypto v0.21.0

2
go.sum Normal file
View File

@ -0,0 +1,2 @@
golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA=
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=

30
main.go
View File

@ -9,11 +9,13 @@ import (
"os"
"sync"
"time"
"golang.org/x/crypto/bcrypt"
)
type Account struct {
nickname string
password string
passHash []byte
}
type ServerContext struct {
@ -169,7 +171,6 @@ func handleEcho(_ *HandlerContext, reqBytes []byte) (resBytes []byte, err error)
}
func handleListPeers(handlerCtx *HandlerContext, reqBytes []byte) (resBytes []byte, err error) {
// For the sake of conciseness -> currently unmarshalling empty slice to empty struct
var listPeersReq ListPeersRequest
err = json.Unmarshal(reqBytes, &listPeersReq)
@ -215,7 +216,7 @@ func handleAuth(handlerCtx *HandlerContext, reqBytes []byte) (resBytes []byte, e
if ok {
// Check if password matches
if authReq.Password == account.password {
if bcrypt.CompareHashAndPassword(account.passHash, []byte(authReq.Password)) == nil {
authRes = AuthResponse{true}
handlerCtx.srvCtx.peersListLock.Lock()
handlerCtx.peer.hasAccount = true
@ -226,14 +227,20 @@ func handleAuth(handlerCtx *HandlerContext, reqBytes []byte) (resBytes []byte, e
}
} else {
authRes = AuthResponse{true}
newAcc := Account{authReq.Nickname, authReq.Password}
handlerCtx.srvCtx.accountsLock.Lock()
handlerCtx.srvCtx.accounts[newAcc.nickname] = &newAcc
handlerCtx.srvCtx.accountsLock.Unlock()
handlerCtx.srvCtx.peersListLock.Lock()
handlerCtx.peer.hasAccount = true
handlerCtx.peer.account = &newAcc
handlerCtx.srvCtx.peersListLock.Unlock()
passHash, err := bcrypt.GenerateFromPassword([]byte(authReq.Password), bcrypt.DefaultCost)
if err != nil {
authRes = AuthResponse{false}
} else {
newAcc := Account{authReq.Nickname, passHash}
handlerCtx.srvCtx.accountsLock.Lock()
handlerCtx.srvCtx.accounts[newAcc.nickname] = &newAcc
handlerCtx.srvCtx.accountsLock.Unlock()
handlerCtx.srvCtx.peersListLock.Lock()
handlerCtx.peer.hasAccount = true
handlerCtx.peer.account = &newAcc
handlerCtx.srvCtx.peersListLock.Unlock()
}
}
resBytes, err = json.Marshal(authRes)
@ -265,7 +272,6 @@ func printConnectedPeers(srvCtx *ServerContext) {
func runServer() {
idCounter := 0
srvCtx := &ServerContext{peersList: make([]*Peer, 0), accounts: make(map[string]*Account)}
srvCtx.accounts["xd"] = &Account{"xd", "XD"}
ln, err := net.Listen("tcp", ":8080")
if err != nil {