예제 #1
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
}
예제 #2
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
}
예제 #3
0
파일: auth.go 프로젝트: Raysmond/RaysGo
// 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)
}
예제 #4
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")
}
예제 #5
0
파일: board.go 프로젝트: GeoLyu/Gopen
// 글쓰기 //
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")
				}
			}
		}
	}

}
예제 #6
0
파일: init.go 프로젝트: jango2015/go-cms
/*
数据对象合法性验证
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
}
예제 #7
0
파일: api.go 프로젝트: cnhans/kingdoms
/* 新增武将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()
}
예제 #8
0
파일: user.go 프로젝트: nathan-osman/pratl
// 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()
}
예제 #9
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)
	}

}
예제 #10
0
파일: config.go 프로젝트: Raysmond/RaysGo
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"
}
예제 #11
0
파일: user.go 프로젝트: nathan-osman/pratl
// 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()
}
예제 #12
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
}
예제 #13
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
}
예제 #14
0
파일: api.go 프로젝트: cnhans/kingdoms
/* 新增关卡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()
}
예제 #15
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)
			}
		}
	}
}
예제 #16
0
파일: user.go 프로젝트: naokij/gotalk
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)
	}
}
예제 #17
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
}
예제 #18
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
}
예제 #19
0
파일: admin.go 프로젝트: sshitaime/myblog
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

}
예제 #20
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
}
예제 #21
0
파일: auth.go 프로젝트: naokij/gotalk
//重设密码
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
		}
	}
}
예제 #22
0
파일: admin.go 프로젝트: 11101171/violence
func (this *AdminController) AgentOperate() {
	if this.Ctx.Input.Method() == "GET" {
		agentId := this.Ctx.Input.Param(":agentId")
		beego.Info("agentId", agentId)

		agent := &models.Agent{}
		if agentId != "" {
			agent = agent.SelectOneById(agentId)
		}
		this.Data["AgentForm"] = agent
		this.Layout = "layout/main.html"
		this.TplNames = "admin/agent/operate.html"
	} else {
		agent := &models.Agent{}
		if err := this.ParseForm(agent); err != nil {
			this.Data["jons"] = err
			this.ServeJson()
			return
		}

		agent.UserId = this.GetAuthUser().Id
		var valid *validation.Validation
		if agent.Id == "" {
			valid = agent.ValidAgentAdd()
		} else {
			valid = agent.ValidAgentEdit()
		}

		b, _ := valid.Valid(agent)
		if !b {
			this.Data["ErrorMap"] = valid.ErrorMap()
			this.Data["ErrorForm"] = agent
			for k, v := range valid.ErrorMap() {
				beego.Info(k, " Error is ", "-", v.Value, "-", v.Field, "-", v.Tmpl, "-", v.Key, "=", v.Message, "-")
			}
			this.Layout = "layout/main.html"
			this.TplNames = "admin/agent/operate.html"
			return
		}

		var message string
		if agent.Id == "" {
			message = "新增ssh成功"
			if err := agent.InsertOne(); err != nil {
				this.ErrDataBase("新增ssh失败")
				return
			}
		} else {
			message = "更新ssh成功"
			if err := agent.UpdateOne(); err != nil {
				this.ErrDataBase("更新ssh失败")
				return
			}
		}

		this.DoSuccess(message, "/admin/agent/list")

	}
}
예제 #23
0
파일: auth.go 프로젝트: naokij/gotalk
func (this *AuthController) DoRegister() {
	this.CheckRequestFrequency(3, 15, 30)
	this.Layout = "layout.html"
	this.TplNames = "register.html"
	valid := validation.Validation{}
	form := RegisterForm{}
	if err := this.ParseForm(&form); err != nil {
		beego.Error(err)
	}
	b, err := valid.Valid(form)
	if err != nil {
		beego.Error(err)
	}
	if !b {
		this.registerPageWithErrors(form, valid.Errors)
		return
	}
	//验证用户名
	user := models.User{Username: form.Username}
	if err := user.ValidUsername(); err != nil {
		valid.SetError("username", err.Error())
		this.registerPageWithErrors(form, valid.Errors)
		return
	} else {
		if user.Read("Username") == nil {
			valid.SetError("username", fmt.Sprintf("%s已被使用,请使用其他用户名!", form.Username))
			this.registerPageWithErrors(form, valid.Errors)
			return
		}
	}
	//验证email未被注册
	user.Email = form.Email
	if user.Read("Email") == nil {
		valid.SetError("email", "已被使用,请直接使用此电邮登录")
		this.registerPageWithErrors(form, valid.Errors)
		return
	}
	//通过所有验证
	actCode, _ := user.GenerateActivateCode()
	user.SetPassword(form.Password)
	if err := user.Insert(); err != nil {
		beego.Error(err)
		this.Abort("500")
		return
	}
	sub := sendcloud.NewSubstitution()
	sub.AddTo(user.Email)
	sub.AddSub("%appname%", setting.AppName)
	sub.AddSub("%name%", user.Username)
	sub.AddSub("%url%", setting.AppUrl+beego.UrlFor("AuthController.Activate", ":code", actCode))
	if err := setting.Sendcloud.SendTemplate("gotalk_register", setting.AppName+"欢迎你", setting.From, setting.FromName, sub); err != nil {
		beego.Error(err)
	}
	this.FlashWrite("notice", fmt.Sprintf("注册成功!欢迎你, %s。建议你再花点时间上传头像、验证电子邮件!", user.Username))
	this.LogUserIn(&user, false)
	userEditUrl := beego.UrlFor("UserController.Edit", ":username", user.Username)
	this.Redirect(userEditUrl, 302)
	return
}
예제 #24
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")
				}
			}
		}
	}
}
예제 #25
0
파일: post.go 프로젝트: Raysmond/RaysGo
// Post implemented editing a post
func (this *PostController) EditPost() {
	var (
		post  *models.Node
		form  models.PostForm
		valid validation.Validation
		err   error
	)

	id, _ := helpers.Str2Int64(this.GetParam(":id"))
	if post = models.GetNode(id); post == nil || !this.canEditPost(post) {
		this.Abort("404")
	}

	if err = this.ParseForm(&form); err != nil {
		this.Abort("404")
	}

	result := false
	if ok, e := valid.Valid(form); ok && e == nil {
		post.Title = form.Title
		post.Content = form.Content
		post.ContentType = form.ContentType
		post.CreateTime = time.Now()
		post.IUser.Id = this.User().Id
		post.Status = models.GetStatus(form.Status)
		post.INodeType.Id = models.GetNodeType("post")

		tag := strings.TrimSpace(form.Tags)
		tags := make([]string, 0)
		tagarr := strings.Split(tag, ",")
		for _, v := range tagarr {
			if t := strings.TrimSpace(v); t != "" {
				tags = append(tags, t)
			}
		}

		if _, err = models.Engine.Id(id).Update(post); err == nil {
			models.AddTags(this.User().Id, post.Id, tags)
			result = true
			this.FlashNotice("Post updated successfully.")
		} else {
			this.FlashError("Post updated failed.")
		}

	} else {
		for _, m := range valid.Errors {
			this.FlashError(m.Key + " : " + m.Message)
		}
	}
	this.SaveFlash()
	if result {
		this.Redirect("/post/view/"+fmt.Sprintf("%d", post.Id), 302)
	}
	this.Data["Title"] = "Edit - " + post.Title
	this.Data["Post"] = post
	this.Data["Form"] = form
	this.TplNames = "post/edit.html"
}
예제 #26
0
파일: admin.go 프로젝트: 11101171/violence
// @router /user/operate/?:userId [get,post]
func (this *AdminController) UserOperate() {
	if this.Ctx.Input.Method() == "GET" {
		userId := this.Ctx.Input.Param(":userId")
		beego.Info("userId", userId)

		user := &models.User{}
		if userId != "" {
			user = user.SelectOneById(userId)
		}
		this.Data["UserForm"] = user
		this.Layout = "layout/main.html"
		this.TplNames = "admin/user/operate.html"
		return
	} else {
		user := &models.User{}
		if err := this.ParseForm(user); err != nil {
			this.Data["jons"] = err
			this.ServeJson()
			return
		}
		var valid *validation.Validation
		if user.Id == "" {
			valid = user.ValidUserAdd()
		} else {
			valid = user.ValidUserEdit()
		}

		b, _ := valid.Valid(user)
		if !b {
			this.Data["ErrorMap"] = valid.ErrorMap()
			this.Data["ErrorForm"] = user
			for k, v := range valid.ErrorMap() {
				beego.Info(k, " Error is ", "-", v.Value, "-", v.Field, "-", v.Tmpl, "-", v.Key, "=", v.Message, "-")
			}
			this.Layout = "layout/main.html"
			this.TplNames = "admin/user/operate.html"
			return
		}

		var message string
		if user.Id == "" {
			message = "新增用户成功"
			if err := user.InsertOne(); err != nil {
				this.ErrDataBase("新增用户失败")
				return
			}
		} else {
			message = "更新用户成功"
			if err := user.UpdateOne(); err != nil {
				this.ErrDataBase("更新用户失败")
				return
			}
		}

		this.DoSuccess(message, "/admin/user/list")
	}

}
예제 #27
0
파일: server.go 프로젝트: 11101171/violence
func (this *ServerController) Operate() {
	if this.Ctx.Input.IsGet() {
		serverId := this.Ctx.Input.Param(":serverId")
		beego.Debug("serverId=>", serverId)
		server := &models.Server{}
		if serverId != "" {
			server = server.SelectOneById(serverId)
		}
		this.Data["ServerForm"] = server
		this.Layout = "layout/main.html"
		this.TplNames = "admin/server/operate.html"
	} else {
		server := models.Server{}
		if err := this.ParseForm(&server); err != nil {
			this.ErrInputData("数据错误")
		}

		user := this.GetAuthUser()
		server.UserId = user.Id
		// beego.Debug("server=>",
		// fmt.Sprintf("%+v", server),
		// )
		var valid *validation.Validation
		if server.Id == "" {
			valid = server.ValidServerAdd()
		} else {
			valid = server.ValidServerEdit()
		}

		b, _ := valid.Valid(&server)
		if !b {
			this.Data["ErrorMap"] = valid.ErrorMap()
			this.Data["ErrorForm"] = server
			this.Layout = "layout/main.html"
			this.TplNames = "admin/server/operate.html"
			return
		}

		var message string
		if server.Id == "" {
			message = "新增API配置主题成功"
			if err := server.InsertOne(); err != nil {
				this.ErrDataBase("新增API配置主题失败")
				return
			}
		} else {
			message = "更新API配置主题成功"
			if err := server.UpdateOne(); err != nil {
				this.ErrDataBase("更新API配置主题失败")
				return
			}
		}
		services.GetInstance().CacheService.PutServerContent(server.Id, server.Content)
		this.DoSuccess(message, "/admin/server/index")

	}

}
예제 #28
0
파일: user.go 프로젝트: hugb/beegeserver
func checkUser(u *User) (err error) {
	valid := validation.Validation{}
	if b, _ := valid.Valid(&u); !b {
		for _, err := range valid.Errors {
			return errors.New(err.Message)
		}
	}
	return nil
}
예제 #29
0
func (this *RegisterController) Register() {

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

	register := models.Register{}
	flash := beego.NewFlash()
	// this.Data["Form"] = &register

	if err := this.ParseForm(&register); err != nil {
		beego.Error("Couldn't parse the form. Reason: ", err)
	} else {
		valid := validation.Validation{}

		valid.Required(register.Mail, "mail")

		isValid, _ := valid.Valid(register)

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

			if !isValid {
				this.Data["errors"] = valid.ErrorsMap

				for _, err := range valid.Errors {
					beego.Error(err.Key, err.Message)
				}

			} else {
				r := this.Ctx.Input
				register.IP = r.IP()
				fmt.Println(register.IP)

				_, err := o.Insert(&register)

				// res, err := o.Raw("INSERT INTO `incident` (`cat`, `title`, `description`,`date_request`, `priority`, `user_id`) VALUES (?,?,?,?,?,?)", register.Cat, register.Title, register.Description, date, register.Priority, this.GetSession("uid")).Exec()
				if err == nil {
					err := admin.SendMailAdmin()
					if err != nil {
						fmt.Println(err)
					}
					flash.Success(register.Mail + " : votre demande a bien été envoyé ")
					flash.Store(&this.Controller)
					this.Redirect("/", 302)
				} else {
					flash.Warning("Attention car cette adresse mail : " + register.Mail + " est déjà dans les demandes. ")
					flash.Store(&this.Controller)
					beego.Debug("Couldn't insert in tableName Register. Reason: ", err)

				}
			}

		}

	}
	Template(this, "user", "register", "Demande de Connexion / Nouveau mot de passe")
}
예제 #30
0
// Recursively validates a struct against `valid:"..." tags`
// The arg `parentType` is actually only used as an optional single argument
// Anything more than one is ignored
func Validate(obj interface{}, parentType ...string) (errs []error) {
	// Actual validation happens here
	validator := bvalidation.Validation{}
	valid, err := validator.Valid(obj)
	if err != nil {
		errs = append(errs, err)
		return
	}

	// Figure out if this object is a pointer
	// If so, derefernce it
	v := reflect.ValueOf(obj)
	if v.Kind() == reflect.Ptr {
		v = v.Elem()
	}

	// The actual type name of this object
	Type := v.Type().String()

	// If validation above failed
	if !valid {
		// If this function was called with at least one argument
		// Prepend that argument to the type name
		// Helps us find context in recursive calls
		if len(parentType) > 0 {
			parts := strings.Split(Type, ".")
			Type = fmt.Sprintf("%s.%s", parentType[0], parts[len(parts)-1])
		}

		// Collect all the validation errors and return them
		for _, e := range validator.Errors {
			errFmt := "%s validation failed: `%s` %s (actual value: %#v)"
			errs = append(errs,
				fmt.Errorf(errFmt, Type, e.Field, e.Message, e.Value))
		}
	}

	// Find sub-structs and validate them, too
	for i := range make([]struct{}, v.NumField()) {
		field := v.Field(i)
		if field.Kind() == reflect.Struct {
			errs = append(errs, Validate(field.Interface(), Type)...)
		} else if field.Kind() == reflect.Slice {
			if field.Len() > 0 {
				firstItem := field.Index(0)
				if firstItem.Kind() == reflect.Struct {
					for j := range make([]struct{}, field.Len()) {
						item := field.Index(j).Interface()
						errs = append(errs, Validate(item, Type)...)
					}
				}
			}
		}
	}
	return
}