Esempio n. 1
0
func getAdminListPage(c appengine.Context) string {

	u := user.Current(c)
	if u == nil || !user.IsAdmin(c) {
		url, _ := user.LoginURL(c, "/admin/edit")
		return fmt.Sprintf(`<a href="%s">Sign in or register</a>`, url)
	}

	homepage, _ := template.ParseFiles("site/listpodcast.html")

	q := datastore.NewQuery("Podcast").Order("-PubDate")

	p := make([]Podcast, 0)
	keys, _ := q.GetAll(c, &p)

	for i := 0; i < len(p); i++ {
		p[i].Key = keys[i].Encode()
	}

	e := EditHolder{p}

	html := bytes.NewBufferString("")
	homepage.Execute(html, e)
	return html.String()

}
Esempio n. 2
0
func getAdminEditPage(c appengine.Context, path string) string {

	u := user.Current(c)
	if u == nil || !user.IsAdmin(c) {
		url, _ := user.LoginURL(c, "/admin/edit")
		return fmt.Sprintf(`<a href="%s">Sign in or register</a>`, url)
	}

	//homepage, _ := template.New("template").Funcs(template.FuncMap{"DateToStringAdmin": DateToStringAdmin}).ParseFiles("site/editpodcast.html")

	homepage := template.Must(
		template.
			New("editpodcast.html").
			Funcs(template.FuncMap{"DateToStringAdmin": DateToStringAdmin}).
			ParseFiles("site/editpodcast.html"))

	pA := strings.Split(path, `/`)
	keyString := pA[3]
	key, _ := datastore.DecodeKey(keyString)

	var p Podcast
	datastore.Get(c, key, &p)

	p.Key = key.Encode()
	//p.PubDateFormatted = getValidDate(time.SecondsToUTC(int64(p.PubDate) / 1000000))

	html := bytes.NewBufferString("")
	homepage.Execute(html, p)

	return html.String()

}
Esempio n. 3
0
func gameSrvCronHandler(response http.ResponseWriter, request *http.Request) {
	context := appengine.NewContext(request)
	if !user.IsAdmin(context) {
		http.Error(response, ERR_FORBIDDEN_CRON_URL, http.StatusForbidden)
		return
	}

	query := datastore.NewQuery(model.DB_KIND_GAME_SERVER).
		Filter("Active =", true)
	for queryIterator := query.Run(context); ; {
		var server model.GameServer
		key, err := queryIterator.Next(&server)
		if err == datastore.Done {
			break
		}
		if err != nil {
			log.Fatal(err)
		}
		err = pingGameServer(context, server.Address)
		if err != nil {
			log.Println(err)
			server.Active = false
			server.LastActivationChange = time.Now()
			_, err := datastore.Put(context, key, &server)
			if err != nil {
				log.Fatal(err)
			}
		}
	}
}
Esempio n. 4
0
// Renders a template
func Render(w http.ResponseWriter, r *http.Request, passedTemplate *bytes.Buffer, Statuscode ...int) {
	// Add some HTTP Headers
	if len(Statuscode) == 1 {
		w.WriteHeader(Statuscode[0])
	}

	c := appengine.NewContext(r)
	u := user.Current(c)
	headerdata := HeaderData{}
	if u != nil {
		headerdata.IsLoggedIn = true
		headerdata.Username = u.String()
		if user.IsAdmin(c) {
			headerdata.IsAdmin = true
		}
	}

	// Header
	template.Must(template.ParseFiles("templates/header.html")).Execute(w, headerdata)

	// Now add the passedTemplate
	fmt.Fprintf(w, "%s", string(passedTemplate.Bytes())) // %s = the uninterpreted bytes of the string or slice

	// And now we execute the footer
	template.Must(template.ParseFiles("templates/footer.html")).Execute(w, nil)
}
Esempio n. 5
0
func createPageHeader(title string, w http.ResponseWriter, r *http.Request) *PageHeader {
	pageHeader := &PageHeader{Title: title}
	c := appengine.NewContext(r)
	u := user.Current(c)
	if u == nil {
		url, err := user.LoginURL(c, r.URL.String())
		if err != nil {
			panic("user.LoginURL error: " + err.Error())
		}
		pageHeader.UserURL = url
		pageHeader.UserLabel = "Login"
		pageHeader.IsAdmin = false

	} else {
		url, err := user.LogoutURL(c, r.URL.String())
		if err != nil {
			panic("user.LogoutURL error: " + err.Error())
		}
		pageHeader.UserURL = url
		pageHeader.UserLabel = "Logout"
		pageHeader.LoginMessage = "Hello, " + u.String() + "!"
		pageHeader.IsAdmin = user.IsAdmin(c)
		w.Header().Set("Pragma", "no-cache")
	}

	return pageHeader
}
Esempio n. 6
0
func handleMsgDelete(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if !user.IsAdmin(c) {
		//Redirect
		w.WriteHeader(http.StatusBadRequest)
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		io.WriteString(w, "Sorry, only site admin can do this.")
		return
	}
	id, err := strconv.ParseInt(r.FormValue("id"), 0, 64)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		io.WriteString(w, "BadRequest")
		return
	}
	k := datastore.NewKey(c, "aMessage", "", id, nil)
	err = datastore.Delete(c, k)
	if err != nil {
		w.WriteHeader(http.StatusNotFound)
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		io.WriteString(w, "NotFound")
		return
	}
	DecCount(w, r)
	w.WriteHeader(http.StatusOK)
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	io.WriteString(w, "OK")
	return
}
func admin(w http.ResponseWriter, r *http.Request) {
	// handle requests to "/admin/"
	c := appengine.NewContext(r)
	billQuery := datastore.NewQuery("Bill").Order("-Session").Order("-Number")
	bills := make([]bill.Bill, 0)
	if _, err := billQuery.GetAll(c, &bills); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	senatorQuery := datastore.NewQuery("Senator").Order("-Name")
	senators := make([]senator.Senator, 0)
	if _, err := senatorQuery.GetAll(c, &senators); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	login, _ := user.LoginURL(c, "/")
	logout, _ := user.LogoutURL(c, "/")
	pageInfo := PageInfo{Title: "Administrator Dashboard",
		User:      user.Current(c),
		Admin:     user.IsAdmin(c),
		LoginURL:  login,
		LogoutURL: logout,
		Bills:     bills,
		Senators:  senators}
	if err := adminTemplate.Execute(w, pageInfo); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}
Esempio n. 8
0
func CurrentUser(c appengine.Context) *User {
	appengineUser := user.Current(c)
	if appengineUser == nil {
		return Anonymous
	}

	u, err := GetUserByUserId(c, appengineUser.ID)
	if err != nil {
		return Anonymous
	}

	if u == nil {
		u, err = CreateUserFromAppengine(c, appengineUser)
		if err != nil {
			return Anonymous
		}
	}

	if user.IsAdmin(c) && !u.IsAdmin {
		u.IsAdmin = true
		// ignore error
		entity.Put(c, u)
	}

	return u
}
Esempio n. 9
0
func handlePost(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if r.Method != "GET" || r.URL.Path != "/post" {
		serve404(w)
		return
	}
	c := appengine.NewContext(r)
	u := user.Current(c)
	if u == nil {
		url, err := user.LoginURL(c, r.URL.String())
		if err != nil {
			serveError(c, w, err)
			return
		}
		w.Header().Set("Location", url)
		w.WriteHeader(http.StatusFound)
		return
	}
	if !user.IsAdmin(c) {
		serve404(w)
		return
	}
	uploadURL, err := blobstore.UploadURL(c, "/upload", nil)
	if err != nil {
		serveError(c, w, err)
		return
	}
	err = postTemplate.Execute(w, uploadURL)
	if err != nil {
		serveError(c, w, err)
	}
}
Esempio n. 10
0
func CheckPerm(w http.ResponseWriter, r *http.Request, op byte) (err error) {

	c := appengine.NewContext(r)
	u := user.Current(c)

	if u == nil {
		redirectLogin(w, r)
		return errors.New("user not exits")
	}

	if !user.IsAdmin(c) {
		// Si no es admin, deberiamos buscarlo en nuestra base
		// de datos de usuarios permitidos y comprobar si
		// con su rol puede hacer dicha operación
		// De esa busqueda calculamos la variable perm y la comparamos
		// con op

		/*if !IsAllowed(perm,op){
		redirectLogin(w,r)
		return
		}*/

		redirectLogin(w, r)
		return errors.New("user has not perm for the operation")
	}

	// Si es admin puede cualquier cosa
	return nil
}
Esempio n. 11
0
func admin(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	u := user.Current(c)

	if u == nil {
		url, err := user.LoginURL(c, r.URL.String())

		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Location", url)
		w.WriteHeader(http.StatusFound)
		return
	}

	/* Si el usuario es administrador. */
	if user.IsAdmin(c) {

		categorias := getCategorias(c, 10)

		contenido := ContenidoAdmin{categorias}

		/* Ejecuto el template y envio la salida al Writer. */
		err2 := adminTpl.Execute(w, contenido)

		if err2 != nil {
			http.Error(w, err2.Error(), http.StatusInternalServerError)
		}
	} else {
		fmt.Fprint(w, "El usuario no es admin.")
	}
}
Esempio n. 12
0
func getAdminAddPage(c appengine.Context) string {

	u := user.Current(c)
	if u == nil || !user.IsAdmin(c) {
		url, _ := user.LoginURL(c, "/admin/add")
		return fmt.Sprintf(`<a href="%s">Sign in or register</a>`, url)
	}

	//homepage, _ := template.ParseFile("site/editpodcast.html")

	//homepage, _ := template.New("template").Funcs(template.FuncMap{"DateToStringAdmin": DateToStringAdmin}).ParseFiles("site/editpodcast.html")
	//homepage, _ := template.ParseFiles("site/editpodcast.html")

	homepage := template.Must(
		template.
			New("editpodcast.html").
			Funcs(template.FuncMap{"DateToStringAdmin": DateToStringAdmin}).
			ParseFiles("site/editpodcast.html"))

	html := bytes.NewBufferString("")
	p := Podcast{}
	homepage.Execute(html, p)

	//c := appengine.NewContext(r)
	c.Infof("TESTING: %v", html.String())

	return html.String()

}
Esempio n. 13
0
func pollHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	parts := strings.Split(r.URL.Path, "/")
	if len(parts) != 3 {
		http.Error(w, "Must provide a poll id.", http.StatusBadRequest)
		return
	}
	poll, err := fetchPoll(c, parts[2])
	if err != nil {
		writeError(c, w, err)
		return
	}

	vote, _ := fetchVote(c, poll)

	options, err := fetchOptions(c, poll)
	if err != nil {
		writeError(c, w, err)
		return
	}

	u := user.Current(c)

	v := map[string]interface{}{
		"poll":    poll,
		"options": options,
		"super":   user.IsAdmin(c) || poll.Owner == u.Id,
		"pollid":  parts[2],
		"userid":  u.Id,
		"vote":    vote,
	}

	templates.Execute(w, "poll.html", v)
}
Esempio n. 14
0
/*
 * Get user info
 *
 * @param c (appengine.Context)
 *
 * @return (string)
 */
func getUserInfo(c appengine.Context) *UserData {
	u := user.Current(c)
	if u != nil {
		return &UserData{Nickname: u.String(), Email: u.Email, IsAdmin: user.IsAdmin(c)}
	}

	return nil
}
Esempio n. 15
0
func (o *ownerAuth) AllowedAccess(req *http.Request) auth.Operation {
	c := appengine.NewContext(req)
	if user.IsAdmin(c) {
		return auth.OpAll
	}
	if o.fallback != nil {
		return o.fallback.AllowedAccess(req)
	}
	return 0
}
Esempio n. 16
0
// Protect a URL by forcing a login.
func AdminAuth(req *f.Request, res *f.Response, next func()) {
	context := appengine.NewContext(req.Request.Request)
	u := user.Current(context)
	if u == nil || user.IsAdmin(context) == false {
		url, _ := user.LoginURL(context, req.Url)
		res.Redirect(url)
		return
	}
	// context.Debugf("User: %v", u.String())
}
Esempio n. 17
0
//RenderLayout inserts template with given name into the layout and sets the title and pipeline.
//The template should be loaded inside templates variable
//If any arguments are provided after the context, they will be treated as links
//to JavaScript scripts to load in the header of the template.
func RenderLayout(tmpl string, title string, data interface{}, c Context, jsIncludes ...string) {
	RenderTemplate("header.html", struct {
		Title      string
		JsIncludes []string
		Admin      bool
		AppName    string
	}{title, jsIncludes, user.IsAdmin(c), C.Title}, c)
	RenderTemplate(tmpl, data, c)
	RenderTemplate("footer.html", template.HTML(C.Footer), c)
}
Esempio n. 18
0
func adminOnly(next myHandler) myHandler {
	return func(ctx *Context, w http.ResponseWriter, r *http.Request) error {
		if !user.IsAdmin(ctx.c) {
			http.Redirect(w, r, "/bills/dashboard", http.StatusFound)
			return nil
		}

		return next(ctx, w, r)
	}
}
Esempio n. 19
0
func handleLogin(ctx *Context, w http.ResponseWriter, r *http.Request) error {
	if user.IsAdmin(ctx.c) {
		ctx.Flash("Welcome admin user!")
		ctx.Redirect("/admin/dashboard")
		return nil
	}

	ctx.Flash("Welcome regular user!")
	ctx.Redirect("/bills/dashboard")
	return nil
}
Esempio n. 20
0
func NewContext(w http.ResponseWriter, r *http.Request) *Context {
	c := &Context{
		w: w,
		r: r,
	}

	c.c = appengine.NewContext(r)
	c.user = user.Current(c.c)
	c.admin = user.IsAdmin(c.c)

	return c
}
Esempio n. 21
0
// adminHandler is the rapper handler for the admin section. App Engine
// itself should ensure that the `/admin/*` pages can only be accessed
// when an Administrator, but redudance never hurt!
func adminHandler(fn http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		c := appengine.NewContext(r)
		if !user.IsAdmin(c) {
			// Gives an error, non-admin users shouldn't be here! Also logs it
			errorGenerator(w, "Not allowed.", 401)
			c.Errorf("adminHandler: Unauthorized user from `%v` tried to access: %v", r.RemoteAddr, r.RawURL)
			return
		} else {
			fn(w, r)
		}
	}
}
Esempio n. 22
0
func Login(r *http.Request) (bool, string, string, error) {
	c := appengine.NewContext(r)
	u := user.Current(c)
	if u == nil {
		url, err := user.LoginURL(c, r.URL.String())
		if err != nil {
			return false, "", "", err
		}
		return false, "", url, nil
	}

	return user.IsAdmin(c), u.String(), "", nil
}
Esempio n. 23
0
func newBill(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	if r.Method == "GET" {
		// display form for adding a new bill
		login, _ := user.LoginURL(c, "/")
		logout, _ := user.LogoutURL(c, "/")
		pageInfo := PageInfo{
			Title:     "New Bill",
			User:      user.Current(c),
			Admin:     user.IsAdmin(c),
			LoginURL:  login,
			LogoutURL: logout,
		}
		if err := newTemplate.Execute(w, pageInfo); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}

	} else if r.Method == "POST" {
		// add a new bill to the datastore
		// first, get a unique id for the bill that is
		// one more than the highest existing id
		id := getUniqueBillId(w, r)
		if id < 0 {
			http.Error(w, "Problem with getUniqueBillId", http.StatusInternalServerError)
		}
		// construct the bill from the form values
		session, _ := strconv.Atoi(r.FormValue("session"))
		number, _ := strconv.Atoi(r.FormValue("number"))
		bill := Bill{
			Session:   session,
			Number:    number,
			Name:      r.FormValue("name"),
			Type:      r.FormValue("type"),
			Committee: r.FormValue("committee"),
			Status:    r.FormValue("status"),
			ID:        id,
			PDFURL:    r.FormValue("PDFURL"),
		}
		// add bill to the datastore
		_, err := datastore.Put(c, datastore.NewIncompleteKey(c, "Bill", nil), &bill)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		http.Redirect(w, r, "/admin/", http.StatusFound)
	}
}
Esempio n. 24
0
func putTweet(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	requireLogin(c, w, r.URL.String())
	if user.IsAdmin(c) {
		body, readErr := ioutil.ReadAll(r.Body)
		if readErr != nil {
			fmt.Fprintf(w, "Read Error: %s", readErr)
			return
		}
		saveErr := saveTweet(c, "tweet", body)
		if saveErr != nil {
			fmt.Fprintf(w, "Save Error: %s", saveErr)
			return
		}
	}
}
Esempio n. 25
0
func CreateUserAppengine(c appengine.Context, appengineUser *user.User) (*User, error) {
	u := &User{
		Key: UserKey(c, appengineUser.ID),

		Name:       appengineUser.String(),
		Email:      appengineUser.Email,
		AuthDomain: appengineUser.AuthDomain,
		IsAdmin:    user.IsAdmin(c),

		FederatedIdentity: appengineUser.FederatedIdentity,
		FederatedProvider: appengineUser.FederatedProvider,
	}
	if err := SaveUser(c, u); err != nil {
		c.Errorf("SaveUser error: " + err.Error())
	}
	return u, nil
}
Esempio n. 26
0
func setUser(r *http.Request) *UserType {
	User := UserType{}
	c := appengine.NewContext(r)
	u := user.Current(c)
	if u != nil {
		User.Nick = u.String()
		User.Email = u.Email
		User.IsAdmin = user.IsAdmin(c)
		User.Context = c
	} else {
		User.Nick = ""
		User.Email = ""
		User.IsAdmin = false
		User.Context = c
	}
	return &User
}
Esempio n. 27
0
func ExportOpml(c mpg.Context, w http.ResponseWriter, r *http.Request) {
	gn := goon.FromContext(c)
	var u User
	if uid := r.FormValue("u"); len(uid) != 0 && user.IsAdmin(c) {
		u = User{Id: uid}
	} else {
		cu := user.Current(c)
		u = User{Id: cu.ID}
	}
	ud := UserData{Id: "data", Parent: gn.Key(&u)}
	if err := gn.Get(&u); err != nil {
		serveError(w, err)
		return
	}
	gn.Get(&ud)
	downloadOpml(w, ud.Opml, u.Email)
}
func addSenator(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if r.Method != "POST" {
		login, _ := user.LoginURL(c, "/")
		logout, _ := user.LogoutURL(c, "/")
		pageInfo := PageInfo{
			Title:     "New Senator",
			User:      user.Current(c),
			Admin:     user.IsAdmin(c),
			LoginURL:  login,
			LogoutURL: logout,
		}
		if err := newTemplate.Execute(w, pageInfo); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
		return
	}

	q := datastore.NewQuery("Senator").Order("-ID").Limit(1)
	senators := make([]Senator, 0, 1)
	if _, err := q.GetAll(c, &senators); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	var id int
	if len(senators) == 0 {
		id = 1
	} else {
		id = senators[0].ID + 1
	}

	senator := Senator{
		ID:        id,
		Name:      r.FormValue("name"),
		Committee: r.FormValue("committee"),
		Email:     r.FormValue("email"),
		Location:  r.FormValue("location"),
	}
	_, err := datastore.Put(c, datastore.NewIncompleteKey(c, "Senator", nil), &senator)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	http.Redirect(w, r, "/admin/", http.StatusFound)
}
Esempio n. 29
0
File: add.go Progetto: npk/trailk
func Add(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	trailk := context.NewContext()
	keyTool := key.NewTool(c)

	if !user.IsAdmin(c) {
		controller.ServerError(http.StatusForbidden, w, errors.New(
			"Only administrator can access this page"))

		return
	}

	data := &sourceAddData{
		Name: r.FormValue("Name"),
		URL:  r.FormValue("URL"),
		Type: r.FormValue("Type"),
	}

	if strings.ToUpper(r.Method) == "POST" {
		fetcher := urlfetch.NewURLFetcher(c)

		sourceKey, err := addSource(trailk, c, keyTool, fetcher, data)

		if err != nil {
			data.Error = err
		} else {
			http.Redirect(w, r, fmt.Sprintf(
				"/source?id=%d&type=%s", sourceKey.IntID(), data.Type), 301)

			return
		}
	}

	buf, tplErr := template.Render("sources-add", data)

	if tplErr != nil {
		controller.ServerError(http.StatusInternalServerError, w, tplErr)

		return
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.WriteHeader(http.StatusOK)
	w.Write(buf.Bytes())
}
Esempio n. 30
0
func CreateUserFromAppengine(c appengine.Context, appengineUser *user.User) (*User, error) {
	u := &User{
		UserId: appengineUser.ID,

		Name:       appengineUser.String(),
		Email:      appengineUser.Email,
		AuthDomain: appengineUser.AuthDomain,
		IsAdmin:    user.IsAdmin(c),

		FederatedIdentity: appengineUser.FederatedIdentity,
		FederatedProvider: appengineUser.FederatedProvider,
	}
	initUser(u)
	if err := entity.Put(c, u); err != nil {
		return nil, err
	}
	return u, nil
}