Golang Context.DefaultPostForm Examples

Golang Context.DefaultPostForm - 15 examples found. These are the top rated real world Golang examples of github.com/gin-gonic/gin.Context.DefaultPostForm extracted from open source projects. You can rate examples to help us improve the quality of examples.
Example #1
0
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})
}
Example #2
0
// Login is a page with a login form and an alternative to the login API,
// this route handles both GET and POST requests.
func Login(c *gin.Context) {
	session := sessions.Default(c)
	defer session.Save()

	// returnURL can come from GET or POST or use default.
	returnURL := c.DefaultQuery("return_url", c.DefaultPostForm("return_url", "/"))

	if c.Request.Method == "POST" {
		var schema LoginSchema
		if c.Bind(&schema) == nil {
			// Fetch the user matching this username.
			user := GetUserByUsername(schema.Username)

			// If the user exists, the ID is > 0, check the password.
			if user.ID > 0 && user.CheckPassword(schema.Password) {
				session.Set("userID", user.ID)
				c.Redirect(http.StatusFound, returnURL)
				return
			}
			session.AddFlash("Invalid username or password")
		}
	}

	c.HTML(200, "login.html", pongo2.Context{
		"title":      "Login",
		"messages":   session.Flashes(),
		"csrf_token": nosurf.Token(c.Request),
		"return_url": returnURL,
	})
}
Example #3
0
// update an object from its change form
func changeUpdate(c *gin.Context) {
	log.Println("hitting changeUpdate")
	action := c.DefaultPostForm("action", "save")
	delete(c.Request.Form, "action") // don't keep this as part of the object
	modelAdmin, exists := modelAdmins[strings.ToLower(c.Param("model"))]
	if !exists {
		c.String(http.StatusNotFound, "Not found.")
		return
	}
	if !hasPermissions(c, modelAdmin.ModelName, "write", nil) { // TODO: add in the ID(s)
		return
	}
	switch action {
	case "save":
		saveFromForm(c)
		c.Request.Method = "GET"
		c.Redirect(http.StatusFound, fmt.Sprintf("../%v", strings.ToLower(c.Param("model"))))
	case "save-continue":
		saveFromForm(c)
		change(c)
	case "delete":
		modelAdmin.Accessor.DeletePK(c.Param("pk"))
		c.Request.Method = "GET"
		c.Redirect(http.StatusFound, fmt.Sprintf("../%v", strings.ToLower(c.Param("model"))))
	}
}
Example #4
0
// CreateC handles the multipart form upload and creates an encrypted file
func CreateC(c *gin.Context) {
	var err error
	var duration time.Duration
	var once bool

	c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, conf.C.SizeLimit*utils.MegaByte)

	once = c.PostForm("once") != ""
	d := c.DefaultPostForm("duration", "1d")

	if val, ok := models.DurationMap[d]; ok {
		duration = val
	} else {
		logger.ErrC(c, "server", "Invalid duration", d)
		c.String(http.StatusBadRequest, "Invalid duration\n")
		c.AbortWithStatus(http.StatusBadRequest)
		return
	}

	fd, h, err := c.Request.FormFile("file")
	if err != nil {
		logger.ErrC(c, "server", "Couldn't read file", err)
		c.String(http.StatusRequestEntityTooLarge, "Entity is too large (Max : %v MB)\n", conf.C.SizeLimit)
		c.AbortWithStatus(http.StatusRequestEntityTooLarge)
		return
	}
	defer fd.Close()

	res := models.NewResourceFromForm(h, once, duration)
	k, err := res.WriteEncrypted(fd)
	if err != nil {
		logger.ErrC(c, "server", "Couldn't write file", err)
		c.String(http.StatusInternalServerError, "Something went wrong on the server. Try again later.")
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}

	if conf.C.DiskQuota > 0 {
		if models.S.CurrentSize+uint64(res.Size) > uint64(conf.C.DiskQuota*utils.GigaByte) {
			logger.ErrC(c, "server", "Quota exceeded")
			c.String(http.StatusBadRequest, "Insufficient disk space. Try again later.")
			c.AbortWithStatus(http.StatusBadRequest)
			os.Remove(path.Join(conf.C.UploadDir, res.Key))
			return
		}
	}

	if err = res.Save(); err != nil {
		logger.ErrC(c, "server", "Couldn't save in the database", err)
		c.String(http.StatusInternalServerError, "Something went wrong on the server. Try again later.")
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}
	res.LogCreated(c)
	ns := conf.C.NameServer
	if conf.C.AppendPort {
		ns = fmt.Sprintf("%s:%d", conf.C.NameServer, conf.C.Port)
	}
	c.String(http.StatusCreated, "%v://%s/v/%s/%s\n", utils.DetectScheme(c), ns, res.Key, k)
}
Example #5
0
//SaveNewPair will save a new pair of Esperanto to English definitions to the data store
func SaveNewPair(c *gin.Context, phrases []Pair) {
	if !c.MustGet("Authenticated").(bool) {
		c.JSON(401, gin.H{"status": "Unauthorized"})
	} else {
		eo := c.DefaultPostForm("esperanto", "")
		en := c.DefaultPostForm("english", "")
		if eo == "" || en == "" {
			c.JSON(400, gin.H{"status": "You must pass in both an 'esperanto' phrase and an 'english' phrase"})
		} else {
			pair := Pair{eo, en}
			pbFile := config.PhraseBookLocation + "phrasebook.txt"
			file, err := os.OpenFile(pbFile, os.O_APPEND|os.O_WRONLY, 0600)
			if err != nil {
				c.JSON(500, gin.H{"status": "There was a problem saving that pair"})
				panic(err)
			}
			defer file.Close()

			writeString := fmt.Sprintf("\n%s|%s", pair.Esperanto, pair.English)
			if _, err = file.WriteString(writeString); err != nil {
				c.JSON(500, gin.H{"status": "There was a problem saving that pair"})
				panic(err)
			}
			_ = append(phrases, pair)
			c.JSON(200, pair)
		}
	}
}
Example #6
0
func putUser(c *gin.Context) {
	id := c.Param("id")
	other := c.DefaultQuery("page", "0") // shortcut for c.Request.URL.Query().Get("page")
	message := c.DefaultPostForm("message", "Nothing over here")

	str := fmt.Sprintf("Id: %s, Message: %s, Other: %s", id, message, other)
	c.JSON(http.StatusOK, gin.H{
		"message": str,
	})
}