-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathemail_confirmations_handler.go
73 lines (57 loc) · 2.05 KB
/
email_confirmations_handler.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
package main
import (
"log"
"net/http"
"github.com/flosch/pongo2"
"github.com/plentiform/plentiform/mailers"
repo "github.com/plentiform/plentiform/repositories"
"github.com/tuvistavie/securerandom"
)
func (app *Application) EmailConfirmationsNewHandler(w http.ResponseWriter, r *http.Request) {
app.Render(w, r, "email_confirmations/new", pongo2.Context{})
}
func (app *Application) EmailConfirmationsCreateHandler(w http.ResponseWriter, r *http.Request) {
session, _ := app.GetSession(r)
usersRepo := repo.NewUsersRepository(app.db)
ok := app.recaptchaClient.Verify(*r)
if !ok {
session.AddFlash("Invalid ReCaptcha")
session.Save(r, w)
app.Render(w, r, "email_confirmations/new", pongo2.Context{"email": r.PostFormValue("email")})
return
}
user, _ := usersRepo.FindByEmail(r.PostFormValue("email"))
token, _ := securerandom.UrlSafeBase64(10, true)
user.EmailConfirmationToken = &token
_, err := usersRepo.Update(user)
if err != nil {
log.Println(err)
session.AddFlash("Something bad happened :(")
session.Save(r, w)
app.Render(w, r, "email_confirmations/new", pongo2.Context{"email": r.PostFormValue("email")})
return
}
mailers.SendEmailConfirmation(app.emailClient, app.hostName, user)
session.AddFlash("Please check your email for confirmation instructions.")
session.Save(r, w)
http.Redirect(w, r, "/email_confirmation/new", 302)
}
func (app *Application) EmailConfirmationsShowHandler(w http.ResponseWriter, r *http.Request) {
session, _ := app.GetSession(r)
token := r.URL.Query().Get("token")
usersRepo := repo.NewUsersRepository(app.db)
user, _ := usersRepo.FindByEmailConfirmationToken(token)
if user == nil {
session.AddFlash("This token is not associated with a user.")
session.Save(r, w)
http.Redirect(w, r, "/email_confirmation/new", 302)
return
}
user.EmailConfirmationToken = nil
user.IsEmailConfirmed = true
usersRepo.Update(user) // TODO Error handling
session.Values["userId"] = user.Id
session.AddFlash("Successfully confirmed your email address.")
session.Save(r, w)
http.Redirect(w, r, "/", 302)
}