Example #1
0
// 通过唯一键(uid或username)获取用户信息
func findUserByUniq(field, val string) *model.User {
	user := model.NewUser()
	err := user.Where(field + "=" + val).Find()
	if err != nil {
		logger.Errorf("获取用户 %s 信息失败:%s", val, err)
		return nil
	}
	if user.Uid == 0 {
		return nil
	}

	// 获取用户角色信息
	userRoleList, err := model.NewUserRole().
		Order("roleid ASC").Where("uid="+strconv.Itoa(user.Uid)).FindAll("uid", "roleid")
	if err != nil {
		logger.Errorf("获取用户 %s 角色 信息失败:%s", val, err)
		return nil
	}

	if roleNum := len(userRoleList); roleNum > 0 {
		user.Roleids = make([]int, roleNum)
		user.Rolenames = make([]string, roleNum)

		for i, userRole := range userRoleList {
			user.Roleids[i] = userRole.Roleid
			user.Rolenames[i] = Roles[userRole.Roleid-1].Name
		}
	}

	return user
}
Example #2
0
func FindUsers() (map[int]*model.User, error) {
	userList, err := model.NewUser().FindAll()
	if err != nil {
		logger.Errorln("user service FindUsers Error:", err)
		return nil, err
	}
	userCount := len(userList)
	userMap := make(map[int]*model.User, userCount)
	uids := make([]int, userCount)
	for i, user := range userList {
		userMap[user.Uid] = user
		uids[i] = user.Uid
	}
	// 获得角色信息
	userRoleList, err := model.NewUserRole().Where("uid in (" + util.Join(uids, ",") + ")").FindAll()
	if err != nil {
		logger.Errorln("user service FindUsers Error:", err)
		return nil, err
	}
	for _, userRole := range userRoleList {
		user := userMap[userRole.Uid]
		if len(user.Roleids) == 0 {
			user.Roleids = []int{userRole.Roleid}
			user.Rolenames = []string{model.AllRole[userRole.Roleid].Name}
		} else {
			user.Roleids = append(user.Roleids, userRole.Roleid)
			user.Rolenames = append(user.Rolenames, model.AllRole[userRole.Roleid].Name)
		}
	}
	return userMap, nil
}
Example #3
0
// 获取单个用户信息
func FindUserByUsername(username string) *model.User {
	user := model.NewUser()
	err := user.Where("username="******"获取用户 %s 信息失败:%s", username, err)
		return nil
	}
	if user.Uid == 0 {
		return nil
	}

	// 获取角色信息
	userRoleList, err := model.NewUserRole().Where("uid=" + strconv.Itoa(user.Uid)).FindAll()
	if err != nil {
		logger.Errorf("获取用户 %s 角色 信息失败:%s", username, err)
		return nil
	}
	for _, userRole := range userRoleList {
		if len(user.Roleids) == 0 {
			user.Rolenames = []string{model.AllRole[userRole.Roleid].Name}
		} else {
			user.Rolenames = append(user.Rolenames, model.AllRole[userRole.Roleid].Name)
		}
	}
	return user
}
Example #4
0
func CreateUser(form url.Values) (errMsg string, err error) {
	// 存用户基本信息,产生自增长UID
	user := model.NewUser()
	err = util.ConvertAssign(user, form)
	if err != nil {
		logger.Errorln("user ConvertAssign error", err)
		errMsg = err.Error()
		return
	}
	uid, err := user.Insert()
	if err != nil {
		errMsg = "内部服务器错误"
		logger.Errorln(errMsg, ":", err)
		return
	}

	// 存用户登录信息
	userLogin := model.NewUserLogin()
	err = util.ConvertAssign(userLogin, form)
	if err != nil {
		errMsg = err.Error()
		logger.Errorln("CreateUser error:", err)
		return
	}
	userLogin.Uid = uid
	_, err = userLogin.Insert()
	if err != nil {
		errMsg = "内部服务器错误"
		logger.Errorln(errMsg, ":", err)
		return
	}

	// 存用户角色信息
	userRole := model.NewUserRole()
	// 默认为初级会员
	roleId := model.AllRoleId[len(model.AllRoleId)-1]
	if form.Get("roleid") != "" {
		tmpId, err := strconv.Atoi(form.Get("roleid"))
		if err == nil {
			roleId = tmpId
		}
	}
	userRole.Roleid = roleId
	userRole.Uid = uid
	if _, err = userRole.Insert(); err != nil {
		logger.Errorln("userRole insert Error:", err)
	}

	// 存用户活跃信息,初始活跃+2
	userActive := model.NewUserActive()
	userActive.Uid = uid
	userActive.Username = user.Username
	userActive.Email = user.Email
	userActive.Weight = 2
	if _, err = userActive.Insert(); err != nil {
		logger.Errorln("UserActive insert Error:", err)
	}
	return
}
Example #5
0
func FindNewUsers(start, num int) []*model.User {
	users, err := model.NewUser().Order("ctime DESC").Limit(strconv.Itoa(start) + "," + strconv.Itoa(num)).FindAll([]string{"uid", "username", "email", "avatar", "ctime"}...)
	if err != nil {
		logger.Errorln("user service FindNewUsers error:", err)
		return nil
	}
	return users
}
Example #6
0
// 更换头像
func ChangeAvatar(uid int, avatar string) (err error) {
	err = model.NewUser().Set("avatar=?", avatar).Where("uid=?", uid).Update()
	if err == nil {
		err = model.NewUserActive().Set("avatar=?", avatar).Where("uid=?", uid).Update()
	}

	return
}
Example #7
0
// 通过邮箱获取用户信息
func FindUserByEmail(email string) *model.User {
	user := model.NewUser()
	err := user.Where("email=?", email).Find()
	if err != nil {
		logger.Errorln("FindUserByEmail error:", err)
	}

	return user
}
Example #8
0
// UpdateUserStatus 更新用户状态
func UpdateUserStatus(uid, status int) {
	setClause := "status=" + strconv.Itoa(status)
	err := model.NewUser().Set(setClause).Where("uid=?", uid).Update()
	if err != nil {
		logger.Errorf("更新用户 【%s】 状态失败:%s", uid, err)
		return
	}

	return
}
Example #9
0
func UpdateUser(form url.Values) (errMsg string, err error) {
	fields := []string{"name", "open", "city", "company", "github", "weibo", "website", "status", "introduce"}
	setClause := GenSetClause(form, fields)
	username := form.Get("username")
	err = model.NewUser().Set(setClause).Where("username="******"更新用户 【%s】 信息失败:%s", username, err)
		errMsg = "对不起,服务器内部错误,请稍后再试!"
		return
	}
	return
}
Example #10
0
// 通过UID获取用户名
func FindUsernameByUid(uid int) string {
	user := model.NewUser()
	err := user.Where("uid=" + strconv.Itoa(uid)).Find()
	if err != nil {
		logger.Errorf("获取用户 %s 信息失败:%s", uid, err)
		return ""
	}
	if user.Uid == 0 {
		return ""
	}

	return user.Username
}
Example #11
0
// 获取用户信息
func getUserInfos(uids map[int]int) map[int]*model.User {
	// 获取用户信息
	inUids := util.Join(util.MapIntKeys(uids), ",")
	users, err := model.NewUser().Where("uid in(" + inUids + ")").FindAll()
	if err != nil {
		logger.Errorln("user service getUserInfos Error:", err)
		return map[int]*model.User{}
	}
	userMap := make(map[int]*model.User, len(users))
	for _, user := range users {
		userMap[user.Uid] = user
	}
	return userMap
}
Example #12
0
func UpdateUserReminder(form url.Values) (errMsg string, err error) {
	fields := []string{"lowestPrice", "highestPrice", "Emailnotice"}
	setClause := GenSetClause(form, fields)
	username := form.Get("username")
	err = model.NewUser().Set(setClause).Where("username="******"更新用户 【%s】 reminder信息失败:%s", username, err)
		errMsg = "对不起,服务器内部错误,请稍后再试!"
		return
	}

	// 修改用户资料,活跃度+1
	go IncUserWeight("username="+username, 1)

	return
}
Example #13
0
// @某人
func parseAtUser(content string) string {
	user := model.NewUser()

	reg := regexp.MustCompile(`@([^\s@]{4,20})`)
	return reg.ReplaceAllStringFunc(content, func(matched string) string {
		username := matched[1:]

		// 校验 username 是否存在
		err := user.Where("username=?", username).Find()
		if err != nil {
			return matched
		}

		if user.Username != username {
			return matched
		}
		return fmt.Sprintf(`<a href="/user/%s" title="%s">%s</a>`, username, matched, matched)
	})
}
Example #14
0
// 获取当前登录用户信息(常用信息)
func FindCurrentUser(username string) (user map[string]interface{}, err error) {
	userInfo := model.NewUser()
	err = userInfo.Where("username="******"获取用户 %s 信息失败:%s", username, err)
		return
	}
	if userInfo.Uid == 0 {
		logger.Infof("用户 %s 不存在!", username)
		return
	}
	user = map[string]interface{}{
		"uid":      userInfo.Uid,
		"username": userInfo.Username,
		"email":    userInfo.Email,
		"avatar":   userInfo.Avatar,
		"status":   userInfo.Status,
	}

	// 获取未读消息数
	user["msgnum"] = FindNotReadMsgNum(userInfo.Uid)

	// 获取角色信息
	userRoleList, err := model.NewUserRole().Where("uid=" + strconv.Itoa(userInfo.Uid)).FindAll()
	if err != nil {
		logger.Errorf("获取用户 %s 角色 信息失败:%s", username, err)
		return
	}
	for _, userRole := range userRoleList {
		if userRole.Roleid <= model.AdminMinRoleId {
			// 是管理员
			user["isadmin"] = true
		}
	}

	RecordLoginTime(username)

	return
}
Example #15
0
func FindUsersByPage(conds map[string]string, curPage, limit int) ([]*model.User, int) {
	conditions := make([]string, 0, len(conds))
	for k, v := range conds {
		conditions = append(conditions, k+"="+v)
	}

	user := model.NewUser()

	limitStr := strconv.Itoa((curPage-1)*limit) + "," + strconv.Itoa(limit)
	userList, err := user.Where(strings.Join(conditions, " AND ")).Limit(limitStr).
		FindAll()
	if err != nil {
		logger.Errorln("user service FindUsersByPage Error:", err)
		return nil, 0
	}

	total, err := user.Count()
	if err != nil {
		logger.Errorln("user service FindUsersByPage COUNT Error:", err)
		return nil, 0
	}

	return userList, total
}
Example #16
0
func CreateUser(form url.Values) (errMsg string, err error) {
	if EmailExists(form.Get("email")) {
		err = errors.New("该邮箱已注册过")
		return
	}
	if UsernameExists(form.Get("username")) {
		err = errors.New("用户名已存在")
		return
	}
	// 存用户基本信息,产生自增长UID
	user := model.NewUser()
	err = util.ConvertAssign(user, form)
	if err != nil {
		logger.Errorln("user ConvertAssign error", err)
		errMsg = err.Error()
		return
	}
	user.Ctime = util.TimeNow()

	// 随机给一个默认头像
	user.Avatar = DefaultAvatars[rand.Intn(len(DefaultAvatars))]
	uid, err := user.Insert()
	if err != nil {
		errMsg = "内部服务器错误"
		logger.Errorln(errMsg, ":", err)
		return
	}

	// 存用户登录信息
	userLogin := model.NewUserLogin()
	err = util.ConvertAssign(userLogin, form)
	if err != nil {
		errMsg = err.Error()
		logger.Errorln("CreateUser error:", err)
		return
	}
	userLogin.Uid = uid
	_, err = userLogin.Insert()
	if err != nil {
		errMsg = "内部服务器错误"
		logger.Errorln(errMsg, ":", err)
		return
	}

	// 存用户角色信息
	userRole := model.NewUserRole()
	// 默认为初级会员
	userRole.Roleid = Roles[len(Roles)-1].Roleid
	userRole.Uid = uid
	if _, err = userRole.Insert(); err != nil {
		logger.Errorln("userRole insert Error:", err)
	}

	// 存用户活跃信息,初始活跃+2
	userActive := model.NewUserActive()
	userActive.Uid = uid
	userActive.Username = user.Username
	userActive.Avatar = user.Avatar
	userActive.Email = user.Email
	userActive.Weight = 2
	if _, err = userActive.Insert(); err != nil {
		logger.Errorln("UserActive insert Error:", err)
	}
	return
}
Example #17
0
// 邮件订阅或取消订阅
func EmailSubscribe(uid, unsubscribe int) {
	err := model.NewUser().Set("unsubscribe=?", unsubscribe).Where("uid=?", uid).Update()
	if err != nil {
		logger.Errorln("Email Subscribe Error:", err)
	}
}
Example #18
0
// 订阅邮件通知
func EmailNotice() {

	beginDate := time.Now().Add(-7 * 24 * time.Hour).Format("2006-01-02")
	endDate := time.Now().Add(-24 * time.Hour).Format("2006-01-02")

	beginTime := beginDate + " 00:00:00"

	// 本周晨读(过去 7 天)
	readings, err := model.NewMorningReading().Where("ctime>? AND rtype=0", beginTime).Order("id DESC").FindAll()
	if err != nil {
		logger.Errorln("find morning reading error:", err)
	}

	// 本周精彩文章
	articles, err := model.NewArticle().Where("ctime>? AND status!=2", beginTime).Order("cmtnum DESC, likenum DESC, viewnum DESC").Limit("10").FindAll()
	if err != nil {
		logger.Errorln("find article error:", err)
	}

	// 本周热门主题
	topics, err := model.NewTopic().Where("ctime>? AND flag IN(0,1)", beginTime).Order("tid DESC").Limit("10").FindAll()
	if err != nil {
		logger.Errorln("find topic error:", err)
	}

	data := map[string]interface{}{
		"readings":  readings,
		"articles":  articles,
		"topics":    topics,
		"beginDate": beginDate,
		"endDate":   endDate,
	}

	// 给所有用户发送邮件
	userModel := model.NewUser()

	var (
		lastUid = 0
		limit   = "500"
		users   []*model.User
	)

	for {
		users, err = userModel.Where("uid>?", lastUid).Order("uid ASC").Limit(limit).FindAll()
		if err != nil {
			logger.Errorln("find user error:", err)
			continue
		}

		if len(users) == 0 {
			break
		}

		for _, user := range users {
			if user.Unsubscribe == 1 {
				logger.Infoln("user unsubscribe", user)
				continue
			}

			data["email"] = user.Email
			data["token"] = GenUnsubscribeToken(user)

			content, err := genEmailContent(data)
			if err != nil {
				logger.Errorln("from email.html gen email content error:", err)
				continue
			}

			SendMail("每周精选", content, []string{user.Email})

			if lastUid < user.Uid {
				lastUid = user.Uid
			}

			// 控制发信速度
			time.Sleep(30 * time.Second)
		}
	}

}