示例#1
0
func (hooks UserResourceHooks) AllowUpdate(res kit.Resource, obj kit.Model, old kit.Model, user kit.User) bool {
	if user == nil {
		return false
	}
	if user.HasRole("admin") || user.HasPermission("users.update") {
		return true
	}
	return obj.GetId() == user.GetId()
}
示例#2
0
func (res *Resource) update(obj kit.Model, user kit.User, partial bool) apperror.Error {
	if hook, ok := res.hooks.(UpdateHook); ok {
		return hook.Update(res, obj, user)
	}

	oldObj, err := res.FindOne(obj.GetId())
	if err != nil {
		return err
	} else if oldObj == nil {
		return apperror.New("not_found")
	}

	if allowUpdate, ok := res.hooks.(AllowUpdateHook); ok {
		if !allowUpdate.AllowUpdate(res, obj, oldObj, user) {
			return apperror.New("permission_denied")
		}
	}

	if beforeUpdate, ok := res.hooks.(BeforeUpdateHook); ok {
		if err := beforeUpdate.BeforeUpdate(res, obj, oldObj, user); err != nil {
			return err
		}
	}

	if partial {
		rOld := reflector.Reflect(oldObj).MustStruct()
		rNew := reflector.Reflect(oldObj).MustStruct()

		for fieldName, _ := range res.modelInfo.Attributes() {
			val := rNew.Field(fieldName)
			if !val.IsZero() {
				rOld.Field(fieldName).Set(val)
			}
		}
		for fieldName, _ := range res.modelInfo.Relations() {
			val := rNew.Field(fieldName)
			if !val.IsZero() {
				rOld.Field(fieldName).Set(val)
			}
		}

		obj = oldObj
	}

	if err := res.backend.Update(obj); err != nil {
		return err
	}

	if afterUpdate, ok := res.hooks.(AfterUpdateHook); ok {
		if err := afterUpdate.AfterUpdate(res, obj, oldObj, user); err != nil {
			return err
		}
	}

	return nil
}