微信个人绑定状态复核前检查点
保存微信个人绑定后端、按实际收件账户推送和回归源码;前端未接入,回归用例未执行,尚未部署验收。
This commit is contained in:
1 parent
8104998417
commit
e79095d5f3
9 files changed
+981
-24
No files matched your search
@@ -102,11 +102,15 @@ type bulkTarget struct {
|
||||
// ConfigService 是插件全局 Secret 和用户设置的唯一写服务。
|
||||
// HTTP 路由在 CG-025 完成能力接入前不得直接暴露本服务的写方法。
|
||||
type ConfigService struct {
|
||||
engine *xorm.Engine
|
||||
vault *credential.Vault
|
||||
now func() time.Time
|
||||
ticketsMu sync.Mutex
|
||||
tickets map[string]pluginBulkTicket
|
||||
engine *xorm.Engine
|
||||
vault *credential.Vault
|
||||
now func() time.Time
|
||||
ticketsMu sync.Mutex
|
||||
tickets map[string]pluginBulkTicket
|
||||
bindingMu sync.Mutex
|
||||
wechatBindings map[string]weChatBinding
|
||||
weChatTestMu sync.Mutex
|
||||
weChatTestAttempts map[int]time.Time
|
||||
}
|
||||
|
||||
func NewConfigService(engine *xorm.Engine, vault *credential.Vault) (*ConfigService, error) {
|
||||
|
||||
@@ -91,6 +91,95 @@ func TestConfigServiceAllowsEmptyTelegramChatIDToDisablePush(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestEveryRoleKeepsIndependentOwnWeChatSettings(t *testing.T) {
|
||||
service, engine := newPluginConfigService(t)
|
||||
for _, role := range []access.Role{access.RoleSuperAdmin, access.RoleAdmin, access.RoleUser} {
|
||||
t.Run(string(role), func(t *testing.T) {
|
||||
user := insertPluginTestUser(t, engine, "wechat-"+string(role), role)
|
||||
status, err := service.GetOwnWeChatSettings(user.ID)
|
||||
if err != nil || status.Settings.OpenID != "" || status.Version != 0 {
|
||||
t.Fatalf("角色=%s,不应自动继承系统接收人:%v", role, err)
|
||||
}
|
||||
if _, err := service.UpdateOwnWeChatPreferences(user.ID, true, false, false, 0); !errors.Is(err, ErrWeChatBinding) {
|
||||
t.Fatal("未绑定身份时不应直接启用微信推送")
|
||||
}
|
||||
settings := WeChatUserSettings{AppID: "wx-test-application", OpenID: "openid-" + string(role), Enabled: true}
|
||||
status, err = service.saveWeChatSettings(user.ID, settings, 0)
|
||||
if err != nil || status.Settings != settings || status.Version != 1 {
|
||||
t.Fatalf("角色=%s,保存独立接收人失败:%v", role, err)
|
||||
}
|
||||
record, found, err := service.findUserSetting(weChatPluginID, user.ID)
|
||||
if err != nil || !found || record.SettingsCiphertext == "" || record.SettingsCiphertext == settings.OpenID {
|
||||
t.Fatal("微信个人身份必须加密保存")
|
||||
}
|
||||
if _, err := service.UpdateOwnWeChatPreferences(user.ID, false, false, false, 0); !errors.Is(err, ErrPluginSettingConflict) {
|
||||
t.Fatal("旧版本不应覆盖绑定设置")
|
||||
}
|
||||
status, err = service.UpdateOwnWeChatPreferences(user.ID, false, false, false, 1)
|
||||
if err != nil || status.Settings.OpenID != settings.OpenID || status.Settings.Enabled {
|
||||
t.Fatal("停用推送应保留本人绑定")
|
||||
}
|
||||
status, err = service.UpdateOwnWeChatPreferences(user.ID, false, false, true, 2)
|
||||
if err != nil || status.Settings.OpenID != "" || status.Settings.Enabled || status.Version != 3 {
|
||||
t.Fatal("解绑应清除本人接收身份")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWeChatBindingStatusRejectsOtherSessionsAndRevokedAccounts(t *testing.T) {
|
||||
service, engine := newPluginConfigService(t)
|
||||
user := insertPluginTestUser(t, engine, "wechat-binding", access.RoleSuperAdmin)
|
||||
other := insertPluginTestUser(t, engine, "wechat-other", access.RoleUser)
|
||||
actor := NotificationBindingActor{UserID: user.ID, SessionVersion: user.SessionVersion,
|
||||
SecurityVersion: user.SecurityVersion, SessionHash: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"}
|
||||
now := time.Now().UTC()
|
||||
service.now = func() time.Time { return now }
|
||||
service.wechatBindings = map[string]weChatBinding{"ticket": {Actor: actor, Status: WeChatBindingStatus{Phase: "waiting", ExpiresAt: now.Add(time.Minute)}}}
|
||||
if _, err := service.GetWeChatBinding(actor, "ticket"); err != nil {
|
||||
t.Fatalf("本人会话应能读取绑定状态:%v", err)
|
||||
}
|
||||
otherActor := actor
|
||||
otherActor.UserID = other.ID
|
||||
if _, err := service.GetWeChatBinding(otherActor, "ticket"); !errors.Is(err, ErrWeChatBinding) {
|
||||
t.Fatal("其他账户不应读取绑定请求")
|
||||
}
|
||||
otherActor = actor
|
||||
otherActor.SessionHash = "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789"
|
||||
if _, err := service.GetWeChatBinding(otherActor, "ticket"); !errors.Is(err, ErrWeChatBinding) {
|
||||
t.Fatal("同一账户的其他会话不应接管绑定")
|
||||
}
|
||||
now = now.Add(2 * time.Minute)
|
||||
if _, err := service.GetWeChatBinding(actor, "ticket"); !errors.Is(err, ErrWeChatBinding) {
|
||||
t.Fatal("过期绑定不应继续使用")
|
||||
}
|
||||
now = now.Add(-2 * time.Minute)
|
||||
if _, err := engine.ID(user.ID).Cols("disabled").Update(&models.User{Disabled: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := service.GetWeChatBinding(actor, "ticket"); !errors.Is(err, ErrWeChatBinding) {
|
||||
t.Fatal("被禁用账户的绑定必须立即失效")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWeChatTestMessagesAreRateLimitedPerAccount(t *testing.T) {
|
||||
service, engine := newPluginConfigService(t)
|
||||
first := insertPluginTestUser(t, engine, "wechat-rate-first", access.RoleUser)
|
||||
second := insertPluginTestUser(t, engine, "wechat-rate-second", access.RoleUser)
|
||||
now := time.Now().UTC()
|
||||
service.now = func() time.Time { return now }
|
||||
if service.ReserveWeChatTest(first.ID) != nil || service.ReserveWeChatTest(second.ID) != nil {
|
||||
t.Fatal("不同账户首次测试应相互独立")
|
||||
}
|
||||
if service.ReserveWeChatTest(first.ID) == nil {
|
||||
t.Fatal("短时间内不应重复发送测试消息")
|
||||
}
|
||||
now = now.Add(30 * time.Second)
|
||||
if err := service.ReserveWeChatTest(first.ID); err != nil {
|
||||
t.Fatalf("冷却结束后应允许重试:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEveryRoleKeepsIndependentOwnTelegramSettings(t *testing.T) {
|
||||
service, engine := newPluginConfigService(t)
|
||||
var users []models.User
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
"git.pcux.cn/xuans/Smail/utils/credential"
|
||||
)
|
||||
|
||||
const WeChatCallbackPath = "/api/v1/plugin/binding/wechat/callback"
|
||||
|
||||
// NotificationBindingActor 将绑定限制在发起扫码的登录会话,角色不影响本人绑定。
|
||||
type NotificationBindingActor struct {
|
||||
UserID int
|
||||
SessionVersion int
|
||||
SecurityVersion int
|
||||
SessionHash string
|
||||
}
|
||||
|
||||
type WeChatBindingStatus struct {
|
||||
Ticket string `json:"ticket,omitempty"`
|
||||
URL string `json:"url,omitempty"`
|
||||
Phase string `json:"phase"`
|
||||
DisplayName string `json:"displayName,omitempty"`
|
||||
ExpiresAt time.Time `json:"expiresAt"`
|
||||
}
|
||||
|
||||
type weChatBinding struct {
|
||||
Actor NotificationBindingActor
|
||||
Version uint64
|
||||
Fingerprint string
|
||||
Settings WeChatUserSettings
|
||||
Status WeChatBindingStatus
|
||||
}
|
||||
|
||||
type weChatBindingConfig struct {
|
||||
AppID string
|
||||
Secret string
|
||||
Callback string
|
||||
Fingerprint string
|
||||
}
|
||||
|
||||
func (s *ConfigService) weChatConfiguration() (weChatBindingConfig, error) {
|
||||
var result weChatBindingConfig
|
||||
manager := config.CurrentManager()
|
||||
current := config.CurrentConfig()
|
||||
if manager == nil || current == nil {
|
||||
return result, WeChatNotice("请联系超级管理员配置微信公众号")
|
||||
}
|
||||
instance, exists := manager.Snapshot().Plugins.Plugins[weChatPluginID]
|
||||
if !exists || !instance.Enabled {
|
||||
return result, WeChatNotice("请联系超级管理员配置并启用微信公众号")
|
||||
}
|
||||
var settings struct {
|
||||
AppID string `json:"appId"`
|
||||
TemplateID string `json:"templateId"`
|
||||
WebDomain string `json:"webDomain"`
|
||||
}
|
||||
if json.Unmarshal(instance.Settings, &settings) != nil || !validWeChatIdentity(settings.AppID) || settings.TemplateID == "" {
|
||||
return result, WeChatNotice("请联系超级管理员补全微信公众号配置")
|
||||
}
|
||||
domain := strings.TrimSpace(current.WebDomain)
|
||||
parsed, err := url.Parse("https://" + domain)
|
||||
if err != nil || domain == "" || parsed.Host != domain || parsed.User != nil || parsed.Path != "" ||
|
||||
parsed.RawQuery != "" || parsed.Fragment != "" || !strings.EqualFold(settings.WebDomain, domain) {
|
||||
return result, WeChatNotice("公众号授权域名与后台域名不一致,请联系超级管理员")
|
||||
}
|
||||
secret, err := s.openSecretForPlugin(weChatPluginID, "appSecret")
|
||||
if err != nil || secret == "" {
|
||||
return result, WeChatNotice("请联系超级管理员配置微信公众号密钥")
|
||||
}
|
||||
fingerprint, err := s.vault.Fingerprint(settings.AppID + "\x00" + secret + "\x00" + domain)
|
||||
if err != nil {
|
||||
return result, ErrPluginStoreUnavailable
|
||||
}
|
||||
return weChatBindingConfig{AppID: settings.AppID, Secret: secret, Callback: "https://" + domain + WeChatCallbackPath, Fingerprint: fingerprint}, nil
|
||||
}
|
||||
|
||||
func (s *ConfigService) WeChatBindingAvailability() (bool, string) {
|
||||
if _, err := s.weChatConfiguration(); err != nil {
|
||||
return false, err.Error()
|
||||
}
|
||||
return true, ""
|
||||
}
|
||||
|
||||
func (s *ConfigService) validateBindingActor(actor NotificationBindingActor) error {
|
||||
user, err := s.activeNotificationUser(actor.UserID)
|
||||
if err != nil || len(actor.SessionHash) != 64 || user.SessionVersion != actor.SessionVersion || user.SecurityVersion != actor.SecurityVersion {
|
||||
return ErrWeChatBinding
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ConfigService) BeginWeChatBinding(actor NotificationBindingActor) (WeChatBindingStatus, error) {
|
||||
if err := s.validateBindingActor(actor); err != nil {
|
||||
return WeChatBindingStatus{}, err
|
||||
}
|
||||
configuration, err := s.weChatConfiguration()
|
||||
if err != nil {
|
||||
return WeChatBindingStatus{}, err
|
||||
}
|
||||
current, err := s.GetOwnWeChatSettings(actor.UserID)
|
||||
if err != nil {
|
||||
return WeChatBindingStatus{}, err
|
||||
}
|
||||
var nonce [32]byte
|
||||
if _, err := rand.Read(nonce[:]); err != nil {
|
||||
return WeChatBindingStatus{}, ErrPluginStoreUnavailable
|
||||
}
|
||||
ticket := base64.RawURLEncoding.EncodeToString(nonce[:])
|
||||
now := s.currentTime()
|
||||
status := WeChatBindingStatus{Ticket: ticket, Phase: "waiting", ExpiresAt: now.Add(5 * time.Minute)}
|
||||
s.bindingMu.Lock()
|
||||
defer s.bindingMu.Unlock()
|
||||
if s.wechatBindings == nil {
|
||||
s.wechatBindings = make(map[string]weChatBinding)
|
||||
}
|
||||
for key, binding := range s.wechatBindings {
|
||||
if !binding.Status.ExpiresAt.After(now) || binding.Actor.UserID == actor.UserID {
|
||||
delete(s.wechatBindings, key)
|
||||
}
|
||||
}
|
||||
if len(s.wechatBindings) >= 2048 {
|
||||
return WeChatBindingStatus{}, WeChatNotice("当前绑定请求较多,请稍后重试")
|
||||
}
|
||||
s.wechatBindings[ticket] = weChatBinding{Actor: actor, Version: current.Version, Fingerprint: configuration.Fingerprint, Status: status}
|
||||
query := url.Values{"appid": {configuration.AppID}, "redirect_uri": {configuration.Callback},
|
||||
"response_type": {"code"}, "scope": {"snsapi_userinfo"}, "state": {ticket}}
|
||||
status.URL = "https://open.weixin.qq.com/connect/oauth2/authorize?" + query.Encode() + "#wechat_redirect"
|
||||
return status, nil
|
||||
}
|
||||
|
||||
func (s *ConfigService) GetWeChatBinding(actor NotificationBindingActor, ticket string) (WeChatBindingStatus, error) {
|
||||
if err := s.validateBindingActor(actor); err != nil {
|
||||
return WeChatBindingStatus{}, err
|
||||
}
|
||||
s.bindingMu.Lock()
|
||||
defer s.bindingMu.Unlock()
|
||||
binding, found := s.wechatBindings[ticket]
|
||||
if !found || binding.Actor != actor || !binding.Status.ExpiresAt.After(s.currentTime()) {
|
||||
return WeChatBindingStatus{}, ErrWeChatBinding
|
||||
}
|
||||
return binding.Status, nil
|
||||
}
|
||||
|
||||
func (s *ConfigService) CancelWeChatBinding(actor NotificationBindingActor, ticket string) error {
|
||||
if _, err := s.GetWeChatBinding(actor, ticket); err != nil {
|
||||
return err
|
||||
}
|
||||
s.bindingMu.Lock()
|
||||
delete(s.wechatBindings, ticket)
|
||||
s.bindingMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// ClaimWeChatBinding 只认领一次外部身份,不直接写入个人设置;仍需原页面确认。
|
||||
func (s *ConfigService) ClaimWeChatBinding(ctx context.Context, ticket, code string) error {
|
||||
if s == nil || len(ticket) != 43 || code == "" || len(code) > 512 {
|
||||
return ErrWeChatBinding
|
||||
}
|
||||
s.bindingMu.Lock()
|
||||
binding, found := s.wechatBindings[ticket]
|
||||
if !found || binding.Status.Phase != "waiting" || !binding.Status.ExpiresAt.After(s.currentTime()) {
|
||||
s.bindingMu.Unlock()
|
||||
return ErrWeChatBinding
|
||||
}
|
||||
binding.Status.Phase = "processing"
|
||||
s.wechatBindings[ticket] = binding
|
||||
s.bindingMu.Unlock()
|
||||
accepted := false
|
||||
defer func() {
|
||||
if !accepted {
|
||||
s.bindingMu.Lock()
|
||||
delete(s.wechatBindings, ticket)
|
||||
s.bindingMu.Unlock()
|
||||
}
|
||||
}()
|
||||
if err := s.validateBindingActor(binding.Actor); err != nil {
|
||||
return err
|
||||
}
|
||||
configuration, err := s.weChatConfiguration()
|
||||
if err != nil || configuration.Fingerprint != binding.Fingerprint {
|
||||
return ErrWeChatBinding
|
||||
}
|
||||
var token struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
OpenID string `json:"openid"`
|
||||
ErrorCode int `json:"errcode"`
|
||||
}
|
||||
if err := requestWeChatBindingJSON(ctx, "/sns/oauth2/access_token", url.Values{
|
||||
"appid": {configuration.AppID}, "secret": {configuration.Secret}, "code": {code}, "grant_type": {"authorization_code"},
|
||||
}, &token); err != nil || token.ErrorCode != 0 || !validWeChatIdentity(token.OpenID) || token.AccessToken == "" || len(token.AccessToken) > 4096 {
|
||||
return WeChatNotice("微信授权失败,请重新扫码")
|
||||
}
|
||||
var profile struct {
|
||||
OpenID string `json:"openid"`
|
||||
Nickname string `json:"nickname"`
|
||||
ErrorCode int `json:"errcode"`
|
||||
}
|
||||
if err := requestWeChatBindingJSON(ctx, "/sns/userinfo", url.Values{
|
||||
"access_token": {token.AccessToken}, "openid": {token.OpenID}, "lang": {"zh_CN"},
|
||||
}, &profile); err != nil || profile.ErrorCode != 0 || profile.OpenID != token.OpenID || len(profile.Nickname) > 256 {
|
||||
return WeChatNotice("微信身份读取失败,请重新扫码")
|
||||
}
|
||||
binding.Settings = WeChatUserSettings{AppID: configuration.AppID, OpenID: token.OpenID, DisplayName: profile.Nickname, Enabled: true}
|
||||
binding.Status.Phase = "claimed"
|
||||
binding.Status.DisplayName = profile.Nickname
|
||||
if binding.Status.DisplayName == "" {
|
||||
binding.Status.DisplayName = "微信用户 · " + token.OpenID[len(token.OpenID)-6:]
|
||||
}
|
||||
s.bindingMu.Lock()
|
||||
defer s.bindingMu.Unlock()
|
||||
if current, exists := s.wechatBindings[ticket]; !exists || current.Status.Phase != "processing" || !current.Status.ExpiresAt.After(s.currentTime()) {
|
||||
return ErrWeChatBinding
|
||||
}
|
||||
s.wechatBindings[ticket] = binding
|
||||
accepted = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ConfigService) ConfirmWeChatBinding(actor NotificationBindingActor, ticket string) (WeChatUserSettingsStatus, error) {
|
||||
if err := s.validateBindingActor(actor); err != nil {
|
||||
return WeChatUserSettingsStatus{}, err
|
||||
}
|
||||
configuration, err := s.weChatConfiguration()
|
||||
if err != nil {
|
||||
return WeChatUserSettingsStatus{}, err
|
||||
}
|
||||
s.bindingMu.Lock()
|
||||
defer s.bindingMu.Unlock()
|
||||
binding, found := s.wechatBindings[ticket]
|
||||
if !found || binding.Actor != actor || binding.Status.Phase != "claimed" ||
|
||||
!binding.Status.ExpiresAt.After(s.currentTime()) || binding.Fingerprint != configuration.Fingerprint {
|
||||
return WeChatUserSettingsStatus{}, ErrWeChatBinding
|
||||
}
|
||||
delete(s.wechatBindings, ticket)
|
||||
return s.saveWeChatSettings(actor.UserID, binding.Settings, binding.Version)
|
||||
}
|
||||
|
||||
func (s *ConfigService) ReserveWeChatTest(userID int) error {
|
||||
if _, err := s.activeNotificationUser(userID); err != nil {
|
||||
return err
|
||||
}
|
||||
s.weChatTestMu.Lock()
|
||||
defer s.weChatTestMu.Unlock()
|
||||
now := s.currentTime()
|
||||
if s.weChatTestAttempts == nil {
|
||||
s.weChatTestAttempts = make(map[int]time.Time)
|
||||
}
|
||||
for id, last := range s.weChatTestAttempts {
|
||||
if now.Sub(last) >= 30*time.Second {
|
||||
delete(s.weChatTestAttempts, id)
|
||||
}
|
||||
}
|
||||
if _, exists := s.weChatTestAttempts[userID]; exists || len(s.weChatTestAttempts) >= 4096 {
|
||||
return WeChatNotice("测试消息发送过于频繁,请三十秒后重试")
|
||||
}
|
||||
s.weChatTestAttempts[userID] = now
|
||||
return nil
|
||||
}
|
||||
|
||||
func requestWeChatBindingJSON(ctx context.Context, path string, query url.Values, target any) error {
|
||||
client := credential.NewRestrictedHTTPClientForTargets(10_000, []credential.NetworkTarget{{Scheme: "https", Host: "api.weixin.qq.com", Port: 443}})
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.weixin.qq.com"+path+"?"+query.Encode(), nil)
|
||||
if err != nil {
|
||||
return ErrWeChatBinding
|
||||
}
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
return ErrWeChatBinding
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return ErrWeChatBinding
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(response.Body, (64<<10)+1))
|
||||
if err != nil || len(data) > 64<<10 || json.Unmarshal(data, target) != nil {
|
||||
return ErrWeChatBinding
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
"git.pcux.cn/xuans/Smail/services/access"
|
||||
"git.pcux.cn/xuans/Smail/utils/credential"
|
||||
)
|
||||
|
||||
const weChatPluginID = "wechat_push"
|
||||
|
||||
var ErrWeChatBinding = errors.New("微信绑定已失效,请重新扫码")
|
||||
|
||||
// WeChatNotice 仅承载可公开的固定业务提示,数据库和外部请求错误不得使用此类型。
|
||||
type WeChatNotice string
|
||||
|
||||
func (notice WeChatNotice) Error() string { return string(notice) }
|
||||
|
||||
// WeChatUserSettings 只通过已验证的扫码流程写入接收身份,不接受页面直接指定 OpenID。
|
||||
type WeChatUserSettings struct {
|
||||
AppID string `json:"appId"`
|
||||
OpenID string `json:"openId"`
|
||||
DisplayName string `json:"displayName"`
|
||||
Enabled bool `json:"enabled"`
|
||||
ShowContent bool `json:"showContent"`
|
||||
}
|
||||
|
||||
type WeChatUserSettingsStatus struct {
|
||||
Settings WeChatUserSettings
|
||||
Version uint64
|
||||
}
|
||||
|
||||
type WeChatUserSettingsEntry struct {
|
||||
UserID int
|
||||
Settings WeChatUserSettings
|
||||
}
|
||||
|
||||
func (s *ConfigService) activeNotificationUser(userID int) (models.User, error) {
|
||||
if s == nil || s.engine == nil || s.vault == nil || userID <= 0 {
|
||||
return models.User{}, ErrPluginStoreUnavailable
|
||||
}
|
||||
user, found, err := s.findUser(userID)
|
||||
if err != nil || !found || user.Disabled != 0 {
|
||||
return models.User{}, ErrPluginStoreUnavailable
|
||||
}
|
||||
if err := access.Authorize(access.Request{ActorRole: user.EffectiveRole(), Capability: access.CapabilityPluginWriteOwn, OwnResource: true}); err != nil {
|
||||
return models.User{}, err
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *ConfigService) GetOwnWeChatSettings(userID int) (WeChatUserSettingsStatus, error) {
|
||||
if _, err := s.activeNotificationUser(userID); err != nil {
|
||||
return WeChatUserSettingsStatus{}, err
|
||||
}
|
||||
record, found, err := s.findUserSetting(weChatPluginID, userID)
|
||||
if err != nil || !found {
|
||||
return WeChatUserSettingsStatus{}, err
|
||||
}
|
||||
settings, err := s.decodeWeChatSettings(record)
|
||||
return WeChatUserSettingsStatus{Settings: settings, Version: record.Version}, err
|
||||
}
|
||||
|
||||
func (s *ConfigService) decodeWeChatSettings(record models.PluginUserSetting) (WeChatUserSettings, error) {
|
||||
var settings WeChatUserSettings
|
||||
if record.SchemaVersion != userSettingsSchemaVersion {
|
||||
return settings, ErrPluginStoreUnavailable
|
||||
}
|
||||
plaintext, err := s.vault.Decrypt(credential.CurrentVersion, record.SettingsCiphertext)
|
||||
if err != nil {
|
||||
return settings, ErrPluginStoreUnavailable
|
||||
}
|
||||
fingerprint, err := s.vault.Fingerprint(plaintext)
|
||||
if err != nil || fingerprint != record.SettingsHash || !json.Valid([]byte(plaintext)) {
|
||||
return settings, ErrPluginStoreUnavailable
|
||||
}
|
||||
decoder := json.NewDecoder(strings.NewReader(plaintext))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&settings); err != nil || !validWeChatSettings(settings) {
|
||||
return WeChatUserSettings{}, ErrPluginStoreUnavailable
|
||||
}
|
||||
return settings, nil
|
||||
}
|
||||
|
||||
func validWeChatIdentity(value string) bool {
|
||||
if len(value) < 8 || len(value) > 128 {
|
||||
return false
|
||||
}
|
||||
for _, char := range value {
|
||||
if !(char >= 'a' && char <= 'z' || char >= 'A' && char <= 'Z' || char >= '0' && char <= '9' || char == '-' || char == '_') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func validWeChatSettings(settings WeChatUserSettings) bool {
|
||||
if len(settings.DisplayName) > 256 {
|
||||
return false
|
||||
}
|
||||
if settings.OpenID == "" {
|
||||
return settings.AppID == "" && !settings.Enabled
|
||||
}
|
||||
return validWeChatIdentity(settings.OpenID) && validWeChatIdentity(settings.AppID)
|
||||
}
|
||||
|
||||
func (s *ConfigService) saveWeChatSettings(userID int, settings WeChatUserSettings, expectedVersion uint64) (WeChatUserSettingsStatus, error) {
|
||||
if _, err := s.activeNotificationUser(userID); err != nil {
|
||||
return WeChatUserSettingsStatus{}, err
|
||||
}
|
||||
if !validWeChatSettings(settings) {
|
||||
return WeChatUserSettingsStatus{}, ErrWeChatBinding
|
||||
}
|
||||
payload, err := json.Marshal(settings)
|
||||
if err != nil {
|
||||
return WeChatUserSettingsStatus{}, ErrPluginStoreUnavailable
|
||||
}
|
||||
ciphertext, err := s.vault.Encrypt(string(payload))
|
||||
if err != nil {
|
||||
return WeChatUserSettingsStatus{}, ErrPluginStoreUnavailable
|
||||
}
|
||||
fingerprint, err := s.vault.Fingerprint(string(payload))
|
||||
if err != nil {
|
||||
return WeChatUserSettingsStatus{}, ErrPluginStoreUnavailable
|
||||
}
|
||||
current, found, err := s.findUserSetting(weChatPluginID, userID)
|
||||
if err != nil {
|
||||
return WeChatUserSettingsStatus{}, err
|
||||
}
|
||||
if current.Version != expectedVersion || !found && expectedVersion != 0 {
|
||||
return WeChatUserSettingsStatus{}, ErrPluginSettingConflict
|
||||
}
|
||||
now := s.currentTime()
|
||||
record := models.PluginUserSetting{PluginID: weChatPluginID, UserID: userID, SchemaVersion: userSettingsSchemaVersion,
|
||||
SettingsCiphertext: ciphertext, SettingsHash: fingerprint, Enabled: true, Version: expectedVersion + 1, CreatedAt: now, UpdatedAt: now}
|
||||
if !found {
|
||||
if _, err := s.engine.Insert(&record); err != nil {
|
||||
return WeChatUserSettingsStatus{}, ErrPluginSettingConflict
|
||||
}
|
||||
} else {
|
||||
changed, err := s.engine.ID(current.ID).Where("version = ?", expectedVersion).
|
||||
Cols("schema_version", "settings_ciphertext", "settings_hash", "enabled", "version", "updated_at").Update(&record)
|
||||
if err != nil || changed != 1 {
|
||||
return WeChatUserSettingsStatus{}, ErrPluginSettingConflict
|
||||
}
|
||||
}
|
||||
return WeChatUserSettingsStatus{Settings: settings, Version: record.Version}, nil
|
||||
}
|
||||
|
||||
func (s *ConfigService) UpdateOwnWeChatPreferences(userID int, enabled, showContent, unbind bool, expectedVersion uint64) (WeChatUserSettingsStatus, error) {
|
||||
current, err := s.GetOwnWeChatSettings(userID)
|
||||
if err != nil {
|
||||
return current, err
|
||||
}
|
||||
settings := current.Settings
|
||||
if unbind {
|
||||
settings = WeChatUserSettings{}
|
||||
} else {
|
||||
settings.Enabled, settings.ShowContent = enabled, showContent
|
||||
}
|
||||
return s.saveWeChatSettings(userID, settings, expectedVersion)
|
||||
}
|
||||
|
||||
func (s *ConfigService) ListWeChatUserSettings() ([]WeChatUserSettingsEntry, error) {
|
||||
if s == nil || s.engine == nil || s.vault == nil {
|
||||
return nil, ErrPluginStoreUnavailable
|
||||
}
|
||||
var records []models.PluginUserSetting
|
||||
if err := s.engine.Where("plugin_id = ? AND enabled = ?", weChatPluginID, true).Find(&records); err != nil {
|
||||
return nil, ErrPluginStoreUnavailable
|
||||
}
|
||||
entries := make([]WeChatUserSettingsEntry, 0, len(records))
|
||||
for _, record := range records {
|
||||
user, found, err := s.findUser(record.UserID)
|
||||
if err != nil {
|
||||
return nil, ErrPluginStoreUnavailable
|
||||
}
|
||||
if !found || user.Disabled != 0 {
|
||||
continue
|
||||
}
|
||||
settings, err := s.decodeWeChatSettings(record)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
entries = append(entries, WeChatUserSettingsEntry{UserID: record.UserID, Settings: settings})
|
||||
}
|
||||
return entries, nil
|
||||
}
|
||||
Reference in new issue
Block a user