- auth for weixin.
This commit is contained in:
@@ -1,25 +1,70 @@
|
||||
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状态不对"
|
||||
)
|
||||
|
||||
func GetUserInfo(code string, state string) (token *weixinsnsapi.UserInfo, err error) {
|
||||
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 {
|
||||
return wxapi.GetUserInfo(token.OpenID)
|
||||
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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user