Example #1
0
func RenderRegisterForm(ctx *gin.Context, result *RegisterResult, user *SiteUser) {
	tplData := gin.H{
		"title":          "Automata Theory - Lab 1, form validation",
		"alertMessage":   "",
		"showAlertName":  false,
		"showAlertEmail": false,
		"nickname":       "",
		"email":          "",
	}

	if result != nil && result.status != UserValid {
		tplData["alertMessage"] = result.message
		switch result.status {
		case UserInvalidNickname:
			tplData["showAlertName"] = true
		case UserInvalidEmail:
			tplData["showAlertEmail"] = true
		case UserWeakPassword:
			tplData["showAlertPassword"] = true
		case UserPasswordMismatch:
			tplData["showAlertPassword"] = true
		}
	}

	if user != nil {
		tplData["nickname"] = user.nickname
		tplData["email"] = user.email
	}

	ctx.HTML(http.StatusOK, "reg-form.tpl", tplData)
}
Example #2
0
func HomeR(c *gin.Context) {
	// dependency injection
	var (
		whiskyStore = c.MustGet(WhiskyStoreKey).(WhiskyStore)
		reviewStore = c.MustGet(ReviewStoreKey).(ReviewStore)
		user        = GetUser(c)
	)

	// temporary variables
	var (
		activity []Review
		trending []Whisky
		err      error
	)

	// get activity stream for user
	activity, err = reviewStore.GetActivity(user.ID, LIMIT)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	// get trending whiskies
	trending, err = whiskyStore.GetTrending(LIMIT)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	c.HTML(http.StatusOK, "home.html", gin.H{
		"User":     user,
		"Activity": activity,
		"Trending": trending,
	})
}
Example #3
0
func (pc *NodeController) postNodeAction(c *gin.Context) {

	id := c.Param("id")

	var form models.NodeUpdateForm
	if err := c.Bind(&form); err != nil {
		c.AbortWithStatus(http.StatusBadRequest)
		return
	}

	node, err := models.NodeMapper.FetchOneById(id)
	if err != nil {
		c.HTML(http.StatusInternalServerError, "error_500.html", map[string]interface{}{
			"error": err,
		})
		return
	}

	if node == nil {
		c.HTML(http.StatusNotFound, "error_404.html", map[string]interface{}{
			"text": "Node not found",
		})
		return
	}

	node.Tags = form.Tags
	node.Description = form.Description
	models.NodeMapper.Update(node)

	c.Redirect(http.StatusFound, "/nodes")
}
Example #4
0
func EditWhiskyFormR(c *gin.Context) {
	// dependency injection
	var (
		whiskyStore = c.MustGet(WhiskyStoreKey).(WhiskyStore)
		user        = GetUser(c)
	)

	// only authenticated users can perform this action
	if !user.Authenticated() {
		c.AbortWithStatus(http.StatusUnauthorized)
		return
	}

	// fetch whisky to edit
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.AbortWithStatus(http.StatusBadRequest)
		return
	}

	whisky, err := whiskyStore.GetWhisky(id)
	if err != nil {
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}

	c.HTML(http.StatusOK, "whisky-form.html", gin.H{
		"Action": "Edit",
		"User":   user,
		"Form":   whisky,
		"Errors": map[string]string{},
	})
}
Example #5
0
func UserR(c *gin.Context) {
	// dependency injection
	var (
		whiskyStore = c.MustGet(WhiskyStoreKey).(WhiskyStore)
		reviewStore = c.MustGet(ReviewStoreKey).(ReviewStore)
		user        = GetUser(c)
	)

	// parse id
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.AbortWithError(http.StatusBadRequest, err)
		return
	}

	// fetch whiksy
	whisky, err := whiskyStore.GetWhisky(id)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	// fetch reviews
	reviews, err := reviewStore.GetAllReviews(id, 30)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	c.HTML(http.StatusOK, "whisky.html", gin.H{
		"User":    user,
		"Whisky":  whisky,
		"Reviews": reviews,
	})
}
Example #6
0
func (self *EnvController) New(c *gin.Context) {
	username := self.CurrentUser(c)

	if username == "" {
		c.Redirect(http.StatusFound, "/")

		return
	}

	appName := c.Param("appName")
	key := c.PostForm("key")
	value := c.PostForm("value")

	err := env.Create(self.etcd, username, appName, key, value)

	if err != nil {
		fmt.Fprintf(os.Stderr, "%+v\n", err)

		c.HTML(http.StatusInternalServerError, "app.tmpl", gin.H{
			"alert":   true,
			"error":   true,
			"message": "Failed to add environment variable.",
		})

		return
	}

	c.Redirect(http.StatusSeeOther, "/apps/"+appName)
}
func (fc *FrontController) HomeCtr(c *gin.Context) {
	page, err := strconv.Atoi(c.DefaultQuery("page", "1"))
	if err != nil {
		log.Fatal(err)
	}
	page -= 1
	if page < 0 {
		page = 0
	}

	prev_page := page
	if prev_page < 1 {
		prev_page = 1
	}
	next_page := page + 2

	rpp := 20
	offset := page * rpp
	CKey := fmt.Sprintf("home-page-%d-rpp-%d", page, rpp)
	var blogList string
	val, ok := Cache.Get(CKey)
	if val != nil && ok == true {
		fmt.Println("Ok, we found cache, Cache Len: ", Cache.Len())
		blogList = val.(string)
	} else {
		rows, err := DB.Query("Select aid, title from top_article where publish_status = 1 order by aid desc limit ? offset ? ", &rpp, &offset)
		if err != nil {
			log.Fatal(err)
		}
		defer rows.Close()
		var (
			aid   int
			title sql.NullString
		)
		for rows.Next() {
			err := rows.Scan(&aid, &title)
			if err != nil {
				log.Fatal(err)
			}
			blogList += fmt.Sprintf(
				"<li><a href=\"/view/%d\">%s</a></li>",
				aid,
				title.String,
			)
		}
		err = rows.Err()
		if err != nil {
			log.Fatal(err)
		}
		Cache.Add(CKey, blogList)
	}
	session := sessions.Default(c)
	username := session.Get("username")
	c.HTML(http.StatusOK, "index.html", gin.H{
		"bloglist":  template.HTML(blogList),
		"username":  username,
		"prev_page": prev_page,
		"next_page": next_page,
	})
}
Example #8
0
// Login is a page with a login form and an alternative to the login API,
// this route handles both GET and POST requests.
func Login(c *gin.Context) {
	session := sessions.Default(c)
	defer session.Save()

	// returnURL can come from GET or POST or use default.
	returnURL := c.DefaultQuery("return_url", c.DefaultPostForm("return_url", "/"))

	if c.Request.Method == "POST" {
		var schema LoginSchema
		if c.Bind(&schema) == nil {
			// Fetch the user matching this username.
			user := GetUserByUsername(schema.Username)

			// If the user exists, the ID is > 0, check the password.
			if user.ID > 0 && user.CheckPassword(schema.Password) {
				session.Set("userID", user.ID)
				c.Redirect(http.StatusFound, returnURL)
				return
			}
			session.AddFlash("Invalid username or password")
		}
	}

	c.HTML(200, "login.html", pongo2.Context{
		"title":      "Login",
		"messages":   session.Flashes(),
		"csrf_token": nosurf.Token(c.Request),
		"return_url": returnURL,
	})
}
Example #9
0
func (c *Convergence) viewPage(ctx *gin.Context) {
	key := ctx.Param("key")
	title := ctx.Param("title")

	var err error
	var page *Page

	if _, err := strconv.Atoi(title); err == nil {
		page, err = c.Confluence.GetPageByID(key, title)
		if err != nil {
			c.showError(ctx, err)
			return
		}
	}

	if page == nil {
		page, err = c.Confluence.GetPageByTitle(key, title)
		if err != nil {
			c.showError(ctx, err)
			return
		}
	}

	ctx.HTML(http.StatusOK, "page.html", gin.H{
		"Title": page.Title,
		"Body":  c.processBody(page.Body, key),
		"Index": key,
	})
}
Example #10
0
func postRoute(c *gin.Context) {
	key := c.Params.ByName("key")

	if len(key) < 2 {
		four04(c, "Invalid Post")
		return
	}

	key = key[1:]

	var ps []Itm
	r := Items().Find(bson.M{"key": key}).Sort("-date").Limit(1)
	r.All(&ps)

	if len(ps) == 0 {
		four04(c, "Post not found")
		return
	}

	var posts []Itm
	results := Items().Find(bson.M{"date": bson.M{"$lte": ps[0].Date}}).Sort("-date").Limit(20)
	results.All(&posts)

	obj := gin.H{"title": ps[0].Title, "posts": posts, "channels": AllChannels()}

	c.HTML(200, "full.html", obj)
}
Example #11
0
func channelRoute(c *gin.Context) {
	key := c.Params.ByName("key")
	if len(key) < 2 {
		four04(c, "Channel Not Found")
		return
	}

	key = key[1:]

	fmt.Println(key)

	var posts []Itm
	results := Items().Find(bson.M{"channelkey": key}).Sort("-date").Limit(20)
	results.All(&posts)

	if len(posts) == 0 {
		four04(c, "No Articles")
		return
	}

	var currentChannel Chnl
	err := Channels().Find(bson.M{"key": key}).One(&currentChannel)
	if err != nil {
		if string(err.Error()) == "not found" {
			four04(c, "Channel not found")
			return
		} else {
			fmt.Println(err)
		}
	}

	obj := gin.H{"title": currentChannel.Title, "header": currentChannel.Title, "posts": posts, "channels": AllChannels()}

	c.HTML(200, "full.html", obj)
}
Example #12
0
func (self *AppController) New(c *gin.Context) {
	username := self.CurrentUser(c)

	if username == "" {
		c.Redirect(http.StatusFound, "/")

		return
	}

	appName := c.PostForm("appName")

	err := app.Create(self.etcd, username, appName)

	if err != nil {
		fmt.Fprintf(os.Stderr, "%+v\n", err)

		c.HTML(http.StatusInternalServerError, "apps.tmpl", gin.H{
			"alert":   true,
			"error":   true,
			"message": "Failed to create app.",
		})

		return
	}

	c.Redirect(http.StatusSeeOther, "/apps/"+appName)
}
Example #13
0
// frontpage when no routes are possible.
func Index(c *gin.Context) {
	// this is how gin API renders
	// response.  c.HTML will render
	// go template for us.
	// gin.H is a shorthand for map[string]interface{}
	c.HTML(200, "index.html", gin.H{})
}
Example #14
0
func ShowIndex(c *gin.Context) {
	user := session.User(c)
	if user == nil {
		c.Redirect(http.StatusSeeOther, "/login")
		return
	}

	// get the repository list from the cache
	repos, err := cache.GetRepos(c, user)
	if err != nil {
		c.String(400, err.Error())
		return
	}

	// filter to only show the currently active ones
	activeRepos, err := store.GetRepoListOf(c, repos)
	if err != nil {
		c.String(400, err.Error())
		return
	}

	c.HTML(200, "index.html", gin.H{
		"User":  user,
		"Repos": activeRepos,
	})
}
Example #15
0
func searchRoute(c *gin.Context) {
	q := c.Params.ByName("query")
	if len(q) < 2 {
		four04(c, "Query is too short. Please try a longer query.")
		return
	}

	q = q[1:]

	channels := AllChannels()

	var posts []Itm
	// TODO need to send a PR to Gustavo with support for textscore sorting
	results := Items().Find(bson.M{"$text": bson.M{"$search": q}}).Skip(Offset(c)).Limit(pLimit)

	results.All(&posts)

	if len(posts) == 0 {
		four04(c, "No Articles for query '"+q+"'")
		return
	}

	obj := gin.H{"title": q, "header": q, "items": posts, "posts": posts, "channels": channels}

	if strings.ToLower(c.Request.Header.Get("X-Requested-With")) == "xmlhttprequest" {
		c.HTML(200, "items.html", obj)
	} else {
		c.HTML(200, "full.html", obj)
	}
}
Example #16
0
func GetAdminNewsEdit(c *gin.Context) {
	nw := News{}
	i, _ := strconv.Atoi(c.Param("kkk"))
	NewsSession.Find(gin.H{"id": i}).One(&nw)
	fmt.Println(nw.Short, nw.Id)
	c.HTML(200, "editn.html", gin.H{"news": nw})
}
Example #17
0
func ShowRepo(c *gin.Context) {
	user := session.User(c)
	repo := session.Repo(c)

	builds, _ := store.GetBuildList(c, repo)
	groups := []*model.BuildGroup{}

	var curr *model.BuildGroup
	for _, build := range builds {
		date := time.Unix(build.Created, 0).Format("Jan 2 2006")
		if curr == nil || curr.Date != date {
			curr = &model.BuildGroup{}
			curr.Date = date
			groups = append(groups, curr)
		}
		curr.Builds = append(curr.Builds, build)
	}

	httputil.SetCookie(c.Writer, c.Request, "user_last", repo.FullName)

	c.HTML(200, "repo.html", gin.H{
		"User":   user,
		"Repo":   repo,
		"Builds": builds,
		"Groups": groups,
	})

}
Example #18
0
func UserLogin(c *gin.Context) {
	var cookie middleware.CookieManager
	cookie = c.MustGet("CM").(middleware.CookieManager)
	if c.Request.Method == "GET" {
		data := tool.GetTD(c)

		fmt.Println(data)
		c.HTML(http.StatusOK, "login.html", data)
	} else if c.Request.Method == "POST" {

		email := c.PostForm("email")
		password := c.PostForm("password")
		user := model.User{}
		model.T.DB.Debug().Where("email = ? and password = ?", email, password).First(&user)
		if user.Name != "" {
			cookie.Add("user_id", user.ID)
			cookie.WriteCookies()
			c.Redirect(http.StatusMovedPermanently, "/")
		} else {
			cookie.Flash("fail_msg", "login failed :(")
			c.Redirect(http.StatusMovedPermanently, "/user/login")
		}

	}
}
Example #19
0
func (fc *FrontController) ViewCtr(c *gin.Context) {
	id := c.Param("id")
	var blog VBlogItem
	CKey := fmt.Sprintf("blogitem-%d", id)
	val, ok := Cache.Get(CKey)
	if val != nil && ok == true {
		fmt.Println("Ok, we found cache, Cache Len: ", Cache.Len())
		blog = val.(VBlogItem)
	} else {
		rows, err := DB.Query("Select * from top_article where aid = ?", &id)
		if err != nil {
			log.Fatal(err)
		}
		defer rows.Close()
		var ()
		for rows.Next() {
			err := rows.Scan(&blog.aid, &blog.title, &blog.content, &blog.publish_time, &blog.publish_status)
			if err != nil {
				log.Fatal(err)
			}
		}
		err = rows.Err()
		if err != nil {
			log.Fatal(err)
		}
		Cache.Add(CKey, blog)
	}
	c.HTML(http.StatusOK, "view.html", gin.H{
		"aid":          blog.aid,
		"title":        blog.title.String,
		"content":      template.HTML(blog.content.String),
		"publish_time": blog.publish_time.String,
	})

}
Example #20
0
/**
 * 1 - Show a deployment
 */
func (ctl *DeploymentController) getDeploymentAction(c *gin.Context) {

	appId := c.Param("app_id")
	deployId := c.Param("deploy_id")

	application := ctl.getApplication(c, appId)
	if application == nil {
		return
	}

	deployment := ctl.getDeployment(c, application, deployId)
	if deployment == nil {
		return
	}

	karhuURL, _ := url.Parse(env.GetDefault("PUBLIC_HOST", "http://127.0.0.1:8080"))
	webSocketProto := "ws"
	if karhuURL.Scheme == "https" {
		webSocketProto = "wss"
	}

	c.HTML(http.StatusOK, "deployment_show.html", map[string]interface{}{
		"application":     application,
		"deployment":      deployment,
		"public_host":     karhuURL.Host,
		"websocket_proto": webSocketProto,
	})
}
Example #21
0
func WhiskyListR(c *gin.Context) {
	// dependency injection
	var (
		whiskyStore = c.MustGet(WhiskyStoreKey).(WhiskyStore)
		user        = GetUser(c)
	)

	// get whiskies
	list, err := whiskyStore.GetAllWhiskies()
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	// transform list into alphabet map
	whiskies := map[string][]Whisky{}
	for _, whisky := range list {
		group := strings.ToUpper(whisky.Distillery[0:1])
		whiskies[group] = append(whiskies[group], whisky)
	}

	c.HTML(http.StatusOK, "list.html", gin.H{
		"User":     user,
		"Whiskies": whiskies,
	})
}
Example #22
0
func (pc *MonitoringController) getMonitoringAction(c *gin.Context) {

	host := c.Query("host")
	stat := c.DefaultQuery("stat", "all")
	t := c.DefaultQuery("time", "last1800")

	hosts, err := models.NodeMapper.FetchAll()
	if err != nil {
		panic(err)
	}

	var graphs models.Graphs

	var target []string
	if host != "" {
		target = []string{host}
	} else {
		for _, h := range hosts {
			target = append(target, h.Hostname)
		}
	}

	if graphs, err = models.GraphMapper.FetchAll(target, stat, t); err != nil {
		panic(err)
	}

	c.HTML(http.StatusOK, "monitoring_show.html", map[string]interface{}{
		"host":   host,
		"stat":   stat,
		"time":   t,
		"hosts":  hosts,
		"stats":  models.GraphStats,
		"graphs": graphs,
	})
}
Example #23
0
func UserListR(c *gin.Context) {
	// dependency injection
	var (
		userStore = c.MustGet(UserStoreKey).(UserStore)
		user      = GetUser(c)
	)

	// get users
	list, err := userStore.GetAllUser()
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	// transform list into alphabet map
	users := map[string][]User{}
	for _, user := range list {
		group := strings.ToUpper(user.Name[0:1])
		users[group] = append(users[group], user)
	}

	c.HTML(http.StatusOK, "users.html", gin.H{
		"User":  user,
		"Users": users,
	})
}
Example #24
0
// openVPNHandler generate the openvpn config
func (r *openvpnAuthd) openVPNHandler(cx *gin.Context) {
	// step: grab the authentication headers
	emailAddress := cx.Request.Header.Get(r.config.AuthHeader)
	if emailAddress == "" {
		cx.AbortWithStatus(http.StatusForbidden)
		return
	}

	// step: generate a certificate for them
	cert, err := r.vault.GetCertificate(emailAddress, r.config.VaultPath, r.config.SessionDuration)
	if err != nil {
		glog.Errorf("failed to generate the certificate for openvpn account, reason: %s", err)
		cx.AbortWithStatus(http.StatusInternalServerError)
		return
	}

	// step: template out the config
	cx.HTML(http.StatusOK, "openvpn.html", gin.H{
		"openvpn_servers": r.config.servers,
		"ttl":             cert.TTL,
		"expires_in":      time.Now().Add(cert.TTL),
		"certificate":     cert.Certificate,
		"private_key":     cert.PrivateKey,
		"issuing_ca":      cert.IssuingCA,
		"email":           emailAddress,
	})
}
Example #25
0
func EditReviewFormR(c *gin.Context) {
	// dependency injection
	var (
		reviewStore = c.MustGet(ReviewStoreKey).(ReviewStore)
		user        = GetUser(c)
	)

	// only authenticated users can perform this action
	if !user.Authenticated() {
		c.AbortWithStatus(http.StatusUnauthorized)
		return
	}

	// fetch review
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.AbortWithError(http.StatusBadRequest, err)
		return
	}

	review, err := reviewStore.GetReview(id)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	c.HTML(http.StatusOK, "review-form.html", gin.H{
		"Action": "Edit",
		"User":   user,
		"Form":   review,
		"Errors": map[string]string{},
	})
}
Example #26
0
func (h *WebHandler) Index(c *gin.Context) {
	res, rec := []Result{}, []algorithm.Record{}
	e := h.DB.Limit(10).Order("idx desc").Find(&rec).Error
	if e != nil {
		c.HTML(http.StatusOK,
			"index",
			gin.H{
				"title":   "NICE",
				"results": "",
				"error":   fmt.Sprintf("Error occured[%s]", e.Error()),
			},
		)
		return
	}
	//bkt := base.NewBucket(false)
	//fmt.Println("xxxx:",len(bkt.Balls))
	for k, _ := range rec {
		res = append(res, rec[k].LoadResult())
	}
	c.HTML(http.StatusOK,
		"index",
		gin.H{
			"title":   "NICE",
			"results": res,
			"error":   "",
		},
	)
}
Example #27
0
func (pc *NodeController) getNodeAddDOAction(c *gin.Context) {

	a, err := models.AccessMapper.FetchOne("do")
	if err != nil {
		panic(err)
	}

	if a == nil {

		c.HTML(http.StatusOK, "node_add_do.html", map[string]interface{}{})
		return
	}

	oauthClient := oauth2.NewClient(oauth2.NoContext, &DOTokenSource{
		AccessToken: a.AccessKey,
	})
	client := godo.NewClient(oauthClient)

	regions, _, err := client.Regions.List(&godo.ListOptions{})
	if err != nil {
		panic(err)
	}

	sizes, _, err := client.Sizes.List(&godo.ListOptions{})
	if err != nil {
		panic(err)
	}

	c.HTML(http.StatusOK, "node_add_do.html", map[string]interface{}{
		"AccessKey": true,
		"DORegions": regions,
		"DOSizes":   sizes,
	})
}
Example #28
0
func postRoute(c *gin.Context) {

	key := c.Params.ByName("key")

	if len(key) < 2 {
		four04(c, "Invalid Post")
		return
	}

	key = key[1:]

	var ps []Itm
	r := Items().Find(bson.M{"key": key}).Sort("-date").Limit(1)
	r.All(&ps)

	if len(ps) == 0 {
		four04(c, "Post not found")
		return
	}

	var posts []Itm
	results := Items().Find(bson.M{"date": bson.M{"$lte": ps[0].Date}}).Sort("-date").Limit(pLimit)
	results.All(&posts)

	channels := AllChannels()

	obj := gin.H{"title": ps[0].Title, "posts": posts, "items": posts, "channels": channels, "current": ps[0].Key}

	if strings.ToLower(c.Request.Header.Get("X-Requested-With")) == "xmlhttprequest" {
		c.HTML(200, "main.html", obj)
	} else {
		c.HTML(200, "full.html", obj)
	}
}
Example #29
0
func HomeHandler(c *gin.Context) {
	// "SELECT * FROM posts ORDER BY id DESC LIMIT %s", sp
	// "SELECT count(*) FROM posts"
	var posts []Post
	DB.Order("pid desc").Limit(sp).Find(&posts)

	if len(posts) == 0 {
		c.Redirect(http.StatusFound, "/user/compose")
		return
	}
	var countrows int
	DB.Model(&Post{}).Count(&countrows)

	var sumpage int
	if countrows%sp == 0 {
		sumpage = countrows / sp
	} else {
		sumpage = countrows/sp + 1
	}
	//title and tag
	titles := component.GetTitle()
	tags := component.GetTag()
	c.HTML(http.StatusOK, "home.tmpl", gin.H{
		"home":    "welcome home",
		"posts":   posts,
		"sumpage": sumpage,
		"onpage":  1,
		"current": c.MustGet("current").(bool),
		"titles":  titles,
		"tags":    tags,
	})
}
Example #30
0
func RenderUserPage(ctx *gin.Context, user *SiteUser) {
	ctx.HTML(http.StatusOK, "reg-results.tpl", gin.H{
		"title":        "Automata Theory - Lab 1, form validation",
		"userNickname": user.nickname,
		"userEmail":    user.email,
	})
}