-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapi-user.go
220 lines (194 loc) · 7.37 KB
/
api-user.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/bcrypt"
)
func (h *HTTPServer) setupUserHandlers() {
h.router.PUT("/user/:email", createUser())
h.router.POST("/user/:email/activate", activateUser())
// h.router.POST("/user/:email/disable", disableUser())
}
func createUser() func(*gin.Context) {
return func(c *gin.Context) {
pmethod := c.Request.Method
ppath := c.FullPath()
email := strings.ToLower(c.Param("email"))
logrus.Debugf("createUser email=%s", email)
m := make(map[string]string)
data, _ := ioutil.ReadAll(c.Request.Body)
err := json.Unmarshal(data, &m)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"message": fmt.Sprintf("Couldn't parse body contents. err=%s", err)})
invocationCounter.WithLabelValues(pmethod, ppath, "500").Inc()
return
}
m["email"] = email
//VALIDATE INPUTS
valid := validateField(m, "email", "^(([^<>()\\[\\]\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\.,;:\\s@\"]+)*)|(\".+\"))@(([^<>()[\\]\\.,;:\\s@\"]+\\.)+[^<>()[\\]\\.,;:\\s@\"]{2,})$")
if !valid {
c.JSON(455, gin.H{"message": "Invalid email"})
invocationCounter.WithLabelValues(pmethod, ppath, "455").Inc()
return
}
valid = validateField(m, "name", "^.{4,}$")
if !valid {
c.JSON(450, gin.H{"message": "Invalid name"})
invocationCounter.WithLabelValues(pmethod, ppath, "450").Inc()
return
}
valid = validateField(m, "password", opt.passwordValidationRegex)
if !valid {
c.JSON(460, gin.H{"message": "Invalid password"})
invocationCounter.WithLabelValues(pmethod, ppath, "460").Inc()
return
}
//VERIFY IF EMAIL ALREADY EXISTS
var u User
if !db.First(&u, "email = ?", email).RecordNotFound() {
if u.ActivationDate != nil {
c.JSON(465, gin.H{"message": "Email already registered"})
invocationCounter.WithLabelValues(pmethod, ppath, "465").Inc()
return
}
logrus.Infof("New account registration with existing email in pending activation state. Replacing it.")
err := db.Unscoped().Delete(&u).Error
if err != nil {
logrus.Warnf("Couldn't delete user email=%s. err=%s", email, err)
c.JSON(500, gin.H{"message": "Server error"})
invocationCounter.WithLabelValues(pmethod, ppath, "500").Inc()
return
}
}
//CREATE ACCOUNT
pwd := m["password"]
phash, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.MinCost)
if err != nil {
logrus.Warnf("Couldn't hash password for email=%s. err=%s", email, err)
c.JSON(500, gin.H{"message": "Server error"})
invocationCounter.WithLabelValues(pmethod, ppath, "500").Inc()
return
}
u0 := User{
Email: email,
Enabled: 1,
CreationDate: time.Now(),
Name: m["name"],
PasswordDate: time.Now(),
PasswordHash: string(phash),
ActivationDate: nil,
PasswordValidUntil: generatePasswordValidUntil(),
}
if opt.accountActivationMethod == "direct" {
now := time.Now()
u0.ActivationDate = &now
}
err = db.Create(&u0).Error
if err != nil {
logrus.Warnf("Error creating user email=%s. err=%s", email, err)
c.JSON(500, gin.H{"message": "Server error"})
invocationCounter.WithLabelValues(pmethod, ppath, "500").Inc()
return
}
if opt.accountActivationMethod == "direct" {
c.JSON(201, gin.H{"message": "Account created and activated"})
invocationCounter.WithLabelValues(pmethod, ppath, "201").Inc()
return
}
//SEND ACTIVATION TOKEN TO USER EMAIL
_, activationTokenString, err := createJWTToken(email, opt.validationTokenExpirationMinutes, "activation", "password", nil)
if err != nil {
logrus.Warnf("Error creating activation token for email=%s. err=%s", email, err)
c.JSON(500, gin.H{"message": "Server error"})
invocationCounter.WithLabelValues(pmethod, ppath, "500").Inc()
return
}
logrus.Debugf("Sending activation mail to %s", email)
htmlBody := strings.ReplaceAll(opt.mailActivationHTMLBody, "EMAIL", u0.Email)
htmlBody = strings.ReplaceAll(htmlBody, "DISPLAY_NAME", u0.Name)
htmlBody = strings.ReplaceAll(htmlBody, "ACTIVATION_TOKEN", activationTokenString)
err = sendMail(opt.mailActivationSubject, htmlBody, email, u0.Name)
if err != nil {
logrus.Warnf("Couldn't send account validation email to %s (%s). err=%s", email, opt.mailActivationSubject, err)
mailCounter.WithLabelValues("POST", "activation", "500").Inc()
c.JSON(500, gin.H{"message": "Server error"})
return
}
logrus.Debugf("Account created and activation link sent to email %s", email)
// logrus.Debugf("Activation token=%s", activationTokenString)
mailCounter.WithLabelValues("POST", "activation", "202").Inc()
if opt.mailTokensTests == "true" {
logrus.Warnf("ADDING ACTIVATION TOKEN TO RESPONSE HEADER. NEVER USE THIS IN PRODUCTION. DISABLE THIS BY REMOVING ENV 'MAIL_TOKENS_FOR_TESTS'")
c.Header("Test-Token", activationTokenString)
}
c.JSON(250, gin.H{"message": "Account created and activation link sent to email"})
invocationCounter.WithLabelValues(pmethod, ppath, "250").Inc()
return
}
}
func activateUser() func(*gin.Context) {
// * response body json: name, jwtAccessToken, jwtRefreshToken, accessTokenExpirationDate, refreshTokenExpirationDate
return func(c *gin.Context) {
pmethod := c.Request.Method
ppath := c.FullPath()
email := strings.ToLower(c.Param("email"))
logrus.Debugf("activateUser email=%s", email)
_, err := loadAndValidateToken(c.Request, "activation", email)
if err != nil {
c.JSON(450, gin.H{"message": "Invalid activation token"})
invocationCounter.WithLabelValues(pmethod, ppath, "450").Inc()
return
}
var u User
db1 := db.First(&u, "email = ?", email)
if db1.RecordNotFound() {
c.JSON(404, gin.H{"message": "Account not found"})
invocationCounter.WithLabelValues(pmethod, ppath, "404").Inc()
return
}
err = db1.Error
if err != nil {
logrus.Warnf("Error getting user during activation. email=%s err=%s", email, err)
c.JSON(500, gin.H{"message": "Server error"})
invocationCounter.WithLabelValues(pmethod, ppath, "500").Inc()
return
}
if u.Enabled == 0 {
c.JSON(460, gin.H{"message": "Account disabled"})
invocationCounter.WithLabelValues(pmethod, ppath, "460").Inc()
return
}
if u.ActivationDate != nil {
c.JSON(455, gin.H{"message": "Account already activated"})
invocationCounter.WithLabelValues(pmethod, ppath, "455").Inc()
return
}
err = db.Model(&u).UpdateColumn("activationDate", time.Now()).Error
if err != nil {
logrus.Warnf("Error activating user. email=%s err=%s", email, err)
c.JSON(500, gin.H{"message": "Server error"})
invocationCounter.WithLabelValues(pmethod, ppath, "500").Inc()
return
}
//ACCOUNT ACTIVATED. CREATE ACCESS TOKENS FOR DIRECT SIGNIN
defaultAccessClaims := make(map[string]interface{})
defaultAccessClaims["scope"] = strings.Split(opt.accessTokenDefaultScope, ",")
tokensResponse, err := createAccessAndRefreshToken(u.Name, email, "password", defaultAccessClaims, nil)
if err != nil {
logrus.Warnf("Error generating tokens for user %s. err=%s", email, err)
c.JSON(500, gin.H{"message": "Server error"})
invocationCounter.WithLabelValues(pmethod, ppath, "500").Inc()
return
}
tokensResponse["message"] = "Account activated successfuly"
c.JSON(202, tokensResponse)
invocationCounter.WithLabelValues(pmethod, ppath, "202").Inc()
logrus.Debugf("Account %s activated successfuly", email)
}
}