示例#1
0
//Add ajoute un nouvel utilisateur
func (u *UserService) Add(user models.User) (models.User, error) {
	mongo := u.MongoService.Mongo.Copy()
	defer mongo.Close()
	id := bson.NewObjectId()

	salt, err := utils.GenerateSalt()
	if err != nil {
		return models.User{}, errors.New("Error when generatiing Salt")
	}
	user.Salt = string(salt[:32])

	password, err := utils.HashPassword([]byte(user.Password), salt)
	if err != nil {
		return models.User{}, err
	}
	user.Password = string(password[:32])

	userCollection := mongo.Database.C("user")
	userCollection.Insert(&models.User{ID: id, Username: user.Username, Firstname: user.Firstname, Lastname: user.Lastname, Password: user.Password, Salt: user.Salt, Email: user.Email})

	err = userCollection.FindId(id).One(&user)

	if err != nil {
		return models.User{}, errors.New("User not saved")
	}

	return user, nil
}
示例#2
0
//Update modifie un utilisateur existant
func (u *UserService) Update(id string, user models.User) (err error) {
	defer func() {
		if r := recover(); r != nil {
			err = errors.New("Incorrect ID")
		}
	}()

	mongo := u.MongoService.Mongo.Copy()
	defer mongo.Close()

	salt, err := utils.GenerateSalt()
	if err != nil {
		return err
	}
	user.Salt = string(salt[:32])

	password, err := utils.HashPassword([]byte(user.Password), salt)
	if err != nil {
		return err
	}
	user.Password = string(password[:32])

	userCollection := mongo.Database.C("user")
	err = userCollection.Update(bson.M{"_id": bson.ObjectIdHex(id)}, bson.M{"$set": bson.M{"username": user.Username, "lastname": user.Lastname, "firstname": user.Firstname, "password": user.Password, "salt": user.Salt, "email": user.Email}})

	return err
}