feat: Added chapter 6 first auth attempt

This commit is contained in:
2024-10-24 22:40:26 +02:00
parent 9603509fcd
commit e72fd2ee86
10 changed files with 125 additions and 17 deletions

12
internal/auth/auth.go Normal file
View File

@ -0,0 +1,12 @@
package auth
import "golang.org/x/crypto/bcrypt"
func HashPassword(password string) (string, error) {
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 10)
return string(hashedPassword), err
}
func CheckPasswordHash(password, hash string) error {
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
}

View File

@ -19,8 +19,9 @@ type Chirp struct {
}
type User struct {
ID uuid.UUID
CreatedAt time.Time
UpdatedAt time.Time
Email string
ID uuid.UUID
CreatedAt time.Time
UpdatedAt time.Time
Email string
HashedPassword string
}

View File

@ -10,31 +10,33 @@ import (
)
const createUser = `-- name: CreateUser :one
INSERT INTO users (id, created_at, updated_at, email)
INSERT INTO users (id, created_at, updated_at, email, hashed_password)
VALUES (
gen_random_uuid(),
NOW(),
NOW(),
$1
$1,
$2
)
RETURNING id, created_at, updated_at, email
RETURNING id, created_at, updated_at, email, hashed_password
`
func (q *Queries) CreateUser(ctx context.Context, email string) (User, error) {
row := q.db.QueryRowContext(ctx, createUser, email)
func (q *Queries) CreateUser(ctx context.Context, email string, hashed_password string) (User, error) {
row := q.db.QueryRowContext(ctx, createUser, email, hashed_password)
var i User
err := row.Scan(
&i.ID,
&i.CreatedAt,
&i.UpdatedAt,
&i.Email,
&i.HashedPassword,
)
return i, err
}
const deleteUser = `-- name: DeleteUser :one
DELETE FROM users
RETURNING id, created_at, updated_at, email
RETURNING id, created_at, updated_at, email, hashed_password
`
func (q *Queries) DeleteUser(ctx context.Context) (User, error) {
@ -45,6 +47,25 @@ func (q *Queries) DeleteUser(ctx context.Context) (User, error) {
&i.CreatedAt,
&i.UpdatedAt,
&i.Email,
&i.HashedPassword,
)
return i, err
}
const getUserByEmail = `-- name: GetUserByEmail :one
SELECT id, created_at, updated_at, email, hashed_password FROM users
WHERE users.email = $1
`
func (q *Queries) GetUserByEmail(ctx context.Context, email string) (User, error) {
row := q.db.QueryRowContext(ctx, getUserByEmail, email)
var i User
err := row.Scan(
&i.ID,
&i.CreatedAt,
&i.UpdatedAt,
&i.Email,
&i.HashedPassword,
)
return i, err
}