From f0baa5466ed13b886cf40121525983fd7d57d8f7 Mon Sep 17 00:00:00 2001 From: ptrcnull Date: Sun, 3 Jan 2021 05:10:52 +0100 Subject: [PATCH] feat: Added Telegram auth module --- modules/auth/telegram/main.go | 77 ++++++++++++++++++++++++++++++++++ modules/auth/telegram/types.go | 16 +++++++ 2 files changed, 93 insertions(+) create mode 100644 modules/auth/telegram/main.go create mode 100644 modules/auth/telegram/types.go diff --git a/modules/auth/telegram/main.go b/modules/auth/telegram/main.go new file mode 100644 index 0000000..5e15185 --- /dev/null +++ b/modules/auth/telegram/main.go @@ -0,0 +1,77 @@ +package telegram + +import ( + "git.ddd.rip/ptrcnull/modweb" + "github.com/gofiber/fiber/v2" + "html/template" + "net/url" +) + +type Module struct { + BotID string + Origin string + Callback func(data *LoginData)*modweb.User +} + +func (m Module) FriendlyName() string { + return "Telegram Login" +} + +func (m Module) Name() string { + return "auth-telegram" +} + +func (m Module) Init(mm *modweb.ModuleManager) { + app := mm.Fiber() + app.Post("/callback", func(ctx *fiber.Ctx) error { + session := mm.Session(ctx) + defer session.Save() + + if session.Get("user") != nil { + return ctx.Status(200).JSON(fiber.Map{"ok": false}) + } + + var data LoginData + + err := ctx.BodyParser(&data) + if err != nil { + return err + } + + if data.Event != "auth_result" { + return ctx.Status(200).JSON(fiber.Map{"ok": false}) + } + + user := m.Callback(&data) + if user != nil { + user.Save(session) + } + + return ctx.Status(200).JSON(fiber.Map{"ok": true}) + }) +} + +func (m Module) Hidden() bool { + return true +} + +func (m Module) MinAccessLevel() int64 { + return -1 +} + +func (m Module) LoginURL() template.URL { + callback := "fetch('/auth-telegram/callback', { method: 'POST', body: ev.data, headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin' }).then(() => { window.location = '/' }).catch(alert)" + params := url.Values{} + params.Set("bot_id", m.BotID) + params.Set("origin", m.Origin) + destination := "https://oauth.telegram.org/auth?" + params.Encode() + return template.URL("javascript:(()=>{" + + "window.addEventListener('message',(ev)=>{" + callback + "});" + + "window.open('" + destination + "', '_blank')" + + "})()") +} + +func (m Module) RegisterURL() template.URL { + return "" +} + diff --git a/modules/auth/telegram/types.go b/modules/auth/telegram/types.go new file mode 100644 index 0000000..70fcb34 --- /dev/null +++ b/modules/auth/telegram/types.go @@ -0,0 +1,16 @@ +package telegram + +type LoginData struct { + Event string `json:"event"` + Result LoginDataResult `json:"result"` + Origin string `json:"origin"` +} + +type LoginDataResult struct { + ID int `json:"id"` + FirstName string `json:"first_name"` + Username string `json:"username"` + PhotoURL string `json:"photo_url"` + AuthDate int `json:"auth_date"` + Hash string `json:"hash"` +}