mirror of
https://github.com/empayre/fleet.git
synced 2024-11-06 17:05:18 +00:00
76 lines
1.7 KiB
Go
76 lines
1.7 KiB
Go
|
package kitserver
|
||
|
|
||
|
import (
|
||
|
"crypto/rand"
|
||
|
"encoding/base64"
|
||
|
"fmt"
|
||
|
|
||
|
"github.com/kolide/kolide-ose/kolide"
|
||
|
"golang.org/x/crypto/bcrypt"
|
||
|
"golang.org/x/net/context"
|
||
|
)
|
||
|
|
||
|
func (s service) NewUser(ctx context.Context, p kolide.UserPayload) (*kolide.User, error) {
|
||
|
user, err := userFromPayload(p, s.saltKeySize, s.bcryptCost)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
user, err = s.ds.NewUser(user)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
return user, nil
|
||
|
}
|
||
|
|
||
|
func userFromPayload(p kolide.UserPayload, keySize, cost int) (*kolide.User, error) {
|
||
|
hashed, salt, err := hashPassword(*p.Password, keySize, cost)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
return &kolide.User{
|
||
|
Username: *p.Username,
|
||
|
Email: *p.Email,
|
||
|
Admin: falseIfNil(p.Admin),
|
||
|
NeedsPasswordReset: falseIfNil(p.NeedsPasswordReset),
|
||
|
Salt: salt,
|
||
|
Password: hashed,
|
||
|
}, nil
|
||
|
}
|
||
|
|
||
|
func hashPassword(plaintext string, keySize, cost int) ([]byte, string, error) {
|
||
|
salt, err := generateRandomText(keySize)
|
||
|
if err != nil {
|
||
|
return nil, "", err
|
||
|
}
|
||
|
|
||
|
withSalt := []byte(fmt.Sprintf("%s%s", plaintext, salt))
|
||
|
hashed, err := bcrypt.GenerateFromPassword(withSalt, cost)
|
||
|
if err != nil {
|
||
|
return nil, "", err
|
||
|
}
|
||
|
|
||
|
return hashed, salt, nil
|
||
|
|
||
|
}
|
||
|
|
||
|
// generateRandomText return a string generated by filling in keySize bytes with
|
||
|
// random data and then base64 encoding those bytes
|
||
|
func generateRandomText(keySize int) (string, error) {
|
||
|
key := make([]byte, keySize)
|
||
|
_, err := rand.Read(key)
|
||
|
if err != nil {
|
||
|
return "", err
|
||
|
}
|
||
|
|
||
|
return base64.StdEncoding.EncodeToString(key), nil
|
||
|
}
|
||
|
|
||
|
// helper to convert a bool pointer false
|
||
|
func falseIfNil(b *bool) bool {
|
||
|
if b == nil {
|
||
|
return false
|
||
|
}
|
||
|
return *b
|
||
|
}
|