Beispiel #1
0
func (c *Index) RSS(ctx *web.Context) string {
	p := PostModelInit()
	results := p.RSS()

	ctx.ContentType("xml")
	return mustache.RenderFile("templates/rss.mustache", map[string][]map[string]string{"posts": results})
}
Beispiel #2
0
func Start(ctx *web.Context, handler *MHandler) *Session {
	session := new(Session)
	session.handler = handler
	session.handler.Clean()
	old := false
	if ctx.Cookies != nil {
		if id, exists := ctx.Cookies["bloody_sess"]; exists {
			session.id = id
			old = true
		}
	}
	if !old {
		// Starts new session
		session.generateId()
		session.handler.Store(session.GetID(), nil)
	}
	rt := session.handler.Retrieve(session.GetID())
	json.Unmarshal(rt.SessionData, &session.Data)
	if session.Data == nil {
		t := make(map[string]interface{})
		session.Data = t
	}
	ctx.SetCookie("bloody_sess", session.GetID(), time.Now().Unix()+3600)
	return session
}
Beispiel #3
0
func index(ctx *web.Context, val string) string {
	switch val {
	case "Liberator":
		ctx.Redirect(302, util.Settings.WebHome())
	}
	return val
}
Beispiel #4
0
func LoadPost(ctx *web.Context, val string) {
	username := ctx.Params["username"]
	password := ctx.Params["password"]

	salt := strconv.Itoa64(time.Nanoseconds()) + username

	var h hash.Hash = sha256.New()
	h.Write([]byte(password + salt))

	s, _err := conn.Prepare("INSERT INTO users VALUES(NULL, ?, ?, ?)")
	utils.ReportErr(_err)

	s.Exec(username, string(h.Sum()), salt)
	s.Finalize()
	conn.Close()
	sidebar := utils.Loadmustache("admin.mustache", &map[string]string{})

	//TESTING, REMOVE LATER
	script := "<script type=\"text/javascript\" src=\"../inc/adminref.js\"></script>"
	content := "Welcome to the admin panel, use the control box on your right to control the site content"
	//ENDTESTING

	mapping := map[string]string{"css": "../inc/site.css",
		"title":   "Proggin: Admin panel",
		"sidebar": sidebar,
		"content": content,
		"script":  script}

	output := utils.Loadmustache("frame.mustache", &mapping)
	ctx.WriteString(output)
}
Beispiel #5
0
func get_delete(ctx *web.Context, id string) {
	log.Printf("get_delete %s\n", id)
	if e, err := Load(id); err == nil {
		ctx.WriteString(page(edit_form("/delete", e.Id, e.Date, e.Body, "Really delete")))
	} else {
		ctx.WriteString(page("<p>Invalid ID</p>"))
	}
}
Beispiel #6
0
func checkGodLevel(ctx *web.Context) bool {
	godlevel, _ := ctx.GetSecureCookie("godlevel")
	godlevel = godHash(godlevel)
	if godlevel == admin_pass {
		return true
	}
	return false
}
Beispiel #7
0
func create_person(ctx *web.Context) {
	var p Personne
	Personnes := gouda.M(p)
	p.Id = 0
	p.Nom = ctx.Request.Params["nom"][0]
	p.Age, _ = strconv.Atoi(ctx.Request.Params["age"][0])
	Personnes.Save(p)
	ctx.Redirect(302, "/")
}
Beispiel #8
0
func (c *Index) ReadPost(ctx *web.Context, postId string) string {
	p := PostModelInit()
	result := p.RenderPost(postId)

	viewVars := make(map[string]interface{})
	viewVars["Title"] = result.Title
	viewVars["Content"] = result.Content
	viewVars["Date"] = time.Unix(result.Created, 0).Format(blogConfig.Get("dateFormat"))
	viewVars["Id"] = objectIdHex(result.Id.String())
	// To be used within the {{Comments}} blog
	viewVars["PostId"] = objectIdHex(result.Id.String())

	if result.Status == 0 {
		sessionH := session.Start(ctx, h)
		defer sessionH.Save()
		if sessionH.Data["logged"] == nil {
			ctx.Redirect(302, "/")
			return ""
		}
	}

	if blogConfig.Get("enableComment") != "" {
		viewVars["EnableComment"] = true
	} else {
		viewVars["EnableComment"] = false
	}

	// Render comments
	comments := make([]map[string]string, 0)
	for i, v := range result.Comments {
		comments = append(comments, map[string]string{
			"Number":  strconv.Itoa(i + 1),
			"Date":    time.Unix(v.Created, 0).Format(blogConfig.Get("dateFormat")),
			"Id":      v.Id[0:9],
			"RealId":  v.Id,
			"Content": v.Content,
			"Author":  v.Author})
	}
	viewVars["Comments"] = comments

	if next, exists := p.GetNextId(objectIdHex(result.Id.String())); exists {
		viewVars["Next"] = next
	}
	if last, exists := p.GetLastId(objectIdHex(result.Id.String())); exists {
		viewVars["Last"] = last
	}

	sessionH := session.Start(ctx, h)
	defer sessionH.Save()
	viewVars["Admin"] = false
	if sessionH.Data["logged"] != nil {
		viewVars["Admin"] = true
	}

	output := mustache.RenderFile("templates/view-post.mustache", viewVars)
	return render(output, result.Title)
}
Beispiel #9
0
func adminIndexGet(ctx *web.Context) string {
	sessionH := session.Start(ctx, h)
	defer sessionH.Save()
	if sessionH.Data["logged"] != nil {
		ctx.Redirect(302, "/admin/post/list")
		return ""
	}
	ctx.Redirect(302, "/admin/login")
	return ""
}
Beispiel #10
0
func saveHandler(ctx *web.Context, title string) {
	body, ok := ctx.Request.Params["body"]
	if !ok {
		ctx.Abort(500, "No body supplied.")
		return
	}
	page := makePage(title, string(body))
	page.save()
	redirect(ctx, "view", title)
}
Beispiel #11
0
/*redirects the shortened URL to the real URL*/
func redirect(ctx *web.Context, key string) {
	/*fetch our URL*/
	url, _ := redisClient.Get(getRedisKey(key))
	if url == nil {
		printError(ctx, "I can't find that URL")
	} else {
		/*redirect*/
		ctx.Redirect(301, string(url))
	}
}
Beispiel #12
0
func update_person(ctx *web.Context) {
	var p Personne
	Personnes := gouda.M(p)
	i, _ := strconv.Atoi(ctx.Request.Params["id"][0])
	p = Personnes.Where(gouda.F("id").Eq(i)).First().(Personne)
	p.Nom = ctx.Request.Params["nom"][0]
	p.Age, _ = strconv.Atoi(ctx.Request.Params["age"][0])
	Personnes.Save(p)
	ctx.Redirect(302, "/person/"+fmt.Sprint(p.Id))
}
Beispiel #13
0
func adminLoginGet(ctx *web.Context) string {
	sessionH := session.Start(ctx, h)
	defer sessionH.Save()
	if sessionH.Data["logged"] != nil {
		ctx.Redirect(302, "/admin/post/list")
		return ""
	}
	output := mustache.RenderFile("templates/admin-login.mustache")
	return render(output, "Login")
}
Beispiel #14
0
func newPostGet(ctx *web.Context) string {
	sessionH := session.Start(ctx, h)
	defer sessionH.Save()
	if sessionH.Data["logged"] == nil {
		ctx.Redirect(302, "/admin/login")
		return ""
	}
	output := mustache.RenderFile("templates/new-post.mustache")
	return render(output, "New Post")
}
Beispiel #15
0
func Get(ctx *web.Context, val string) {
	v := strings.Split(val, "/", 2)
	controllerName := ""
	actionName := ""
	if len(v) == 2 {
		controllerName, actionName = v[0], v[1]
	} else if len(v) == 1 {
		controllerName = v[0]
		actionName = "index"
	}

	if conType, ok := C.Controllers[controllerName]; ok {
		conTypePtr := reflect.PtrTo(conType)
		actionMethName := strings.ToUpper(string(actionName[0:1])) + actionName[1:]
		var actionMeth reflect.Method
		found := false
		for i := 0; i < conTypePtr.NumMethod(); i++ {
			if conTypePtr.Method(i).Name == actionMethName {
				actionMeth = conTypePtr.Method(i)
				found = true
				break
			}
		}
		if !found {
			return
		}
		conValue := reflect.New(conType)
		conIndirect := reflect.Indirect(conValue)

		// Inject Params
		conIndirect.FieldByName("Params").Set(reflect.ValueOf(ctx.Request.Params))

		// Inject beans
		for beanName, setterFunc := range bean.Registry() {
			if _, ok := conType.FieldByName(beanName); ok {
				if f := conIndirect.FieldByName(beanName); f.IsValid() {
					f.Set(reflect.ValueOf(setterFunc()))
				}
			}
		}

		action := actionMeth.Func
		ret := action.Call([]reflect.Value{conValue})
		if len(ret) == 2 {
			m := ret[0].Interface().(mv.Model)
			v := ret[1].Interface().(mv.View)
			controllerName = v.String()
			ctx.WriteString(mustache.RenderFile("app/view/"+controllerName+"/index.m", m))
		} else if len(ret) == 1 {
			m := ret[0].Interface().(mv.Model)
			ctx.WriteString(mustache.RenderFile("app/view/"+controllerName+"/"+actionName+".m", m))
		}
	}
	return
}
Beispiel #16
0
// function to resolve a shorturl and redirect
func resolve(ctx *web.Context, short string) {
	kurl, err := load(short)
	if err == nil {
		go redis.Hincrby(kurl.Key, "Clicks", 1)
		ctx.Redirect(http.StatusMovedPermanently,
			kurl.LongUrl)
	} else {
		ctx.Redirect(http.StatusMovedPermanently,
			ROLL)
	}
}
Beispiel #17
0
func get_specific_id(ctx *web.Context, id string) {
	log.Printf("get_specific_id %s\n", id)
	if e, err := Load(id); err == nil {
		t := entry_template
		m := map[string]interface{}{"Id": e.Id, "Date": e.Date, "Body": e.Body}
		s := mustache.Render(t, m)
		ctx.WriteString(page(s))
	} else {
		ctx.WriteString(page(fmt.Sprintf("<p>Invalid ID</p> <!--%v-->", err)))
	}
}
Beispiel #18
0
func newPostPost(ctx *web.Context) {
	sessionH := session.Start(ctx, h)
	defer sessionH.Save()
	if sessionH.Data["logged"] == nil {
		ctx.Redirect(302, "/admin/login")
		return
	}
	p := PostModelInit()
	p.Create(ctx.Params["title"], ctx.Params["content"])
	ctx.Redirect(302, "/admin/post/list")
}
Beispiel #19
0
// renders /
func index(ctx *web.Context) string {
	css, ok := ctx.Params["css"]
	if ok {
		SetCSS(ctx, css)
		ctx.Redirect(302, "/")
		return "ok"
	}
	//posts := postsForMonth(time.LocalTime()) //Db.GetLastNPosts(10)

	//	posts := lastPosts(0xff)
	posts := postsForLastNDays(4)
	if len(posts) <= 0 {
		posts = lastPosts(23)
	}
	//fmt.Printf("posts: %#v\n", posts)
	//embedded struct - our mustache templates need a NumOfComments field to render
	//but we don't want to put that field into the BlogPost Struct so it won't get stored
	//into the DB
	type MyPost struct {
		BlogPost
		NumOfComments int
	}

	//posts ordered by date. this is ugly. TODO: look up if mustache hase something to handle this situation
	type Date struct {
		Date  string
		Posts []MyPost
	}
	Db := DBGet()
	defer Db.Close()

	//loop through our posts and put them into the appropriate date structure
	dates := []Date{}
	var cur_date time.Time
	var date *Date
	for _, p := range posts {
		post_date := time.SecondsToLocalTime(p.Timestamp)
		if !(cur_date.Day == post_date.Day && cur_date.Month == post_date.Month && cur_date.Year == post_date.Year) {
			cur_date = *post_date
			dates = append(dates, Date{Date: cur_date.Format("Mon Jan _2 2006")})
			date = &dates[len(dates)-1]
		}
		p.Comments, _ = Db.GetComments(p.Id)
		mp := MyPost{p, len(p.Comments)}
		date.Posts = append(date.Posts, mp)
	}
	m := map[string]interface{}{
		"Dates": dates,
	}

	tmpl, _ := mustache.ParseFile("templ/index.mustache")
	s := tmpl.Render(&m, getCSS(ctx))
	return s
}
Beispiel #20
0
func adminDelPage(ctx *web.Context, id string) {
	sessionH := session.Start(ctx, h)
	defer sessionH.Save()
	if sessionH.Data["logged"] == nil {
		ctx.Redirect(302, "/admin/login")
		return
	}
	p := PageModelInit()
	p.Delete(id)

	ctx.Redirect(302, "/admin/page/list")
}
Beispiel #21
0
func delPost(ctx *web.Context, postId string) {
	sessionH := session.Start(ctx, h)
	defer sessionH.Save()
	if sessionH.Data["logged"] == nil {
		ctx.Redirect(302, "/admin/login")
		return
	}
	p := PostModelInit()
	p.Delete(postId)

	ctx.Redirect(302, "/admin/post/list")
}
Beispiel #22
0
func adminEditPagePost(ctx *web.Context, id string) {
	sessionH := session.Start(ctx, h)
	defer sessionH.Save()
	if sessionH.Data["logged"] == nil {
		ctx.Redirect(302, "/admin/login")
		return
	}
	p := PageModelInit()
	p.Update(ctx.Params["title"], ctx.Params["content"], id)

	ctx.Redirect(302, "/admin/page/list")
}
Beispiel #23
0
func pageRouter(ctx *web.Context, route string) {
	switch route {
	case "search":
		json, e := Search(ctx)
		if e != nil {
			ctx.WriteString(e.String())
		}
		ctx.Write(json)
	default:

	}
}
Beispiel #24
0
func adminListPagesGet(ctx *web.Context) string {
	sessionH := session.Start(ctx, h)
	defer sessionH.Save()
	if sessionH.Data["logged"] == nil {
		ctx.Redirect(302, "/admin/login")
		return ""
	}
	p := PageModelInit()
	results := p.List()

	output := mustache.RenderFile("templates/list-pages.mustache", map[string][]map[string]string{"pages": results})
	return render(output, "List Pages")
}
Beispiel #25
0
func editPostGet(ctx *web.Context, postId string) string {
	sessionH := session.Start(ctx, h)
	defer sessionH.Save()
	if sessionH.Data["logged"] == nil {
		ctx.Redirect(302, "/admin/login")
		return ""
	}
	p := PostModelInit()
	result := p.Get(postId)

	output := mustache.RenderFile("templates/edit-post.mustache", map[string]string{"Title": result.Title, "Content": result.Content, "id": objectIdHex(result.Id.String())})
	return render(output, "Edit Post")
}
Beispiel #26
0
func person_delete(ctx *web.Context, val string) {
	var p Personne
	var c Car
	Personnes := gouda.M(p)
	Cars := gouda.M(c)
	i, _ := strconv.Atoi(val)
	p = Personnes.Where(gouda.F("id").Eq(i)).First().(Personne)
	cars := Personnes.GetAssociated("cars", p).([]interface{})
	for _, c := range cars {
		Cars.Delete(c.(Car))
	}
	Personnes.Delete(p)
	ctx.Redirect(302, "/")
}
Beispiel #27
0
func get_from(ctx *web.Context, id string) {
	log.Printf("get_root\n")
	p := `{{#entries}}` + entry_template + `{{/entries}}` + footer_template
	t := page(p)
	m := make(map[string]interface{})
	entries, _ := LoadRange(id, *max_entries)
	m["entries"] = entries
	m["id"] = id
	if len(entries) == *max_entries {
		m["from_id"] = entries[len(entries)-1].Id
	}
	s := mustache.Render(t, m)
	ctx.WriteString(s)
}
Beispiel #28
0
func adminLoginPost(ctx *web.Context) {
	sessionH := session.Start(ctx, h)
	defer sessionH.Save()
	if sessionH.Data["logged"] != nil {
		ctx.Redirect(302, "/admin/post/list")
		return
	}
	if ctx.Params["username"] == config.Get("adminuser") && ctx.Params["password"] == config.Get("adminpasswd") {
		t := time.LocalTime()
		var h hash.Hash = sha1.New()
		h.Write([]byte(strconv.Itoa64(t.Seconds())))
		sessionH.Data["logged"] = hex.EncodeToString(h.Sum())
	}
	ctx.Redirect(302, "/admin/post/list")
}
Beispiel #29
0
// function to shorten and store a url
func shorten(ctx *web.Context, data string) {
	host := config.GetStringDefault("hostname", "localhost")
	r, _ := ctx.Request.Params["url"]
	theUrl, err := isValidUrl(string(r))
	if err == nil {
		ctr, _ := redis.Incr(COUNTER)
		encoded := Encode(ctr)
		location := fmt.Sprintf("%s://%s/%s", HTTP, host, encoded)
		store(encoded, location, theUrl.Raw)
		// redirect to the info page
		ctx.Redirect(http.StatusMovedPermanently, location+"+")
	} else {
		ctx.Redirect(http.StatusNotFound, ROLL)
	}
}
Beispiel #30
0
func renderTmpl(ctx *web.Context, tmpl, title, body string) {
	d := map[string]string{
		"prefix": urlPrefix,
		"title":  title,
		"body":   body,
	}
	t, err := template.ParseFile("tmpl/"+tmpl+".html", nil)
	if err != nil {
		ctx.Abort(500, "Unable to Parse template file: "+err.String())
		return
	}
	err = t.Execute(ctx, d)
	if err != nil {
		ctx.Abort(500, "Unable to Execute template: "+err.String())
	}
}