Exemple #1
0
//BindCreate is default create binder
func BindCreate(a *Admin, resource *Resource) {
	resource.ResourceController.Post(a.GetURL(resource, ""), func(request prago.Request) {
		ValidateCSRF(request)
		var item interface{}
		resource.newItem(&item)

		form, err := resource.StructCache.GetForm(item, GetLocale(request), resource.VisibilityFilter, resource.EditabilityFilter)
		prago.Must(err)

		if resource.AfterFormCreated != nil {
			form = resource.AfterFormCreated(form, request, true)
		}

		resource.StructCache.BindData(item, request.Params(), request.Request().MultipartForm, form.getFilter())

		if resource.BeforeCreate != nil {
			if !resource.BeforeCreate(request, item) {
				return
			}
		}

		prago.Must(a.Create(item))

		if resource.AfterCreate != nil {
			if !resource.AfterCreate(request, item) {
				return
			}
		}

		AddFlashMessage(request, messages.Messages.Get(GetLocale(request), "admin_item_created"))
		prago.Redirect(request, a.Prefix+"/"+resource.ID)
	})
}
Exemple #2
0
//BindDelete is default delete binder
func BindDelete(a *Admin, resource *Resource) {
	resource.ResourceController.Post(a.GetURL(resource, ":id/delete"), func(request prago.Request) {
		ValidateCSRF(request)
		id, err := strconv.Atoi(request.Params().Get("id"))
		prago.Must(err)

		if resource.BeforeDelete != nil {
			if !resource.BeforeDelete(request, id) {
				return
			}
		}

		var item interface{}
		resource.newItem(&item)
		_, err = a.Query().WhereIs("id", int64(id)).Delete(item)
		prago.Must(err)

		if resource.AfterDelete != nil {
			if !resource.AfterDelete(request, id) {
				return
			}
		}

		AddFlashMessage(request, messages.Messages.Get(GetLocale(request), "admin_item_deleted"))
		prago.Redirect(request, a.Prefix+"/"+resource.ID)
	})
}
Exemple #3
0
//BindDetail is default detail binder
func BindDetail(a *Admin, resource *Resource) {
	resource.ResourceController.Get(a.GetURL(resource, ":id"), func(request prago.Request) {
		id, err := strconv.Atoi(request.Params().Get("id"))
		prago.Must(err)

		var item interface{}
		resource.newItem(&item)
		prago.Must(a.Query().WhereIs("id", int64(id)).Get(item))

		form, err := resource.StructCache.GetForm(item, GetLocale(request), resource.VisibilityFilter, resource.EditabilityFilter)
		prago.Must(err)

		form.Action = request.Params().Get("id")
		form.AddSubmit("_submit", messages.Messages.Get(GetLocale(request), "admin_edit"))
		AddCSRFToken(form, request)

		if resource.AfterFormCreated != nil {
			form = resource.AfterFormCreated(form, request, false)
		}

		if resource.BeforeDetail != nil {
			if !resource.BeforeDetail(request, item) {
				return
			}
		}

		request.SetData("admin_title", messages.Messages.Get(GetLocale(request), "admin_edit")+" - "+resource.Name(GetLocale(request)))
		request.SetData("admin_item", item)
		request.SetData("admin_form", form)
		request.SetData("admin_yield", "admin_edit")
		prago.Render(request, 200, "admin_layout")
	})
}
Exemple #4
0
func bindListResourceAPI(a *Admin) {
	a.AdminController.Get(a.Prefix+"/_api/resource/:name", func(request prago.Request) {
		locale := GetLocale(request)
		user := GetUser(request)
		name := request.Params().Get("name")
		resource, found := a.resourceNameMap[name]

		if !found {
			render404(request)
			return
		}

		if !resource.Authenticate(user) {
			render403(request)
			return
		}

		var item interface{}
		resource.newItem(&item)
		c, err := a.Query().Count(item)
		prago.Must(err)
		if c == 0 {
			prago.WriteAPI(request, []string{}, 200)
			return
		}

		ret := []resourceItem{}

		var items interface{}
		resource.newItems(&items)
		prago.Must(a.Query().Get(items))

		itemsVal := reflect.ValueOf(items).Elem()

		for i := 0; i < itemsVal.Len(); i++ {
			item := itemsVal.Index(i)

			id := item.Elem().FieldByName("ID").Int()

			var name string
			ifaceItemName, ok := item.Interface().(interface {
				AdminItemName(string) string
			})
			if ok {
				name = ifaceItemName.AdminItemName(locale)
			} else {
				name = item.Elem().FieldByName("Name").String()
			}

			ret = append(ret, resourceItem{
				ID:   id,
				Name: name,
			})
		}

		prago.WriteAPI(request, ret, 200)
	})
}
Exemple #5
0
func uploadFile(fileHeader *multipart.FileHeader, fileUploadPath string) (*File, error) {
	fileName := utils.PrettyFilename(fileHeader.Filename)
	file := &File{}
	file.Name = fileName
	file.UID = shortuuid.UUID()
	folderPath, filePath := file.getPath(fileUploadPath + "original")
	prago.Must(loadFile(folderPath, filePath, fileHeader))
	prago.Must(file.update(fileUploadPath))
	return file, nil
}
Exemple #6
0
func bindImageAPI(a *Admin, fileDownloadPath string) {
	a.App.MainController().Get(a.Prefix+"/_api/image/list", func(request prago.Request) {
		var images []*File

		fmt.Println(request.Params().Get("ids"))

		if len(request.Params().Get("ids")) > 0 {
			ids := strings.Split(request.Params().Get("ids"), ",")
			for _, v := range ids {
				var image File
				err := a.Query().WhereIs("uid", v).Get(&image)
				if err == nil {
					images = append(images, &image)
				} else {
					if err != ErrItemNotFound {
						panic(err)
					}
				}
			}
		} else {
			filter := "%" + request.Params().Get("q") + "%"
			q := a.Query().WhereIs("filetype", "image").OrderDesc("createdat").Limit(10)
			if len(request.Params().Get("q")) > 0 {
				q = q.Where("name LIKE ? OR description LIKE ?", filter, filter)
			}
			prago.Must(q.Get(&images))
		}
		writeFileResponse(request, images)

	})

	a.AdminController.Post(a.Prefix+"/_api/image/upload", func(request prago.Request) {
		multipartFiles := request.Request().MultipartForm.File["file"]

		description := request.Params().Get("description")

		files := []*File{}

		for _, v := range multipartFiles {
			file, err := uploadFile(v, fileUploadPath)
			if err != nil {
				panic(err)
			}
			file.User = GetUser(request).ID
			file.Description = description
			prago.Must(a.Create(file))
			files = append(files, file)
		}

		writeFileResponse(request, files)
	})
}
Exemple #7
0
//BindNew is default new binder
func BindNew(a *Admin, resource *Resource) {
	resource.ResourceController.Get(a.GetURL(resource, "new"), func(request prago.Request) {
		var item interface{}
		resource.newItem(&item)

		if resource.BeforeNew != nil {
			if !resource.BeforeNew(request, item) {
				return
			}
		}

		form, err := resource.StructCache.GetForm(item, GetLocale(request), resource.VisibilityFilter, resource.EditabilityFilter)
		prago.Must(err)

		form.Action = "../" + resource.ID
		form.AddSubmit("_submit", messages.Messages.Get(GetLocale(request), "admin_create"))
		AddCSRFToken(form, request)

		if resource.AfterFormCreated != nil {
			form = resource.AfterFormCreated(form, request, true)
		}

		request.SetData("admin_title", messages.Messages.Get(GetLocale(request), "admin_new")+" - "+resource.Name(GetLocale(request)))

		request.SetData("admin_form", form)
		request.SetData("admin_yield", "admin_new")
		prago.Render(request, 200, "admin_layout")
	})
}
Exemple #8
0
func (resource *Resource) valueToCell(admin *Admin, field reflect.StructField, val reflect.Value) (cell listCell) {
	cell.TemplateName = "admin_string"
	var item interface{}
	reflect.ValueOf(&item).Elem().Set(val)

	switch item.(type) {
	case string:
		cell.Value = item.(string)
	case bool:
		if item.(bool) {
			cell.Value = "✅"
		}
	case int64:
		cell.Value = fmt.Sprintf("%d", item.(int64))
		if field.Tag.Get("prago-type") == "relation" {
			relationResource := resource.admin.getResourceByName(field.Name)

			var relationItem interface{}
			relationResource.newItem(&relationItem)
			prago.Must(admin.Query().WhereIs("id", item.(int64)).Get(relationItem))

			ifaceItemName, ok := relationItem.(interface {
				AdminItemName(string) string
			})
			if ok {
				cell.Value = ifaceItemName.AdminItemName("cs")
				cell.TemplateName = "admin_link"
				cell.URL = fmt.Sprintf("%s/%d", relationResource.ID, item.(int64))
				return
			}

			nameField := reflect.ValueOf(relationItem).Elem().FieldByName("Name")

			cell.Value = nameField.String()
			cell.TemplateName = "admin_link"
			cell.URL = fmt.Sprintf("%s/%d", relationResource.ID, item.(int64))
			return
		}
	}

	if field.Tag.Get("prago-type") == "image" {
		cell.TemplateName = "admin_image"
	}

	if val.Type() == reflect.TypeOf(time.Now()) {
		var tm time.Time
		reflect.ValueOf(&tm).Elem().Set(val)
		cell.Value = tm.Format("2006-01-02 15:04:05")
	}

	if len(field.Tag.Get("prago-preview-type")) > 0 {
		cell.TemplateName = field.Tag.Get("prago-preview-type")
	}

	return
}
Exemple #9
0
//BindUpdate is default update binder
func BindUpdate(a *Admin, resource *Resource) {
	resource.ResourceController.Post(a.GetURL(resource, ":id"), func(request prago.Request) {
		ValidateCSRF(request)
		id, err := strconv.Atoi(request.Params().Get("id"))
		prago.Must(err)

		var item interface{}
		resource.newItem(&item)
		prago.Must(a.Query().WhereIs("id", int64(id)).Get(item))

		form, err := resource.StructCache.GetForm(item, GetLocale(request), resource.VisibilityFilter, resource.EditabilityFilter)
		prago.Must(err)

		if resource.AfterFormCreated != nil {
			form = resource.AfterFormCreated(form, request, false)
		}

		err = resource.StructCache.BindData(item, request.Params(), request.Request().MultipartForm, form.getFilter())
		prago.Must(err)

		if resource.BeforeUpdate != nil {
			if !resource.BeforeUpdate(request, item) {
				return
			}
		}

		err = a.Save(item)
		prago.Must(err)

		if resource.AfterUpdate != nil {
			if !resource.AfterUpdate(request, item) {
				return
			}
		}

		AddFlashMessage(request, messages.Messages.Get(GetLocale(request), "admin_item_edited"))
		prago.Redirect(request, a.Prefix+"/"+resource.ID)
	})
}
Exemple #10
0
//BindOrder is default order binder
func BindOrder(a *Admin, resource *Resource) {
	resource.ResourceController.Post(a.GetURL(resource, "order"), func(request prago.Request) {
		decoder := json.NewDecoder(request.Request().Body)
		var t = map[string][]int{}
		err := decoder.Decode(&t)
		prago.Must(err)

		order, ok := t["order"]
		if !ok {
			panic("wrong format")
		}

		for i, id := range order {
			var item interface{}
			resource.newItem(&item)
			prago.Must(a.Query().WhereIs("id", int64(id)).Get(item))
			prago.Must(resource.StructCache.BindOrder(item, int64(i)))
			prago.Must(a.Save(item))
		}

		prago.WriteAPI(request, true, 200)
	})
}
Exemple #11
0
func (s *Sessions) around(request prago.Request, next func()) {

	if request.IsProcessed() {
		next()
		return
	}

	sessionName := s.app.Data()["appName"].(string)
	session, err := s.cookieStore.Get(request.Request(), sessionName)
	if err != nil {
		request.Log().Errorln("Session not valid")
		request.Response().Header().Set("Set-Cookie", sessionName+"=; expires=Thu, 01 Jan 1970 00:00:01 GMT;")
		panic(err)
	}

	flashes := session.Flashes()
	if len(flashes) > 0 {
		request.SetData("flash_messages", flashes)
		prago.Must(session.Save(request.Request(), request.Response()))
	}

	request.SetData("session", session)
	next()
}
Exemple #12
0
//InitResource for user
func (User) InitResource(a *Admin, resource *Resource) error {

	a.AdminAccessController.AddBeforeAction(func(request prago.Request) {
		request.SetData("locale", GetLocale(request))
	})

	loginForm := func(locale string) *Form {
		form := NewForm()
		form.Method = "POST"
		form.AddEmailInput("email", messages.Messages.Get(locale, "admin_email")).Focused = true
		form.AddPasswordInput("password", messages.Messages.Get(locale, "admin_password"))
		form.AddSubmit("send", messages.Messages.Get(locale, "admin_login_action"))
		return form
	}

	renderLogin := func(request prago.Request, form *Form, locale string) {
		title := fmt.Sprintf("%s - %s", messages.Messages.Get(locale, "admin_login_name"), a.AppName)
		request.SetData("bottom", fmt.Sprintf("<a href=\"registration\">%s</a><br><a href=\"forgot\">%s</a>",
			messages.Messages.Get(locale, "admin_register"),
			messages.Messages.Get(locale, "admin_forgoten"),
		))
		request.SetData("admin_header_prefix", a.Prefix)
		request.SetData("admin_form", form)
		request.SetData("title", title)

		prago.Render(request, 200, "admin_login")
	}

	a.AdminAccessController.Get(a.GetURL(resource, "confirm_email"), func(request prago.Request) {
		email := request.Params().Get("email")
		token := request.Params().Get("token")

		var user User
		err := a.Query().WhereIs("email", email).Get(&user)
		if err == nil {
			if !user.emailConfirmed() {
				if token == user.emailToken(request.App()) {
					user.EmailConfirmedAt = time.Now()
					err = a.Save(&user)
					if err == nil {
						AddFlashMessage(request, messages.Messages.Get(GetLocale(request), "admin_confirm_email_ok"))
						prago.Redirect(request, a.Prefix+"/user/login")
						return
					}
				}
			}
		}

		AddFlashMessage(request, messages.Messages.Get(GetLocale(request), "admin_confirm_email_fail"))
		prago.Redirect(request, a.Prefix+"/user/login")
	})

	forgotForm := func(locale string) *Form {
		form := NewForm()
		form.Method = "POST"
		form.AddEmailInput("email", messages.Messages.Get(locale, "admin_email")).Focused = true
		form.AddSubmit("send", messages.Messages.Get(locale, "admin_forgotten_submit"))
		return form
	}

	renderForgot := func(request prago.Request, form *Form, locale string) {
		title := fmt.Sprintf("%s - %s", messages.Messages.Get(locale, "admin_forgotten_name"), a.AppName)
		request.SetData("bottom", fmt.Sprintf("<a href=\"login\">%s</a>",
			messages.Messages.Get(locale, "admin_login_action"),
		))
		request.SetData("admin_header_prefix", a.Prefix)
		request.SetData("admin_form", form)
		request.SetData("title", title)

		prago.Render(request, 200, "admin_login")
	}

	a.AdminAccessController.Get(a.GetURL(resource, "forgot"), func(request prago.Request) {
		locale := GetLocale(request)
		form := forgotForm(locale)
		renderForgot(request, form, locale)
	})

	a.AdminAccessController.Post(a.GetURL(resource, "forgot"), func(request prago.Request) {
		email := request.Params().Get("email")
		email = fixEmail(email)

		var user User
		err := a.Query().WhereIs("email", email).Get(&user)
		if err == nil {
			if user.emailConfirmed() {
				if !time.Now().AddDate(0, 0, -1).Before(user.EmailRenewedAt) {
					user.EmailRenewedAt = time.Now()
					err = a.Save(&user)
					if err == nil {
						err = user.sendRenew(request, a)
						if err == nil {
							AddFlashMessage(request, messages.Messages.Get(GetLocale(request), "admin_forgoten_sent", user.Email))
							prago.Redirect(request, a.Prefix+"/user/login")
							return
						}
					}
				}
			}
		}

		AddFlashMessage(request, messages.Messages.Get(GetLocale(request), "admin_forgoten_error", user.Email))
		prago.Redirect(request, a.Prefix+"/user/forgot")
	})

	renewPasswordForm := func(locale string) (form *Form) {
		form = NewForm()
		form.Method = "POST"

		passwordInput := form.AddPasswordInput("password", messages.Messages.Get(locale, "admin_password_new"),
			MinLengthValidator(messages.Messages.Get(locale, "admin_password_length"), 8))
		passwordInput.Focused = true
		form.AddSubmit("send", messages.Messages.Get(locale, "admin_forgoten_set"))
		return
	}

	renderRenew := func(request prago.Request, form *Form, locale string) {
		email := request.Params().Get("email")
		email = fixEmail(email)
		title := fmt.Sprintf("%s - %s", email, messages.Messages.Get(locale, "admin_forgoten_set"))
		request.SetData("bottom", fmt.Sprintf("<a href=\"login\">%s</a>",
			messages.Messages.Get(locale, "admin_login_action"),
		))
		request.SetData("admin_header_prefix", a.Prefix)
		request.SetData("admin_form", form)
		request.SetData("title", title)

		prago.Render(request, 200, "admin_login")
	}

	a.AdminAccessController.Get(a.GetURL(resource, "renew_password"), func(request prago.Request) {
		locale := GetLocale(request)
		form := renewPasswordForm(locale)
		renderRenew(request, form, locale)
	})

	a.AdminAccessController.Post(a.GetURL(resource, "renew_password"), func(request prago.Request) {
		locale := GetLocale(request)

		form := renewPasswordForm(locale)

		form.BindData(request.Params())
		form.Validate()

		email := request.Params().Get("email")
		email = fixEmail(email)
		token := request.Params().Get("token")

		errStr := messages.Messages.Get(locale, "admin_error")

		var user User
		err := a.Query().WhereIs("email", email).Get(&user)
		if err == nil {
			if token == user.emailToken(request.App()) {
				if form.Valid {
					err = user.newPassword(request.Params().Get("password"))
					if err == nil {
						err = a.Save(&user)
						if err == nil {
							AddFlashMessage(request, messages.Messages.Get(locale, "admin_password_changed"))
							prago.Redirect(request, a.Prefix+"/user/login")
							return
						}
					}
				}
			}
		}
		AddFlashMessage(request, errStr)
		form.GetItemByName("password").Value = ""
		renderLogin(request, form, locale)
	})

	a.AdminAccessController.Get(a.GetURL(resource, "login"), func(request prago.Request) {
		locale := GetLocale(request)
		form := loginForm(locale)
		renderLogin(request, form, locale)
	})

	a.AdminAccessController.Post(a.GetURL(resource, "login"), func(request prago.Request) {
		email := request.Params().Get("email")
		email = fixEmail(email)
		password := request.Params().Get("password")

		session := request.GetData("session").(*sessions.Session)

		locale := GetLocale(request)
		form := loginForm(locale)
		form.Items[0].Value = email
		form.Errors = []string{messages.Messages.Get(locale, "admin_login_error")}

		var user User
		err := a.Query().WhereIs("email", email).Get(&user)
		if err != nil {
			if err == ErrItemNotFound {
				prago.Must(session.Save(request.Request(), request.Response()))
				renderLogin(request, form, locale)
				return
			}
			panic(err)
		}

		if !user.isPassword(password) {
			renderLogin(request, form, locale)
			return
		}

		user.LoggedInTime = time.Now()
		user.LoggedInUseragent = request.Request().UserAgent()
		user.LoggedInIP = request.Request().Header.Get("X-Forwarded-For")

		prago.Must(a.Save(&user))

		session.Values["user_id"] = user.ID
		session.AddFlash(messages.Messages.Get(locale, "admin_login_ok"))
		prago.Must(session.Save(request.Request(), request.Response()))
		prago.Redirect(request, a.Prefix)
	})

	a.AdminController.Get(a.GetURL(resource, "as")+"/:id", func(request prago.Request) {

		u := GetUser(request)
		if !u.IsSysadmin {
			panic("access denied")
		}

		id, err := strconv.Atoi(request.Params().Get("id"))
		if err != nil {
			panic(err)
		}

		var user User
		prago.Must(a.Query().WhereIs("id", id).Get(&user))

		session := request.GetData("session").(*sessions.Session)
		session.Values["user_id"] = user.ID
		prago.Must(session.Save(request.Request(), request.Response()))
		prago.Redirect(request, a.Prefix)

	})

	newUserForm := func(locale string) *Form {
		form := NewForm()
		form.Method = "POST"
		form.AddTextInput("name", messages.Messages.Get(locale, "Name"),
			NonEmptyValidator(messages.Messages.Get(locale, "admin_user_name_not_empty")),
		)
		form.AddEmailInput("email", messages.Messages.Get(locale, "admin_email"),
			EmailValidator(messages.Messages.Get(locale, "admin_email_not_valid")),
			NewValidator(func(field *FormItem) bool {
				if len(field.Errors) != 0 {
					return true
				}
				var user User
				a.Query().WhereIs("email", field.Value).Get(&user)
				if user.Email == field.Value {
					return false
				}
				return true
			}, messages.Messages.Get(locale, "admin_email_already_registered")),
		)
		form.AddPasswordInput("password", messages.Messages.Get(locale, "admin_register_password"),
			MinLengthValidator("", 8),
		)
		form.AddSubmit("send", messages.Messages.Get(locale, "admin_register"))
		return form
	}

	renderRegistration := func(request prago.Request, form *Form, locale string) {
		title := fmt.Sprintf("%s - %s", messages.Messages.Get(locale, "admin_register"), a.AppName)
		request.SetData("bottom", fmt.Sprintf("<a href=\"login\">%s</a>",
			messages.Messages.Get(locale, "admin_login_action"),
		))
		request.SetData("admin_header_prefix", a.Prefix)
		request.SetData("admin_form", form)
		request.SetData("title", title)

		prago.Render(request, 200, "admin_login")
	}

	a.AdminAccessController.Get(a.GetURL(resource, "registration"), func(request prago.Request) {
		locale := GetLocale(request)
		renderRegistration(request, newUserForm(locale), locale)
	})

	a.AdminAccessController.Post(a.GetURL(resource, "registration"), func(request prago.Request) {
		locale := GetLocale(request)

		form := newUserForm(locale)

		form.BindData(request.Params())
		form.Validate()

		if form.Valid {
			email := request.Params().Get("email")
			email = fixEmail(email)
			user := &User{}
			user.Email = email
			user.Name = request.Params().Get("name")
			user.IsActive = true
			user.Locale = locale
			prago.Must(user.newPassword(request.Params().Get("password")))
			prago.Must(user.sendConfirmEmail(request, a))
			err := user.sendAdminEmail(request, a)
			if err != nil {
				request.App().Log().Println(err)
			}
			prago.Must(a.Create(user))

			AddFlashMessage(request, messages.Messages.Get(locale, "admin_confirm_email_send", user.Email))
			prago.Redirect(request, a.Prefix+"/user/login")
		} else {
			form.GetItemByName("password").Value = ""
			renderRegistration(request, form, locale)
		}
	})

	a.AdminController.Get(a.Prefix+"/logout", func(request prago.Request) {
		ValidateCSRF(request)
		session := request.GetData("session").(*sessions.Session)
		delete(session.Values, "user_id")
		session.AddFlash(messages.Messages.Get(GetLocale(request), "admin_logout_ok"))
		err := session.Save(request.Request(), request.Response())
		if err != nil {
			panic(err)
		}
		prago.Redirect(request, a.GetURL(resource, "login"))
	})

	settingsForm := func(locale string, user *User) *Form {
		form, err := resource.StructCache.GetForm(user, locale, whiteListFilter("Name", "Email"), whiteListFilter("Name", "Locale"))
		if err != nil {
			panic(err)
		}

		sel := form.AddSelect("Locale", messages.Messages.Get(locale, "admin_locale"), availableLocales)
		sel.Value = user.Locale

		form.AddSubmit("_submit", messages.Messages.Get(locale, "admin_edit"))
		return form
	}

	renderSettings := func(request prago.Request, user *User, form *Form) {
		request.SetData("admin_item", user)
		request.SetData("admin_form", form)
		request.SetData("admin_yield", "admin_settings")
		prago.Render(request, 200, "admin_layout")
	}

	a.AdminController.Get(a.GetURL(resource, "settings"), func(request prago.Request) {
		user := GetUser(request)
		form := settingsForm(GetLocale(request), user)
		AddCSRFToken(form, request)
		request.SetData("admin_title", messages.Messages.Get(GetLocale(request), "admin_settings"))
		renderSettings(request, user, form)
	})

	a.AdminController.Post(a.GetURL(resource, "settings"), func(request prago.Request) {
		ValidateCSRF(request)
		user := GetUser(request)
		form := settingsForm(GetLocale(request), user)
		AddCSRFToken(form, request)
		form.Validate()
		if form.Valid {
			prago.Must(resource.StructCache.BindData(user, request.Params(), request.Request().MultipartForm, form.getFilter()))
			prago.Must(a.Save(user))
			AddFlashMessage(request, messages.Messages.Get(GetLocale(request), "admin_settings_changed"))
			prago.Redirect(request, a.GetURL(resource, "settings"))
			return
		}
		renderSettings(request, user, form)
	})

	changePasswordForm := func(request prago.Request) *Form {
		user := GetUser(request)
		locale := GetLocale(request)
		oldValidator := NewValidator(func(field *FormItem) bool {
			if !user.isPassword(field.Value) {
				return false
			}
			return true
		}, messages.Messages.Get(locale, "admin_password_wrong"))

		form := NewForm()
		form.Method = "POST"
		form.AddPasswordInput("oldpassword",
			messages.Messages.Get(locale, "admin_password_old"),
			oldValidator,
		)
		form.AddPasswordInput("newpassword",
			messages.Messages.Get(locale, "admin_password_new"),
			MinLengthValidator(messages.Messages.Get(locale, "admin_password_length"), 8),
		)
		form.AddSubmit("_submit", messages.Messages.Get(locale, "admin_save"))
		return form
	}

	renderPasswordForm := func(request prago.Request, form *Form) {
		request.SetData("admin_title", messages.Messages.Get(GetLocale(request), "admin_password_change"))
		request.SetData("admin_form", form)
		request.SetData("admin_yield", "admin_form_view")
		prago.Render(request, 200, "admin_layout")
	}

	a.AdminController.Get(a.GetURL(resource, "password"), func(request prago.Request) {
		form := changePasswordForm(request)
		renderPasswordForm(request, form)
	})

	a.AdminController.Post(a.GetURL(resource, "password"), func(request prago.Request) {
		form := changePasswordForm(request)
		form.BindData(request.Params())
		form.Validate()
		if form.Valid {
			password := request.Params().Get("newpassword")
			user := GetUser(request)
			prago.Must(user.newPassword(password))
			prago.Must(a.Save(user))
			AddFlashMessage(request, messages.Messages.Get(GetLocale(request), "admin_password_changed"))
			prago.Redirect(request, a.GetURL(resource, "settings"))
		} else {
			renderPasswordForm(request, form)
		}
	})

	return nil
}
Exemple #13
0
//AddFlashMessage adds flash message to request
func AddFlashMessage(request prago.Request, message string) {
	session := request.GetData("session").(*sessions.Session)
	session.AddFlash(message)
	prago.Must(session.Save(request.Request(), request.Response()))
}
Exemple #14
0
//InitResource of file
func (File) InitResource(a *Admin, resource *Resource) error {
	resource.Pagination = 100

	fileUploadPath = a.App.Config.GetString("fileUploadPath")
	fileDownloadPath = a.App.Config.GetString("fileDownloadPath")

	if !strings.HasSuffix(fileUploadPath, "/") {
		fileUploadPath += "/"
	}
	if !strings.HasSuffix(fileDownloadPath, "/") {
		fileDownloadPath += "/"
	}

	bindImageAPI(a, fileDownloadPath)

	resource.Actions["create"] = func(a *Admin, resource *Resource) {
		resource.ResourceController.Post(a.GetURL(resource, ""), func(request prago.Request) {
			ValidateCSRF(request)

			multipartFiles := request.Request().MultipartForm.File["file"]
			if len(multipartFiles) != 1 {
				panic("must have 1 file selected")
			}

			file, err := uploadFile(multipartFiles[0], fileUploadPath)
			if err != nil {
				panic(err)
			}
			file.User = GetUser(request).ID
			file.Description = request.Params().Get("Description")
			prago.Must(a.Create(file))

			AddFlashMessage(request, messages.Messages.Get(GetLocale(request), "admin_item_created"))
			prago.Redirect(request, a.Prefix+"/"+resource.ID)
		})
	}

	resource.Actions["detail"] = func(a *Admin, resource *Resource) {
		resource.ResourceController.Get(a.GetURL(resource, ":id"), func(request prago.Request) {
			id, err := strconv.Atoi(request.Params().Get("id"))
			prago.Must(err)

			var file File
			prago.Must(a.Query().WhereIs("id", int64(id)).Get(&file))

			form := NewForm()
			form.Method = "POST"

			fi := form.AddTextInput("Name", messages.Messages.Get(GetLocale(request), "Name"))
			fi.Readonly = true
			fi.Value = file.Name

			_, fileURL := file.getPath(fileDownloadPath + "original")

			fi = form.AddTextInput("url", messages.Messages.Get(GetLocale(request), "Url"))
			fi.Readonly = true
			fi.Value = fileURL
			fi.SubTemplate = "admin_item_link"

			fi = form.AddTextInput("size", messages.Messages.Get(GetLocale(request), "Size"))
			fi.Readonly = true
			fi.Value = fmt.Sprintf("%d", file.Size)

			fi = form.AddTextInput("uploadedBy", messages.Messages.Get(GetLocale(request), "Uploaded By"))
			fi.Readonly = true
			fi.Value = fmt.Sprintf("%d", file.User)

			fi = form.AddTextInput("fileType", messages.Messages.Get(GetLocale(request), "Type"))
			fi.Readonly = true
			fi.Value = file.FileType

			if file.isImage() {
				fi = form.AddTextInput("width", messages.Messages.Get(GetLocale(request), "Width"))
				fi.Readonly = true
				fi.Value = fmt.Sprintf("%d", file.Width)

				fi = form.AddTextInput("height", messages.Messages.Get(GetLocale(request), "Height"))
				fi.Readonly = true
				fi.Value = fmt.Sprintf("%d", file.Height)

				for _, v := range []string{"large", "medium", "small"} {
					fi = form.AddTextInput("thumb"+v, messages.Messages.Get(GetLocale(request), v))
					fi.Readonly = true
					_, path := file.getPath(fileDownloadPath + "thumb/" + v)
					fi.Value = path
					fi.SubTemplate = "admin_item_link"
				}

			}

			fi = form.AddTextareaInput("Description", messages.Messages.Get(GetLocale(request), "Description"))
			fi.Value = file.Description
			fi.Focused = true
			form.AddSubmit("_submit", messages.Messages.Get(GetLocale(request), "admin_edit"))
			AddCSRFToken(form, request)

			request.SetData("admin_item", file)
			request.SetData("admin_form", form)
			request.SetData("admin_yield", "admin_edit")
			prago.Render(request, 200, "admin_layout")
		})
	}

	return nil
}