-
Notifications
You must be signed in to change notification settings - Fork 20
/
auth.handlers.go
247 lines (203 loc) · 6.21 KB
/
auth.handlers.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
package handlers
import (
"errors"
"fmt"
"net/http"
"strings"
"github.com/emarifer/go-echo-templ-htmx/services"
"github.com/emarifer/go-echo-templ-htmx/views/auth_views"
"golang.org/x/crypto/bcrypt"
"github.com/a-h/templ"
"github.com/gorilla/sessions"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
)
const (
auth_sessions_key string = "authenticate-sessions"
auth_key string = "authenticated"
user_id_key string = "user_id"
username_key string = "username"
tzone_key string = "time_zone"
)
/********** Handlers for Auth Views **********/
type AuthService interface {
CreateUser(u services.User) error
CheckEmail(email string) (services.User, error)
// GetUserById(id int) (services.User, error)
}
func NewAuthHandler(us AuthService) *AuthHandler {
return &AuthHandler{
UserServices: us,
}
}
type AuthHandler struct {
UserServices AuthService
}
func (ah *AuthHandler) homeHandler(c echo.Context) error {
fromProtected, ok := c.Get("FROMPROTECTED").(bool)
if !ok {
return errors.New("invalid type for key 'FROMPROTECTED'")
}
homeView := auth_views.Home(fromProtected)
// isError = false
c.Set("ISERROR", false)
// fmt.Printf("\033[31mFROMPROTECTED = %t\n\033[0m", fromProtected)
return renderView(c, auth_views.HomeIndex(
"| Home",
"",
fromProtected,
c.Get("ISERROR").(bool),
getFlashmessages(c, "error"),
getFlashmessages(c, "success"),
homeView,
))
}
func (ah *AuthHandler) registerHandler(c echo.Context) error {
fromProtected, ok := c.Get("FROMPROTECTED").(bool)
if !ok {
return errors.New("invalid type for key 'FROMPROTECTED'")
}
registerView := auth_views.Register(fromProtected)
// isError = false
c.Set("ISERROR", false)
if c.Request().Method == "POST" {
user := services.User{
Email: c.FormValue("email"),
Password: c.FormValue("password"),
Username: c.FormValue("username"),
}
err := ah.UserServices.CreateUser(user)
if err != nil {
if strings.Contains(err.Error(), "UNIQUE constraint failed") {
err = errors.New("the email is already in use")
setFlashmessages(c, "error", fmt.Sprintf(
"something went wrong: %s",
err,
))
return c.Redirect(http.StatusSeeOther, "/register")
}
return echo.NewHTTPError(
echo.ErrInternalServerError.Code,
fmt.Sprintf(
"something went wrong: %s",
err,
))
}
setFlashmessages(c, "success", "You have successfully registered!!")
return c.Redirect(http.StatusSeeOther, "/login")
}
return renderView(c, auth_views.RegisterIndex(
"| Register",
"",
fromProtected,
c.Get("ISERROR").(bool),
getFlashmessages(c, "error"),
getFlashmessages(c, "success"),
registerView,
))
}
func (ah *AuthHandler) loginHandler(c echo.Context) error {
fromProtected, ok := c.Get("FROMPROTECTED").(bool)
if !ok {
return errors.New("invalid type for key 'FROMPROTECTED'")
}
loginView := auth_views.Login(fromProtected)
// isError = false
c.Set("ISERROR", false)
if c.Request().Method == "POST" {
// obtaining the time zone from the POST request of the login form
tzone := ""
if len(c.Request().Header["X-Timezone"]) != 0 {
tzone = c.Request().Header["X-Timezone"][0]
}
// Authentication goes here
user, err := ah.UserServices.CheckEmail(c.FormValue("email"))
if err != nil {
if strings.Contains(err.Error(), "no rows in result set") {
setFlashmessages(c, "error", "There is no user with that email")
return c.Redirect(http.StatusSeeOther, "/login")
}
return echo.NewHTTPError(
echo.ErrInternalServerError.Code,
fmt.Sprintf(
"something went wrong: %s",
err,
))
}
err = bcrypt.CompareHashAndPassword(
[]byte(user.Password),
[]byte(c.FormValue("password")),
)
if err != nil {
// In production you have to give the user a generic message
setFlashmessages(c, "error", "Incorrect password")
return c.Redirect(http.StatusSeeOther, "/login")
}
// Get Session and setting Cookies
sess, _ := session.Get(auth_sessions_key, c)
sess.Options = &sessions.Options{
Path: "/",
MaxAge: 3600, // in seconds
HttpOnly: true,
}
// Set user as authenticated, their username,
// their ID and the client's time zone
sess.Values = map[interface{}]interface{}{
auth_key: true,
user_id_key: user.ID,
username_key: user.Username,
tzone_key: tzone,
}
sess.Save(c.Request(), c.Response())
setFlashmessages(c, "success", "You have successfully logged in!!")
return c.Redirect(http.StatusSeeOther, "/todo/list")
}
return renderView(c, auth_views.LoginIndex(
"| Login",
"",
fromProtected,
c.Get("ISERROR").(bool),
getFlashmessages(c, "error"),
getFlashmessages(c, "success"),
loginView,
))
}
func (ah *AuthHandler) flagsMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
sess, _ := session.Get(auth_sessions_key, c)
if auth, ok := sess.Values[auth_key].(bool); !ok || !auth {
// fmt.Printf("\033[36m Ok=%t, Auth=%t \n\033[0m", ok, auth)
c.Set("FROMPROTECTED", false)
return next(c)
}
c.Set("FROMPROTECTED", true)
return next(c)
}
}
func (ah *AuthHandler) authMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
sess, _ := session.Get(auth_sessions_key, c)
if auth, ok := sess.Values[auth_key].(bool); !ok || !auth {
// fmt.Printf("\033[36m Ok=%t, Auth=%t \n\033[0m", ok, auth)
// fromProtected = false
c.Set("FROMPROTECTED", false)
return echo.NewHTTPError(echo.ErrUnauthorized.Code, "Please provide valid credentials")
}
if userId, ok := sess.Values[user_id_key].(int); ok && userId != 0 {
c.Set(user_id_key, userId) // set the user_id in the context
}
if username, ok := sess.Values[username_key].(string); ok && len(username) != 0 {
c.Set(username_key, username) // set the username in the context
}
if tzone, ok := sess.Values[tzone_key].(string); ok && len(tzone) != 0 {
c.Set(tzone_key, tzone) // set the client's time zone in the context
}
// fromProtected = true
c.Set("FROMPROTECTED", true)
return next(c)
}
}
func renderView(c echo.Context, cmp templ.Component) error {
c.Response().Header().Set(echo.HeaderContentType, echo.MIMETextHTML)
return cmp.Render(c.Request().Context(), c.Response().Writer)
}