// HandleUpdate handles the POST of the form to update a user func HandleUpdate(context router.Context) error { // Find the user user, err := users.Find(context.ParamInt("id")) if err != nil { return router.NotFoundError(err) } // Authorise update user err = authorise.ResourceAndAuthenticity(context, user) if err != nil { return router.NotAuthorizedError(err) } // Get the params params, err := context.Params() if err != nil { return router.InternalError(err) } // Clean params further for customers, they may only update email, password, key allowedParams := params.Map() u := authorise.CurrentUser(context) if !u.Admin() { // allowedParams = params.Clean(users.AllowedParamsCustomer()) } err = user.Update(allowedParams) if err != nil { return router.InternalError(err) } // Redirect to user return router.Redirect(context, user.URLShow()) }
// HandleShow displays a single story func HandleShow(context router.Context) error { // Find the story story, err := stories.Find(context.ParamInt("id")) if err != nil { return router.InternalError(err) } // Redirect requests to the canonical url if context.Path() != story.URLShow() { return router.Redirect(context, story.URLShow()) } // Find the comments for this story // Fetch the comments q := comments.Where("story_id=?", story.Id).Order(comments.RankOrder) rootComments, err := comments.FindAll(q) if err != nil { return router.InternalError(err) } // Render the template view := view.New(context) view.AddKey("story", story) view.AddKey("meta_title", story.Name) view.AddKey("meta_desc", story.Summary) view.AddKey("meta_keywords", story.Name) view.AddKey("comments", rootComments) return view.Render() }
// POST pages/create func HandleCreate(context router.Context) error { // Authorise err := authorise.Path(context) if err != nil { return router.NotAuthorizedError(err) } // Setup context params, err := context.Params() if err != nil { return router.InternalError(err) } id, err := pages.Create(params.Map()) if err != nil { context.Logf("#info Failed to create page %v", params) return router.InternalError(err) } // Log creation context.Logf("#info Created page id,%d", id) // Redirect to the new page p, err := pages.Find(id) if err != nil { context.Logf("#error Error creating page,%s", err) } return router.Redirect(context, p.URLIndex()) }
// HandleUpdate or PUT /users/1/update func HandleUpdate(context router.Context) error { // Find the user id := context.ParamInt("id") user, err := users.Find(id) if err != nil { context.Logf("#error Error finding user %s", err) return router.NotFoundError(err) } // Authorise err = authorise.ResourceAndAuthenticity(context, user) if err != nil { return router.NotAuthorizedError(err) } // Get the params params, err := context.Params() if err != nil { return router.InternalError(err) } context.Logf("PARAMS RECD:%v", params) err = user.Update(params.Map()) if err != nil { return router.InternalError(err) } // Redirect to user return router.Redirect(context, user.URLShow()) }
// HandleCreate handles the POST of the create form for pages func HandleCreate(context router.Context) error { // Authorise err := authorise.ResourceAndAuthenticity(context, nil) if err != nil { return router.NotAuthorizedError(err) } // Setup context params, err := context.Params() if err != nil { return router.InternalError(err) } id, err := pages.Create(params.Map()) if err != nil { return router.InternalError(err) } // Log creation context.Logf("#info Created page id,%d", id) // Redirect to the new page m, err := pages.Find(id) if err != nil { return router.InternalError(err) } return router.Redirect(context, m.URLIndex()) }
// HandleShow displays a single story func HandleShow(context router.Context) error { // Find the story story, err := stories.Find(context.ParamInt("id")) if err != nil { return router.InternalError(err) } // Find the comments for this story // Fetch the comments q := comments.Where("story_id=?", story.Id).Order(comments.RankOrder) rootComments, err := comments.FindAll(q) if err != nil { return router.InternalError(err) } // Render the template view := view.New(context) view.AddKey("story", story) view.AddKey("meta_title", story.Name) view.AddKey("meta_desc", story.Summary) view.AddKey("meta_keywords", story.Name) view.AddKey("comments", rootComments) view.AddKey("authenticity_token", authorise.CreateAuthenticityToken(context)) return view.Render() }
// HandleUpdate responds to POST /comments/update func HandleUpdate(context router.Context) error { // Find the comment comment, err := comments.Find(context.ParamInt("id")) if err != nil { return router.NotFoundError(err) } // Authorise update comment, check auth token err = authorise.ResourceAndAuthenticity(context, comment) if err != nil { return router.NotAuthorizedError(err) } // Update the comment from params params, err := context.Params() if err != nil { return router.InternalError(err) } // Clean params according to role accepted := comments.AllowedParams() if authorise.CurrentUser(context).Admin() { accepted = comments.AllowedParamsAdmin() } cleanedParams := params.Clean(accepted) err = comment.Update(cleanedParams) if err != nil { return router.InternalError(err) } // Redirect to comment return router.Redirect(context, comment.URLShow()) }
// validateParams checks these params pass validation checks func validateParams(params map[string]string) error { err := validate.Length(params["name"], 0, 100) if err != nil { return router.InternalError(err, "Name invalid length", "Your name must be between 0 and 100 characters long") } err = validate.Length(params["key"], 1000, 5000) if err != nil { return router.InternalError(err, "Key too short", "Your key must be at least 1000 characters long") } // Password may be blank if len(params["password"]) > 0 { // check length err := validate.Length(params["password"], 5, 100) if err != nil { return router.InternalError(err, "Password too short", "Your password must be at least 5 characters") } // HASH the password before storage at all times hash, err := auth.HashPassword(params["password"]) if err != nil { return err } params["password"] = hash } else { // Delete password param delete(params, "password") } return err }
// HandleUpdate handles POST or PUT /images/1/update func HandleUpdate(context router.Context) error { // Find the image image, err := images.Find(context.ParamInt("id")) if err != nil { context.Logf("#error Error finding image %s", err) return router.NotFoundError(err) } // Authorise err = authorise.Resource(context, image) if err != nil { return router.NotAuthorizedError(err) } // Update the image params, err := context.Params() if err != nil { return router.InternalError(err) } err = image.Update(params.Map()) if err != nil { return router.InternalError(err) } // We redirect back to source if redirect param is set return router.Redirect(context, image.URLUpdate()) }
// HandleUpdate handles the POST of the form to update a post func HandleUpdate(context router.Context) error { // Find the post post, err := posts.Find(context.ParamInt("id")) if err != nil { return router.NotFoundError(err) } // Authorise update post err = authorise.Resource(context, post) if err != nil { return router.NotAuthorizedError(err) } // Update the post from params params, err := context.Params() if err != nil { return router.InternalError(err) } err = post.Update(params.Map()) if err != nil { return router.InternalError(err) } // Redirect to post return router.Redirect(context, post.URLShow()) }
// HandleUpdate handles POST or PUT /pages/1/update func HandleUpdate(context router.Context) error { // Find the page page, err := pages.Find(context.ParamInt("id")) if err != nil { return router.NotFoundError(err) } // Authorise updating the page err = authorise.Resource(context, page) if err != nil { return router.NotAuthorizedError(err) } // Update the page from params params, err := context.Params() if err != nil { return router.InternalError(err) } err = page.Update(params.Map()) if err != nil { return router.InternalError(err) } // We then find the page again, and retreive the new Url, in case it has changed during update page, err = pages.Find(context.ParamInt("id")) if err != nil { return router.NotFoundError(err) } // Redirect to page url return router.Redirect(context, page.Url) }
// HandleUpdate handles the POST of the form to update a page func HandleUpdate(context router.Context) error { // Find the page page, err := pages.Find(context.ParamInt("id")) if err != nil { return router.NotFoundError(err) } // Authorise update page err = authorise.ResourceAndAuthenticity(context, page) if err != nil { return router.NotAuthorizedError(err) } // Update the page from params params, err := context.Params() if err != nil { return router.InternalError(err) } err = page.Update(params.Map()) if err != nil { return router.InternalError(err) } // Redirect to page return router.Redirect(context, page.URLShow()) }
// HandleUpdate responds to POST /comments/update func HandleUpdate(context router.Context) error { // Find the comment comment, err := comments.Find(context.ParamInt("id")) if err != nil { return router.NotFoundError(err) } // Authorise update comment, check auth token err = authorise.ResourceAndAuthenticity(context, comment) if err != nil { return router.NotAuthorizedError(err) } // Update the comment from params params, err := context.Params() if err != nil { return router.InternalError(err) } err = comment.Update(params.Map()) if err != nil { return router.InternalError(err) } // Redirect to comment return router.Redirect(context, comment.URLShow()) }
// POST users/create func HandleCreate(context router.Context) error { // Authorise err := authorise.Path(context) if err != nil { return router.NotAuthorizedError(err) } // Setup context params, err := context.Params() if err != nil { return router.InternalError(err) } // We should check for duplicates in here id, err := users.Create(params.Map()) if err != nil { return router.InternalError(err, "Error", "Sorry, an error occurred creating the user record.") } else { context.Logf("#info Created user id,%d", id) } // Redirect to the new user p, err := users.Find(id) if err != nil { return router.InternalError(err, "Error", "Sorry, an error occurred finding the new user record.") } return router.Redirect(context, p.URLIndex()) }
// HandleUpdate serves POST or PUT /tags/1/update func HandleUpdate(context router.Context) error { // Find the tag tag, err := tags.Find(context.ParamInt("id")) if err != nil { return router.NotFoundError(err) } // Authorise err = authorise.Resource(context, tag) if err != nil { return router.NotAuthorizedError(err) } // Update the tag params, err := context.Params() if err != nil { return router.InternalError(err) } err = tag.Update(params.Map()) if err != nil { return router.InternalError(err) } // Redirect to tag return router.Redirect(context, tag.URLShow()) }
// HandleUpdateShow handles the POST of the form to update a file func HandleUpdate(context router.Context) error { // Find the file file, err := files.Find(context.ParamInt("id")) if err != nil { return router.NotFoundError(err) } // Authorise update file err = authorise.Resource(context, file) if err != nil { return router.NotAuthorizedError(err) } // Update the file from params params, err := context.Params() if err != nil { return router.InternalError(err) } // Find the to user, by querying users on username or email // Set the user id if found, else return 404 error, user not found // TODO: Make *sure* this only accepts the params we want err = file.Update(params.Map()) if err != nil { return router.InternalError(err) } // Redirect to file return router.Redirect(context, file.URLShow()) }
// HandleUpdate handles the POST of the form to update a story func HandleUpdate(context router.Context) error { // Find the story story, err := stories.Find(context.ParamInt("id")) if err != nil { return router.NotFoundError(err) } // Authorise update story err = authorise.ResourceAndAuthenticity(context, story) if err != nil { return router.NotAuthorizedError(err) } // Update the story from params params, err := context.Params() if err != nil { return router.InternalError(err) } err = story.Update(params.Map()) if err != nil { return err // Create returns a router.Error } err = updateStoriesRank() if err != nil { return router.InternalError(err) } // Redirect to story return router.Redirect(context, story.URLShow()) }
// HandleUpdate or PUT /users/1/update func HandleUpdate(context router.Context) error { // Find the user id := context.ParamInt("id") user, err := users.Find(id) if err != nil { context.Logf("#error Error finding user %s", err) return router.NotFoundError(err) } // Authorise err = authorise.Resource(context, user) if err != nil { return router.NotAuthorizedError(err) } // We expect only one image, what about replacing the existing when updating? // At present we just create a new image files, err := context.ParamFiles("image") if err != nil { return router.InternalError(err) } // Get the params params, err := context.Params() if err != nil { return router.InternalError(err) } var imageID int64 if len(files) > 0 { fileHandle := files[0] // Create an image (saving the image representation on disk) imageParams := map[string]string{"name": user.Name, "status": "100"} imageID, err = images.Create(imageParams, fileHandle) if err != nil { return router.InternalError(err) } params.Set("image_id", fmt.Sprintf("%d", imageID)) delete(params, "image") } err = user.Update(params.Map()) if err != nil { return router.InternalError(err) } // Redirect to user return router.Redirect(context, user.URLShow()) }
// addStoryVote adjusts the story points, and adds a vote record for this user func addStoryVote(story *stories.Story, user *users.User, ip string, delta int64) error { if story.Points < -5 && delta < 0 { return router.InternalError(nil, "Vote Failed", "Story is already hidden") } // Update the story points by delta err := story.Update(map[string]string{"points": fmt.Sprintf("%d", story.Points+delta)}) if err != nil { return router.InternalError(err, "Vote Failed", "Sorry your adjust vote points") } return recordStoryVote(story, user, ip, delta) }
// HandleIndex serves a get request at /pages func HandleIndex(context router.Context) error { // Authorise err := authorise.Path(context) if err != nil { return router.NotAuthorizedError(err) } // Fetch the pages q := pages.Query().Order("url asc") // Filter if necessary filter := context.Param("filter") if len(filter) > 0 { filter = strings.Replace(filter, "&", "", -1) filter = strings.Replace(filter, " ", "", -1) filter = strings.Replace(filter, " ", " & ", -1) q.Where("(to_tsvector(name) || to_tsvector(summary) || to_tsvector(url) @@ to_tsquery(?) )", filter) } pageList, err := pages.FindAll(q) if err != nil { context.Logf("#error Error indexing pages %s", err) return router.InternalError(err) } // Serve template view := view.New(context) view.AddKey("filter", filter) view.AddKey("pages", pageList) return view.Render() }
// HandleHome displays a list of stories using gravity to order them // used for the home page for gravity rank see votes.go // responds to GET / func HandleHome(context router.Context) error { // Build a query q := stories.Query().Limit(listLimit) // Select only above 0 points, Order by rank, then points, then name q.Where("points > 0").Order("rank desc, points desc, id desc") // Set the offset in pages if we have one page := int(context.ParamInt("page")) if page > 0 { q.Offset(listLimit * page) } // Fetch the stories results, err := stories.FindAll(q) if err != nil { return router.InternalError(err) } // Render the template view := view.New(context) setStoriesMetadata(view, context.Request()) view.AddKey("page", page) view.AddKey("stories", results) view.Template("stories/views/index.html.got") if context.Param("format") == ".xml" { view.Layout("") view.Template("stories/views/index.xml.got") } return view.Render() }
// HandleHome displays a list of stories using gravity to order them // used for the home page for gravity rank see votes.go func HandleHome(context router.Context) error { // Build a query q := stories.Query().Limit(listLimit) // Select only above 0 points, Order by rank, then points, then name q.Where("points > 0").Order("rank desc, points desc, id desc") // Fetch the stories results, err := stories.FindAll(q) if err != nil { return router.InternalError(err) } // Render the template view := view.New(context) view.AddKey("stories", results) view.AddKey("meta_title", "Golang News") view.AddKey("meta_desc", "News for Go Hackers, in the style of Hacker News. A curated selection of the latest links about the Go programming language.") view.AddKey("meta_keywords", "golang news, blog, links, go developers, go web apps, web applications, fragmenta") view.AddKey("authenticity_token", authorise.CreateAuthenticityToken(context)) view.Template("stories/views/index.html.got") return view.Render() }
// HandleHome serves a get request at / func HandleHome(context router.Context) error { // Setup context for template view := view.New(context) // Authorise err := authorise.Path(context) if err != nil { return router.NotAuthorizedError(err) } // If nothing exists, redirect to set up page if missingUsersAndPages() { return router.Redirect(context, "/fragmenta/setup") } page, err := pages.Find(1) if err != nil { return router.InternalError(err) } view.AddKey("page", page) view.AddKey("meta_title", page.Name) view.AddKey("meta_desc", page.Summary) view.AddKey("meta_keywords", page.Keywords) return view.Render() }
// HandleDownload sends a single file func HandleDownload(context router.Context) error { // Find the file file, err := files.Find(context.ParamInt("id")) if err != nil { return router.InternalError(err) } // Authorise access to this file - only the file owners can access their own files err = authorise.Resource(context, file) if err != nil { return router.NotAuthorizedError(err) } // If we are permitted, send the file to the user //w.Header().Set("Content-Type", "text/plain; charset=utf-8") //http.DetectContentType(data []byte) string h := context.Header() h.Set("Content-Type", "application/pgp-encrypted") h.Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", file.Name())) h.Set("Content-Transfer-Encoding", "binary") http.ServeFile(context, context.Request(), file.Path) return nil }
// HandleIndex displays a list of files func HandleIndex(context router.Context) error { // Authorise err := authorise.Path(context) if err != nil { return router.NotAuthorizedError(err) } // Find the current user and check status u := authorise.CurrentUser(context) if u.Anon() { // return router.NotAuthorizedError(err) } // For admins, show all files, order by date desc q := files.Query().Order("updated_at desc") // otherwise show just the logged in user's files if !u.Admin() { // Find the files for this user, unless q = files.Where("user_id=?", u.Id) } // Fetch the files results, err := files.FindAll(q) if err != nil { return router.InternalError(err) } // Render the template view := view.New(context) view.AddKey("files", results) return view.Render() }
// Create inserts a new record in the database using params, and returns the newly created id func Create(params map[string]string) (int64, error) { // Remove params not in AllowedParams params = model.CleanParams(params, AllowedParams()) // Check params for invalid values err := validateParams(params) if err != nil { return 0, err } // Check name is unique - no duplicate names allowed count, err := Query().Where("name=?", params["name"]).Count() if err != nil { return 0, err } if count > 0 { return 0, router.InternalError(err, "User name taken", "A username with this email already exists, sorry.") } // Update date params params["created_at"] = query.TimeString(time.Now().UTC()) params["updated_at"] = query.TimeString(time.Now().UTC()) return Query().Insert(params) }
// Serve a get request at /images // // func HandleIndex(context router.Context) error { // Authorise err := authorise.Path(context) if err != nil { return router.NotAuthorizedError(err) } // Setup context for template view := view.New(context) // Build a query q := images.Query() // Show only published (defaults to showing all) // q.Apply(status.WherePublished) // Order by required order, or default to id asc switch context.Param("order") { case "1": q.Order("created_at desc") case "2": q.Order("updated_at desc") case "3": q.Order("name asc") default: q.Order("id desc") } // Filter if necessary - this assumes name and summary cols filter := context.Param("filter") if len(filter) > 0 { filter = strings.Replace(filter, "&", "", -1) filter = strings.Replace(filter, " ", "", -1) filter = strings.Replace(filter, " ", " & ", -1) q.Where("( to_tsvector(name) || to_tsvector(summary) @@ to_tsquery(?) )", filter) } // Fetch the images imagesList, err := images.FindAll(q) if err != nil { return router.InternalError(err) } // Serve template view.AddKey("filter", filter) view.AddKey("images", imagesList) // Can we add these programatically? view.AddKey("admin_links", helpers.Link("Create image", images.New().URLCreate())) return view.Render() }
// HandleCreate handles the POST of the create form for users func HandleCreate(context router.Context) error { // Authorise err := authorise.Resource(context, nil) if err != nil { return router.NotAuthorizedError(err) } // Setup context params, err := context.Params() if err != nil { return router.InternalError(err) } // Default to customer role etc - admins will have to promote afterwards params.Set("role", fmt.Sprintf("%d", users.RoleCustomer)) params.Set("status", fmt.Sprintf("%d", status.Published)) id, err := users.Create(params.Map()) if err != nil { return err } // Log creation context.Logf("#info Created user id,%d", id) // Redirect to the new user user, err := users.Find(id) if err != nil { return router.InternalError(err) } // Save the details in a secure cookie session, err := auth.Session(context, context.Request()) if err != nil { return router.InternalError(err) } context.Logf("#info CREATE for user: %d", user.Id) session.Set(auth.SessionUserKey, fmt.Sprintf("%d", user.Id)) session.Save(context) // Send them to their user profile page return router.Redirect(context, user.URLShow()) }
// removeUserPoints removes these points from this user func adjustUserPoints(user *users.User, delta int64) error { // Update the user points err := user.Update(map[string]string{"points": fmt.Sprintf("%d", user.Points+delta)}) if err != nil { return router.InternalError(err, "Vote Failed", "Sorry could not adjust user points") } return nil }
// HandleCreate responds to POST images/create func HandleCreate(context router.Context) error { // Authorise err := authorise.Path(context) if err != nil { return router.NotAuthorizedError(err) } // We expect only one image, what about replacing the existing when updating? // At present we just create a new image files, err := context.ParamFiles("image") if err != nil { return router.InternalError(err) } if len(files) == 0 { return router.NotFoundError(nil) } // Get the params params, err := context.Params() if err != nil { return router.InternalError(err) } id, err := images.Create(params.Map(), files[0]) if err != nil { context.Logf("#error Error creating image,%s", err) return router.InternalError(err) } // Log creation context.Logf("#info Created image id,%d", id) // Redirect to the new image m, err := images.Find(id) if err != nil { context.Logf("#error Error creating image,%s", err) } return router.Redirect(context, m.URLShow()) }