Example #1
0
func login(c echo.Context) error {
	username := c.FormValue("username")
	password := c.FormValue("password")

	if username == "jon" && password == "shhh!" {
		// Create token
		token := jwt.New(jwt.SigningMethodHS256)

		// Set claims
		claims := token.Claims.(jwt.MapClaims)
		claims["name"] = "Jon Snow"
		claims["admin"] = true
		claims["exp"] = time.Now().Add(time.Hour * 72).Unix()

		// Generate encoded token and send it as response.
		t, err := token.SignedString([]byte("secret"))
		if err != nil {
			return err
		}
		return c.JSON(http.StatusOK, map[string]string{
			"token": t,
		})
	}

	return echo.ErrUnauthorized
}
Example #2
0
func (RuleController) Del(ctx echo.Context) error {
	err := logic.DefaultRule.Delete(ctx, ctx.FormValue("id"))
	if err != nil {
		return fail(ctx, 1, "删除失败")
	}
	return success(ctx, nil)
}
Example #3
0
// 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)
}
Example #4
0
func login(c echo.Context) error {
	username := c.FormValue("username")
	password := c.FormValue("password")

	if username == "jon" && password == "shhh!" {

		// Set custom claims
		claims := &jwtCustomClaims{
			"Jon Snow",
			true,
			jwt.StandardClaims{
				ExpiresAt: time.Now().Add(time.Hour * 72).Unix(),
			},
		}

		// Create token with claims
		token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

		// Generate encoded token and send it as response.
		t, err := token.SignedString([]byte("secret"))
		if err != nil {
			return err
		}
		return c.JSON(http.StatusOK, map[string]string{
			"token": t,
		})
	}

	return echo.ErrUnauthorized
}
Example #5
0
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())
}
Example #6
0
func upload(c echo.Context) error {
	// Read form fields
	name := c.FormValue("name")
	email := c.FormValue("email")

	//-----------
	// Read file
	//-----------

	// Source
	file, err := c.FormFile("file")
	if err != nil {
		return err
	}
	src, err := file.Open()
	if err != nil {
		return err
	}
	defer src.Close()

	// Destination
	dst, err := os.Create(file.Filename)
	if err != nil {
		return err
	}
	defer dst.Close()

	// Copy
	if _, err = io.Copy(dst, src); err != nil {
		return err
	}

	return c.HTML(http.StatusOK, fmt.Sprintf("<p>File %s uploaded successfully with fields name=%s and email=%s.</p>", file.Filename, name, email))
}
Example #7
0
// 删除消息
func (MessageController) Delete(ctx echo.Context) error {
	id := ctx.FormValue("id")
	msgtype := ctx.FormValue("msgtype")
	if !logic.DefaultMessage.DeleteMessage(ctx, id, msgtype) {
		return fail(ctx, 1, "对不起,删除失败,请稍候再试!")
	}

	return success(ctx, nil)
}
Example #8
0
func parseConds(ctx echo.Context, fields []string) map[string]string {
	conds := make(map[string]string)

	for _, field := range fields {
		if value := ctx.FormValue(field); value != "" {
			conds[field] = value
		}
	}

	return conds
}
Example #9
0
// ChangePwd 修改密码
func (AccountController) ChangePwd(ctx echo.Context) error {
	curUser := ctx.Get("user").(*model.Me)

	curPasswd := ctx.FormValue("cur_passwd")
	newPasswd := ctx.FormValue("passwd")
	errMsg, err := logic.DefaultUser.UpdatePasswd(ctx, curUser.Username, curPasswd, newPasswd)
	if err != nil {
		return fail(ctx, 1, errMsg)
	}
	return success(ctx, nil)
}
Example #10
0
File: gomd.go Project: nochso/gomd
func EditHandlerPost(c echo.Context) error {
	filepath := c.P(0)
	eolIndex, _ := strconv.Atoi(c.FormValue("eol"))
	content := c.FormValue("content")
	convertedContent, err := eol.LineEnding(eolIndex).Apply(content)
	if err != nil {
		convertedContent = content
		log.Println("Error while converting EOL. Saving without conversion.")
	}
	ioutil.WriteFile(filepath, []byte(convertedContent), 0644)
	c.Set("editorView", NewEditorView(filepath, content))
	return EditHandler(c)
}
Example #11
0
// Transfer 转换图片:通过 url 从远程下载图片然后转存到七牛
func (ImageController) Transfer(ctx echo.Context) error {
	origUrl := ctx.FormValue("url")
	if origUrl == "" {
		return fail(ctx, 1, "url不能为空!")
	}

	path, err := logic.DefaultUploader.TransferUrl(ctx, origUrl)
	if err != nil {
		return fail(ctx, 2, "文件上传失败!")
	}

	return success(ctx, map[string]interface{}{"uri": logic.ImageDomain + path})
}
Example #12
0
// 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)
}
Example #13
0
// New 新建规则
func (RuleController) New(ctx echo.Context) error {
	var data = make(map[string]interface{})

	if ctx.FormValue("submit") == "1" {
		user := ctx.Get("user").(*model.Me)

		errMsg, err := logic.DefaultRule.Save(ctx, ctx.FormParams(), user.Username)
		if err != nil {
			return fail(ctx, 1, errMsg)
		}
		return success(ctx, nil)
	}

	return render(ctx, "rule/new.html", data)
}
Example #14
0
// Create 创建wiki页
func (WikiController) Create(ctx echo.Context) error {
	title := ctx.FormValue("title")
	// 请求新建 wiki 页面
	if title == "" || ctx.Request().Method() != "POST" {
		return render(ctx, "wiki/new.html", map[string]interface{}{"activeWiki": "active"})
	}

	me := ctx.Get("user").(*model.Me)
	err := logic.DefaultWiki.Create(ctx, me, ctx.FormParams())
	if err != nil {
		return fail(ctx, 1, "内部服务错误")
	}

	return success(ctx, nil)
}
Example #15
0
// Create 新建项目
func (ProjectController) Create(ctx echo.Context) error {
	name := ctx.FormValue("name")
	// 请求新建项目页面
	if name == "" || ctx.Request().Method() != "POST" {
		project := &model.OpenProject{}
		return render(ctx, "projects/new.html", map[string]interface{}{"project": project, "activeProjects": "active"})
	}

	user := ctx.Get("user").(*model.Me)
	err := logic.DefaultProject.Publish(ctx, user, ctx.FormParams())
	if err != nil {
		return fail(ctx, 1, "内部服务错误!")
	}
	return success(ctx, nil)
}
Example #16
0
// ChangeAvatar 更换头像
func (AccountController) ChangeAvatar(ctx echo.Context) error {
	objLog := getLogger(ctx)

	curUser := ctx.Get("user").(*model.Me)

	// avatar 为空时,表示使用 gravater 头像
	avatar := ctx.FormValue("avatar")
	err := logic.DefaultUser.ChangeAvatar(ctx, curUser.Uid, avatar)
	if err != nil {
		objLog.Errorln("account controller change avatar error:", err)

		return fail(ctx, 2, "更换头像失败")
	}

	return success(ctx, nil)
}
Example #17
0
func SetCookie(ctx echo.Context, username string) {
	Store.Options.HttpOnly = true

	session := GetCookieSession(ctx)
	if ctx.FormValue("remember_me") != "1" {
		// 浏览器关闭,cookie删除,否则保存30天(github.com/gorilla/sessions 包的默认值)
		session.Options = &sessions.Options{
			Path:     "/",
			HttpOnly: true,
		}
	}
	session.Values["username"] = username
	req := Request(ctx)
	resp := ResponseWriter(ctx)
	session.Save(req, resp)
}
Example #18
0
// Create 新建主题
func (TopicController) Create(ctx echo.Context) error {
	nodes := logic.GenNodes()

	title := ctx.FormValue("title")
	// 请求新建主题页面
	if title == "" || ctx.Request().Method() != "POST" {
		return render(ctx, "topics/new.html", map[string]interface{}{"nodes": nodes, "activeTopics": "active"})
	}

	me := ctx.Get("user").(*model.Me)
	err := logic.DefaultTopic.Publish(ctx, me, ctx.FormParams())
	if err != nil {
		return fail(ctx, 1, "内部服务错误")
	}

	return success(ctx, nil)
}
Example #19
0
// Like 喜欢(或取消喜欢)
func (LikeController) Like(ctx echo.Context) error {
	form := ctx.FormParams()
	if !util.CheckInt(form, "objtype") || !util.CheckInt(form, "flag") {
		return fail(ctx, 1, "参数错误")
	}

	user := ctx.Get("user").(*model.Me)
	objid := goutils.MustInt(ctx.Param("objid"))
	objtype := goutils.MustInt(ctx.FormValue("objtype"))
	likeFlag := goutils.MustInt(ctx.FormValue("flag"))

	err := logic.DefaultLike.LikeObject(ctx, user.Uid, objid, objtype, likeFlag)
	if err != nil {
		return fail(ctx, 2, "服务器内部错误")
	}

	return success(ctx, nil)
}
Example #20
0
// ActivateAccount will activate a user account from a token or an admin.
func ActivateAccount(c echo.Context) error {
	db := ToDB(c)
	token, password := c.Param("token"), c.FormValue("password")
	usr, err := db.GetAccountByToken(token)
	if err != nil {
		return ErrInvalidActivationToken.Log(err)
	}

	usr.SetActive()
	if err := usr.SetPassword(password); err != nil {
		return ErrPasswordSimple.Log(err)
	}

	if err := db.UpdateAccount(usr); err != nil {
		return ErrSaving.Log(err)
	}

	return c.JSON(http.StatusOK, usr)
}
Example #21
0
File: api.go Project: nubunto/vise
func SaveFile(c echo.Context) error {
	req := c.Request()

	days, err := strconv.Atoi(c.FormValue("days"))
	if err != nil {
		return err
	}

	file, err := req.FormFile("file")
	if err != nil {
		return err
	}

	srcFile, err := file.Open()
	if err != nil {
		return err
	}
	defer srcFile.Close()

	userToken := c.FormValue("user-token")
	if len(userToken) == 0 {
		userToken = uuid.New()
	}
	fileToken := uuid.New()
	boltFile := types.File{
		UserToken:     userToken,
		FileToken:     fileToken,
		DaysAvailable: days,
		Filename:      file.Filename,
	}
	err = uppath.UploadFile(boltFile, srcFile)
	if err != nil {
		return err
	}

	err = persistence.Save(boltFile)
	if err != nil {
		return err
	}

	return c.JSON(http.StatusOK, FileUploadResponse{ResponseOK, userToken})
}
Example #22
0
// Create 收藏(取消收藏)
func (FavoriteController) Create(ctx echo.Context) error {
	objtype := goutils.MustInt(ctx.FormValue("objtype"))
	objid := goutils.MustInt(ctx.Param("objid"))
	collect := goutils.MustInt(ctx.FormValue("collect"))

	user := ctx.Get("user").(*model.Me)

	var err error
	if collect == 1 {
		err = logic.DefaultFavorite.Save(ctx, user.Uid, objid, objtype)
	} else {
		err = logic.DefaultFavorite.Cancel(ctx, user.Uid, objid, objtype)
	}

	if err != nil {
		return fail(ctx, 1, err.Error())
	}

	return success(ctx, nil)
}
Example #23
0
// SendActivateEmail 发送注册激活邮件
func (self AccountController) SendActivateEmail(ctx echo.Context) error {
	uuid := ctx.FormValue("uuid")
	if uuid != "" {
		email, ok := regActivateCodeMap[uuid]
		if !ok {
			return fail(ctx, 1, "非法请求")
		}

		go logic.DefaultEmail.SendActivateMail(email, uuid)
	} else {
		user, ok := ctx.Get("user").(*model.Me)
		if !ok {
			return fail(ctx, 1, "非法请求")
		}

		go logic.DefaultEmail.SendActivateMail(user.Email, self.genUUID(user.Email))
	}

	return success(ctx, nil)
}
Example #24
0
func upload(c echo.Context) error {
	// Read form fields
	name := c.FormValue("name")
	email := c.FormValue("email")

	//------------
	// Read files
	//------------

	// Multipart form
	form, err := c.MultipartForm()
	if err != nil {
		return err
	}
	files := form.File["files"]

	for _, file := range files {
		// Source
		src, err := file.Open()
		if err != nil {
			return err
		}
		defer src.Close()

		// Destination
		dst, err := os.Create(file.Filename)
		if err != nil {
			return err
		}
		defer dst.Close()

		// Copy
		if _, err = io.Copy(dst, src); err != nil {
			return err
		}

	}

	return c.HTML(http.StatusOK, fmt.Sprintf("<p>Uploaded successfully %d files with fields name=%s and email=%s.</p>", len(files), name, email))
}
Example #25
0
func (self InstallController) SetupConfig(ctx echo.Context) error {
	// config/env.ini 存在
	if db.MasterDB != nil {
		if logic.DefaultInstall.IsTableExist(ctx) {
			return ctx.Redirect(http.StatusSeeOther, "/")
		}
		return ctx.Redirect(http.StatusSeeOther, "/install/do")
	}

	step := goutils.MustInt(ctx.QueryParam("step"))
	if step == 2 {
		err := self.genConfig(ctx)
		if err != nil {
			data := map[string]interface{}{
				"dbhost":   ctx.FormValue("dbhost"),
				"dbport":   ctx.FormValue("dbport"),
				"dbname":   ctx.FormValue("dbname"),
				"uname":    ctx.FormValue("uname"),
				"err_type": 1,
			}

			if err == db.ConnectDBErr {
				data["err_type"] = 1
			} else if err == db.UseDBErr {
				data["err_type"] = 2
			}

			return renderInstall(ctx, "install/setup-err.html", data)
		}
	}
	return renderInstall(ctx, "install/setup-config.html", map[string]interface{}{"step": step})
}
Example #26
0
// 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)
}
Example #27
0
// ForgetPasswd 忘记密码
func (AccountController) ForgetPasswd(ctx echo.Context) error {
	if _, ok := ctx.Get("user").(*model.Me); ok {
		return ctx.Redirect(http.StatusSeeOther, "/")
	}

	contentTpl := "user/forget_pwd.html"
	data := map[string]interface{}{"activeUsers": "active"}

	email := ctx.FormValue("email")
	if email == "" || ctx.Request().Method() != "POST" {
		return render(ctx, contentTpl, data)
	}

	// 校验email是否存在
	if logic.DefaultUser.UserExists(ctx, "email", email) {
		var uuid string
		for {
			uuid = guuid.NewV4().String()
			if _, ok := resetPwdMap[uuid]; !ok {
				resetPwdMap[uuid] = email
				break
			}
			logger.Infoln("forget passwd GenUUID 冲突....")
		}
		var emailUrl string
		if strings.HasSuffix(email, "@gmail.com") {
			emailUrl = "http://mail.google.com"
		} else {
			pos := strings.LastIndex(email, "@")
			emailUrl = "http://mail." + email[pos+1:]
		}
		data["success"] = template.HTML(`一封包含了重设密码链接的邮件已经发送到您的注册邮箱,按照邮件中的提示,即可重设您的密码。<a href="` + emailUrl + `" target="_blank">立即前往邮箱</a>`)
		go logic.DefaultEmail.SendResetpwdMail(email, uuid)
	} else {
		data["error"] = "该邮箱没有在本社区注册过!"
	}

	return render(ctx, contentTpl, data)
}
Example #28
0
// Publish
func (ReadingController) Publish(ctx echo.Context) error {
	var data = make(map[string]interface{})

	if ctx.FormValue("submit") == "1" {
		user := ctx.Get("user").(*model.Me)
		errMsg, err := logic.DefaultReading.SaveReading(ctx, ctx.FormParams(), user.Username)
		if err != nil {
			return fail(ctx, 1, errMsg)
		}
		return success(ctx, nil)
	}

	id := goutils.MustInt(ctx.QueryParam("id"))
	if id != 0 {
		reading := logic.DefaultReading.FindById(ctx, id)
		if reading != nil {
			data["reading"] = reading
		}
	}

	return render(ctx, "reading/modify.html", data)
}
Example #29
0
// CrawlProject
func (ProjectController) CrawlProject(ctx echo.Context) error {
	var data = make(map[string]interface{})

	if ctx.FormValue("submit") == "1" {
		urls := strings.Split(ctx.FormValue("urls"), "\n")

		var errMsg string
		for _, projectUrl := range urls {
			err := logic.DefaultProject.ParseProjectList(strings.TrimSpace(projectUrl))
			if err != nil {
				errMsg = err.Error()
			}
		}

		if errMsg != "" {
			return fail(ctx, 1, errMsg)
		}
		return success(ctx, nil)
	}

	return render(ctx, "project/new.html", data)
}
Example #30
0
// Modify 编辑规则
func (self RuleController) Modify(ctx echo.Context) error {
	var data = make(map[string]interface{})

	if ctx.FormValue("submit") == "1" {
		user := ctx.Get("user").(*model.Me)

		errMsg, err := logic.DefaultRule.Save(ctx, ctx.FormParams(), user.Username)
		if err != nil {
			return fail(ctx, 1, errMsg)
		}
		return success(ctx, nil)
	}

	rule := logic.DefaultRule.FindById(ctx, ctx.QueryParam("id"))
	if rule == nil {
		return ctx.Redirect(http.StatusSeeOther, ctx.Echo().URI(echo.HandlerFunc(self.RuleList)))
	}

	data["rule"] = rule

	return render(ctx, "rule/modify.html", data)
}