Skip to content

Instantly share code, notes, and snippets.

@guotie
Created September 11, 2016 00:48
Show Gist options
  • Save guotie/8f585bc00ae56cbefdae669e3bf765a9 to your computer and use it in GitHub Desktop.
Save guotie/8f585bc00ae56cbefdae669e3bf765a9 to your computer and use it in GitHub Desktop.
package user
import (
"fmt"
"regexp"
"strconv"
"time"
"dxmall/utils"
"github.com/jinzhu/gorm"
"github.com/smtc/glog"
"gopkg.in/redis.v3"
)
var (
allDigital = regexp.MustCompile(`^[0-9]*$`)
minPasswdLen = 6
NameOrPasswdInvalid = fmt.Errorf("username or password invalid")
EmptyUserPhone = fmt.Errorf("user phone is empty")
EmptyPassword = fmt.Errorf("password is emtpy")
PasswordTooShort = fmt.Errorf("password too short")
UserPhoneHasExist = fmt.Errorf("user phone has exist")
UserPhoneInvalid = fmt.Errorf("user phone invalid")
)
// 定义用户
//
type DxUser struct {
Id int64
UserName string `gorm:"not null;unique;size:40" json:"username"`
Passwd string `gorm:"not null;size:160" json:"passwd"`
UserPhone int64 `gorm:"not null;unique;size:40" json:"phone"`
RegIp string `gorm:"not null;size:40"` // 注册地址
Nickname string //昵称
IsDel bool
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func GetUser(db *gorm.DB, id int64) (*DxUser, error) {
var user DxUser
err := db.Where("id = ?", id).First(&user).Error
return &user, err
}
//
// 根据用户名查找用户
func GetUserByName(db *gorm.DB, name string) (*DxUser, error) {
var (
err error
user DxUser
)
if allDigital.Match([]byte(name)) {
err = db.Where("user_phone = ?", name).First(&user).Error
} else {
err = db.Where("user_name = ?", name).First(&user).Error
}
return &user, err
}
func GetOrCreateAndLogin(db *gorm.DB, phone, passwd, name, ipaddr string, areaid int) *DxUser {
user, err := GetUserByName(db, phone)
if err == gorm.ErrRecordNotFound {
user, _, _ = CreateUser(db, phone, passwd, name, ipaddr, areaid)
return user
}
return user
}
// 用户注册, 仅要求提供最简单的信息:
// phone, passwd 必须且不为空; name可以为空
// phone就是手机号码, 创建记录时, 当name为空时, name= "m" + phone
// ipaddr是用户的公网地址
//
// 1 检查手机号码是否存在
// 2 检查密码是否符合规范
//
func CreateUser(db *gorm.DB, phone, passwd, name, ipaddr string, areaid int) (*DxUser, int, error) {
if phone == "" {
return nil, utils.ERROR_EmptyUserPhone, EmptyUserPhone
}
if passwd == "" {
return nil, utils.ERROR_EmptyPassword, EmptyPassword
}
if len(passwd) < minPasswdLen {
return nil, utils.ERROR_PasswordTooShort, PasswordTooShort
}
user, err := GetUserByName(db, phone)
if err != gorm.ErrRecordNotFound {
return nil, utils.ERROR_UserPhoneHasExist, UserPhoneHasExist
}
if err = utils.ValidPhoneNo(phone); err != nil {
return nil, utils.ERROR_PhoneNoInvalid, err
}
if name != "" {
if err = utils.ValidUserName(name); err != nil {
return nil, utils.ERROR_UserNameInvalid, err
}
} else {
name = "m" + phone[0:3] + "****" + phone[len(phone)-4:len(phone)]
}
iphone, err := strconv.ParseInt(phone, 10, 64)
if err != nil {
return nil, utils.ERROR_PhoneNoInvalid, UserPhoneInvalid
}
// 填充资料
user = new(DxUser)
user.UserPhone = iphone
user.UserName = name
user.Passwd = utils.Createpasswd(passwd)
user.RegIp = ipaddr
user.Regtime = time.Now()
user.AreaId = areaid
// 创建
err = db.Create(user).Error
return user, utils.ERROR_CREATE_USER, err
}
// 如果name全为数字, 则把name当做手机号码
// authen user
// 认证用户身份
func AuthenUser(db *gorm.DB, name, passwd string) (*DxUser, error) {
user, err := GetUserByName(db, name)
if err != nil {
return nil, NameOrPasswdInvalid
}
// 验证成功
if utils.Checkpasswd(user.Passwd, passwd) {
return user, nil
}
glog.Error("AuthenUser: password invalid: username=%s password=%s\n", name, passwd)
return nil, NameOrPasswdInvalid
}
//
// 返回access token和refresh token
// token都保存在redis中
func (u *DxUser) GetTokens(rc *redis.Client, client *DxClient) (*AccessToken, string, error) {
token, err := GrantAccessToken(rc, client.Name, u.Id, client.AccessSeconds, "default")
if err != nil {
return nil, "", err
}
// 如果 refresh seconds 为 0, 直接返回!
if client.RefreshSeconds == 0 {
return token, "", err
}
rt, err := GrantRefreshToken(rc, client.Name, u.Id, client.RefreshSeconds, "default")
if err != nil {
return token, "", err
}
return token, rt.Token, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment