Exemplo n.º 1
0
// SectionsNew renders page for adding new CV section
func SectionsNew(r render.Render, tokens oauth2.Tokens, session sessions.Session, params martini.Params) {
	pd := NewPageData(tokens, session)
	sectionType, _ := strconv.Atoi(params["type"])
	pd.SectionType = sectionType
	pd.Section = &Section{}
	r.HTML(200, "sections-new", pd)
}
Exemplo n.º 2
0
func GoLoginHandler(r render.Render, params martini.Params) {
	path := params["path"]
	if path == "" {
		path = "/"
	}
	r.HTML(200, "admin/login", map[string]string{"path": path})
}
Exemplo n.º 3
0
func getLoginPage(user sessionauth.User, r render.Render) {
	if user.IsAuthenticated() {
		r.Redirect(INDEX_PAGE)
		return
	}
	r.HTML(200, LOGIN_PAGE, nil)
}
Exemplo n.º 4
0
func (ps ProjectService) Create(projet models.Project, r render.Render) {
	err := utils.ORM.Save(&projet).Error
	if err != nil {
		utils.Log.Error("Failed to create project: %v", err)
		r.HTML(403, "project/new", projet)
	}
}
Exemplo n.º 5
0
func recovery(
	c martini.Context,
	req *http.Request,
	ren render.Render,
	dec formDecoder,
) {
	defer func() {
		if r := recover(); r != nil {
			switch err := r.(type) {
			case jsonError:
				handleJsonError(err, ren)
			case authError:
				authenticate(err, dec, ren, req)
			case userError:
				ren.HTML(200, "error", m{
					"Message": formatMessage(err.Error()),
				})
			case csql.Error:
				ren.HTML(200, "error", m{
					"Message": formatMessage(err.Error()),
				})
			default:
				panic(r)
			}
		}
	}()
	c.Next()
}
Exemplo n.º 6
0
func Edit(params martini.Params, r render.Render, db *mgo.Database) {
	available := new(AvailableForm)
	available.Op = "Edit"
	available.Channels = append(available.Channels,
		Channel{"email", false},
		Channel{"web", false},
		Channel{"push", false},
	)
	oId := bson.ObjectIdHex(params["_id"])
	err := db.C(availableCollection).FindId(oId).One(&available.Topic)
	if err != nil {
		r.HTML(400, "400", err)
	}

	fmt.Println(available.Channels)

	for i, v := range available.Channels {
		for _, value := range available.Topic.Channels {
			if v.Name == value {
				available.Channels[i].Enabled = true
			}
		}
	}

	r.HTML(200, "available/form", available)
}
Exemplo n.º 7
0
func SignUp(s sessions.Session, r render.Render, x csrf.CSRF) {
	returnvals := map[string]interface{}{
		"csrf":  x.GetToken(),
		"Title": "Nightcrawler Signup",
	}
	r.HTML(200, "sign_up", returnvals)
}
Exemplo n.º 8
0
func GetPaste(params martini.Params, ren render.Render, r *http.Request, cf *swift.Connection, mc *memcache.Client) {
	cachedPaste, err := mc.Get(params["pasteid"])
	format := params["format"]
	if err != nil {
		log.Println(err)
	}
	var paste Paste
	paste.PasteId = params["pasteid"]
	if cachedPaste == nil {
		log.Println("Asking swift for ", params["pasteid"])
		cfPaste, err := cf.ObjectGetBytes("go-cfpaste", params["pasteid"])
		if err != nil {
			if err.Error() == "Object Not Found" {
				ren.HTML(404, "404", paste)
				return
			} else {
				log.Println(err)
				ren.Error(500)
				return
			}
		}
		err = json.Unmarshal(cfPaste, &paste)
		PanicIf(err)
	} else {
		log.Println("Cache hit for ", params["pasteid"])
		err = json.Unmarshal(cachedPaste.Value, &paste)
		PanicIf(err)
	}
	if format == "json" {
		ren.JSON(200, paste)
	} else {
		ren.HTML(200, "paste", paste)
	}
	return
}
Exemplo n.º 9
0
func EditComponent(ren render.Render, db *sql.DB, params martini.Params, t *template.TemplateData) {
	var component_id string = params["id"]

	if component_id != "new" {
		component, err := repository.GetComponent(db, component_id)

		if err != nil || component == nil {
			t.SessionMessage.AddDanger("Failed to load component.")

			ren.Redirect("/component")

			return
		}

		t.Data = component

		id, _ := strconv.ParseInt(params["id"], 10, 64)

		t.MediaList = getMediaList(db, COMPONENT, id)

		ren.HTML(200, "blah/component/edit", t)
	} else {
		ren.HTML(200, "blah/component/edit", nil)
	}
}
Exemplo n.º 10
0
func SearchPage(user common.User, session sessions.Session, r render.Render, req *http.Request) {
	src, err := handleSearch(req.URL.Query())

	if err != nil {
		r.Error(400)
	}

	status := common.GetCodeSourceStatus(src)

	id := rand.Int63()
	params := req.URL.Query()
	usr := params.Get("user")
	repo := params.Get("repo")
	session.Set(id, usr+"/"+repo)

	data := struct {
		common.User
		Pagename     string
		Theme        string
		SourceStatus string
		WS_ID        int64

		Source *common.CodeSource
	}{user, "search", "standard", string(status), id, src}

	r.HTML(200, "search", data)
}
Exemplo n.º 11
0
func Edit(rw http.ResponseWriter, req *http.Request, r render.Render, params martini.Params) {
	c := appengine.NewContext(req)
	var b banner.Banner

	intID, err := strconv.Atoi(params["id"])
	if err == nil {
		b.ID = int64(intID)
	}

	if b.ID > 0 {
		if err := b.Get(c); err != nil {
			http.Redirect(rw, req, "/admin?error="+err.Error(), http.StatusFound)
			return
		}
	}

	uploadURL, err := blobstore.UploadURL(c, "/admin/banners/"+strconv.Itoa(intID), nil)
	if err != nil {
		http.Redirect(rw, req, "/admin?error="+err.Error(), http.StatusFound)
		return
	}

	bag := make(map[string]interface{}, 0)
	bag["Host"] = req.URL.Host
	bag["Admin"] = true
	bag["Banner"] = b
	bag["URL"] = uploadURL
	bag["ActiveNav"] = "banners"
	r.HTML(200, "admin/banners/edit", bag)

	return
}
Exemplo n.º 12
0
Arquivo: quote.go Projeto: firba1/irq
func Quote(db model.Model, r render.Render, params martini.Params, isJson IsJson) {
	id, err := strconv.Atoi(params["id"])
	if err != nil {
		RenderError(r, 404, isJson, "invalid quote id")
		return
	}

	quote, err := db.GetQuote(id)
	if err != nil {
		RenderError(r, 404, isJson, "quote not found")
		return
	}

	if isJson {
		r.JSON(200, quote)
		return
	}

	env := quotePageEnv{
		PageEnv:        PageEnv{Title: fmt.Sprintf("#%d", quote.ID)},
		Quotes:         []model.Quote{quote},
		ShowPagination: false,
	}
	r.HTML(200, "quote", env)
}
Exemplo n.º 13
0
func CreateAdmin(r render.Render, req *http.Request) {
	if len(cache.Users) > 0 {
		r.Error(404)
		return
	}
	if req.Method == "GET" {
		r.HTML(200, "user_add", map[string]interface{}{})
		return
	}

	req.ParseForm()
	values := req.Form
	m := &model.User{}
	m.Account = values.Get("account")
	m.Password = model.Md5(values.Get("password"))
	m.Info = values.Get("info")
	m.Name = values.Get("name")
	if !checkNull([]string{m.Account, m.Password, m.Info, m.Name}...) {
		service.Logs.Error("args err")
		return
	}
	m.Status = model.UserStatusAdmin
	_, err := dao.AddUser(m)
	if err != nil {
		service.Logs.Error("dao.InsertUser err(%v)", err)
		return
	}
	r.Redirect("/", 302)
	return
}
Exemplo n.º 14
0
func EditInvertebrate(ren render.Render, db *sql.DB, params martini.Params, t *template.TemplateData) {
	var invertebrate_id string = params["id"]

	if invertebrate_id != "new" {
		invertebrate, err := repository.GetInvertebrate(db, invertebrate_id)

		if err != nil || invertebrate == nil {
			t.SessionMessage.AddDanger("Failed to load invertebrate.")

			ren.Redirect("/invertebrate")

			return
		}

		id, _ := strconv.ParseInt(params["id"], 10, 64)

		invertebrate.PopularNames.Names, err = repository.GetPopularNames(db, id, INVERTEBRATE)

		t.Data = invertebrate

		t.MediaList = getMediaList(db, INVERTEBRATE, id)

		ren.HTML(200, "blah/invertebrate/edit", t)
	} else {
		ren.HTML(200, "blah/invertebrate/edit", nil)
	}
}
Exemplo n.º 15
0
func Answer(req *http.Request, r render.Render) {
	returnData := make(map[string]interface{})
	if req.Method == "GET" {
		blankList, choiceList, judgeList := appService.GetTitleId(1, 1, 1)
		returnData["blankList"] = blankList
		returnData["choiceList"] = choiceList
		returnData["judgeList"] = judgeList
		r.HTML(200, "answer", returnData)
		return
	}
	req.ParseForm()
	values := req.Form
	records := values.Get("records")
	if records == "" {
		r.Data(500, []byte("error"))
	}
	name, recordsList, err := appService.CheckRecords(records)
	if err != nil {
		r.Data(500, []byte("appService.CheckRecords error"))
	}
	returnData["name"] = name
	returnData["list"] = recordsList
	r.HTML(200, "record", returnData)
	return
}
Exemplo n.º 16
0
func getIndex(req *http.Request, params martini.Params, rd render.Render, session sessions.Session, db *sqlx.DB) {

	queries := req.URL.Query()
	fmt.Println(queries)

	// appName := params["appName"]
	// fmt.Println(appName)

	//session.Set("hello", "world")

	// You can also get a single result, a la QueryRow
	// pic := Picture{}
	// err := db.Get(&pic, "SELECT * FROM picture WHERE orig_id=1")
	// if err != nil {
	// 	log.Fatal(err)
	// }
	// fmt.Printf("%#v\n", pic)

	// user := &User{Id: "123", Name: "jason", AccessToken: "123123", LastAuthTime: 432123, Valid: 1}
	// ret := user.Insert()
	// fmt.Println(ret)

	url := fmt.Sprintf(API_URL, ClientId, RedirectUrl)

	rd.HTML(200, "auth_index", H{
		"url": url,
	})

}
Exemplo n.º 17
0
// ReadUser is a route which fetches user according to parameter "id" on API side and according to retrieved
// session cookie on frontend side.
// Returns user struct with all posts merged to object on API call. Frontend call will render user "home" page, "user/index.tmpl".
func ReadUser(req *http.Request, params martini.Params, res render.Render, s sessions.Session) {
	var user User
	switch Root(req) {
	case "api":
		id, err := strconv.Atoi(params["id"])
		if err != nil {
			log.Println(err)
			res.JSON(400, map[string]interface{}{"error": "The user ID could not be parsed from the request URL."})
			return
		}
		user.ID = int64(id)
		user, err := user.Get()
		if err != nil {
			log.Println(err)
			if err.Error() == "not found" {
				res.JSON(404, NotFound())
				return
			}
			res.JSON(500, map[string]interface{}{"error": "Internal server error"})
			return
		}
		res.JSON(200, user)
		return
	case "user":
		user, err := user.Session(s)
		if err != nil {
			log.Println(err)
			s.Set("user", -1)
			res.HTML(500, "error", err)
			return
		}
		res.HTML(200, "user/index", user)
		return
	}
}
Exemplo n.º 18
0
func View(rw http.ResponseWriter, req *http.Request, r render.Render, params martini.Params) {
	c := appengine.NewContext(req)
	var q quote.Quote

	intID, err := strconv.Atoi(params["id"])
	if err == nil {
		q.ID = int64(intID)
	}

	if q.ID > 0 {
		if err := q.Get(c); err != nil {
			http.Redirect(rw, req, "/admin?error="+err.Error(), http.StatusFound)
			return
		}
	}

	bag := make(map[string]interface{}, 0)
	bag["Host"] = req.URL.Host
	bag["Admin"] = true
	bag["Quote"] = q
	bag["ActiveNav"] = "quotes"
	r.HTML(200, "admin/quote/view", bag)

	return
}
Exemplo n.º 19
0
func IndexArticles(db *sql.DB, r *http.Request, ren render.Render) {
	search := "%" + r.URL.Query().Get("search") + "%"
	rows, err := db.Query(`SELECT id, title, content
                         FROM article
                         WHERE title ILIKE $1
                         OR content ILIKE $1
												 ORDER BY id DESC`, search)
	PanicIf(err)
	defer rows.Close()

	articles := []Article{}
	for rows.Next() {
		a := Article{}
		err := rows.Scan(&a.Id, &a.Title, &a.Content)
		a.Content = PrepareContent(a.Content)

		PanicIf(err)
		articles = append(articles, a)
	}

	if len(articles) == 0 {
		a := Article{}
		a.Content = "No posts found"
		articles = append(articles, a)
	}

	ren.HTML(200, "articles", articles)
}
Exemplo n.º 20
0
func ExtensionPage(w http.ResponseWriter, r *http.Request, re render.Render) {
	re.HTML(200, "cextension", map[string]interface{}{
		"loggedin": false,
		"q":        r.URL.Query().Get("q"),
		"repo":     r.URL.Query().Get("repo"),
	})
}
Exemplo n.º 21
0
func awardUser(db *mgo.Database, session sessions.Session, r render.Render, x csrf.CSRF) {
	template := make(map[string]string)
	template["contactUrl"] = os.Getenv("CONTACT_URL")
	template["contactValue"] = os.Getenv("CONTACT_VALUE")
	user := session.Get("user").(string)
	status := checkStatus(db, user)
	if status == 0 {
		template["message"] = "Can't seem to find records of you :/"
		r.HTML(http.StatusUnauthorized, "error", template)
	} else if status == 1 {
		err := userHasAuth(db, user)
		if err != nil {
			log.Println(err)
			template["message"] = "Uh oh! Please report this :("
			r.HTML(http.StatusInternalServerError, "error", template)
		} else {
			r.HTML(http.StatusOK, "form", x.GetToken())
		}
	} else if status == 2 {
		r.HTML(http.StatusOK, "form", x.GetToken())
	} else if status == 3 {
		template["message"] = "Hey buddy, it seems you have been awarded before."
		r.HTML(http.StatusUnauthorized, "error", template)
	}
}
Exemplo n.º 22
0
func CheckErr(r render.Render, err error, str string) bool {
	if err != nil {
		r.HTML(200, "test", str)
		return true
	}
	return false
}
Exemplo n.º 23
0
func IndexHandler(rr render.Render, w http.ResponseWriter, r *http.Request) {
	var pp models.Post
	p := make([]models.Post, 0)
	namefs := utils.Getlistfileindirectory(Pathposts)
	tnamefs := namefs
	vsegopost := len(namefs)
	if len(namefs) != 0 {
		namefs = utils.SorttoDown(namefs)
		if Kolpost > len(namefs) {
			tnamefs = namefs[:]
		} else {
			tnamefs = namefs[:Kolpost]
		}

		for _, namef := range tnamefs {
			pp.GetPostfromFileMd(Pathposts + string(os.PathSeparator) + namef)
			if !pp.GetDraft() { // не отражаются черновики
				p = append(p, pp)
			}
		}
	} else {
		p = append(p, models.Post{Id: "ПОСТОВ НЕТ", Title: "ЭТОТ БЛОГ ПУСТ. ПРИХОДИТЕ ПОЗЖЕ ;)", ContentText: ""})
	}

	rr.HTML(200, "index", &models.PagePost{TitlePage: "Блог проектов kaefik", Posts: p, Postright: vsegopost - Kolpost})
}
Exemplo n.º 24
0
func EditPlant(ren render.Render, db *sql.DB, params martini.Params, t *template.TemplateData) {
	var plant_id string = params["id"]

	if plant_id != "new" {
		plant, err := repository.GetPlant(db, plant_id)

		if err != nil || plant == nil {
			t.SessionMessage.AddDanger("Failed to load plant.")

			ren.Redirect("/plant")

			return
		}

		id, _ := strconv.ParseInt(params["id"], 10, 64)

		plant.PopularNames.Names, err = repository.GetPopularNames(db, id, PLANT)

		t.Data = plant

		t.MediaList = getMediaList(db, PLANT, id)

		ren.HTML(200, "blah/plant/edit", t)
	} else {
		ren.HTML(200, "blah/plant/edit", nil)
	}
}
Exemplo n.º 25
0
Arquivo: main.go Projeto: jf/gwp
//  Handler function for fan-out and fan-in
func mosaic(f UploadForm, r render.Render) {
	t0 := time.Now()
	file, _ := f.Image.Open()
	original, _, _ := image.Decode(file)
	bounds := original.Bounds()
	db := cloneTilesDB()

	// fan-out
	c1 := cut(original, &db, f.TileSize, bounds.Min.X, bounds.Min.Y, bounds.Max.X/2, bounds.Max.Y/2)
	c2 := cut(original, &db, f.TileSize, bounds.Max.X/2, bounds.Min.Y, bounds.Max.X, bounds.Max.Y/2)
	c3 := cut(original, &db, f.TileSize, bounds.Min.X, bounds.Max.Y/2, bounds.Max.X/2, bounds.Max.Y)
	c4 := cut(original, &db, f.TileSize, bounds.Max.X/2, bounds.Max.Y/2, bounds.Max.X, bounds.Max.Y)

	// fan-in
	c := combine(bounds, c1, c2, c3, c4)

	buf1 := new(bytes.Buffer)
	jpeg.Encode(buf1, original, nil)
	originalStr := base64.StdEncoding.EncodeToString(buf1.Bytes())

	t1 := time.Now()
	images := map[string]string{
		"original": originalStr,
		"mosaic":   <-c,
		"duration": fmt.Sprintf("%v ", t1.Sub(t0)),
	}

	r.HTML(200, "results", images)
}
Exemplo n.º 26
0
func (this *HttpWeb) Cluster(params martini.Params, r render.Render) {
	r.HTML(200, "templates/cluster", map[string]interface{}{
		"title":             "cluster",
		"clusterName":       params["clusterName"],
		"autoshow_problems": true,
	})
}
Exemplo n.º 27
0
func userInforEdit(session sessions.Session, r render.Render) {
	user_number := session.Get("user_number")
	user_name := session.Get("user_name")
	if user_number == nil || user_name == nil {
		r.HTML(200, "home", nil)
	}
	var name string
	var number string
	if value, ok := user_name.(string); ok {
		name = value
	} else {
		r.HTML(200, "home", nil)
	}

	if value, ok := user_number.(string); ok {
		number = value
	} else {
		r.HTML(200, "home", nil)
	}

	var user model.User
	user, err := model.GetUserInfo(name, number)
	if err != true {
		r.HTML(200, "home", nil)
	} else {
		r.HTML(200, "userInforEdit", user)
	}
}
Exemplo n.º 28
0
func (this *HttpWeb) About(params martini.Params, r render.Render) {

	r.HTML(200, "templates/about", map[string]interface{}{
		"title":             "about",
		"autoshow_problems": false,
	})
}
Exemplo n.º 29
0
func getRegisterPage(user sessionauth.User, r render.Render) {
	if user.IsAuthenticated() {
		r.Redirect(INDEX_PAGE)
		return
	}
	r.HTML(200, REGISTER_PAGE, nil)
}
Exemplo n.º 30
0
func loginWithNameAndPwd(r *http.Request, res http.ResponseWriter, params martini.Params, session sessions.Session, render render.Render, l *log.Logger) {
	err := r.ParseForm()
	if err != nil {
		l.Printf("ParseForm error: %v\n", err)
		render.HTML(200, "error", "登录失败!")
		return
	}

	username := r.PostFormValue("username")
	//password := r.PostFormValue("password")

	l.Printf("Start logging in, username = %s \n", username)
	//gitlabClient, err := gogitlab.NewGitlabByLogin(constant.GitLabHost, constant.GitLabApiPath, username, password)
	//if err != nil {
	//	l.Printf("Login error: %v\n", err)
	//	render.HTML(200, "error", "登录失败!")
	//	return
	//}
	//gitUser, err := gitlabClient.CurrentUser()
	//if err != nil {
	//	l.Printf("Get current error: %v\n", err)
	//	render.HTML(200, "error", "登录失败!")
	//	return
	//}
	uInfo := &UserInfo{}
	session.Set(constant.UserInfoKey, uInfo)
	render.HTML(200, "dashboard", uInfo)
}