Пример #1
0
func LoginUserFromRememberCookie(user *models.User, ctx *context.Context) (success bool) {
	userName := ctx.GetCookie(setting.CookieUserName)
	if len(userName) == 0 {
		return false
	}

	defer func() {
		if !success {
			DeleteRememberCookie(ctx)
		}
	}()

	user.UserName = userName
	if err := user.Read("UserName"); err != nil {
		return false
	}

	secret := utils.EncodeMd5(user.Rands + user.Password)
	value, _ := ctx.GetSecureCookie(secret, setting.CookieRememberName)
	if value != userName {
		return false
	}

	LoginUser(user, ctx, true)

	return true
}
Пример #2
0
// Active implemented check Email actice code.
func (this *RegisterRouter) Active() {
	this.TplNames = "auth/active.html"

	// no need active
	if this.CheckActiveRedirect(false) {
		return
	}

	code := this.GetString(":code")

	var user models.User

	if auth.VerifyUserActiveCode(&user, code) {
		user.IsActive = true
		user.Rands = models.GetUserSalt()
		if err := user.Update("IsActive", "Rands", "Updated"); err != nil {
			beego.Error("Active: user Update ", err)
		}
		if this.IsLogin {
			this.User = user
		}

		this.Redirect("/active/success", 302)

	} else {
		this.Data["Success"] = false
	}
}
Пример #3
0
// register create user
func RegisterUser(user *models.User, username, email, password string, locale i18n.Locale) error {
	// use random salt encode password
	salt := models.GetUserSalt()
	pwd := utils.EncodePassword(password, salt)

	user.UserName = strings.ToLower(username)
	user.Email = strings.ToLower(email)

	// save salt and encode password, use $ as split char
	user.Password = fmt.Sprintf("%s$%s", salt, pwd)

	// save md5 email value for gravatar
	user.GrEmail = utils.EncodeMd5(user.Email)

	// Use username as default nickname.
	user.NickName = user.UserName

	//set default language
	if locale.Lang == "en-US" {
		user.Lang = setting.LangEnUS
	} else {
		user.Lang = setting.LangZhCN
	}

	//set default avatar
	user.AvatarType = setting.AvatarTypeGravatar
	return user.Insert()
}
Пример #4
0
func (this *UserRouter) Home() {
	this.TplName = "user/home.html"

	var user models.User
	if this.getUser(&user) {
		return
	}

	limit := 5

	var posts []*models.Post
	var comments []*models.Comment

	user.RecentPosts().Limit(limit).RelatedSel().All(&posts)
	user.RecentComments().Limit(limit).RelatedSel().All(&comments)

	var ftopics []*models.FollowTopic
	var topics []*models.Topic
	nums, _ := models.FollowTopics().Filter("User", &user.Id).Limit(8).OrderBy("-Created").RelatedSel("Topic").All(&ftopics, "Topic")
	if nums > 0 {
		topics = make([]*models.Topic, 0, nums)
		for _, ft := range ftopics {
			topics = append(topics, ft.Topic)
		}
	}
	this.Data["TheUserTopics"] = topics
	this.Data["TheUserTopicsMore"] = nums >= 8

	this.Data["TheUserPosts"] = posts
	this.Data["TheUserComments"] = comments
}
Пример #5
0
func (p *socialAuther) LoginUser(ctx *context.Context, uid int) (string, error) {
	user := models.User{Id: uid}
	if user.Read() == nil {
		auth.LoginUser(&user, ctx, true)
	}
	return auth.GetLoginRedirect(ctx), nil
}
Пример #6
0
// Reset implemented user password reset.
func (this *ForgotRouter) ResetPost() {
	this.TplNames = "auth/reset.html"

	code := this.GetString(":code")
	this.Data["Code"] = code

	var user models.User

	if auth.VerifyUserResetPwdCode(&user, code) {
		this.Data["Success"] = true

		form := auth.ResetPwdForm{}
		if this.ValidFormSets(&form) == false {
			return
		}

		user.IsActive = true
		user.Rands = models.GetUserSalt()

		if err := auth.SaveNewPassword(&user, form.Password); err != nil {
			beego.Error("ResetPost Save New Password: "******"/login", 302, "ResetSuccess")

	} else {
		this.Data["Success"] = false
	}
}
Пример #7
0
func (form *PostAdminForm) Valid(v *validation.Validation) {
	user := models.User{Id: form.User}
	if user.Read() != nil {
		v.SetError("User", "admin.not_found_by_id")
	}

	user.Id = form.LastReply
	if user.Read() != nil {
		v.SetError("LastReply", "admin.not_found_by_id")
	}

	user.Id = form.LastAuthor
	if user.Read() != nil {
		v.SetError("LastReply", "admin.not_found_by_id")
	}

	topic := models.Topic{Id: form.Topic}
	if topic.Read() != nil {
		v.SetError("Topic", "admin.not_found_by_id")
	}

	cat := models.Category{Id: form.Category}
	if cat.Read() != nil {
		v.SetError("Category", "admin.not_found_by_id")
	}

	if len(i18n.GetLangByIndex(form.Lang)) == 0 {
		v.SetError("Lang", "Not Found")
	}
}
Пример #8
0
func (form *CommentAdminForm) Valid(v *validation.Validation) {
	user := models.User{Id: form.User}
	if user.Read() != nil {
		v.SetError("User", "admin.not_found_by_id")
	}

	post := models.Post{Id: form.Post}
	if post.Read() != nil {
		v.SetError("Post", "admin.not_found_by_id")
	}
}
Пример #9
0
// get user if key exist in session
func GetUserFromSession(user *models.User, sess session.Store) bool {
	id := GetUserIdFromSession(sess)
	if id > 0 {
		u := models.User{Id: id}
		if u.Read() == nil {
			*user = u
			return true
		}
	}

	return false
}
Пример #10
0
// check if exist user by username or email
func HasUser(user *models.User, username string) bool {
	var err error
	qs := orm.NewOrm()
	if strings.IndexRune(username, '@') == -1 {
		user.UserName = username
		err = qs.Read(user, "UserName")
	} else {
		user.Email = username
		err = qs.Read(user, "Email")
	}
	if err == nil {
		return true
	}
	return false
}
Пример #11
0
// view for new object save
func (this *UserAdminRouter) Save() {
	form := auth.UserAdminForm{Create: true}
	if this.ValidFormSets(&form) == false {
		return
	}

	var user models.User
	form.SetToUser(&user)
	if err := user.Insert(); err == nil {
		this.FlashRedirect(fmt.Sprintf("/admin/user/%d", user.Id), 302, "CreateSuccess")
		return
	} else {
		beego.Error(err)
		this.Data["Error"] = err
	}
}
Пример #12
0
// get user by erify code
func getVerifyUser(user *models.User, code string) bool {
	if len(code) <= utils.TimeLimitCodeLength {
		return false
	}

	// use tail hex username query user
	hexStr := code[utils.TimeLimitCodeLength:]
	if b, err := hex.DecodeString(hexStr); err == nil {
		user.UserName = string(b)
		if user.Read("UserName") == nil {
			return true
		}
	}

	return false
}
Пример #13
0
func (form *ProfileForm) SaveUserProfile(user *models.User) error {
	// set md5 value if the value is an email
	if strings.IndexRune(form.GrEmail, '@') != -1 {
		form.GrEmail = utils.EncodeMd5(form.GrEmail)
	}

	changes := utils.FormChanges(user, form)
	if len(changes) > 0 {
		// if email changed then need re-active
		if user.Email != form.Email {
			user.IsActive = false
			changes = append(changes, "IsActive")
		}

		utils.SetFormValues(form, user)
		return user.Update(changes...)
	}
	return nil
}
Пример #14
0
func (this *UserRouter) Comments() {
	this.TplNames = "user/comments.html"

	var user models.User
	if this.getUser(&user) {
		return
	}

	limit := 20

	qs := user.RecentComments()
	nums, _ := qs.Count()

	pager := this.SetPaginator(limit, nums)

	var comments []*models.Comment
	qs.Limit(limit, pager.Offset()).RelatedSel().All(&comments)

	this.Data["TheUserComments"] = comments
}
Пример #15
0
func (this *UserRouter) FavoritePosts() {
	this.TplNames = "user/favorite-posts.html"

	var user models.User
	if this.getUser(&user) {
		return
	}

	var postIds orm.ParamsList
	var posts []models.Post
	nums, _ := user.FavoritePosts().OrderBy("-Created").ValuesFlat(&postIds, "Post")
	if nums > 0 {
		qs := models.Posts().Filter("Id__in", postIds)
		cnt, _ := models.CountObjects(qs)
		pager := this.SetPaginator(setting.PostCountPerPage, cnt)
		qs = qs.OrderBy("-Created").Limit(setting.PostCountPerPage, pager.Offset()).RelatedSel()
		models.ListObjects(qs, &posts)
	}

	this.Data["TheUserFavoritePosts"] = posts
}
Пример #16
0
func (this *UserRouter) getUser(user *models.User) bool {
	username := this.GetString(":username")
	user.UserName = username

	err := user.Read("UserName")
	if err != nil {
		this.Abort("404")
		return true
	}

	IsFollowed := false

	if this.IsLogin {
		if this.User.Id != user.Id {
			IsFollowed = this.User.FollowingUsers().Filter("FollowUser", user.Id).Exist()
		}
	}

	this.Data["TheUser"] = &user
	this.Data["IsFollowed"] = IsFollowed

	return false
}
Пример #17
0
func (this *UserRouter) Home() {
	this.Data["IsUserHomePage"] = true
	this.TplNames = "user/home.html"

	var user models.User
	if this.getUser(&user) {
		return
	}

	//recent posts and comments
	limit := 5

	var posts []*models.Post
	var comments []*models.Comment

	user.RecentPosts().Limit(limit).RelatedSel().All(&posts)
	user.RecentComments().Limit(limit).RelatedSel().All(&comments)

	this.Data["TheUserPosts"] = posts
	this.Data["TheUserComments"] = comments

	//follow topics
	var ftopics []*models.FollowTopic
	var topics []*models.Topic
	ftNums, _ := models.FollowTopics().Filter("User", &user.Id).Limit(8).OrderBy("-Created").RelatedSel("Topic").All(&ftopics, "Topic")
	if ftNums > 0 {
		topics = make([]*models.Topic, 0, ftNums)
		for _, ft := range ftopics {
			topics = append(topics, ft.Topic)
		}
	}
	this.Data["TheUserFollowTopics"] = topics
	this.Data["TheUserFollowTopicsMore"] = ftNums >= 8

	//favorite posts
	var favPostIds orm.ParamsList
	var favPosts []models.Post
	favNums, _ := user.FavoritePosts().Limit(8).OrderBy("-Created").ValuesFlat(&favPostIds, "Post")
	if favNums > 0 {
		qs := models.Posts().Filter("Id__in", favPostIds)
		qs = qs.OrderBy("-Created").RelatedSel()
		models.ListObjects(qs, &favPosts)
	}
	this.Data["TheUserFavoritePosts"] = favPosts
	this.Data["TheUserFavoritePostsMore"] = favNums >= 8

}
Пример #18
0
// register create user
func RegisterUser(user *models.User, username, email, password string) error {
	// use random salt encode password
	salt := models.GetUserSalt()
	pwd := utils.EncodePassword(password, salt)

	user.UserName = strings.ToLower(username)
	user.Email = strings.ToLower(email)

	// save salt and encode password, use $ as split char
	user.Password = fmt.Sprintf("%s$%s", salt, pwd)

	// save md5 email value for gravatar
	user.GrEmail = utils.EncodeMd5(user.Email)

	// Use username as default nickname.
	user.NickName = user.UserName

	return user.Insert()
}
Пример #19
0
//set a new avatar type to user
func SaveAvatarType(user *models.User, avatarType int) error {
	user.AvatarType = avatarType
	return user.Update("AvatarType", "Updated")
}
Пример #20
0
func UserFollow(user *models.User, theUser *models.User) {
	if theUser.Read() == nil {
		var mutual bool
		tFollow := models.Follow{User: theUser, FollowUser: user}
		if err := tFollow.Read("User", "FollowUser"); err == nil {
			mutual = true
		}

		follow := models.Follow{User: user, FollowUser: theUser, Mutual: mutual}
		if err := follow.Insert(); err == nil && mutual {
			tFollow.Mutual = mutual
			tFollow.Update("Mutual")
		}

		if nums, err := user.FollowingUsers().Count(); err == nil {
			user.Following = int(nums)
			user.Update("Following")
		}

		if nums, err := theUser.FollowerUsers().Count(); err == nil {
			theUser.Followers = int(nums)
			theUser.Update("Followers")
		}
	}
}
Пример #21
0
//upload user avatar
func UploadUserAvatarToQiniu(r io.ReadSeeker, filename string, mime string, bucketName string, user *models.User) error {
	var ext string

	// test image mime type
	switch mime {
	case "image/jpeg":
		ext = ".jpg"

	case "image/png":
		ext = ".png"

	case "image/gif":
		ext = ".gif"

	default:
		ext = filepath.Ext(filename)
		switch ext {
		case ".jpg", ".png", ".gif":
		default:
			return fmt.Errorf("unsupport image format `%s`", filename)
		}
	}

	// decode image
	var err error
	switch ext {
	case ".jpg":
		_, err = jpeg.Decode(r)
	case ".png":
		_, err = png.Decode(r)
	case ".gif":
		_, err = gif.Decode(r)
	}

	if err != nil {
		return err
	}

	//reset reader pointer
	if _, err := r.Seek(0, 0); err != nil {
		return err
	}
	var data []byte
	if data, err = ioutil.ReadAll(r); err != nil {
		return err
	}

	if len(data) > setting.AvatarImageMaxLength {
		return fmt.Errorf("avatar image size too large", filename)
	}

	//reset reader pointer again
	if _, err := r.Seek(0, 0); err != nil {
		return err
	}

	//save to qiniu
	var uptoken = utils.GetQiniuUptoken(bucketName)
	var putRet qio.PutRet
	var putExtra = &qio.PutExtra{
		MimeType: mime,
	}

	err = qio.PutWithoutKey(nil, &putRet, uptoken, r, putExtra)
	if err != nil {
		return err
	}

	//update user
	user.AvatarKey = putRet.Key
	if err := user.Update("AvatarKey", "Updated"); err != nil {
		return err
	}
	return nil
}
Пример #22
0
func (this *UserRouter) getFollows(user *models.User, following bool) []map[string]interface{} {
	limit := 20

	var qs orm.QuerySeter

	if following {
		qs = user.FollowingUsers()
	} else {
		qs = user.FollowerUsers()
	}

	nums, _ := qs.Count()

	pager := this.SetPaginator(limit, nums)

	qs = qs.Limit(limit, pager.Offset())

	var follows []*models.Follow

	if following {
		qs.RelatedSel("FollowUser").All(&follows, "FollowUser")
	} else {
		qs.RelatedSel("User").All(&follows, "User")
	}

	if len(follows) == 0 {
		return nil
	}

	ids := make([]int, 0, len(follows))
	for _, follow := range follows {
		if following {
			ids = append(ids, follow.FollowUser.Id)
		} else {
			ids = append(ids, follow.User.Id)
		}
	}

	var eids orm.ParamsList
	this.User.FollowingUsers().Filter("FollowUser__in", ids).ValuesFlat(&eids, "FollowUser__Id")

	var fids map[int]bool
	if len(eids) > 0 {
		fids = make(map[int]bool)
		for _, id := range eids {
			tid, _ := utils.StrTo(utils.ToStr(id)).Int()
			if tid > 0 {
				fids[tid] = true
			}
		}
	}

	users := make([]map[string]interface{}, 0, len(follows))
	for _, follow := range follows {
		IsFollowed := false
		var u *models.User
		if following {
			u = follow.FollowUser
		} else {
			u = follow.User
		}
		if fids != nil {
			IsFollowed = fids[u.Id]
		}
		users = append(users, map[string]interface{}{
			"User":       u,
			"IsFollowed": IsFollowed,
		})
	}

	return users
}
Пример #23
0
// set a new password to user
func SaveNewPassword(user *models.User, password string) error {
	salt := models.GetUserSalt()
	user.Password = fmt.Sprintf("%s$%s", salt, utils.EncodePassword(password, salt))
	return user.Update("Password", "Rands", "Updated")
}
Пример #24
0
func UserUnFollow(user *models.User, theUser *models.User) {
	num, _ := user.FollowingUsers().Filter("FollowUser", theUser.Id).Delete()
	if num > 0 {
		theUser.FollowingUsers().Filter("FollowUser", user.Id).Update(orm.Params{
			"Mutual": false,
		})

		if nums, err := user.FollowingUsers().Count(); err == nil {
			user.Following = int(nums)
			user.Update("Following")
		}

		if nums, err := theUser.FollowerUsers().Count(); err == nil {
			theUser.Followers = int(nums)
			theUser.Update("Followers")
		}
	}
}
Пример #25
0
func (form *PageAdminForm) Valid(v *validation.Validation) {
	user := models.User{Id: form.User}
	if user.Read() != nil {
		v.SetError("User", "admin.not_found_by_id")
	}
}