예제 #1
0
// Add adds a new shorturl
func (view View) Add(w http.ResponseWriter, req *http.Request) {
	url := req.FormValue("url")
	if url == "" {
		http.Redirect(w, req, "/", http.StatusFound)
		return
	}
	host := getIP(req)
	if err := checkAllowed(req, url, host); err != nil {
		data := map[string]interface{}{
			csrf.TemplateTag: csrf.TemplateField(req),
			"Error":          err,
		}
		view.renderTemplate(w, "index", data)
		return
	}
	clientid := getClientID(req.Cookies())
	if clientid == "" {
		http.Error(w, "Failed to add shorturl", http.StatusForbidden)
		return
	}
	s, err := Add(view.DB, url, host, clientid)
	if err != nil {
		log.Printf("Failed to add (%s)", err)
		http.Error(w, "Failed to add short url", http.StatusInternalServerError)
		return
	}
	http.Redirect(w, req, s.PreviewURL(), http.StatusFound)
}
예제 #2
0
func (controller *usersController) newPost(rw http.ResponseWriter, req *http.Request) (int, error) {
	err := req.ParseForm()
	if err != nil {
		return http.StatusInternalServerError, err
	}

	decoder := schema.NewDecoder()
	// Ignore unknown keys to prevent errors from the CSRF token.
	decoder.IgnoreUnknownKeys(true)
	formUser := new(viewmodels.UsersEditViewModel)
	err = decoder.Decode(formUser, req.PostForm)
	if err != nil {
		return http.StatusInternalServerError, err
	}

	valErrors := validateUserForm(formUser, false)
	if len(valErrors) > 0 {
		isAuthenticated, user := getCurrentUser(rw, req, controller.authorizer)
		vm := viewmodels.NewUserViewModel(formUser, controller.roles, isAuthenticated, user, valErrors)
		vm.CsrfField = csrf.TemplateField(req)
		return http.StatusOK, controller.newTemplate.Execute(rw, vm)
	}

	var user httpauth.UserData
	user.Username = formUser.Username
	user.Email = formUser.Email
	password := formUser.Password
	user.Role = formUser.Role
	err = controller.authorizer.Register(rw, req, user, password)
	if err != nil {
		return http.StatusInternalServerError, err
	}
	http.Redirect(rw, req, "/settings/users", http.StatusSeeOther)
	return http.StatusSeeOther, nil
}
예제 #3
0
func (controller *profileController) post(rw http.ResponseWriter, req *http.Request) (int, error) {
	err := req.ParseForm()
	if err != nil {
		return http.StatusInternalServerError, err
	}

	decoder := schema.NewDecoder()
	// Ignore unknown keys to prevent errors from the CSRF token.
	decoder.IgnoreUnknownKeys(true)
	formUser := new(viewmodels.ProfileEditViewModel)
	err = decoder.Decode(formUser, req.PostForm)
	if err != nil {
		return http.StatusInternalServerError, err
	}

	valErrors := validateProfileForm(formUser, true)
	if len(valErrors) > 0 {
		isAuthenticated, user := getCurrentUser(rw, req, controller.authorizer)
		vm := viewmodels.EditProfileViewModel(formUser, isAuthenticated, user, valErrors)
		vm.CsrfField = csrf.TemplateField(req)
		return http.StatusOK, controller.template.Execute(rw, vm)
	}

	// Update the user.
	err = controller.authorizer.Update(rw, req, "", formUser.Password, formUser.Email)
	if err != nil {
		return http.StatusInternalServerError, err
	}
	http.Redirect(rw, req, "/", http.StatusSeeOther)
	return http.StatusSeeOther, nil
}
예제 #4
0
파일: wiki.go 프로젝트: supermet/gowiki
func loginHandler(c *gin.Context) {
	redirectTarget := strings.TrimSpace(c.DefaultPostForm("next", c.DefaultQuery("next", "")))
	//	c.HTML(http.StatusOK, "login_page.html", gin.H{csrf.TemplateTag: csrf.TemplateField(c.Request),
	//		"err": "", "user_name": "", "pass": "", "next": redirectTarget})
	renderTemplate(c.Writer, "login_page.html", gin.H{csrf.TemplateTag: csrf.TemplateField(c.Request),
		"err": "", "user_name": "", "pass": "", "next": redirectTarget})
}
예제 #5
0
func (controller *contactsController) editGet(rw http.ResponseWriter, req *http.Request) (int, error) {
	vars := mux.Vars(req)
	contactID, err := strconv.ParseInt(vars["contactID"], 10, 64)
	if err != nil {
		return http.StatusInternalServerError, err
	}
	// Get the contact to edit
	contact := new(database.Contact)
	err = contact.GetContact(controller.DB, contactID)
	if err != nil {
		return http.StatusInternalServerError, err
	}
	isAuthenticated, user := getCurrentUser(rw, req, controller.authorizer)
	contactEdit := new(viewmodels.ContactsEditViewModel)
	contactEdit.Name = contact.Name
	contactEdit.ContactID = contact.ContactID
	contactEdit.EmailAddress = contact.EmailAddress
	contactEdit.SmsNumber = contact.SmsNumber
	contactEdit.EmailActive = contact.EmailActive
	contactEdit.SmsActive = contact.SmsActive
	contactEdit.SelectedSites, err = getContactSiteIDs(controller, contact)
	if err != nil {
		return http.StatusInternalServerError, err
	}

	sites, errGet := getAllSites(controller)
	if errGet != nil {
		return http.StatusInternalServerError, errGet
	}

	vm := viewmodels.EditContactViewModel(contactEdit, sites, isAuthenticated, user, make(map[string]string))
	vm.CsrfField = csrf.TemplateField(req)
	return http.StatusOK, controller.editTemplate.Execute(rw, vm)
}
예제 #6
0
파일: wiki.go 프로젝트: supermet/gowiki
// upload logic
func upload(c *gin.Context) {
	if c.Request.Method == "GET" {
		ct := gin.H{csrf.TemplateTag: csrf.TemplateField(c.Request)}
		form := renderStrTemplate("uploadForm.html", ct)
		renderTemplate(c.Writer, "base.html", updateMap(ct, map[string]interface{}{"title": "Upload", "pageTitle": "Upload Form", "content": form}))
	} else if c.Request.Method == "POST" {
		c.Request.ParseMultipartForm(32 << 20)
		file, handler, err := c.Request.FormFile("uploadfile")
		if err != nil {
			log.Println(err)
			c.Redirect(http.StatusFound, "/upload")
			return
		}
		defer file.Close()
		//		fmt.Fprintf(c.Writer, "%v", handler.Header)
		f, err := os.OpenFile("/tmp/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
		if err != nil {
			log.Println(err)
			c.Redirect(http.StatusFound, "/upload")
			return
		}
		defer f.Close()
		io.Copy(f, file)
		c.Redirect(http.StatusFound, "/upload")
	}
}
예제 #7
0
// SetUser is a HTTP middleware for setting the user and build information.
func SetUser(h http.Handler) http.Handler {
	return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		context.Set(req, csrf.TemplateTag, csrf.TemplateField(req)) // Set CSRF field everywhere
		context.Set(req, "Version", Version)
		context.Set(req, "Branch", Branch)
		context.Set(req, "user", &Account{})
		ses, err := store.Get(req, "evemu")
		if err != nil {
			log.Printf("Failed to get session cookie: %s", err.Error())
			h.ServeHTTP(rw, req)
			return
		}

		if v, ok := ses.Values["user"]; ok {
			if v.(int) == 0 {
				h.ServeHTTP(rw, req)
				return
			}
			//a, err := DBAccountFromID(v.(int))
			a, err := Layer.GetAccountFromID(v.(int)) // TODO: Unsafe, may panic
			if err != nil {
				log.Printf("Failed to get account from id: %s", err.Error())
				h.ServeHTTP(rw, req)
				return
			}
			context.Set(req, "user", a)
		}
		h.ServeHTTP(rw, req)
	})
}
예제 #8
0
func (controller *usersController) newGet(rw http.ResponseWriter, req *http.Request) (int, error) {
	isAuthenticated, user := getCurrentUser(rw, req, controller.authorizer)
	userEdit := new(viewmodels.UsersEditViewModel)
	userEdit.Role = "user"
	vm := viewmodels.NewUserViewModel(userEdit, controller.roles, isAuthenticated, user, make(map[string]string))
	vm.CsrfField = csrf.TemplateField(req)
	return http.StatusOK, controller.newTemplate.Execute(rw, vm)
}
예제 #9
0
파일: mod_http.go 프로젝트: ZiRo-/srndv2
func (self httpModUI) writeTemplateParam(wr http.ResponseWriter, r *http.Request, name string, param map[string]interface{}) {
	if param == nil {
		param = make(map[string]interface{})
	}
	param[csrf.TemplateTag] = csrf.TemplateField(r)
	param["prefix"] = self.prefix
	param["mod_prefix"] = self.mod_prefix
	io.WriteString(wr, template.renderTemplate(name, param))
}
예제 #10
0
//DefaultData returns common to all pages template data
func DefaultData(r *http.Request) map[string]interface{} {
	return map[string]interface{}{
		"ActiveUser":     context.Get(r, "user"),           //signed in models.User
		"Active":         "",                               //active uri shortening for menu item highlight
		"Title":          "",                               //page title:w
		"SignupEnabled":  context.Get(r, "signup_enabled"), //signup route is enabled (otherwise everyone can signup ;)
		csrf.TemplateTag: csrf.TemplateField(r),
	}
}
예제 #11
0
파일: auth.go 프로젝트: echlebek/erickson
func getSignup(ctx context, w http.ResponseWriter, req *http.Request) {
	wrap := map[string]interface{}{
		"Stylesheets":    assets.StylesheetHandlers,
		"Scripts":        assets.ScriptHandlers,
		csrf.TemplateTag: csrf.TemplateField(req),
	}
	if err := assets.Templates["signup.html"].Execute(w, wrap); err != nil {
		log.Println(err)
		http.Error(w, err500, 500)
		return
	}
}
예제 #12
0
func (controller *contactsController) newPost(rw http.ResponseWriter, req *http.Request) (int, error) {
	err := req.ParseForm()
	if err != nil {
		return http.StatusInternalServerError, err
	}

	decoder := schema.NewDecoder()
	// Ignore unknown keys to prevent errors from the CSRF token.
	decoder.IgnoreUnknownKeys(true)
	formContact := new(viewmodels.ContactsEditViewModel)
	err = decoder.Decode(formContact, req.PostForm)
	if err != nil {
		return http.StatusInternalServerError, err
	}

	valErrors := validateContactForm(formContact)
	if len(valErrors) > 0 {
		isAuthenticated, user := getCurrentUser(rw, req, controller.authorizer)
		sites, errGet := getAllSites(controller)
		if errGet != nil {
			return http.StatusInternalServerError, err
		}
		vm := viewmodels.NewContactViewModel(formContact, sites, false,
			isAuthenticated, user, valErrors)
		vm.CsrfField = csrf.TemplateField(req)
		return http.StatusOK, controller.newTemplate.Execute(rw, vm)
	}

	contact := database.Contact{}
	mapContacts(&contact, formContact)
	err = contact.CreateContact(controller.DB)
	if err != nil {
		return http.StatusInternalServerError, err
	}

	//Add contact to any selected sites
	for _, siteSelID := range formContact.SelectedSites {
		err = addContactToSite(controller, contact.ContactID, siteSelID)
		if err != nil {
			return http.StatusInternalServerError, err
		}
	}

	// Refresh the pinger with the changes.
	// TODO: Check whether this contact has been added to any site first.
	err = controller.pinger.UpdateSiteSettings()
	if err != nil {
		return http.StatusInternalServerError, err
	}

	http.Redirect(rw, req, "/settings/contacts", http.StatusSeeOther)
	return http.StatusSeeOther, nil
}
예제 #13
0
파일: wiki.go 프로젝트: supermet/gowiki
func pageRouter(c *gin.Context) {
	var db = connectDB()
	defer db.Close()
	page, err := getPage(db, c.Param("link"))
	ctxt := gin.H{csrf.TemplateTag: csrf.TemplateField(c.Request),
		"title": page.Title_ru, "pageTitle": page.Title_ru, "content": page.Content_ru}
	if err != nil {
		writeError(c, "<b>Извините, но страница не найдена</b>", http.StatusNotFound)
		return
	}
	renderTemplate(c.Writer, "base.html", ctxt)
}
예제 #14
0
func (controller *sitesController) newPost(rw http.ResponseWriter, req *http.Request) (int, error) {
	err := req.ParseForm()
	if err != nil {
		return http.StatusInternalServerError, err
	}

	decoder := schema.NewDecoder()
	// Ignore unknown keys to prevent errors from the CSRF token.
	decoder.IgnoreUnknownKeys(true)
	formSite := new(viewmodels.SitesEditViewModel)
	err = decoder.Decode(formSite, req.PostForm)
	if err != nil {
		return http.StatusInternalServerError, err
	}

	valErrors := validateSiteForm(formSite)
	if len(valErrors) > 0 {
		isAuthenticated, user := getCurrentUser(rw, req, controller.authorizer)
		var contacts database.Contacts
		err = contacts.GetContacts(controller.DB)
		if err != nil {
			return http.StatusInternalServerError, err
		}
		vm := viewmodels.NewSiteViewModel(formSite, contacts, isAuthenticated, user, valErrors)
		vm.CsrfField = csrf.TemplateField(req)
		return http.StatusOK, controller.newTemplate.Execute(rw, vm)
	}

	site := database.Site{}
	viewmodels.MapSiteVMtoDB(formSite, &site)
	err = site.CreateSite(controller.DB)
	if err != nil {
		return http.StatusInternalServerError, err
	}

	//Add any selected contacts
	for _, contactSelID := range formSite.SelectedContacts {
		err = site.AddContactToSite(controller.DB, contactSelID)
		if err != nil {
			return http.StatusInternalServerError, err
		}
	}

	// Refresh the pinger with the changes.
	err = controller.pinger.UpdateSiteSettings()
	if err != nil {
		return http.StatusInternalServerError, err
	}

	http.Redirect(rw, req, "/settings", http.StatusSeeOther)
	return http.StatusSeeOther, nil
}
예제 #15
0
파일: auth.go 프로젝트: echlebek/erickson
func getLogin(ctx context, w http.ResponseWriter, req *http.Request) {
	wrap := struct {
		Stylesheets map[string]http.Handler
		Scripts     map[string]http.Handler
		CSRFField   template.HTML
		BadAuth     bool // The previous request was a failed login attempt
	}{assets.StylesheetHandlers, assets.ScriptHandlers, csrf.TemplateField(req), ctx.badAuth}
	if err := assets.Templates["login.html"].Execute(w, wrap); err != nil {
		log.Println(err)
		http.Error(w, err500, 500)
		return
	}
}
예제 #16
0
func (controller *profileController) get(rw http.ResponseWriter, req *http.Request) (int, error) {
	isAuthenticated, user := getCurrentUser(rw, req, controller.authorizer)
	// Get the user to edit
	editUser, err := controller.authBackend.User(user.Username)
	if err != nil {
		return http.StatusInternalServerError, err
	}
	userEdit := new(viewmodels.ProfileEditViewModel)
	userEdit.Email = editUser.Email
	vm := viewmodels.EditProfileViewModel(userEdit, isAuthenticated, user, make(map[string]string))
	vm.CsrfField = csrf.TemplateField(req)
	return http.StatusOK, controller.template.Execute(rw, vm)
}
예제 #17
0
func (controller *contactsController) newGet(rw http.ResponseWriter, req *http.Request) (int, error) {
	isAuthenticated, user := getCurrentUser(rw, req, controller.authorizer)
	contactEdit := new(viewmodels.ContactsEditViewModel)
	contactEdit.EmailActive = false
	contactEdit.SmsActive = false
	sites, err := getAllSites(controller)
	if err != nil {
		return http.StatusInternalServerError, err
	}
	vm := viewmodels.NewContactViewModel(contactEdit, sites, true,
		isAuthenticated, user, make(map[string]string))
	vm.CsrfField = csrf.TemplateField(req)
	return http.StatusOK, controller.newTemplate.Execute(rw, vm)
}
예제 #18
0
func getReview(ctx context, w http.ResponseWriter, req *http.Request) {
	session, err := ctx.store.Get(req, SessionName)
	if err != nil {
		log.Println(err)
		http.Error(w, err500, 500)
		return
	}
	username, ok := session.Values["username"].(string)
	if !ok {
		http.Error(w, err500, 500)
		return
	}
	review, err := ctx.db.GetReview(ctx.review)
	if err != nil {
		http.NotFound(w, req)
		return
	}
	if len(review.Revisions) <= ctx.revision {
		http.NotFound(w, req)
		return
	}

	res := resource.Review{
		R:               review,
		CurrentRevision: ctx.revision,
		URL:             ctx.reviewURL(),
	}
	wrap := struct {
		resource.Review
		Stylesheets            map[string]http.Handler
		Scripts                map[string]http.Handler
		CSRFField              template.HTML
		Session                *sessions.Session
		ReviewOwnedByUser      bool
		UnpublishedAnnotations int
	}{
		res,
		assets.StylesheetHandlers,
		assets.ScriptHandlers,
		csrf.TemplateField(req),
		session,
		review.Submitter == username,
		review.Revisions[ctx.revision].UnpublishedAnnotationsFor(username),
	}
	if err := assets.Templates["review.html"].Execute(w, wrap); err != nil {
		log.Println(err)
		return
	}
}
예제 #19
0
파일: wiki.go 프로젝트: supermet/gowiki
func indexPageHandler(c *gin.Context) {
	userName := getSessionUser(c.Request)
	var db = connectDB()
	defer db.Close()
	page, _ := getPage(db, "tarify")
	page, _ = getPage(db, "about")
	page, _ = getPage(db, "policy")
	page, _ = getPage(db, "por_rasch_elenr_ur_lic")
	page, _ = getPage(db, "perechen-dokumentov-dlya-zaklyucheniya-dogovora-elektrosnabzheniya")

	//	c.HTML(http.StatusOK, "base.html", gin.H{csrf.TemplateTag: csrf.TemplateField(c.Request),
	//		"userName": userName, "pageTitle": (*page).Title_ru, "content": template.HTML((*page).Content_ru)})
	renderTemplate(c.Writer, "base.html", gin.H{csrf.TemplateTag: csrf.TemplateField(c.Request),
		"title": page.Title_ru, "userName": userName, "pageTitle": page.Title_ru, "content": page.Content_ru})
}
예제 #20
0
func (controller *contactsController) deletePost(rw http.ResponseWriter, req *http.Request) (int, error) {
	err := req.ParseForm()
	if err != nil {
		return http.StatusInternalServerError, err
	}

	decoder := schema.NewDecoder()
	// Ignore unknown keys to prevent errors from the CSRF token.
	decoder.IgnoreUnknownKeys(true)
	formContact := new(viewmodels.ContactsEditViewModel)
	err = decoder.Decode(formContact, req.PostForm)
	if err != nil {
		return http.StatusInternalServerError, err
	}

	valErrors := validateContactForm(formContact)
	if len(valErrors) > 0 {
		isAuthenticated, user := getCurrentUser(rw, req, controller.authorizer)
		var noSites = []database.Site{}
		vm := viewmodels.EditContactViewModel(formContact, noSites, isAuthenticated,
			user, valErrors)
		vm.CsrfField = csrf.TemplateField(req)
		return http.StatusOK, controller.deleteTemplate.Execute(rw, vm)
	}

	// Get the contact to delete
	contact := new(database.Contact)
	err = contact.GetContact(controller.DB, formContact.ContactID)
	if err != nil {
		return http.StatusInternalServerError, err
	}

	mapContacts(contact, formContact)
	err = contact.DeleteContact(controller.DB)
	if err != nil {
		return http.StatusInternalServerError, err
	}

	// Refresh the pinger with the changes.
	// TODO: Check whether this contact is associated with any active site first.
	err = controller.pinger.UpdateSiteSettings()
	if err != nil {
		return http.StatusInternalServerError, err
	}

	http.Redirect(rw, req, "/settings/contacts", http.StatusSeeOther)
	return http.StatusSeeOther, nil
}
예제 #21
0
파일: wiki.go 프로젝트: supermet/gowiki
func authLoginHandler(c *gin.Context) {
	user_name := strings.TrimSpace(c.PostForm("user_name"))
	pass := strings.TrimSpace(c.PostForm("password"))
	redirectTarget := strings.TrimSpace(c.DefaultPostForm("next", c.DefaultQuery("next", "")))
	can_login, err := canLogin(user_name, pass)
	if can_login {
		// .. check credentials ..
		setSessionUser(user_name, c.Writer)
		c.Redirect(http.StatusFound, redirectTarget)
		return
	}
	//	c.HTML(http.StatusOK, "login_page.html", gin.H{csrf.TemplateTag: csrf.TemplateField(c.Request),
	//		"err": err, "user_name": user_name, "pass": pass, "next": redirectTarget})
	renderTemplate(c.Writer, "login_page.html", gin.H{csrf.TemplateTag: csrf.TemplateField(c.Request),
		"err": err, "user_name": user_name, "pass": pass, "next": redirectTarget})
}
예제 #22
0
파일: server.go 프로젝트: thcyron/tracklog
func (s *Server) render(w http.ResponseWriter, r *http.Request, name string) {
	ctx := NewContext(r, w)

	tmpl := s.tmpl
	if tmpl == nil {
		t, err := s.loadTemplates()
		if err != nil {
			panic(err)
		}
		tmpl = t
	}

	data := renderData{
		Title:             ctx.Title(),
		ActiveTab:         ctx.ActiveTab(),
		Breadcrumb:        ctx.Breadcrumb(),
		User:              ctx.User(),
		CSRFToken:         csrf.Token(r),
		CSRFField:         csrf.TemplateField(r),
		MapboxAccessToken: s.config.Server.MapboxAccessToken,
		Version:           tracklog.Version,
		Data:              ctx.Data(),
	}
	if s.config.Server.Development {
		data.Runtime = fmt.Sprintf("%.0fms", time.Now().Sub(ctx.Start()).Seconds()*1000)
	}

	if ctx.NoLayout() {
		if err := tmpl.ExecuteTemplate(w, name+".html", data); err != nil {
			panic(err)
		}
		return
	}

	buf := new(bytes.Buffer)
	if err := tmpl.ExecuteTemplate(buf, name+".html", data); err != nil {
		panic(err)
	}
	data.Content = template.HTML(buf.String())

	w.Header().Set("Content-Type", "text/html; charset=utf-8")

	if err := tmpl.ExecuteTemplate(w, "layout.html", data); err != nil {
		panic(err)
	}
}
예제 #23
0
func (controller *usersController) editGet(rw http.ResponseWriter, req *http.Request) (int, error) {
	vars := mux.Vars(req)
	username := vars["username"]
	// Get the user to edit
	editUser, err := controller.authBackend.User(username)
	if err != nil {
		return http.StatusInternalServerError, err
	}
	isAuthenticated, user := getCurrentUser(rw, req, controller.authorizer)
	userEdit := new(viewmodels.UsersEditViewModel)
	userEdit.Email = editUser.Email
	userEdit.Role = editUser.Role
	userEdit.Username = editUser.Username
	vm := viewmodels.EditUserViewModel(userEdit, controller.roles, isAuthenticated, user, make(map[string]string))
	vm.CsrfField = csrf.TemplateField(req)
	return http.StatusOK, controller.editTemplate.Execute(rw, vm)
}
예제 #24
0
func (controller *sitesController) newGet(rw http.ResponseWriter, req *http.Request) (int, error) {
	isAuthenticated, user := getCurrentUser(rw, req, controller.authorizer)
	siteNew := new(viewmodels.SitesEditViewModel)
	siteNew.IsActive = true
	// Get all of the contacts to display in the table.
	var contacts database.Contacts
	err := contacts.GetContacts(controller.DB)
	if err != nil {
		return http.StatusInternalServerError, err
	}
	// These are strings in the ViewModel.
	siteNew.PingIntervalSeconds = "60"
	siteNew.TimeoutSeconds = "15"
	siteNew.SelectedContacts = []int64{}
	vm := viewmodels.NewSiteViewModel(siteNew, contacts, isAuthenticated, user, make(map[string]string))
	vm.CsrfField = csrf.TemplateField(req)
	return http.StatusOK, controller.newTemplate.Execute(rw, vm)
}
예제 #25
0
func (controller *sitesController) editGet(rw http.ResponseWriter, req *http.Request) (int, error) {
	vars := mux.Vars(req)
	siteID, err := strconv.ParseInt(vars["siteID"], 10, 64)
	if err != nil {
		return http.StatusInternalServerError, err
	}
	// Get the site to edit
	site := new(database.Site)
	err = site.GetSite(controller.DB, siteID)
	if err != nil {
		return http.StatusInternalServerError, err
	}
	// Get all of the contacts to display in the table.
	var contacts database.Contacts
	err = contacts.GetContacts(controller.DB)
	if err != nil {
		return http.StatusInternalServerError, err
	}
	// Also get the site contacts to display in a table.
	err = site.GetSiteContacts(controller.DB, siteID)
	if err != nil {
		return http.StatusInternalServerError, err
	}

	selectedContacts := []int64{}
	for _, contact := range site.Contacts {
		selectedContacts = append(selectedContacts, contact.ContactID)
	}

	isAuthenticated, user := getCurrentUser(rw, req, controller.authorizer)
	siteEdit := new(viewmodels.SitesEditViewModel)
	viewmodels.MapSiteDBtoVM(site, siteEdit)

	siteEdit.SelectedContacts = selectedContacts

	vm := viewmodels.EditSiteViewModel(siteEdit, contacts, isAuthenticated, user, make(map[string]string))
	vm.CsrfField = csrf.TemplateField(req)
	return http.StatusOK, controller.editTemplate.Execute(rw, vm)
}
예제 #26
0
func home(ctx context, w http.ResponseWriter, req *http.Request) {
	session, err := ctx.store.Get(req, SessionName)
	if err != nil {
		log.Println(err)
		http.Error(w, err500, 500)
		return
	}
	sums, err := ctx.db.GetSummaries()
	if err != nil {
		log.Println(err)
		http.Error(w, err500, 500)
		return
	}
	res := make([]resource.ReviewSummary, 0, len(sums))
	for _, s := range sums {
		ctx := ctx
		ctx.review = s.ID
		res = append(res, resource.ReviewSummary{Summary: s, URL: ctx.reviewURL()})
	}
	sort.Sort(resource.SummaryBySubmitTime(res))
	wrap := struct {
		Reviews     []resource.ReviewSummary
		Stylesheets map[string]http.Handler
		Scripts     map[string]http.Handler
		CSRFField   template.HTML
		Session     *sessions.Session
	}{
		res,
		assets.StylesheetHandlers,
		assets.ScriptHandlers,
		csrf.TemplateField(req),
		session,
	}
	if err := assets.Templates["reviews.html"].Execute(w, wrap); err != nil {
		log.Println(err)
		http.Error(w, err500, 500)
		return
	}
}
예제 #27
0
func (controller *contactsController) deleteGet(rw http.ResponseWriter, req *http.Request) (int, error) {
	vars := mux.Vars(req)
	contactID, err := strconv.ParseInt(vars["contactID"], 10, 64)
	if err != nil {
		return http.StatusInternalServerError, err
	}
	// Get the contact to edit
	contact := new(database.Contact)
	err = contact.GetContact(controller.DB, contactID)
	if err != nil {
		return http.StatusInternalServerError, err
	}
	isAuthenticated, user := getCurrentUser(rw, req, controller.authorizer)
	contactDelete := new(viewmodels.ContactsEditViewModel)
	contactDelete.Name = contact.Name
	contactDelete.ContactID = contact.ContactID
	contactDelete.EmailAddress = contact.EmailAddress
	var noSites = []database.Site{}
	vm := viewmodels.EditContactViewModel(contactDelete, noSites, isAuthenticated,
		user, make(map[string]string))
	vm.CsrfField = csrf.TemplateField(req)
	return http.StatusOK, controller.deleteTemplate.Execute(rw, vm)
}
예제 #28
0
파일: mod_http.go 프로젝트: ZiRo-/srndv2
func (self httpModUI) HandleLogin(wr http.ResponseWriter, r *http.Request) {
	privkey := r.FormValue("privkey")
	msg := "failed login: "******"no key"
	} else {
		ok, err := self.CheckKey(privkey)
		if err != nil {
			msg += fmt.Sprintf("%s", err)
		} else if ok {
			msg = "login okay"
			sess := self.getSession(r)
			sess.Values["privkey"] = privkey
			sess.Save(r, wr)
		} else {
			msg += "invalid key"
		}
	}
	self.writeTemplateParam(wr, r, "modlogin_result.mustache", map[string]interface{}{"message": msg, csrf.TemplateTag: csrf.TemplateField(r)})
}
예제 #29
0
func (controller *contactsController) editPost(rw http.ResponseWriter, req *http.Request) (int, error) {
	err := req.ParseForm()
	if err != nil {
		return http.StatusInternalServerError, err
	}

	decoder := schema.NewDecoder()
	// Ignore unknown keys to prevent errors from the CSRF token.
	decoder.IgnoreUnknownKeys(true)
	formContact := new(viewmodels.ContactsEditViewModel)
	err = decoder.Decode(formContact, req.PostForm)
	if err != nil {
		return http.StatusInternalServerError, err
	}

	valErrors := validateContactForm(formContact)
	if len(valErrors) > 0 {
		isAuthenticated, user := getCurrentUser(rw, req, controller.authorizer)
		sites, errGet := getAllSites(controller)
		if errGet != nil {
			return http.StatusInternalServerError, err
		}
		vm := viewmodels.EditContactViewModel(formContact, sites, isAuthenticated,
			user, valErrors)
		vm.CsrfField = csrf.TemplateField(req)
		return http.StatusOK, controller.editTemplate.Execute(rw, vm)
	}

	// Get the contact to update
	contact := new(database.Contact)
	err = contact.GetContact(controller.DB, formContact.ContactID)
	if err != nil {
		return http.StatusInternalServerError, err
	}

	mapContacts(contact, formContact)
	err = contact.UpdateContact(controller.DB)
	if err != nil {
		return http.StatusInternalServerError, err
	}

	contactSiteIDS, getErr := getContactSiteIDs(controller, contact)
	if getErr != nil {
		return http.StatusInternalServerError, getErr
	}
	//Loop selected ones first and if it's not already in the site then add it.
	for _, siteSelID := range formContact.SelectedSites {
		if !int64InSlice(int64(siteSelID), contactSiteIDS) {
			err = addContactToSite(controller, contact.ContactID, siteSelID)
			if err != nil {
				return http.StatusInternalServerError, err
			}
		}
	}

	// Loop existing contact sites and if it's not in the selected items then remove it.
	for _, contactSiteID := range contactSiteIDS {
		if !int64InSlice(int64(contactSiteID), formContact.SelectedSites) {
			err = removeContactFromSite(controller, contact.ContactID, contactSiteID)
			if err != nil {
				return http.StatusInternalServerError, err
			}
		}
	}

	// Refresh the pinger with the changes.
	// TODO: Check whether this contact is associated with any active site first.
	err = controller.pinger.UpdateSiteSettings()
	if err != nil {
		return http.StatusInternalServerError, err
	}

	http.Redirect(rw, req, "/settings/contacts", http.StatusSeeOther)
	return http.StatusSeeOther, nil
}
예제 #30
0
파일: wiki.go 프로젝트: supermet/gowiki
func writeError(c *gin.Context, error string, status int) {
	c.Writer.WriteHeader(status)
	renderTemplate(c.Writer, "base.html", gin.H{csrf.TemplateTag: csrf.TemplateField(c.Request),
		"title": "Ошибка!", "pageTitle": "Ошибка!", "content": error})
}