-
Notifications
You must be signed in to change notification settings - Fork 2
/
plugin.go
195 lines (163 loc) · 5.83 KB
/
plugin.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
package pocketbase_plugin_telegram_auth
import (
"errors"
"fmt"
"net/http"
"github.com/iamelevich/pocketbase-plugin-telegram-auth/forms"
"github.com/labstack/echo/v5"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/apis"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/daos"
pbForms "github.com/pocketbase/pocketbase/forms"
"github.com/pocketbase/pocketbase/models"
"github.com/pocketbase/pocketbase/resolvers"
"github.com/pocketbase/pocketbase/tools/auth"
"github.com/pocketbase/pocketbase/tools/search"
)
// Options defines optional struct to customize the default plugin behavior.
type Options struct {
// BotToken is a Telegram bot token.
// You can get it from @BotFather.
BotToken string
// CollectionKey is a collection key (name or id) for PocketBase auth collection.
CollectionKey string
}
type Plugin struct {
app core.App
options *Options
collection *models.Collection
}
// Validate plugin options. Return error if some option is invalid.
func (p *Plugin) Validate() error {
if p.options == nil {
return fmt.Errorf("options is required")
}
if p.options.BotToken == "" {
return fmt.Errorf("bot token is required")
}
if p.options.CollectionKey == "" {
return fmt.Errorf("collection key is required")
}
return nil
}
// GetCollection returns PocketBase collection object for collection with name or id from options.CollectionKey.
func (p *Plugin) GetCollection() (*models.Collection, error) {
// If collection object stored in plugin - return it
if p.collection != nil {
return p.collection, nil
}
// If no collection object - find it, store and return
if collection, err := p.app.Dao().FindCollectionByNameOrId(p.options.CollectionKey); err != nil {
return nil, err
} else {
p.collection = collection
return collection, nil
}
}
// GetForm returns Telegram login form for collection with name or id from options.CollectionKey.
func (p *Plugin) GetForm(optAuthRecord *models.Record) (*forms.RecordTelegramLogin, error) {
collection, findCollectionErr := p.GetCollection()
if findCollectionErr != nil {
return nil, findCollectionErr
}
if collection.Type != models.CollectionTypeAuth {
return nil, errors.New("Wrong collection type. " + p.options.CollectionKey + " should be auth collection")
}
return forms.NewRecordTelegramLogin(p.app, p.options.BotToken, collection, optAuthRecord), nil
}
// AuthByTelegramData returns auth record and auth user by Telegram data.
func (p *Plugin) AuthByTelegramData(tgData forms.TelegramData) (*models.Record, *auth.AuthUser, error) {
form, err := p.GetForm(nil)
if err != nil {
return nil, nil, err
}
return form.SubmitWithTelegramData(&tgData)
}
// MustRegister is a helper function to register plugin and panic if error occurred.
func MustRegister(app core.App, options *Options) *Plugin {
if p, err := Register(app, options); err != nil {
panic(err)
} else {
return p
}
}
// Register plugin in PocketBase app.
func Register(app core.App, options *Options) (*Plugin, error) {
p := &Plugin{app: app}
// Set default options
if options != nil {
p.options = options
} else {
p.options = &Options{}
}
// Validate options
if err := p.Validate(); err != nil {
return p, err
}
app.OnBeforeServe().Add(func(e *core.ServeEvent) error {
// or you can also use the shorter e.Router.GET("/articles/:slug", handler, middlewares...)
_, routeError := e.Router.AddRoute(echo.Route{
Method: http.MethodPost,
Path: "/api/collections/" + p.options.CollectionKey + "/auth-with-telegram",
Handler: func(c echo.Context) error {
collection, findCollectionErr := p.GetCollection()
if findCollectionErr != nil {
return apis.NewNotFoundError("Collection not found", findCollectionErr)
}
var fallbackAuthRecord *models.Record
loggedAuthRecord, _ := c.Get(apis.ContextAuthRecordKey).(*models.Record)
if loggedAuthRecord != nil && loggedAuthRecord.Collection().Id == collection.Id {
fallbackAuthRecord = loggedAuthRecord
}
form, getFormErr := p.GetForm(fallbackAuthRecord)
if getFormErr != nil {
return apis.NewBadRequestError(getFormErr.Error(), getFormErr)
}
if readErr := c.Bind(form); readErr != nil {
return apis.NewBadRequestError("An error occurred while loading the submitted data.", readErr)
}
record, authData, submitErr := form.Submit(func(createForm *pbForms.RecordUpsert, authRecord *models.Record, authUser *auth.AuthUser) error {
return createForm.DrySubmit(func(txDao *daos.Dao) error {
requestInfo := apis.RequestInfo(c)
requestInfo.Data = form.CreateData
createRuleFunc := func(q *dbx.SelectQuery) error {
admin, _ := c.Get(apis.ContextAdminKey).(*models.Admin)
if admin != nil {
return nil // either admin or the rule is empty
}
if collection.CreateRule == nil {
return errors.New("Only admins can create new accounts with OAuth2")
}
if *collection.CreateRule != "" {
resolver := resolvers.NewRecordFieldResolver(txDao, collection, requestInfo, true)
if expr, err := search.FilterData(*collection.CreateRule).BuildExpr(resolver); err != nil {
return err
} else {
if updateQueryError := resolver.UpdateQuery(q); updateQueryError != nil {
return updateQueryError
}
q.AndWhere(expr)
}
}
return nil
}
if _, err := txDao.FindRecordById(collection.Id, createForm.Id, createRuleFunc); err != nil {
return fmt.Errorf("Failed create rule constraint: %w", err)
}
return nil
})
})
if submitErr != nil {
return apis.NewBadRequestError("Failed to authenticate.", submitErr)
}
return apis.RecordAuthResponse(p.app, c, record, authData)
},
Middlewares: []echo.MiddlewareFunc{
apis.ActivityLogger(app),
},
})
return routeError
})
return p, nil
}