diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ab4783b --- /dev/null +++ b/.gitignore @@ -0,0 +1,28 @@ +*.log +.DS_Store +doc +tmp +pkg +*.gem +*.pid +coverage +coverage.data +build/* +*.pbxuser +*.mode1v3 +.svn +profile +.console_history +.sass-cache/* +.rake_tasks~ +*.log.lck +solr/ +.jhw-cache/ +jhw.* +*.sublime* +node_modules/ +dist/ +generated/ +.vendor/ +bin/* +gin-bin diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..0d62759 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,8 @@ +The MIT License (MIT) +Copyright (c) 2017 Mark Bates + +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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..ed02c5f --- /dev/null +++ b/README.md @@ -0,0 +1,13 @@ +# Auth Generator for Buffalo + +## Installation + +```bash +$ go get -u github.com/gobuffalo/buffalo-auth +``` + +## Usage + +```bash +$ buffalo generate auth +``` diff --git a/auth/auth.go b/auth/auth.go new file mode 100644 index 0000000..d28328f --- /dev/null +++ b/auth/auth.go @@ -0,0 +1,42 @@ +package auth + +import ( + "os/exec" + "path/filepath" + + "github.com/gobuffalo/buffalo/generators" + "github.com/gobuffalo/makr" +) + +// New actions/auth.go file configured to the specified providers. +func New() (*makr.Generator, error) { + g := makr.New() + files, err := generators.Find(filepath.Join("github.com", "gobuffalo", "buffalo-auth", "auth")) + if err != nil { + return nil, err + } + + g.Add(makr.NewCommand(exec.Command("buffalo", "db", "generate", "model", "user", "email", "password_hash"))) + + for _, f := range files { + g.Add(makr.NewFile(f.WritePath, f.Body)) + } + + g.Add(&makr.Func{ + Should: func(data makr.Data) bool { return true }, + Runner: func(root string, data makr.Data) error { + return generators.AddInsideAppBlock( + `app.Use(SetCurrentUser)`, + `app.Use(Authorize)`, + `app.GET("/users/new", UsersNew)`, + `app.POST("/users", UsersCreate)`, + `app.GET("/signin", AuthNew)`, + `app.POST("/signin", AuthCreate)`, + `app.DELETE("/signout", AuthDestroy)`, + `app.Middleware.Skip(Authorize, HomeHandler, UsersNew, UsersCreate, AuthNew, AuthCreate)`, + ) + }, + }) + g.Add(makr.NewCommand(makr.GoGet("github.com/markbates/goth/..."))) + return g, nil +} diff --git a/auth/templates/actions/auth.go.tmpl b/auth/templates/actions/auth.go.tmpl new file mode 100644 index 0000000..8ddc7ce --- /dev/null +++ b/auth/templates/actions/auth.go.tmpl @@ -0,0 +1,66 @@ +package actions + +import ( + "database/sql" + "strings" + + "{{.packagePath}}/models" + "github.com/gobuffalo/buffalo" + "github.com/markbates/pop" + "github.com/markbates/validate" + "github.com/pkg/errors" + "golang.org/x/crypto/bcrypt" +) + +// AuthNew loads the signin page +func AuthNew(c buffalo.Context) error { + c.Set("user", models.User{}) + return c.Render(200, r.HTML("auth/new.html")) +} + +// AuthCreate attempts to log the user in with an existing account. +func AuthCreate(c buffalo.Context) error { + u := &models.User{} + if err := c.Bind(u); err != nil { + return errors.WithStack(err) + } + + tx := c.Value("tx").(*pop.Connection) + + // find a user with the email + err := tx.Where("email = ?", strings.ToLower(u.Email)).First(u) + + // helper function to handle bad attempts + bad := func() error { + c.Set("user", u) + verrs := validate.NewErrors() + verrs.Add("email", "invalid email/password") + c.Set("errors", verrs) + return c.Render(422, r.HTML("auth/new.html")) + } + + if err != nil { + if errors.Cause(err) == sql.ErrNoRows { + // couldn't find an user with the supplied email address. + return bad() + } + return errors.WithStack(err) + } + + // confirm that the given password matches the hashed password from the db + err = bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(u.Password)) + if err != nil { + return bad() + } + c.Session().Set("current_user_id", u.ID) + c.Flash().Add("success", "Welcome Back to Buffalo!") + + return c.Redirect(302, "/") +} + +// AuthDestroy clears the session and logs a user out +func AuthDestroy(c buffalo.Context) error { + c.Session().Clear() + c.Flash().Add("success", "You have been logged out!") + return c.Redirect(302, "/") +} diff --git a/auth/templates/actions/auth_test.go.tmpl b/auth/templates/actions/auth_test.go.tmpl new file mode 100644 index 0000000..6ea9728 --- /dev/null +++ b/auth/templates/actions/auth_test.go.tmpl @@ -0,0 +1,57 @@ +package actions + +import ( + "net/http" + + "{{.packagePath}}/models" + "github.com/markbates/goth" + "github.com/markbates/goth/gothic" + "github.com/markbates/pop/nulls" +) + +func (as *ActionSuite) Test_Auth_New() { + res := as.HTML("/signin").Get() + as.Equal(200, res.Code) + as.Contains(res.Body.String(), "Sign In") +} + +func (as *ActionSuite) Test_Auth_Create() { + u := &models.User{ + Email: "mark@example.com", + Password: "password", + PasswordConfirmation: "password", + } + verrs, err := u.Create(as.DB) + as.NoError(err) + as.False(verrs.HasAny()) + + res := as.HTML("/signin").Post(u) + as.Equal(302, res.Code) + as.Equal("/", res.Location()) +} + +func (as *ActionSuite) Test_Auth_Create_UnknownUser() { + u := &models.User{ + Email: "mark@example.com", + Password: "password", + } + res := as.HTML("/signin").Post(u) + as.Equal(422, res.Code) + as.Contains(res.Body.String(), "invalid email/password") +} + +func (as *ActionSuite) Test_Auth_Create_BadPassword() { + u := &models.User{ + Email: "mark@example.com", + Password: "password", + PasswordConfirmation: "password", + } + verrs, err := u.Create(as.DB) + as.NoError(err) + as.False(verrs.HasAny()) + + u.Password = "bad" + res := as.HTML("/signin").Post(u) + as.Equal(422, res.Code) + as.Contains(res.Body.String(), "invalid email/password") +} diff --git a/auth/templates/actions/home_test.go.tmpl b/auth/templates/actions/home_test.go.tmpl new file mode 100644 index 0000000..68925af --- /dev/null +++ b/auth/templates/actions/home_test.go.tmpl @@ -0,0 +1,30 @@ +package actions + +import "{{.packagePath}}/models" + +func (as *ActionSuite) Test_HomeHandler() { + res := as.HTML("/").Get() + as.Equal(200, res.Code) + as.Contains(res.Body.String(), "Sign In") +} + +func (as *ActionSuite) Test_HomeHandler_LoggedIn() { + u := &models.User{ + Email: "mark@example.com", + Password: "password", + PasswordConfirmation: "password", + } + verrs, err := u.Create(as.DB) + as.NoError(err) + as.False(verrs.HasAny()) + as.Session.Set("current_user_id", u.ID) + + res := as.HTML("/").Get() + as.Equal(200, res.Code) + as.Contains(res.Body.String(), "Sign Out") + + as.Session.Clear() + res = as.HTML("/").Get() + as.Equal(200, res.Code) + as.Contains(res.Body.String(), "Sign In") +} diff --git a/auth/templates/actions/users.go.tmpl b/auth/templates/actions/users.go.tmpl new file mode 100644 index 0000000..f8bfbff --- /dev/null +++ b/auth/templates/actions/users.go.tmpl @@ -0,0 +1,67 @@ +package actions + +import ( + "{{.packagePath}}/models" + "github.com/gobuffalo/buffalo" + "github.com/markbates/pop" + "github.com/pkg/errors" +) + +func UsersNew(c buffalo.Context) error { + u := models.User{} + c.Set("user", u) + return c.Render(200, r.HTML("users/new.html")) +} + +// UsersCreate registers a new user with the application. +func UsersCreate(c buffalo.Context) error { + u := &models.User{} + if err := c.Bind(u); err != nil { + return errors.WithStack(err) + } + + tx := c.Value("tx").(*pop.Connection) + verrs, err := u.Create(tx) + if err != nil { + return errors.WithStack(err) + } + + if verrs.HasAny() { + c.Set("user", u) + c.Set("errors", verrs) + return c.Render(200, r.HTML("users/new.html")) + } + + c.Session().Set("current_user_id", u.ID) + c.Flash().Add("success", "Welcome to Buffalo!") + + return c.Redirect(302, "/") +} + +// SetCurrentUser attempts to find a user based on the current_user_id +// in the session. If one is found it is set on the context. +func SetCurrentUser(next buffalo.Handler) buffalo.Handler { + return func(c buffalo.Context) error { + if uid := c.Session().Get("current_user_id"); uid != nil { + u := &models.User{} + tx := c.Value("tx").(*pop.Connection) + err := tx.Find(u, uid) + if err != nil { + return errors.WithStack(err) + } + c.Set("current_user", u) + } + return next(c) + } +} + +// Authorize require a user be logged in before accessing a route +func Authorize(next buffalo.Handler) buffalo.Handler { + return func(c buffalo.Context) error { + if uid := c.Session().Get("current_user_id"); uid == nil { + c.Flash().Add("danger", "You must be authorized to see that page") + return c.Redirect(302, "/") + } + return next(c) + } +} diff --git a/auth/templates/actions/users_test.go.tmpl b/auth/templates/actions/users_test.go.tmpl new file mode 100644 index 0000000..2297b60 --- /dev/null +++ b/auth/templates/actions/users_test.go.tmpl @@ -0,0 +1,29 @@ +package actions + +import ( + "{{.packagePath}}/models" +) + +func (as *ActionSuite) Test_Users_New() { + res := as.HTML("/users/new").Get() + as.Equal(200, res.Code) +} + +func (as *ActionSuite) Test_Users_Create() { + count, err := as.DB.Count("users") + as.NoError(err) + as.Equal(0, count) + + u := &models.User{ + Email: "mark@example.com", + Password: "password", + PasswordConfirmation: "password", + } + + res := as.HTML("/users").Post(u) + as.Equal(302, res.Code) + + count, err = as.DB.Count("users") + as.NoError(err) + as.Equal(1, count) +} diff --git a/auth/templates/models/user.go.tmpl b/auth/templates/models/user.go.tmpl new file mode 100644 index 0000000..62a33d6 --- /dev/null +++ b/auth/templates/models/user.go.tmpl @@ -0,0 +1,87 @@ +package models + +import ( + "encoding/json" + "strings" + "time" + + "github.com/markbates/pop" + "github.com/markbates/validate" + "github.com/markbates/validate/validators" + "github.com/pkg/errors" + "github.com/satori/go.uuid" + "golang.org/x/crypto/bcrypt" +) + +type User struct { + ID uuid.UUID `json:"id" db:"id"` + CreatedAt time.Time `json:"created_at" db:"created_at"` + UpdatedAt time.Time `json:"updated_at" db:"updated_at"` + Email string `json:"email" db:"email"` + PasswordHash string `json:"-" db:"password_hash"` + Password string `json:"-" db:"-"` + PasswordConfirmation string `json:"-" db:"-"` +} + +// String is not required by pop and may be deleted +func (u User) String() string { + ju, _ := json.Marshal(u) + return string(ju) +} + +// Create wraps up the pattern of encrypting the password and +// running validations. Useful when writing tests. +func (u *User) Create(tx *pop.Connection) (*validate.Errors, error) { + u.Email = strings.ToLower(u.Email) + ph, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost) + if err != nil { + return validate.NewErrors(), errors.WithStack(err) + } + u.PasswordHash = string(ph) + return tx.ValidateAndCreate(u) +} + +// Users is not required by pop and may be deleted +type Users []User + +// String is not required by pop and may be deleted +func (u Users) String() string { + ju, _ := json.Marshal(u) + return string(ju) +} + +// Validate gets run every time you call a "pop.Validate" method. +func (u *User) Validate(tx *pop.Connection) (*validate.Errors, error) { + var err error + return validate.Validate( + &validators.StringIsPresent{Field: u.Email, Name: "Email"}, + &validators.StringIsPresent{Field: u.PasswordHash, Name: "PasswordHash"}, + // check to see if the email address is already taken: + &validators.FuncValidator{ + Field: u.Email, + Name: "Email", + Message: "%s is already taken", + Fn: func() bool { + var b bool + q := tx.Where("email = ?", u.Email) + if u.ID != uuid.Nil { + q = q.Where("id != ?", u.ID) + } + b, err = q.Exists(u) + if err != nil { + return false + } + return !b + }, + }, + ), err +} + +// ValidateCreate gets run every time you call "pop.ValidateAndCreate" method. +func (u *User) ValidateCreate(tx *pop.Connection) (*validate.Errors, error) { + var err error + return validate.Validate( + &validators.StringIsPresent{Field: u.Password, Name: "Password"}, + &validators.StringsMatch{Name: "Password", Field: u.Password, Field2: u.PasswordConfirmation, Message: "Password does not match confirmation"}, + ), err +} diff --git a/auth/templates/models/user_test.go.tmpl b/auth/templates/models/user_test.go.tmpl new file mode 100644 index 0000000..930856b --- /dev/null +++ b/auth/templates/models/user_test.go.tmpl @@ -0,0 +1,80 @@ +package models_test + +import ( + "{{.packagePath}}/models" +) + +func (ms *ModelSuite) Test_User_Create() { + count, err := ms.DB.Count("users") + ms.NoError(err) + ms.Equal(0, count) + + u := &models.User{ + Email: "mark@example.com", + Password: "password", + PasswordConfirmation: "password", + } + ms.Zero(u.PasswordHash) + + verrs, err := u.Create(ms.DB) + ms.NoError(err) + ms.False(verrs.HasAny()) + ms.NotZero(u.PasswordHash) + + count, err = ms.DB.Count("users") + ms.NoError(err) + ms.Equal(1, count) +} + +func (ms *ModelSuite) Test_User_Create_ValidationErrors() { + count, err := ms.DB.Count("users") + ms.NoError(err) + ms.Equal(0, count) + + u := &models.User{ + Password: "password", + } + ms.Zero(u.PasswordHash) + + verrs, err := u.Create(ms.DB) + ms.NoError(err) + ms.True(verrs.HasAny()) + + count, err = ms.DB.Count("users") + ms.NoError(err) + ms.Equal(0, count) +} + +func (ms *ModelSuite) Test_User_Create_UserExists() { + count, err := ms.DB.Count("users") + ms.NoError(err) + ms.Equal(0, count) + + u := &models.User{ + Email: "mark@example.com", + Password: "password", + PasswordConfirmation: "password", + } + ms.Zero(u.PasswordHash) + + verrs, err := u.Create(ms.DB) + ms.NoError(err) + ms.False(verrs.HasAny()) + ms.NotZero(u.PasswordHash) + + count, err = ms.DB.Count("users") + ms.NoError(err) + ms.Equal(1, count) + + u = &models.User{ + Email: "mark@example.com", + Password: "password", + } + verrs, err = u.Create(ms.DB) + ms.NoError(err) + ms.True(verrs.HasAny()) + + count, err = ms.DB.Count("users") + ms.NoError(err) + ms.Equal(1, count) +} diff --git a/auth/templates/templates/auth/new.html.tmpl b/auth/templates/templates/auth/new.html.tmpl new file mode 100644 index 0000000..53a19be --- /dev/null +++ b/auth/templates/templates/auth/new.html.tmpl @@ -0,0 +1,8 @@ +