gogmagog/models/user.go
2021-01-12 11:17:03 -06:00

77 lines
1.9 KiB
Go

package models
import (
"fmt"
"golang.org/x/crypto/bcrypt"
)
// User represents the full DB user field, for inserts and compares.
// No reason to return the hashed pw on the route though.
type User struct {
UserID int64
Username string
DisplayName string
Password []byte
}
// UserNoPassword contains the non password user fields.
// This is preferred outside of the model / store.
type UserNoPassword struct {
UserID int64 `json:"user_id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
}
// User returns a single plan from the store by plan_id.
func (m *Model) User(id int) (*UserNoPassword, error) {
user, err := m.SelectUserByID(id)
if user == nil {
return nil, wrapNotFound(err)
}
return user.NoPassword(), wrapNotFound(err)
}
// NoPassword strips the user of password.
func (u *User) NoPassword() *UserNoPassword {
return &UserNoPassword{
UserID: u.UserID,
Username: u.Username,
DisplayName: u.DisplayName,
}
}
// CreateUserRequest represents a desired user creation.
type CreateUserRequest struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
}
// CreateUser takes in a create user request and returns the ID of the newly created user.
func (m *Model) CreateUser(req *CreateUserRequest) (int, error) {
if req.Username == "" {
return -1, fmt.Errorf("No username provided")
}
if req.Password == "" {
return -1, fmt.Errorf("No password provided")
}
hash, err := hashPassword(req.Password)
if err != nil {
return -1, err
}
desiredUser := &User{
Username: req.Username,
DisplayName: req.DisplayName,
Password: hash,
}
return m.InsertUser(desiredUser)
}
// hashPassword hashes a password
func hashPassword(password string) ([]byte, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 11)
return bytes, err
}