Beispiel #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})
}
Beispiel #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,
	})
}
Beispiel #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"))))
	}
}
Beispiel #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)
}
Beispiel #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)
		}
	}
}
Beispiel #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,
	})
}
Beispiel #7
0
// Logout is a route that logs the current user and redirects to the home page.
func Logout(c *gin.Context) {
	session := sessions.Default(c)
	defer session.Save()

	var userID uint // userID must be a uint, sets userID to 0
	session.Set("userID", userID)

	// returnURL can come from GET or POST or use default.
	returnURL := c.DefaultQuery("return_url", c.DefaultPostForm("return_url", "/"))
	c.Redirect(http.StatusFound, returnURL)
}
Beispiel #8
0
func (pc *BuildController) postBuild(c *gin.Context) {

	app, err := pc.getApp(c)
	if err != nil {
		c.JSON(http.StatusNotFound, err)
		return
	}

	commitHash := c.DefaultPostForm("commit_hash", "")

	build := models.BuildMapper.Create(app, commitHash)

	file, _, err := c.Request.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, errors.New(errors.Error{
			Label: "invalid_file",
			Field: "file",
			Text:  "Missing zip file",
		}))
		return
	}
	defer file.Close()

	if err := build.AttachFile(file); err != nil {
		c.JSON(http.StatusBadRequest, errors.New(errors.Error{
			Label: "invalid_file",
			Field: "file",
			Text:  err.Error(),
		}))
		return
	}

	if err := models.BuildMapper.Save(build); err != nil {
		panic(err)
	}

	if c.DefaultQuery("deploy", "0") == "1" {

		resp, err := http.Post(fmt.Sprintf("http://localhost:8080/api/apps/%s/builds/%s/deploy", app.Id.Hex(), build.Id.Hex()), "json/application", nil)
		if err != nil {
			c.JSON(http.StatusBadRequest, errors.New(errors.Error{
				Label: "deploy_issue",
				Field: "deploy",
				Text:  err.Error(),
			}))
			return
		}
		resp.Body.Close()
	}

	c.JSON(http.StatusCreated, build)
}
Beispiel #9
0
func doPOSTGoogleOauth2Login(c *gin.Context) {

	oauthtoken := c.DefaultPostForm("oauthtoken", "undefined")

	err := aa.AuthorizeGoogleOauth2(c, oauthtoken)
	if err != nil {
		c.HTML(http.StatusOK, "logingoauth2.tmpl", gin.H{
			"error": err,
		})
	} else {
		c.Redirect(http.StatusSeeOther, "/w")
	}
}
func handleAddComment(c *gin.Context) {
	db, err := connectDB()
	if err != nil {
		c.Redirect(http.StatusFound, "/")
		return
	}
	parent_id := c.DefaultPostForm("parent_id", DEFAULT_POST)
	name := c.DefaultPostForm("name", DEFAULT_POST)
	comment := c.DefaultPostForm("comment", DEFAULT_POST)
	replyer_name := c.DefaultPostForm("replyer_name", DEFAULT_POST)
	if !(parent_id == DEFAULT_POST || name == DEFAULT_POST ||
		replyer_name == DEFAULT_POST || comment == DEFAULT_POST) {

		i_parent_id, err := strconv.ParseInt(parent_id, 10, 32)
		if err == nil {
			db.Create(&MessageBoard{
				ParentId:    int(i_parent_id),
				Nickname:    name,
				ReplyerName: replyer_name,
				Content:     comment,
				Time:        time.Now(),
			})
		}
	}
	db.Close()
	c.Redirect(http.StatusFound, "/")
}
Beispiel #11
0
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})
}
Beispiel #12
0
func doPOSTEntry(c *gin.Context) {

	ws := normalize(c.Param("ws"))
	id := normalize(c.Param("id"))

	entry := model.Entry{
		Workspace: ws,
		ID:        id,
		Markdown:  c.DefaultPostForm("Markdown", "undefined"),
	}

	err := instance.Srv.Store.Entry.StoreEntry(&entry)
	if err != nil {
		dumpError(c, err)
		return
	}
	c.Redirect(http.StatusSeeOther, "/w/"+ws)
	return

}
Beispiel #13
0
func Do(c *gin.Context) {
	ac := getAppConfig(c)

	instanceID := c.PostForm("instance")
	if _, ok := ac.Instances[instanceID]; ok == false {
		c.JSON(http.StatusOK, gin.H{
			"status": "failure",
			"msg":    "不存在目标应用",
		})
		return
	}
	targetAction := c.PostForm("action")
	if validAction(targetAction) == false {
		c.JSON(http.StatusOK, gin.H{
			"status": "failure",
			"msg":    "不存在目标action",
		})
		return
	}
	m, err := newMemcached(ac.Instances[instanceID].Source)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"status": "failure",
			"msg":    "目标Memcached服务连接失败:" + err.Error(),
		})
		return
	}
	defer m.Close()

	targetInstanceConfig := ac.Instances[instanceID]
	targetMiddleman := MiddlemanManager.Get(targetInstanceConfig.MiddlemanName, targetInstanceConfig.MiddlemanConfig)
	if targetMiddleman == nil {
		targetMiddleman = MiddlemanManager.Get("default", nil)
	}

	switch {
	case targetAction == "get":
		key := targetMiddleman.GenInnerKey(c.PostForm("key"))
		resp, err := m.Get(key)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"status": "failure",
				"msg":    "获取缓存数据失败:" + err.Error(),
			})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"status": "success",
			"data":   targetMiddleman.UnserializeValue(resp),
		})
		return
	case targetAction == "set":
		key := targetMiddleman.GenInnerKey(c.PostForm("key"))
		value := targetMiddleman.SerializeValue(c.PostForm("value"))
		expTime := c.DefaultPostForm("exp_time", "0")
		expTimeInt, err := strconv.Atoi(expTime)
		if err != nil {
			expTimeInt = 0
		}
		resp, err := m.Set(memcached.StorageCmdArgStruct{"key": key, "value": value, "expire_time": expTimeInt})
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"status": "failure",
				"msg":    "添加缓存失败:" + err.Error(),
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"status": "success",
			"data":   string(resp),
		})
	case targetAction == "delete":
		key := targetMiddleman.GenInnerKey(c.PostForm("key"))
		resp, err := m.Delete(key)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"status": "failure",
				"msg":    "删除缓存失败:" + err.Error(),
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"status": "success",
			"data":   string(resp),
		})
	case targetAction == "flush_all":
		resp, err := m.FlushAll()
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"status": "failure",
				"msg":    "清空缓存失败:" + err.Error(),
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"status": "success",
			"data":   string(resp),
		})
	}
}
Beispiel #14
0
// Create handles the multipart form upload and creates a file
func Create(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()

	u := uniuri.NewLen(conf.C.UniURILength)
	file, err := os.Create(path.Join(conf.C.UploadDir, u))
	if err != nil {
		logger.ErrC(c, "server", "Couldn't create file", err)
		c.String(http.StatusInternalServerError, "Something went wrong on the server side. Try again later.")
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}
	defer file.Close()

	wr, err := io.Copy(file, bufio.NewReaderSize(fd, 512))
	if err != nil {
		logger.ErrC(c, "server", "Couldn't write file", err)
		c.String(http.StatusInternalServerError, "Something went wrong on the server side. Try again later.")
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}
	if conf.C.DiskQuota > 0 {
		if models.S.CurrentSize+uint64(wr) > uint64(conf.C.DiskQuota*utils.GigaByte) {
			logger.ErrC(c, "server", "Quota exceeded")
			c.String(http.StatusBadRequest, "Not enough free space. Try again later.")
			c.AbortWithStatus(http.StatusBadRequest)
			os.Remove(path.Join(conf.C.UploadDir, u))
			return
		}
	}
	newres := &models.Resource{
		Key:      u,
		Name:     h.Filename,
		Once:     once,
		DeleteAt: time.Now().Add(duration),
		Size:     wr,
	}
	if err = newres.Save(); err != nil {
		logger.ErrC(c, "server", "Couldn't save in database", err)
		c.String(http.StatusInternalServerError, "Something went wrong on the server. Try again later.")
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}
	newres.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\n", utils.DetectScheme(c), ns, u)
}
Beispiel #15
0
func buttonPressed(c *gin.Context, name string) bool {
	return c.DefaultPostForm(name, "undefined") != "undefined"
}