Example #1
0
func isLocalizable(scope *gorm.Scope) (isLocalizable bool) {
	if scope.GetModelStruct().ModelType == nil {
		return false
	}
	_, isLocalizable = reflect.New(scope.GetModelStruct().ModelType).Interface().(l10nInterface)
	return
}
Example #2
0
// PrimaryField return gorm's primary field
func (res *Resource) PrimaryField() *gorm.Field {
	if res.primaryField == nil {
		scope := gorm.Scope{Value: res.Value}
		res.primaryField = scope.PrimaryField()
	}
	return res.primaryField
}
Example #3
0
func assignCreatedBy(scope *gorm.Scope) {
	if isAuditable(scope) {
		if user, ok := getCurrentUser(scope); ok {
			scope.SetColumn("CreatedBy", user)
		}
	}
}
Example #4
0
func updateTimeStampWhenCreate(scope *gorm.Scope) {
	if !scope.HasError() {
		now := time.Now()
		scope.SetColumn("Created", now)
		scope.SetColumn("Updated", now)
	}
}
Example #5
0
func syncToProductionAfterDelete(scope *gorm.Scope) {
	if !scope.HasError() {
		if ok, clone := getModeAndNewScope(scope); ok {
			gorm.Delete(clone)
		}
	}
}
Example #6
0
func beforeDelete(scope *gorm.Scope) {
	if isLocalizable(scope) {
		if locale, ok := getLocale(scope); ok { // is locale
			scope.Search.Where(fmt.Sprintf("%v.language_code = ?", scope.QuotedTableName()), locale)
		}
	}
}
Example #7
0
func setLocale(scope *gorm.Scope, locale string) {
	for _, field := range scope.Fields() {
		if field.Name == "LanguageCode" {
			field.Set(locale)
		}
	}
}
Example #8
0
func syncDeleteFromProductionToDraft(scope *gorm.Scope) {
	if !scope.HasError() {
		if ok, clone := isProductionModeAndNewScope(scope); ok {
			scope.DB().Callback().Delete().Get("gorm:delete")(clone)
		}
	}
}
Example #9
0
func syncDeleteFromProductionToDraft(scope *gorm.Scope) {
	if !scope.HasError() {
		if ok, clone := isProductionModeAndNewScope(scope); ok {
			gorm.Delete(clone)
		}
	}
}
Example #10
0
func isDraftMode(scope *gorm.Scope) bool {
	if draftMode, ok := scope.Get("publish:draft_mode"); ok {
		if isDraft, ok := draftMode.(bool); ok && isDraft {
			return true
		}
	}
	return false
}
Example #11
0
func getLocale(scope *gorm.Scope) (locale string, ok bool) {
	if str, ok := scope.DB().Get("l10n:locale"); ok {
		if locale, ok := str.(string); ok {
			return locale, (locale != Global) && (locale != "")
		}
	}
	return Global, false
}
Example #12
0
func syncColumns(scope *gorm.Scope) (columns []string) {
	for _, field := range scope.GetModelStruct().StructFields {
		if isSyncField(field) {
			columns = append(columns, field.DBName)
		}
	}
	return
}
Example #13
0
func validate(scope *gorm.Scope) {
	db := scope.DB()
	if _, ok := db.Get(settingKey); !ok {
		db.InstantSet(settingKey, map[string][]string{})
	}

	if result, ok := db.Get(skipValidations); !(ok && result.(bool)) {
		scope.CallMethodWithErrorCheck("Validate")
	}
}
Example #14
0
func syncToProductionAfterUpdate(scope *gorm.Scope) {
	if ok, clone := getModeAndNewScope(scope); ok {
		if updateAttrs, ok := scope.InstanceGet("gorm:update_attrs"); ok {
			table := originalTableName(scope.TableName())
			clone.Search = scope.Search
			clone.Search.Table(table)
			clone.InstanceSet("gorm:update_attrs", updateAttrs)
		}
		gorm.Update(clone)
	}
}
func (user *User) setEncryptedPassword(scope *gorm.Scope) error {
	pw, err := bcrypt.GenerateFromPassword([]byte(user.Password), 0)
	if err != nil {
		return err
	}

	scope.SetColumn("EncryptedPassword", string(pw))
	user.Password = ""

	return nil
}
Example #16
0
func toQueryCondition(scope *gorm.Scope, columns []string) string {
	var newColumns []string
	for _, column := range columns {
		newColumns = append(newColumns, scope.Quote(column))
	}

	if len(columns) > 1 {
		return fmt.Sprintf("(%v)", strings.Join(newColumns, ","))
	}
	return strings.Join(columns, ",")
}
Example #17
0
func beforeCreate(scope *gorm.Scope) {
	if isLocalizable(scope) {
		if locale, ok := getLocale(scope); ok { // is locale
			if isLocaleCreateable(scope) || !scope.PrimaryKeyZero() {
				setLocale(scope, locale)
			} else {
				scope.Err(errors.New("permission denied to create from locale"))
			}
		} else {
			setLocale(scope, Global)
		}
	}
}
Example #18
0
func (session *Session) BeforeCreate(scope *gorm.Scope) error {
	scope.SetColumn("Token", GenerateRandomString(64))
	scope.SetColumn("UUID", generateUUID())
	scope.SetColumn("Moment", time.Now().UTC().Unix())
	scope.SetColumn("ExpiresIn", expirationLengthForTokenType(session.TokenType))
	return nil
}
Example #19
0
func getFuncMap(scope *gorm.Scope, field *gorm.Field, filename string) template.FuncMap {
	hash := func() string { return strings.Replace(time.Now().Format("20060102150506.000000000"), ".", "", -1) }
	return template.FuncMap{
		"class":       scope.TableName,
		"primary_key": func() string { return fmt.Sprintf("%v", scope.PrimaryKeyValue()) },
		"column":      func() string { return field.Name },
		"filename":    func() string { return filename },
		"basename":    func() string { return strings.TrimSuffix(path.Base(filename), path.Ext(filename)) },
		"hash":        hash,
		"filename_with_hash": func() string {
			return fmt.Sprintf("%v.%v%v", strings.TrimSuffix(filename, path.Ext(filename)), hash(), path.Ext(filename))
		},
		"extension": func() string { return strings.TrimPrefix(path.Ext(filename), ".") },
	}
}
Example #20
0
func getFuncMap(scope *gorm.Scope, field *gorm.Field, filename string) template.FuncMap {
	hash := func() string { return strings.Replace(time.Now().Format("20060102150506.000000000"), ".", "", -1) }
	return template.FuncMap{
		"class":       func() string { return inflection.Plural(utils.ToParamString(scope.GetModelStruct().ModelType.Name())) },
		"primary_key": func() string { return fmt.Sprintf("%v", scope.PrimaryKeyValue()) },
		"column":      func() string { return strings.ToLower(field.Name) },
		"filename":    func() string { return filename },
		"basename":    func() string { return strings.TrimSuffix(path.Base(filename), path.Ext(filename)) },
		"hash":        hash,
		"filename_with_hash": func() string {
			return urlReplacer.ReplaceAllString(fmt.Sprintf("%v.%v%v", strings.TrimSuffix(filename, path.Ext(filename)), hash(), path.Ext(filename)), "-")
		},
		"extension": func() string { return strings.TrimPrefix(path.Ext(filename), ".") },
	}
}
Example #21
0
func beforeUpdate(scope *gorm.Scope) {
	if isLocalizable(scope) {
		locale, isLocale := getLocale(scope)

		switch mode, _ := scope.DB().Get("l10n:mode"); mode {
		case "unscoped":
		default:
			scope.Search.Where("language_code = ?", locale)
			setLocale(scope, locale)
		}

		if isLocale {
			scope.Search.Omit(syncColumns(scope)...)
		}
	}
}
Example #22
0
func createPublishEvent(scope *gorm.Scope) {
	if _, ok := scope.InstanceGet("publish:creating_publish_event"); ok {
		if event, ok := scope.Get(publishEvent); ok {
			if event, ok := event.(*PublishEvent); ok {
				event.PublishStatus = DIRTY
				scope.Err(scope.NewDB().Save(&event).Error)
			}
		}
	}
}
Example #23
0
func getModeAndNewScope(scope *gorm.Scope) (isProduction bool, clone *gorm.Scope) {
	if draftMode, ok := scope.Get("publish:draft_mode"); !ok || !draftMode.(bool) {
		if _, ok := scope.InstanceGet("publish:supported_model"); ok {
			table := originalTableName(scope.TableName())
			clone := scope.New(scope.Value)
			clone.Search.Table(table)
			return true, clone
		}
	}
	return false, nil
}
Example #24
0
func isProductionModeAndNewScope(scope *gorm.Scope) (isProduction bool, clone *gorm.Scope) {
	if !IsDraftMode(scope.DB()) {
		if _, ok := scope.InstanceGet("publish:supported_model"); ok {
			table := OriginalTableName(scope.TableName())
			clone := scope.New(scope.Value)
			clone.Search.Table(table)
			return true, clone
		}
	}
	return false, nil
}
Example #25
0
func assignUpdatedBy(scope *gorm.Scope) {
	if isAuditable(scope) {
		if user, ok := scope.DB().Get("audited:current_user"); ok {
			var currentUser string
			if primaryField := scope.New(user).PrimaryField(); primaryField != nil {
				currentUser = fmt.Sprintf("%v", primaryField.Field.Interface())
			} else {
				currentUser = fmt.Sprintf("%v", user)
			}

			if attrs, ok := scope.InstanceGet("gorm:update_attrs"); ok {
				updateAttrs := attrs.(map[string]interface{})
				updateAttrs["updated_by"] = currentUser
				scope.InstanceSet("gorm:update_attrs", updateAttrs)
			} else {
				scope.SetColumn("UpdatedBy", currentUser)
			}
		}
	}
}
Example #26
0
func syncUpdateFromProductionToDraft(scope *gorm.Scope) {
	if !scope.HasError() {
		if ok, clone := isProductionModeAndNewScope(scope); ok {
			if updateAttrs, ok := scope.InstanceGet("gorm:update_attrs"); ok {
				table := OriginalTableName(scope.TableName())
				clone.Search = scope.Search
				clone.Search.Table(table)
				clone.InstanceSet("gorm:update_attrs", updateAttrs)
			}
			scope.DB().Callback().Update().Get("gorm:update")(clone)
		}
	}
}
Example #27
0
func cropField(field *gorm.Field, scope *gorm.Scope) (cropped bool) {
	if field.Field.CanAddr() {
		// TODO Handle scanner
		if media, ok := field.Field.Addr().Interface().(Media); ok && !media.Cropped() {
			option := parseTagOption(field.Tag.Get("media_library"))
			if media.GetFileHeader() != nil || media.NeedCrop() {
				var file multipart.File
				var err error
				if fileHeader := media.GetFileHeader(); fileHeader != nil {
					file, err = media.GetFileHeader().Open()
				} else {
					file, err = media.Retrieve(media.URL("original"))
				}

				if err != nil {
					scope.Err(err)
					return false
				}

				media.Cropped(true)

				if url := media.GetURL(option, scope, field, media); url == "" {
					scope.Err(errors.New("invalid URL"))
				} else {
					result, _ := json.Marshal(map[string]string{"Url": url})
					media.Scan(string(result))
				}

				if file != nil {
					defer file.Close()
					var handled = false
					for _, handler := range mediaHandlers {
						if handler.CouldHandle(media) {
							file.Seek(0, 0)
							if scope.Err(handler.Handle(media, file, option)) == nil {
								handled = true
							}
						}
					}

					// Save File
					if !handled {
						scope.Err(media.Store(media.URL(), option, file))
					}
				}
				return true
			}
		}
	}
	return false
}
Example #28
0
func beforeQuery(scope *gorm.Scope) {
	if isLocalizable(scope) {
		quotedTableName := scope.QuotedTableName()
		locale, _ := getLocale(scope)
		switch mode, _ := scope.DB().Get("l10n:mode"); mode {
		case "locale":
			scope.Search.Where(fmt.Sprintf("%v.language_code = ?", quotedTableName), locale)
		case "global":
			scope.Search.Where(fmt.Sprintf("%v.language_code = ?", quotedTableName), Global)
		case "unscoped":
		default:
			quotedPrimaryKey := scope.Quote(scope.PrimaryKey())
			scope.Search.Unscoped = true
			if scope.Fields()["deleted_at"] != nil {
				scope.Search.Where(fmt.Sprintf("((%v NOT IN (SELECT DISTINCT(%v) FROM %v t2 WHERE t2.language_code = ? AND t2.deleted_at IS NULL) AND language_code = ?) OR language_code = ?) AND deleted_at IS NULL", quotedPrimaryKey, quotedPrimaryKey, quotedTableName), locale, Global, locale)
			} else {
				scope.Search.Where(fmt.Sprintf("(%v NOT IN (SELECT DISTINCT(%v) FROM %v t2 WHERE t2.language_code = ?) AND language_code = ?) OR (language_code = ?)", quotedPrimaryKey, quotedPrimaryKey, quotedTableName), locale, Global, locale)
			}
		}
	}
}
Example #29
0
func validate(scope *gorm.Scope) {
	if _, ok := scope.Get("gorm:update_column"); !ok {
		if result, ok := scope.DB().Get(skipValidations); !(ok && result.(bool)) {
			scope.CallMethodWithErrorCheck("Validate")
		}
	}
}
Example #30
0
// Callback function: invoked after the creation/update of an object. To populate its default fields
func updateFields(scope *gorm.Scope) {
	if !scope.HasError() {
		newScope := scope.New(scope.Value)
		newScope.Search = newScope.Search.Table(scope.TableName())

		if scope.PrimaryKey() != "" {
			gorm.Query(newScope)
		} else {
			// TODO: find a way to populate fields of scope.Value selecting * matching on every fields

		}
		scope = newScope
	}
}