feat: Added Telegram auth module

This commit is contained in:
ptrcnull 2021-01-03 05:10:52 +01:00
parent 202b175a4a
commit f0baa5466e
2 changed files with 93 additions and 0 deletions

View file

@ -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 ""
}

View file

@ -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"`
}