Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
markbates committed Nov 3, 2017
0 parents commit c4e91be
Show file tree
Hide file tree
Showing 18 changed files with 643 additions and 0 deletions.
28 changes: 28 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -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
8 changes: 8 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -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.
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Auth Generator for Buffalo

## Installation

```bash
$ go get -u github.com/gobuffalo/buffalo-auth
```

## Usage

```bash
$ buffalo generate auth
```
42 changes: 42 additions & 0 deletions auth/auth.go
Original file line number Diff line number Diff line change
@@ -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
}
66 changes: 66 additions & 0 deletions auth/templates/actions/auth.go.tmpl
Original file line number Diff line number Diff line change
@@ -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, "/")
}
57 changes: 57 additions & 0 deletions auth/templates/actions/auth_test.go.tmpl
Original file line number Diff line number Diff line change
@@ -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: "[email protected]",
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: "[email protected]",
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: "[email protected]",
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")
}
30 changes: 30 additions & 0 deletions auth/templates/actions/home_test.go.tmpl
Original file line number Diff line number Diff line change
@@ -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: "[email protected]",
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")
}
67 changes: 67 additions & 0 deletions auth/templates/actions/users.go.tmpl
Original file line number Diff line number Diff line change
@@ -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)
}
}
29 changes: 29 additions & 0 deletions auth/templates/actions/users_test.go.tmpl
Original file line number Diff line number Diff line change
@@ -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: "[email protected]",
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)
}
Loading

0 comments on commit c4e91be

Please sign in to comment.