示例#1
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
}
示例#2
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
}
示例#3
0
func TestUserUpdateNormal(t *testing.T) {
	BeforeEach()

	oldUsername := "******"
	newUsername := "******"
	user := models.User{Username: oldUsername}
	user, err := userService.Add(user)

	user.Username = newUsername
	err = userService.Update(string(user.ID.Hex()), user)

	if err != nil {
		t.Fatalf("Mustn't return error: %s", err)
	}

	user, err = userService.GetByID(user.ID.Hex())

	if strings.Compare(user.Username, newUsername) != 0 {
		t.Fatalf("Expected %s to be %s", user.Username, newUsername)
	}

	if err != nil {
		t.Fatalf("Mustn't return an error")
	}

	if reflect.DeepEqual(user, models.User{}) {
		t.Fatalf("Must return an user")
	}
	userService.Delete(user)
}