Example #1
0
func (this *AdminController) ByMailIncident() {
	flash := beego.NewFlash()
	o := orm.NewOrm()
	o.Using("default")

	var incidents []*models.Incident

	mail := this.GetSession("uid")

	num, err := o.QueryTable("Incident").Filter("User", mail).RelatedSel().All(&incidents)

	if err != orm.ErrNoRows && num > 0 {

		this.TplNames = "index/index.tpl"
		this.Data["incidents"] = incidents

		flash := beego.NewFlash()

		flash.Notice("Mes incidents déclarés")
		flash.Store(&this.Controller)

	} else {
		// No result
		flash.Error("Aucun Incident dans la Base de données")
		flash.Store(&this.Controller)
		this.Redirect("/", 302)
	}

	Template(this, "user", "myincident", "Liste de mes incidents déclarés")

}
Example #2
0
func (manage *ManageController) Update() {
	o := orm.NewOrm()
	o.Using("default")
	flash := beego.NewFlash()

	//convert the string value to an int
	if articleId, err := strconv.Atoi(manage.Ctx.Input.Param(":id")); err == nil {
		article := models.Article{Id: articleId}
		if o.Read(&article) == nil {
			article.Client = "Sitepoint"
			article.Url = "http:"
			if num, err := o.Update(&article); err == nil {
				flash.Notice("Record Was Update.")
				flash.Store(&manage.Controller)
				beego.Info("Record Was Update. ", num)
			} else {
				flash.Notice("Record Was NOT Updated.")
				flash.Store(&manage.Controller)
				beego.Error("Couldn't find article matching id: ", articleId)
			}
		} else {
			flash.Notice("Record Was NOT Updated.")
			flash.Store(&manage.Controller)
			beego.Error("Couldn't convert id from a string to a number. ", err)

		}
	}

	// redirect afterwards
	manage.Redirect("/manage/view", 302)

}
Example #3
0
func (this *AdminController) DeleteDemand() {
	o := orm.NewOrm()
	o.Using("default")

	demandId, _ := strconv.Atoi(this.Ctx.Input.Param(":id"))

	register := models.Register{}

	flash := beego.NewFlash()

	if exist := o.QueryTable(register.TableName()).Filter("Id", demandId).Exist(); exist {
		if num, err := o.Delete(&models.Register{Id: demandId}); err == nil {
			beego.Info("Record Deleted. ", num)
			flash.Notice("La demande a bien été supprimé")
		} else {
			beego.Error("La demande n'a pu être supprimé. Raison: ", err)
		}

	} else {
		flash.Notice("La demande n'existe pas %d", demandId)
	}

	flash.Store(&this.Controller)

	this.Redirect("/incident-manager/admin/register", 302)
}
Example #4
0
File: crit.go Project: grr89/hrkb
// update criteria
func (c *Crit) Get() {
	c.Data["isEdit"] = true
	c.TplNames = "crit/form.tpl"
	c.Data["xsrfdata"] = template.HTML(c.XsrfFormHtml())
	id, err := strconv.Atoi(c.Ctx.Input.Param(":id"))

	if err != nil {
		beego.Error(err)
		id = 0
	}
	var crit M.Crit
	if DM.FindByPk(&crit, id) != nil {
		flash := beego.NewFlash()
		flash.Notice(T("crit_not_found"))
		flash.Store(&c.Controller)
		c.Redirect(beego.UrlFor("Crit.Index"), 302)
		return
	}
	var deps []M.Dep
	err = DM.FindAll(&M.Dep{}, &deps, M.Sf{"Id", "Title"}, M.Where{})
	if err != nil {
		beego.Error(err)
	}

	c.Data["deps"] = deps
	c.Data["crit"] = crit
}
Example #5
0
func (this *MainController) DoLogin() {
	var (
		uemail string = strings.TrimSpace(this.GetString("uemail"))
		upw    string = strings.TrimSpace(this.GetString("upw"))
	)

	user, err := buser.FindUserByEmail(uemail)
	log.Println("user " + user.Username)
	log.Println("user.Password " + user.Password)
	log.Println("utils.Md5(upw) " + utils.Md5(upw))
	if (err != nil) || (user.Password != utils.Md5(upw)) || (user.Uid < 1) {
		flash := beego.NewFlash()
		flash.Set("uemail", uemail)
		flash.Set("error", utils.WrapString("登录出错,请检查用户名密码是否正确"))
		flash.Store(&this.Controller)
		url := utils.U("")
		this.Redirect(url, 302)
	} else {
		this.SetSession("IsLoggedIn", true)
		uc := context.UserContext{}
		context.SetUserContext(user.Uid, uc)
		url := utils.U("home")
		this.Redirect(url, 302)
	}

}
Example #6
0
// 个人信息
func (this *MainController) Profile() {
	beego.ReadFromRequest(&this.Controller)
	user, _ := models.UserGetById(this.userId)

	if this.isPost() {
		flash := beego.NewFlash()
		user.Email = this.GetString("email")
		user.Update()
		password1 := this.GetString("password1")
		password2 := this.GetString("password2")
		if password1 != "" {
			if len(password1) < 6 {
				flash.Error("密码长度必须大于6位")
				flash.Store(&this.Controller)
				this.redirect(beego.URLFor(".Profile"))
			} else if password2 != password1 {
				flash.Error("两次输入的密码不一致")
				flash.Store(&this.Controller)
				this.redirect(beego.URLFor(".Profile"))
			} else {
				user.Salt = string(utils.RandomCreateBytes(10))
				user.Password = libs.Md5([]byte(password1 + user.Salt))
				user.Update()
			}
		}
		flash.Success("修改成功!")
		flash.Store(&this.Controller)
		this.redirect(beego.URLFor(".Profile"))
	}

	this.Data["pageTitle"] = "个人信息"
	this.Data["user"] = user
	this.display()
}
Example #7
0
func (this *AdminController) DeleteUser() {
	o := orm.NewOrm()
	o.Using("default")

	usersId, _ := strconv.Atoi(this.Ctx.Input.Param(":id"))

	users := models.User{}

	flash := beego.NewFlash()

	if exist := o.QueryTable(users.TableName()).Filter("Id", usersId).Exist(); exist {
		if num, err := o.Delete(&models.User{Id: usersId}); err == nil {
			beego.Info("Record Deleted. ", num)
			flash.Warning("L'utilisateur a bien été supprimé")
		} else {
			beego.Error("L'utilisateur n'a pu être supprimé. Raison: ", err)
		}

	} else {
		flash.Error("L'utilisateur n'existe pas %d", usersId)
	}

	flash.Store(&this.Controller)

	this.Redirect("/incident-manager/admin/user", 302)
}
Example #8
0
func (c *UserController) Verify() {
	c.setupView("user/verify")
	flash := beego.NewFlash()

	uuid := c.Ctx.Input.Param(":uuid")
	user := &models.AuthUser{
		Reg_key: uuid,
	}
	o := orm.NewOrm()
	o.Using("default")
	errRead := o.Read(user, "Reg_key")
	if errRead != nil {
		flash.Error("Invalid data!")
		flash.Store(&c.Controller)
		return
	}
	user.Reg_key = ""
	numRows, errUpdate := o.Update(user, "Reg_key")
	if errUpdate != nil {
		fmt.Println(errUpdate)
		return
	}
	if numRows > 0 {
		flash.Notice("Account verified!")
		flash.Store(&c.Controller)
	}
}
Example #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)
	}

}
Example #10
0
func (c *ContactController) Contactsave() {
	fmt.Println("Contactsave kick")

	var f interface{}
	json.Unmarshal(c.Ctx.Input.CopyBody(100), &f)
	m := f.(map[string]interface{})
	//        fmt.Println(m["name"])
	//        fmt.Println(m["email"])
	contact := new(contact.Contact)
	contact.Name = m["name"].(string)
	contact.Email = m["email"].(string)

	err := c.repository.Save(contact)
	flash := beego.NewFlash()
	if err != nil {
		flash.Error("The contact could not be saved. Please, try again.")
	} else {
		flash.Notice("The contact has been saved.")
	}
	flash.Store(&c.Controller)

	contact2, _ := c.repository.FindAll()
	c.Data["json"] = &contact2
	c.ServeJSON()

	//   c.Redirect("/contact", 302)

}
Example #11
0
func (this *UserController) Signup() {
	uid := this.GetSession("Uid")
	if uid != nil {
		this.Redirect("/", 302)
	}

	if this.Ctx.Input.Param("0") != "submit" {
		this.Redirect("/user/login", 302)
	}

	user := models.User{
		Username: this.GetString("username"),
		Password: this.GetString("passkey"),
		Name:     this.GetString("name"),
		College:  this.GetString("college"),
		Email:    this.GetString("email"),
	}
	// All the fields verified, as well checked if username and email are unique
	err := user.SignupVerify()
	if err != nil {
		flash := beego.NewFlash()
		flash.Error(err.Error())
		flash.Store(&this.Controller)
	}
	uid, done := user.Create()

	if done {
		this.SetSession("Uid", this.GetString("username"))
		this.SetSession("id", uid)
		this.Redirect("/", 302)
	}
	this.Redirect("/user/login", 302)
}
Example #12
0
File: lang.go Project: grr89/hrkb
func (c *Lang) Remove() {

	s := T("lang_not_found")
	d := M.Lang{}

	id, err := strconv.Atoi(c.Ctx.Input.Param(":id"))

	if err == nil {
		err = DM.DeleteByPkWithFetch(&d, id)
	}

	if err == nil {
		s = T("lang_removed")
		err = c.cleanLang(d.Code)
	}

	if err != nil {
		beego.Error(err)
	}

	if c.IsAjax() {
		c.Data["json"] = RJson{s, err == nil}
		return
	}

	flash := beego.NewFlash()
	flash.Notice(s)
	flash.Store(&c.Controller)

	c.Redirect(beego.UrlFor("Lang.Index"), 302)

}
Example #13
0
// 删除用户
func (this *UserController) DeleteUser() {
	flash := beego.NewFlash()
	if checkAccountSession(&this.Controller) {
		id := this.Ctx.Input.Param(":id") // /user/:id 删除用户的路径
		idNum, err := strconv.ParseInt(id, 10, 64)
		if err != nil {
			beego.Error("删除用户失败:" + err.Error())
			flash.Error("删除用户失败!")
			flash.Store(&this.Controller)
			return
		}
		models.DeleteUser(idNum) //删除用户
		this.DelSession("user")  //清空session
		flash.Notice("用户删除成功!")
		flash.Store(&this.Controller)
		this.Redirect("/", 302) //重定向到主页
		return
	} else {
		flash.Error("您尚未登录,请登录!")
		flash.Store(&this.Controller)
		this.Redirect("/login", 302) //跳转到登录页
		return
	}

}
Example #14
0
func (self *EditQuestionHandler) Get() {
	self.TplNames = "sdc/edit-question.html"
	flash := beego.NewFlash()

	qid, _ := self.GetInt(":qid")

	if qid_handler, err := model.GetQuestion(qid); err == nil && qid_handler != nil {
		uid, _ := self.GetSession("userid").(int64)
		role, _ := self.GetSession("userrole").(int64)
		allow := bool(false)

		if qid_handler.Uid == uid && qid_handler.Id == qid {
			allow = true
		} else if role < 0 {
			allow = true
		}

		if allow {

			self.Data["question"] = *qid_handler
			self.Data["inode"], _ = model.GetNode(qid_handler.Nid)
		} else {

			//没有权限执行该操作则直接跳转到登录页面
			self.Redirect("/user/signin/", 302)
		}

	} else {

		flash.Error(fmt.Sprint(err))
		flash.Store(&self.Controller)
		return
	}
}
Example #15
0
func (self *EditAnswerHandler) Get() {
	self.TplNames = "sdc/edit-answer.html"
	flash := beego.NewFlash()

	aid, _ := self.GetInt(":aid")

	if aid_handler, err := model.GetAnswer(aid); err == nil && aid_handler != nil {
		uid, _ := self.GetSession("userid").(int64)
		role, _ := self.GetSession("userrole").(int64)
		allow := bool(false)

		if aid_handler.Uid == uid && aid_handler.Id == aid {
			allow = true
		} else if role < 0 {
			allow = true
		}

		if allow {
			self.Data["answer"] = *aid_handler
		} else {
			//没有权限执行该操作则直接跳转到登录页面
			self.Redirect("/user/signin/", 302)
		}

	} else {

		flash.Error(fmt.Sprint(err))
		flash.Store(&self.Controller)
		return
	}
}
Example #16
0
// 根据文章id删除文章
func (this *TopicController) DeleteTopic() {

	flash := beego.NewFlash()

	if checkAccountSession(&this.Controller) { //验证用户是否已登录
		id, err := strconv.ParseInt(this.Ctx.Input.Param(":id"), 10, 64)
		if err != nil {
			beego.Error("转换文章id失败")
			flash.Error("删除文章失败!")
			flash.Store(&this.Controller)
			return
		}
		if !models.DeleteTopic(id) {
			beego.Error("删除文章失败")
			flash.Error("删除文章失败!")
			flash.Store(&this.Controller)
			return
		}
		this.Redirect("/", 302) //删除成功回首页
		return
	} else {
		flash.Error("您尚未登录,请登录!")
		flash.Store(&this.Controller)
		this.Redirect("/login", 302) //跳转到登录页
		return
	}

}
Example #17
0
func (self *EditAnswerController) Get() {
	self.TplNames = "q/edit-answer.html"
	self.LayoutSections["Heads"] = "q/head.html"
	self.LayoutSections["Scripts"] = "q/scripts.html"
	flash := beego.NewFlash()

	aid, _ := self.GetInt64(":aid")

	a := &models.Reply{Id: aid}
	if err := a.Read(); err == orm.ErrNoRows {
		flash.Error(fmt.Sprint(err))
		flash.Store(&self.Controller)
		return
	}

	uid, _ := self.GetSession("userid").(int64)
	role, _ := self.GetSession("userrole").(int64)

	if isAllow(a, uid, aid, role) {
		q := &models.Question{Id: a.Pid}
		if err := q.ReadOneOnly("Title", "Content"); err == orm.ErrNoRows {
			flash.Error("对应的问题已删除。")
			flash.Store(&self.Controller)
			return
		}
		self.Data["q"] = *q
		self.Data["a"] = *a
	} else {
		//没有权限执行该操作则直接跳转到登录页面
		self.Redirect("/u/signin/", 302)
	}
}
Example #18
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")
				}
			}
		}
	}

}
Example #19
0
func (c *LoginController) Login() {

	if c.IsLogin {
		c.Ctx.Redirect(302, c.UrlFor("UsersController.Index"))
		return
	}

	c.TplNames = "login/login.tpl"
	c.Data["xsrfdata"] = template.HTML(c.XsrfFormHtml())

	if !c.Ctx.Input.IsPost() {
		return
	}

	flash := beego.NewFlash()
	email := c.GetString("Email")
	password := c.GetString("Password")

	user, err := lib.Authenticate(email, password)
	if err != nil || user.Id < 1 {
		flash.Warning(err.Error())
		flash.Store(&c.Controller)
		return
	}

	flash.Success("Success logged in")
	flash.Store(&c.Controller)

	c.SetLogin(user)

	c.Redirect(c.UrlFor("UsersController.Index"), 303)
}
Example #20
0
// 根据用户名查看用户详细信息
func (this *UserController) GetUserInfo() {
	flash := beego.NewFlash()
	if checkAccountSession(&this.Controller) {
		username := this.Ctx.Input.Param(":username") //user/:username
		user, err := models.GetUserInfo(username)
		if err != nil {
			beego.Error("获取用户信息失败:" + err.Error())
			flash.Error("获取用户信息失败!")
			flash.Store(&this.Controller)
			this.Redirect("/", 302)
			return
		}
		if this.GetSession("user") != nil {
			user := this.GetSession("user").(*models.User) //从Session中获取用户信息
			this.Data["Nickname"] = user.Nickname
			this.Data["Username"] = user.Username
			this.Data["IsLogin"] = true
		}
		this.Data["User"] = user
		this.TplNames = "user.html"
	} else {
		flash.Error("您尚未登录,请登录!")
		flash.Store(&this.Controller)
		this.Redirect("/login", 302) //跳转到登录页
		return
	}

}
Example #21
0
File: user.go Project: grr89/hrkb
//remove user
func (c *User) Remove() {

	s := T("user_not_found")
	d := M.User{}

	id, err := strconv.Atoi(c.Ctx.Input.Param(":id"))

	if err == nil {
		err = DM.DeleteByPk(&d, id)
	}

	if err != nil {
		beego.Error(err)
	} else {
		s = T("user_removed", map[string]interface{}{"Login": d.Login})
	}

	if c.IsAjax() {
		c.Data["json"] = RJson{s, err == nil}
		return
	}

	flash := beego.NewFlash()
	flash.Notice(s)
	flash.Store(&c.Controller)

	c.Redirect(beego.UrlFor("User.Index"), 302)
}
Example #22
0
File: crit.go Project: grr89/hrkb
//remove criteria
func (c *Crit) Remove() {
	s := T("crit_not_found")
	crit := M.Crit{}

	id, err := strconv.Atoi(c.Ctx.Input.Param(":id"))

	if err == nil {
		err = DM.DeleteByPk(&crit, id)
	}

	if err != nil {
		beego.Error(err)
	} else {
		s = T("crit_removed", map[string]interface{}{"Title": crit.Title})
	}

	if c.IsAjax() {
		c.Data["json"] = RJson{s, err == nil}
		return
	}

	flash := beego.NewFlash()
	flash.Notice(s)
	flash.Store(&c.Controller)

	c.Redirect(beego.UrlFor("Crit.Index"), 302)

}
Example #23
0
File: user.go Project: grr89/hrkb
//view concrete user
func (c *User) Get() {

	var u M.User
	var err error

	c.Data["xsrfdata"] = template.HTML(c.XsrfFormHtml())
	c.Data["isEdit"] = true
	c.TplNames = "user/form.tpl"

	id, err := strconv.Atoi(c.Ctx.Input.Param(":id"))

	if err == nil {
		err = DM.FindByPk(&u, id)
	}

	if err != nil {
		flash := beego.NewFlash()
		flash.Notice(T("user_not_found"))
		flash.Store(&c.Controller)
		c.Redirect(beego.UrlFor("User.Index"), 302)
		return
	}

	c.Data["user"] = u
	c.Data["roles"] = c.rolesList()
}
Example #24
0
func (c *ErrorController) Error404() {
	flash := beego.NewFlash()
	flash.Error("Erreur : la page demandée n'est pas accessible")
	flash.Store(&c.Controller)
	c.Data["content"] = "page not found"
	c.Redirect("/", 302)
}
Example #25
0
File: cand.go Project: grr89/hrkb
//edit candidate
func (c *Cand) Edit() {

	flash := beego.NewFlash()
	var deps []M.Dep
	var err error

	if err := DM.FindAll(&M.Dep{}, &deps, M.Sf{}, M.Where{}); err != nil {
		beego.Error("Department find error: ", err)

		flash.Error(T("internal"))
		flash.Store(&c.Controller)

		return
	}
	var id int

	if id, err = strconv.Atoi(c.Ctx.Input.Param(":id")); err != nil {
		beego.Error(err)
	}

	var cand M.Cand

	if DM.FindByPk(&cand, id) != nil {
		flash.Notice(T("nocand"))
		flash.Store(&c.Controller)

		c.Redirect(beego.UrlFor("Cand.Index"), 302)
		return
	}

	c.Data["cand"] = cand
	c.Data["deps"] = deps
	c.Data["xsrfdata"] = template.HTML(c.XsrfFormHtml())
}
Example #26
0
// 用户登录表单提交
func (this *UserController) LoginAction() {
	flash := beego.NewFlash()
	user := &models.User{}
	err := this.ParseForm(user)

	if err != nil {
		beego.Error("用户登录失败:" + err.Error())
		flash.Error("用户登录失败!")
		flash.Store(&this.Controller)
		this.Redirect("/login", 302) //登录失败,重定向到登录页
		return
	}

	user.Password = models.MD5(user.Password) //将密码以MD5加密存储
	captchaCode := this.Input().Get("captcha")

	//判断验证码是否正确
	if !captcha.VerifyString(this.GetSession("captchaStr").(string), captchaCode) {
		flash.Error("验证码不正确!")
		flash.Store(&this.Controller)
		this.DelSession("captchaStr") //从session中清空
		this.Redirect("/login", 302)  //验证码不正确,重定向到登录页
		return
	} else {
		isAutoLogin := this.Input().Get("isAutoLogin") == "on" //是否自动登录

		u := models.Login(user) //成功返回user,失败返回nil

		if u != nil {
			maxAge := 0
			if isAutoLogin {
				maxAge = 72 * 24 * 60
			}
			this.Ctx.SetCookie("username", user.Username, maxAge, "/") //设置cookie
			this.Ctx.SetCookie("password", user.Password, maxAge, "/") //设置cookie

			u.Lastlogin = time.Now().Local() //设置最后登录时间
			u.Loginip = this.Ctx.Input.IP()  //获取客户端IP

			if !models.UserModify(u) { //用户登录成功后更新最后登录时间
				beego.Error("更新用户最后登录时间失败" + err.Error())
				flash.Error("更新用户最后登录时间失败!")
				flash.Store(&this.Controller)
			}

			this.SetSession("user", u) //将用户信息存放到Session中
			flash.Notice("用户" + u.Nickname + "登录成功!")
			flash.Store(&this.Controller)
			this.Redirect("/", 302) //登录成功
			return
		} else {
			flash.Error("用户名或密码不正确!")
			flash.Store(&this.Controller)
			this.Redirect("/login", 302) //登录失败,重定向到登录页
			return
		}
	}

}
Example #27
0
func (self *EditTopicHandler) Post() {
	self.TplNames = "edit-topic.html"
	flash := beego.NewFlash()

	tid, _ := self.GetInt(":tid")
	nid, _ := self.GetInt("nodeid")

	if nd, err := model.GetNode(nid); nd != nil && err == nil {

		uid, _ := self.GetSession("userid").(int64)
		tid_title := self.GetString("title")
		tid_content := self.GetString("content")

		if tid_title != "" && tid_content != "" {

			if tp, err := model.GetTopic(tid); tp != nil && err == nil {

				tp.Title = tid_title
				tp.Uid = uid

				//删去用户没再使用的图片
				helper.DelLostImages(tp.Content, tid_content)
				tp.Content = tid_content

				if s, e := helper.GetBannerThumbnail(tid_content); e == nil {
					tp.Attachment = s
				}

				if cat, err := model.GetCategory(nd.Pid); err == nil {
					tp.Category = cat.Title
				}

				if row, err := model.PutTopic(tid, tp); row == 1 && err == nil {
					model.SetRecordforImageOnEdit(tid, uid)
					self.Redirect("/"+strconv.Itoa(int(tid))+"/", 302)
				} else {

					flash.Error("更新话题出现错误:", fmt.Sprint(err))
					flash.Store(&self.Controller)
					return
				}
			} else {

				flash.Error("无法获取根本不存在的话题!")
				flash.Store(&self.Controller)
				return
			}
		} else {

			flash.Error("话题标题或内容为空!")
			flash.Store(&self.Controller)
			return
		}
	} else {
		flash.Error(fmt.Sprint(err))
		flash.Store(&self.Controller)
		return
	}
}
Example #28
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")
				}
			}
		}
	}
}
Example #29
0
func (c *LoginController) Logout() {
	c.DelLogin()
	flash := beego.NewFlash()
	flash.Success("Success logged out")
	flash.Store(&c.Controller)

	c.Ctx.Redirect(302, c.UrlFor("LoginController.Login"))
}
Example #30
0
// 密码找回Action
func (this *UserController) GetPwdAction() {
	flash := beego.NewFlash()
	username := this.GetString("username")      //获取用户名
	mail := this.GetString("email")             //获取电子邮件
	if models.CheckUserExists(username, mail) { //根据用户名和电子邮件验证用户是否存在

		var uid, exprise string

		//计算24小时后的时间并格式化
		exprise = time.Now().Local().Add(time.Hour * 24).Format("2006-01-02 15:04:05") //24小时后

		uid = uuid.New() //生成一个uuid标识串

		url := "http://127.0.0.1:8081/modifypwd?username="******"&uuid=" + uid

		content := "<strong>亲爱的" + username + ":</strong><p>系统检测到你的找回密码请求,请点击该链接或拷贝到浏览器以继续。24小时内有效!<a href=\"" + url + "\" target=\"_blank\">" + url + "</a></p>"

		user := &models.User{
			Username: username,
			Email:    mail,
			Uuid:     uid,
			Exprise:  exprise,
		}

		if models.UpdateUser(user) { //更新uuid和密码找回失效时间到数据库中
			//用户存在,发取回密码的邮件
			e := &email.Email{
				To:      []string{mail},
				From:    "*****@*****.**",
				Subject: "找回密码,24小时内有效",
				HTML:    []byte(content),
				Headers: textproto.MIMEHeader{},
			}
			err := e.Send("smtp.163.com:25", smtp.PlainAuth("", "username", "******", "smtp.163.com")) //应用环境中需要替换username和password为有效的值
			if err != nil {
				beego.Error("邮件发送失败:" + err.Error())
				flash.Error("邮件发送失败,请稍后再试!")
				flash.Store(&this.Controller)
				this.Redirect("/getpwd", 302) //重定向到密码找回页
			} else {
				flash.Notice("密码找回邮件已发送,请到邮箱中查看!")
				flash.Store(&this.Controller)
				this.Redirect("/getpwd", 302) //重定向到密码找回页
			}
		} else {
			flash.Error("请求失败!")
			flash.Store(&this.Controller)
			this.Redirect("/getpwd", 302) //重定向到密码找回页
			return
		}

	} else {
		flash.Error("该用户不存在!")
		flash.Store(&this.Controller)
		this.Redirect("/getpwd", 302) //重定向到密码找回页
		return
	}
}