Example #1
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 #2
0
func (this *AdminController) GetUser() {

	flash := beego.ReadFromRequest(&this.Controller)
	if _, ok := flash.Data["notice"]; ok {
	}

	badgeCount(this)

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

	var users []*models.User

	qs := o.QueryTable("User")
	num, err := qs.OrderBy("-id").All(&users)

	if err != orm.ErrNoRows && num > 0 {
		this.Data["users"] = users

	} else {
		flash.Error("Aucun Utilisateur dans la Base de données")
		flash.Store(&this.Controller)
		this.Redirect("/incident-manager/admin/user", 302)
	}

	Template(this, "admin", "user", "Tous les Utilisateurs")
}
Example #3
0
// 用户注册页
func (this *UserController) Register() {

	beego.ReadFromRequest(&this.Controller)
	this.Data["Title"] = "用户注册"
	this.TplNames = "register.html"

}
Example #4
0
func (this *AdminController) GetIncident() {

	if this.GetSession("role") != "admin" {
		this.Redirect("/incident-manager", 302)
	}

	flash := beego.ReadFromRequest(&this.Controller)
	if _, ok := flash.Data["notice"]; ok {
	}

	badgeCount(this)

	r := this.Ctx.Input
	fmt.Println("Administrateur avec comme IP : " + r.IP())

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

	var incidents []*models.Incident

	num, err := o.QueryTable("Incident").OrderBy("-id").RelatedSel().All(&incidents)

	if err != orm.ErrNoRows && num > 0 {
		this.TplNames = "index/index.tpl"
		this.Data["incidents"] = incidents
	} else {
		// No result
		flash.Error("Aucun Incident dans la Base de données")
		flash.Store(&this.Controller)
	}

	Template(this, "index", "index", "Liste incidents")

}
Example #5
0
func (this *AdminController) RegisterDemand() {

	flash := beego.ReadFromRequest(&this.Controller)
	if _, ok := flash.Data["notice"]; ok {
	}

	badgeCount(this)

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

	var demand []*models.Register

	num, err := o.QueryTable("Register").OrderBy("-id").RelatedSel().All(&demand)

	if err != orm.ErrNoRows && num > 0 {
		this.TplNames = "admin/register.tpl"
		this.Data["demand"] = demand

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

	Template(this, "admin", "register", "Demande de connexion")
}
Example #6
0
// 首页
func (this *HomeController) Get() {

	beego.ReadFromRequest(&this.Controller) //解析flash数据

	checkAccountSession(&this.Controller)

	this.Data["IsHome"] = true

	qs := models.QuerySeter("topic") //获取orm.QuerySeter

	// 可以在此处加上查询过滤条件

	// qs = qs.Filter("category", "git")

	count, _ := models.CountObjects(qs) //查询总记录数

	pager := this.SetPaginator(10, count) //设置分页信息页大小、总记录数

	qs = qs. /*Filter("category", "git").*/ OrderBy("-created").Limit(10, pager.Offset()).RelatedSel() //执行分页

	//var topics []models.Topic 声明一个slice 使用此方式声明的slice在使用的时候若需要取指针的地址需要加取地址&运算符

	topics := new([]models.Topic) //该方式创建的topics已经指向指针的地址了,使用该指针的地址时,不需要再加取地址运算符

	models.ListObjects(qs, topics) //查询结果带分页

	categories := models.GetAllCategory() //查询所有的分类

	this.Data["Topics"] = topics
	this.Data["Categories"] = categories

	this.TplNames = "index.html"
}
Example #7
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 #8
0
func (this *MainController) Get() {
	u := this.GetSession("user")
	if u != nil {
		usr, ok := u.(m.User)
		if ok && usr.UserName != "" {
			this.Data[INFO] = SUCCESS
			this.Data["user"] = usr
		} else {
			this.Data[INFO] = DEFAULT
		}
	} else {
		this.Data[INFO] = DEFAULT
	}

	datas, err := m.GetKindsList()

	if err != nil {
	}
	this.Data["kinds"] = datas
	this.Data["status"] = 0

	flash := beego.ReadFromRequest(&this.Controller)
	if n, ok := flash.Data["notice"]; ok {
		this.Data["status"], _ = strconv.Atoi(n)
	}

	this.TplNames = "index.html"
}
Example #9
0
func (manage *ManageController) View() {
	manage.Layout = "basic-layout.tpl"
	manage.LayoutSections = make(map[string]string)
	manage.LayoutSections["Header"] = "header.tpl"
	manage.LayoutSections["Footer"] = "footer.tpl"
	manage.TplNames = "manage/view.tpl"

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

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

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

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

	var articles []*models.Article
	num, err := o.QueryTable("articles").All(&articles)

	if err != orm.ErrNoRows && num > 0 {
		manage.Data["records"] = articles
	}
}
Example #10
0
func (this *BaseController) Prepare() {
	this.controllerName, this.actionName = this.GetControllerAndAction()
	this.userSession()
	this.flash = beego.ReadFromRequest(&this.Controller)

	// load configuration
	helpers.LoadConf()
	models.LoadAndSetConfig()

	this.Data["PageStartTime"] = time.Now()
	this.Data["AppName"] = helpers.AppName
	this.Data["AppDescription"] = helpers.AppDescription
	this.Data["AppKeywords"] = helpers.AppKeywords
	this.Data["AppAuthor"] = helpers.AppAuthor

	// default layout
	this.Layout = helpers.DefaultLayout

	// filter users
	if app, ok := this.AppController.(AuthPreparer); ok {
		app.AuthPrepare()
	}

	if app, ok := this.AppController.(NestPreparer); ok {
		app.NestPrepare()
	}
}
Example #11
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 #12
0
func (this *MainController) Notice() {
	this.activeContent("notice")

	flash := beego.ReadFromRequest(&this.Controller)
	if n, ok := flash.Data["notice"]; ok {
		this.Data["notice"] = n
	}
}
Example #13
0
func (c *ListController) Get() {
	flash := beego.ReadFromRequest(&c.Controller)

	if _, err := os.Stat(exepath + "/.config.json"); err != nil {
		fmt.Println("erreur Il n'y a pas de config.json")
		c.DestroySession()
	}

	go func() {
		t := models.ListFolder{}
		t.Folder = listFolder(Root)
		WriteJson(t, exepath, "listFolder")
	}()

	if _, ok := flash.Data["notice"]; ok {
	}
	if _, ok := flash.Data["error"]; ok {
	}
	if _, ok := flash.Data["success"]; ok {
	}
	if _, ok := flash.Data["warning"]; ok {
	}
	v := c.GetSession("raspDlna")
	if v == nil {
		c.SetSession("raspDlnaID", int(1))
		c.Data["num"] = 0

	} else {
		c.SetSession("raspDlnaID", v.(int)+1)
		c.Data["num"] = v.(int)
	}

	file := filepath.Clean(c.Ctx.Input.Param(":dir"))

	d, _ := Emplacement(Root, file)
	l := List(d)

	c.Data["title"] = strings.Title("liste")
	c.Data["href"] = "/" + file
	c.Data["back"] = path.Dir(file)

	c.Data["chemin"] = breadcrumb(file)

	user, group := MapUidGid()
	c.Data["user"] = user
	c.Data["group"] = group

	sd := SpaceDisk()
	reg, _ := regexp.Compile("[^A-Za-z0-9/-]+")
	sd1 := strings.Split(reg.ReplaceAllString(sd[1], " "), " ")
	c.Data["spacedisk"] = sd1

	c.Data["nonLues"], c.Data["numNonLues"] = Nonlues(Root)
	c.Data["dirname"] = l
	c.Layout = "index.tpl"
	c.TplNames = "list.tpl"

}
Example #14
0
func (b *Base) Prepare() {
	b.Data[`moreStyles`] = &more{}
	b.Data[`beforeScripts`] = &more{}
	b.Data[`laterScripts`] = &more{}
	b.Data["position"] = ``
	b.Data[`title`] = ""
	beego.ReadFromRequest(&b.Controller)

}
Example #15
0
func (this *MainController) Login() {
	log.Println("MainController IsLoggedIn", this.IsLoggedIn)
	if this.IsLoggedIn {
		url := utils.U("home")
		this.Redirect(url, 302)
	} else {
		flash := beego.ReadFromRequest(&this.Controller)
		this.Data["flash"] = flash.Data
		this.TplNames = "oa/index.tpl"
	}
}
Example #16
0
// 密码找回修改密码页
func (this *UserController) ModifyPWD() {

	beego.ReadFromRequest(&this.Controller) //从Request中解析flash数据
	flash := beego.NewFlash()
	username := this.GetString("username")
	uid := this.GetString("uuid")
	if username == "" || uid == "" {

		flash.Error("非法的请求!")
		flash.Store(&this.Controller)

	} else {

		user := &models.User{
			Username: username,
			Uuid:     uid,
		}

		//检查是否非法请求

		u := models.QueryUserByUsernameAndUUID(username, uid) //根据uuid和用户名查询用户信息

		if u != nil {

			exprise := u.Exprise //获取过期时间

			nowtime := time.Now().Local() //获取当前时间

			exprisetime, err := time.Parse("2006-01-02 15:04:05", exprise) //时间字符串转化

			if err != nil {
				beego.Error("解析时间失败:" + err.Error())
			}

			//判断链接是否有效

			if nowtime.After(exprisetime) { //判断当前时间是否在失效时间之后 为true表示连接已失效
				flash.Error("该请求已失效!")
				flash.Store(&this.Controller)
			}

			this.Data["User"] = user

		} else {
			flash.Error("非法的请求!")
			flash.Store(&this.Controller)
		}

	}
	this.Data["Title"] = "密码重置"
	this.TplNames = "modify_pwd.html"
	return
}
Example #17
0
func (self *Settings) Get() {

	self.TplNames = "settings.html"
	beego.ReadFromRequest(&self.Controller)

	sess_userid, _ := self.GetSession("userid").(int64)

	if usr, err := model.GetUser(sess_userid); usr != nil && err == nil {
		self.Data["usr"] = *usr
		return
	}
}
Example #18
0
// @router /addUser [get]
func (this *MainController) AddUser() {
	flash := beego.ReadFromRequest(&this.Controller)
	if _, ok := flash.Data["notice"]; ok {
		//显示设置成功
		this.TplNames = "addUser.html"
	} else if _, ok = flash.Data["error"]; ok {
		//显示错误
		this.TplNames = "addUser.html"
	} else {
		// 不然默认显示设置页面
		this.TplNames = "addUser.html"
	}

}
Example #19
0
// user login
func (this *UserController) Login() {
	flash := beego.ReadFromRequest(&this.Controller)
	username := this.Input().Get("userName")
	password := this.Input().Get("password")

	if user := m.ValidateUser(username, password); user.UserName != "" {
		this.SetSession("user", user)
		this.Redirect("/", 302)
	} else {
		this.Data[INFO] = FAILED
		flash.Store(&this.Controller)
		flash.Notice("1")
		flash.Store(&this.Controller)
		this.Redirect("/", 302)
	}
}
Example #20
0
func (this *BaseController) Prepare() {
	if setting.ConfigBroken {
		this.Abort("500")
	}
	this.checkDeny()

	// page start time
	this.Data["PageStartTime"] = time.Now()
	this.Data["AppName"] = setting.AppName
	this.Data["AppVer"] = setting.AppVer
	this.Data["PageTitle"] = setting.AppName

	// start session
	this.StartSession()
	//从session中读取登录信息
	switch {
	// save logined user if exist in session
	case this.loginViaSession():
		this.IsLogin = true
	// save logined user if exist in remember cookie
	case this.loginViaRememberCookie():
		this.IsLogin = true
	}

	if this.IsLogin {
		this.Data["User"] = &this.User
		this.Data["IsLogin"] = this.IsLogin

		// if user forbided then do logout
		if this.User.IsBanned {
			this.LogUserOut()
			this.FlashWrite("error", "您的帐号被禁用,无法为您登录!")
			this.Redirect("/login", 302)
			return
		}
	}

	// read flash message
	beego.ReadFromRequest(&this.Controller)

	//检查once token,防止表单多次提交
	if this.Ctx.Request.Method == "POST" || this.Ctx.Request.Method == "DELETE" || this.Ctx.Request.Method == "PUT" ||
		(this.Ctx.Request.Method == "POST" && (this.Ctx.Request.Form.Get("_method") == "delete" || this.Ctx.Request.Form.Get("_method") == "put")) {
		this.CheckOnceToken()
	}

}
Example #21
0
// 跳转到新增页面
func (this *TopicController) Add() {

	beego.ReadFromRequest(&this.Controller)

	flash := beego.NewFlash()

	if checkAccountSession(&this.Controller) { //验证用户是否已登录
		this.Data["IsTopic"] = true
		this.Data["Title"] = "添加文章"
		this.TplNames = "add_topic.html"
		return
	} else {
		flash.Error("您尚未登录,请登录!")
		flash.Store(&this.Controller)
		this.Redirect("/login", 302) //跳转到登录页
		return
	}
}
Example #22
0
func (manage *ManageController) View() {
	flash := beego.ReadFromRequest(&manage.Controller)
	manage.TplNames = "view.tpl"

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

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

	var articles []*models.Article
	num, err := o.QueryTable("Article").All(&articles)

	if err != orm.ErrNoRows && num > 0 {
		manage.Data["records"] = articles
	}
}
Example #23
0
func (this *Usercontroller) Add() {

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

	//mensajes
	flash := beego.ReadFromRequest(&this.Controller)

	usuarios := models.Usuarios{}
	err := this.ParseForm(&usuarios)
	if err != nil {
		beego.Error("No se pudo obtener datos: ", err)
	} else if this.Ctx.Input.Method() == "POST" {
		//verificamos si usuario existe
		user := this.Ctx.Request.FormValue("Usuario")
		exist := o.QueryTable("Usuarios").Filter("Usuario", user).Exist()

		if !exist {

			//insertamos datos
			id, err := o.Insert(&usuarios)
			flash.Store(&this.Controller)
			if err == nil {
				msg := Sprintf("Usuario insertado id: %d", id)
				beego.Debug(msg)
				flash.Notice(msg)

			} else {
				msg := Sprintf("No se pudo crear nuevo usuario. Por: ", err)
				beego.Debug(msg)
				flash.Error(msg)
			}

		} else {
			msg := Sprint("  !! El usuario YA existe !!")
			beego.Debug(msg)
			flash.Error(msg)
		}
	}

}
Example #24
0
//帖子内容
func (this *ContentsList) Get() {
	id, _ := this.GetInt("id")
	bbs, err := m.GetBBSById(id)
	if err != nil {
	}
	responses, count, err := m.GetResByBBSId(bbs.BBSId)
	if err != nil {
	}

	flash := beego.ReadFromRequest(&this.Controller)
	if n, ok := flash.Data["notice"]; ok {
		this.Data["show"], _ = strconv.Atoi(n)
	}

	this.Data["responses"] = responses
	this.Data["bbs"] = bbs
	this.Data["id"] = id
	this.Data["count"] = count
	//this.Data[INFO] = SUCCESS
	this.TplNames = "pageContents.html"
}
Example #25
0
// 登录
func (this *MainController) Login() {
	if this.userId > 0 {
		this.redirect("/")
	}
	beego.ReadFromRequest(&this.Controller)
	if this.isPost() {
		flash := beego.NewFlash()

		username := strings.TrimSpace(this.GetString("username"))
		password := strings.TrimSpace(this.GetString("password"))
		remember := this.GetString("remember")
		if username != "" && password != "" {
			user, err := models.UserGetByName(username)
			errorMsg := ""
			if err != nil || user.Password != libs.Md5([]byte(password+user.Salt)) {
				errorMsg = "帐号或密码错误"
			} else if user.Status == -1 {
				errorMsg = "该帐号已禁用"
			} else {
				user.LastIp = this.getClientIp()
				user.LastLogin = time.Now().Unix()
				models.UserUpdate(user)

				authkey := libs.Md5([]byte(this.getClientIp() + "|" + user.Password + user.Salt))
				if remember == "yes" {
					this.Ctx.SetCookie("auth", strconv.Itoa(user.Id)+"|"+authkey, 7*86400)
				} else {
					this.Ctx.SetCookie("auth", strconv.Itoa(user.Id)+"|"+authkey)
				}

				this.redirect(beego.URLFor("TaskController.List"))
			}
			flash.Error(errorMsg)
			flash.Store(&this.Controller)
			this.redirect(beego.URLFor("MainController.Login"))
		}
	}

	this.TplName = "main/login.html"
}
Example #26
0
// 修改文章页面
func (this *TopicController) ModifyTopic() {

	beego.ReadFromRequest(&this.Controller)
	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("获取文章id失败!")
			flash.Store(&this.Controller)
			return
		}
		topic := models.ViewTopicById(id)
		this.Data["Topic"] = topic
		this.TplNames = "modify_topic.html"
	} else {
		flash.Error("您尚未登录,请登录!")
		flash.Store(&this.Controller)
		this.Redirect("/login", 302) //跳转到登录页
		return
	}
}
Example #27
0
// 根据文章id查看文章
func (this *TopicController) ViewTopic() {

	beego.ReadFromRequest(&this.Controller)
	flash := beego.NewFlash()

	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["IsTopic"] = true
	}
	id, err := strconv.ParseInt(this.Ctx.Input.Param(":id"), 10, 64)
	if err != nil {
		beego.Error("获取文章id失败" + err.Error())
		flash.Error("获取文章id失败!")
		flash.Store(&this.Controller)
		return
	}
	topic := models.ViewTopicById(id)
	this.Data["Topic"] = topic
	this.TplNames = "view_topic.html"
}
Example #28
0
func (this *IndexController) Get() {
	flash := beego.ReadFromRequest(&this.Controller)
	if _, ok := flash.Data["notice"]; ok {
	}
	v := this.GetSession("IncidentManager")
	if v == nil {
		this.SetSession("IncidentID", int(1))
		this.Data["num"] = 0

	} else {
		this.SetSession("IncidentID", v.(int)+1)
		this.Data["num"] = v.(int)
	}

	r := this.Ctx.Input
	fmt.Println("Utilisateur avec comme IP : " + r.IP())

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

	var incidents []*models.Incident

	num, err := o.QueryTable("Incident").OrderBy("-id").RelatedSel().All(&incidents)

	if err != orm.ErrNoRows && num > 0 {
		this.TplNames = "index/index.tpl"
		this.Data["incidents"] = incidents

	} else {
		// No result
		flash.Error("Aucun incident dans la base de données")
		flash.Store(&this.Controller)
	}

	Template(this, "index", "index.tpl", "Liste incidents")

}
Example #29
0
func (this *LaunchController) Post() {

	sess := this.GetSession("acme")
	if sess == nil {
		this.Redirect("/user/login/home", 302)
		return
	}
	m := sess.(map[string]interface{})
	username, _ := m["username"].(string)
	username = strings.ToLower(username)

	this.activeContent("appLaunch")
	fmt.Println("app launch started")
	numbertolaunch, _ := strconv.Atoi(this.GetString("launchNumber"))

	file := this.GetString("filelist")

	for i := 0; i < numbertolaunch; i++ {

		//Read File for launching
		podfile, err := ioutil.ReadFile("./restcalls/" + file)

		if err != nil {
			panic(err)
		}

		chararactersToGenerate := 8
		set := gostrgen.Lower | gostrgen.Digit
		include := ""   // optionally include some additional letters
		exclude := "Ol" //exclude big 'O' and small 'l' to avoid confusion with zero and one.

		randomstring, err := gostrgen.RandGen(chararactersToGenerate, set, include, exclude)
		if err != nil {
			fmt.Println(err)
		}

		//append username into JSON FILE

		var newstring string = ""
		var usernamestring = username + "-" + randomstring

		JSONSPLIT := strings.Split(string(podfile), "#USERNAME")
		newstring = newstring + JSONSPLIT[0] + usernamestring + JSONSPLIT[1] + usernamestring + JSONSPLIT[2]

		fmt.Println(newstring)

		//Create the request
		url := "http://" + os.Getenv("MARATHON_ENDPOINT") + "/v2/apps/"
		bytestring := []byte(newstring)
		req, err := http.NewRequest("POST", url, bytes.NewBuffer(bytestring))

		//Make the request
		res, err := http.DefaultClient.Do(req)

		if err != nil {
			panic(err) //Something is wrong while sending request
		}

		if res.StatusCode != 201 {
			fmt.Printf("Success expected: %d", res.StatusCode) //Uh-oh this means our test failed
		}

		this.Data["Launching"] = "Launching successful! Redirecting in 2s ..."
		time.Sleep(5 * time.Second)
		this.Redirect("/user/apps", 302)

	}
	flash := beego.ReadFromRequest(&this.Controller)
	if n, ok := flash.Data["notice"]; ok {
		this.Data["notice"] = n
	}
}
Example #30
0
func (this *LoginController) Login() {
	flash := beego.ReadFromRequest(&this.Controller)
	if _, ok := flash.Data["notice"]; ok {
	}

	this.Ctx.Request.ParseForm()
	username := this.Ctx.Request.Form.Get("username")
	password := this.Ctx.Request.Form.Get("password")

	newPass := admin.Md5Pass(password)

	fmt.Println(username, newPass)

	if this.Ctx.Input.Method() == "POST" {
		o := orm.NewOrm()
		o.Using("default")

		var users []*models.User

		qs := o.QueryTable("user")
		err := qs.Filter("mail__iexact", username).Filter("pass__iexact", newPass).One(&users)
		if err == orm.ErrNoRows {
			// No result
			flash := beego.NewFlash()
			flash.Error("Vérifie tes informations car apparemment elles ne sont pas bonnes.")
			flash.Store(&this.Controller)
		} else {
			v := this.GetSession("IncidentManager")
			if v == nil {
				this.SetSession("IncidentID", int(1))
				for _, data := range users {
					this.SetSession("uid", data.Id)
					this.SetSession("mail", data.Mail)
					this.SetSession("role", data.Role)
				}
				this.Data["num"] = 0

			} else {
				this.SetSession("IncidentID", v.(int)+1)
				this.Data["num"] = v.(int)
			}
			flash := beego.NewFlash()

			flash.Notice("Bienvenue : " + username)
			flash.Store(&this.Controller)
			if this.GetSession("role") == "admin" {
				this.Redirect("/incident-manager/admin", 302)
			} else if this.GetSession("role") == "user" {
				this.Redirect("/incident-manager", 302)
			}

		}

	}

	this.Layout = "layout.tpl"
	this.TplNames = "login.tpl"
	this.Data["title2"] = "Se connecter"
	this.Data["role"] = this.GetSession("role")
	this.Data["mail"] = this.GetSession("mail")
	this.LayoutSections = make(map[string]string)
	this.LayoutSections["navbar"] = "index/navbar.tpl"
	this.LayoutSections["footer"] = "index/footer.tpl"

}