예제 #1
0
파일: auth.go 프로젝트: yanue/go-webmail
func Login(c *gin.Context) {
	user := c.PostForm("user")
	pass := c.PostForm("pass")
	fmt.Println(user)
	fmt.Println(pass)
	mail.GoLogin("*****@*****.**", "402407")
}
예제 #2
0
파일: order.go 프로젝트: sdvdxl/wine
// 删除订单
func OrderDeleteHandler(c *gin.Context) {
	r := render.New(c)

	//超级管理员才可以删除订单
	auth := userauth.Auth(c)
	if !auth.IsRole(bean.ROLE_SUPER_ADMIN) {
		r.JSON(util.JsonResult{Msg: "您没有权限"})
		return
	}

	oids := strings.TrimSpace(c.PostForm("oid"))

	var orderIds []string
	err := json.Unmarshal([]byte(oids), &orderIds)
	if err != nil {
		Logger.Warn("order delete uuids:%v, err: %v", oids, err)
		r.JSON(util.JsonResult{Success: true, Msg: "订单参数错误"})
		return
	}

	if len(orderIds) == 0 {
		r.JSON(util.JsonResult{Success: true, Msg: "请选择订单"})
		return
	}

	deleteSQL := "delete from order_info where uuid in ("
	for _, v := range orderIds {
		deleteSQL += "'" + v + "' ,"
	}
	deleteSQL = deleteSQL[:len(deleteSQL)-1] + ")"
	Logger.Debug("order delete sql: %v", deleteSQL)
	_, err = db.Engine.Exec(deleteSQL)
	util.PanicError(err)
	r.JSON(util.JsonResult{Success: true, Msg: "删除成功"})
}
예제 #3
0
func AddCourse(ctx *gin.Context) (*Course, error) {
	db := ctx.MustGet("db").(*sql.DB)
	course := new(Course)
	course.Name = ctx.PostForm("name")
	course.Email = ctx.PostForm("email")
	course.Url = ctx.PostForm("url")
	course.Priority, _ = strconv.Atoi(ctx.PostForm("priority"))
	course.Checkoff, _ = strconv.Atoi(ctx.PostForm("checkoff"))
	course.Note = ctx.PostForm("note")

	err := db.QueryRow(`
		INSERT INTO 
		courses(name, email, url, priority, checkoff, note) 
		VALUES($1,$2,$3,$4,$5,$6) returning id;`,
		&course.Name,
		&course.Email,
		&course.Url,
		&course.Priority,
		&course.Checkoff,
		&course.Note).Scan(&course.Id)

	if err != nil {
		return nil, err
	}
	return course, nil
}
예제 #4
0
func (self *EnvController) New(c *gin.Context) {
	username := self.CurrentUser(c)

	if username == "" {
		c.Redirect(http.StatusFound, "/")

		return
	}

	appName := c.Param("appName")
	key := c.PostForm("key")
	value := c.PostForm("value")

	err := env.Create(self.etcd, username, appName, key, value)

	if err != nil {
		fmt.Fprintf(os.Stderr, "%+v\n", err)

		c.HTML(http.StatusInternalServerError, "app.tmpl", gin.H{
			"alert":   true,
			"error":   true,
			"message": "Failed to add environment variable.",
		})

		return
	}

	c.Redirect(http.StatusSeeOther, "/apps/"+appName)
}
예제 #5
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)
}
예제 #6
0
func (self *ArgController) Delete(c *gin.Context) {
	username := self.CurrentUser(c)

	if username == "" {
		c.Redirect(http.StatusFound, "/")

		return
	}

	appName := c.Param("appName")
	key := c.PostForm("key")

	err := arg.Delete(self.etcd, username, appName, key)

	if err != nil {
		fmt.Fprintf(os.Stderr, "%+v\n", err)

		c.HTML(http.StatusInternalServerError, "app.tmpl", gin.H{
			"alert":   true,
			"error":   true,
			"message": "Failed to delete build arg.",
		})

		return
	}

	c.Redirect(http.StatusSeeOther, "/apps/"+appName)
}
예제 #7
0
func UpdateCourse(ctx *gin.Context) (*Course, error) {
	db := ctx.MustGet("db").(*sql.DB)
	course := new(Course)
	course.Id, _ = strconv.Atoi(ctx.Param("id"))
	course.Name = ctx.PostForm("name")
	course.Url = ctx.PostForm("url")
	course.Priority, _ = strconv.Atoi(ctx.PostForm("priority"))
	course.Checkoff, _ = strconv.Atoi(ctx.PostForm("checkoff"))
	checkoffTimeStamp := ctx.PostForm("checkoff_time") // , _ = time.Parse(time.RFC3339, ctx.PostForm("checkoff_time"))
	course.Note = ctx.PostForm("note")
	course.UpdatedAt = time.Now()

	err := db.QueryRow("UPDATE courses SET (name, url, priority, checkoff, checkoff_time, note, updated_at) = ($1,$2,$3,$4,$5,$6,$7) WHERE id=$8 returning id;",
		&course.Name,
		&course.Url,
		&course.Priority,
		&course.Checkoff,
		checkoffTimeStamp,
		&course.Note,
		&course.UpdatedAt,
		&course.Id).Scan(&course.Id)

	if err != nil {
		return nil, err
	}
	return course, nil
}
예제 #8
0
파일: model.go 프로젝트: Focinfi/apifaker
// UpdateWithAttrsInGinContext finds a LineItem with id param,
// updates it with attrs from gin.Contex.PostForm(),
// returns the edited LineItem
func (model *Model) UpdateWithAttrs(id float64, ctx *gin.Context) (LineItem, error) {
	// check if element does exsit
	li, ok := model.Get(id)
	if !ok {
		return li, SeedsErrorf("model %s[id:%d] does not exsit", model.Name, id)
	}

	// update model
	for _, column := range model.Columns {
		value := ctx.PostForm(column.Name)

		if value == "" || column.Name == "id" {
			continue
		}

		formatVal, err := FormatValue(column.Type, value)
		if err == nil {
			err = column.CheckValue(formatVal, model)
		}

		if err != nil {
			return li, err
		} else {
			oldValue, _ := li.Get(column.Name)
			column.RemoveUniquenessOf(oldValue)
			li.Set(column.Name, formatVal)
			column.AddUniquenessOf(formatVal)
		}
	}
	return li, nil
}
예제 #9
0
func uploadRecipients(c *gin.Context) {
	if c.PostForm("delete") != "" {
		log.Printf("DeleteAll")
		_, err := Db.Exec("DELETE FROM `recipient` WHERE `campaign_id`=?", c.Param("id"))
		checkErr(err)
	}

	if c.PostForm("submit") != "" {
		file, head, err := c.Request.FormFile("file")
		checkErr(err)
		if err == nil {
			fpath := "tmp/" + string(time.Now().UnixNano()) + head.Filename
			out, err := os.Create(fpath)
			checkErr(err)
			defer out.Close()
			_, err = io.Copy(out, file)
			checkErr(err)
			postRecipientCsv(c.Param("id"), fpath)
			os.Remove(fpath)
		}

	}

	hRecipients(c)
}
예제 #10
0
func postCheck(c *gin.Context) {
	lang := c.PostForm("lang")
	text := c.PostForm("text")

	speller, err := aspell.NewSpeller(map[string]string{
		"lang": lang,
	})

	if err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
	}
	defer speller.Delete()

	test := strings.Fields(text)

	result := make(map[string][]string)

	for i := range test {
		if speller.Check(stripchars(test[i], ".,!?+=")) != true {
			result[stripchars(test[i], ".,!?+=")] = speller.Suggest(test[i])
		}
	}

	c.JSON(200, gin.H{"lang": lang, "misspelled": result})
}
예제 #11
0
파일: rotas.go 프로젝트: viliamjr/favoritos
// Salvar define a rota para salvar o link
func Salvar(c *gin.Context) {

	link := construirLink(c)

	if c.PostForm("inputId") != "" {

		modelo.AtualizarLink(link)
		c.HTML(http.StatusOK, "favoritos.html", gin.H{
			"proxPagina": 1,
			"links":      modelo.ObterPagina(0, true),
			"msg":        "Link atualizado!!",
		})
	} else {

		erro := modelo.NovoLink(link)
		msg := "Link salvo com sucesso!"
		if erro != nil {
			msg = "OPA! Esse link já foi cadastrado O.o"
			log.Printf("Erro ao inserir novo link: %v\n", erro)
		}
		c.HTML(http.StatusOK, "resp-salvar.html", gin.H{
			"error": erro,
			"msg":   msg,
		})
	}
}
예제 #12
0
/**
 * Handler for POST /api/v1/admin/register
 */
func V1RegisterHandler(c *gin.Context) {
	request := AdminUser{
		Email:    c.PostForm("email"),
		Password: c.PostForm("password"),
	}

	failureResponse := gin.H{
		"status":  "failed",
		"message": "Could not complete registration",
	}

	currentUsers := GetAdminUsers()

	if len(currentUsers) > 0 {
		for _, user := range currentUsers {
			if request.Email == user.Email {
				c.JSON(http.StatusOK, failureResponse)
				return
			}
		}
	}

	request.hashPassword()
	err := SaveAdminUser(request)
	if err != nil {
		c.JSON(http.StatusOK, failureResponse)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"status":  "OK",
		"message": "User created successfully",
	})
}
func (h *FrontendHandlers) PostLogin(c *gin.Context) {
	data := &LoginData{
		Username: c.PostForm("username"),
		Password: c.PostForm("password"),
	}

	if v := validateLogin(data); v.HasError() {
		data.Validate = v.Messages()
		h.render.HTML(c.Writer, 200, "login", data)
		return
	}

	info, err := h.loginService.Login(data.Username, data.Password)
	if err != nil {
		data.Error = err.Error()
		h.render.HTML(c.Writer, 200, "login", data)
		return
	}

	session := sessions.Default(c)
	session.Set("user_id", info.Id)
	session.Save()

	c.Redirect(302, "/")
}
예제 #14
0
파일: main.go 프로젝트: highsoul/eshop
func UserLogin(c *gin.Context) {
	var cookie middleware.CookieManager
	cookie = c.MustGet("CM").(middleware.CookieManager)
	if c.Request.Method == "GET" {
		data := tool.GetTD(c)

		fmt.Println(data)
		c.HTML(http.StatusOK, "login.html", data)
	} else if c.Request.Method == "POST" {

		email := c.PostForm("email")
		password := c.PostForm("password")
		user := model.User{}
		model.T.DB.Debug().Where("email = ? and password = ?", email, password).First(&user)
		if user.Name != "" {
			cookie.Add("user_id", user.ID)
			cookie.WriteCookies()
			c.Redirect(http.StatusMovedPermanently, "/")
		} else {
			cookie.Flash("fail_msg", "login failed :(")
			c.Redirect(http.StatusMovedPermanently, "/user/login")
		}

	}
}
예제 #15
0
func (self *AppController) New(c *gin.Context) {
	username := self.CurrentUser(c)

	if username == "" {
		c.Redirect(http.StatusFound, "/")

		return
	}

	appName := c.PostForm("appName")

	err := app.Create(self.etcd, username, appName)

	if err != nil {
		fmt.Fprintf(os.Stderr, "%+v\n", err)

		c.HTML(http.StatusInternalServerError, "apps.tmpl", gin.H{
			"alert":   true,
			"error":   true,
			"message": "Failed to create app.",
		})

		return
	}

	c.Redirect(http.StatusSeeOther, "/apps/"+appName)
}
예제 #16
0
파일: login.go 프로젝트: senvid/gin-example
func LoginPostHandler(c *gin.Context) {
	email := c.PostForm("email")
	password := c.PostForm("password")
	if email != "" && password != "" {
		var user User
		DB.Where("email = ? and password = ?", email, password).Find(&user)

		if user.Uid == 0 {
			c.String(http.StatusUnauthorized, "false")
			return
		}

		//value := base64.StdEncoding.EncodeToString([]byte(strconv.Itoa(int(user.Uid))))
		value := strconv.Itoa(int(user.Uid))
		userCookie := http.Cookie{
			Name:     "user",
			Value:    value,
			MaxAge:   86400,
			HttpOnly: true,
		}
		log.Println("value 原始值:", value)
		//http.SetCookie(c.Writer, &userCookie)
		util.SetSecureCookie(c.Writer, &userCookie)
		//c.String(200, "ok")
		c.Redirect(301, "/")
	} else {
		c.String(http.StatusUnauthorized, "false")
	}

}
예제 #17
0
파일: main.go 프로젝트: brainopia/shorty
func Shorten(c *gin.Context) {
	url := c.PostForm("url")
	code := nextCode()
	record := Record{Url: url, Code: code}

	try(db.Create(&record).Error)
	c.String(200, "http://shorty.com/%s", code)
}
예제 #18
0
// BookCreate is for POST /books
func BookCreate(c *gin.Context) {
	book := models.Book{Title: c.PostForm("title")}
	if BookM.Create(&book) {
		c.Redirect(http.StatusMovedPermanently, "/books/new")
	} else {
		c.Redirect(http.StatusMovedPermanently, "/book/"+strconv.Itoa(int(book.ID)))
	}
}
예제 #19
0
// POST /posts/:id/edit
func Update(c *gin.Context) {
	p := SetPost(c)
	if p == nil {
		return
	}
	p.Update(c.PostForm("title"), c.PostForm("text"))
	ctl.Redirect(c, p.Path())
}
예제 #20
0
func startStreamHandler(c *gin.Context) {
	username := c.PostForm("username")
	title := c.PostForm("title")

	c.JSON(200, gin.H{
		"upload_url": "/streamPart/" + username + "/" + title + "/",
		"stream_id":  "stream-" + username + "-" + title,
	})
}
예제 #21
0
func FindUser(ctx *gin.Context) (*User, error) {
	db := ctx.MustGet("db").(*sql.DB)
	email := ctx.PostForm("email")
	user := new(User)
	err := db.QueryRow("SELECT * FROM classmates WHERE email=$1;", email).Scan(&user.Id, &user.Name, &user.Email, &user.Password, &user.CreatedAt, &user.UpdatedAt)
	if err != nil {
		return nil, err
	}
	return user, nil
}
예제 #22
0
func AccountsUpdater(c *gin.Context) {
	acc_id, err := strconv.ParseInt(c.Param("accountId"), 10, 64)
	if err != nil {
		log.Fatal(err)
	}

	trans_id, err := strconv.ParseInt(c.PostForm("ID"), 10, 64)
	if err != nil {
		log.Printf("Invalid ID: %v - %v\n", trans_id, err)
		return
	}

	var account *Account
	for _, acc := range accounts {
		if acc.ID == acc_id {
			account = acc
			break
		}
	}

	var transaction Transaction
	for _, trans := range account.Transactions {
		if trans.ID == trans_id {
			transaction = trans
		}
	}

	transaction.Payee = c.PostForm("Payee")
	transaction.Memo = c.PostForm("Memo")
	debit, err := decimal.NewFromString(c.PostForm("Debit"))
	if err != nil {
		log.Printf("Invalid Debit %v\n", err)
	} else {
		transaction.Debit = debit
	}
	credit, err := decimal.NewFromString(c.PostForm("Credit"))
	if err != nil {
		log.Printf("Invalid Credit %v\n", err)
	} else {
		transaction.Credit = credit
	}

	for trans_key, trans := range account.Transactions {
		if trans.ID == trans_id {
			account.Transactions[trans_key] = transaction

			jsonResponse, err := json.Marshal(transaction)
			if err != nil {
				log.Printf("Json marshaling error: %v\n", err)
				return
			}
			c.JSON(http.StatusOK, jsonResponse)
		}
	}
}
예제 #23
0
파일: main.go 프로젝트: 4Second2None/gin
func roomPOST(c *gin.Context) {
	roomid := c.Param("roomid")
	userid := c.PostForm("user")
	message := c.PostForm("message")
	room(roomid).Submit(userid + ": " + message)

	c.JSON(200, gin.H{
		"status":  "success",
		"message": message,
	})
}
예제 #24
0
파일: server.go 프로젝트: TTUCourse/TTUPyQ
func postApiPostsPage(c *gin.Context) {
	page, _ := strconv.ParseInt(c.PostForm("p"), 0, 64)
	var list []PostInfo
	_, err := dbmap.Select(&list, "SELECT id, author, title, time FROM PYQ LIMIT ?,10", (page-1)*10)
	if err == nil {
		c.JSON(http.StatusOK, list)
	} else {
		checkErr(err, "postApi Error")
		c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
	}
}
예제 #25
0
// add accepts a form post and creates a new
// greoting in the system. It could be made a
// lot smarter and automatically check for the
// content type to handle forms, JSON etc...
func (g greeter) add(c *gin.Context) {
	ctx := getContext(c)
	req := &engine.AddGreetingRequest{
		Author:  c.PostForm("Author"),
		Content: c.PostForm("Content"),
	}
	g.Add(ctx, req)
	// TODO: set a flash cookie for "added"
	// if this was a web request, otherwise
	// send a nice JSON response ...
	c.Redirect(http.StatusFound, "/")
}
예제 #26
0
파일: main.go 프로젝트: highsoul/eshop
func DelAddress(c *gin.Context) {

	var cookie middleware.CookieManager
	cookie = c.MustGet("CM").(middleware.CookieManager)
	a_id, _ := strconv.Atoi(c.PostForm("id"))
	address := model.Address{}
	address.Get(a_id)
	fmt.Println(address)
	address.Delete()
	cookie.Flash("success_msg", "address delete success")
	c.JSON(http.StatusOK, address)
}
예제 #27
0
파일: developers.go 프로젝트: mottam/goploy
func UpdateDeveloper(c *gin.Context) {
	changes := &m.Developer{Name: c.PostForm("name"), GithubAccount: c.PostForm("github")}
	dev := &m.Developer{}
	dev.LoggedUser(&db, c)
	err := dev.Update(&db, changes)
	if err != nil {
		c.Error(err)
	} else {
		c.Redirect(http.StatusFound, "/")
		c.Abort()
	}
}
예제 #28
0
파일: main.go 프로젝트: aclisp/kubecon
func updateConfig(c *gin.Context) {
	if c.MustGet(gin.AuthUserKey).(string) != "admin" {
		c.HTML(http.StatusInternalServerError, "error", gin.H{"error": "Unauthorized"})
		return
	}

	kubeclient.KubeConfig.APIServerURL = c.PostForm("inputAPIServerURL")
	kubeclient.KubeConfig.Username = c.PostForm("inputUsername")
	kubeclient.KubeConfig.Password = c.PostForm("inputPassword")
	kubeclient.SaveKubeConfig()
	kubeclient.Init()
	c.Redirect(http.StatusMovedPermanently, "/")
}
예제 #29
0
// BookUpdate is for POST /book/:id
func BookUpdate(c *gin.Context) {
	var book models.Book
	var err error
	if book, err = models.NewBookWithID(c.Param("id")); err == nil {
		book.Title = c.PostForm("title")
		err = book.Save()
	}
	if err == nil {
		c.Redirect(http.StatusMovedPermanently, "/book/"+strconv.Itoa(int(book.ID)))
	} else {
		c.HTML(http.StatusNotFound, "404.tmpl", nil)
	}
}
예제 #30
0
func slashLoginPOST(c *gin.Context) {
	loginGroup := sessions.Default(c)
	group := strings.ToLower(c.PostForm("group"))
	if _, err := os.Stat(path.Join("data", group+".db")); err == nil {
		loginGroup.Set("group", group)
		loginGroup.Save()
		c.Redirect(302, "/dashboard/"+group)
	} else {
		c.HTML(http.StatusOK, "login.tmpl", gin.H{
			"ErrorMessage": "Incorrect login.",
		})
	}
}