Hashing password

Using postgres' pgcrypt
This commit is contained in:
cdricms
2025-01-17 10:39:59 +01:00
parent 89f44f4469
commit fdc3122b68
7 changed files with 88 additions and 28 deletions

View File

@@ -53,13 +53,8 @@ func HandleLogin(w http.ResponseWriter, r *http.Request) {
return
}
var user core.User
count, err := core.DB.NewSelect().
Model(&user).
Where("email = ? AND password = ?", login.Email, login.Password).
Limit(1).
ScanAndCount(context.Background())
if count == 0 {
user, err := core.Verify(context.Background(), login.Email, login.Password)
if user == nil {
core.JSONError{
Status: core.Error,
Message: "User not found.",

View File

@@ -36,8 +36,8 @@ const (
type Status string
const (
Active Status = "Active"
Inactive Status = "Inactive"
Active Status = "Active"
Inactive Status = "Inactive"
)
type User struct {
@@ -56,6 +56,43 @@ type User struct {
Articles []*Blog `bun:"rel:has-many,join:user_id=blog_id" json:"articles,omitempty"`
}
func (u *User) Insert(ctx context.Context) (sql.Result, error) {
u.Password = fmt.Sprintf("crypt('%s', gen_salt('bf'))", u.Password)
return DB.NewInsert().
Model(u).
Value("password", u.Password).
Exec(ctx)
}
func Verify(ctx context.Context, email, password string) (*User, error) {
// var user User
// query := `
// SELECT *
// FROM users
// WHERE email = ? AND password = crypt(?, password)
// `
//
// err := DB.NewRaw(query, email, password).Scan(ctx, user)
var user User
count, err := DB.NewSelect().
Model(&user).
Where("email = ? AND password = crypt(?, password)", email, password).
Limit(1).
ScanAndCount(context.Background())
if count == 0 {
return nil, fmt.Errorf("invalid email or password")
}
if err != nil {
if err == sql.ErrNoRows {
return nil, fmt.Errorf("invalid email or password")
}
return nil, err
}
return &user, nil
}
type Event struct {
bun.BaseModel `bun:"table:events"`
@@ -69,7 +106,7 @@ type Event struct {
type EventToUser struct {
bun.BaseModel `bun:"table:events_to_users"`
EventID uuid.UUID `bun:"type:uuid,pk"`
EventID uuid.UUID `bun:"type:uuid,pk"`
UserID uuid.UUID `bun:"type:uuid,pk"`
Event *Event `bun:"rel:belongs-to,join:event_id=event_id"`
@@ -103,12 +140,18 @@ func InitDatabase(dsn DSN) (*bun.DB, error) {
sqldb := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(dsn.ToString())))
db := bun.NewDB(sqldb, pgdialect.New())
ctx := context.Background()
_, err := db.ExecContext(ctx, "CREATE EXTENSION IF NOT EXISTS pgcrypto;")
if err != nil {
return nil, err
}
db.RegisterModel((*EventToUser)(nil))
_, err := db.NewCreateTable().Model((*User)(nil)).IfNotExists().Exec(context.Background())
_, err = db.NewCreateTable().Model((*Event)(nil)).IfNotExists().Exec(context.Background())
_, err = db.NewCreateTable().Model((*EventToUser)(nil)).IfNotExists().Exec(context.Background())
_, err = db.NewCreateTable().Model((*Blog)(nil)).IfNotExists().Exec(context.Background())
_, err = db.NewCreateTable().Model((*WebsiteSettings)(nil)).IfNotExists().Exec(context.Background())
_, err = db.NewCreateTable().Model((*User)(nil)).IfNotExists().Exec(ctx)
_, err = db.NewCreateTable().Model((*Event)(nil)).IfNotExists().Exec(ctx)
_, err = db.NewCreateTable().Model((*EventToUser)(nil)).IfNotExists().Exec(ctx)
_, err = db.NewCreateTable().Model((*Blog)(nil)).IfNotExists().Exec(ctx)
_, err = db.NewCreateTable().Model((*WebsiteSettings)(nil)).IfNotExists().Exec(ctx)
if err != nil {
return nil, err
}

View File

@@ -17,7 +17,7 @@ func HandleCreateBlog(w http.ResponseWriter, r *http.Request) {
}.Respond(w, http.StatusMethodNotAllowed)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
core.JSONError{
@@ -26,16 +26,16 @@ func HandleCreateBlog(w http.ResponseWriter, r *http.Request) {
}.Respond(w, http.StatusNoContent)
return
}
var blog core.Blog
var blog core.Blog
if err = json.Unmarshal(body, &blog); err != nil {
core.JSONError{
Status: core.Error,
Message: err.Error(),
}.Respond(w, http.StatusNoContent)
return
}
}
_, err = core.DB.NewInsert().Model(blog).Exec(context.Background())
_, err = core.DB.NewInsert().Model(blog).Exec(context.Background())
if err != nil {
core.JSONError{
Status: core.Error,
@@ -46,6 +46,6 @@ func HandleCreateBlog(w http.ResponseWriter, r *http.Request) {
core.JSONSuccess{
Status: core.Success,
Message: "Blog inserted",
Data: blog,
Data: blog,
}.Respond(w, http.StatusCreated)
}

View File

@@ -32,14 +32,15 @@ func HandleCreateUser(w http.ResponseWriter, r *http.Request) {
log.Println(user)
res, err := core.DB.NewInsert().Model(&user).Exec(context.Background())
if res == nil {
core.JSONError{
Status: core.Error,
Message: "The user couldn't be inserted.",
}.Respond(w, http.StatusNotAcceptable)
return
}
res, err := user.Insert(context.Background())
log.Println(res)
// if res == nil {
// core.JSONError{
// Status: core.Error,
// Message: "The user couldn't be inserted.",
// }.Respond(w, http.StatusNotAcceptable)
// return
// }
if err != nil {
core.JSONError{