blog_backend_api/controller/user.go

525 lines
12 KiB
Go
Raw Normal View History

2019-01-25 09:11:15 +00:00
package controller
2019-02-23 06:19:29 +00:00
2019-01-25 09:11:15 +00:00
import (
2020-08-23 18:08:26 +00:00
"background/config"
"background/db"
"background/logs"
"background/model"
"background/redis"
2019-04-07 04:25:07 +00:00
"background/utils"
2019-03-12 06:01:25 +00:00
"bytes"
"crypto/md5"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"math/rand"
"net/http"
"net/smtp"
"regexp"
"strconv"
"strings"
"time"
2020-08-23 18:08:26 +00:00
"github.com/fatih/structs"
"github.com/gin-gonic/gin"
_ "github.com/go-sql-driver/mysql"
sessions "github.com/tommy351/gin-sessions"
2019-01-25 09:11:15 +00:00
)
2019-03-07 06:06:29 +00:00
2019-03-12 06:01:25 +00:00
type UserController struct {
2019-03-07 06:06:29 +00:00
}
2019-01-25 09:11:15 +00:00
type ReqSendEmailCode struct {
2019-03-07 02:36:09 +00:00
EmailAdress string `json:"email_address"`
2019-01-25 09:11:15 +00:00
}
type SetUserGroupReq struct {
2019-03-07 02:36:09 +00:00
Id int64 `json:"id,omitempty"`
2019-01-25 09:11:15 +00:00
Description string `json:"description"`
2019-03-07 02:36:09 +00:00
GroupName string `json:"group_name"`
UserIds []int `json:"user_ids"`
2019-01-25 09:11:15 +00:00
}
type RespBase struct {
2019-03-07 02:36:09 +00:00
Msg string
2019-01-25 09:11:15 +00:00
Status int
2019-03-07 02:36:09 +00:00
Data interface{}
2019-01-25 09:11:15 +00:00
}
2019-03-12 06:01:25 +00:00
func (this *UserController) Auth(c *gin.Context) {
2019-01-25 09:11:15 +00:00
var resp RespBase
var statuscode int
statuscode = 200
2019-03-07 02:36:09 +00:00
var userinfo map[string]interface{}
2019-01-25 09:11:15 +00:00
//var userSockToken map[string] interface{}
defer func() {
c.JSON(statuscode, resp)
}()
socketToken := c.Query("socketToken")
2019-03-07 02:36:09 +00:00
struserinfo, e := redis.Get(socketToken)
2019-01-25 09:11:15 +00:00
2019-03-07 02:36:09 +00:00
if e != nil {
2019-01-25 09:11:15 +00:00
logs.Error(e.Error())
return
}
2019-03-07 02:36:09 +00:00
e = json.Unmarshal([]byte(struserinfo), userinfo)
if nil != e {
2019-01-25 09:11:15 +00:00
logs.Error(e.Error())
return
}
}
2019-03-07 02:36:09 +00:00
2019-03-07 06:06:29 +00:00
func (this *UserController) SetUser(c *gin.Context) {
2019-01-29 13:57:53 +00:00
2019-04-07 04:25:07 +00:00
}
2020-06-24 17:15:46 +00:00
2019-04-07 04:25:07 +00:00
func (this *UserController) ModifyPasswd(c *gin.Context) {
2020-08-23 18:08:26 +00:00
type ReqModifyPasswd struct {
id int `json:"id"`
2019-04-07 04:25:07 +00:00
UserName string `json:"user_name"`
Password string `json:"password"`
}
var req ReqModifyPasswd
var resp RespBase
resp.Status = -1
resp.Msg = "err"
defer func() {
2020-08-23 18:08:26 +00:00
c.JSON(200, resp)
2019-04-07 04:25:07 +00:00
}()
e := c.BindJSON(&req)
2020-08-23 18:08:26 +00:00
if nil != e {
2019-04-07 04:25:07 +00:00
logs.Error(e.Error())
return
}
2020-08-23 18:08:26 +00:00
e = model.ModyfyPassword(req.UserName, req.Password)
if nil != e {
2019-04-07 04:25:07 +00:00
logs.Error(e.Error())
return
}
resp.Msg = "OK"
resp.Status = 0
2019-01-25 09:11:15 +00:00
}
2020-06-24 17:15:46 +00:00
2019-03-07 06:06:29 +00:00
func (this *UserController) DelUser(c *gin.Context) {
2019-01-25 09:11:15 +00:00
}
2019-03-07 06:06:29 +00:00
func (this *UserController) GetUser(c *gin.Context) {
2019-01-25 09:11:15 +00:00
var resp RespBase
resp.Msg = "操作失败"
resp.Status = 20
defer func() {
2019-03-07 02:36:09 +00:00
c.JSON(200, resp)
2019-01-25 09:11:15 +00:00
}()
session := sessions.Get(c)
userinfo := session.Get("")
2019-03-07 02:36:09 +00:00
if userinfo == nil {
2019-01-25 09:11:15 +00:00
logs.Error("error could not find key")
return
}
2019-03-07 02:36:09 +00:00
var users map[string]interface{}
e := json.Unmarshal([]byte(userinfo.(string)), &users)
2019-01-25 09:11:15 +00:00
if nil != e {
logs.Error(e.Error())
}
delete(users, "socketToken")
2019-01-25 09:11:15 +00:00
resp.Status = 0
resp.Msg = "操作成功"
resp.Data = users
}
2019-03-07 02:36:09 +00:00
2019-03-12 06:01:25 +00:00
func (this *UserController) Users(c *gin.Context) {
2019-01-25 09:11:15 +00:00
var statuscode int
var resp RespBase
resp.Msg = "获取失败"
resp.Status = 0
statuscode = 200
defer func() {
2019-03-07 02:36:09 +00:00
c.JSON(statuscode, resp)
2019-01-25 09:11:15 +00:00
}()
2019-02-23 06:19:29 +00:00
offset := c.Query("offset")
limit := c.Query("limit")
2019-03-07 02:36:09 +00:00
ioffset, e := strconv.Atoi(offset)
if nil != e {
2019-01-25 09:11:15 +00:00
logs.Error(e.Error())
return
}
2019-03-07 02:36:09 +00:00
ilimit, er := strconv.Atoi(limit)
if nil != er {
2019-02-23 06:19:29 +00:00
logs.Error(e.Error())
return
2019-01-25 09:11:15 +00:00
}
2019-03-07 02:36:09 +00:00
dat := map[string]interface{}{}
users, all := model.GetUsers(int32(ilimit), int32(ioffset), "")
2019-02-23 06:19:29 +00:00
dat["users"] = users
dat["all"] = all
resp.Msg = "OK"
resp.Data = dat
}
2019-01-25 09:11:15 +00:00
2019-03-07 06:06:29 +00:00
func (this *UserController) SerarchUsers(c *gin.Context) {
2019-02-23 06:19:29 +00:00
var statuscode int
var resp RespBase
2019-01-25 09:11:15 +00:00
2019-02-23 06:19:29 +00:00
resp.Msg = "获取失败"
resp.Status = 0
statuscode = 200
defer func() {
2019-03-07 02:36:09 +00:00
c.JSON(statuscode, resp)
2019-02-23 06:19:29 +00:00
}()
offset := c.Query("offset")
limit := c.Query("limit")
username := c.PostForm("username")
2019-03-07 02:36:09 +00:00
ioffset, e := strconv.Atoi(offset)
if nil != e {
2019-02-23 06:19:29 +00:00
logs.Error(e.Error())
return
}
2019-03-07 02:36:09 +00:00
ilimit, er := strconv.Atoi(limit)
if nil != er {
2019-02-23 06:19:29 +00:00
logs.Error(e.Error())
return
2019-01-25 09:11:15 +00:00
}
2019-02-23 06:19:29 +00:00
2019-03-07 02:36:09 +00:00
dat := map[string]interface{}{}
users, all := model.GetUsers(int32(ilimit), int32(ioffset), username)
2019-02-23 06:19:29 +00:00
dat["users"] = users
dat["all"] = all
2019-01-25 09:11:15 +00:00
resp.Msg = "OK"
2019-02-23 06:19:29 +00:00
resp.Data = dat
2019-01-25 09:11:15 +00:00
}
2019-03-12 06:01:25 +00:00
func CreateVerify(length int32) string {
2019-03-07 02:36:09 +00:00
strAry := []byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
2019-01-25 09:11:15 +00:00
result := string("")
2019-03-07 02:36:09 +00:00
for i := int32(0); i < length; i++ {
2019-01-25 09:11:15 +00:00
x := rand.Intn(len(strAry))
result += string(strAry[x])
}
return result
}
2019-03-07 02:36:09 +00:00
2019-01-25 09:11:15 +00:00
/**
2019-03-07 02:36:09 +00:00
* Token
* @param {Number} length Token
* @return {string} Token
*/
2019-03-12 06:01:25 +00:00
func createToken(length int32) string {
2019-03-07 02:36:09 +00:00
strAry := []byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '_'}
2019-01-25 09:11:15 +00:00
result := string("")
2019-03-07 02:36:09 +00:00
for i := int32(0); i < length; i++ {
2019-01-25 09:11:15 +00:00
x := rand.Intn(len(strAry))
result += string(strAry[x])
}
return result
}
2019-03-07 02:36:09 +00:00
func DefaultOption(c *gin.Context) {
2019-01-25 09:11:15 +00:00
var resp RespBase
defer func() {
c.JSON(204, resp)
}()
}
2019-03-07 02:36:09 +00:00
2019-03-07 06:06:29 +00:00
func (this *UserController) Login(c *gin.Context) {
2019-01-25 09:11:15 +00:00
type LoginReq struct {
2019-03-07 02:36:09 +00:00
RememberMe int32 `json:"remember_me"`
UserName string `json:"user_name"`
UserPwd string `json:"user_pwd"`
2019-01-25 09:11:15 +00:00
}
var req LoginReq
statusCode := 200
var resp RespBase
defer func() {
c.JSON(statusCode, resp)
}()
e := c.Bind(&req)
2019-03-07 02:36:09 +00:00
if e != nil {
2019-01-25 09:11:15 +00:00
log.Println(e.Error())
return
}
h := md5.New()
h.Write([]byte(req.UserPwd)) // 需要加密的字符串为 123456
passmd5 := h.Sum(nil)
var result []model.Users
2020-08-23 18:08:26 +00:00
query := fmt.Sprintf("select * from users where user_name = '%s'", req.UserName)
2019-06-30 14:59:00 +00:00
er := db.GetMysqlClient().Query2(query,
&result)
logs.Debug("sql query:" + query)
2019-03-07 02:36:09 +00:00
if nil != er {
2019-01-25 09:11:15 +00:00
log.Println(er.Error())
}
2019-04-07 04:25:07 +00:00
strpassmd5 := utils.ByteSliceToString(passmd5)
2019-01-25 09:11:15 +00:00
if len(result) == 1 {
if result[0].UserPwd == strpassmd5 {
socketToken := md5.New()
socketToken.Write([]byte(createToken(6))) // 需要加密的字符串为 123456
socketTokenMd5 := socketToken.Sum(nil)
m := structs.Map(result[0])
m["SocketToken"] = utils.ByteSliceToString(socketTokenMd5)
2019-03-07 02:36:09 +00:00
sessionInfo, err := json.Marshal(m)
if err != nil {
2019-01-25 09:11:15 +00:00
log.Println(err.Error())
}
2019-03-07 02:36:09 +00:00
if req.RememberMe == 1 {
2019-08-01 14:52:57 +00:00
config.RedisOne().Set(utils.ByteSliceToString(socketTokenMd5), string(sessionInfo), time.Second*24*3600)
2019-03-07 02:36:09 +00:00
} else {
2019-08-01 14:52:57 +00:00
config.RedisOne().Set(utils.ByteSliceToString(socketTokenMd5), string(sessionInfo), time.Second*8*3600)
2019-01-25 09:11:15 +00:00
}
//存储session
session := sessions.Get(c)
2019-03-07 02:36:09 +00:00
session.Set("", string(sessionInfo))
2019-01-25 09:11:15 +00:00
//session.
var Options *sessions.Options
2019-03-07 02:36:09 +00:00
if req.RememberMe == 1 {
2019-01-25 09:11:15 +00:00
Options = &sessions.Options{
MaxAge: 2 * 24 * 3600 * 1000,
}
2019-03-07 02:36:09 +00:00
} else {
2019-01-25 09:11:15 +00:00
Options = &sessions.Options{
MaxAge: 8 * 3600 * 1000,
}
}
session.Options(*Options)
session.Save()
resp.Msg = "登录成功"
resp.Status = 0
resp.Data = string(sessionInfo)
2019-03-07 02:36:09 +00:00
} else {
2019-02-23 06:19:29 +00:00
resp.Status = 422
2019-01-25 09:11:15 +00:00
resp.Msg = "用户密码不正确"
}
2019-03-07 02:36:09 +00:00
} else {
2019-02-23 06:19:29 +00:00
resp.Status = 422
2019-01-25 09:11:15 +00:00
resp.Msg = "登录账号不存在,请重新输入"
}
}
2019-03-07 06:06:29 +00:00
func (this *UserController) Register(c *gin.Context) {
2019-01-25 09:11:15 +00:00
type RegisterReq struct {
DisplayName string `json:"display_name"`
EmailAdress string `json:"email_address"`
2019-03-07 02:36:09 +00:00
EmailCode string `json:"email_code"`
UserName string `json:"user_name"`
UserPwd string `json:"user_pwd"`
2019-01-25 09:11:15 +00:00
}
var req RegisterReq
statusCode := 200
var resp RespBase
var user model.Users
resp.Msg = "失败"
resp.Status = 1
defer func() {
c.JSON(statusCode, resp)
}()
e := c.Bind(&req)
2019-03-07 02:36:09 +00:00
if e != nil {
2019-01-25 09:11:15 +00:00
log.Println(e.Error())
return
}
2019-03-07 02:36:09 +00:00
userKey := fmt.Sprintf("user_%s_verify", req.EmailAdress)
2019-02-23 06:19:29 +00:00
verify := config.RedisOne().Get(userKey).Val()
2019-01-25 09:11:15 +00:00
2019-03-07 02:36:09 +00:00
if verify != req.EmailCode {
2019-01-25 09:11:15 +00:00
resp.Msg = "验证码错误"
resp.Status = 20
return
}
user.UserName = req.UserName
user.EmailAddress = req.EmailAdress
user.DisplayName = req.DisplayName
h := md5.New()
h.Write([]byte(req.UserPwd))
passwdmd5 := h.Sum(nil)
2019-04-07 04:25:07 +00:00
strpassmd5 := utils.ByteSliceToString(passwdmd5)
2019-01-25 09:11:15 +00:00
user.UserPwd = strpassmd5
2019-02-23 06:19:29 +00:00
user.UpdatedDate = time.Now().Format("2006-01-02 15:04:05")
user.CreatedDate = time.Now().Format("2006-01-02 15:04:05")
var result []model.Users
2019-01-25 09:11:15 +00:00
2019-02-23 06:19:29 +00:00
er := db.GetMysqlClient().Query2("select * from users where user_name = ?",
2019-03-07 02:36:09 +00:00
&result, req.UserName)
if nil != er {
2019-02-23 06:19:29 +00:00
log.Println(er.Error())
return
}
2019-03-07 02:36:09 +00:00
if len(result) > 0 {
2019-02-23 06:19:29 +00:00
resp.Msg = "失败,账号已经存在"
resp.Status = 20
return
}
2019-04-07 04:25:07 +00:00
query := fmt.Sprintf("insert into users(user_name,user_pwd,created_date,"+
"updated_date,display_name,email_address) values ('%s','%s','%s','%s','%s','%s')", user.UserName, user.UserPwd, user.CreatedDate, user.UpdatedDate,
2019-03-07 02:36:09 +00:00
user.DisplayName, user.EmailAddress)
n, er := db.GetMysqlClient().Insert(query)
if n == 0 || n < 0 {
2019-01-25 09:11:15 +00:00
statusCode = 422
logs.Error(er.Error())
resp.Msg = "失败,账号已经存在"
resp.Status = 20
return
}
2019-03-07 02:36:09 +00:00
if nil != er {
2019-01-25 09:11:15 +00:00
statusCode = 422
logs.Error(er.Error())
resp.Msg = "失败"
resp.Status = 20
return
}
resp.Msg = "成功"
resp.Status = 0
}
2019-03-07 06:06:29 +00:00
func (this *UserController) Logout(c *gin.Context) {
2019-09-06 07:53:04 +00:00
token := c.Param("token")
2020-08-23 18:08:26 +00:00
log.Print("logout token is ", token)
2019-01-25 09:11:15 +00:00
var resp RespBase
2019-09-06 07:53:04 +00:00
config.RedisOne().Del(token)
2019-01-25 09:11:15 +00:00
resp.Msg = "退出成功"
resp.Status = 0
defer func() {
2019-03-07 02:36:09 +00:00
c.JSON(200, resp)
2019-01-25 09:11:15 +00:00
}()
session := sessions.Get(c)
session.Delete("")
session.Save()
}
2019-03-07 02:36:09 +00:00
func Reader2Json(r io.ReadCloser) string {
2019-01-25 09:11:15 +00:00
var ret string
2019-03-07 02:36:09 +00:00
for i := 0; ; i++ {
s := make([]byte, 10)
_, e := r.Read(s)
2019-01-25 09:11:15 +00:00
ret += string(s)
2019-03-07 02:36:09 +00:00
if e != nil {
2019-01-25 09:11:15 +00:00
break
}
}
return ret
}
2019-03-12 06:01:25 +00:00
func SendExternalEmail(msg interface{}) error {
2019-03-07 02:36:09 +00:00
req := make(map[string]interface{}, 1)
2019-01-25 09:11:15 +00:00
req["type"] = "text"
req["action"] = "smtp-sys"
req["apiType"] = "send"
2019-03-07 02:36:09 +00:00
content, err := json.Marshal(msg)
if err != nil {
2019-01-25 09:11:15 +00:00
log.Println(err.Error())
return errors.New("Json marshal error")
}
req["content"] = string(content)
var buffer bytes.Buffer
2019-03-07 02:36:09 +00:00
b, e := json.Marshal(req)
if e != nil {
2019-01-25 09:11:15 +00:00
log.Println(e.Error())
}
buffer.Write(b)
2019-03-07 02:36:09 +00:00
resp, err := http.Post("http://47.93.230.163:8091/msg/v1/send", "application/json", &buffer)
2019-01-25 09:11:15 +00:00
2019-03-07 02:36:09 +00:00
if resp.StatusCode != 200 {
2019-01-25 09:11:15 +00:00
return errors.New("error send emain")
}
2019-03-07 02:36:09 +00:00
if err != nil {
2019-01-25 09:11:15 +00:00
logs.Error("error send email")
return err
}
2019-03-07 02:36:09 +00:00
return nil
2019-01-25 09:11:15 +00:00
}
2019-03-07 02:36:09 +00:00
func SendToMail(title, user string, password string, host string, to string, content string,
2019-01-25 09:11:15 +00:00
ifgenerate bool) error {
var content_type string
hp := strings.Split(host, ":")
auth := smtp.PlainAuth("", user, password, hp[0])
content_type = "Content-Type: text/plain" + "; charset=UTF-8"
msg := []byte("To: " + to + "\r\nFrom: " + user + "\r\nSubject: " + title + "\r\n" +
2019-03-07 02:36:09 +00:00
content_type + "\r\n\r\n" + content + "\r\n")
2019-01-25 09:11:15 +00:00
send_to := strings.Split(to, ";")
//检测是否是邮件地址
2019-03-07 02:36:09 +00:00
for k, _ := range send_to {
2019-01-25 09:11:15 +00:00
match, _ := regexp.MatchString("[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?", send_to[k])
2019-03-07 02:36:09 +00:00
if !match {
2019-01-25 09:11:15 +00:00
return errors.New("Format Error")
}
}
2019-03-07 02:36:09 +00:00
err := smtp.SendMail(host, auth, user, send_to, msg)
if err != nil {
2019-01-25 09:11:15 +00:00
return err
}
return err
}
2019-03-07 06:06:29 +00:00
func (this *UserController) SendEmailCode(c *gin.Context) {
2019-01-25 09:11:15 +00:00
var req ReqSendEmailCode
2019-03-07 02:36:09 +00:00
var resp RespBase = RespBase{Msg: "邮件已经存在", Status: 0}
2019-01-25 09:11:15 +00:00
statusCode := 200
defer func() {
c.JSON(statusCode, resp)
}()
e := c.Bind(&req)
2019-03-07 02:36:09 +00:00
if nil != e {
2019-01-25 09:11:15 +00:00
log.Println(e.Error())
resp.Msg = "请求参数错误"
return
}
//判断邮箱是否存在
var users []model.Users
2019-03-07 06:06:29 +00:00
e = db.GetMysqlClient().Query2("select * from users where email_adress = ?", &users, req.EmailAdress)
2019-03-12 06:01:25 +00:00
if nil != e {
2019-03-07 06:06:29 +00:00
log.Print(e.Error())
resp.Msg = "email address error"
return
}
2019-03-07 02:36:09 +00:00
if len(users) != 0 {
2019-01-25 09:11:15 +00:00
statusCode = 422
return
}
//产生验证码
verify := CreateVerify(6)
session := sessions.Get(c)
2019-03-07 02:36:09 +00:00
session.Set(req.EmailAdress, verify)
2019-01-25 09:11:15 +00:00
session.Save()
2019-03-07 02:36:09 +00:00
sendcontent := make(map[string]interface{}, 1)
2019-01-25 09:11:15 +00:00
sendcontent["subject"] = "邮箱验证码,请注意查收"
sendcontent["receivers"] = req.EmailAdress
sendcontent["content"] = string("您本次注册的验证码为:") + verify + string(",工作人员不会向您索取,请勿泄露。请尽快完成操作。")
e = SendExternalEmail(sendcontent)
2019-03-07 02:36:09 +00:00
if e != nil {
2019-01-25 09:11:15 +00:00
log.Println(e.Error())
return
}
//成功
resp.Msg = "发送成功"
2019-03-07 02:36:09 +00:00
}