mindoc/models/Member.go

584 lines
16 KiB
Go
Raw Normal View History

2017-04-20 18:19:32 +08:00
// Package models .
package models
2017-04-21 18:20:35 +08:00
import (
2019-05-21 10:09:37 +08:00
"crypto/md5"
"encoding/hex"
"encoding/json"
2017-05-03 14:22:05 +08:00
"errors"
2017-05-24 20:31:58 +08:00
"fmt"
"io/ioutil"
"net/http"
"net/url"
2017-05-03 14:22:05 +08:00
"regexp"
2019-05-21 10:09:37 +08:00
"strconv"
2017-05-03 14:22:05 +08:00
"strings"
2017-05-24 20:31:58 +08:00
"time"
"gopkg.in/ldap.v2"
2017-05-24 20:31:58 +08:00
"math"
"github.com/beego/beego/v2/client/orm"
"github.com/beego/beego/v2/core/logs"
"github.com/beego/beego/v2/server/web"
"github.com/mindoc-org/mindoc/conf"
"github.com/mindoc-org/mindoc/utils"
2017-04-21 18:20:35 +08:00
)
2017-04-20 18:19:32 +08:00
type Member struct {
2017-05-24 20:31:58 +08:00
MemberId int `orm:"pk;auto;unique;column(member_id)" json:"member_id"`
Account string `orm:"size(100);unique;column(account)" json:"account"`
2018-11-05 18:50:01 +08:00
RealName string `orm:"size(255);column(real_name)" json:"real_name"`
2017-05-24 20:31:58 +08:00
Password string `orm:"size(1000);column(password)" json:"-"`
//认证方式: local 本地数据库 /ldap LDAP
AuthMethod string `orm:"column(auth_method);default(local);size(50);" json:"auth_method"`
2017-05-24 20:31:58 +08:00
Description string `orm:"column(description);size(2000)" json:"description"`
Email string `orm:"size(100);column(email);unique" json:"email"`
Phone string `orm:"size(255);column(phone);null;default(null)" json:"phone"`
Avatar string `orm:"size(1000);column(avatar)" json:"avatar"`
//用户角色0 超级管理员 /1 管理员/ 2 普通用户 .
2018-11-05 18:50:01 +08:00
Role conf.SystemRole `orm:"column(role);type(int);default(1);index" json:"role"`
RoleName string `orm:"-" json:"role_name"`
Status int `orm:"column(status);type(int);default(0)" json:"status"` //用户状态0 正常/1 禁用
CreateTime time.Time `orm:"type(datetime);column(create_time);auto_now_add" json:"create_time"`
CreateAt int `orm:"type(int);column(create_at)" json:"create_at"`
LastLoginTime time.Time `orm:"type(datetime);column(last_login_time);null" json:"last_login_time"`
2017-04-21 18:20:35 +08:00
}
// TableName 获取对应数据库表名.
func (m *Member) TableName() string {
return "members"
}
2017-05-24 20:31:58 +08:00
2017-04-21 18:20:35 +08:00
// TableEngine 获取数据使用的引擎.
func (m *Member) TableEngine() string {
return "INNODB"
}
2017-05-24 20:31:58 +08:00
func (m *Member) TableNameWithPrefix() string {
return conf.GetDatabasePrefix() + m.TableName()
2017-04-22 17:24:17 +08:00
}
2017-04-21 18:20:35 +08:00
func NewMember() *Member {
return &Member{}
}
// Login 用户登录.
2017-05-24 20:31:58 +08:00
func (m *Member) Login(account string, password string) (*Member, error) {
2017-04-21 18:20:35 +08:00
o := orm.NewOrm()
member := &Member{}
2018-09-11 16:08:07 +08:00
//err := o.QueryTable(m.TableNameWithPrefix()).Filter("account", account).Filter("status", 0).One(member)
2018-11-05 18:50:01 +08:00
err := o.Raw("select * from md_members where (account = ? or email = ?) and status = 0 limit 1;", account, account).QueryRow(member)
2017-04-21 18:20:35 +08:00
if err != nil {
if web.AppConfig.DefaultBool("ldap_enable", false) {
logs.Info("转入LDAP登陆 ->", account)
2017-05-24 20:31:58 +08:00
return member.ldapLogin(account, password)
} else if url, err := web.AppConfig.String("http_login_url"); url != "" {
logs.Info("转入 HTTP 接口登陆 ->", account)
return member.httpLogin(account, password)
2017-05-24 20:31:58 +08:00
} else {
logs.Error("user login for `%s`: %s", account, err)
2017-05-24 20:31:58 +08:00
return member, ErrMemberNoExist
}
}
switch member.AuthMethod {
case "":
2017-05-24 20:31:58 +08:00
case "local":
ok, err := utils.PasswordVerify(member.Password, password)
if ok && err == nil {
m.ResolveRoleName()
return member, nil
}
case "ldap":
return member.ldapLogin(account, password)
case "http":
return member.httpLogin(account, password)
2017-05-24 20:31:58 +08:00
default:
return member, ErrMemberAuthMethodInvalid
2017-04-21 18:20:35 +08:00
}
2017-05-24 20:31:58 +08:00
return member, ErrorMemberPasswordError
}
2017-04-21 18:20:35 +08:00
2021-03-19 10:33:59 +08:00
// TmpLogin 用于钉钉临时登录
func (m *Member) TmpLogin(account string) (*Member, error) {
o := orm.NewOrm()
member := &Member{}
err := o.Raw("select * from md_members where account = ? and status = 0 limit 1;", account).QueryRow(member)
if err != nil {
return member, ErrorMemberPasswordError
}
return member, nil
}
2017-05-24 20:31:58 +08:00
//ldapLogin 通过LDAP登陆
func (m *Member) ldapLogin(account string, password string) (*Member, error) {
if web.AppConfig.DefaultBool("ldap_enable", false) {
2017-05-24 20:31:58 +08:00
return m, ErrMemberAuthMethodInvalid
}
var err error
ldaphost, _ := web.AppConfig.String("ldap_host")
lc, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", ldaphost, web.AppConfig.DefaultInt("ldap_port", 3268)))
2017-05-24 20:31:58 +08:00
if err != nil {
logs.Error("绑定 LDAP 用户失败 ->", err)
2017-05-24 20:31:58 +08:00
return m, ErrLDAPConnect
}
defer lc.Close()
ldapuser, _ := web.AppConfig.String("ldap_user")
ldappass, _ := web.AppConfig.String("ldap_password")
err = lc.Bind(ldapuser, ldappass)
2017-05-24 20:31:58 +08:00
if err != nil {
logs.Error("绑定 LDAP 用户失败 ->", err)
2017-05-24 20:31:58 +08:00
return m, ErrLDAPFirstBind
}
ldapbase, _ := web.AppConfig.String("ldap_base")
ldapfilter, _ := web.AppConfig.String("ldap_filter")
ldapattr, _ := web.AppConfig.String("ldap_attribute")
2017-05-24 20:31:58 +08:00
searchRequest := ldap.NewSearchRequest(
ldapbase,
2017-05-24 20:31:58 +08:00
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
//修改objectClass通过配置文件获取值
fmt.Sprintf("(&(%s)(%s=%s))", ldapfilter, ldapattr, account),
2017-05-24 20:31:58 +08:00
[]string{"dn", "mail"},
nil,
)
searchResult, err := lc.Search(searchRequest)
if err != nil {
logs.Error("绑定 LDAP 用户失败 ->", err)
2017-05-24 20:31:58 +08:00
return m, ErrLDAPSearch
}
if len(searchResult.Entries) != 1 {
return m, ErrLDAPUserNotFoundOrTooMany
}
userdn := searchResult.Entries[0].DN
err = lc.Bind(userdn, password)
if err != nil {
logs.Error("绑定 LDAP 用户失败 ->", err)
2017-05-24 20:31:58 +08:00
return m, ErrorMemberPasswordError
}
if m.MemberId <= 0 {
2017-05-24 20:31:58 +08:00
m.Account = account
m.Email = searchResult.Entries[0].GetAttributeValue("mail")
m.AuthMethod = "ldap"
m.Avatar = "/static/images/headimgurl.jpg"
m.Role = conf.SystemRole(web.AppConfig.DefaultInt("ldap_user_role", 2))
2017-05-25 15:19:17 +08:00
m.CreateTime = time.Now()
2017-05-24 20:31:58 +08:00
err = m.Add()
if err != nil {
logs.Error("自动注册LDAP用户错误", err)
2017-05-24 20:31:58 +08:00
return m, ErrorMemberPasswordError
}
m.ResolveRoleName()
2017-04-21 18:20:35 +08:00
}
2017-05-24 20:31:58 +08:00
return m, nil
2017-04-20 18:19:32 +08:00
}
2017-04-21 18:20:35 +08:00
func (m *Member) httpLogin(account, password string) (*Member, error) {
urlStr, _ := web.AppConfig.String("http_login_url")
if urlStr == "" {
return nil, ErrMemberAuthMethodInvalid
}
2019-05-21 10:09:37 +08:00
val := url.Values{
"account": []string{account},
"password": []string{password},
"time": []string{strconv.FormatInt(time.Now().Unix(), 10)},
}
h := md5.New()
h.Write([]byte(val.Encode() + web.AppConfig.DefaultString("http_login_secret", "")))
2019-05-21 10:09:37 +08:00
val.Add("sn", hex.EncodeToString(h.Sum(nil)))
resp, err := http.PostForm(urlStr, val)
if err != nil {
logs.Error("通过接口登录失败 -> ", urlStr, account, err)
return nil, ErrHTTPServerFail
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
logs.Error("读取接口返回值失败 -> ", urlStr, account, err)
return nil, ErrHTTPServerFail
}
logs.Info("HTTP 登录接口返回数据 ->", string(body))
var result map[string]interface{}
if err := json.Unmarshal(body, &result); err != nil {
logs.Error("解析接口返回值失败 -> ", urlStr, account, string(body))
return nil, ErrHTTPServerFail
}
if code, ok := result["errcode"]; !ok || code.(float64) != 200 {
if msg, ok := result["message"]; ok {
return nil, errors.New(msg.(string))
}
return nil, ErrHTTPServerFail
}
if m.MemberId <= 0 {
member := NewMember()
if email, ok := result["email"]; !ok || email == "" {
return nil, errors.New("接口返回的数据缺少邮箱字段")
} else {
member.Email = email.(string)
}
if avatar, ok := result["avater"]; ok && avatar != "" {
member.Avatar = avatar.(string)
} else {
member.Avatar = conf.URLForWithCdnImage("/static/images/headimgurl.jpg")
}
if realName, ok := result["real_name"]; ok && realName != "" {
member.RealName = realName.(string)
}
member.Account = account
member.Password = password
member.AuthMethod = "http"
member.Role = conf.SystemRole(web.AppConfig.DefaultInt("ldap_user_role", 2))
member.CreateTime = time.Now()
if err := member.Add(); err != nil {
logs.Error("自动注册用户错误", err)
return m, ErrorMemberPasswordError
}
member.ResolveRoleName()
*m = *member
}
return m, nil
}
2017-04-21 18:20:35 +08:00
// Add 添加一个用户.
2017-05-24 20:31:58 +08:00
func (m *Member) Add() error {
2017-04-21 18:20:35 +08:00
o := orm.NewOrm()
2017-05-24 20:31:58 +08:00
if ok, err := regexp.MatchString(conf.RegexpAccount, m.Account); m.Account == "" || !ok || err != nil {
2017-05-03 14:22:05 +08:00
return errors.New("账号只能由英文字母数字组成且在3-50个字符")
}
if m.Email == "" {
return errors.New("邮箱不能为空")
}
2017-05-24 20:31:58 +08:00
if ok, err := regexp.MatchString(conf.RegexpEmail, m.Email); !ok || err != nil || m.Email == "" {
2017-05-03 14:22:05 +08:00
return errors.New("邮箱格式不正确")
}
2017-05-24 20:31:58 +08:00
if m.AuthMethod == "local" {
if l := strings.Count(m.Password, ""); l < 6 || l >= 50 {
return errors.New("密码不能为空且必须在6-50个字符之间")
}
2017-05-03 14:22:05 +08:00
}
2017-05-24 20:31:58 +08:00
if c, err := o.QueryTable(m.TableNameWithPrefix()).Filter("email", m.Email).Count(); err == nil && c > 0 {
return errors.New("邮箱已被使用")
2017-05-03 14:22:05 +08:00
}
2017-05-24 20:31:58 +08:00
hash, err := utils.PasswordHash(m.Password)
2017-04-21 18:20:35 +08:00
2017-05-24 20:31:58 +08:00
if err != nil {
logs.Error("加密用户密码失败 =>", err)
return errors.New("加密用户密码失败")
2017-04-21 18:20:35 +08:00
}
m.Password = hash
if m.AuthMethod == "" {
m.AuthMethod = "local"
}
2017-05-24 20:31:58 +08:00
_, err = o.Insert(m)
2017-04-21 18:20:35 +08:00
if err != nil {
logs.Error("保存用户数据到数据时失败 =>", err)
return errors.New("保存用户失败")
2017-04-21 18:20:35 +08:00
}
m.ResolveRoleName()
2017-05-24 20:31:58 +08:00
return nil
2017-04-21 18:20:35 +08:00
}
// Update 更新用户信息.
2017-05-24 20:31:58 +08:00
func (m *Member) Update(cols ...string) error {
2017-04-21 18:20:35 +08:00
o := orm.NewOrm()
2017-05-03 14:22:05 +08:00
if m.Email == "" {
return errors.New("邮箱不能为空")
}
2018-11-05 18:50:01 +08:00
if c, err := o.QueryTable(m.TableNameWithPrefix()).Filter("email", m.Email).Exclude("member_id", m.MemberId).Count(); err == nil && c > 0 {
return errors.New("邮箱已被使用")
}
2017-05-24 20:31:58 +08:00
if _, err := o.Update(m, cols...); err != nil {
logs.Error("保存用户信息失败=>", err)
return errors.New("保存用户信息失败")
2017-04-21 18:20:35 +08:00
}
return nil
}
2018-11-05 18:50:01 +08:00
func (m *Member) Find(id int, cols ...string) (*Member, error) {
2017-04-21 18:20:35 +08:00
o := orm.NewOrm()
2018-11-05 18:50:01 +08:00
if err := o.QueryTable(m.TableNameWithPrefix()).Filter("member_id", id).One(m, cols...); err != nil {
2017-05-24 20:31:58 +08:00
return m, err
2017-04-21 18:20:35 +08:00
}
m.ResolveRoleName()
2017-05-24 20:31:58 +08:00
return m, nil
2017-04-25 20:05:59 +08:00
}
2017-05-24 20:31:58 +08:00
func (m *Member) ResolveRoleName() {
if m.Role == conf.MemberSuperRole {
m.RoleName = "超级管理员"
2017-05-24 20:31:58 +08:00
} else if m.Role == conf.MemberAdminRole {
m.RoleName = "管理员"
2017-05-24 20:31:58 +08:00
} else if m.Role == conf.MemberGeneralRole {
m.RoleName = "普通用户"
}
2017-04-22 17:24:17 +08:00
}
//根据账号查找用户.
2017-05-24 20:31:58 +08:00
func (m *Member) FindByAccount(account string) (*Member, error) {
2017-04-22 17:24:17 +08:00
o := orm.NewOrm()
2017-05-24 20:31:58 +08:00
err := o.QueryTable(m.TableNameWithPrefix()).Filter("account", account).One(m)
2017-04-22 17:24:17 +08:00
if err == nil {
2017-04-25 20:05:59 +08:00
m.ResolveRoleName()
}
2017-05-24 20:31:58 +08:00
return m, err
2017-04-22 17:24:17 +08:00
}
2018-11-05 18:50:01 +08:00
//批量查询用户
2018-11-05 18:50:01 +08:00
func (m *Member) FindByAccountList(accounts ...string) ([]*Member, error) {
o := orm.NewOrm()
var members []*Member
2018-11-05 18:50:01 +08:00
_, err := o.QueryTable(m.TableNameWithPrefix()).Filter("account__in", accounts).All(&members)
if err == nil {
2018-11-05 18:50:01 +08:00
for _, item := range members {
item.ResolveRoleName()
}
}
return members, err
}
2017-04-22 17:24:17 +08:00
//分页查找用户.
2018-01-26 18:07:55 +08:00
func (m *Member) FindToPager(pageIndex, pageSize int) ([]*Member, int, error) {
2017-04-23 12:48:46 +08:00
o := orm.NewOrm()
var members []*Member
2017-04-23 12:48:46 +08:00
offset := (pageIndex - 1) * pageSize
2017-05-24 20:31:58 +08:00
totalCount, err := o.QueryTable(m.TableNameWithPrefix()).Count()
2017-04-23 12:48:46 +08:00
if err != nil {
2017-05-24 20:31:58 +08:00
return members, 0, err
2017-04-23 12:48:46 +08:00
}
2017-05-24 20:31:58 +08:00
_, err = o.QueryTable(m.TableNameWithPrefix()).OrderBy("-member_id").Offset(offset).Limit(pageSize).All(&members)
2017-04-23 12:48:46 +08:00
if err != nil {
2017-05-24 20:31:58 +08:00
return members, 0, err
2017-04-23 12:48:46 +08:00
}
2017-04-22 17:24:17 +08:00
2017-05-24 20:31:58 +08:00
for _, m := range members {
m.ResolveRoleName()
}
2018-01-26 18:07:55 +08:00
return members, int(totalCount), nil
2017-04-23 12:48:46 +08:00
}
2017-04-22 17:24:17 +08:00
func (m *Member) IsAdministrator() bool {
if m == nil || m.MemberId <= 0 {
return false
}
return m.Role == 0 || m.Role == 1
}
//根据指定字段查找用户.
2017-05-24 20:31:58 +08:00
func (m *Member) FindByFieldFirst(field string, value interface{}) (*Member, error) {
2017-05-03 14:22:05 +08:00
o := orm.NewOrm()
2017-05-24 20:31:58 +08:00
err := o.QueryTable(m.TableNameWithPrefix()).Filter(field, value).OrderBy("-member_id").One(m)
2017-05-24 20:31:58 +08:00
return m, err
2017-05-03 14:22:05 +08:00
}
//校验用户.
func (m *Member) Valid(is_hash_password bool) error {
//邮箱不能为空
if m.Email == "" {
return ErrMemberEmailEmpty
}
//用户描述必须小于500字
if strings.Count(m.Description, "") > 500 {
return ErrMemberDescriptionTooLong
}
2017-05-26 14:19:27 +08:00
if m.Role != conf.MemberGeneralRole && m.Role != conf.MemberSuperRole && m.Role != conf.MemberAdminRole {
return ErrMemberRoleError
}
if m.Status != 0 && m.Status != 1 {
m.Status = 0
}
//邮箱格式校验
if ok, err := regexp.MatchString(conf.RegexpEmail, m.Email); !ok || err != nil || m.Email == "" {
return ErrMemberEmailFormatError
}
//如果是未加密密码,需要校验密码格式
if !is_hash_password {
if l := strings.Count(m.Password, ""); m.Password == "" || l > 50 || l < 6 {
return ErrMemberPasswordFormatError
}
}
//校验邮箱是否呗使用
if member, err := NewMember().FindByFieldFirst("email", m.Account); err == nil && member.MemberId > 0 {
if m.MemberId > 0 && m.MemberId != member.MemberId {
return ErrMemberEmailExist
}
if m.MemberId <= 0 {
return ErrMemberEmailExist
}
}
2017-05-26 14:19:27 +08:00
if m.MemberId > 0 {
//校验用户是否存在
if _, err := NewMember().Find(m.MemberId); err != nil {
return err
}
} else {
//校验账号格式是否正确
if ok, err := regexp.MatchString(conf.RegexpAccount, m.Account); m.Account == "" || !ok || err != nil {
return ErrMemberAccountFormatError
}
//校验账号是否被使用
if member, err := NewMember().FindByAccount(m.Account); err == nil && member.MemberId > 0 {
return ErrMemberExist
}
}
return nil
}
//删除一个用户.
func (m *Member) Delete(oldId int, newId int) error {
ormer := orm.NewOrm()
o, err := ormer.Begin()
if err != nil {
return err
}
_, err = o.Raw("DELETE FROM md_members WHERE member_id = ?", oldId).Exec()
if err != nil {
o.Rollback()
return err
}
_, err = o.Raw("UPDATE md_attachment SET `create_at` = ? WHERE `create_at` = ?", newId, oldId).Exec()
if err != nil {
o.Rollback()
return err
}
_, err = o.Raw("UPDATE md_books SET member_id = ? WHERE member_id = ?", newId, oldId).Exec()
if err != nil {
o.Rollback()
return err
}
_, err = o.Raw("UPDATE md_document_history SET member_id=? WHERE member_id = ?", newId, oldId).Exec()
if err != nil {
o.Rollback()
return err
}
_, err = o.Raw("UPDATE md_document_history SET modify_at=? WHERE modify_at = ?", newId, oldId).Exec()
if err != nil {
o.Rollback()
return err
}
_, err = o.Raw("UPDATE md_documents SET member_id = ? WHERE member_id = ?;", newId, oldId).Exec()
if err != nil {
o.Rollback()
return err
}
_, err = o.Raw("UPDATE md_documents SET modify_at = ? WHERE modify_at = ?", newId, oldId).Exec()
if err != nil {
o.Rollback()
return err
}
2018-11-05 18:50:01 +08:00
_, err = o.Raw("UPDATE md_blogs SET member_id = ? WHERE member_id = ?;", newId, oldId).Exec()
if err != nil {
o.Rollback()
return err
}
_, err = o.Raw("UPDATE md_blogs SET modify_at = ? WHERE modify_at = ?", newId, oldId).Exec()
if err != nil {
o.Rollback()
return err
}
_, err = o.Raw("UPDATE md_templates SET modify_at = ? WHERE modify_at = ?", newId, oldId).Exec()
if err != nil {
o.Rollback()
return err
}
_, err = o.Raw("UPDATE md_templates SET member_id = ? WHERE member_id = ?", newId, oldId).Exec()
if err != nil {
o.Rollback()
return err
}
_, err = o.QueryTable(NewTeamMember()).Filter("member_id", oldId).Delete()
2018-11-05 18:50:01 +08:00
if err != nil {
o.Rollback()
return err
}
2017-07-10 16:23:15 +08:00
//_,err = o.Raw("UPDATE md_relationship SET member_id = ? WHERE member_id = ?",newId,oldId).Exec()
//if err != nil {
//
// if err != nil {
// o.Rollback()
// return err
// }
//}
var relationshipList []*Relationship
2017-07-10 16:23:15 +08:00
_, err = o.QueryTable(NewRelationship().TableNameWithPrefix()).Filter("member_id", oldId).Limit(math.MaxInt32).All(&relationshipList)
2017-07-10 16:23:15 +08:00
if err == nil {
for _, relationship := range relationshipList {
2017-07-10 16:59:49 +08:00
//如果存在创始人,则删除
if relationship.RoleId == 0 {
rel := NewRelationship()
err = o.QueryTable(relationship.TableNameWithPrefix()).Filter("book_id", relationship.BookId).Filter("member_id", newId).One(rel)
2017-07-10 16:59:49 +08:00
if err == nil {
if _, err := o.Delete(relationship); err != nil {
logs.Error(err)
2017-07-10 16:59:49 +08:00
}
relationship.RelationshipId = rel.RelationshipId
}
2017-07-10 16:23:15 +08:00
relationship.MemberId = newId
2017-07-10 16:59:49 +08:00
relationship.RoleId = 0
if _, err := o.Update(relationship); err != nil {
logs.Error(err)
2017-07-10 16:59:49 +08:00
}
} else {
if _, err := o.Delete(relationship); err != nil {
logs.Error(err)
2017-07-10 16:59:49 +08:00
}
2017-07-10 16:23:15 +08:00
}
}
}
2017-07-10 16:23:15 +08:00
if err = o.Commit(); err != nil {
o.Rollback()
return err
}
return nil
}