71 lines
1.6 KiB
Go
71 lines
1.6 KiB
Go
package weixin
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"git.rosy.net.cn/baseapi/platformapi/weixinsnsapi"
|
|
"git.rosy.net.cn/baseapi/utils"
|
|
"git.rosy.net.cn/jx-callback/business/jxcallback/auth"
|
|
"git.rosy.net.cn/jx-callback/globals"
|
|
"git.rosy.net.cn/jx-callback/globals/api"
|
|
)
|
|
|
|
const (
|
|
LoginType = "weixinsns"
|
|
DefTempPasswordDuration = 5 * time.Minute // 登录时间限制在5分钟内
|
|
)
|
|
|
|
var (
|
|
ErrLoginFailed = errors.New("登录失败")
|
|
StrStateIsWrong = "state:%s状态不对"
|
|
)
|
|
|
|
type Auther struct {
|
|
}
|
|
|
|
type UserInfoExt struct {
|
|
weixinsnsapi.UserInfo
|
|
TempPassword string `json:"tempPassword"` // 一段时间有效的登录密码
|
|
}
|
|
|
|
func init() {
|
|
auth.RegisterAuther(LoginType, new(Auther))
|
|
}
|
|
|
|
func GetUserInfo(code string, state string) (token *UserInfoExt, err error) {
|
|
if state == "" {
|
|
wxapi := weixinsnsapi.New(api.WeixinAPI.GetAppID(), api.WeixinAPI.GetSecret())
|
|
token, err2 := wxapi.RefreshToken(code)
|
|
if err = err2; err == nil {
|
|
wxUserinfo, err2 := wxapi.GetUserInfo(token.OpenID)
|
|
if err = err2; err == nil {
|
|
pwd := utils.GetUUID()
|
|
globals.Cacher.Set(wxUserinfo.OpenID, pwd, DefTempPasswordDuration)
|
|
return &UserInfoExt{
|
|
UserInfo: *wxUserinfo,
|
|
TempPassword: pwd,
|
|
}, nil
|
|
}
|
|
}
|
|
} else {
|
|
err = fmt.Errorf(StrStateIsWrong, state)
|
|
}
|
|
return nil, err
|
|
}
|
|
|
|
func (a *Auther) Login(openid, password string) error {
|
|
if value := globals.Cacher.Get(openid); value != nil {
|
|
if password == value.(string) {
|
|
globals.Cacher.Del(openid)
|
|
return nil
|
|
}
|
|
}
|
|
return ErrLoginFailed
|
|
}
|
|
|
|
func (a *Auther) Logout(openid string) error {
|
|
return globals.Cacher.Del(openid)
|
|
}
|