Ejemplo n.º 1
0
// Update user in database. (update salt and password if needed)
func (u User) Update(db *mgo.DbQueue) error {
	var user User

	err := db.FindOneID("users", &user, u.ID)
	if err != nil {
		return err
	}

	if u.Username != "" {
		if u.Password == "" {
			return tools.NewError(nil, 400, "bad request: need password to update username")
		}
		user.Username = u.Username
		user.Salt, err = tools.GenSalt(12)
		if err != nil {
			return err
		}
		user.Password = tools.PasswordHash(user.Username, u.Password, user.Salt)
	}
	if u.Password != "" {
		user.Salt, err = tools.GenSalt(12)
		if err != nil {
			return err
		}
		user.Password = tools.PasswordHash(user.Username, u.Password, user.Salt)
	}
	if u.Domains != nil {
		user.Domains = u.Domains
	}
	if u.Variables != nil {
		user.Variables = u.Variables
	}
	user.Enable = u.Enable

	err = db.Push(func(db *mgo.Database, ec chan error) {
		ec <- db.C("users").UpdateId(u.ID, user)
	})
	return err
}
Ejemplo n.º 2
0
// Create a new user in database.
// (generates Salt)
func (u *User) Create(db *mgo.DbQueue) (bson.ObjectId, error) {
	n, err := db.Count("users", bson.M{"username": u.Username})
	if err != nil {
		return "", err
	}
	if n != 0 {
		return "", tools.NewError(nil, 409, "duplicate: user already exists")
	}

	u.ID = bson.NewObjectId()
	u.Salt, err = tools.GenSalt(12)
	if err != nil {
		return "", err
	}
	u.Password = tools.PasswordHash(u.Username, u.Password, u.Salt)
	err = db.Insert("users", u)
	return u.ID, err
}