Beispiel #1
0
// RegisterPost handles registration form, and create a session for the new user if the registration
// process is complete.
//
//		Method           POST
//
//		Route            /auth/register
//
//		Restrictions     None
//
// 		Template         None (All actions redirect to other routes )
//
// Flash messages may be set before redirection.
func RegisterPost(ctx *echo.Context) error {
	var flashMessages = flash.New()
	f := forms.New(utils.GetLang(ctx))
	lf := f.RegisterForm()(ctx.Request())
	if !lf.IsValid() {

		// Case the form is not valid, ships it back with the errors exclusively
		utils.SetData(ctx, authForm, lf)
		return ctx.Render(http.StatusOK, tmpl.RegisterTpl, utils.GetData(ctx))
	}

	// we are not interested in the returned user, rather we make sure the user has
	// been created.
	_, err := query.CreateNewUser(lf.GetModel().(forms.Register))
	if err != nil {
		flashMessages.Err(msgAccountCreateFailed)
		flashMessages.Save(ctx)
		ctx.Redirect(http.StatusFound, "/auth/register")
		return nil
	}

	// TODO: improve the message to include directions to use the current email and
	// password to login?
	flashMessages.Success(msgAccountCreate)
	flashMessages.Save(ctx)

	// Don't create session in this route, its best to leave only one place which
	// messes with the main user session. So we redirect to the login page, and encourage
	// the user to login.
	ctx.Redirect(http.StatusFound, "/auth/login")
	return nil
}
Beispiel #2
0
func index(c *echo.Context) error {
	deviceids, err := tracksDB.GetDevicesID(groupID)
	if err != nil {
		return err
	}
	return c.Render(http.StatusOK, "index.html", deviceids)
}
Beispiel #3
0
// ArchiveView shows a list of posts arranged by its date
func ArchiveView(c *echo.Context) error {
	id := c.Param("id")
	var err error

	// Get archive data
	var archive models.Archive
	err = database.Current.Get(&archive, database.Queries.ArchiveBySignature, id)
	if err != nil {
		log.Println("Cannot get archive by signature", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	// Get related posts
	var posts []models.AuthoredPost
	err = database.Current.Select(&posts, database.Queries.ArchiveAuthoredPosts, id)
	if err != nil {
		log.Println("Cannot select posts", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	// Create our render context and fill base data
	ac := archiveContext{
		Archive:      archive,
		RelatedPosts: posts,
	}

	err = fillBlogContext(c, &ac.blogContext)
	if err != nil {
		log.Println("Cannot fill blog context", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	return c.Render(200, "archive", ac)
}
Beispiel #4
0
func welcome(c *echo.Context) error {
	type User struct {
		Name string
		Age  int8
	}
	return c.Render(http.StatusOK, "welcome", User{Name: "schaffer", Age: 23})
}
Beispiel #5
0
// Home shows the resumes home page.
//
//		Method           GET
//
//		Route            /resume/
//
//		Restrictions     Yes
//
// 		Template         resume/home.html
func Home(ctx *echo.Context) error {
	user := ctx.Get("User").(*models.Person)
	if res, err := query.GetAllPersonResumes(user); err == nil {
		utils.SetData(ctx, "resumes", res)
	}
	return ctx.Render(http.StatusOK, tmpl.ResumeHomeTpl, utils.GetData(ctx))
}
Beispiel #6
0
// Register renders registration form.
//
//		Method           GET
//
//		Route            /auth/register
//
//		Restrictions     None
//
// 		Template         auth/register.html
func Register(ctx *echo.Context) error {
	f := forms.New(utils.GetLang(ctx))
	utils.SetData(ctx, authForm, f.RegisterForm()())

	// set page tittle to register
	utils.SetData(ctx, "PageTitle", "register")
	return ctx.Render(http.StatusOK, tmpl.RegisterTpl, utils.GetData(ctx))
}
Beispiel #7
0
// RegionsHome renders regions home page.
//
//
//		Method           GET
//
//		Route            /jobs/regions
//
//		Restrictions     None
//
// 		Template         base/regions.html
//
func RegionsHome(ctx *echo.Context) error {
	regs, err := query.GetAllRegions()
	if err != nil {
		utils.SetData(ctx, "Message", tmpl.NotFoundMessage)
		return ctx.Render(http.StatusNotFound, tmpl.ErrNotFoundTpl, utils.GetData(ctx))
	}
	utils.SetData(ctx, settings.RegionsListKey, regs)
	return ctx.Render(http.StatusOK, tmpl.BaseRegionsTpl, utils.GetData(ctx))
}
Beispiel #8
0
func HandleError(err error, c *echo.Context) {
	err = c.Render(500, "500", baseContext{
		Info:  config.BlogInfo,
		Error: err,
	})
	if err != nil {
		log.Println("Cannot report error:", err)
	}
}
Beispiel #9
0
// CategoryView shows a list of posts arranged by its category
func CategoryView(c *echo.Context) error {
	// Parse pagination attributes
	pn, ps := utils.GetPage(c)
	id, _ := strconv.Atoi(c.Param("id"))

	// Get category using id
	var category models.Category
	err := database.Current.Get(&category, database.Queries.CategoryByID, id)
	if err != nil {
		log.Println("Cannot select category:", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	// Query the posts
	var posts []models.AuthoredPost
	err = database.Current.Select(&posts, database.Queries.AuthoredPostsByCategory, id, ps, ps*(pn-1))
	if err != nil {
		log.Println("Cannot select posts:", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	var count int
	err = database.Current.Get(&count, database.Queries.PostByCategoryCount, id)
	if err != nil {
		log.Println("Cannot count posts:", err)
	}

	pc := int(math.Floor(float64(count/ps))) + 1

	// Generate preview for all posts
	for _, p := range posts {
		p.Preview = createPreview(p.TextContent)
	}

	// Create our context and fill base data
	cc := categoryContext{
		Category: category,
		RelatedPosts: models.Paginated{
			TotalObjects:  count,
			PageCount:     pc,
			PageNumber:    pn,
			PageSize:      ps,
			NextAvailable: pn < pc,
			Results:       posts,
		},
	}

	err = fillBlogContext(c, &cc.blogContext)
	if err != nil {
		log.Println("Cannot fill blog context", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	// Render the results
	return c.Render(200, "category", cc)
}
Beispiel #10
0
// Login renders login form.
//
//		Method           GET
//
//		Route            /auth/login
//
//		Restrictions     None
//
// 		Template         auth/login.html
//
func Login(ctx *echo.Context) error {

	f := forms.New(utils.GetLang(ctx))
	utils.SetData(ctx, authForm, f.LoginForm()())

	// set page tittle to login
	utils.SetData(ctx, "PageTitle", "login")

	return ctx.Render(http.StatusOK, tmpl.LoginTpl, utils.GetData(ctx))
}
Beispiel #11
0
func Login(context echo.Context) error {
	_, err := helpers.ValidateJWT(context)
	if err != nil {
		return context.Render(http.StatusOK, "login", os.Getenv("AUTH0_CALLBACK"))
	}

	context.Redirect(http.StatusMovedPermanently, "/frontend")

	return context.String(http.StatusOK, "Done")
}
Beispiel #12
0
// Home displays home page
func (*SiteController) Home(c echo.Context) error {
	var site models.Site

	ret, err := site.Home()
	if err != nil {
		return c.Render(500, "500", err)
	}

	return c.Render(200, "index", ret)
}
Beispiel #13
0
// Single shows single page
func (*SiteController) Single(c echo.Context) error {
	var site models.Site

	ret, err := site.Single(c.P(0))
	if err != nil {
		return c.Render(400, "404", err)
	}

	return c.Render(200, "index", ret)
}
Beispiel #14
0
// JobsHome renders jobs home page
//
//
//		Method           GET
//
//		Route            /jobs/
//
//		Restrictions     None
//
// 		Template         base/jobs.html
func JobsHome(ctx *echo.Context) error {
	jobs, err := query.GetLatestJobs()
	if err != nil {
		utils.SetData(ctx, "Message", tmpl.NotFoundMessage)
		return ctx.Render(http.StatusNotFound, tmpl.ErrNotFoundTpl, utils.GetData(ctx))

	}
	utils.SetData(ctx, settings.JobsListKey, jobs)
	utils.SetData(ctx, settings.PageTitleKey, "jobs")
	return ctx.Render(http.StatusOK, tmpl.BaseJobsHomeTpl, utils.GetData(ctx))
}
Beispiel #15
0
// RegionsJobView renders jobs from a gien region. The region name should be in short form.
//
//
//		Method           GET
//
//		Route            /jobs/regions/:name
//
//		Restrictions     None
//
// 		Template         base/regions_job.html
//
func RegionsJobView(ctx *echo.Context) error {
	name := ctx.Param("name")
	jobs, count, err := query.GetJobByRegionShort(name)
	if err != nil {
		utils.SetData(ctx, "Message", tmpl.NotFoundMessage)
		return ctx.Render(http.StatusNotFound, tmpl.ErrNotFoundTpl, utils.GetData(ctx))
	}
	utils.SetData(ctx, settings.JobsFound, count)
	utils.SetData(ctx, settings.JobsListKey, jobs)
	return ctx.Render(http.StatusOK, tmpl.BaseRegionsJobViewTpl, utils.GetData(ctx))
}
Beispiel #16
0
func index(c *echo.Context) error {
	p1 := game.NewPlay("player1")
	p2 := game.NewPlay("player2")
	players := [2]*game.Play{p1, p2}

	g, _ := game.New()
	g.Start(players)
	game.Push(g)
	game.Save()
	return c.Render(http.StatusOK, "index.html", g.GetGrids())
}
Beispiel #17
0
func current(c *echo.Context) error {
	deviceID := c.Param("deviceid")
	track, err := tracksDB.GetLast(groupID, deviceID)
	if err != nil {
		if err == mgo.ErrNotFound {
			return echo.NewHTTPError(http.StatusNotFound)
		}
		return err
	}
	return c.Render(http.StatusOK, "current.html", track)
}
Beispiel #18
0
func getJob(c *echo.Context) error {
	mdb, _ := getDatabase()
	id := c.Param("id")
	job, err := db.GetJobById(mdb, id)

	defer mdb.Session.Close()

	if err != nil {
		return c.Render(404, "job", JobPage{nil, false, false})
	}

	return c.Render(200, "job", JobPage{&job, false, false})
}
Beispiel #19
0
func jobs(c *echo.Context) error {

	mdb, _ := getDatabase()
	jobs, err := db.GetJobs(mdb, nil, 0)

	defer mdb.Session.Close()

	if err != nil {
		return err
	}

	return c.Render(200, "jobs", JobsPage{jobs, false, true})
}
Beispiel #20
0
// Delete deletes the resume.
//
//		Method           POST
//
//		Route            /resume/delete/:id
//
//		Restrictions     Yes
//
// 		Template         None
func Delete(ctx *echo.Context) error {
	var flashMessages = flash.New()
	id, err := utils.GetInt(ctx.Param("id"))
	if err != nil {
		utils.SetData(ctx, "Message", tmpl.BadRequestMessage)
		return ctx.Render(http.StatusBadRequest, tmpl.ErrBadRequest, utils.GetData(ctx))
	}
	user := ctx.Get("User").(*models.Person)

	resume, err := query.GetResumeByID(id)
	if err != nil {
		utils.SetData(ctx, "Message", tmpl.NotFoundMessage)
		return ctx.Render(http.StatusNotFound, tmpl.ErrNotFoundTpl, tmpl.NotFoundMessage)
	}

	// Users are allowed to delete resumes that they don't own.
	if resume.PersonID != user.ID {
		utils.SetData(ctx, "Message", tmpl.BadRequestMessage)
		return ctx.Render(http.StatusBadRequest, tmpl.ErrBadRequest, utils.GetData(ctx))
	}

	err = query.Delete(resume)
	if err != nil {
		utils.SetData(ctx, "Message", tmpl.ServerErrorMessage)
		return ctx.Render(http.StatusInternalServerError, tmpl.ErrServerTpl, utils.GetData(ctx))
	}

	flashMessages.Success("resume successful deleted")
	flashMessages.Save(ctx)
	ctx.Redirect(http.StatusFound, "/resume/")
	return nil
}
Beispiel #21
0
// DocsHome renders the home.md document for the given language.
//
//		Method           GET
//
//		Route            /docs
//
//		Restrictions     None
//
// 		Template         base/docs_index.html
//
func DocsHome(ctx *echo.Context) error {
	data := utils.GetData(ctx).(utils.Data)
	lang := data.Get(settings.LangDataKey).(string)
	home := settings.DocsPath + "/" + lang + "/" + settings.DocsIndexPage
	d, err := static.Asset(home)
	if err != nil {
		utils.SetData(ctx, "Message", tmpl.NotFoundMessage)
		return ctx.Render(http.StatusNotFound, tmpl.ErrNotFoundTpl, utils.GetData(ctx))
	}
	data.Set("doc", string(d))
	data.Set(docIndex, getDocIndex(lang))
	data.Set("PageTitle", settings.DocsIndexPage)
	return ctx.Render(http.StatusOK, tmpl.BaseDocsHomeTpl, data)
}
Beispiel #22
0
// ProfileView renders the profile data with the fancy portfolio template
func ProfileView(c *echo.Context) error {
	id := c.Param("id") // ID in this case applies to username
	var err error

	var profile models.Profile
	err = database.Current.Get(&profile, database.Queries.ProfileByUsername, id)
	if err != nil {
		log.Println("Cannot get profile:", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	var skills []models.ResumeSkill
	err = database.Current.Select(&skills, database.Queries.ResumeSkillsByProfileID, profile.ID)
	if err != nil {
		log.Println("Cannot get skills:", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	var jobs []models.ResumeJob
	err = database.Current.Select(&jobs, database.Queries.ResumeJobsByProfileID, profile.ID)
	if err != nil {
		log.Println("Cannot select jobs:", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	var education []models.ResumeEducation
	err = database.Current.Select(&education, database.Queries.ResumeEducationByProfileID, profile.ID)
	if err != nil {
		log.Println("Cannot select education:", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	var projects []models.ResumeProject
	err = database.Current.Select(&projects, database.Queries.ResumeProjectsByProfileID, profile.ID)
	if err != nil {
		log.Println("Cannot select projects:", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	pc := profileContext{
		Profile:   profile,
		Skills:    skills,
		Jobs:      jobs,
		Education: education,
		Projects:  projects,
	}

	return c.Render(200, "profile", pc)
}
Beispiel #23
0
func (h *handler) IndexGetHandler(c *echo.Context) error {
	n, _ := h.back.Model.Package.DummyList()
	p, _ := h.back.Model.Package.DummyList()
	u, _ := h.back.Model.Package.DummyList()
	data := struct {
		New     []model.PackageRow
		Popular []model.PackageRow
		Updated []model.PackageRow
	}{
		n,
		p,
		u,
	}
	return c.Render(http.StatusOK, "index.html", data)
}
Beispiel #24
0
// Index serves blog index view
func Index(c *echo.Context) error {

	// Parse pagination attributes
	pn, ps := utils.GetPage(c)

	// Query the posts
	var posts []models.AuthoredPost
	err := database.Current.Select(&posts, database.Queries.AuthoredPosts, ps, ps*(pn-1))
	if err != nil {
		log.Println("Cannot select posts:", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	var count int
	err = database.Current.Get(&count, database.Queries.PostCount)
	if err != nil {
		log.Println("Cannot count posts:", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	pc := int(math.Floor(float64(count/ps))) + 1

	// Generate preview for all posts
	for _, p := range posts {
		p.Preview = createPreview(p.TextContent)
	}

	// Create our render context and fill base data
	ic := indexContext{
		PostResults: models.Paginated{
			TotalObjects:  count,
			PageCount:     pc,
			PageNumber:    pn,
			PageSize:      ps,
			NextAvailable: pn < pc,
			Results:       posts,
		},
	}

	err = fillBlogContext(c, &ic.blogContext)
	if err != nil {
		log.Println("Cannot fill blog context", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	// Render the results
	return c.Render(200, "index", ic)
}
Beispiel #25
0
func HandleErrors(err error, c *echo.Context) {
	f := Errors[err]
	if f != nil {
		f(err, c)
		return
	}
	if c.Request().Header.Get("Content-Type") == imt.Application.JSON {
		JSONErrorHandler(echo.NewHTTPError(500, err.Error()), c)
	} else {
		code := http.StatusInternalServerError
		if he, ok := err.(*echo.HTTPError); ok {
			code = he.Code()
		}
		c.Render(code, strconv.Itoa(code), err)
	}
}
Beispiel #26
0
func (h *handler) PackageGetHandler(c *echo.Context) error {

	pName := strings.Replace(c.Request().RequestURI, "/p/", "", -1)
	p, err := h.back.Model.Package.GetItem(pName)
	if err != nil {
		log.Println(err)
		return c.Redirect(http.StatusTemporaryRedirect, "/")
	}

	data := struct {
		Package model.PackageRow
	}{
		p,
	}
	return c.Render(http.StatusOK, "package.html", data)
}
Beispiel #27
0
func legalDoc(c *echo.Context, class string) error {
	slug := c.Param("slug")

	var document models.LegalDocument
	err := database.Current.Get(&document, database.Queries.LegalDocumentBySlug, slug, class)
	if err != nil {
		log.Println("Cannot retrieve legal document:", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	dc := documentContext{
		Info:     config.BlogInfo,
		Document: document,
	}
	return c.Render(200, "legal_document", dc)
}
Beispiel #28
0
func EditHandler(c echo.Context) error {
	var ev *EditorView
	ev, ok := c.Get("editorView").(*EditorView)
	if !ok {
		log.Println("reading file")
		filepath := c.P(0)
		content, err := ioutil.ReadFile(filepath)
		if err != nil {
			return echo.NewHTTPError(http.StatusInternalServerError, "Unable to read requested file")
		}
		ev = NewEditorView(filepath, string(content))
		ev.CurrentLineEnding = eol.DetectDefault(ev.Content, eol.OSDefault())
		log.Println(ev.CurrentLineEnding.Description())
	}
	return c.Render(http.StatusOK, "base", ev)
}
Beispiel #29
0
// Handler
func recentMedia(c *echo.Context) error {

	var err error

	//log.Println("InstaChache: ", InstaCache)

	// Caching UserID
	var id string
	x, found := InstaCache.Get("userID")
	if found {
		id = x.(string)
	} else {
		id, err = getUserID(C.USERNAME)
		if err != nil {
			log.Println("Error in getUserID func: ", err)
			err = c.String(http.StatusBadRequest, "User not found: "+err.Error())
		}
		if err == nil {
			InstaCache.Set("userID", id, cache.DefaultExpiration)
		}
	}

	//log.Println("UserID: ", id)

	// Caching Instafeed last 20 photos
	var mediasResponse *MediasResponse
	if x, found := InstaCache.Get("mediasResponse"); found {
		mediasResponse = x.(*MediasResponse)
	} else {
		mediasResponse, err = getRecentMedia(id, 20)

		if err != nil {
			log.Println("Error in getRecentMedia: ", err)
			err = c.String(http.StatusBadRequest, "Media not found: "+err.Error())
		}

		if err == nil {
			InstaCache.Set("mediasResponse", mediasResponse, cache.DefaultExpiration)
		}
	}

	if mediasResponse.Meta.Code == 200 {
		err = c.Render(http.StatusOK, "index", mediasResponse)
	}

	return err
}
Beispiel #30
0
func View(c *echo.Context) error {
	domain := c.Get("domain").(Domain)
	a := readMapFile(domain.MapFile, nil)
	b := make([][]string, 0)
	for i := 0; i < len(a); i++ {
		if strings.Contains(a[i].Email, "@"+domain.Name) {
			b = append(b, []string{a[i].Email, a[i].Target})
		}
	}
	if len(b) == 0 {
		b = append(b, []string{"@" + domain.Name, "nobody"})
	}
	return c.Render(http.StatusOK, "view", struct {
		Aliases [][]string
		Domain  string
	}{b, domain.Name})
}