//POST /quotes //POST /slack/insertQuote func (a *AppContext) NewQuote(c *echo.Context) error { r := c.Request() SetDefaultHeaders(c) //Parse post values r.ParseForm() isValid := len(r.Form["text"]) > 0 && len(r.Form["team_id"]) > 0 if !isValid { log.Println("Invalid form (empty?)\nI'm a doctor Jim, not a magician!") return c.JSON(http.StatusBadRequest, "Looks like I'm missing some parameters, sir.") } fmt.Printf("form:: %s\n", r.Form) //Transfer post values to quote variable quote := new(st.Quote) decoder := schema.NewDecoder() if err := decoder.Decode(quote, c.Request().PostForm); err != nil { fmt.Println(err) } fmt.Printf("Filled quote: %#v\n", quote) //Save the quote in the database a.Storage.SaveQuote(quote) resp := "Saving quote: " + quote.Text fmt.Println("\n\n") return c.JSON(http.StatusOK, resp) }
// GetHabloAuth returns an hablo authorization if available and valid func GetHabloAuth(c *echo.Context) (*models.HabloAuth, error) { header := c.Request().Header authv := header.Get("Authorization") // Get bearer token if !strings.HasPrefix(strings.ToLower(authv), "bearer") { return nil, ErrNoToken } values := strings.Split(authv, " ") if len(values) < 2 { return nil, ErrNoToken } token := values[1] // Find token in collection var auth models.HabloAuth err := mangos.FindOne(models.NCAuth, bson.M{"token": token}, &auth) if err != nil { return nil, err } return &auth, nil }
func CustomHTTPErrorHandler(err error, c echo.Context) { code := http.StatusInternalServerError response := ErrResponse{} switch v := err.(type) { case types.ErrNotFound: code = http.StatusNotFound response = ErrResponse{"error": v.Error()} case types.ErrConflict: code = http.StatusConflict response = ErrResponse{"error": v.Error()} case types.ErrValidation: code = http.StatusUnprocessableEntity response = ErrResponse{"error": v.Errors} case *echo.HTTPError: response = ErrResponse{"error": v.Message} default: response = ErrResponse{"error": v.Error()} } if !c.Response().Committed { if c.Request().Method == echo.HEAD { // Issue #608 c.NoContent(code) } else { c.JSON(code, response) } } }
// DeleteSession delete session by name. func DeleteSession(ctx *echo.Context, sessionName string) error { ss, err := store.Get(ctx.Request(), sessionName) if err != nil { return err } return store.Delete(ctx.Request(), ctx.Response(), ss) }
func upload(c *echo.Context) error { req := c.Request() req.ParseMultipartForm(16 << 20) // Max memory 16 MiB // Read form fields name := c.Form("name") email := c.Form("email") // Read files files := req.MultipartForm.File["files"] for _, f := range files { // Source file src, err := f.Open() if err != nil { return err } defer src.Close() // Destination file dst, err := os.Create(f.Filename) if err != nil { return err } defer dst.Close() if _, err = io.Copy(dst, src); err != nil { return err } } return c.String(http.StatusOK, "Thank You! %s <%s>, %d files uploaded successfully.", name, email, len(files)) }
func (app *App) putValues(ctx *echo.Context) (err error) { key := ctx.Param("key") value, err := readBody(ctx.Request()) if err != nil { return err } app.Lock() entry, ok := app.store[key] if !ok { entry = newEntry() entry.Lock() app.store[key] = entry } else { entry.Lock() } app.Unlock() entry.value = value entry.lockID = generateID(32) app.cond.Broadcast() entry.Unlock() response := map[string]interface{}{} response["lock_id"] = entry.lockID ctx.JSON(200, response) return }
// Create 发布新资源 func (ResourceController) Create(ctx echo.Context) error { title := ctx.FormValue("title") // 请求新建资源页面 if title == "" || ctx.Request().Method() != "POST" { return render(ctx, "resources/new.html", map[string]interface{}{"activeResources": "active", "categories": logic.AllCategory}) } errMsg := "" resForm := ctx.FormValue("form") if resForm == model.LinkForm { if ctx.FormValue("url") == "" { errMsg = "url不能为空" } } else { if ctx.FormValue("content") == "" { errMsg = "内容不能为空" } } if errMsg != "" { return fail(ctx, 1, errMsg) } me := ctx.Get("user").(*model.Me) err := logic.DefaultResource.Publish(ctx, me, ctx.FormParams()) if err != nil { return fail(ctx, 2, "内部服务错误,请稍候再试!") } return success(ctx, nil) }
// Modify 修改主题 func (TopicController) Modify(ctx echo.Context) error { tid := goutils.MustInt(ctx.FormValue("tid")) if tid == 0 { return ctx.Redirect(http.StatusSeeOther, "/topics") } nodes := logic.GenNodes() if ctx.Request().Method() != "POST" { topics := logic.DefaultTopic.FindByTids([]int{tid}) if len(topics) == 0 { return ctx.Redirect(http.StatusSeeOther, "/topics") } return render(ctx, "topics/new.html", map[string]interface{}{"nodes": nodes, "topic": topics[0], "activeTopics": "active"}) } me := ctx.Get("user").(*model.Me) err := logic.DefaultTopic.Publish(ctx, me, ctx.FormParams()) if err != nil { if err == logic.NotModifyAuthorityErr { return fail(ctx, 1, "没有权限操作") } return fail(ctx, 2, "服务错误,请稍后重试!") } return success(ctx, nil) }
// OverrideRequestMethod overrides the http // request's method with the specified method. func OverrideRequestMethod(c *echo.Context, method string) error { if !isValidOverrideMethod(method) { return ErrInvalidOverrideMethod } c.Request().Header.Set(HeaderHTTPMethodOverride, method) return nil }
//GET /activities func (a *AppContext) GetActivities(c *echo.Context) error { var activities []st.Activity var err error var query = c.Request().URL.Query().Get("q") //Check for token header SetDefaultHeaders(c) //Get quote from database if query != "" { //Seperate search terms and put them into a string array activities, err = a.Storage.SearchActivities(strings.Split(query, ",")) } else { activities, err = a.Storage.FindAllActivities() } if err != nil { return c.JSON(http.StatusBadRequest, Error{"Activities could not be found.", err}) } return c.JSON(http.StatusOK, FormatResponse("Fetched", activities)) }
// EmailUnsub 邮件订阅/退订页面 func (UserController) EmailUnsub(ctx echo.Context) error { token := ctx.FormValue("u") if token == "" { return ctx.Redirect(http.StatusSeeOther, "/") } // 校验 token 的合法性 email := ctx.FormValue("email") user := logic.DefaultUser.FindOne(ctx, "email", email) if user.Email == "" { return ctx.Redirect(http.StatusSeeOther, "/") } realToken := logic.DefaultEmail.GenUnsubscribeToken(user) if token != realToken { return ctx.Redirect(http.StatusSeeOther, "/") } if ctx.Request().Method() != "POST" { data := map[string]interface{}{ "email": email, "token": token, "unsubscribe": user.Unsubscribe, } return render(ctx, "user/email_unsub.html", data) } logic.DefaultUser.EmailSubscribe(ctx, user.Uid, goutils.MustInt(ctx.FormValue("unsubscribe"))) return success(ctx, nil) }
// Checking rate limit 10 request / 1 sec. func checkRateLimit(con redis.Conn, c *echo.Context) bool { ip, _, err := net.SplitHostPort(c.Request().RemoteAddr) if err != nil { panic(err) } //If list of ip address's length is 10 retun false. current, err := redis.Int(con.Do("LLEN", ip)) if err == nil && current > 10 { return false } exists, err := redis.Bool(con.Do("EXISTS", ip)) if err != nil { panic(err) } if !exists { con.Send("MULTI") con.Send("RPUSH", ip, ip) con.Send("EXPIRE", ip, 1) _, err := con.Do("EXEC") if err != nil { panic(err) } } else { _, err := con.Do("RPUSHX", ip, ip) if err != nil { panic(err) } } return true }
// RegisterPost handles registration form, and create a session for the new user if the registration // process is complete. // // Method POST // // Route /auth/register // // Restrictions None // // Template None (All actions redirect to other routes ) // // Flash messages may be set before redirection. func RegisterPost(ctx *echo.Context) error { var flashMessages = flash.New() f := forms.New(utils.GetLang(ctx)) lf := f.RegisterForm()(ctx.Request()) if !lf.IsValid() { // Case the form is not valid, ships it back with the errors exclusively utils.SetData(ctx, authForm, lf) return ctx.Render(http.StatusOK, tmpl.RegisterTpl, utils.GetData(ctx)) } // we are not interested in the returned user, rather we make sure the user has // been created. _, err := query.CreateNewUser(lf.GetModel().(forms.Register)) if err != nil { flashMessages.Err(msgAccountCreateFailed) flashMessages.Save(ctx) ctx.Redirect(http.StatusFound, "/auth/register") return nil } // TODO: improve the message to include directions to use the current email and // password to login? flashMessages.Success(msgAccountCreate) flashMessages.Save(ctx) // Don't create session in this route, its best to leave only one place which // messes with the main user session. So we redirect to the login page, and encourage // the user to login. ctx.Redirect(http.StatusFound, "/auth/login") return nil }
func Index(c *echo.Context) error { authCookie, err := c.Request().Cookie("testcook") logrus.Infof(">>> cooki: %+v, err: %+v", authCookie, err) dbconn := c.Get("db").(*mgo.Database) counts := dbconn.C("counts") if err := counts.Insert(&models.TestStruct{"index"}); err != nil { c.String(500, fmt.Sprintf("broken: %s", err.Error())) return nil } t, err := template.ParseFiles("static/html/layout.html", "static/html/greet.html", "static/html/mainPage.html") if err != nil { c.String(500, fmt.Sprintf("broken: %s", err.Error())) return nil } loggedIn := false user, ok := c.Get("user").(models.Account) if ok { loggedIn = user.Username != "" } args := map[string]interface{}{ "Username": user.Username, "LoggedIn": loggedIn, "Logout": fmt.Sprintf("http://*****:*****@%s", viper.GetString("base_uri"))} t.Execute(c.Response(), args) return nil }
func httpTimeline(c *echo.Context) error { r := c.Request() w := c.Response() e := c.Get("engine").(storage.Engine) domain := c.Param("domain") iter, code, err := domainIteratorResource(domain, r, e) if err != nil { return c.JSON(code, map[string]interface{}{ "error": fmt.Sprint(err), }) } events, err := view.Timeline(iter, view.Descending) if err != nil { return c.JSON(code, map[string]interface{}{ "error": fmt.Sprint(err), }) } return json.NewEncoder(w).Encode(events) }
func httpLog(c *echo.Context) error { r := c.Request() w := c.Response() e := c.Get("engine").(storage.Engine) domain := c.Param("domain") iter, code, err := domainIteratorResource(domain, r, e) if err != nil { return c.JSON(code, map[string]interface{}{ "error": fmt.Sprint(err), }) } facts, err := origins.ReadAll(iter) if err != nil { return c.JSON(code, map[string]interface{}{ "error": fmt.Sprint(err), }) } return json.NewEncoder(w).Encode(facts) }
func GetDownloadToken(c *echo.Context) error { filename := c.Query("filename") if len(filename) == 0 { return c.JSON( http.StatusBadRequest, hash{ "error": "filename not specified", }, ) } accessToken, fail := oauth2.GetAccessToken(c.Request()) if fail != nil { return oauthError(c, fail) } user := c.Get("user").(*users.User) token, err := createDownloadToken(user, accessToken, filename) if err != nil { return err } return c.JSON( http.StatusOK, hash{ "token": token, }, ) }
// Login POST /auth/login func (*UsersController) Login(c echo.Context) error { var payload models.LoginPayload var user models.User an, _, err := net.SplitHostPort(c.Request().RemoteAddress()) if err != nil { return c.JSON(400, utils.ErrMarshal(err.Error())) } if err = c.Bind(&payload); err != nil { return c.JSON(400, utils.ErrMarshal(err.Error())) } ret, err := user.Login(payload) if err != nil { msg := err.Error() // login failed err = utils.ST.Infraction(an, "Login") if err != nil { msg = msg + " " + err.Error() return c.JSON(400, utils.ErrMarshal(msg)) } // auth fails, increment infraction _, err = utils.ST.Strikes(an, "Login") return c.JSON(400, utils.ErrMarshal(msg)) } return c.JSON(200, ret) }
func renderInstall(ctx echo.Context, filename string, data map[string]interface{}) error { objLog := getLogger(ctx) if data == nil { data = make(map[string]interface{}) } filename = config.TemplateDir + filename requestURI := ctx.Request().URI() tpl, err := template.ParseFiles(filename) if err != nil { objLog.Errorf("解析模板出错(ParseFiles):[%q] %s\n", requestURI, err) return err } buf := new(bytes.Buffer) err = tpl.Execute(buf, data) if err != nil { objLog.Errorf("执行模板出错(Execute):[%q] %s\n", requestURI, err) return err } return ctx.HTML(http.StatusOK, buf.String()) }
// JobsNewPost process the new job form. // // Method POST // // Route /dash/jobs/new // // Restrictions Yes // // Template None func JobsNewPost(ctx *echo.Context) error { var flashMessages = flash.New() f := forms.New(utils.GetLang(ctx)) jf := f.JobForm()(ctx.Request()) if !jf.IsValid() { // TODO: improve flash message ? flashMessages.Err(msgInvalidorm) flashMessages.Save(ctx) ctx.Redirect(http.StatusFound, "/dash/jobs/new") return nil } if isLoged := ctx.Get("IsLoged"); isLoged != nil { person := ctx.Get("User").(*models.Person) if jerr := query.PersonCreateJob(person, jf.GetModel().(forms.JobForm)); jerr != nil { // TODO: improve flash message ? flashMessages.Err("some really bad fish happened") flashMessages.Save(ctx) ctx.Redirect(http.StatusFound, "/dash/jobs/new") return nil } // add flash message flashMessages.Success("new job was created successful") flashMessages.Save(ctx) ctx.Redirect(http.StatusFound, "/dash/") return nil } he := echo.NewHTTPError(http.StatusUnauthorized) ctx.Error(he) return nil }
func Upload(c *echo.Context) error { req := c.Request() req.ParseMultipartForm(16 * 1024 * 1024) // Read files files := req.MultipartForm.File["files"] for _, f := range files { // Source file src, err := f.Open() if err != nil { return err } defer src.Close() // Destination file dst, err := os.Create(slugifyFilename(f.Filename)) if err != nil { return err } defer dst.Close() if _, err = io.Copy(dst, src); err != nil { return err } } return nil }
func defaultCacheKeyAlgorithm(ctx echo.Context) string { filter := map[string]bool{ "from": true, "sign": true, "nonce": true, "timestamp": true, } form := ctx.FormParams() var keys = make([]string, 0, len(form)) for key := range form { if _, ok := filter[key]; !ok { keys = append(keys, key) } } sort.Sort(sort.StringSlice(keys)) buffer := goutils.NewBuffer() for _, k := range keys { buffer.Append(k).Append("=").Append(ctx.FormValue(k)) } req := ctx.Request() return goutils.Md5(req.Method() + req.URL().Path() + buffer.String()) }
func (h *handler) handleUploadTarFunc(c echo.Context) error { req := c.Request() basePath := req.Header().Get(shared.BASE_PATH_HTTP_HEADER_NAME) if strings.TrimSpace(basePath) == "" { return fmt.Errorf("Request does not contain header '%s'", shared.BASE_PATH_HTTP_HEADER_NAME) } isDirVal := req.Header().Get(shared.IS_DIR_HTTP_HEADER_NAME) if strings.TrimSpace(isDirVal) == "" { return fmt.Errorf("Request does not contain header '%s'", shared.IS_DIR_HTTP_HEADER_NAME) } isDir := strings.TrimSpace(isDirVal) == "1" if isDir { //TODO: Is permission fine? if err := os.MkdirAll(basePath, 0755); err != nil { return fmt.Errorf("Unable to create base path %s, error: %s", basePath, err.Error()) } } if isDir { h.logger.Infof("Now starting to receive dir '%s'", basePath) tarReceiver := tar_io.Factories.TarReceiver.Dir(basePath) return tar_io.SaveTarToReceiver(req.Body(), tarReceiver) } else { h.logger.Infof("Now starting to receive file '%s'", basePath) tarReceiver := tar_io.Factories.TarReceiver.File(basePath) return tar_io.SaveTarToReceiver(req.Body(), tarReceiver) } }
func PublishApp(c *echo.Context) error { body, err := ioutil.ReadAll(c.Request().Body) if err != nil { log.Error(err) return reterr(err, "", c) } var all struct { Data struct { Attributes struct { Alias string `json:"alias"` CollectionName string `json:"collection-name"` DisplayName string `json:"display-name"` FilePath string `json:"file-path"` Path string `json:"path"` } Type string `json:"type"` } `json:"data"` } err = json.Unmarshal(body, &all) if err != nil { log.Error(err) return reterr(err, "", c) } username, pwd, _ := c.Request().BasicAuth() utils.ExecuteCommandAsAdmin("C:\\Windows\\System32\\WindowsPowershell\\v1.0\\powershell.exe Import-module RemoteDesktop; New-RDRemoteApp -CollectionName "+all.Data.Attributes.CollectionName+" -DisplayName "+all.Data.Attributes.DisplayName+" -FilePath '"+all.Data.Attributes.Path+"'", username, pwd, domain) return checkIfPublishSucceeded(c, all.Data.Attributes.DisplayName) }
func OauthResponse(c *echo.Context) (goth.Session, *goth.User, error) { //println("gothic.OauthResponse") platform, err := getPlatform(c) if err != nil { return nil, nil, err } req := c.Request() //println("gothic.getSession") sess, err := getSession(platform, req) if err != nil { return nil, nil, err } //println("gothic.Authorize") _, err = sess.Authorize(platform, req.URL.Query()) if err != nil { return sess, nil, err } //println("gothic.OauthResponse.Authorize response", authorized) user, err := platform.FetchUser(sess) if err != nil { return nil, nil, err } return sess, user, nil }
func (rc *ResourceController) IndexHandler(c *echo.Context) error { defer func() error { if r := recover(); r != nil { switch x := r.(type) { case search.Error: return c.JSON(x.HTTPStatus, x.OperationOutcome) default: outcome := models.NewOperationOutcome("fatal", "exception", "") return c.JSON(http.StatusInternalServerError, outcome) } } return nil }() searchQuery := search.Query{Resource: rc.Name, Query: c.Request().URL.RawQuery} baseURL := responseURL(c.Request(), rc.Name) bundle, err := rc.DAL.Search(*baseURL, searchQuery) if err != nil { return err } c.Set("bundle", bundle) c.Set("Resource", rc.Name) c.Set("Action", "search") c.Response().Header().Set("Access-Control-Allow-Origin", "*") return c.JSON(http.StatusOK, bundle) }
func CreateAccount(c *echo.Context) error { logrus.Infof("create account") caRequest, err := validateCreateAccount(c.Request().Body) if err != nil { logrus.Errorf("failed create account input validation %s", err.Error()) c.JSON(400, Response{}) return nil } db := c.Get("db").(*mgo.Database) _, err = models.LoadAccount(db, caRequest.Username) if err == nil { logrus.Errorf("account taken: %s", caRequest.Username) c.JSON(409, Response{}) return nil } else if err != models.AccountNotFound && err != nil { logrus.Errorf("db error in create account: %s", err.Error()) c.JSON(500, Response{}) return nil } a := models.Account{ Username: caRequest.Username, Password: caRequest.Password, } err = models.CreateAccount(db, a) if err != nil { logrus.Errorf("failed to create account: %s", err.Error()) c.JSON(500, Response{}) return nil } c.JSON(200, Response{true, a}) return nil }
// JWTFromHeader is a `JWTExtractor` that extracts token from the `Authorization` request // header. func JWTFromHeader(c echo.Context) (string, error) { auth := c.Request().Header().Get(echo.HeaderAuthorization) l := len(bearer) if len(auth) > l+1 && auth[:l] == bearer { return auth[l+1:], nil } return "", errors.New("empty or invalid jwt in authorization header") }
// GetBody 获取请求的body func GetBody(ctx echo.Context) (string, error) { bodyByte, err := ioutil.ReadAll(ctx.Request().Body()) if err != nil { return "", err } return string(bodyByte), nil }
// JWTFromHeader is a `JWTExtractor` that extracts token from the `Authorization` request // header. func JWTFromHeader(c echo.Context) (string, error) { auth := c.Request().Header().Get(echo.HeaderAuthorization) l := len(bearer) if len(auth) > l+1 && auth[:l] == bearer { return auth[l+1:], nil } return "", echo.NewHTTPError(http.StatusBadRequest, "empty or invalid authorization header="+auth) }