Пример #1
0
func (l *LoginController) Recovery() {

	email := l.GetString("email")
	valid := validation.Validation{}
	valid.Email(email, "email")
	if valid.HasErrors() {
		var msg string
		for _, err := range valid.Errors {
			msg += fmt.Sprintf("%s: %s\r", err.Key, err.Message)
		}
		l.Ctx.ResponseWriter.WriteHeader(400)
		l.Data["json"] = &map[string]interface{}{"status": "error", "message": msg}
		l.ServeJson()
		return
	}

	user, _ := rbacModels.UserGetByEmail(email)
	if user.Id == 0 {
		l.Data["json"] = &map[string]interface{}{"status": "error", "message": "Пользователь не найден"}
	} else {
		site_url := beego.AppConfig.String("site_url")
		reset_token, _ := user.GenResetPassToken()
		params := map[string]interface{}{}
		params["user:one-time-login-url"] = fmt.Sprintf("%s/admin/reset?token=%s", site_url, reset_token)
		msg := emailSystem.New()
		msg.Template = "email_password_reset"
		msg.Params = &params
		msg.User = user
		if err := msg.SendMail(); err == nil {
			l.Data["json"] = &map[string]interface{}{"status": "info", "message": "Дальнейшие инструкции высланы на указанный почтовый ящик"}
		}
	}

	l.ServeJson()
}
Пример #2
0
/*
数据对象合法性验证
args:要检验的元素,长度为0,则检验全部元素
*/
func (this *base) invalidModel(m interface{}, args ...interface{}) (data interface{}, invalid bool) {

	valid := validation.Validation{}

	b, err := valid.Valid(m)
	if err != nil {
		data = utils.JsonMessage(false, "", err.Error())
		invalid = true
		return
	}
	if !b {
		var errstr string
		//检验元素
		if n := len(args); n > 0 {
			for _, err := range valid.Errors {
				if utils.ListContains(args, err.Key[0:strings.Index(err.Key, ".")]) {
					errstr += fmt.Sprintf("%s %s;", err.Key, err.Message)
				}
			}
		} else {
			for _, err := range valid.Errors {
				errstr += fmt.Sprintf("%s %s;", err.Key, err.Message)
			}
		}

		if errstr == "" {
			invalid = false
		} else {
			data = utils.JsonMessage(false, "", errstr)
			invalid = true
		}
		return
	}
	return
}
Пример #3
0
// Valid ...
func (r *RepTarget) Valid(v *validation.Validation) {
	if len(r.Name) == 0 {
		v.SetError("name", "can not be empty")
	}

	if len(r.Name) > 64 {
		v.SetError("name", "max length is 64")
	}

	if len(r.URL) == 0 {
		v.SetError("endpoint", "can not be empty")
	}

	r.URL = utils.FormatEndpoint(r.URL)

	if len(r.URL) > 64 {
		v.SetError("endpoint", "max length is 64")
	}

	// password is encoded using base64, the length of this field
	// in DB is 64, so the max length in request is 48
	if len(r.Password) > 48 {
		v.SetError("password", "max length is 48")
	}
}
Пример #4
0
func UpdateBackupSet(a *BackupSets) error {
	beego.Debug("[M] Got data:", a)
	o := orm.NewOrm()
	err := o.Begin()
	if err != nil {
		return err
	}
	validator := new(validation.Validation)
	valid, err := validator.Valid(a)
	if err != nil {
		o.Rollback()
		return err
	}
	if !valid {
		o.Rollback()
		var errS string
		for _, err := range validator.Errors {
			errS = fmt.Sprintf("%s, %s:%s", errS, err.Key, err.Message)
		}
		return fmt.Errorf("Bad info: %s", errS)
	}
	_, err = o.Update(a)
	if err != nil {
		o.Rollback()
		return err
	}
	o.Commit()
	return nil
}
Пример #5
0
func (this *baseRouter) validForm(form interface{}, names ...string) (bool, map[string]*validation.ValidationError) {
	// parse request params to form ptr struct
	utils.ParseForm(form, this.Input())

	// Put data back in case users input invalid data for any section.
	name := reflect.ValueOf(form).Elem().Type().Name()
	if len(names) > 0 {
		name = names[0]
	}
	this.Data[name] = form

	errName := name + "Error"

	// check form once
	if this.FormOnceNotMatch() {
		return false, nil
	}

	// Verify basic input.
	valid := validation.Validation{}
	if ok, _ := valid.Valid(form); !ok {
		errs := valid.ErrorMap()
		this.Data[errName] = &valid
		return false, errs
	}
	return true, nil
}
Пример #6
0
// Login attempts to authenticate a user. If successful, they are redirected to
// the list of channels that they can join.
func (c *UserController) Login() {
	f := &LoginForm{}
	if c.Ctx.Request.Method == "POST" {
		if err := c.ParseForm(f); err == nil {
			v := validation.Validation{}
			b, err := v.Valid(f)
			if b && err == nil {
				u, err := models.FindUser(f.Email)
				if err == nil {
					if err := u.Authenticate(f.Password); err == nil {
						c.SetSession("user_id", u.Id)
						r := c.GetString("redirect")
						if r == "" {
							r = c.URLFor("ChatController.Index")
						}
						c.Redirect(r, 302)
						return
					} else {
						c.Data["Error"] = "Invalid password"
					}
				} else {
					c.Data["Error"] = "No account with that email address"
				}
			} else {
				c.Data["Error"] = "Invalid form input"
			}
		} else {
			c.Data["Error"] = "Unable to parse form"
		}
	}
	c.TplName = "user/login.tpl"
	c.Render()
}
Пример #7
0
func (this *AdminController) EditUser() {
	o := orm.NewOrm()
	o.Using("default")

	usersId, _ := strconv.Atoi(this.Ctx.Input.Param(":id"))
	users := models.User{}

	flash := beego.NewFlash()

	err := o.QueryTable("user").Filter("id", usersId).One(&users)

	if err != orm.ErrNoRows {

		err := this.ParseForm(&users)
		if err != nil {

			beego.Error("Impossible de parser. Raison: ", err)

		} else {

			valid := validation.Validation{}

			valid.Required(users.Mail, "mail")
			valid.Required(users.Role, "role")

			isValid, _ := valid.Valid(users)

			if this.Ctx.Input.Method() == "POST" {

				if !isValid {
					flash.Error("Impossible de mettre à jour l'utilisateur")
					flash.Store(&this.Controller)
					this.Redirect("/incident-manager/admin/user", 302)
				} else {
					_, err := o.Update(&users)

					if err == nil {
						flash.Notice("Utilisateur " + users.Mail + " mis à jour")
						flash.Store(&this.Controller)

						this.Redirect("/incident-manager/admin/user", 302)
					} else {
						fmt.Println("erreur")

						beego.Debug("Mise à jour Impossible dû a : ", err)
					}
				}

			}

		}
		this.Redirect("/incident-manager/admin/user", 302)

	} else {
		flash.Notice("Utilisateur %d n'existe pas", usersId)
		flash.Store(&this.Controller)
		this.Redirect("/incident-manager/", 302)
	}

}
Пример #8
0
// Post implemented login action
func (this *LoginController) Login() {
	var (
		user  models.User
		form  models.LoginForm
		valid validation.Validation
	)

	if err := this.ParseForm(&form); err != nil {
		fmt.Println(err)
	} else {
		if ok, valid_err := valid.Valid(form); ok && valid_err == nil {
			user.Name = form.UserName
			//user.Password = helpers.EncryptPassword(form.Password, nil)
			has, gerr := models.Engine.Get(&user)
			if has && gerr == nil && helpers.ValidatePassword(user.Password, form.Password) {
				this.SetSession("username", user.Name)
				this.SetSession("userid", int(user.Id))
				this.SetSession("userrole", int(user.IRole.Id))
				this.SetSession("useremail", user.Email)

				this.Redirect("/user/view/"+fmt.Sprintf("%d", user.Id), 302)
			}
		} else {
			for _, e := range valid.Errors {
				this.FlashError(e.Key + " : " + e.Message)
			}
		}
	}

	this.SaveFlash()
	this.Data["Form"] = form
	this.Data["Title"] = "Login"
	this.TplNames = "auth/login.html"
	// this.Redirect("/login", 302)
}
Пример #9
0
//重设密码
func (this *AuthController) ResetPassword() {
	code := this.Ctx.Input.Param(":code")
	user := models.User{}
	if !user.TestActivateCode(code) {
		this.Abort("403")
	}
	this.Data["code"] = code
	this.Data["PageTitle"] = fmt.Sprintf("重设密码 | %s", setting.AppName)
	this.Layout = "layout.html"
	this.TplNames = "reset-password.html"
	valid := validation.Validation{}
	form := ResetPasswordForm{}
	if this.Ctx.Request.Method == "POST" {
		if err := this.ParseForm(&form); err != nil {
			beego.Error(err)
		}
		b, err := valid.Valid(form)
		if err != nil {
			beego.Error(err)
		}
		if b {
			user.SetPassword(form.Password)
			if err := user.Update(); err != nil {
				beego.Error(err)
				this.Abort("500")
			}
			user.ConsumeActivateCode(code)
			this.FlashWrite("notice", "新密码已经生效,请重新登录!")
			this.Redirect("/login", 302)
		} else {
			this.Data["HasError"] = true
			this.Data["errors"] = valid.Errors
		}
	}
}
Пример #10
0
func (u *User) Check(v *validation.Validation) {
	if u.Name == "toukii" && u.Passwd == "1234" {
		v.Clear()
	} else {
		v.SetError("login", "user is abnormal.")
	}
}
Пример #11
0
// Valid is the custom validation. It runs only when all the standard validations pass
func (o *Object) Valid(v *validation.Validation) {
	if o.Score == 0 {
		// We have no way to set error code here
		// TODO: fix it in Beego
		v.SetError("Score", "Can not be empty")
	}
}
Пример #12
0
// 글쓰기 //
func (write *BoardController) Write() {
	write.Layout = "admin/layout.html"
	write.LayoutSections = make(map[string]string)
	write.LayoutSections["Header"] = "board/common/header.html"
	write.LayoutSections["Footer"] = "board/common/footer.html"
	write.TplNames = "board/write.html"

	flash := beego.ReadFromRequest(&write.Controller)

	if ok := flash.Data["error"]; ok != "" {
		write.Data["flash"] = ok
	}

	o := orm.NewOrm()
	o.Using("default")

	board := models.Board{}

	if err := write.ParseForm(&board); err != nil {
		beego.Error("에러발생 : ", err)
	} else {
		write.Data["boards"] = board
		valid := validation.Validation{}
		isValid, _ := valid.Valid(board)

		if write.Ctx.Input.Method() == "POST" {
			if !isValid {
				write.Data["Errors"] = valid.ErrorsMap
				beego.Error("폼이 에러")
			} else {
				searchArticle := models.Board{Idx: board.Idx}
				beego.Debug("추가된 게시물 : ", board.Idx)
				err = o.Read(&searchArticle)
				beego.Debug("Err:", err)
				flash := beego.NewFlash()

				if err == orm.ErrNoRows || err == orm.ErrMissPK {
					beego.Debug("Query 내역 : ", board)
					id, err := o.Insert(&board)
					if err == nil {
						msg := fmt.Sprintf("게시글이 다음과 같은 고유번호로 생성되었다 IDX :", id)
						beego.Debug(msg)
						flash.Notice(msg)
						flash.Store(&write.Controller)
					} else {
						msg := fmt.Sprintf("다음과 같은 이유로 새로운 게시물을 추가할수 없다. 사유 : ", err)
						beego.Debug(msg)
						flash.Error(msg)
						flash.Store(&write.Controller)
					}
					// 내용을 Insert후 /board 로 리다이렉트
					write.Redirect("/board", 302)
				} else {
					beego.Debug("Article found matching details supplied. Cannot insert")
				}
			}
		}
	}

}
Пример #13
0
func (manage *ManageController) Add() {
	manage.TplNames = "add.tpl"
	o := orm.NewOrm()
	o.Using("default")
	article := models.Article{}

	if err := manage.ParseForm(&article); err != nil {
		beego.Error("Couldn't parse the form. Reason: ", err)
	} else {
		manage.Data["Article"] = article
	}

	if manage.Ctx.Input.Method() == "POST" {
		valid := validation.Validation{}
		isValid, _ := valid.Valid(article)
		if !isValid {
			manage.Data["Error"] = valid.ErrorsMap
			beego.Error("Form didn't validate.", valid.ErrorsMap)
		} else {
			id, err := o.Insert(&article)
			if err == nil {
				msg := fmt.Sprintf("Article inserted with id: ", id)
				beego.Debug(msg)
			} else {
				msg := fmt.Sprintf("Couldn't insert new article. Reason: ", err)
				beego.Debug(msg)
			}
		}
	}
}
Пример #14
0
func (model *ResetPwdModel) Valid(v *validation.Validation) {
	// Check if passwords of two times are same.
	if model.Password != model.PasswordRe {
		v.SetError("PasswordRe", "auth.repassword_not_match")
		return
	}
}
Пример #15
0
/**
 * 登录
 */
func (this *LoginController) Login() {
	val := validation.Validation{}
	username := this.GetString("username")
	password := this.GetString("password")

	val.Required(username, "username")
	val.Required(password, "password")

	if val.HasErrors() {
		for _, v := range val.Errors {
			this.Ctx.WriteString("<script>alert('" + v.Key + " " + v.Message + "');</script>") //遇到一个错误就可以StopRun了其实,这里只是练习验证模块
		}
		this.StopRun()
	}
	toolbox.Display("u", username)
	toolbox.Display("pa", password)

	password = utils.LoginPassword(password)
	toolbox.Display("paaa", password)

	if user.CheckLogin(username, password) == true {
		this.SetSession("username", username)
		this.Ctx.SetCookie("username", username)
		this.Redirect("/admin", 302)
	} else {
		this.Redirect("/login", 302)
	}
}
Пример #16
0
func (this *BaseController) ValidForm(form interface{}) bool {

	log.Println("ValidForm")

	valid := validation.Validation{}
	ok, _ := valid.Valid(form)
	if !ok {
		for _, err := range valid.Errors {
			/* set error message */
			slice := strings.Split(err.Key, ".")
			name := slice[0] + "Error"
			message := "valid." + err.Message
			this.Data[name] = i18n.Tr(this.Locale.Lang, message)

			log.Println(name)
			log.Println(message)
			log.Println(this.Locale.Lang)
			log.Println(i18n.Tr(this.Locale.Lang, message))

			return false
		}
	}

	return true
}
Пример #17
0
func (this *ConfigController) ConfigPost() {
	var (
		form  models.ConfigForm
		valid validation.Validation
	)

	if err := this.ParseForm(&form); err != nil {
		fmt.Println(err)
	} else {
		if ok, ve := valid.Valid(form); ok && ve == nil {
			if form.Save() {
				this.FlashNotice("Configuration saved successfully.")
			} else {
				this.FlashError("Configuration saved failed.")
			}
		} else {
			for _, e := range valid.Errors {
				this.FlashError(e.Key + " : " + e.Message)
			}
		}
	}

	this.SaveFlash()
	this.Data["Form"] = form
	this.Data["Title"] = "Website configuration"
	this.TplNames = "admin/config.html"
}
Пример #18
0
func (this *AticleController) Add() {

	var article models.Article
	valid := validation.Validation{}
	title := this.GetString("title", "")
	content := this.GetString("content", "")
	typeId, _ := this.GetInt("typeId")
	article.Content = content
	article.Title = title
	article.TypeId = typeId
	this.Data["art"] = article
	this.GetLayout("admin/edit.tpl")
	b, err := valid.Valid(&article)
	if err != nil {
		beego.Error(err)
	}
	if !b {
		this.Data["err"] = valid.Errors
		return
	}

	models.InsertArt(&article)
	types := models.GetAllType()
	this.Data["types"] = types
	article.Content = ""
	article.Title = ""
	article.TypeId = -1
	this.Data["art"] = article

}
Пример #19
0
// Register displays the registration form.
func (c *UserController) Register() {
	f := &RegisterForm{}
	if c.Ctx.Request.Method == "POST" {
		if err := c.ParseForm(f); err == nil {
			v := validation.Validation{}
			b, err := v.Valid(f)
			if b && err == nil {
				if f.Password == f.Password2 {
					u, err := models.NewUser(f.Email, f.Name, f.Password)
					if err == nil {
						c.SetSession("user_id", u.Id)
						c.Redirect(c.URLFor("ChatController.Index"), 302)
						return
					} else {
						c.Data["Error"] = "Unable to complete registration"
					}
				} else {
					c.Data["Error"] = "Passwords don't match"
				}
			} else {
				c.Data["Error"] = "Invalid form input"
			}
		} else {
			c.Data["Error"] = "Unable to parse form"
		}
	}
	c.TplName = "user/register.tpl"
	c.Render()
}
Пример #20
0
func DeletePath(h *Paths) error {
	beego.Debug("[M] Got data:", h)
	o := orm.NewOrm()
	err := o.Begin()
	if err != nil {
		return err
	}
	validator := new(validation.Validation)
	valid, err := validator.Valid(h)
	if err != nil {
		o.Rollback()
		return err
	}
	if !valid {
		o.Rollback()
		var errS string
		for _, err := range validator.Errors {
			errS = fmt.Sprintf("%s, %s:%s", errS, err.Key, err.Message)
		}
		return fmt.Errorf("Bad info: %s", errS)
	}
	_, err = o.QueryM2M(h, "AppSet").Clear()
	if err != nil {
		o.Rollback()
		return err
	}
	_, err = o.Delete(h)
	if err != nil {
		o.Rollback()
		return err
	}
	o.Commit()
	return nil
}
Пример #21
0
func AddBackupSet(a *BackupSets) (string, error) {
	beego.Debug("[M] Got data:", a)
	o := orm.NewOrm()
	err := o.Begin()
	if err != nil {
		return "", err
	}

	a.Id = uuid.New()
	beego.Debug("[M] Got new id:", a.Id)
	validator := new(validation.Validation)
	valid, err := validator.Valid(a)
	if err != nil {
		o.Rollback()
		return "", err
	}
	if !valid {
		o.Rollback()
		var errS string
		for _, err := range validator.Errors {
			errS = fmt.Sprintf("%s, %s:%s", errS, err.Key, err.Message)
		}
		return "", fmt.Errorf("Bad info: %s", errS)
	}
	beego.Debug("[M] Got new data:", a)
	_, err = o.Insert(a)
	if err != nil {
		o.Rollback()
		return "", err
	}
	beego.Debug("[M] App set saved")
	o.Commit()
	return a.Id, nil
}
Пример #22
0
/* 新增关卡post */
func (this *ApiController) AddLevel() {
	//登陆提交的表单
	level := &models.Level{}
	//数据采集
	if err := this.ParseForm(level); err != nil {
		this.Data["json"] = -1
		this.ServeJson()
		this.StopRun()
	}
	//数据验证
	valid := validation.Validation{}
	b, err := valid.Valid(level)
	if err != nil {
		// handle error
	}
	if !b { //验证出错,停止
		this.Data["json"] = -2
		this.ServeJson()
		this.StopRun()
	}
	//卡牌id是否存在
	if level.IdExist(level.Id) {
		this.Data["json"] = -3
		this.ServeJson()
		this.StopRun()
	}
	//插入新关卡
	level.Insert()
	//输出
	this.Data["json"] = 1
	this.ServeJson()
}
Пример #23
0
func (form *ResetPwdForm) Valid(v *validation.Validation) {
	// Check if passwords of two times are same.
	if form.Password != form.PasswordRe {
		v.SetError("PasswordRe", "Passwords of two times are not matched.")
		return
	}
}
Пример #24
0
/* 新增武将post */
func (this *ApiController) AddCard() {
	//登陆提交的表单
	card := &models.Card{}
	//数据采集
	if err := this.ParseForm(card); err != nil {
		this.Data["json"] = -1
		this.ServeJson()
		this.StopRun()
	}
	//数据验证
	valid := validation.Validation{}
	b, _ := valid.Valid(card)
	if !b { //验证出错,停止
		this.Data["json"] = -2
		this.ServeJson()
		this.StopRun()
	}
	//卡牌id是否存在
	if card.IdExist(card.Id) {
		this.Data["json"] = -3
		this.ServeJson()
		this.StopRun()
	}
	//插入新卡牌
	card.Insert()
	SetAllCards()
	//输出
	this.Data["json"] = 1
	this.ServeJson()
}
Пример #25
0
func (form *PostAdminForm) Valid(v *validation.Validation) {
	user := models.User{Id: form.User}
	if user.Read() != nil {
		v.SetError("User", "admin.not_found_by_id")
	}

	user.Id = form.LastReply
	if user.Read() != nil {
		v.SetError("LastReply", "admin.not_found_by_id")
	}

	user.Id = form.LastAuthor
	if user.Read() != nil {
		v.SetError("LastReply", "admin.not_found_by_id")
	}

	topic := models.Topic{Id: form.Topic}
	if topic.Read() != nil {
		v.SetError("Topic", "admin.not_found_by_id")
	}

	if len(i18n.GetLangByIndex(form.Lang)) == 0 {
		v.SetError("Lang", "Not Found")
	}
}
Пример #26
0
/**
 *	@auther		jream.lu
 *	@intro		入参验证
 *	@logic
 *	@todo		返回值
 *	@meta		meta map[string][]string	   rawMetaHeader
 *	@data		data ...interface{}	切片指针	rawDataBody
 *	@return 	返回 true, metaMap, error
 */
func InputParamsCheck(meta map[string][]string, data ...interface{}) (result Result, err error) {
	//MetaHeader check
	metaCheckResult, err := MetaHeaderCheck(meta)
	if err != nil {
		return metaCheckResult, err
	}

	//DataParams check
	valid := validation.Validation{}

	for _, val := range data {
		is, err := valid.Valid(val)

		//日志

		//检查参数
		if err != nil {
			// handle error
			log.Println(i18n.Tr(global.Lang, "outputParams.SYSTEMILLEGAL"), err)
		}

		if !is {
			for _, err := range valid.Errors {
				log.Println(i18n.Tr(global.Lang, "outputParams.DATAPARAMSILLEGAL"), err.Key, ":", err.Message)
				result.MetaCheckResult = nil
				result.RequestID = metaCheckResult.MetaCheckResult["request-id"]
				result.Message = i18n.Tr(global.Lang, "outputParams.DATAPARAMSILLEGAL") + " " + err.Key + ":" + err.Message
				return result, errors.New(i18n.Tr(global.Lang, "outputParams.DATAPARAMSILLEGAL"))
			}
		}
	}

	return metaCheckResult, nil
}
Пример #27
0
func Test_Valid(t *testing.T) {
	valid := validation.Validation{}
	user := &models.User{Username: "******", Password: "******"}
	b, err := valid.Valid(user)
	if err != nil {
		// handle error
		t.Log(err.Error())
		t.Error("Valid Error")
	}
	if !b {
		// validation does not pass
		// blabla...
		for _, err := range valid.Errors {
			t.Log(err.Field + "-" + err.String())
			t.Log(err.Key, err.Message)
		}

		t.Log("ppppp")
		for k, v := range valid.ErrorMap() {
			t.Log(k, "=", v)
		}
		t.Error("Valid Error")
	}

	t.Log("Valid not has errors")
}
Пример #28
0
func DeleteRole(a *Roles) error {
	beego.Debug("[M] Got data:", a)
	o := orm.NewOrm()
	err := o.Begin()
	if err != nil {
		return err
	}
	validator := new(validation.Validation)
	valid, err := validator.Valid(a)
	if err != nil {
		o.Rollback()
		return err
	}
	if !valid {
		o.Rollback()
		var errS string
		for _, err := range validator.Errors {
			errS = fmt.Sprintf("%s, %s:%s", errS, err.Key, err.Message)
		}
		return fmt.Errorf("Bad info: %s", errS)
	}
	_, err = o.QueryTable("roles").Filter("removable", true).
		Filter("id", a.Id).Filter("name", a.Name).Delete()
	if err != nil {
		o.Rollback()
		return err
	}
	o.Commit()
	return nil
}
Пример #29
0
func (this *UserController) processUserPasswordForm(user *models.User) {
	valid := validation.Validation{}
	userPasswordForm := UserPasswordForm{}
	if err := this.ParseForm(&userPasswordForm); err != nil {
		beego.Error(err)
	}
	_, err := valid.Valid(userPasswordForm)
	if err != nil {
		beego.Error(err)
		this.Abort("400")
	}
	if !user.VerifyPassword(userPasswordForm.CurrentPassword) {
		valid.SetError("CurrentPassword", "当前密码错误")
	}
	if len(valid.Errors) > 0 {
		this.Data["UserPasswordFormValidErrors"] = valid.Errors
		beego.Trace(fmt.Sprint(valid.Errors))
	} else {
		user.SetPassword(userPasswordForm.Password)
		if err := user.Update(); err != nil {
			this.Abort("500")
		}
		this.FlashWrite("notice", "密码已更新!")
		this.Redirect(this.Ctx.Request.RequestURI, 302)
	}
}
Пример #30
0
func (manage *ManageController) Add() {
	manage.Data["Form"] = &models.Article{}
	manage.Layout = "basic-layout.tpl"
	manage.LayoutSections = make(map[string]string)
	manage.LayoutSections["Header"] = "header.tpl"
	manage.LayoutSections["Footer"] = "footer.tpl"
	manage.TplNames = "manage/add.tpl"

	flash := beego.ReadFromRequest(&manage.Controller)

	if ok := flash.Data["error"]; ok != "" {
		// Display error messages
		manage.Data["flash"] = ok
	}

	o := orm.NewOrm()
	o.Using("default")

	article := models.Article{}

	if err := manage.ParseForm(&article); err != nil {
		beego.Error("Couldn't parse the form. Reason: ", err)
	} else {
		manage.Data["Articles"] = article
		valid := validation.Validation{}
		isValid, _ := valid.Valid(article)

		if manage.Ctx.Input.Method() == "POST" {
			if !isValid {
				manage.Data["Errors"] = valid.ErrorsMap
				beego.Error("Form didn't validate.")
			} else {
				searchArticle := models.Article{Name: article.Name}
				beego.Debug("Article name supplied:", article.Name)
				err = o.Read(&searchArticle)
				beego.Debug("Err:", err)
				flash := beego.NewFlash()

				if err == orm.ErrNoRows || err == orm.ErrMissPK {
					beego.Debug("No article found matching details supplied. Attempting to insert article: ", article)
					id, err := o.Insert(&article)
					if err == nil {
						msg := fmt.Sprintf("Article inserted with id:", id)
						beego.Debug(msg)
						flash.Notice(msg)
						flash.Store(&manage.Controller)
					} else {
						msg := fmt.Sprintf("Couldn't insert new article. Reason: ", err)
						beego.Debug(msg)
						flash.Error(msg)
						flash.Store(&manage.Controller)
					}
				} else {
					beego.Debug("Article found matching details supplied. Cannot insert")
				}
			}
		}
	}
}