This repository has been archived by the owner on Dec 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
auth.go
78 lines (64 loc) · 2.05 KB
/
auth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package actions
import (
"database/sql"
"github.com/brittonhayes/hikeshi/models"
"github.com/gobuffalo/buffalo"
"github.com/gobuffalo/pop/v5"
"github.com/gobuffalo/validate/v3"
"github.com/pkg/errors"
"golang.org/x/crypto/bcrypt"
"net/http"
"strings"
)
// AuthLanding shows a landing page to login
func AuthLanding(c buffalo.Context) error {
return c.Render(200, r.HTML("auth/landing.plush.html", "empty.plush.html"))
}
// AuthNew loads the signin page
func AuthNew(c buffalo.Context) error {
c.Set("user", models.User{})
return c.Render(200, r.HTML("auth/new.plush.html", "empty.plush.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(strings.TrimSpace(u.Email))).First(u)
// helper function to handle bad attempts
bad := func() error {
verrs := validate.NewErrors()
verrs.Add("email", "invalid email/password")
c.Set("errors", verrs)
c.Set("user", u)
return c.Render(http.StatusUnauthorized, r.HTML("auth/new.plush.html", "empty.plush.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 Hikeshi!")
redirectURL := "/"
if redir, ok := c.Session().Get("redirectURL").(string); ok && redir != "" {
redirectURL = redir
}
return c.Redirect(302, redirectURL)
}
// 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, "/auth")
}