-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
173 lines (129 loc) · 5.74 KB
/
main.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
package main
import (
"log"
"net/http"
"os"
"github.com/joho/godotenv"
"github.com/labstack/echo/v5"
"github.com/pocketbase/pocketbase"
"github.com/pocketbase/pocketbase/apis"
"github.com/pocketbase/pocketbase/models"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/mailer"
"github.com/sethvargo/go-password/password"
"github.com/pquerna/otp/totp"
)
func goDotEnvVariable(key string) string {
// load .env file
err := godotenv.Load(".env")
if err != nil {
log.Fatalf("Error loading .env file")
}
return os.Getenv(key)
}
func generateUniqueId() string {
rand.Seed(time.Now().UnixNano())
// generate a random 8-digit ID
id := ""
for i := 0; i < 8; i++ {
id += strconv.Itoa(rand.Intn(10))
}
return id
}
func main() {
app := pocketbase.New()
// serves static files from the provided public dir (if exists)
app.OnBeforeServe().Add(func(e *core.ServeEvent) error {
issuer := goDotEnvVariable("issuer")
secretField := goDotEnvVariable("secretField")
e.Router.POST("/auth-login", func(c echo.Context) error {
data := &struct {
Email string `form:"email" json:"email"`
Password string `form:"password" json:"password"`
TwoFactorCode string `form:"twoFactorCode" json:"twoFactorCode"`
}{}
if err := c.Bind(data); err != nil {
return apis.NewBadRequestError("Failed to read request data", err)
}
record, err := app.Dao().FindFirstRecordByData("users", "email", data.Email)
if err != nil || !record.ValidatePassword(data.Password) {
return apis.NewBadRequestError("Invalid credentials", err)
}
if record.Get(secretField) != "" && data.TwoFactorCode == "" {
return c.JSON(http.StatusOK, map[string]bool{"tfa_required": true})
}
if data.TwoFactorCode != "" {
valid := totp.Validate(data.TwoFactorCode, record.Get(secretField).(string))
if !valid {
return apis.NewBadRequestError("Google authenticator code not correct", nil)
}
}
return apis.RecordAuthResponse(app, c, record, nil)
}, apis.ActivityLogger(app))
e.Router.POST("/auth-remove-totp", func(c echo.Context) error {
data := &struct {
TwoFactorCode string `form:"twoFactorCode" json:"twoFactorCode"`
}{}
if err := c.Bind(data); err != nil {
return apis.NewBadRequestError("Failed to read request data", err)
}
authRecord, _ := c.Get(apis.ContextAuthRecordKey).(*models.Record)
if authRecord == nil {
return apis.NewForbiddenError("Only auth records can access this endpoint", nil)
}
valid := totp.Validate(data.TwoFactorCode, authRecord.Get(secretField).(string))
if !valid {
return apis.NewForbiddenError("Google authenticator code not correct", nil)
}
authRecord.Set(secretField, nil)
app.Dao().Save(authRecord)
return c.JSON(http.StatusOK, map[string]string{"message": "Google Authenticator is now deactivated", "status": "success"})
}, /* optional middlewares */)
e.Router.POST("/auth-activate-totp", func(c echo.Context) error {
data := &struct {
Secret string `form:"secret" json:"secret"`
Issuer string `form:"issuer" json:"issuer"`
TwoFactorCode string `form:"twoFactorCode" json:"twoFactorCode"`
}{}
// read the request data
if err := c.Bind(data); err != nil {
return apis.NewBadRequestError("Failed to read request data", err)
}
if data.Issuer != issuer {
return apis.NewForbiddenError("Unkown authentication issuer", nil)
}
authRecord, _ := c.Get(apis.ContextAuthRecordKey).(*models.Record)
if authRecord == nil {
return apis.NewForbiddenError("Only auth records can access this endpoint", nil)
}
valid := totp.Validate(data.TwoFactorCode, data.Secret)
if !valid {
return apis.NewForbiddenError("Google authenticator code not correct", nil)
}
authRecord.Set(secretField, data.Secret)
app.Dao().Save(authRecord)
return c.JSON(http.StatusOK, map[string]string{"message": "Google Authenticator is now activated", "status": "success"})
}, /* optional middlewares */)
e.Router.GET("/auth-generate-totp", func(c echo.Context) error {
authRecord, _ := c.Get(apis.ContextAuthRecordKey).(*models.Record)
if authRecord == nil {
return apis.NewForbiddenError("Only auth records can access this endpoint", nil)
}
if authRecord.Get(secretField) != "" {
return apis.NewForbiddenError("Authenticator already exists for this user", nil)
}
key, err := totp.Generate(totp.GenerateOpts{
Issuer: issuer,
AccountName: authRecord.Get("email").(string),
})
if err != nil {
return apis.NewForbiddenError(err.Error(), nil)
}
return c.JSON(http.StatusOK, map[string]string{"secret": key.Secret(), "issuer": issuer, "status": "success"})
}, /* optional middlewares */)
return nil
})
if err := app.Start(); err != nil {
log.Fatal(err)
}
}