Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

Better form validation (#77)

Guilherme Oenning1fe161ffca10
diff --git a/app/handlers/idea.go b/app/handlers/idea.go
index a675d2095..cf69b0e89 100644
--- a/app/handlers/idea.go
+++ b/app/handlers/idea.go
@@ -1,12 +1,9 @@
package handlers
import (
- "strings"
-
"github.com/getfider/fider/app"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/im"
"github.com/getfider/fider/app/pkg/web"
- "github.com/getfider/fider/app/validate"
)
// Index is the default home page
@@ -23,28 +20,12 @@ func Index() web.HandlerFunc {
}
}
-type ideaInput struct {
- Title string `json:"title"`
- Description string `json:"description"`
-}
-
// PostIdea creates a new idea on current tenant
func PostIdea() web.HandlerFunc {
return func(c web.Context) error {
- input := new(ideaInput)
- if err := c.Bind(input); err != nil {
- return c.Failure(err)
- }
-
- ok, messages, err := validate.Idea(input.Title, input.Description)
- if err != nil {
- return c.Failure(err)
- }
-
- if !ok {
- return c.BadRequest(web.Map{
- "message": strings.Join(messages, ","),
- })
+ input := new(im.Idea)
+ if result := c.BindTo(input); !result.Ok {
+ return c.HandleValidation(result)
}
ideas := c.Services().Ideas
@@ -69,20 +50,9 @@ func UpdateIdea() web.HandlerFunc {
return c.Failure(err)
}
- input := new(ideaInput)
- if err := c.Bind(input); err != nil {
- return c.Failure(err)
- }
-
- ok, messages, err := validate.Idea(input.Title, input.Description)
- if err != nil {
- return c.Failure(err)
- }
-
- if !ok {
- return c.BadRequest(web.Map{
- "message": strings.Join(messages, ","),
- })
+ input := new(im.Idea)
+ if result := c.BindTo(input); !result.Ok {
+ return c.HandleValidation(result)
}
idea, err := c.Services().Ideas.GetByNumber(number)
@@ -128,22 +98,12 @@ func IdeaDetails() web.HandlerFunc {
}
}
-type newCommentInput struct {
- Content string `json:"content"`
-}
-
// PostComment creates a new comment on given idea
func PostComment() web.HandlerFunc {
return func(c web.Context) error {
- input := new(newCommentInput)
- if err := c.Bind(input); err != nil {
- return c.Failure(err)
- }
-
- if strings.Trim(input.Content, " ") == "" {
- return c.BadRequest(web.Map{
- "message": "Comment is required.",
- })
+ input := new(im.NewComment)
+ if result := c.BindTo(input); !result.Ok {
+ return c.HandleValidation(result)
}
ideaNumber, err := c.ParamAsInt("number")
@@ -164,29 +124,12 @@ func PostComment() web.HandlerFunc {
}
}
-type setResponseInput struct {
- Status int `json:"status"`
- Text string `json:"text"`
-}
-
// SetResponse changes current idea staff response
func SetResponse() web.HandlerFunc {
return func(c web.Context) error {
- input := new(setResponseInput)
- if err := c.Bind(input); err != nil {
- return c.Failure(err)
- }
-
- if input.Status < models.IdeaNew || input.Status > models.IdeaDeclined {
- return c.BadRequest(web.Map{
- "message": "Status is invalid.",
- })
- }
-
- if strings.Trim(input.Text, " ") == "" {
- return c.BadRequest(web.Map{
- "message": "Text is required.",
- })
+ input := new(im.SetResponse)
+ if result := c.BindTo(input); !result.Ok {
+ return c.HandleValidation(result)
}
ideaNumber, err := c.ParamAsInt("number")
diff --git a/app/handlers/signup.go b/app/handlers/signup.go
index ee3fb61ef..58c2d2fb1 100644
--- a/app/handlers/signup.go
+++ b/app/handlers/signup.go
@@ -7,24 +7,20 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/im"
"github.com/getfider/fider/app/pkg/env"
- "github.com/getfider/fider/app/pkg/jwt"
+ "github.com/getfider/fider/app/pkg/validate"
"github.com/getfider/fider/app/pkg/web"
- "github.com/getfider/fider/app/validate"
)
// CheckAvailability checks if given domain is available to be used
func CheckAvailability() web.HandlerFunc {
return func(c web.Context) error {
subdomain := strings.ToLower(c.Param("subdomain"))
- ok, messages, err := validate.Subdomain(c.Services().Tenants, subdomain)
- if err != nil {
- return c.Failure(err)
- }
- if !ok {
+ if result := validate.Subdomain(c.Services().Tenants, subdomain); !result.Ok {
return c.Ok(web.Map{
- "message": strings.Join(messages, ","),
+ "message": strings.Join(result.Messages, ","),
})
}
@@ -32,50 +28,12 @@ func CheckAvailability() web.HandlerFunc {
}
}
-type createTenantInput struct {
- Token string `json:"token"`
- Name string `json:"name"`
- Subdomain string `json:"subdomain"`
-}
-
//CreateTenant creates a new tenant
func CreateTenant() web.HandlerFunc {
return func(c web.Context) error {
- input := new(createTenantInput)
- if err := c.Bind(input); err != nil {
- return c.Failure(err)
- }
-
- if input.Token == "" {
- return c.BadRequest(web.Map{
- "message": "Please identify yourself before proceeding",
- })
- }
-
- claims, err := jwt.DecodeOAuthClaims(input.Token)
- if err != nil {
- return c.Failure(err)
- }
-
- if env.IsSingleHostMode() {
- input.Subdomain = "default"
- }
-
- if input.Name == "" {
- return c.BadRequest(web.Map{
- "message": "Name is required",
- })
- }
-
- ok, messages, err := validate.Subdomain(c.Services().Tenants, input.Subdomain)
- if err != nil {
- return c.Failure(err)
- }
-
- if !ok {
- return c.BadRequest(web.Map{
- "message": strings.Join(messages, ","),
- })
+ input := new(im.CreateTenant)
+ if result := c.BindTo(input); !result.Ok {
+ return c.HandleValidation(result)
}
tenant, err := c.Services().Tenants.Add(input.Name, input.Subdomain)
@@ -84,14 +42,15 @@ func CreateTenant() web.HandlerFunc {
}
user := &models.User{
- Name: claims.OAuthName,
- Email: claims.OAuthEmail,
+ Name: input.UserClaims.OAuthName,
+ Email: input.UserClaims.OAuthEmail,
Tenant: tenant,
Role: models.RoleAdministrator,
Providers: []*models.UserProvider{
- {UID: claims.OAuthID, Name: claims.OAuthProvider},
+ {UID: input.UserClaims.OAuthID, Name: input.UserClaims.OAuthProvider},
},
}
+
if err := c.Services().Users.Register(user); err != nil {
return c.Failure(err)
}
diff --git a/app/handlers/signup_test.go b/app/handlers/signup_test.go
index 3b155e921..be95b8dde 100644
--- a/app/handlers/signup_test.go
+++ b/app/handlers/signup_test.go
@@ -7,9 +7,9 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/handlers"
- "github.com/getfider/fider/app/pkg/mock"
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/jwt"
+ "github.com/getfider/fider/app/pkg/mock"
"github.com/getfider/fider/app/pkg/web"
"github.com/getfider/fider/app/storage/inmemory"
. "github.com/onsi/gomega"
@@ -111,42 +111,6 @@ func TestCreateTenantHandler_EmptyInput(t *testing.T) {
Expect(code).To(Equal(400))
}
-func TestCreateTenantHandler_EmptyName(t *testing.T) {
- RegisterTestingT(t)
-
- server := mock.NewServer()
- server.Context.SetServices(&app.Services{
- Tenants: &inmemory.TenantStorage{},
- })
- token, _ := jwt.Encode(&models.OAuthClaims{
- OAuthID: "123",
- OAuthName: "Jon Snow",
- OAuthEmail: "[email protected]",
- OAuthProvider: "facebook",
- })
- code, _ := server.ExecutePost(handlers.CreateTenant(), fmt.Sprintf(`{ "token": "%s" }`, token))
-
- Expect(code).To(Equal(400))
-}
-
-func TestCreateTenantHandler_EmptySubdomain(t *testing.T) {
- RegisterTestingT(t)
-
- server := mock.NewServer()
- server.Context.SetServices(&app.Services{
- Tenants: &inmemory.TenantStorage{},
- })
- token, _ := jwt.Encode(&models.OAuthClaims{
- OAuthID: "123",
- OAuthName: "Jon Snow",
- OAuthEmail: "[email protected]",
- OAuthProvider: "facebook",
- })
- code, _ := server.ExecutePost(handlers.CreateTenant(), fmt.Sprintf(`{ "token": "%s", "name": "My Company" }`, token))
-
- Expect(code).To(Equal(400))
-}
-
func TestCreateTenantHandler_ValidInput(t *testing.T) {
RegisterTestingT(t)
diff --git a/app/models/feedback.go b/app/models/feedback.go
index 67e80111c..3490cf373 100644
--- a/app/models/feedback.go
+++ b/app/models/feedback.go
@@ -1,6 +1,8 @@
package models
-import "time"
+import (
+ "time"
+)
//Idea represents an idea on a tenant board
type Idea struct {
diff --git a/app/models/im/idea.go b/app/models/im/idea.go
new file mode 100644
index 000000000..44d9bcc4f
--- /dev/null
+++ b/app/models/im/idea.go
@@ -0,0 +1,84 @@
+package im
+
+import (
+ "strings"
+
+ "github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/pkg/validate"
+)
+
+// Idea represents an unsaved idea
+type Idea struct {
+ Title string `json:"title"`
+ Description string `json:"description"`
+}
+
+// IsAuthorized returns true if current user is authorized to perform this action
+func (input *Idea) IsAuthorized(user *models.User) bool {
+ return true
+}
+
+// Validate is current model is valid
+func (input *Idea) Validate(services *app.Services) *validate.Result {
+ result := validate.Success()
+
+ input.Title = strings.Trim(input.Title, " ")
+
+ if input.Title == "" {
+ result.AddFieldFailure("title", "Title is required.")
+ }
+
+ if len(input.Title) < 10 || len(strings.Split(input.Title, " ")) < 3 {
+ result.AddFieldFailure("title", "Title needs to be more descriptive.")
+ }
+
+ return result
+}
+
+// NewComment represents a new comment
+type NewComment struct {
+ Content string `json:"content"`
+}
+
+// IsAuthorized returns true if current user is authorized to perform this action
+func (c *NewComment) IsAuthorized(user *models.User) bool {
+ return true
+}
+
+// Validate is current model is valid
+func (c *NewComment) Validate(services *app.Services) *validate.Result {
+ result := validate.Success()
+
+ if strings.Trim(c.Content, " ") == "" {
+ result.AddFieldFailure("content", "Comment is required.")
+ }
+
+ return result
+}
+
+// SetResponse represents the action to update an idea response
+type SetResponse struct {
+ Status int `json:"status"`
+ Text string `json:"text"`
+}
+
+// IsAuthorized returns true if current user is authorized to perform this action
+func (input *SetResponse) IsAuthorized(user *models.User) bool {
+ return true
+}
+
+// Validate is current model is valid
+func (input *SetResponse) Validate(services *app.Services) *validate.Result {
+ result := validate.Success()
+
+ if input.Status < models.IdeaNew || input.Status > models.IdeaDeclined {
+ result.AddFieldFailure("status", "Status is invalid.")
+ }
+
+ if strings.Trim(input.Text, " ") == "" {
+ result.AddFieldFailure("text", "Text is required.")
+ }
+
+ return result
+}
diff --git a/app/validate/idea_test.go b/app/models/im/idea_test.go
similarity index 58%
rename from app/validate/idea_test.go
rename to app/models/im/idea_test.go
index 95a1386d6..6d1a8742d 100644
--- a/app/validate/idea_test.go
+++ b/app/models/im/idea_test.go
@@ -1,9 +1,9 @@
-package validate_test
+package im_test
import (
"testing"
- "github.com/getfider/fider/app/validate"
+ "github.com/getfider/fider/app/models/im"
. "github.com/onsi/gomega"
)
@@ -21,10 +21,9 @@ func TestInvalidIdeaTitles(t *testing.T) {
"my+company",
"1234567890123456789012345678901234567890ABC",
} {
- ok, messages, err := validate.Idea(title, "")
- Expect(ok).To(BeFalse())
- Expect(len(messages) > 0).To(BeTrue())
- Expect(err).To(BeNil())
+ idea := im.Idea{Title: title}
+ result := idea.Validate(services)
+ ExpectFailed(result, "title")
}
}
@@ -35,9 +34,8 @@ func TestValidIdeaTitles(t *testing.T) {
"this is my new idea",
"this idea is very descriptive",
} {
- ok, messages, err := validate.Idea(title, "")
- Expect(ok).To(BeTrue())
- Expect(len(messages)).To(Equal(0))
- Expect(err).To(BeNil())
+ idea := im.Idea{Title: title}
+ result := idea.Validate(services)
+ ExpectSuccess(result)
}
}
diff --git a/app/models/im/im_test.go b/app/models/im/im_test.go
new file mode 100644
index 000000000..fabf22a80
--- /dev/null
+++ b/app/models/im/im_test.go
@@ -0,0 +1,38 @@
+package im_test
+
+import (
+ "github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/pkg/jwt"
+ "github.com/getfider/fider/app/pkg/validate"
+ "github.com/getfider/fider/app/storage/inmemory"
+ . "github.com/onsi/gomega"
+)
+
+var jonSnowToken, _ = jwt.Encode(&models.OAuthClaims{
+ OAuthID: "123",
+ OAuthName: "Jon Snow",
+ OAuthEmail: "[email protected]",
+ OAuthProvider: "facebook",
+})
+
+var services = &app.Services{
+ Tenants: &inmemory.TenantStorage{},
+}
+
+func ExpectFailed(result *validate.Result, field string) {
+ Expect(result.Ok).To(BeFalse())
+ Expect(result.Error).To(BeNil())
+ if field == "" {
+ Expect(len(result.Messages) > 0).To(BeTrue())
+ } else {
+ Expect(len(result.Failures[field]) > 0).To(BeTrue())
+ }
+}
+
+func ExpectSuccess(result *validate.Result) {
+ Expect(result.Ok).To(BeTrue())
+ Expect(len(result.Messages)).To(Equal(0))
+ Expect(len(result.Failures)).To(Equal(0))
+ Expect(result.Error).To(BeNil())
+}
diff --git a/app/models/im/tenant.go b/app/models/im/tenant.go
new file mode 100644
index 000000000..c50e02fd2
--- /dev/null
+++ b/app/models/im/tenant.go
@@ -0,0 +1,51 @@
+package im
+
+import (
+ "github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/pkg/env"
+ "github.com/getfider/fider/app/pkg/jwt"
+ "github.com/getfider/fider/app/pkg/validate"
+)
+
+//CreateTenant is the input model used to create a tenant
+type CreateTenant struct {
+ Token string `json:"token"`
+ Name string `json:"name"`
+ Subdomain string `json:"subdomain"`
+ UserClaims *models.OAuthClaims
+}
+
+// IsAuthorized returns true if current user is authorized to perform this action
+func (i *CreateTenant) IsAuthorized(user *models.User) bool {
+ return true
+}
+
+// Validate is current model is valid
+func (i *CreateTenant) Validate(services *app.Services) *validate.Result {
+ result := validate.Success()
+
+ var err error
+ if i.Token == "" {
+ result.AddFieldFailure("token", "Please identify yourself before proceeding.")
+ } else {
+ if i.UserClaims, err = jwt.DecodeOAuthClaims(i.Token); err != nil {
+ return validate.Error(err)
+ }
+ }
+
+ if env.IsSingleHostMode() {
+ i.Subdomain = "default"
+ }
+
+ if i.Name == "" {
+ result.AddFieldFailure("name", "Name is required.")
+ }
+
+ subdomainResult := validate.Subdomain(services.Tenants, i.Subdomain)
+ if !subdomainResult.Ok {
+ result.AddFieldFailure("subdomain", subdomainResult.Messages...)
+ }
+
+ return result
+}
diff --git a/app/models/im/tenant_test.go b/app/models/im/tenant_test.go
new file mode 100644
index 000000000..5dc895bd4
--- /dev/null
+++ b/app/models/im/tenant_test.go
@@ -0,0 +1,32 @@
+package im_test
+
+import (
+ "testing"
+
+ "github.com/getfider/fider/app/models/im"
+ . "github.com/onsi/gomega"
+)
+
+func TestCreateTenant_EmptyToken(t *testing.T) {
+ RegisterTestingT(t)
+
+ input := im.CreateTenant{Token: ""}
+ result := input.Validate(services)
+ ExpectFailed(result, "token")
+}
+
+func TestCreateTenant_EmptyName(t *testing.T) {
+ RegisterTestingT(t)
+
+ input := im.CreateTenant{Token: jonSnowToken, Name: ""}
+ result := input.Validate(services)
+ ExpectFailed(result, "name")
+}
+
+func TestCreateTenant_EmptySubdomain(t *testing.T) {
+ RegisterTestingT(t)
+
+ input := im.CreateTenant{Token: jonSnowToken, Name: "My Company"}
+ result := input.Validate(services)
+ ExpectFailed(result, "subdomain")
+}
diff --git a/app/pkg/validate/domain.go b/app/pkg/validate/domain.go
new file mode 100644
index 000000000..120ac2227
--- /dev/null
+++ b/app/pkg/validate/domain.go
@@ -0,0 +1,46 @@
+package validate
+
+import (
+ "fmt"
+ "regexp"
+
+ "strings"
+
+ "github.com/getfider/fider/app/storage"
+)
+
+var r, _ = regexp.Compile("^[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]$")
+
+//Subdomain validates given subdomain
+func Subdomain(tenants storage.Tenant, subdomain string) *Result {
+ subdomain = strings.ToLower(subdomain)
+
+ if len(subdomain) <= 2 {
+ return Failed([]string{"Subdomain must be more than 2 characters."})
+ }
+
+ if len(subdomain) > 40 {
+ return Failed([]string{"Subdomain must be less than 40 characters."})
+ }
+
+ if !r.MatchString(subdomain) {
+ return Failed([]string{"Subdomain contains invalid characters."})
+ }
+
+ switch subdomain {
+ case
+ "signup", "fider", "admin", "setup", "about", "wecanhearyou":
+ return Failed([]string{fmt.Sprintf("%s is not a valid subdomain name.", subdomain)})
+ }
+
+ available, err := tenants.IsSubdomainAvailable(subdomain)
+ if err != nil {
+ return Error(err)
+ }
+
+ if !available {
+ return Failed([]string{"This subdomain is not available anymore."})
+ }
+
+ return Success()
+}
diff --git a/app/validate/domain_test.go b/app/pkg/validate/domain_test.go
similarity index 59%
rename from app/validate/domain_test.go
rename to app/pkg/validate/domain_test.go
index e95143bcf..ea741322f 100644
--- a/app/validate/domain_test.go
+++ b/app/pkg/validate/domain_test.go
@@ -3,8 +3,8 @@ package validate_test
import (
"testing"
+ "github.com/getfider/fider/app/pkg/validate"
"github.com/getfider/fider/app/storage/inmemory"
- "github.com/getfider/fider/app/validate"
. "github.com/onsi/gomega"
)
@@ -22,10 +22,10 @@ func TestInvalidSubdomains(t *testing.T) {
"my+company",
"1234567890123456789012345678901234567890ABC",
} {
- ok, messages, err := validate.Subdomain(nil, subdomain)
- Expect(ok).To(BeFalse())
- Expect(len(messages) > 0).To(BeTrue())
- Expect(err).To(BeNil())
+ result := validate.Subdomain(nil, subdomain)
+ Expect(result.Ok).To(BeFalse())
+ Expect(len(result.Messages) > 0).To(BeTrue())
+ Expect(result.Error).To(BeNil())
}
}
@@ -43,19 +43,19 @@ func TestValidSubdomains_Availability(t *testing.T) {
"newyork",
"NewYork",
} {
- ok, messages, err := validate.Subdomain(tenants, subdomain)
- Expect(ok).To(BeFalse())
- Expect(len(messages)).To(Equal(1))
- Expect(err).To(BeNil())
+ result := validate.Subdomain(tenants, subdomain)
+ Expect(result.Ok).To(BeFalse())
+ Expect(len(result.Messages) > 0).To(BeTrue())
+ Expect(result.Error).To(BeNil())
}
for _, subdomain := range []string{
"my-company",
"123-company",
} {
- ok, messages, err := validate.Subdomain(tenants, subdomain)
- Expect(ok).To(BeTrue())
- Expect(len(messages)).To(Equal(0))
- Expect(err).To(BeNil())
+ result := validate.Subdomain(tenants, subdomain)
+ Expect(result.Ok).To(BeTrue())
+ Expect(len(result.Messages)).To(Equal(0))
+ Expect(result.Error).To(BeNil())
}
}
diff --git a/app/pkg/validate/validation.go b/app/pkg/validate/validation.go
new file mode 100644
index 000000000..e45608875
--- /dev/null
+++ b/app/pkg/validate/validation.go
@@ -0,0 +1,66 @@
+package validate
+
+import (
+ "github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models"
+)
+
+// Validatable defines which models can be validated against context
+type Validatable interface {
+ Validate(services *app.Services) *Result
+ IsAuthorized(user *models.User) bool
+}
+
+// Result is returned after each validation
+type Result struct {
+ Ok bool
+ Authorized bool
+ Error error
+ Messages []string
+ Failures map[string][]string
+}
+
+//AddFailure as a general message
+func (r *Result) AddFailure(message string) {
+ if r.Messages == nil {
+ r.Messages = []string{}
+ }
+ r.Messages = append(r.Messages, message)
+ r.Ok = false
+}
+
+//AddFieldFailure add failure message to specific field
+func (r *Result) AddFieldFailure(field string, messages ...string) {
+ if r.Failures == nil {
+ r.Failures = make(map[string][]string)
+ }
+
+ if r.Failures[field] == nil {
+ r.Failures[field] = []string{}
+ }
+
+ for _, message := range messages {
+ r.Failures[field] = append(r.Failures[field], message)
+ }
+ r.Ok = false
+}
+
+// Success returns a successful validation
+func Success() *Result {
+ return &Result{Ok: true, Authorized: true}
+}
+
+// Failed returns a failed validation result
+func Failed(messages []string) *Result {
+ return &Result{Ok: false, Authorized: true, Messages: messages}
+}
+
+// Error returns a failed validation result
+func Error(err error) *Result {
+ return &Result{Ok: false, Authorized: true, Error: err}
+}
+
+// Unauthorized returns an unauthorized validation result
+func Unauthorized() *Result {
+ return &Result{Ok: false, Authorized: false}
+}
diff --git a/app/pkg/web/context.go b/app/pkg/web/context.go
index c7f7f0b80..5783b0312 100644
--- a/app/pkg/web/context.go
+++ b/app/pkg/web/context.go
@@ -11,6 +11,7 @@ import (
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/dbx"
"github.com/getfider/fider/app/pkg/env"
+ "github.com/getfider/fider/app/pkg/validate"
"github.com/labstack/echo"
)
@@ -46,6 +47,18 @@ func (ctx *Context) SetTenant(tenant *models.Tenant) {
ctx.Set(tenantContextKey, tenant)
}
+//BindTo context values into given model
+func (ctx *Context) BindTo(i validate.Validatable) *validate.Result {
+ err := ctx.Bind(i)
+ if err != nil {
+ return validate.Error(err)
+ }
+ if !i.IsAuthorized(ctx.User()) {
+ return validate.Unauthorized()
+ }
+ return i.Validate(ctx.Services())
+}
+
//IsAuthenticated returns true if user is authenticated
func (ctx *Context) IsAuthenticated() bool {
return ctx.Get(userContextKey) != nil
@@ -66,6 +79,23 @@ func (ctx *Context) Failure(err error) error {
return echo.NewHTTPError(http.StatusInternalServerError, err)
}
+//HandleValidation handles given validation result property to return 400 or 500
+func (ctx *Context) HandleValidation(result *validate.Result) error {
+ if result.Error != nil {
+ return ctx.Failure(result.Error)
+ }
+
+ if !result.Authorized {
+ return ctx.Unauthorized()
+ }
+
+ fmt.Print(result)
+ return ctx.BadRequest(Map{
+ "message": result.Messages,
+ "failures": result.Failures,
+ })
+}
+
//Unauthorized returns a 401 response
func (ctx *Context) Unauthorized() error {
return ctx.JSON(http.StatusUnauthorized, Map{})
diff --git a/app/validate/domain.go b/app/validate/domain.go
deleted file mode 100644
index 2418163bd..000000000
--- a/app/validate/domain.go
+++ /dev/null
@@ -1,46 +0,0 @@
-package validate
-
-import (
- "fmt"
- "regexp"
-
- "strings"
-
- "github.com/getfider/fider/app/storage"
-)
-
-var r, _ = regexp.Compile("^[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]$")
-
-//Subdomain validates given subdomain
-func Subdomain(tenants storage.Tenant, subdomain string) (bool, []string, error) {
- subdomain = strings.ToLower(subdomain)
-
- if len(subdomain) <= 2 {
- return false, []string{"Subdomain must be more than 2 characters"}, nil
- }
-
- if len(subdomain) > 40 {
- return false, []string{"Subdomain must be less than 40 characters"}, nil
- }
-
- if !r.MatchString(subdomain) {
- return false, []string{"Subdomain contains invalid characters"}, nil
- }
-
- switch subdomain {
- case
- "signup", "fider", "admin", "setup", "about", "wecanhearyou":
- return false, []string{fmt.Sprintf("%s is not a valid subdomain name", subdomain)}, nil
- }
-
- available, err := tenants.IsSubdomainAvailable(subdomain)
- if err != nil {
- return false, make([]string, 0), err
- }
-
- if !available {
- return false, []string{"This subdomain is not available anymore"}, nil
- }
-
- return true, make([]string, 0), nil
-}
diff --git a/app/validate/idea.go b/app/validate/idea.go
deleted file mode 100644
index e5309f17f..000000000
--- a/app/validate/idea.go
+++ /dev/null
@@ -1,19 +0,0 @@
-package validate
-
-import (
- "strings"
-)
-
-//Idea validates given idea
-func Idea(title string, description string) (bool, []string, error) {
-
- if strings.Trim(title, " ") == "" {
- return false, []string{"Title is required."}, nil
- }
-
- if len(title) < 10 || len(strings.Split(title, " ")) < 3 {
- return false, []string{"Title needs to be more descriptive."}, nil
- }
-
- return true, make([]string, 0), nil
-}
diff --git a/public/components/CommentInput.tsx b/public/components/CommentInput.tsx
index 4c8db000e..4757242b1 100644
--- a/public/components/CommentInput.tsx
+++ b/public/components/CommentInput.tsx
@@ -52,7 +52,7 @@ export class CommentInput extends React.Component<CommentInputProps, CommentInpu
? <Button className="primary" onClick={ () => this.submit() }>
Add Comment
</Button>
- : <div className="ui message">
+ : <div className="ui message signin-message">
<div className="header">
Hey! We need to know who you are
</div>
@@ -60,13 +60,13 @@ export class CommentInput extends React.Component<CommentInputProps, CommentInpu
<SocialSignInList orientation="horizontal" size="small" />
</div>;
- return <form className="ui reply form">
+ return <div className="ui reply form">
<DisplayError error={this.state.error} />
<div className="field">
<textarea onKeyUp={(e) => { this.setState({ content: e.currentTarget.value }); }}
placeholder="Leave your comment here..."></textarea>
</div>
{ (this.state.content || user) && button }
- </form>;
+ </div>;
}
}
diff --git a/public/components/ResponseForm.tsx b/public/components/ResponseForm.tsx
index 3b07782cb..2d18ecfd1 100644
--- a/public/components/ResponseForm.tsx
+++ b/public/components/ResponseForm.tsx
@@ -57,8 +57,8 @@ export class ResponseForm extends React.Component<ResponseFormProps, ResponseFor
public render() {
const button = <Button className="primary" onClick={async () => this.activate()}>Respond</Button>;
- const form = <form className="ui reply form">
- <DisplayError error={this.state.error} />
+ const form = <div className="ui reply form">
+ <DisplayError fields={['status']} error={this.state.error} />
<div className="two fields">
<div className="field">
<label>Status</label>
@@ -71,6 +71,7 @@ export class ResponseForm extends React.Component<ResponseFormProps, ResponseFor
</select>
</div>
</div>
+ <DisplayError fields={['text']} error={this.state.error} />
<div className="field">
<textarea
ref={(input) => this.text = input!}
@@ -84,7 +85,7 @@ export class ResponseForm extends React.Component<ResponseFormProps, ResponseFor
<Button className="basic" onClick={async () => this.deactivate()}>
Cancel
</Button>
- </form>;
+ </div>;
return this.state.active ? form : button;
}
diff --git a/public/components/SupportCounter.tsx b/public/components/SupportCounter.tsx
index 76f6ac29a..3607e2f92 100644
--- a/public/components/SupportCounter.tsx
+++ b/public/components/SupportCounter.tsx
@@ -97,7 +97,7 @@ export class SupportCounter extends React.Component<SupportCounterProps, Support
{ status.closed ? disabled : this.state.supported ? undo : support }
</div>
</div>
- <div ref={(e) => { this.list = e!; } } className="ui popup transition hidden">
+ <div ref={(e) => { this.list = e!; } } className="ui popup transition hidden signin-message">
<p className="header">Hey! We need to know who you are</p>
<SocialSignInList orientation="horizontal" size="small" />
</div>
diff --git a/public/components/common/DisplayError.tsx b/public/components/common/DisplayError.tsx
index d05d4b6ac..de6ad4e6e 100644
--- a/public/components/common/DisplayError.tsx
+++ b/public/components/common/DisplayError.tsx
@@ -1,12 +1,34 @@
import * as React from 'react';
import { Session, Failure } from '@fider/services';
-export const DisplayError = (props: {error?: Failure}) => {
+const arrayToTag = (items: string[]) => {
+ return items.map((m) => <li>{m}</li>);
+};
+
+interface DisplayErrorProps {
+ error?: Failure;
+ fields?: string[];
+}
+
+export const DisplayError = (props: DisplayErrorProps) => {
if (!props.error) {
return <div></div>;
}
- return <div className="ui small negative message">
- <p>{ props.error.message }</p>
- </div>;
+ let items: JSX.Element[] = [];
+
+ if (props.error.messages && !props.fields) {
+ items = arrayToTag(props.error.messages);
+ } else if (props.error.failures) {
+ for (const field of props.fields || Object.keys(props.error.failures)) {
+ if (props.error.failures.hasOwnProperty(field)) {
+ const tags = arrayToTag(props.error.failures[field]);
+ tags.forEach((t) => items.push(t));
+ }
+ }
+ }
+
+ return items.length > 0 ? <div className="display-error ui pointing below red basic label">
+ <ul>{ items }</ul>
+ </div> : null;
};
diff --git a/public/main.scss b/public/main.scss
index 7f6c3a7f7..d275f053a 100644
--- a/public/main.scss
+++ b/public/main.scss
@@ -24,10 +24,6 @@ body {
}
}
-.ui.violet.button {
- background-color: $violet;
-}
-
code {
padding: 2px 4px;
font-size: 90%;
@@ -108,3 +104,40 @@ code {
}
}
+.ui[class*="bottom pointing"].label:before, .ui[class*="pointing below"].label:before {
+ left: 20px;
+}
+
+.display-error {
+ ul {
+ padding: 0;
+ margin: 0;
+ list-style-type: none;
+ text-align: left;
+ li {
+ padding: 5px;
+ }
+ }
+}
+
+.ui.basic.red.label {
+ background-color: #fff4f4 !important;
+ color: #d84e4e !important;
+ border-color: #ef7878 !important;
+}
+
+.ui.message.signin-message {
+ background-color: #fff;
+}
+
+.ui.popup.signin-message {
+ min-width: 290px;
+}
+
+.ui.violet.button {
+ background-color: $violet;
+}
+
+.ui.inverted.violet.button, .ui.inverted.violet.buttons .button {
+ background-color: #fff;
+}
\ No newline at end of file
diff --git a/public/pages/home/IdeaInput.tsx b/public/pages/home/IdeaInput.tsx
index 46795a844..75a008a2a 100644
--- a/public/pages/home/IdeaInput.tsx
+++ b/public/pages/home/IdeaInput.tsx
@@ -58,6 +58,7 @@ export class IdeaInput extends React.Component<{}, IdeaInputState> {
public render() {
const user = this.session.getCurrentUser();
+ const buttonCss = this.state.title === '' ? 'primary disabled' : 'primary';
const details = user ?
<div>
<div className="field">
@@ -65,12 +66,12 @@ export class IdeaInput extends React.Component<{}, IdeaInputState> {
rows={6}
placeholder="Describe your idea (optional)"></textarea>
</div>
- <Button className="primary" onClick={() => this.form.submit() }>
+ <Button className={buttonCss} onClick={() => this.form.submit() }>
Submit Idea
</Button>
</div> :
<div>
- <div className="ui message">
+ <div className="ui message signin-message">
<div className="header">
Hey! We need to know who you are
</div>
diff --git a/public/pages/home/SiteHomePage.tsx b/public/pages/home/SiteHomePage.tsx
index 063688b00..61f764ba5 100644
--- a/public/pages/home/SiteHomePage.tsx
+++ b/public/pages/home/SiteHomePage.tsx
@@ -42,11 +42,11 @@ export class SiteHomePage extends React.Component<{}, SiteHomePageState> {
{ x.title }
</a>
<MultiLineText className="description" text={ x.description } markdown={true} />
- <ShowIdeaResponse status={ x.status } response={ x.response } />
<div className="extra">
shared <Moment date={x.createdOn} />
<div style={{float: 'right'}}>{ x.totalComments } <i className="comments icon"/></div>
</div>
+ <ShowIdeaResponse status={ x.status } response={ x.response } />
</div>
</div>);
diff --git a/public/pages/signup/SignUpPage.tsx b/public/pages/signup/SignUpPage.tsx
index ac22ef570..8152be75f 100644
--- a/public/pages/signup/SignUpPage.tsx
+++ b/public/pages/signup/SignUpPage.tsx
@@ -1,6 +1,6 @@
import * as React from 'react';
-import { SocialSignInList, Footer, Button, Form, EnvironmentInfo, Gravatar, DisplayError } from '@fider/components/common';
+import { SocialSignInList, Footer, Button, EnvironmentInfo, Gravatar, DisplayError } from '@fider/components/common';
import { AppSettings } from '@fider/models';
import { setTitle, getQueryString } from '@fider/utils/page';
import { decode } from '@fider/utils/jwt';
@@ -31,7 +31,6 @@ interface SignUpPageState {
export class SignUpPage extends React.Component<{}, SignUpPageState> {
private settings: AppSettings;
private user: OAuthUser;
- private form: Form;
@inject(injectables.Session)
public session: Session;
@@ -62,8 +61,6 @@ export class SignUpPage extends React.Component<{}, SignUpPageState> {
}
private async confirm() {
- this.form.clearFailure();
-
const result = await this.service.create(
this.user && this.user.token,
this.state.name,
@@ -76,7 +73,7 @@ export class SignUpPage extends React.Component<{}, SignUpPageState> {
location.href = `${location.protocol}//${this.state.subdomain.value}${this.settings.domain}`;
}
} else if (result.error) {
- this.form.setFailure(result.error);
+ this.setState({ error: result.error });
}
}
@@ -99,6 +96,7 @@ export class SignUpPage extends React.Component<{}, SignUpPageState> {
<img className="logo" src={logo} />
<h3 className="ui header">1. Who are you?</h3>
+ <DisplayError fields={['token']} error={this.state.error} />
{
this.user ?
@@ -117,7 +115,8 @@ export class SignUpPage extends React.Component<{}, SignUpPageState> {
<div className="ui section divider"></div>
<h3 className="ui header">2. Company/Product details</h3>
- <Form ref={(f) => { this.form = f!; } } onSubmit={() => this.confirm()}>
+ <DisplayError fields={['name', 'subdomain']} error={this.state.error} />
+ <div className="ui form">
<div className="inline field">
<input id="name" type="text"
placeholder="Name"
@@ -145,14 +144,14 @@ export class SignUpPage extends React.Component<{}, SignUpPageState> {
}
</div>
</div> }
- </Form>
+ </div>
<div className="ui section divider"></div>
<h3 className="ui header">3. Review and continue</h3>
<p>Make sure information provided above is correct before proceeding.</p>
- <Button className="positive" size="large" onClick={() => this.form.submit()}>Confirm</Button>
+ <Button className="positive" size="large" onClick={() => this.confirm()}>Confirm</Button>
</div>
<Footer />
</div>;
diff --git a/public/services/http.ts b/public/services/http.ts
index 606a0b97f..e19795ac3 100644
--- a/public/services/http.ts
+++ b/public/services/http.ts
@@ -5,7 +5,10 @@ axios.defaults.validateStatus = (status: number) => {
};
export interface Failure {
- message: string;
+ messages: string[];
+ failures: {
+ [key: string]: string[]
+ };
}
export interface Result<T = void> {
@@ -24,7 +27,10 @@ function toResult<T>(response: AxiosResponse): Result<T> {
return {
ok: false,
data: response.data as T,
- error: { message: response.data.message }
+ error: {
+ messages: response.data.messages,
+ failures: response.data.failures,
+ }
};
}
}
diff --git a/router.go b/router.go
index 660a4d72b..dd465cd79 100644
--- a/router.go
+++ b/router.go
@@ -79,7 +79,6 @@ func GetMainEngine(settings *models.AppSettings) *web.Engine {
private.Use(middlewares.IsAuthenticated())
private.Post("/api/ideas", handlers.PostIdea())
- private.Post("/api/ideas/:number", handlers.UpdateIdea())
private.Post("/api/ideas/:number/comments", handlers.PostComment())
private.Post("/api/ideas/:number/status", handlers.SetResponse())
private.Post("/api/ideas/:number/support", handlers.AddSupporter())