/
authenticate.go
178 lines (163 loc) · 5.25 KB
/
authenticate.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
package auth
import (
"golang.org/x/crypto/bcrypt"
"os/exec"
"strings"
"net/http"
"github.com/gorilla/sessions"
"time"
"github.com/asafron/meetings-scheduler/db"
"github.com/asafron/meetings-scheduler/helpers"
"github.com/asafron/meetings-scheduler/models"
"github.com/asafron/meetings-scheduler/config"
)
type Authenticator struct {
dal *db.DAL
cookieJar *sessions.CookieStore
}
func NewAuthenticator(dal *db.DAL, cookieKey string) *Authenticator {
a := Authenticator{}
a.dal = dal
a.cookieJar = sessions.NewCookieStore([]byte(cookieKey))
return &a
}
func (a *Authenticator) Register(email string , password string, firstName string , lastName string) (string, error) {
if email == "" {
return "", helpers.AuthenticationErrorRegisterNoEmail
}
if password == "" {
return "", helpers.AuthenticationErrorRegisterNoPassword
}
// Generate and save hash
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return "", helpers.AuthenticationErrorRegisterPasswordNotValid
}
// Create confirmation token
token, tokenErr := exec.Command("uuidgen").Output()
if tokenErr !=nil {
return "", tokenErr
}
confirmationToken := strings.TrimRight(strings.ToLower(string(token)), "\n")
err = a.dal.InsertUser(email, hash, firstName, lastName, confirmationToken)
if err != nil {
return "", helpers.AuthenticationErrorRegisterUserCreationFailed
}
return confirmationToken, nil
}
func (a *Authenticator) Login(rw http.ResponseWriter, req *http.Request, email string, password string) error {
session, _ := a.cookieJar.Get(req, "auth")
if session.Values["email"] != nil {
// Set the current user
username:= (session.Values["email"]).(string)
user, err := a.dal.FindActiveUserByEmail(username)
if err == nil {
helpers.SetCurrentUser(req,*user)
}
return helpers.AuthenticationErrorLoginAlreadyAuthenticated
}
// Try to find the user, to see if it already logged in...
user, err := a.dal.FindActiveUserByEmail(email)
if err == nil {
verify := bcrypt.CompareHashAndPassword(user.Hash, []byte(password))
if verify != nil {
return helpers.AuthenticationErrorLoginWrongEmailPassword
}
} else {
return helpers.AuthenticationErrorLoginUserNotExists
}
session.Values["email"] = email
session.Save(req, rw)
helpers.SetCurrentUser(req,*user)
return nil
}
func (a *Authenticator) Authorize(rw http.ResponseWriter, req *http.Request) (*models.User, error) {
var user *models.User
authSession, err := a.cookieJar.Get(req, "auth")
if err != nil {
return user, helpers.AuthenticationErrorAuthorizeNewSession
}
username := authSession.Values["email"]
if !authSession.IsNew && username != nil {
user, err = a.dal.FindActiveUserByEmail(username.(string))
if err == helpers.AuthenticationErrorLoginUserNotExists {
authSession.Options.MaxAge = -1 // kill the cookie
authSession.Save(req, rw)
return user, helpers.AuthenticationErrorLoginUserNotExists
} else if err != nil {
return user, helpers.GeneralErrorInternal
}
}
if username == nil {
return user,helpers.AuthenticationErrorAuthorizeUserNotLoggedIn
}
return user,nil
}
func (a *Authenticator) Logout(rw http.ResponseWriter, req *http.Request) error {
session, _ := a.cookieJar.Get(req, "auth")
defer session.Save(req, rw)
session.Options.MaxAge = -1 // kill the cookie
return nil
}
func (auth *Authenticator) ConfirmUser(email string, confirmationToken string) error {
// Locate the user
user, err := auth.dal.FindUserByConfirmationToken(confirmationToken, email)
if err != nil {
return helpers.AuthenticationErrorConfirmationTokenNotValid
}
// If all is OK, confirm the user
err = auth.dal.UpdateUserConfirmation(user.Id, models.USER_CONFIRMED, models.CONFIRMATION_TOKEN_INVALID, true)
if err != nil {
return helpers.GeneralErrorInternal
}
return nil
}
func (auth *Authenticator) CreatePasswordRecovery(email string) (string,error) {
// Locate the user
user, err := auth.dal.FindActiveUserByEmail(email)
if err != nil {
return "", err
}
// If all is OK, create password recovery
token, err := helpers.CreateToken()
if err != nil {
return "", err
}
// Update user, set expiry to 24 hours from now
err = auth.dal.UpdateUserRecovery(user.Id, token, models.RECOVER_TOKEN_VALID, time.Now().UTC().Add(time.Hour * 24) )
if err!=nil {
return "", err
}
return token, nil
}
func (auth *Authenticator) UpdateUserPasswordFromRecovery(email string, token string, password string ) error {
//get the user
user, err := auth.dal.FindUserByRecoveryToken(token,email)
if err != nil {
return err
}
//generate hash
// Generate and save hash
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return helpers.AuthenticationErrorRegisterPasswordNotValid
}
err = auth.dal.UpdateUserPassword(user.Id,hash, models.RECOVER_TOKEN_INVALID, time.Now().UTC())
if err!=nil {
return err
}
return nil
}
func (auth *Authenticator) AuthMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var user *models.User
var err error=nil
user, err = auth.Authorize(w, r)
if err != nil {
http.Redirect(w, r, config.GetConfigWrapper().GetCurrent().DashboardBaseUrl, http.StatusSeeOther)
return
}
helpers.SetCurrentUser(r,*user)
h.ServeHTTP(w, r)
})
}