implemented login logic
This commit is contained in:
+20
-10
@@ -21,7 +21,7 @@ func InitDatabase(ctx context.Context) {
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
Id SERIAL PRIMARY KEY,
|
||||
Name VARCHAR(20) UNIQUE NOT NULL,
|
||||
pass_hash VARCHAR(60) NOT NULL,
|
||||
PassHash VARCHAR(60) NOT NULL,
|
||||
Color VARCHAR(3) NOT NULL
|
||||
)
|
||||
`)
|
||||
@@ -31,8 +31,8 @@ func InitDatabase(ctx context.Context) {
|
||||
dbConnection = conn
|
||||
}
|
||||
|
||||
func AddNewUser(ctx context.Context, user User) (uint, error) {
|
||||
var id uint
|
||||
func AddNewUser(ctx context.Context, user User) (uint32, error) {
|
||||
var id uint32
|
||||
var err error
|
||||
|
||||
if len(user.Name) == 0 || len(user.Name) > 20 {
|
||||
@@ -54,16 +54,16 @@ func AddNewUser(ctx context.Context, user User) (uint, error) {
|
||||
return 0, errors.New("color invalid")
|
||||
}
|
||||
err = dbConnection.QueryRow(ctx, `
|
||||
INSERT INTO users (Name, pass_hash, Color)
|
||||
INSERT INTO users (Name, PassHash, Color)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING Id
|
||||
`, user.Name, user.IsPasswordHashed, user.Color).Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
func CheckPassword(ctx context.Context, id string, plainPassword string) bool {
|
||||
func isPassValid(ctx context.Context, id uint32, plainPassword string) bool {
|
||||
var controlHash string
|
||||
err := dbConnection.QueryRow(ctx, "SELECT pass_hash FROM users WHERE Id = $1", id).Scan(&controlHash)
|
||||
err := dbConnection.QueryRow(ctx, "SELECT PassHash FROM users WHERE Id = $1", id).Scan(&controlHash)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
@@ -71,13 +71,23 @@ func CheckPassword(ctx context.Context, id string, plainPassword string) bool {
|
||||
return bcrypt.CompareHashAndPassword([]byte(controlHash), []byte(plainPassword)) == nil
|
||||
}
|
||||
|
||||
func GetUserData(ctx context.Context, id string) (User, error) {
|
||||
func GetUserDataById(ctx context.Context, id uint32) (*User, error) {
|
||||
var user User
|
||||
err := dbConnection.QueryRow(ctx, "SELECT Id, Name, pass_hash, Color FROM users WHERE Id = $1", id).
|
||||
err := dbConnection.QueryRow(ctx, "SELECT Id, Name, PassHash, Color FROM users WHERE Id = $1", id).
|
||||
Scan(&user.Id, &user.Name, &user.Password, &user.Color)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
return &User{}, err
|
||||
}
|
||||
user.IsPasswordHashed = true
|
||||
return user, nil
|
||||
return &user, nil
|
||||
}
|
||||
func GetUserDataByName(ctx context.Context, name string) (*User, error) {
|
||||
var user User
|
||||
err := dbConnection.QueryRow(ctx, "SELECT Id, Name, PassHash, Color FROM users WHERE Name = $1", name).
|
||||
Scan(&user.Id, &user.Name, &user.Password, &user.Color)
|
||||
if err != nil {
|
||||
return &User{}, err
|
||||
}
|
||||
user.IsPasswordHashed = true
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func RegisterHandler(response http.ResponseWriter, request *http.Request) {
|
||||
if request.Method != http.MethodPost {
|
||||
http.Error(response, "POST only", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
ctx := request.Context()
|
||||
username := request.FormValue("username")
|
||||
password := request.FormValue("password")
|
||||
|
||||
if len(username) < 2 {
|
||||
http.Error(response, "short username", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if len(password) < 8 {
|
||||
http.Error(response, "short password", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := GetUserDataByName(ctx, username); err == nil {
|
||||
http.Error(response, "User already exists", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := AddNewUser(ctx, User{0, username, password, "xxx", false}); err != nil {
|
||||
http.Error(response, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func LoginHandler(response http.ResponseWriter, request *http.Request) {
|
||||
if request.Method != http.MethodPost {
|
||||
http.Error(response, "POST only", http.StatusMethodNotAllowed)
|
||||
}
|
||||
ctx := request.Context()
|
||||
username := request.FormValue("username")
|
||||
password := request.FormValue("password")
|
||||
|
||||
if len(username) < 2 {
|
||||
http.Error(response, "short username", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
user, err := GetUserDataByName(ctx, username)
|
||||
if err != nil {
|
||||
http.Error(response, "Bad login", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)) == nil {
|
||||
token, err := GetToken(user)
|
||||
if err != nil {
|
||||
http.Error(response, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if _, err = response.Write([]byte(token)); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,5 +36,7 @@ func main() {
|
||||
|
||||
http.Handle("/ws", srv)
|
||||
log.Println("server listening on :8080")
|
||||
http.HandleFunc("POST /register", RegisterHandler)
|
||||
http.HandleFunc("POST /login", LoginHandler)
|
||||
log.Fatal(http.ListenAndServe(":8080", nil))
|
||||
}
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ package main
|
||||
import "github.com/coder/websocket"
|
||||
|
||||
type User struct {
|
||||
Id uint
|
||||
Id uint32
|
||||
Name string
|
||||
Password string
|
||||
Color string
|
||||
|
||||
@@ -3,6 +3,7 @@ package main
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
@@ -11,10 +12,10 @@ import (
|
||||
|
||||
var secretKey = []byte("replace-with-env-variable")
|
||||
|
||||
func GetToken(userID string) (string, error) {
|
||||
func GetToken(user *User) (string, error) {
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256,
|
||||
jwt.RegisteredClaims{
|
||||
Subject: userID,
|
||||
Subject: strconv.Itoa(int(user.Id)),
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
|
||||
+12
-2
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -109,13 +110,22 @@ func handleUnauthenticatedMessage(ctx context.Context, conn *websocket.Conn, msg
|
||||
conn.Close(websocket.StatusPolicyViolation, "invalid token")
|
||||
return
|
||||
}
|
||||
user, err := GetUserData(ctx, subject)
|
||||
|
||||
var subjectId uint32
|
||||
parsed, err := strconv.ParseUint(subject, 10, 32)
|
||||
subjectId = uint32(parsed)
|
||||
if err != nil {
|
||||
conn.Close(websocket.StatusPolicyViolation, "invalid token")
|
||||
return
|
||||
}
|
||||
|
||||
user, err := GetUserDataById(ctx, subjectId)
|
||||
if err != nil {
|
||||
conn.Close(websocket.StatusPolicyViolation, "invalid token")
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
authenticatedConnections = append(authenticatedConnections, AuthConnection{connection: conn, user: user})
|
||||
authenticatedConnections = append(authenticatedConnections, AuthConnection{connection: conn, user: *user})
|
||||
mu.Unlock()
|
||||
sendAndCloseIfFails(conn, map[string]any{
|
||||
"authAs": user.Name,
|
||||
|
||||
Reference in New Issue
Block a user