Open platform to collect and prioritize feedback
Sign in by e-mail (#124)
Guilherme Oenning6f2c27b96668
diff --git a/.ci.env b/.ci.envindex 1ef9eb27b..ad0e4d588 100644--- a/.ci.env+++ b/.ci.env@@ -2,4 +2,10 @@ GO_ENV=testHOST_MODE=multiDATABASE_URL=postgres://fider_test:fider_test-pw@postgres:5432/fider_test?sslmode=disableAUTH_ENDPOINT=http://login.test.fider.io:3000-JWT_SECRET=SOME_RANDOM_TOKEN_JUST_FOR_TESTING\ No newline at end of file+JWT_SECRET=SOME_RANDOM_TOKEN_JUST_FOR_TESTING++SMTP_HOST=smtp.random.org+SMTP_PORT=465+SMTP_PASSWORD=random\ No newline at end of filediff --git a/.example.env b/.example.envindex 20a92c2cd..a57c1d166 100644--- a/.example.env+++ b/.example.env@@ -1,6 +1,7 @@GO_ENV=developmentDATABASE_URL=postgres://fider:fider-pw@localhost:5555/fider?sslmode=disableJWT_SECRET=hsjl]W;&ZcHxT&FK;s%bgIQF:#ch=~#Al4:5]N;7V<qPZ3e9lT4'%;go;LIkc%k+NOREPLY_EMAIL=OAUTH_FACEBOOK_APPID=OAUTH_FACEBOOK_SECRET=@@ -9,4 +10,12 @@ OAUTH_GOOGLE_CLIENTID=OAUTH_GOOGLE_SECRET=OAUTH_GITHUB_CLIENTID=-OAUTH_GITHUB_SECRET=\ No newline at end of file+OAUTH_GITHUB_SECRET=++MAILGUN_API=+MAILGUN_DOMAIN=++SMTP_HOST=+SMTP_PORT=+SMTP_USERNAME=+SMTP_PASSWORD=\ No newline at end of filediff --git a/.test.env b/.test.envindex 580d41b03..dcee35c62 100644--- a/.test.env+++ b/.test.env@@ -2,4 +2,10 @@ GO_ENV=testHOST_MODE=multiDATABASE_URL=postgres://fider_test:fider_test-pw@localhost:5566/fider_test?sslmode=disableAUTH_ENDPOINT=http://login.test.fider.io:3000-JWT_SECRET=SOME_RANDOM_TOKEN_JUST_FOR_TESTING\ No newline at end of file+JWT_SECRET=SOME_RANDOM_TOKEN_JUST_FOR_TESTING++SMTP_HOST=smtp.random.org+SMTP_PORT=465+SMTP_PASSWORD=random\ No newline at end of filediff --git a/app/actions/actions.go b/app/actions/actions.goindex 25b25be62..7b203f98b 100644--- a/app/actions/actions.go+++ b/app/actions/actions.go@@ -8,7 +8,7 @@ import (// Actionable is any action that the user can perform using the web apptype Actionable interface {- NewModel() interface{}+ Initialize() interface{}Validate(services *app.Services) *validate.ResultIsAuthorized(user *models.User) bool}diff --git a/app/actions/idea.go b/app/actions/idea.goindex 62c23b3dd..31d233250 100644--- a/app/actions/idea.go+++ b/app/actions/idea.go@@ -13,8 +13,8 @@ type CreateNewIdea struct {Model *models.NewIdea}-// NewModel initializes the model-func (input *CreateNewIdea) NewModel() interface{} {+// Initialize the model+func (input *CreateNewIdea) Initialize() interface{} {input.Model = new(models.NewIdea)return input.Model}@@ -46,8 +46,8 @@ type AddNewComment struct {Model *models.NewComment}-// NewModel initializes the model-func (input *AddNewComment) NewModel() interface{} {+// Initialize the model+func (input *AddNewComment) Initialize() interface{} {input.Model = new(models.NewComment)return input.Model}@@ -73,8 +73,8 @@ type SetResponse struct {Model *models.SetResponse}-// NewModel initializes the model-func (input *SetResponse) NewModel() interface{} {+// Initialize the model+func (input *SetResponse) Initialize() interface{} {input.Model = new(models.SetResponse)return input.Model}diff --git a/app/actions/signin.go b/app/actions/signin.gonew file mode 100644index 000000000..164e41a77--- /dev/null+++ b/app/actions/signin.go@@ -0,0 +1,89 @@+package actions++import (+ "strings"++ "github.com/getfider/fider/app"+ "github.com/getfider/fider/app/models"+ "github.com/getfider/fider/app/pkg/uuid"+ "github.com/getfider/fider/app/pkg/validate"+)++// SignInByEmail happens when user request to sign in by email+type SignInByEmail struct {+ Model *models.SignInByEmail+}++// Initialize the model+func (input *SignInByEmail) Initialize() interface{} {+ input.Model = new(models.SignInByEmail)+ input.Model.VerificationKey = strings.Replace(uuid.NewV4().String(), "-", "", 4)+ return input.Model+}++// IsAuthorized returns true if current user is authorized to perform this action+func (input *SignInByEmail) IsAuthorized(user *models.User) bool {+ return true+}++// Validate is current model is valid+func (input *SignInByEmail) Validate(services *app.Services) *validate.Result {+ result := validate.Success()+ input.Model.Email = strings.Trim(strings.ToLower(input.Model.Email), " ")++ if input.Model.Email == "" {+ result.AddFieldFailure("email", "E-mail is required.")+ return result+ }++ emailResult := validate.Email(input.Model.Email)+ if !emailResult.Ok {+ result.AddFieldFailure("email", emailResult.Messages...)+ }++ return result+}++// CompleteProfile happens when user completes his profile during first time sign in+type CompleteProfile struct {+ Model *models.CompleteProfile+}++// Initialize the model+func (input *CompleteProfile) Initialize() interface{} {+ input.Model = new(models.CompleteProfile)+ return input.Model+}++// IsAuthorized returns true if current user is authorized to perform this action+func (input *CompleteProfile) IsAuthorized(user *models.User) bool {+ return true+}++// Validate is current model is valid+func (input *CompleteProfile) Validate(services *app.Services) *validate.Result {+ result := validate.Success()+ input.Model.Key = strings.Trim(input.Model.Key, " ")+ input.Model.Name = strings.Trim(input.Model.Name, " ")++ if input.Model.Name == "" {+ result.AddFieldFailure("name", "Name is required.")+ }++ if input.Model.Key == "" {+ result.AddFieldFailure("key", "Key is required.")+ } else {+ request, err := services.Tenants.FindVerificationByKey(input.Model.Key)+ if err != nil {+ if err == app.ErrNotFound {+ result.AddFieldFailure("key", "Key is invalid.")+ } else {+ return validate.Error(err)+ }+ } else {+ input.Model.Email = request.Email+ }+ }++ return result+}diff --git a/app/actions/signin_test.go b/app/actions/signin_test.gonew file mode 100644index 000000000..2fdc099af--- /dev/null+++ b/app/actions/signin_test.go@@ -0,0 +1,63 @@+package actions_test++import (+ "testing"++ "github.com/getfider/fider/app/actions"+ "github.com/getfider/fider/app/models"++ . "github.com/onsi/gomega"+)++func TestSignInByEmail_EmptyEmail(t *testing.T) {+ RegisterTestingT(t)++ action := actions.SignInByEmail{Model: &models.SignInByEmail{Email: " "}}+ result := action.Validate(services)+ ExpectFailed(result, "email")+}++func TestSignInByEmail_InvalidEmail(t *testing.T) {+ RegisterTestingT(t)++ action := actions.SignInByEmail{Model: &models.SignInByEmail{Email: "Hi :)"}}+ result := action.Validate(services)+ ExpectFailed(result, "email")+}++func TestSignInByEmail_ShouldHaveVerificationKey(t *testing.T) {+ RegisterTestingT(t)++ action := actions.SignInByEmail{}+ action.Initialize()+ action.Model.Email = "[email protected]"++ result := action.Validate(services)+ ExpectSuccess(result)+ Expect(action.Model.VerificationKey).NotTo(Equal(""))+}++func TestCompleteProfile_EmptyNameAndKey(t *testing.T) {+ RegisterTestingT(t)++ action := actions.CompleteProfile{Model: &models.CompleteProfile{}}+ result := action.Validate(services)+ ExpectFailed(result, "name")+ ExpectFailed(result, "key")+}++func TestCompleteProfile_UnknownKey(t *testing.T) {+ RegisterTestingT(t)+ action := actions.CompleteProfile{Model: &models.CompleteProfile{Name: "Jon Snow", Key: "1234567890"}}+ result := action.Validate(services)+ ExpectFailed(result, "key")+}++func TestCompleteProfile_ValidKey(t *testing.T) {+ RegisterTestingT(t)+ services.Tenants.SaveVerificationKey("[email protected]", "1234567890")+ action := actions.CompleteProfile{Model: &models.CompleteProfile{Name: "Jon Snow", Key: "1234567890"}}+ result := action.Validate(services)+ ExpectSuccess(result)+ Expect(action.Model.Email).To(Equal("[email protected]"))+}diff --git a/app/actions/tenant.go b/app/actions/tenant.goindex 01d610155..201108247 100644--- a/app/actions/tenant.go+++ b/app/actions/tenant.go@@ -15,8 +15,8 @@ type CreateTenant struct {Model *models.CreateTenant}-// NewModel initializes the model-func (input *CreateTenant) NewModel() interface{} {+// Initialize the model+func (input *CreateTenant) Initialize() interface{} {input.Model = new(models.CreateTenant)return input.Model}@@ -62,8 +62,8 @@ type UpdateTenantSettings struct {Model *models.UpdateTenantSettings}-// NewModel initializes the model-func (input *UpdateTenantSettings) NewModel() interface{} {+// Initialize the model+func (input *UpdateTenantSettings) Initialize() interface{} {input.Model = new(models.UpdateTenantSettings)return input.Model}diff --git a/app/handlers/admin.go b/app/handlers/admin.goindex 7a4d19aaa..fc7be2297 100644--- a/app/handlers/admin.go+++ b/app/handlers/admin.go@@ -12,7 +12,7 @@ func UpdateSettings() web.HandlerFunc {if result := c.BindTo(input); !result.Ok {return c.HandleValidation(result)}- err := c.Services().Tenants.UpdateSettings(c.Tenant().ID, input.Model)+ err := c.Services().Tenants.UpdateSettings(input.Model)if err != nil {return c.Failure(err)}diff --git a/app/handlers/oauth_test.go b/app/handlers/oauth_test.godeleted file mode 100644index c3807f97f..000000000--- a/app/handlers/oauth_test.go+++ /dev/null@@ -1,122 +0,0 @@-package handlers_test--import (- "testing"-- "net/http"-- "github.com/getfider/fider/app/handlers"- "github.com/getfider/fider/app/models"- "github.com/getfider/fider/app/pkg/mock"- "github.com/getfider/fider/app/pkg/oauth"- . "github.com/onsi/gomega"-)--func TestLoginHandler(t *testing.T) {- RegisterTestingT(t)-- server, _ := mock.NewServer()- code, response := server.Execute(handlers.Login(oauth.FacebookProvider))-- Expect(code).To(Equal(http.StatusTemporaryRedirect))- Expect(response.Header().Get("Location")).To(Equal("http://orange.test.canherayou.com/oauth/token?provider=facebook&redirect="))-}--func TestCallbackHandler_InvalidState(t *testing.T) {- RegisterTestingT(t)-- server, _ := mock.NewServer()-- Expect(func() {- server.- WithURL("http://login.test.canherayou.com/oauth/callback?state=abc").- Execute(handlers.OAuthCallback(oauth.FacebookProvider))- }).To(Panic())-}--func TestCallbackHandler_InvalidCode(t *testing.T) {- RegisterTestingT(t)-- server, _ := mock.NewServer()- code, response := server.- WithURL("http://login.test.canherayou.com/oauth/callback?state=http://orange.test.fider.io").- Execute(handlers.OAuthCallback(oauth.FacebookProvider))-- Expect(code).To(Equal(http.StatusTemporaryRedirect))- Expect(response.Header().Get("Location")).To(Equal("http://orange.test.fider.io"))-}--func TestCallbackHandler_ExistingUserAndProvider(t *testing.T) {- RegisterTestingT(t)-- server, _ := mock.NewServer()- code, response := server.- WithURL("http://demo.test.canherayou.com/oauth/callback?state=http://demo.test.fider.io&code=123").- Execute(handlers.OAuthCallback(oauth.FacebookProvider))-- Expect(code).To(Equal(http.StatusTemporaryRedirect))- Expect(response.Header().Get("Location")).To(Equal("http://demo.test.fider.io?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyL2lkIjoxLCJ1c2VyL25hbWUiOiJKb24gU25vdyIsInVzZXIvZW1haWwiOiJqb24uc25vd0Bnb3QuY29tIn0.S7P8zTU0rVovmchNbwamBewYbO96GdJcOygn7tbsikw"))-}--func TestCallbackHandler_NewUser(t *testing.T) {- RegisterTestingT(t)-- server, services := mock.NewServer()- code, response := server.- WithURL("http://login.test.canherayou.com/oauth/callback?state=http://orange.test.fider.io&code=456").- Execute(handlers.OAuthCallback(oauth.FacebookProvider))-- user, err := services.Users.GetByEmail(mock.OrangeTenant.ID, "[email protected]")- Expect(err).To(BeNil())- Expect(user.Name).To(Equal("Some Facebook Guy"))-- Expect(code).To(Equal(http.StatusTemporaryRedirect))- Expect(response.Header().Get("Location")).To(Equal("http://orange.test.fider.io?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyL2lkIjozLCJ1c2VyL25hbWUiOiJTb21lIEZhY2Vib29rIEd1eSIsInVzZXIvZW1haWwiOiJzb21lLmd1eUBmYWNlYm9vay5jb20ifQ.ydyGDIZZHbJ-mgvpAsXTZnbs1rBH6cTVjHctZEACUOo"))-}--func TestCallbackHandler_NewUserWithoutEmail(t *testing.T) {- RegisterTestingT(t)-- server, services := mock.NewServer()- services.Users.Register(&models.User{- Name: "Some Guy",- Email: "",- Tenant: mock.DemoTenant,- Providers: []*models.UserProvider{- &models.UserProvider{UID: "GO999", Name: oauth.GoogleProvider},- },- })-- code, response := server.- WithURL("http://login.test.canherayou.com/oauth/callback?state=http://demo.test.fider.io&code=798").- Execute(handlers.OAuthCallback(oauth.FacebookProvider))-- user, err := services.Users.GetByID(3)- Expect(err).To(BeNil())- Expect(user.Name).To(Equal("Some Guy"))- Expect(len(user.Providers)).To(Equal(1))-- user, err = services.Users.GetByID(4)- Expect(err).To(BeNil())- Expect(user.Name).To(Equal("Mark"))- Expect(len(user.Providers)).To(Equal(1))-- Expect(code).To(Equal(http.StatusTemporaryRedirect))- Expect(response.Header().Get("Location")).To(Equal("http://demo.test.fider.io?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyL2lkIjo0LCJ1c2VyL25hbWUiOiJNYXJrIiwidXNlci9lbWFpbCI6IiJ9.G93ZTFcDuHiIlYbDvMnjhoDebeJZMifWbv9v0rayQOI"))-}--func TestCallbackHandler_ExistingUser_NewProvider(t *testing.T) {- RegisterTestingT(t)-- server, services := mock.NewServer()- code, response := server.- WithURL("http://login.test.canherayou.com/oauth/callback?state=http://demo.test.fider.io&code=123").- Execute(handlers.OAuthCallback(oauth.GoogleProvider))-- user, err := services.Users.GetByEmail(mock.DemoTenant.ID, "[email protected]")- Expect(err).To(BeNil())- Expect(len(user.Providers)).To(Equal(2))-- Expect(code).To(Equal(http.StatusTemporaryRedirect))- Expect(response.Header().Get("Location")).To(Equal("http://demo.test.fider.io?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyL2lkIjoxLCJ1c2VyL25hbWUiOiJKb24gU25vdyIsInVzZXIvZW1haWwiOiJqb24uc25vd0Bnb3QuY29tIn0.S7P8zTU0rVovmchNbwamBewYbO96GdJcOygn7tbsikw"))-}diff --git a/app/handlers/oauth.go b/app/handlers/signin.gosimilarity index 50%rename from app/handlers/oauth.gorename to app/handlers/signin.goindex f50a4b356..e4493a60c 100644--- a/app/handlers/oauth.go+++ b/app/handlers/signin.go@@ -1,13 +1,16 @@package handlersimport (+ "fmt""net/http""net/url""strings"+ "time"jwtgo "github.com/dgrijalva/jwt-go""github.com/getfider/fider/app"+ "github.com/getfider/fider/app/actions""github.com/getfider/fider/app/models""github.com/getfider/fider/app/pkg/env""github.com/getfider/fider/app/pkg/jwt"@@ -112,7 +115,6 @@ func OAuthCallback(provider string) web.HandlerFunc {var token stringif token, err = jwt.Encode(claims); err != nil {- c.Logger().Errorf("Encoding claims failed with %s", err)return c.Failure(err)}@@ -123,18 +125,126 @@ func OAuthCallback(provider string) web.HandlerFunc {}}-// Login handles OAuth logins-func Login(provider string) web.HandlerFunc {+// SignIn handles OAuth sign in+func SignIn(provider string) web.HandlerFunc {return func(c web.Context) error {authURL := c.Services().OAuth.GetAuthURL(c.AuthEndpoint(), provider, c.QueryParam("redirect"))return c.Redirect(http.StatusTemporaryRedirect, authURL)}}-// Logout remove auth cookies-func Logout() web.HandlerFunc {+// SignInByEmail sends a new e-mail with verification key+func SignInByEmail() web.HandlerFunc {return func(c web.Context) error {- c.RemoveCookie("auth")+ input := new(actions.SignInByEmail)+ if result := c.BindTo(input); !result.Ok {+ return c.HandleValidation(result)+ }++ err := c.Services().Tenants.SaveVerificationKey(input.Model.Email, input.Model.VerificationKey)+ if err != nil {+ return c.Failure(err)+ }++ subject := fmt.Sprintf("Sign in to %s", c.Tenant().Name)+ link := fmt.Sprintf("%s/signin/verify?k=%s", c.BaseURL(), input.Model.VerificationKey)+ message := fmt.Sprintf("Click and confirm that you want to sign in. This link will expire in 15 minutes and can only be used once. <br /><br /> <a href='%s'>%s</a>", link, link)+ err = c.Services().Emailer.Send(c.Tenant().Name, input.Model.Email, subject, message)+ if err != nil {+ return c.Failure(err)+ }++ return c.Ok(web.Map{})+ }+}++// VerifySignInKey checks if verify key is correct and sign in user+func VerifySignInKey() web.HandlerFunc {+ return func(c web.Context) error {+ key := c.QueryParam("k")++ result, err := c.Services().Tenants.FindVerificationByKey(key)+ if err != nil {+ if err == app.ErrNotFound {+ return c.Redirect(http.StatusTemporaryRedirect, c.BaseURL())+ }+ return c.Failure(err)+ }++ //If key has been used, just go back to home page+ if result.VerifiedOn != nil {+ return c.Redirect(http.StatusTemporaryRedirect, c.BaseURL())+ }++ //If key expired (15 minutes), go back to home page+ if time.Now().After(result.CreatedOn.Add(15 * time.Minute)) {+ err = c.Services().Tenants.SetKeyAsVerified(key)+ if err != nil {+ return c.Failure(err)+ }+ return c.Redirect(http.StatusTemporaryRedirect, c.BaseURL())+ }++ user, err := c.Services().Users.GetByEmail(c.Tenant().ID, result.Email)+ if err != nil {+ if err == app.ErrNotFound {+ // This will render a page for /signin/verify URL using same variables as home page+ return Index()(c)+ }+ return c.Failure(err)+ }++ err = c.Services().Tenants.SetKeyAsVerified(key)+ if err != nil {+ return c.Failure(err)+ }++ err = c.AddAuthCookie(user)+ if err != nil {+ return c.Failure(err)+ }++ return c.Redirect(http.StatusTemporaryRedirect, c.BaseURL())+ }+}++// CompleteSignInProfile handles the action to update user profile+func CompleteSignInProfile() web.HandlerFunc {+ return func(c web.Context) error {+ input := new(actions.CompleteProfile)+ if result := c.BindTo(input); !result.Ok {+ return c.HandleValidation(result)+ }++ user := &models.User{+ Name: input.Model.Name,+ Email: input.Model.Email,+ Tenant: c.Tenant(),+ Role: models.RoleVisitor,+ }+ err := c.Services().Users.Register(user)+ if err != nil {+ return c.Failure(err)+ }++ err = c.Services().Tenants.SetKeyAsVerified(input.Model.Key)+ if err != nil {+ return c.Failure(err)+ }++ err = c.AddAuthCookie(user)+ if err != nil {+ return c.Failure(err)+ }++ return c.Ok(web.Map{})+ }+}++// SignOut remove auth cookies+func SignOut() web.HandlerFunc {+ return func(c web.Context) error {+ c.RemoveCookie(web.CookieAuthName)return c.Redirect(http.StatusTemporaryRedirect, c.QueryParam("redirect"))}}diff --git a/app/handlers/signin_test.go b/app/handlers/signin_test.gonew file mode 100644index 000000000..04a7f4fb0--- /dev/null+++ b/app/handlers/signin_test.go@@ -0,0 +1,290 @@+package handlers_test++import (+ "fmt"+ "testing"+ "time"++ "net/http"++ "github.com/getfider/fider/app/handlers"+ "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/oauth"+ "github.com/getfider/fider/app/pkg/web"+ . "github.com/onsi/gomega"+)++func TestSignOutHandler(t *testing.T) {+ RegisterTestingT(t)++ server, _ := mock.NewServer()+ code, response := server.+ WithURL("http://demo.test.fider.io/signout?redirect=/").+ AddCookie(web.CookieAuthName, "some-value").+ Execute(handlers.SignOut())++ Expect(code).To(Equal(http.StatusTemporaryRedirect))+ Expect(response.Header().Get("Location")).To(Equal("/"))+ Expect(response.Header().Get("Set-Cookie")).To(ContainSubstring(web.CookieAuthName + "=;"))+}++func TestSignInHandler(t *testing.T) {+ RegisterTestingT(t)++ server, _ := mock.NewServer()+ code, response := server.Execute(handlers.SignIn(oauth.FacebookProvider))++ Expect(code).To(Equal(http.StatusTemporaryRedirect))+ Expect(response.Header().Get("Location")).To(Equal("http://orange.test.fider.io/oauth/token?provider=facebook&redirect="))+}++func TestCallbackHandler_InvalidState(t *testing.T) {+ RegisterTestingT(t)++ server, _ := mock.NewServer()++ Expect(func() {+ server.+ WithURL("http://login.test.fider.io/oauth/callback?state=abc").+ Execute(handlers.OAuthCallback(oauth.FacebookProvider))+ }).To(Panic())+}++func TestCallbackHandler_InvalidCode(t *testing.T) {+ RegisterTestingT(t)++ server, _ := mock.NewServer()+ code, response := server.+ WithURL("http://login.test.fider.io/oauth/callback?state=http://orange.test.fider.io").+ Execute(handlers.OAuthCallback(oauth.FacebookProvider))++ Expect(code).To(Equal(http.StatusTemporaryRedirect))+ Expect(response.Header().Get("Location")).To(Equal("http://orange.test.fider.io"))+}++func TestCallbackHandler_ExistingUserAndProvider(t *testing.T) {+ RegisterTestingT(t)++ server, _ := mock.NewServer()+ code, response := server.+ WithURL("http://demo.test.fider.io/oauth/callback?state=http://demo.test.fider.io&code=123").+ Execute(handlers.OAuthCallback(oauth.FacebookProvider))++ Expect(code).To(Equal(http.StatusTemporaryRedirect))+ Expect(response.Header().Get("Location")).To(Equal("http://demo.test.fider.io?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyL2lkIjoxLCJ1c2VyL25hbWUiOiJKb24gU25vdyIsInVzZXIvZW1haWwiOiJqb24uc25vd0Bnb3QuY29tIn0.S7P8zTU0rVovmchNbwamBewYbO96GdJcOygn7tbsikw"))+}++func TestCallbackHandler_NewUser(t *testing.T) {+ RegisterTestingT(t)++ server, services := mock.NewServer()+ code, response := server.+ WithURL("http://login.test.fider.io/oauth/callback?state=http://orange.test.fider.io&code=456").+ Execute(handlers.OAuthCallback(oauth.FacebookProvider))++ user, err := services.Users.GetByEmail(mock.OrangeTenant.ID, "[email protected]")+ Expect(err).To(BeNil())+ Expect(user.Name).To(Equal("Some Facebook Guy"))++ Expect(code).To(Equal(http.StatusTemporaryRedirect))+ Expect(response.Header().Get("Location")).To(Equal("http://orange.test.fider.io?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyL2lkIjozLCJ1c2VyL25hbWUiOiJTb21lIEZhY2Vib29rIEd1eSIsInVzZXIvZW1haWwiOiJzb21lLmd1eUBmYWNlYm9vay5jb20ifQ.ydyGDIZZHbJ-mgvpAsXTZnbs1rBH6cTVjHctZEACUOo"))+}++func TestCallbackHandler_NewUserWithoutEmail(t *testing.T) {+ RegisterTestingT(t)++ server, services := mock.NewServer()+ services.Users.Register(&models.User{+ Name: "Some Guy",+ Email: "",+ Tenant: mock.DemoTenant,+ Providers: []*models.UserProvider{+ &models.UserProvider{UID: "GO999", Name: oauth.GoogleProvider},+ },+ })++ code, response := server.+ WithURL("http://login.test.fider.io/oauth/callback?state=http://demo.test.fider.io&code=798").+ Execute(handlers.OAuthCallback(oauth.FacebookProvider))++ user, err := services.Users.GetByID(3)+ Expect(err).To(BeNil())+ Expect(user.Name).To(Equal("Some Guy"))+ Expect(len(user.Providers)).To(Equal(1))++ user, err = services.Users.GetByID(4)+ Expect(err).To(BeNil())+ Expect(user.Name).To(Equal("Mark"))+ Expect(len(user.Providers)).To(Equal(1))++ Expect(code).To(Equal(http.StatusTemporaryRedirect))+ Expect(response.Header().Get("Location")).To(Equal("http://demo.test.fider.io?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyL2lkIjo0LCJ1c2VyL25hbWUiOiJNYXJrIiwidXNlci9lbWFpbCI6IiJ9.G93ZTFcDuHiIlYbDvMnjhoDebeJZMifWbv9v0rayQOI"))+}++func TestCallbackHandler_ExistingUser_NewProvider(t *testing.T) {+ RegisterTestingT(t)++ server, services := mock.NewServer()+ code, response := server.+ WithURL("http://login.test.fider.io/oauth/callback?state=http://demo.test.fider.io&code=123").+ Execute(handlers.OAuthCallback(oauth.GoogleProvider))++ user, err := services.Users.GetByEmail(mock.DemoTenant.ID, "[email protected]")+ Expect(err).To(BeNil())+ Expect(len(user.Providers)).To(Equal(2))++ Expect(code).To(Equal(http.StatusTemporaryRedirect))+ Expect(response.Header().Get("Location")).To(Equal("http://demo.test.fider.io?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyL2lkIjoxLCJ1c2VyL25hbWUiOiJKb24gU25vdyIsInVzZXIvZW1haWwiOiJqb24uc25vd0Bnb3QuY29tIn0.S7P8zTU0rVovmchNbwamBewYbO96GdJcOygn7tbsikw"))+}++func TestSignInByEmailHandler_WithoutEmail(t *testing.T) {+ RegisterTestingT(t)++ server, _ := mock.NewServer()+ code, _ := server.+ ExecutePost(handlers.SignInByEmail(), "{ }")++ Expect(code).To(Equal(http.StatusBadRequest))+}++func TestSignInByEmailHandler_WithEmail(t *testing.T) {+ RegisterTestingT(t)++ server, _ := mock.NewServer()+ code, _ := server.+ OnTenant(mock.DemoTenant).+ ExecutePost(handlers.SignInByEmail(), `{ "email": "[email protected]" }`)++ Expect(code).To(Equal(http.StatusOK))+}++func TestVerifySignInKeyHandler_UnknownKey(t *testing.T) {+ RegisterTestingT(t)++ server, _ := mock.NewServer()+ code, response := server.+ OnTenant(mock.DemoTenant).+ WithURL("http://demo.test.fider.io/signin/verify?k=unknown").+ Execute(handlers.VerifySignInKey())++ Expect(code).To(Equal(http.StatusTemporaryRedirect))+ Expect(response.Header().Get("Location")).To(Equal("http://demo.test.fider.io"))+}++func TestVerifySignInKeyHandler_UsedKey(t *testing.T) {+ RegisterTestingT(t)++ server, services := mock.NewServer()++ services.Tenants.SaveVerificationKey("[email protected]", "1234567890")+ services.Tenants.SetKeyAsVerified("1234567890")++ code, response := server.+ OnTenant(mock.DemoTenant).+ WithURL("http://demo.test.fider.io/signin/verify?k=1234567890").+ Execute(handlers.VerifySignInKey())++ Expect(code).To(Equal(http.StatusTemporaryRedirect))+ Expect(response.Header().Get("Location")).To(Equal("http://demo.test.fider.io"))+}++func TestVerifySignInKeyHandler_ExpiredKey(t *testing.T) {+ RegisterTestingT(t)++ server, services := mock.NewServer()++ services.Tenants.SaveVerificationKey("[email protected]", "1234567890")+ request, _ := services.Tenants.FindVerificationByKey("1234567890")+ request.CreatedOn = request.CreatedOn.Add(-16 * time.Minute) //reduce 16 minutes++ code, response := server.+ OnTenant(mock.DemoTenant).+ WithURL("http://demo.test.fider.io/signin/verify?k=1234567890").+ Execute(handlers.VerifySignInKey())++ Expect(code).To(Equal(http.StatusTemporaryRedirect))+ Expect(response.Header().Get("Location")).To(Equal("http://demo.test.fider.io"))+}++func TestVerifySignInKeyHandler_CorrectKey_ExistingUser(t *testing.T) {+ RegisterTestingT(t)++ server, services := mock.NewServer()++ services.Tenants.SaveVerificationKey("[email protected]", "1234567890")++ code, response := server.+ OnTenant(mock.DemoTenant).+ WithURL("http://demo.test.fider.io/signin/verify?k=1234567890").+ Execute(handlers.VerifySignInKey())++ token, _ := jwt.Encode(models.FiderClaims{+ UserID: mock.JonSnow.ID,+ UserName: mock.JonSnow.Name,+ UserEmail: mock.JonSnow.Email,+ })++ Expect(code).To(Equal(http.StatusTemporaryRedirect))+ Expect(response.Header().Get("Location")).To(Equal("http://demo.test.fider.io"))+ Expect(response.Header().Get("Set-Cookie")).To(ContainSubstring(fmt.Sprintf("%s=%s;", web.CookieAuthName, token)))+}++func TestVerifySignInKeyHandler_CorrectKey_ExistingNewUser(t *testing.T) {+ RegisterTestingT(t)++ server, services := mock.NewServer()++ services.Tenants.SaveVerificationKey("[email protected]", "1234567890")++ code, _ := server.+ OnTenant(mock.DemoTenant).+ WithURL("http://demo.test.fider.io/signin/verify?k=1234567890").+ Execute(handlers.VerifySignInKey())++ Expect(code).To(Equal(http.StatusOK))+}++func TestCompleteSignInProfileHandler_UnknownKey(t *testing.T) {+ RegisterTestingT(t)++ server, _ := mock.NewServer()++ code, _ := server.+ OnTenant(mock.DemoTenant).+ WithURL("http://demo.test.fider.io/signin/complete").+ ExecutePost(handlers.CompleteSignInProfile(), `{ }`)++ Expect(code).To(Equal(http.StatusBadRequest))+}++func TestCompleteSignInProfileHandler_CorrecKey(t *testing.T) {+ RegisterTestingT(t)++ server, services := mock.NewServer()++ services.Tenants.SaveVerificationKey("[email protected]", "1234567890")++ code, response := server.+ OnTenant(mock.DemoTenant).+ WithURL("http://demo.test.fider.io/signin/complete").+ ExecutePost(handlers.CompleteSignInProfile(), `{ "name": "Hot Pie", "key": "1234567890" }`)+ Expect(code).To(Equal(http.StatusOK))++ user, err := services.Users.GetByEmail(mock.DemoTenant.ID, "[email protected]")+ Expect(err).To(BeNil())+ Expect(user.Name).To(Equal("Hot Pie"))+ Expect(user.Email).To(Equal("[email protected]"))++ token, _ := jwt.Encode(models.FiderClaims{+ UserID: user.ID,+ UserName: user.Name,+ UserEmail: user.Email,+ })+ Expect(response.Header().Get("Set-Cookie")).To(ContainSubstring(fmt.Sprintf("%s=%s;", web.CookieAuthName, token)))++ request, err := services.Tenants.FindVerificationByKey("1234567890")+ Expect(err).To(BeNil())+ Expect(request.VerifiedOn).NotTo(BeNil())+}diff --git a/app/middlewares/domain.go b/app/middlewares/domain.goindex 2b5d5d699..4ef9b4a23 100644--- a/app/middlewares/domain.go+++ b/app/middlewares/domain.go@@ -42,10 +42,6 @@ func MultiTenant() web.MiddlewareFunc {return func(c web.Context) error {tenants := c.Services().Tenantshostname := stripPort(c.Request().Host)- u, err := url.Parse(c.AuthEndpoint())- if err != nil {- return c.Failure(err)- }// If no tenant is specified, redirect user to getfider.com// This is only vadid for fider.io hosting@@ -54,10 +50,6 @@ func MultiTenant() web.MiddlewareFunc {return c.Redirect(http.StatusTemporaryRedirect, "http://getfider.com")}- if hostname == stripPort(u.Host) {- return next(c)- }-tenant, err := tenants.GetByDomain(hostname)if err == nil {c.SetTenant(tenant)diff --git a/app/middlewares/domain_test.go b/app/middlewares/domain_test.goindex e45d3b498..37b16a45e 100644--- a/app/middlewares/domain_test.go+++ b/app/middlewares/domain_test.go@@ -50,22 +50,6 @@ func TestMultiTenant(t *testing.T) {}}-func TestMultiTenant_AuthDomain(t *testing.T) {- RegisterTestingT(t)-- server, _ := mock.NewServer()- server.Use(middlewares.MultiTenant())-- status, _ := server.WithURL("http://login.test.fider.io").Execute(func(c web.Context) error {- if c.Tenant() == nil {- return c.NoContent(http.StatusOK)- }- return c.NoContent(http.StatusInternalServerError)- })-- Expect(status).To(Equal(http.StatusOK))-}-func TestMultiTenant_UnknownDomain(t *testing.T) {RegisterTestingT(t)diff --git a/app/middlewares/jwt.go b/app/middlewares/jwt.goindex 80557beae..79abe6168 100644--- a/app/middlewares/jwt.go+++ b/app/middlewares/jwt.go@@ -15,7 +15,7 @@ func JwtGetter() web.MiddlewareFunc {return func(next web.HandlerFunc) web.HandlerFunc {return func(c web.Context) error {- cookie, err := c.Cookie("auth")+ cookie, err := c.Cookie(web.CookieAuthName)if err != nil {if err == http.ErrNoCookie {return next(c)@@ -29,11 +29,10 @@ func JwtGetter() web.MiddlewareFunc {}services := c.Services()- c.Logger().Info(claims)user, err := services.Users.GetByID(claims.UserID)if err != nil {if err == app.ErrNotFound {- c.RemoveCookie("auth")+ c.RemoveCookie(web.CookieAuthName)return next(c)}return err@@ -64,13 +63,7 @@ func JwtSetter() web.MiddlewareFunc {jwt := query.Get("jwt")if jwt != "" {- c.SetCookie(&http.Cookie{- Name: "auth",- Value: jwt,- HttpOnly: true,- Path: "/",- Expires: time.Now().Add(365 * 24 * time.Hour),- })+ c.AddCookie(web.CookieAuthName, jwt, time.Now().Add(365*24*time.Hour))query.Del("jwt")diff --git a/app/middlewares/jwt_test.go b/app/middlewares/jwt_test.goindex 7eda3a3b2..1a342e0b9 100644--- a/app/middlewares/jwt_test.go+++ b/app/middlewares/jwt_test.go@@ -41,7 +41,7 @@ func TestJwtGetter_WithCookie(t *testing.T) {status, response := server.OnTenant(mock.DemoTenant).AddHeader("Accept", "application/json").- AddCookie("auth", token).+ AddCookie(web.CookieAuthName, token).Execute(func(c web.Context) error {return c.String(http.StatusOK, c.User().Name)})@@ -62,7 +62,7 @@ func TestJwtGetter_WithCookie_DifferentTenant(t *testing.T) {server.Use(middlewares.JwtGetter())status, _ := server.OnTenant(mock.OrangeTenant).- AddCookie("auth", token).+ AddCookie(web.CookieAuthName, token).Execute(func(c web.Context) error {if c.User() == nil {return c.NoContent(http.StatusNoContent)diff --git a/app/middlewares/setup.go b/app/middlewares/setup.goindex c0a2fdd19..4a5d9da16 100644--- a/app/middlewares/setup.go+++ b/app/middlewares/setup.go@@ -4,6 +4,8 @@ import ("fmt""runtime/debug"+ "github.com/getfider/fider/app/pkg/email"+"github.com/getfider/fider/app""github.com/getfider/fider/app/pkg/dbx""github.com/getfider/fider/app/pkg/oauth"@@ -13,7 +15,7 @@ import ()//Setup current context with some services-func Setup(db *dbx.Database) web.MiddlewareFunc {+func Setup(db *dbx.Database, emailer email.Sender) web.MiddlewareFunc {return func(next web.HandlerFunc) web.HandlerFunc {return func(c web.Context) error {logger := c.Logger().(*log.Logger)@@ -25,8 +27,10 @@ func Setup(db *dbx.Database) web.MiddlewareFunc {}c.SetActiveTransaction(trx)+c.SetServices(&app.Services{Tenants: postgres.NewTenantStorage(trx),+ Emailer: emailer,})defer func() {@@ -58,8 +62,10 @@ func AddServices() web.MiddlewareFunc {trx := c.ActiveTransaction()tenant := c.Tenant()services := c.Services()+ services.Tenants.SetCurrentTenant(tenant)services.OAuth = &oauth.HTTPService{}services.Ideas = postgres.NewIdeaStorage(tenant, trx)+ services.Ideas = postgres.NewIdeaStorage(tenant, trx)services.Users = postgres.NewUserStorage(trx)return next(c)}diff --git a/app/models/identity.go b/app/models/identity.goindex 75db76197..09e039290 100644--- a/app/models/identity.go+++ b/app/models/identity.go@@ -1,6 +1,8 @@package modelsimport (+ "time"+jwt "github.com/dgrijalva/jwt-go")@@ -87,3 +89,24 @@ type UpdateTenantSettings struct {WelcomeMessage string `json:"welcomeMessage"`UserClaims *OAuthClaims}++//SignInByEmail is the input model when user request to sign in by email+type SignInByEmail struct {+ Email string `json:"email"`+ VerificationKey string+}++//SignInRequest is the model used by e-mail verification process+type SignInRequest struct {+ Email string+ Key string+ CreatedOn time.Time+ VerifiedOn *time.Time+}++// CompleteProfile is the model used to complete user profile during e-mail sign in+type CompleteProfile struct {+ Key string `json:"key"`+ Name string `json:"name"`+ Email string+}diff --git a/app/pkg/email/email.go b/app/pkg/email/email.gonew file mode 100644index 000000000..f60fb2a29--- /dev/null+++ b/app/pkg/email/email.go@@ -0,0 +1,20 @@+package email++import "github.com/getfider/fider/app/pkg/env"++// NoReply is the default 'from' address+var NoReply = env.MustGet("NOREPLY_EMAIL")++// Sender is used to send e-mails+type Sender interface {+ Send(from, to, subject, message string) error+}++//NoopSender does not send e-mails+type NoopSender struct {+}++//Send an e-mail+func (s *NoopSender) Send(from, to, subject, message string) error {+ return nil+}diff --git a/app/pkg/email/mailgun/mailgun.go b/app/pkg/email/mailgun/mailgun.gonew file mode 100644index 000000000..85a9957eb--- /dev/null+++ b/app/pkg/email/mailgun/mailgun.go@@ -0,0 +1,45 @@+package mailgun++import (+ "fmt"+ "net/http"+ "net/url"+ "strings"++ "github.com/getfider/fider/app/pkg/email"+)++var baseURL = "https://api.mailgun.net/v3/%s/messages"++//Sender is used to send e-mails+type Sender struct {+ domain string+ apiKey string+}++//NewSender creates a new mailgun e-mail sender+func NewSender(domain, apiKey string) *Sender {+ return &Sender{domain, apiKey}+}++//Send an e-mail+func (s *Sender) Send(from, to, subject, message string) error {++ form := url.Values{}+ form.Add("from", fmt.Sprintf("%s <%s>", from, email.NoReply))+ form.Add("to", to)+ form.Add("subject", subject)+ form.Add("html", message)++ url := fmt.Sprintf(baseURL, s.domain)+ request, err := http.NewRequest("POST", url, strings.NewReader(form.Encode()))+ if err != nil {+ return err+ }++ request.SetBasicAuth("api", s.apiKey)+ request.Header.Set("Content-Type", "application/x-www-form-urlencoded")++ _, err = http.DefaultClient.Do(request)+ return err+}diff --git a/app/pkg/email/smtp/smtp.go b/app/pkg/email/smtp/smtp.gonew file mode 100644index 000000000..2ff78ba6a--- /dev/null+++ b/app/pkg/email/smtp/smtp.go@@ -0,0 +1,42 @@+package smtp++import (+ "fmt"+ gosmtp "net/smtp"++ "github.com/getfider/fider/app/pkg/email"+)++//Sender is used to send e-mails+type Sender struct {+ host string+ port string+ username string+ password string+}++//NewSender creates a new mailgun e-mail sender+func NewSender(host, port, username, password string) *Sender {+ return &Sender{host, port, username, password}+}++//Send an e-mail+func (s *Sender) Send(from, to, subject, message string) error {++ headers := make(map[string]string)+ headers["From"] = fmt.Sprintf("%s <%s>", from, email.NoReply)+ headers["To"] = to+ headers["Subject"] = subject+ headers["MIME-version"] = "1.0"+ headers["Content-Type"] = "text/html; charset=\"UTF-8\""++ body := ""+ for k, v := range headers {+ body += fmt.Sprintf("%s: %s\r\n", k, v)+ }+ body += "\r\n" + message++ servername := fmt.Sprintf("%s:%s", s.host, s.port)+ auth := gosmtp.PlainAuth("", s.username, s.password, s.host)+ return gosmtp.SendMail(servername, auth, from, []string{to}, []byte(body))+}diff --git a/app/pkg/env/env.go b/app/pkg/env/env.goindex 6a96f3a8f..31a2805de 100644--- a/app/pkg/env/env.go+++ b/app/pkg/env/env.go@@ -18,6 +18,12 @@ func GetEnvOrDefault(name string, defaultValue string) string {return value}+// IsDefined returns true if given environment variable is defined+func IsDefined(name string) bool {+ value := os.Getenv(name)+ return value != ""+}+// MustGet returns environment variable or panicfunc MustGet(name string) string {value := os.Getenv(name)diff --git a/app/pkg/mock/oauth.go b/app/pkg/mock/oauth.goindex 89041a6d7..58f099e3c 100644--- a/app/pkg/mock/oauth.go+++ b/app/pkg/mock/oauth.go@@ -7,7 +7,7 @@ type OAuthService struct{}//GetAuthURL returns authentication url for given providerfunc (p *OAuthService) GetAuthURL(authEndpoint string, provider string, redirect string) string {- return "http://orange.test.canherayou.com/oauth/token?provider=" + provider + "&redirect=" + redirect+ return "http://orange.test.fider.io/oauth/token?provider=" + provider + "&redirect=" + redirect}//GetProfile returns user profile based on provider and codediff --git a/app/pkg/mock/setup.go b/app/pkg/mock/setup.goindex 77e1625b8..33195690b 100644--- a/app/pkg/mock/setup.go+++ b/app/pkg/mock/setup.go@@ -5,6 +5,7 @@ import ("github.com/getfider/fider/app""github.com/getfider/fider/app/models"+ "github.com/getfider/fider/app/pkg/email""github.com/getfider/fider/app/pkg/oauth""github.com/getfider/fider/app/storage/inmemory")@@ -43,6 +44,7 @@ func createServices(seed bool) *app.Services {Users: &inmemory.UserStorage{},Ideas: &inmemory.IdeaStorage{},OAuth: &OAuthService{},+ Emailer: &email.NoopSender{},}if seed {diff --git a/app/pkg/oauth/http.go b/app/pkg/oauth/http.goindex 2856e3076..c512f59c1 100644--- a/app/pkg/oauth/http.go+++ b/app/pkg/oauth/http.go@@ -119,7 +119,7 @@ func (p *HTTPService) GetProfile(authEndpoint string, provider string, code strireturn nil, fmt.Errorf("HTTP Get profile for %s failed with %s", provider, err)}- //GitHub allows users to omit name, so we use their login+ //GitHub allows users to omit name, so we use their login nameif strings.Trim(profile.Name, " ") == "" {profile.Name = profile.Login}diff --git a/app/pkg/uuid/uuid.go b/app/pkg/uuid/uuid.gonew file mode 100644index 000000000..295f3fc2c--- /dev/null+++ b/app/pkg/uuid/uuid.go@@ -0,0 +1,481 @@+// Copyright (C) 2013-2015 by Maxim Bublis <[email protected]>+//+// Permission is hereby granted, free of charge, to any person obtaining+// a copy of this software and associated documentation files (the+// "Software"), to deal in the Software without restriction, including+// without limitation the rights to use, copy, modify, merge, publish,+// distribute, sublicense, and/or sell copies of the Software, and to+// permit persons to whom the Software is furnished to do so, subject to+// the following conditions:+//+// The above copyright notice and this permission notice shall be+// included in all copies or substantial portions of the Software.+//+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.++// Package uuid provides implementation of Universally Unique Identifier (UUID).+// Supported versions are 1, 3, 4 and 5 (as specified in RFC 4122) and+// version 2 (as specified in DCE 1.1).+package uuid++import (+ "bytes"+ "crypto/md5"+ "crypto/rand"+ "crypto/sha1"+ "database/sql/driver"+ "encoding/binary"+ "encoding/hex"+ "fmt"+ "hash"+ "net"+ "os"+ "sync"+ "time"+)++// UUID layout variants.+const (+ VariantNCS = iota+ VariantRFC4122+ VariantMicrosoft+ VariantFuture+)++// UUID DCE domains.+const (+ DomainPerson = iota+ DomainGroup+ DomainOrg+)++// Difference in 100-nanosecond intervals between+// UUID epoch (October 15, 1582) and Unix epoch (January 1, 1970).+const epochStart = 122192928000000000++// Used in string method conversion+const dash byte = '-'++// UUID v1/v2 storage.+var (+ storageMutex sync.Mutex+ storageOnce sync.Once+ epochFunc = unixTimeFunc+ clockSequence uint16+ lastTime uint64+ hardwareAddr [6]byte+ posixUID = uint32(os.Getuid())+ posixGID = uint32(os.Getgid())+)++// String parse helpers.+var (+ urnPrefix = []byte("urn:uuid:")+ byteGroups = []int{8, 4, 4, 4, 12}+)++func initClockSequence() {+ buf := make([]byte, 2)+ safeRandom(buf)+ clockSequence = binary.BigEndian.Uint16(buf)+}++func initHardwareAddr() {+ interfaces, err := net.Interfaces()+ if err == nil {+ for _, iface := range interfaces {+ if len(iface.HardwareAddr) >= 6 {+ copy(hardwareAddr[:], iface.HardwareAddr)+ return+ }+ }+ }++ // Initialize hardwareAddr randomly in case+ // of real network interfaces absence+ safeRandom(hardwareAddr[:])++ // Set multicast bit as recommended in RFC 4122+ hardwareAddr[0] |= 0x01+}++func initStorage() {+ initClockSequence()+ initHardwareAddr()+}++func safeRandom(dest []byte) {+ if _, err := rand.Read(dest); err != nil {+ panic(err)+ }+}++// Returns difference in 100-nanosecond intervals between+// UUID epoch (October 15, 1582) and current time.+// This is default epoch calculation function.+func unixTimeFunc() uint64 {+ return epochStart + uint64(time.Now().UnixNano()/100)+}++// UUID representation compliant with specification+// described in RFC 4122.+type UUID [16]byte++// NullUUID can be used with the standard sql package to represent a+// UUID value that can be NULL in the database+type NullUUID struct {+ UUID UUID+ Valid bool+}++// The nil UUID is special form of UUID that is specified to have all+// 128 bits set to zero.+var Nil = UUID{}++// Predefined namespace UUIDs.+var (+ NamespaceDNS, _ = FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8")+ NamespaceURL, _ = FromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8")+ NamespaceOID, _ = FromString("6ba7b812-9dad-11d1-80b4-00c04fd430c8")+ NamespaceX500, _ = FromString("6ba7b814-9dad-11d1-80b4-00c04fd430c8")+)++// And returns result of binary AND of two UUIDs.+func And(u1 UUID, u2 UUID) UUID {+ u := UUID{}+ for i := 0; i < 16; i++ {+ u[i] = u1[i] & u2[i]+ }+ return u+}++// Or returns result of binary OR of two UUIDs.+func Or(u1 UUID, u2 UUID) UUID {+ u := UUID{}+ for i := 0; i < 16; i++ {+ u[i] = u1[i] | u2[i]+ }+ return u+}++// Equal returns true if u1 and u2 equals, otherwise returns false.+func Equal(u1 UUID, u2 UUID) bool {+ return bytes.Equal(u1[:], u2[:])+}++// Version returns algorithm version used to generate UUID.+func (u UUID) Version() uint {+ return uint(u[6] >> 4)+}++// Variant returns UUID layout variant.+func (u UUID) Variant() uint {+ switch {+ case (u[8] & 0x80) == 0x00:+ return VariantNCS+ case (u[8]&0xc0)|0x80 == 0x80:+ return VariantRFC4122+ case (u[8]&0xe0)|0xc0 == 0xc0:+ return VariantMicrosoft+ }+ return VariantFuture+}++// Bytes returns bytes slice representation of UUID.+func (u UUID) Bytes() []byte {+ return u[:]+}++// Returns canonical string representation of UUID:+// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.+func (u UUID) String() string {+ buf := make([]byte, 36)++ hex.Encode(buf[0:8], u[0:4])+ buf[8] = dash+ hex.Encode(buf[9:13], u[4:6])+ buf[13] = dash+ hex.Encode(buf[14:18], u[6:8])+ buf[18] = dash+ hex.Encode(buf[19:23], u[8:10])+ buf[23] = dash+ hex.Encode(buf[24:], u[10:])++ return string(buf)+}++// SetVersion sets version bits.+func (u *UUID) SetVersion(v byte) {+ u[6] = (u[6] & 0x0f) | (v << 4)+}++// SetVariant sets variant bits as described in RFC 4122.+func (u *UUID) SetVariant() {+ u[8] = (u[8] & 0xbf) | 0x80+}++// MarshalText implements the encoding.TextMarshaler interface.+// The encoding is the same as returned by String.+func (u UUID) MarshalText() (text []byte, err error) {+ text = []byte(u.String())+ return+}++// UnmarshalText implements the encoding.TextUnmarshaler interface.+// Following formats are supported:+// "6ba7b810-9dad-11d1-80b4-00c04fd430c8",+// "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",+// "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8"+func (u *UUID) UnmarshalText(text []byte) (err error) {+ if len(text) < 32 {+ err = fmt.Errorf("uuid: UUID string too short: %s", text)+ return+ }++ t := text[:]+ braced := false++ if bytes.Equal(t[:9], urnPrefix) {+ t = t[9:]+ } else if t[0] == '{' {+ braced = true+ t = t[1:]+ }++ b := u[:]++ for i, byteGroup := range byteGroups {+ if i > 0 {+ if t[0] != '-' {+ err = fmt.Errorf("uuid: invalid string format")+ return+ }+ t = t[1:]+ }++ if len(t) < byteGroup {+ err = fmt.Errorf("uuid: UUID string too short: %s", text)+ return+ }++ if i == 4 && len(t) > byteGroup &&+ ((braced && t[byteGroup] != '}') || len(t[byteGroup:]) > 1 || !braced) {+ err = fmt.Errorf("uuid: UUID string too long: %s", text)+ return+ }++ _, err = hex.Decode(b[:byteGroup/2], t[:byteGroup])+ if err != nil {+ return+ }++ t = t[byteGroup:]+ b = b[byteGroup/2:]+ }++ return+}++// MarshalBinary implements the encoding.BinaryMarshaler interface.+func (u UUID) MarshalBinary() (data []byte, err error) {+ data = u.Bytes()+ return+}++// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.+// It will return error if the slice isn't 16 bytes long.+func (u *UUID) UnmarshalBinary(data []byte) (err error) {+ if len(data) != 16 {+ err = fmt.Errorf("uuid: UUID must be exactly 16 bytes long, got %d bytes", len(data))+ return+ }+ copy(u[:], data)++ return+}++// Value implements the driver.Valuer interface.+func (u UUID) Value() (driver.Value, error) {+ return u.String(), nil+}++// Scan implements the sql.Scanner interface.+// A 16-byte slice is handled by UnmarshalBinary, while+// a longer byte slice or a string is handled by UnmarshalText.+func (u *UUID) Scan(src interface{}) error {+ switch src := src.(type) {+ case []byte:+ if len(src) == 16 {+ return u.UnmarshalBinary(src)+ }+ return u.UnmarshalText(src)++ case string:+ return u.UnmarshalText([]byte(src))+ }++ return fmt.Errorf("uuid: cannot convert %T to UUID", src)+}++// Value implements the driver.Valuer interface.+func (u NullUUID) Value() (driver.Value, error) {+ if !u.Valid {+ return nil, nil+ }+ // Delegate to UUID Value function+ return u.UUID.Value()+}++// Scan implements the sql.Scanner interface.+func (u *NullUUID) Scan(src interface{}) error {+ if src == nil {+ u.UUID, u.Valid = Nil, false+ return nil+ }++ // Delegate to UUID Scan function+ u.Valid = true+ return u.UUID.Scan(src)+}++// FromBytes returns UUID converted from raw byte slice input.+// It will return error if the slice isn't 16 bytes long.+func FromBytes(input []byte) (u UUID, err error) {+ err = u.UnmarshalBinary(input)+ return+}++// FromBytesOrNil returns UUID converted from raw byte slice input.+// Same behavior as FromBytes, but returns a Nil UUID on error.+func FromBytesOrNil(input []byte) UUID {+ uuid, err := FromBytes(input)+ if err != nil {+ return Nil+ }+ return uuid+}++// FromString returns UUID parsed from string input.+// Input is expected in a form accepted by UnmarshalText.+func FromString(input string) (u UUID, err error) {+ err = u.UnmarshalText([]byte(input))+ return+}++// FromStringOrNil returns UUID parsed from string input.+// Same behavior as FromString, but returns a Nil UUID on error.+func FromStringOrNil(input string) UUID {+ uuid, err := FromString(input)+ if err != nil {+ return Nil+ }+ return uuid+}++// Returns UUID v1/v2 storage state.+// Returns epoch timestamp, clock sequence, and hardware address.+func getStorage() (uint64, uint16, []byte) {+ storageOnce.Do(initStorage)++ storageMutex.Lock()+ defer storageMutex.Unlock()++ timeNow := epochFunc()+ // Clock changed backwards since last UUID generation.+ // Should increase clock sequence.+ if timeNow <= lastTime {+ clockSequence+++ }+ lastTime = timeNow++ return timeNow, clockSequence, hardwareAddr[:]+}++// NewV1 returns UUID based on current timestamp and MAC address.+func NewV1() UUID {+ u := UUID{}++ timeNow, clockSeq, hardwareAddr := getStorage()++ binary.BigEndian.PutUint32(u[0:], uint32(timeNow))+ binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>32))+ binary.BigEndian.PutUint16(u[6:], uint16(timeNow>>48))+ binary.BigEndian.PutUint16(u[8:], clockSeq)++ copy(u[10:], hardwareAddr)++ u.SetVersion(1)+ u.SetVariant()++ return u+}++// NewV2 returns DCE Security UUID based on POSIX UID/GID.+func NewV2(domain byte) UUID {+ u := UUID{}++ timeNow, clockSeq, hardwareAddr := getStorage()++ switch domain {+ case DomainPerson:+ binary.BigEndian.PutUint32(u[0:], posixUID)+ case DomainGroup:+ binary.BigEndian.PutUint32(u[0:], posixGID)+ }++ binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>32))+ binary.BigEndian.PutUint16(u[6:], uint16(timeNow>>48))+ binary.BigEndian.PutUint16(u[8:], clockSeq)+ u[9] = domain++ copy(u[10:], hardwareAddr)++ u.SetVersion(2)+ u.SetVariant()++ return u+}++// NewV3 returns UUID based on MD5 hash of namespace UUID and name.+func NewV3(ns UUID, name string) UUID {+ u := newFromHash(md5.New(), ns, name)+ u.SetVersion(3)+ u.SetVariant()++ return u+}++// NewV4 returns random generated UUID.+func NewV4() UUID {+ u := UUID{}+ safeRandom(u[:])+ u.SetVersion(4)+ u.SetVariant()++ return u+}++// NewV5 returns UUID based on SHA-1 hash of namespace UUID and name.+func NewV5(ns UUID, name string) UUID {+ u := newFromHash(sha1.New(), ns, name)+ u.SetVersion(5)+ u.SetVariant()++ return u+}++// Returns UUID based on hashing of namespace UUID and name.+func newFromHash(h hash.Hash, ns UUID, name string) UUID {+ u := UUID{}+ h.Write(ns[:])+ h.Write([]byte(name))+ copy(u[:], h.Sum(nil))++ return u+}diff --git a/app/pkg/uuid/uuid_test.go b/app/pkg/uuid/uuid_test.gonew file mode 100644index 000000000..56504808f--- /dev/null+++ b/app/pkg/uuid/uuid_test.go@@ -0,0 +1,633 @@+// Copyright (C) 2013, 2015 by Maxim Bublis <[email protected]>+//+// Permission is hereby granted, free of charge, to any person obtaining+// a copy of this software and associated documentation files (the+// "Software"), to deal in the Software without restriction, including+// without limitation the rights to use, copy, modify, merge, publish,+// distribute, sublicense, and/or sell copies of the Software, and to+// permit persons to whom the Software is furnished to do so, subject to+// the following conditions:+//+// The above copyright notice and this permission notice shall be+// included in all copies or substantial portions of the Software.+//+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.++package uuid++import (+ "bytes"+ "testing"+)++func TestBytes(t *testing.T) {+ u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}++ bytes1 := []byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}++ if !bytes.Equal(u.Bytes(), bytes1) {+ t.Errorf("Incorrect bytes representation for UUID: %s", u)+ }+}++func TestString(t *testing.T) {+ if NamespaceDNS.String() != "6ba7b810-9dad-11d1-80b4-00c04fd430c8" {+ t.Errorf("Incorrect string representation for UUID: %s", NamespaceDNS.String())+ }+}++func TestEqual(t *testing.T) {+ if !Equal(NamespaceDNS, NamespaceDNS) {+ t.Errorf("Incorrect comparison of %s and %s", NamespaceDNS, NamespaceDNS)+ }++ if Equal(NamespaceDNS, NamespaceURL) {+ t.Errorf("Incorrect comparison of %s and %s", NamespaceDNS, NamespaceURL)+ }+}++func TestOr(t *testing.T) {+ u1 := UUID{0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff}+ u2 := UUID{0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00}++ u := UUID{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}++ if !Equal(u, Or(u1, u2)) {+ t.Errorf("Incorrect bitwise OR result %s", Or(u1, u2))+ }+}++func TestAnd(t *testing.T) {+ u1 := UUID{0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff}+ u2 := UUID{0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00}++ u := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}++ if !Equal(u, And(u1, u2)) {+ t.Errorf("Incorrect bitwise AND result %s", And(u1, u2))+ }+}++func TestVersion(t *testing.T) {+ u := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}++ if u.Version() != 1 {+ t.Errorf("Incorrect version for UUID: %d", u.Version())+ }+}++func TestSetVersion(t *testing.T) {+ u := UUID{}+ u.SetVersion(4)++ if u.Version() != 4 {+ t.Errorf("Incorrect version for UUID after u.setVersion(4): %d", u.Version())+ }+}++func TestVariant(t *testing.T) {+ u1 := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}++ if u1.Variant() != VariantNCS {+ t.Errorf("Incorrect variant for UUID variant %d: %d", VariantNCS, u1.Variant())+ }++ u2 := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}++ if u2.Variant() != VariantRFC4122 {+ t.Errorf("Incorrect variant for UUID variant %d: %d", VariantRFC4122, u2.Variant())+ }++ u3 := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}++ if u3.Variant() != VariantMicrosoft {+ t.Errorf("Incorrect variant for UUID variant %d: %d", VariantMicrosoft, u3.Variant())+ }++ u4 := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}++ if u4.Variant() != VariantFuture {+ t.Errorf("Incorrect variant for UUID variant %d: %d", VariantFuture, u4.Variant())+ }+}++func TestSetVariant(t *testing.T) {+ u := new(UUID)+ u.SetVariant()++ if u.Variant() != VariantRFC4122 {+ t.Errorf("Incorrect variant for UUID after u.setVariant(): %d", u.Variant())+ }+}++func TestFromBytes(t *testing.T) {+ u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}+ b1 := []byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}++ u1, err := FromBytes(b1)+ if err != nil {+ t.Errorf("Error parsing UUID from bytes: %s", err)+ }++ if !Equal(u, u1) {+ t.Errorf("UUIDs should be equal: %s and %s", u, u1)+ }++ b2 := []byte{}++ _, err = FromBytes(b2)+ if err == nil {+ t.Errorf("Should return error parsing from empty byte slice, got %s", err)+ }+}++func TestMarshalBinary(t *testing.T) {+ u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}+ b1 := []byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}++ b2, err := u.MarshalBinary()+ if err != nil {+ t.Errorf("Error marshaling UUID: %s", err)+ }++ if !bytes.Equal(b1, b2) {+ t.Errorf("Marshaled UUID should be %s, got %s", b1, b2)+ }+}++func TestUnmarshalBinary(t *testing.T) {+ u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}+ b1 := []byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}++ u1 := UUID{}+ err := u1.UnmarshalBinary(b1)+ if err != nil {+ t.Errorf("Error unmarshaling UUID: %s", err)+ }++ if !Equal(u, u1) {+ t.Errorf("UUIDs should be equal: %s and %s", u, u1)+ }++ b2 := []byte{}+ u2 := UUID{}++ err = u2.UnmarshalBinary(b2)+ if err == nil {+ t.Errorf("Should return error unmarshalling from empty byte slice, got %s", err)+ }+}++func TestFromString(t *testing.T) {+ u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}++ s1 := "6ba7b810-9dad-11d1-80b4-00c04fd430c8"+ s2 := "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}"+ s3 := "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8"++ _, err := FromString("")+ if err == nil {+ t.Errorf("Should return error trying to parse empty string, got %s", err)+ }++ u1, err := FromString(s1)+ if err != nil {+ t.Errorf("Error parsing UUID from string: %s", err)+ }++ if !Equal(u, u1) {+ t.Errorf("UUIDs should be equal: %s and %s", u, u1)+ }++ u2, err := FromString(s2)+ if err != nil {+ t.Errorf("Error parsing UUID from string: %s", err)+ }++ if !Equal(u, u2) {+ t.Errorf("UUIDs should be equal: %s and %s", u, u2)+ }++ u3, err := FromString(s3)+ if err != nil {+ t.Errorf("Error parsing UUID from string: %s", err)+ }++ if !Equal(u, u3) {+ t.Errorf("UUIDs should be equal: %s and %s", u, u3)+ }+}++func TestFromStringShort(t *testing.T) {+ // Invalid 35-character UUID string+ s1 := "6ba7b810-9dad-11d1-80b4-00c04fd430c"++ for i := len(s1); i >= 0; i-- {+ _, err := FromString(s1[:i])+ if err == nil {+ t.Errorf("Should return error trying to parse too short string, got %s", err)+ }+ }+}++func TestFromStringLong(t *testing.T) {+ // Invalid 37+ character UUID string+ s := []string{+ "6ba7b810-9dad-11d1-80b4-00c04fd430c8=",+ "6ba7b810-9dad-11d1-80b4-00c04fd430c8}",+ "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}f",+ "6ba7b810-9dad-11d1-80b4-00c04fd430c800c04fd430c8",+ }++ for _, str := range s {+ _, err := FromString(str)+ if err == nil {+ t.Errorf("Should return error trying to parse too long string, passed %s", str)+ }+ }+}++func TestFromStringInvalid(t *testing.T) {+ // Invalid UUID string formats+ s := []string{+ "6ba7b8109dad11d180b400c04fd430c8",+ "6ba7b8109dad11d180b400c04fd430c86ba7b8109dad11d180b400c04fd430c8",+ "urn:uuid:{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",+ "6ba7b8109-dad-11d1-80b4-00c04fd430c8",+ "6ba7b810-9dad1-1d1-80b4-00c04fd430c8",+ "6ba7b810-9dad-11d18-0b4-00c04fd430c8",+ "6ba7b810-9dad-11d1-80b40-0c04fd430c8",+ "6ba7b810+9dad+11d1+80b4+00c04fd430c8",+ "6ba7b810-9dad11d180b400c04fd430c8",+ "6ba7b8109dad-11d180b400c04fd430c8",+ "6ba7b8109dad11d1-80b400c04fd430c8",+ "6ba7b8109dad11d180b4-00c04fd430c8",+ }++ for _, str := range s {+ _, err := FromString(str)+ if err == nil {+ t.Errorf("Should return error trying to parse invalid string, passed %s", str)+ }+ }+}++func TestFromStringOrNil(t *testing.T) {+ u := FromStringOrNil("")+ if u != Nil {+ t.Errorf("Should return Nil UUID on parse failure, got %s", u)+ }+}++func TestFromBytesOrNil(t *testing.T) {+ b := []byte{}+ u := FromBytesOrNil(b)+ if u != Nil {+ t.Errorf("Should return Nil UUID on parse failure, got %s", u)+ }+}++func TestMarshalText(t *testing.T) {+ u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}+ b1 := []byte("6ba7b810-9dad-11d1-80b4-00c04fd430c8")++ b2, err := u.MarshalText()+ if err != nil {+ t.Errorf("Error marshaling UUID: %s", err)+ }++ if !bytes.Equal(b1, b2) {+ t.Errorf("Marshaled UUID should be %s, got %s", b1, b2)+ }+}++func TestUnmarshalText(t *testing.T) {+ u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}+ b1 := []byte("6ba7b810-9dad-11d1-80b4-00c04fd430c8")++ u1 := UUID{}+ err := u1.UnmarshalText(b1)+ if err != nil {+ t.Errorf("Error unmarshaling UUID: %s", err)+ }++ if !Equal(u, u1) {+ t.Errorf("UUIDs should be equal: %s and %s", u, u1)+ }++ b2 := []byte("")+ u2 := UUID{}++ err = u2.UnmarshalText(b2)+ if err == nil {+ t.Errorf("Should return error trying to unmarshal from empty string")+ }+}++func TestValue(t *testing.T) {+ u, err := FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8")+ if err != nil {+ t.Errorf("Error parsing UUID from string: %s", err)+ }++ val, err := u.Value()+ if err != nil {+ t.Errorf("Error getting UUID value: %s", err)+ }++ if val != u.String() {+ t.Errorf("Wrong value returned, should be equal: %s and %s", val, u)+ }+}++func TestValueNil(t *testing.T) {+ u := UUID{}++ val, err := u.Value()+ if err != nil {+ t.Errorf("Error getting UUID value: %s", err)+ }++ if val != Nil.String() {+ t.Errorf("Wrong value returned, should be equal to UUID.Nil: %s", val)+ }+}++func TestNullUUIDValueNil(t *testing.T) {+ u := NullUUID{}++ val, err := u.Value()+ if err != nil {+ t.Errorf("Error getting UUID value: %s", err)+ }++ if val != nil {+ t.Errorf("Wrong value returned, should be nil: %s", val)+ }+}++func TestScanBinary(t *testing.T) {+ u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}+ b1 := []byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}++ u1 := UUID{}+ err := u1.Scan(b1)+ if err != nil {+ t.Errorf("Error unmarshaling UUID: %s", err)+ }++ if !Equal(u, u1) {+ t.Errorf("UUIDs should be equal: %s and %s", u, u1)+ }++ b2 := []byte{}+ u2 := UUID{}++ err = u2.Scan(b2)+ if err == nil {+ t.Errorf("Should return error unmarshalling from empty byte slice, got %s", err)+ }+}++func TestScanString(t *testing.T) {+ u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}+ s1 := "6ba7b810-9dad-11d1-80b4-00c04fd430c8"++ u1 := UUID{}+ err := u1.Scan(s1)+ if err != nil {+ t.Errorf("Error unmarshaling UUID: %s", err)+ }++ if !Equal(u, u1) {+ t.Errorf("UUIDs should be equal: %s and %s", u, u1)+ }++ s2 := ""+ u2 := UUID{}++ err = u2.Scan(s2)+ if err == nil {+ t.Errorf("Should return error trying to unmarshal from empty string")+ }+}++func TestScanText(t *testing.T) {+ u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}+ b1 := []byte("6ba7b810-9dad-11d1-80b4-00c04fd430c8")++ u1 := UUID{}+ err := u1.Scan(b1)+ if err != nil {+ t.Errorf("Error unmarshaling UUID: %s", err)+ }++ if !Equal(u, u1) {+ t.Errorf("UUIDs should be equal: %s and %s", u, u1)+ }++ b2 := []byte("")+ u2 := UUID{}++ err = u2.Scan(b2)+ if err == nil {+ t.Errorf("Should return error trying to unmarshal from empty string")+ }+}++func TestScanUnsupported(t *testing.T) {+ u := UUID{}++ err := u.Scan(true)+ if err == nil {+ t.Errorf("Should return error trying to unmarshal from bool")+ }+}++func TestScanNil(t *testing.T) {+ u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}++ err := u.Scan(nil)+ if err == nil {+ t.Errorf("Error UUID shouldn't allow unmarshalling from nil")+ }+}++func TestNullUUIDScanValid(t *testing.T) {+ u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}+ s1 := "6ba7b810-9dad-11d1-80b4-00c04fd430c8"++ u1 := NullUUID{}+ err := u1.Scan(s1)+ if err != nil {+ t.Errorf("Error unmarshaling NullUUID: %s", err)+ }++ if !u1.Valid {+ t.Errorf("NullUUID should be valid")+ }++ if !Equal(u, u1.UUID) {+ t.Errorf("UUIDs should be equal: %s and %s", u, u1.UUID)+ }+}++func TestNullUUIDScanNil(t *testing.T) {+ u := NullUUID{UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}, true}++ err := u.Scan(nil)+ if err != nil {+ t.Errorf("Error unmarshaling NullUUID: %s", err)+ }++ if u.Valid {+ t.Errorf("NullUUID should not be valid")+ }++ if !Equal(u.UUID, Nil) {+ t.Errorf("NullUUID value should be equal to Nil: %v", u)+ }+}++func TestNewV1(t *testing.T) {+ u := NewV1()++ if u.Version() != 1 {+ t.Errorf("UUIDv1 generated with incorrect version: %d", u.Version())+ }++ if u.Variant() != VariantRFC4122 {+ t.Errorf("UUIDv1 generated with incorrect variant: %d", u.Variant())+ }++ u1 := NewV1()+ u2 := NewV1()++ if Equal(u1, u2) {+ t.Errorf("UUIDv1 generated two equal UUIDs: %s and %s", u1, u2)+ }++ oldFunc := epochFunc+ epochFunc = func() uint64 { return 0 }++ u3 := NewV1()+ u4 := NewV1()++ if Equal(u3, u4) {+ t.Errorf("UUIDv1 generated two equal UUIDs: %s and %s", u3, u4)+ }++ epochFunc = oldFunc+}++func TestNewV2(t *testing.T) {+ u1 := NewV2(DomainPerson)++ if u1.Version() != 2 {+ t.Errorf("UUIDv2 generated with incorrect version: %d", u1.Version())+ }++ if u1.Variant() != VariantRFC4122 {+ t.Errorf("UUIDv2 generated with incorrect variant: %d", u1.Variant())+ }++ u2 := NewV2(DomainGroup)++ if u2.Version() != 2 {+ t.Errorf("UUIDv2 generated with incorrect version: %d", u2.Version())+ }++ if u2.Variant() != VariantRFC4122 {+ t.Errorf("UUIDv2 generated with incorrect variant: %d", u2.Variant())+ }+}++func TestNewV3(t *testing.T) {+ u := NewV3(NamespaceDNS, "www.example.com")++ if u.Version() != 3 {+ t.Errorf("UUIDv3 generated with incorrect version: %d", u.Version())+ }++ if u.Variant() != VariantRFC4122 {+ t.Errorf("UUIDv3 generated with incorrect variant: %d", u.Variant())+ }++ if u.String() != "5df41881-3aed-3515-88a7-2f4a814cf09e" {+ t.Errorf("UUIDv3 generated incorrectly: %s", u.String())+ }++ u = NewV3(NamespaceDNS, "python.org")++ if u.String() != "6fa459ea-ee8a-3ca4-894e-db77e160355e" {+ t.Errorf("UUIDv3 generated incorrectly: %s", u.String())+ }++ u1 := NewV3(NamespaceDNS, "golang.org")+ u2 := NewV3(NamespaceDNS, "golang.org")+ if !Equal(u1, u2) {+ t.Errorf("UUIDv3 generated different UUIDs for same namespace and name: %s and %s", u1, u2)+ }++ u3 := NewV3(NamespaceDNS, "example.com")+ if Equal(u1, u3) {+ t.Errorf("UUIDv3 generated same UUIDs for different names in same namespace: %s and %s", u1, u2)+ }++ u4 := NewV3(NamespaceURL, "golang.org")+ if Equal(u1, u4) {+ t.Errorf("UUIDv3 generated same UUIDs for sane names in different namespaces: %s and %s", u1, u4)+ }+}++func TestNewV4(t *testing.T) {+ u := NewV4()++ if u.Version() != 4 {+ t.Errorf("UUIDv4 generated with incorrect version: %d", u.Version())+ }++ if u.Variant() != VariantRFC4122 {+ t.Errorf("UUIDv4 generated with incorrect variant: %d", u.Variant())+ }+}++func TestNewV5(t *testing.T) {+ u := NewV5(NamespaceDNS, "www.example.com")++ if u.Version() != 5 {+ t.Errorf("UUIDv5 generated with incorrect version: %d", u.Version())+ }++ if u.Variant() != VariantRFC4122 {+ t.Errorf("UUIDv5 generated with incorrect variant: %d", u.Variant())+ }++ u = NewV5(NamespaceDNS, "python.org")++ if u.String() != "886313e1-3b8a-5372-9b90-0c9aee199e5d" {+ t.Errorf("UUIDv5 generated incorrectly: %s", u.String())+ }++ u1 := NewV5(NamespaceDNS, "golang.org")+ u2 := NewV5(NamespaceDNS, "golang.org")+ if !Equal(u1, u2) {+ t.Errorf("UUIDv5 generated different UUIDs for same namespace and name: %s and %s", u1, u2)+ }++ u3 := NewV5(NamespaceDNS, "example.com")+ if Equal(u1, u3) {+ t.Errorf("UUIDv5 generated same UUIDs for different names in same namespace: %s and %s", u1, u2)+ }++ u4 := NewV5(NamespaceURL, "golang.org")+ if Equal(u1, u4) {+ t.Errorf("UUIDv3 generated same UUIDs for sane names in different namespaces: %s and %s", u1, u4)+ }+}diff --git a/app/pkg/validate/domain.go b/app/pkg/validate/domain.goindex 730fdbb1b..f51a99787 100644--- a/app/pkg/validate/domain.go+++ b/app/pkg/validate/domain.go@@ -9,7 +9,7 @@ import ("github.com/getfider/fider/app/storage")-var r, _ = regexp.Compile("^[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]$")+var domainRegex = regexp.MustCompile("^[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]$")//Subdomain validates given subdomainfunc Subdomain(tenants storage.Tenant, subdomain string) *Result {@@ -23,7 +23,7 @@ func Subdomain(tenants storage.Tenant, subdomain string) *Result {return Failed([]string{"Subdomain must be less than 40 characters."})}- if !r.MatchString(subdomain) {+ if !domainRegex.MatchString(subdomain) {return Failed([]string{"Subdomain contains invalid characters."})}diff --git a/app/pkg/validate/email.go b/app/pkg/validate/email.gonew file mode 100644index 000000000..21838824c--- /dev/null+++ b/app/pkg/validate/email.go@@ -0,0 +1,23 @@+package validate++import (+ "regexp"+ "strings"+)++var emailRegex = regexp.MustCompile("^(((([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+(\\.([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|\\.|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.)+(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.?$")++//Email validates given email address+func Email(email string) *Result {+ email = strings.ToLower(email)++ if len(email) > 200 {+ return Failed([]string{"E-mail address must be less than 200 characters."})+ }++ if !emailRegex.MatchString(email) {+ return Failed([]string{"E-mail address is invalid."})+ }++ return Success()+}diff --git a/app/pkg/validate/email_test.go b/app/pkg/validate/email_test.gonew file mode 100644index 000000000..f9d8398ae--- /dev/null+++ b/app/pkg/validate/email_test.go@@ -0,0 +1,45 @@+package validate_test++import (+ "testing"++ "github.com/getfider/fider/app/pkg/validate"+ . "github.com/onsi/gomega"+)++func TestInvalidEmail(t *testing.T) {+ RegisterTestingT(t)++ for _, email := range []string{+ "hello",+ "",+ "my@company",+ "my @company.com",+ "[email protected]",+ "my+company.com",+ "[email protected]",+ "my@[email protected]",+ "@gmail.com",+ "abc12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890@gmail.com",+ } {+ result := validate.Email(email)+ Expect(result.Ok).To(BeFalse())+ Expect(len(result.Messages) > 0).To(BeTrue())+ Expect(result.Error).To(BeNil())+ }+}++func TestValidEmail(t *testing.T) {+ RegisterTestingT(t)++ for _, email := range []string{+ "[email protected]",+ "[email protected]",+ "[email protected]",+ } {+ result := validate.Email(email)+ Expect(result.Ok).To(BeTrue())+ Expect(len(result.Messages)).To(Equal(0))+ Expect(result.Error).To(BeNil())+ }+}diff --git a/app/pkg/web/context.go b/app/pkg/web/context.goindex 9585c40d4..d60235297 100644--- a/app/pkg/web/context.go+++ b/app/pkg/web/context.go@@ -13,6 +13,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/jwt""github.com/getfider/fider/app/pkg/validate""github.com/labstack/echo")@@ -20,6 +21,9 @@ import (// Map defines a generic map of type `map[string]interface{}`.type Map map[string]interface{}+// CookieAuthName is the name of the authentication cookie+const CookieAuthName = "auth"+var (preffixKey = "__CTX_"tenantContextKey = preffixKey + "TENANT"@@ -50,12 +54,13 @@ func (ctx *Context) SetTenant(tenant *models.Tenant) {} else {ctx.Logger().Debug("Current tenant: nil")}+ ctx.Services().Tenants.SetCurrentTenant(tenant)ctx.Set(tenantContextKey, tenant)}//BindTo context values into given modelfunc (ctx *Context) BindTo(i actions.Actionable) *validate.Result {- err := ctx.Bind(i.NewModel())+ err := ctx.Bind(i.Initialize())if err != nil {return validate.Error(err)}@@ -162,6 +167,33 @@ func (ctx *Context) Services() *app.Services {return ctx.Get(servicesContextKey).(*app.Services)}+//AddAuthCookie generates and adds a cookie+func (ctx *Context) AddAuthCookie(user *models.User) error {+ token, err := jwt.Encode(models.FiderClaims{+ UserID: user.ID,+ UserName: user.Name,+ UserEmail: user.Email,+ })++ if err != nil {+ return err+ }++ ctx.AddCookie(CookieAuthName, token, time.Now().Add(365*24*time.Hour))+ return nil+}++//AddCookie adds a cookie+func (ctx *Context) AddCookie(name, value string, expires time.Time) {+ ctx.SetCookie(&http.Cookie{+ Name: name,+ Value: value,+ HttpOnly: true,+ Path: "/",+ Expires: expires,+ })+}+//RemoveCookie removes a cookiefunc (ctx *Context) RemoveCookie(name string) {ctx.SetCookie(&http.Cookie{diff --git a/app/services.go b/app/services.goindex 8ecb3899e..1db386483 100644--- a/app/services.go+++ b/app/services.go@@ -1,6 +1,7 @@package appimport (+ "github.com/getfider/fider/app/pkg/email""github.com/getfider/fider/app/pkg/oauth""github.com/getfider/fider/app/storage")@@ -11,4 +12,5 @@ type Services struct {Users storage.UserTenants storage.TenantIdeas storage.Idea+ Emailer email.Sender}diff --git a/app/storage/idea.go b/app/storage/idea.godeleted file mode 100644index 647e23ce5..000000000--- a/app/storage/idea.go+++ /dev/null@@ -1,18 +0,0 @@-package storage--import "github.com/getfider/fider/app/models"--// Idea contains read and write operations for ideas-type Idea interface {- GetByID(ideaID int) (*models.Idea, error)- GetByNumber(number int) (*models.Idea, error)- GetCommentsByIdea(number int) ([]*models.Comment, error)- GetAll() ([]*models.Idea, error)- Add(title, description string, userID int) (*models.Idea, error)- Update(number int, title, description string) (*models.Idea, error)- AddComment(number int, content string, userID int) (int, error)- AddSupporter(number, userID int) error- RemoveSupporter(number, userID int) error- SetResponse(number int, text string, userID, status int) error- SupportedBy(userID int) ([]int, error)-}diff --git a/app/storage/identity.go b/app/storage/identity.godeleted file mode 100644index 4ff99fa5e..000000000--- a/app/storage/identity.go+++ /dev/null@@ -1,21 +0,0 @@-package storage--import "github.com/getfider/fider/app/models"--// User is used for user operations-type User interface {- GetByID(userID int) (*models.User, error)- GetByEmail(tenantID int, email string) (*models.User, error)- GetByProvider(tenantID int, provider string, uid string) (*models.User, error)- Register(user *models.User) error- RegisterProvider(userID int, provider *models.UserProvider) error-}--// Tenant contains read and write operations for tenants-type Tenant interface {- Add(name string, subdomain string) (*models.Tenant, error)- First() (*models.Tenant, error)- GetByDomain(domain string) (*models.Tenant, error)- UpdateSettings(tenantID int, settings *models.UpdateTenantSettings) error- IsSubdomainAvailable(subdomain string) (bool, error)-}diff --git a/app/storage/inmemory/tenant.go b/app/storage/inmemory/tenant.goindex 88da64a2f..fb08b6037 100644--- a/app/storage/inmemory/tenant.go+++ b/app/storage/inmemory/tenant.go@@ -2,6 +2,7 @@ package inmemoryimport ("strings"+ "time""github.com/getfider/fider/app""github.com/getfider/fider/app/models"@@ -9,8 +10,15 @@ import (// TenantStorage contains read and write operations for tenantstype TenantStorage struct {- lastID int- tenants []*models.Tenant+ lastID int+ tenants []*models.Tenant+ current *models.Tenant+ requests []*models.SignInRequest+}++// SetCurrentTenant tenant+func (s *TenantStorage) SetCurrentTenant(tenant *models.Tenant) {+ s.current = tenant}// Add given tenant to tenant list@@ -52,9 +60,9 @@ func (s *TenantStorage) IsSubdomainAvailable(subdomain string) (bool, error) {}// UpdateSettings of given tenant-func (s *TenantStorage) UpdateSettings(tenantID int, settings *models.UpdateTenantSettings) error {+func (s *TenantStorage) UpdateSettings(settings *models.UpdateTenantSettings) error {for _, tenant := range s.tenants {- if tenant.ID == tenantID {+ if tenant.ID == s.current.ID {tenant.Invitation = settings.Invitationtenant.WelcomeMessage = settings.WelcomeMessagetenant.Name = settings.Title@@ -64,6 +72,38 @@ func (s *TenantStorage) UpdateSettings(tenantID int, settings *models.UpdateTenareturn nil}+// SaveVerificationKey used by e-mail verification+func (s *TenantStorage) SaveVerificationKey(email, key string) error {+ s.requests = append(s.requests, &models.SignInRequest{+ Email: email,+ Key: key,+ CreatedOn: time.Now(),+ VerifiedOn: nil,+ })+ return nil+}++// FindVerificationByKey based on current tenant+func (s *TenantStorage) FindVerificationByKey(key string) (*models.SignInRequest, error) {+ for _, request := range s.requests {+ if request.Key == key {+ return request, nil+ }+ }+ return nil, app.ErrNotFound+}++// SetKeyAsVerified so that it cannot be used anymore+func (s *TenantStorage) SetKeyAsVerified(key string) error {+ for _, request := range s.requests {+ if request.Key == key {+ now := time.Now()+ request.VerifiedOn = &now+ }+ }+ return nil+}+func extractSubdomain(domain string) string {if idx := strings.Index(domain, "."); idx != -1 {return domain[:idx]diff --git a/app/storage/postgres/tenant.go b/app/storage/postgres/tenant.goindex f1c341ded..c44e38e79 100644--- a/app/storage/postgres/tenant.go+++ b/app/storage/postgres/tenant.go@@ -13,7 +13,8 @@ import (// TenantStorage contains read and write operations for tenantstype TenantStorage struct {- trx *dbx.Trx+ trx *dbx.Trx+ current *models.Tenant}// NewTenantStorage creates a new TenantStorage@@ -41,6 +42,34 @@ func (t *dbTenant) toModel() *models.Tenant {}}+type dbSignInRequest struct {+ ID int `db:"id"`+ Email string `db:"email"`+ Key string `db:"key"`+ CreatedOn time.Time `db:"created_on"`+ VerifiedOn dbx.NullTime `db:"verified_on"`+}++func (t *dbSignInRequest) toModel() *models.SignInRequest {+ model := &models.SignInRequest{+ Email: t.Email,+ Key: t.Key,+ CreatedOn: t.CreatedOn,+ VerifiedOn: nil,+ }++ if t.VerifiedOn.Valid {+ model.VerifiedOn = &t.VerifiedOn.Time+ }++ return model+}++// SetCurrentTenant tenant+func (s *TenantStorage) SetCurrentTenant(tenant *models.Tenant) {+ s.current = tenant+}+// Add given tenant to tenant listfunc (s *TenantStorage) Add(name string, subdomain string) (*models.Tenant, error) {var id int@@ -83,9 +112,9 @@ func (s *TenantStorage) GetByDomain(domain string) (*models.Tenant, error) {}// UpdateSettings of given tenant-func (s *TenantStorage) UpdateSettings(tenantID int, settings *models.UpdateTenantSettings) error {+func (s *TenantStorage) UpdateSettings(settings *models.UpdateTenantSettings) error {query := "UPDATE tenants SET name = $1, invitation = $2, welcome_message = $3 WHERE id = $4"- return s.trx.Execute(query, settings.Title, settings.Invitation, settings.WelcomeMessage, tenantID)+ return s.trx.Execute(query, settings.Title, settings.Invitation, settings.WelcomeMessage, s.current.ID)}// IsSubdomainAvailable returns true if subdomain is available to use@@ -94,6 +123,32 @@ func (s *TenantStorage) IsSubdomainAvailable(subdomain string) (bool, error) {return !exists, err}+// SaveVerificationKey used by e-mail verification process+func (s *TenantStorage) SaveVerificationKey(email, key string) error {+ query := "INSERT INTO signin_requests (tenant_id, email, created_on, key) VALUES ($1, $2, $3, $4)"+ return s.trx.Execute(query, s.current.ID, email, time.Now(), key)+}++// FindVerificationByKey based on current tenant+func (s *TenantStorage) FindVerificationByKey(key string) (*models.SignInRequest, error) {+ request := dbSignInRequest{}++ err := s.trx.Get(&request, "SELECT id, email, key, created_on, verified_on FROM signin_requests WHERE key = $1 LIMIT 1", key)+ if err == sql.ErrNoRows {+ return nil, app.ErrNotFound+ } else if err != nil {+ return nil, err+ }++ return request.toModel(), nil+}++// SetKeyAsVerified so that it cannot be used anymore+func (s *TenantStorage) SetKeyAsVerified(key string) error {+ query := "UPDATE signin_requests SET verified_on = $1 WHERE tenant_id = $2 AND key = $3"+ return s.trx.Execute(query, time.Now(), s.current.ID, key)+}+func extractSubdomain(domain string) string {if idx := strings.Index(domain, "."); idx != -1 {return domain[:idx]diff --git a/app/storage/postgres/tenant_test.go b/app/storage/postgres/tenant_test.goindex e28a6abdf..a1a03d09b 100644--- a/app/storage/postgres/tenant_test.go+++ b/app/storage/postgres/tenant_test.go@@ -2,6 +2,7 @@ package postgres_testimport ("testing"+ "time""github.com/getfider/fider/app/models"@@ -126,13 +127,14 @@ func TestTenantStorage_UpdateSettings(t *testing.T) {tenants := postgres.NewTenantStorage(trx)tenant, _ := tenants.GetByDomain("demo")+ tenants.SetCurrentTenant(tenant)settings := &models.UpdateTenantSettings{Title: "New Demonstration",Invitation: "Leave us your suggestion",WelcomeMessage: "Welcome!",}- err := tenants.UpdateSettings(tenant.ID, settings)+ err := tenants.UpdateSettings(settings)Expect(err).To(BeNil())tenant, err = tenants.GetByDomain("demo")@@ -142,3 +144,60 @@ func TestTenantStorage_UpdateSettings(t *testing.T) {Expect(tenant.Invitation).To(Equal("Leave us your suggestion"))Expect(tenant.WelcomeMessage).To(Equal("Welcome!"))}++func TestTenantStorage_SaveFindSet_VerificationKey(t *testing.T) {+ RegisterTestingT(t)+ db, _ := dbx.New()+ db.Seed()+ defer db.Close()++ trx, _ := db.Begin()+ defer trx.Rollback()++ tenants := postgres.NewTenantStorage(trx)+ tenant, _ := tenants.GetByDomain("demo")+ tenants.SetCurrentTenant(tenant)++ //Save new Key+ err := tenants.SaveVerificationKey("[email protected]", "s3cr3tk3y")+ Expect(err).To(BeNil())++ //Find and check values+ result, err := tenants.FindVerificationByKey("s3cr3tk3y")+ Expect(err).To(BeNil())+ Expect(time.Now().After(result.CreatedOn)).To(BeTrue())+ Expect(result.VerifiedOn).To(BeNil())+ Expect(result.Email).To(Equal("[email protected]"))+ Expect(result.Key).To(Equal("s3cr3tk3y"))++ //Set as verified check values+ err = tenants.SetKeyAsVerified("s3cr3tk3y")+ Expect(err).To(BeNil())++ //Find and check that VerifiedOn is now set+ result, err = tenants.FindVerificationByKey("s3cr3tk3y")+ Expect(err).To(BeNil())+ Expect(time.Now().After(result.CreatedOn)).To(BeTrue())+ Expect(result.VerifiedOn.After(result.CreatedOn)).To(BeTrue())+ Expect(result.Email).To(Equal("[email protected]"))+ Expect(result.Key).To(Equal("s3cr3tk3y"))+}++func TestTenantStorage_FindUnknownVerificationKey(t *testing.T) {+ RegisterTestingT(t)+ db, _ := dbx.New()+ db.Seed()+ defer db.Close()++ trx, _ := db.Begin()+ defer trx.Rollback()++ tenants := postgres.NewTenantStorage(trx)+ tenant, _ := tenants.GetByDomain("demo")+ tenants.SetCurrentTenant(tenant)++ //Find and check values+ result, err := tenants.FindVerificationByKey("blahblahblah")+ Expect(err).To(Equal(app.ErrNotFound))+ Expect(result).To(BeNil())+}diff --git a/app/storage/storage.go b/app/storage/storage.gonew file mode 100644index 000000000..3188926a2--- /dev/null+++ b/app/storage/storage.go@@ -0,0 +1,40 @@+package storage++import "github.com/getfider/fider/app/models"++// Idea contains read and write operations for ideas+type Idea interface {+ GetByID(ideaID int) (*models.Idea, error)+ GetByNumber(number int) (*models.Idea, error)+ GetCommentsByIdea(number int) ([]*models.Comment, error)+ GetAll() ([]*models.Idea, error)+ Add(title, description string, userID int) (*models.Idea, error)+ Update(number int, title, description string) (*models.Idea, error)+ AddComment(number int, content string, userID int) (int, error)+ AddSupporter(number, userID int) error+ RemoveSupporter(number, userID int) error+ SetResponse(number int, text string, userID, status int) error+ SupportedBy(userID int) ([]int, error)+}++// User is used for user operations+type User interface {+ GetByID(userID int) (*models.User, error)+ GetByEmail(tenantID int, email string) (*models.User, error)+ GetByProvider(tenantID int, provider string, uid string) (*models.User, error)+ Register(user *models.User) error+ RegisterProvider(userID int, provider *models.UserProvider) error+}++// Tenant contains read and write operations for tenants+type Tenant interface {+ Add(name string, subdomain string) (*models.Tenant, error)+ First() (*models.Tenant, error)+ GetByDomain(domain string) (*models.Tenant, error)+ UpdateSettings(settings *models.UpdateTenantSettings) error+ IsSubdomainAvailable(subdomain string) (bool, error)+ SaveVerificationKey(email, key string) error+ FindVerificationByKey(key string) (*models.SignInRequest, error)+ SetKeyAsVerified(key string) error+ SetCurrentTenant(*models.Tenant)+}diff --git a/migrations/201709081837_create_email_verifications.up.sql b/migrations/201709081837_create_email_verifications.up.sqlnew file mode 100644index 000000000..7e878e2d3--- /dev/null+++ b/migrations/201709081837_create_email_verifications.up.sql@@ -0,0 +1,9 @@+create table if not exists email_verifications (+ id serial primary key,+ tenant_id int not null,+ email varchar(200) not null,+ created_on timestamptz not null,+ key varchar(32) not null,+ verified_on timestamptz null,+ foreign key (tenant_id) references tenants(id)+);\ No newline at end of filediff --git a/migrations/201709091228_create_email_verification_key_index.up.sql b/migrations/201709091228_create_email_verification_key_index.up.sqlnew file mode 100644index 000000000..437bbc01d--- /dev/null+++ b/migrations/201709091228_create_email_verification_key_index.up.sql@@ -0,0 +1 @@+CREATE UNIQUE INDEX email_verification_key_idx ON email_verifications (tenant_id, key);\ No newline at end of filediff --git a/migrations/201709141944_rename_email_verification.up.sql b/migrations/201709141944_rename_email_verification.up.sqlnew file mode 100644index 000000000..4af114445--- /dev/null+++ b/migrations/201709141944_rename_email_verification.up.sql@@ -0,0 +1,3 @@+ALTER TABLE email_verifications RENAME TO signin_requests;+ALTER INDEX email_verifications_pkey RENAME TO signin_requests_pkey;+ALTER INDEX email_verification_key_idx RENAME TO signin_requests_key_idx;\ No newline at end of filediff --git a/public/assets/styles/main.scss b/public/assets/styles/main.scssindex 949e24d78..9c3938a98 100644--- a/public/assets/styles/main.scss+++ b/public/assets/styles/main.scss@@ -217,6 +217,7 @@ code {}.ui.basic.red.label {+ width: 100%;color: #ef7878 !important;border-color: #ef7878 !important;@@ -227,11 +228,14 @@ code {}}-.login-message {+.signin-message {background-color: $menu-color;+ .ui.basic.red.label {+ background-color: $menu-color !important;+ }}-.login-options{+.signin-options{.ui.stackable.grid>.column:not(.row),.column {padding: 10px 5px !important;@@ -242,7 +246,8 @@ code {}}-#login-modal {+#signin-modal,+#signin-complete-modal {text-align: center;@media only screen and (max-width: 767px) {diff --git a/public/components/CommentInput.tsx b/public/components/CommentInput.tsxindex 5f169af30..3afdaaec2 100644--- a/public/components/CommentInput.tsx+++ b/public/components/CommentInput.tsx@@ -1,11 +1,13 @@import * as React from 'react';+import * as ReactDOM from 'react-dom';import Textarea from 'react-textarea-autosize';import { Idea, User } from '@fider/models';-import { Gravatar, UserName, Button, DisplayError, LogInControl } from '@fider/components/common';+import { Gravatar, UserName, Button, DisplayError, SignInControl } from '@fider/components/common';import { inject, injectables } from '@fider/di';import { Session, IdeaService, Failure } from '@fider/services';+import { showSignIn } from '@fider/utils/page';interface CommentInputProps {idea: Idea;@@ -17,6 +19,7 @@ interface CommentInputState {}export class CommentInput extends React.Component<CommentInputProps, CommentInputState> {+ private input: HTMLTextAreaElement;@inject(injectables.Session)public session: Session;@@ -35,6 +38,13 @@ export class CommentInput extends React.Component<CommentInputProps, CommentInpu};}+ private onTextFocused() {+ if (!this.user) {+ this.input.blur();+ showSignIn();+ }+ }+public async submit() {this.setState({error: undefined@@ -53,17 +63,6 @@ export class CommentInput extends React.Component<CommentInputProps, CommentInpupublic render() {const user = this.session.getCurrentUser();- const button = user- ? <Button className="primary" onClick={ () => this.submit() }>- Submit- </Button>- : <div className="ui message login-message">- <div className="header">- Log in to raise your voice.- </div>- <LogInControl />- </div>;-return <div className={`comment-input ${user && 'authenticated' }`}><Gravatar name={ this.user.name } hash={ this.user.gravatar }/><div className="ui form">@@ -71,10 +70,16 @@ export class CommentInput extends React.Component<CommentInputProps, CommentInpu<DisplayError error={this.state.error} /><div className="field"><Textarea onChange={(e) => { this.setState({ content: e.currentTarget.value }); }}+ onFocus={() => this.onTextFocused()}+ inputRef={(e) => this.input = e!}rows={1}placeholder="Write a comment..."/></div>- { this.state.content && button }+ { this.state.content &&+ <Button className="primary" onClick={ () => this.submit() }>+ Submit+ </Button>+ }</div></div>;}diff --git a/public/components/IdeaInput.tsx b/public/components/IdeaInput.tsxindex d01b9380a..1443600d0 100644--- a/public/components/IdeaInput.tsx+++ b/public/components/IdeaInput.tsx@@ -1,9 +1,11 @@import * as React from 'react';import Textarea from 'react-textarea-autosize';-import { DisplayError, Button, Form, LogInControl } from '@fider/components/common';+import { DisplayError, Button, Form } from '@fider/components/common';import { inject, injectables } from '@fider/di';import { Session, IdeaService, Failure } from '@fider/services';+import { User } from '@fider/models';+import { showSignIn } from '@fider/utils/page';interface IdeaInputProps {placeholder: string;@@ -18,31 +20,42 @@ interface IdeaInputState {export class IdeaInput extends React.Component<IdeaInputProps, IdeaInputState> {private title: HTMLInputElement;private form: Form;+ private user: User;@inject(injectables.Session)- public session: Session;+ private session: Session;@inject(injectables.IdeaService)- public service: IdeaService;+ private service: IdeaService;constructor() {- super();- this.state = {- title: '',- description: '',- focused: false- };+ super();+ this.user = this.session.getCurrentUser();+ this.state = {+ title: '',+ description: '',+ focused: false+ };}public componentDidMount() {- this.title.focus();+ if (this.user) {+ this.title.focus();+ }}- public async submit() {+ private onTitleFocused() {+ if (!this.user) {+ this.title.blur();+ showSignIn();+ }+ }++ private async submit() {if (this.state.title) {- this.form.clearFailure();const result = await this.service.addIdea(this.state.title, this.state.description);if (result.ok) {+ this.form.clearFailure();location.href = `/ideas/${result.data.number}/${result.data.slug}`;} else if (result.error) {this.form.setFailure(result.error);@@ -50,45 +63,26 @@ export class IdeaInput extends React.Component<IdeaInputProps, IdeaInputState> {}}- public titleChanged(title: string) {- this.setState({ title });- }-- public titleFocused() {- this.setState({ focused: true });- }-- public titleUnfocused() {- this.setState({ focused: false });- }-public render() {- const user = this.session.getCurrentUser();- const buttonCss = this.state.title === '' ? 'primary disabled' : 'primary';- const details = user ?- <div>- <div className="field">- <Textarea onChange={(e) => this.setState({ description: e.currentTarget.value })} placeholder="Describe your idea" />- </div>- <Button className={buttonCss} onClick={() => this.form.submit() }>- Submit- </Button>- </div> :- <div className="ui message login-message">- <div className="header">- Log in to raise your voice.- </div>- <LogInControl />- </div>;+ const buttonCss = this.state.title === '' ? 'primary disabled' : 'primary';+ const details = <div>+ <div className="field">+ <Textarea onChange={(e) => this.setState({ description: e.currentTarget.value })} placeholder="Describe your idea" />+ </div>+ <Button className={buttonCss} onClick={() => this.form.submit() }>+ Submit+ </Button>+ </div>;- return <Form ref={(f) => { this.form = f!; } } onSubmit={() => this.submit()}>- <input id="new-idea-input"- type="text"- ref={(e) => this.title = e! }- maxLength={100}- onKeyUp={(e) => { this.setState({ title: e.currentTarget.value }); }}- placeholder={this.props.placeholder} />- { this.state.title && details }- </Form>;+ return <Form ref={(f) => { this.form = f!; } } onSubmit={() => this.submit()}>+ <input id="new-idea-input"+ type="text"+ ref={(e) => this.title = e! }+ onFocus={() => this.onTitleFocused()}+ maxLength={100}+ onKeyUp={(e) => { this.setState({ title: e.currentTarget.value }); }}+ placeholder={this.props.placeholder} />+ { this.state.title && details }+ </Form>;}}diff --git a/public/components/LogInModal.tsx b/public/components/LogInModal.tsxdeleted file mode 100644index 726d6349a..000000000--- a/public/components/LogInModal.tsx+++ /dev/null@@ -1,15 +0,0 @@-import * as React from 'react';-import { LogInControl } from '@fider/components/common';--export class LogInModal extends React.Component<{}, {}> {- public render() {- return <div id="login-modal" className="ui modal small">- <div className="header">- Log in to raise your voice.- </div>- <div className="content">- <LogInControl />- </div>- </div>;- }-}diff --git a/public/components/SignInModal.tsx b/public/components/SignInModal.tsxnew file mode 100644index 000000000..4c79d2932--- /dev/null+++ b/public/components/SignInModal.tsx@@ -0,0 +1,15 @@+import * as React from 'react';+import { SignInControl } from '@fider/components/common';++export class SignInModal extends React.Component<{}, {}> {+ public render() {+ return <div id="signin-modal" className="ui modal small">+ <div className="header">+ Sign in to raise your voice+ </div>+ <div className="content">+ <SignInControl signInByEmail={ true } />+ </div>+ </div>;+ }+}diff --git a/public/components/SupportCounter.tsx b/public/components/SupportCounter.tsxindex fe3fd379b..1a44ab472 100644--- a/public/components/SupportCounter.tsx+++ b/public/components/SupportCounter.tsx@@ -1,9 +1,10 @@import * as React from 'react';import { Idea, User, IdeaStatus } from '@fider/models';-import { LogInControl } from '@fider/components/common';+import { SignInControl } from '@fider/components/common';import { inject, injectables } from '@fider/di';import { Session, IdeaService } from '@fider/services';+import { showSignIn } from '@fider/utils/page';interface SupportCounterProps {user: User;@@ -34,9 +35,7 @@ export class SupportCounter extends React.Component<SupportCounterProps, Supportpublic async supportOrUndo() {if (!this.props.user) {- $('#login-modal').modal({- blurring: true- }).modal('show');+ showSignIn();return;}diff --git a/public/components/common/Form.tsx b/public/components/common/Form.tsxindex 3eb2e0e94..da26d5e84 100644--- a/public/components/common/Form.tsx+++ b/public/components/common/Form.tsx@@ -3,38 +3,39 @@ import { Failure } from '@fider/services';import { DisplayError } from './';interface FormProps {- onSubmit: () => Promise<any>;+ onSubmit: () => Promise<any>;}interface FormState {- failure?: Failure;+ failure?: Failure;}export class Form extends React.Component<FormProps, FormState> {-- public constructor(props: FormProps) {- super(props);- }-- public async submit() {- if (this.props.onSubmit) {- await this.props.onSubmit();- }- }-- public async clearFailure() {- this.setState({ failure: undefined });+ public constructor(props: FormProps) {+ super(props);+ }++ public async submit(e?: React.FormEvent<HTMLFormElement>) {+ if (e) {+ e.preventDefault();+ if (this.props.onSubmit) {+ await this.props.onSubmit();+ }}-- public async setFailure(failure: Failure) {- this.setState({ failure });- }-- public render() {- return <div className="ui form">- <DisplayError error={this.state && this.state.failure} />- { this.props.children }- </div>;- }-+ }++ public async clearFailure() {+ this.setState({ failure: undefined });+ }++ public async setFailure(failure: Failure) {+ this.setState({ failure });+ }++ public render() {+ return <form className="ui form" onSubmit={(e) => this.submit(e)}>+ <DisplayError error={this.state && this.state.failure} />+ { this.props.children }+ </form>;+ }}diff --git a/public/components/common/Gravatar.tsx b/public/components/common/Gravatar.tsxindex e8b7af7d9..82b41f077 100644--- a/public/components/common/Gravatar.tsx+++ b/public/components/common/Gravatar.tsx@@ -9,7 +9,7 @@ interface GravatarProps {}export const Gravatar = (props: GravatarProps) => {- const fallback = `${getBaseUrl()}/avatars/50/${props.name}`;+ const fallback = `${getBaseUrl()}/assets/avatars/50/${props.name}`;const hash = props.email ? md5(props.email) : props.hash || '';let element: any;diff --git a/public/components/common/Header.tsx b/public/components/common/Header.tsxindex 4aa05cca7..cc95c58e8 100644--- a/public/components/common/Header.tsx+++ b/public/components/common/Header.tsx@@ -1,9 +1,10 @@import * as React from 'react';import { User, Tenant } from '@fider/models';-import { LogInControl, EnvironmentInfo, Gravatar } from '@fider/components/common';+import { SignInControl, EnvironmentInfo, Gravatar } from '@fider/components/common';import { inject, injectables } from '@fider/di';import { Session } from '@fider/services/Session';+import { showSignIn } from '@fider/utils/page';export class Header extends React.Component<{}, {}> {private dropdown: HTMLElement;@@ -15,65 +16,63 @@ export class Header extends React.Component<{}, {}> {public session: Session;constructor(props: {}) {- super(props);+ super(props);- this.user = this.session.getCurrentUser();- this.tenant = this.session.get<Tenant>('tenant');+ this.user = this.session.getCurrentUser();+ this.tenant = this.session.get<Tenant>('tenant');}public componentDidMount() {- if (this.user) {- $(this.dropdown).popup({- inline: true,- hoverable: true,- popup: this.list,- position : 'bottom right'- });- }+ if (this.user) {+ $(this.dropdown).popup({+ inline: true,+ hoverable: true,+ popup: this.list,+ position : 'bottom right'+ });+ }}- private showModal() {- if (!this.user) {- $('#login-modal').modal({- blurring: true- }).modal('show');- }+ private showModal() {+ if (!this.user) {+ showSignIn();}+ }- public render() {- const items = <div className="ui divided list">- {- this.session.isStaff() &&- <div className="item">- <a href="/admin">- Administration- </a>- </div>- }- <div className="item">- <a className="signout" href="/logout?redirect=/">- Log out- </a>- </div>- </div>;-- return <div>- <EnvironmentInfo />- <div id="menu" className="ui small menu no-border">- <div className="ui container">- <a href="/" className="header item">- { this.tenant.name }- </a>- <a ref={(e) => { this.dropdown = e!; } } onClick={ () => this.showModal() } className={`item login right ${!this.user.name && 'subtitle' }`}>- <Gravatar name={this.user.name} hash={this.user.gravatar} />- { this.user.name || 'Log in' }- { this.user.name && <i className="dropdown icon"></i> }+ public render() {+ const items = <div className="ui divided list">+ {+ this.session.isStaff() &&+ <div className="item">+ <a href="/admin">+ Administration</a>+ </div>+ }+ <div className="item">+ <a className="signout" href="/signout?redirect=/">+ Sign out+ </a></div>+ </div>;++ return <div>+ <EnvironmentInfo />+ <div id="menu" className="ui small menu no-border">+ <div className="ui container">+ <a href="/" className="header item">+ { this.tenant.name }+ </a>+ <a ref={(e) => { this.dropdown = e!; } } onClick={ () => this.showModal() } className={`item signin right ${!this.user.name && 'subtitle' }`}>+ <Gravatar name={this.user.name} hash={this.user.gravatar} />+ { this.user.name || 'Sign in' }+ { this.user.name && <i className="dropdown icon"></i> }+ </a></div>- <div ref={(e) => { this.list = e!; } } className="fdr-profile-popup ui popup transition hidden">- { items }- </div>- </div>;+ </div>+ <div ref={(e) => { this.list = e!; } } className="fdr-profile-popup ui popup transition hidden">+ { items }+ </div>+ </div>;}}diff --git a/public/components/common/LogInControl.tsx b/public/components/common/LogInControl.tsxdeleted file mode 100644index f0cb81033..000000000--- a/public/components/common/LogInControl.tsx+++ /dev/null@@ -1,45 +0,0 @@-import * as React from 'react';-import { SocialLogInButton } from '@fider/components/common';-import { inject, injectables } from '@fider/di';-import { Session } from '@fider/services/Session';-import { AuthSettings } from '@fider/models';--export class LogInControl extends React.Component<{}, {}> {-- @inject(injectables.Session)- public session: Session;-- public render() {- const settings = this.session.get<AuthSettings>('auth');-- const google = settings.providers.google &&- <div className="column">- <SocialLogInButton provider="google" />- </div>;- const facebook = settings.providers.facebook &&- <div className="column">- <SocialLogInButton provider="facebook" />- </div>;- const github = settings.providers.github &&- <div className="column">- <SocialLogInButton provider="github" />- </div>;-- return <div className="login-options">- <p className="info">We'll never post to any of your accounts.</p>- <div className="ui stackable three column centered grid">- { facebook }- { google }- { github }- </div>- </div>;- }-}--/*-<div className="ui horizontal divider">OR</div>-<div className="ui small action fluid input">- <input type="text" placeholder="Log in with e-mail" className="small" />- <button className="ui small disabled primary button">Log in</button>-</div>-*/diff --git a/public/components/common/SignInControl.tsx b/public/components/common/SignInControl.tsxnew file mode 100644index 000000000..f3567ea83--- /dev/null+++ b/public/components/common/SignInControl.tsx@@ -0,0 +1,94 @@+import * as React from 'react';+import { SocialSignInButton, Form } from '@fider/components/common';+import { inject, injectables } from '@fider/di';+import { Session } from '@fider/services/Session';+import { AuthSettings } from '@fider/models';+import { TenantService } from '@fider/services';+import { hideSignIn } from '@fider/utils/page';++interface SignInControlState {+ email: string;+ sent: boolean;+}++interface SignInControlProps {+ signInByEmail: boolean;+}++export class SignInControl extends React.Component<SignInControlProps, SignInControlState> {+ private form: Form;++ @inject(injectables.Session)+ public session: Session;++ @inject(injectables.TenantService)+ public service: TenantService;++ constructor(props: SignInControlProps) {+ super(props);++ this.state = {+ email: '',+ sent: false+ };+ }++ private async signIn() {+ const result = await this.service.signIn(this.state.email);+ if (result.ok) {+ this.form.clearFailure();+ this.setState({ sent: true });+ setTimeout(() => {+ this.setState({ sent: false });+ }, 10000);+ } else if (result.error) {+ this.form.setFailure(result.error);+ }+ }++ public render() {+ const settings = this.session.get<AuthSettings>('auth');++ if (this.state.sent) {+ return <div>+ <p>We sent a sign in link to <b>{ this.state.email }</b>. <br /> Please check your inbox.</p>+ <p><a href="#" onClick={() => hideSignIn()}>OK</a></p>+ </div>;+ }++ const google = settings.providers.google &&+ <div className="column">+ <SocialSignInButton provider="google" />+ </div>;+ const facebook = settings.providers.facebook &&+ <div className="column">+ <SocialSignInButton provider="facebook" />+ </div>;+ const github = settings.providers.github &&+ <div className="column">+ <SocialSignInButton provider="github" />+ </div>;++ return <div className="signin-options">+ <div className="ui stackable three column centered grid">+ { facebook }+ { google }+ { github }+ </div>+ <p className="info">We'll never post to any of your accounts</p>++ { this.props.signInByEmail && <div>+ <div className="ui horizontal divider">OR</div>+ <p>Enter your e-mail address to sign in</p>+ <Form ref={(f) => { this.form = f!; } } onSubmit={() => this.signIn() }>+ <div className="ui small action fluid input">+ <input onChange={(e) => this.setState({ email: e.currentTarget.value }) } type="text" placeholder="[email protected]" className="small" />+ <button onClick={ () => this.form.submit() } className={`ui small positive button ${this.state.email === '' && 'disabled'}`}>+ Sign in+ </button>+ </div>+ </Form>+ </div> }+ </div>;+ }+}diff --git a/public/components/common/SocialLogInButton.tsx b/public/components/common/SocialSignInButton.tsxsimilarity index 90%rename from public/components/common/SocialLogInButton.tsxrename to public/components/common/SocialSignInButton.tsxindex 051bd7cc1..b44dadebd 100644--- a/public/components/common/SocialLogInButton.tsx+++ b/public/components/common/SocialSignInButton.tsx@@ -5,7 +5,7 @@ import { Session } from '@fider/services/Session';import { Button } from '@fider/components/common';import { AuthSettings } from '@fider/models';-interface SocialLogInButtonProps {+interface SocialSignInButtonProps {provider: 'google' | 'facebook' | 'github';}@@ -27,7 +27,7 @@ const providers = {}};-export class SocialLogInButton extends React.Component<SocialLogInButtonProps, {}> {+export class SocialSignInButton extends React.Component<SocialSignInButtonProps, {}> {@inject(injectables.Session)public session: Session;diff --git a/public/components/common/index.tsx b/public/components/common/index.tsxindex c4d6a2e6e..d20e061a7 100644--- a/public/components/common/index.tsx+++ b/public/components/common/index.tsx@@ -6,7 +6,7 @@ export * from './EnvironmentInfo';export * from './Gravatar';export * from './Footer';export * from './Header';-export * from './SocialLogInButton';-export * from './LogInControl';+export * from './SocialSignInButton';+export * from './SignInControl';export * from './Moment';export * from './UserName';diff --git a/public/index.tsx b/public/index.tsxindex cb8966414..da12f5bb4 100644--- a/public/index.tsx+++ b/public/index.tsx@@ -1,10 +1,11 @@import * as React from 'react';import * as ReactDOM from 'react-dom';-import { LogInModal } from '@fider/components/LogInModal';+import { SignInModal } from '@fider/components/SignInModal';import { AdminHomePage } from '@fider/pages/admin/AdminHomePage';import { SiteHomePage } from '@fider/pages/site/SiteHomePage';import { ShowIdeaPage } from '@fider/pages/site/ShowIdeaPage';+import { CompleteSignInProfile } from '@fider/pages/site/CompleteSignInProfile';import { SignUpPage } from '@fider/pages/signup/SignUpPage';import { container, injectables } from '@fider/di';import {@@ -33,6 +34,7 @@ const pathRegex = [{ regex: new RegExp('^\/admin$'), component: <AdminHomePage />, id: 'fdr-admin-page' },{ regex: new RegExp('^\/signup$'), component: <SignUpPage />, id: 'fdr-signup-page' },{ regex: new RegExp('^\/ideas\/\\d+.*$'), component: <ShowIdeaPage />, id: 'fdr-show-idea-page' },+ { regex: new RegExp('^\/signin\/verify'), component: <CompleteSignInProfile />, id: 'fdr-complete-signin-profile' },];const resolveRootComponent = (path: string): PageConfiguration | undefined => {@@ -46,9 +48,11 @@ const resolveRootComponent = (path: string): PageConfiguration | undefined => {document.addEventListener('DOMContentLoaded', () => {const config = resolveRootComponent(location.pathname)!;ReactDOM.render(- <div id={ config.id }>- <LogInModal />- { config.component }+ <div>+ <SignInModal />+ <div id={ config.id }>+ { config.component }+ </div></div>, document.getElementById('root'));});diff --git a/public/pages/signup/SignUpPage.scss b/public/pages/signup/SignUpPage.scssindex 793dbd79b..5d77d6a6f 100644--- a/public/pages/signup/SignUpPage.scss+++ b/public/pages/signup/SignUpPage.scss@@ -2,7 +2,6 @@.page {margin-top: 50px;max-width: 500px !important;- text-align: center;}.fdr-avatar {@@ -13,14 +12,7 @@height: 100px;}- .login-options {- width: 400px;- margin: 0 auto;- }-- .ui.form {- .ui.input, .field > input {- width: 300px;- }+ input#name {+ width: 310px;}}\ No newline at end of filediff --git a/public/pages/signup/SignUpPage.tsx b/public/pages/signup/SignUpPage.tsxindex 8b8333889..7a811ae02 100644--- a/public/pages/signup/SignUpPage.tsx+++ b/public/pages/signup/SignUpPage.tsx@@ -1,6 +1,6 @@import * as React from 'react';-import { LogInControl, Footer, Button, EnvironmentInfo, Gravatar, DisplayError } from '@fider/components/common';+import { SignInControl, 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';@@ -109,7 +109,7 @@ export class SignUpPage extends React.Component<{}, SignUpPageState> {</div> :<div><p>We need to identify you in order to setup your new Fider instance.</p>- <LogInControl />+ <SignInControl signInByEmail={ false } /></div>}@@ -153,7 +153,6 @@ export class SignUpPage extends React.Component<{}, SignUpPageState> {<p>Make sure information provided above is correct before proceeding.</p>-<Button className="positive" size="large" onClick={() => this.confirm()}>Confirm</Button></div><Footer />diff --git a/public/pages/site/CompleteSignInProfile.tsx b/public/pages/site/CompleteSignInProfile.tsxnew file mode 100644index 000000000..f039a6ffb--- /dev/null+++ b/public/pages/site/CompleteSignInProfile.tsx@@ -0,0 +1,65 @@+import * as React from 'react';++import { SiteHomePage } from './SiteHomePage';+import { showModal, getQueryString } from '@fider/utils/page';+import { Form } from '@fider/components/common';++import { inject, injectables } from '@fider/di';+import { TenantService } from '@fider/services';++interface CompleteSignInProfileState {+ name: string;+}++export class CompleteSignInProfile extends React.Component<{}, CompleteSignInProfileState> {+ private form: Form;++ @inject(injectables.TenantService)+ public service: TenantService;++ constructor(props: {}) {+ super(props);+ this.state = {+ name: '',+ };+ }++ public componentDidMount() {+ showModal('#signin-complete-modal', { closable: false });+ }++ private async submit() {+ const key = getQueryString('k');+ const result = await this.service.completeProfile(key!, this.state.name);+ if (result.ok) {+ location.href = '/';+ } else if (result.error) {+ this.form.setFailure(result.error);+ }+ }++ public render() {+ const modal = <div id="signin-complete-modal" className="ui modal small">+ <div className="header">+ Complete your profile+ </div>+ <div className="content">+ <p>Because this is your first sign in, please input your display name.</p>+ <Form ref={(f) => { this.form = f!; } } onSubmit={() => this.submit() }>+ <div className="ui small action fluid input">+ <input onChange={(e) => this.setState({ name: e.currentTarget.value }) } type="text" placeholder="Your display name" className="small" />+ <button onClick={ () => this.form.submit() } className={`ui small positive button ${this.state.name === '' && 'disabled'}`}>+ Submit+ </button>+ </div>+ </Form>+ </div>+ </div>;++ // TODO: remove this duplicated id, should use from index.tsx+ return <div id="fdr-home-page">+ { modal }+ <SiteHomePage />+ </div>;+ }+}diff --git a/public/pages/site/ShowIdeaPage.tsx b/public/pages/site/ShowIdeaPage.tsxindex 311630988..f2d286f10 100644--- a/public/pages/site/ShowIdeaPage.tsx+++ b/public/pages/site/ShowIdeaPage.tsx@@ -7,7 +7,7 @@ import { CommentInput } from '@fider/components/CommentInput';import { ResponseForm } from '@fider/components/ResponseForm';import { SupportCounter } from '@fider/components/SupportCounter';import { ShowIdeaResponse } from '@fider/components/ShowIdeaResponse';-import { Button, UserName, Gravatar, Moment, MultiLineText, Footer, Header, SocialLogInButton } from '@fider/components/common';+import { Button, UserName, Gravatar, Moment, MultiLineText, Footer, Header, SocialSignInButton } from '@fider/components/common';import { inject, injectables } from '@fider/di';import { Session } from '@fider/services';diff --git a/public/pages/site/SiteHomePage.scss b/public/pages/site/SiteHomePage.scssindex 1a8b9f8f3..b7a9ac3b7 100644--- a/public/pages/site/SiteHomePage.scss+++ b/public/pages/site/SiteHomePage.scss@@ -37,7 +37,7 @@border-radius: 0;}- .login-message {+ .signin-message {@media only screen and (min-width: 768px) and (max-width: 991px) {span {display: none;diff --git a/public/services/TenantService.ts b/public/services/TenantService.tsindex 2cc1b5018..cac24f772 100644--- a/public/services/TenantService.ts+++ b/public/services/TenantService.ts@@ -6,6 +6,8 @@ export interface TenantService {create(token?: string, name?: string, subdomain?: string): Promise<Result>;updateSettings(title: string, invitation: string, welcomeMessage: string): Promise<Result>;checkAvailability(subdomain: string): Promise<Result<CheckAvailabilityResponse>>;+ signIn(email: string): Promise<Result>;+ completeProfile(key: string, name: string): Promise<Result>;}export interface CheckAvailabilityResponse {@@ -29,4 +31,17 @@ export class HttpTenantService implements TenantService {public async checkAvailability(subdomain: string): Promise<Result<CheckAvailabilityResponse>> {return await get<CheckAvailabilityResponse>(`/api/tenants/${subdomain}/availability`);}++ public async signIn(email: string): Promise<Result> {+ return await post('/api/signin', {+ email,+ });+ }++ public async completeProfile(key: string, name: string): Promise<Result> {+ return await post('/api/signin/complete', {+ key,+ name,+ });+ }}diff --git a/public/tsd.d.ts b/public/tsd.d.tsindex d934c1492..d3a1e6fab 100644--- a/public/tsd.d.ts+++ b/public/tsd.d.ts@@ -1,5 +1,5 @@interface JQuery {- modal(ops: any): any;+ modal(opts: any): any;popup(args: any): any;dropdown(args?: any): any;}diff --git a/public/utils/page.ts b/public/utils/page.tsindex 5eb23304c..427ca34d1 100644--- a/public/utils/page.ts+++ b/public/utils/page.ts@@ -1,24 +1,46 @@export function setTitle(title: string) {- document.title = title;+ document.title = title;}export function getBaseUrl(): string {- return (window as any)._baseUrl;+ return (window as any)._baseUrl;+}++export interface ModalOptions {+ closable: boolean;+}++export function showModal(selector: string, options?: ModalOptions): void {+ const opts = Object.assign({ blurring: true }, options || { });++ $(selector).modal(opts).modal('show');+}++export function hideModal(selector: string): void {+ $(selector).modal('hide');+}++export function showSignIn(): void {+ showModal('#signin-modal');+}++export function hideSignIn(): void {+ hideModal('#signin-modal');}export function getQueryString(name: string) {- const url = window.location.href;- name = name.replace(/[\[\]]/g, '\\$&');- const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');- const results = regex.exec(url);+ const url = window.location.href;+ name = name.replace(/[\[\]]/g, '\\$&');+ const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');+ const results = regex.exec(url);- if (!results) {- return null;- }+ if (!results) {+ return null;+ }- if (!results[2]) {- return '';- }+ if (!results[2]) {+ return '';+ }- return decodeURIComponent(results[2].replace(/\+/g, ' '));+ return decodeURIComponent(results[2].replace(/\+/g, ' '));}diff --git a/router.go b/router.goindex 16932a298..de375f29a 100644--- a/router.go+++ b/router.go@@ -5,6 +5,10 @@ import ("github.com/getfider/fider/app/middlewares""github.com/getfider/fider/app/models""github.com/getfider/fider/app/pkg/dbx"+ "github.com/getfider/fider/app/pkg/email"+ "github.com/getfider/fider/app/pkg/email/mailgun"+ "github.com/getfider/fider/app/pkg/email/smtp"+ "github.com/getfider/fider/app/pkg/env""github.com/getfider/fider/app/pkg/oauth""github.com/getfider/fider/app/pkg/web""github.com/getfider/fider/app/storage"@@ -19,6 +23,18 @@ type AppServices struct {Settings *models.AppSettings}+func initEmailer() email.Sender {+ if env.IsDefined("MAILGUN_API") {+ return mailgun.NewSender(env.MustGet("MAILGUN_DOMAIN"), env.MustGet("MAILGUN_API"))+ }+ return smtp.NewSender(+ env.MustGet("SMTP_HOST"),+ env.MustGet("SMTP_PORT"),+ env.MustGet("SMTP_USERNAME"),+ env.MustGet("SMTP_PASSWORD"),+ )+}+// GetMainEngine returns main HTTP enginefunc GetMainEngine(settings *models.AppSettings) *web.Engine {r := web.New(settings)@@ -28,17 +44,19 @@ func GetMainEngine(settings *models.AppSettings) *web.Engine {panic(err)}db.Migrate()+ emailer := initEmailer()assets := r.Group("/assets"){assets.Use(middlewares.OneYearCache())+ assets.Get("/avatars/:size/:name", handlers.LetterAvatar())assets.Static("/favicon.ico", "favicon.ico")assets.Static("/", "dist")}signup := r.Group(""){- signup.Use(middlewares.Setup(db))+ signup.Use(middlewares.Setup(db, emailer))signup.Use(middlewares.AddServices())signup.Post("/api/tenants", handlers.CreateTenant())@@ -48,20 +66,20 @@ func GetMainEngine(settings *models.AppSettings) *web.Engine {auth := r.Group("/oauth"){- auth.Use(middlewares.Setup(db))+ auth.Use(middlewares.Setup(db, emailer))auth.Use(middlewares.AddServices())- auth.Get("/facebook", handlers.Login(oauth.FacebookProvider))+ auth.Get("/facebook", handlers.SignIn(oauth.FacebookProvider))auth.Get("/facebook/callback", handlers.OAuthCallback(oauth.FacebookProvider))- auth.Get("/google", handlers.Login(oauth.GoogleProvider))+ auth.Get("/google", handlers.SignIn(oauth.GoogleProvider))auth.Get("/google/callback", handlers.OAuthCallback(oauth.GoogleProvider))- auth.Get("/github", handlers.Login(oauth.GitHubProvider))+ auth.Get("/github", handlers.SignIn(oauth.GitHubProvider))auth.Get("/github/callback", handlers.OAuthCallback(oauth.GitHubProvider))}page := r.Group(""){- page.Use(middlewares.Setup(db))+ page.Use(middlewares.Setup(db, emailer))page.Use(middlewares.Tenant())page.Use(middlewares.AddServices())page.Use(middlewares.JwtGetter())@@ -72,9 +90,11 @@ func GetMainEngine(settings *models.AppSettings) *web.Engine {public.Get("/", handlers.Index())public.Get("/ideas/:number", handlers.IdeaDetails())public.Get("/ideas/:number/*", handlers.IdeaDetails())- public.Get("/logout", handlers.Logout())+ public.Get("/signout", handlers.SignOut())+ public.Get("/signin/verify", handlers.VerifySignInKey())public.Get("/api/status", handlers.Status(settings))- public.Get("/avatars/:size/:name", handlers.LetterAvatar())+ public.Post("/api/signin/complete", handlers.CompleteSignInProfile())+ public.Post("/api/signin", handlers.SignInByEmail())}private := page.Group("/api")diff --git a/tests/pages/HomePage.ts b/tests/pages/HomePage.tsindex 901fe23a6..f870005a1 100644--- a/tests/pages/HomePage.ts+++ b/tests/pages/HomePage.ts@@ -20,13 +20,16 @@ export class HomePage extends Page {@findBy('.ui.button.primary')public SubmitIdea: Button;- @findBy('.login')+ @findBy('.signin')public UserMenu: WebComponent;- @findBy('#login-modal .button.google')+ @findBy('#signin-modal')+ public SignInModal: WebComponent;++ @findBy('#signin-modal .button.google')public GoogleSignIn: Button;- @findBy('#login-modal .button.facebook')+ @findBy('#signin-modal .button.facebook')public FacebookSignIn: Button;@findBy('.ui.form .ui.negative.message')diff --git a/tests/pages/SignUpPage.ts b/tests/pages/SignUpPage.tsindex 063668f8d..421fd7504 100644--- a/tests/pages/SignUpPage.ts+++ b/tests/pages/SignUpPage.ts@@ -1,4 +1,4 @@-import { WebComponent, Browser, Page, Button, TextInput, findBy, elementIsVisible, pageHasLoaded } from '../lib';+import { WebComponent, Browser, Page, Button, TextInput, findBy, elementIsVisible, pageHasLoaded, delay } from '../lib';import { GoogleSignInPage, FacebookSignInPage, HomePage } from './';export class SignUpPage extends Page {@@ -16,16 +16,16 @@ export class SignUpPage extends Page {@findBy('#fdr-signup-page .button.facebook')public FacebookSignIn: Button;- @findBy('.form #name')+ @findBy('#fdr-signup-page .form #name')public Name: TextInput;- @findBy('.form #subdomain')+ @findBy('#fdr-signup-page .form #subdomain')public Subdomain: TextInput;- @findBy('.button.positive')+ @findBy('#fdr-signup-page .button.positive')public Confirm: Button;- @findBy('.green.basic.label')+ @findBy('#fdr-signup-page .page .green.basic.label')private SubdomainOk: WebComponent;public loadCondition() {diff --git a/tests/submit-ideas.ts b/tests/submit-ideas.tsindex 2c9fb845b..8cd39e129 100644--- a/tests/submit-ideas.ts+++ b/tests/submit-ideas.ts@@ -6,14 +6,10 @@ describe('Submit ideas', () => {it('Unauthenticated cannot submit ideas', async () => {// Actionawait pages.home.navigate();- await pages.home.IdeaTitle.type('Add support to TypeScript');+ await pages.home.IdeaTitle.click();// Assert- await Promise.all([- ensure(pages.home.UserMenu).textIs('LOG IN'),- ensure(pages.home.SubmitIdea).isNotVisible(),- ensure(pages.home.IdeaDescription).isNotVisible(),- ]);+ await ensure(pages.home.SignInModal).isVisible();});it('Authenticated user can submit ideas', async () => {@@ -36,7 +32,7 @@ describe('Submit ideas', () => {]);});- it('Can log in with Google and support an idea', async () => {+ it('Can sign in with Google and support an idea', async () => {// Actionawait pages.home.navigate();await pages.home.signInWithGoogle();