Ejemplo n.º 1
0
func (p *socialAuther) LoginUser(ctx *context.Context, uid int) (string, error) {
	user := models.User{Id: uid}
	if user.Read() == nil {
		ctx.Input.CruSession.Set("AuthUsername", user.Username)
	}
	return GetLoginRedirectUrl(ctx), nil
}
Ejemplo n.º 2
0
//通过remember cookie获取登录信息,并且登录
func (this *BaseController) loginViaRememberCookie() (success bool) {
	username := this.Ctx.GetCookie(setting.CookieUserName)
	if len(username) == 0 {
		return false
	}

	defer func() {
		if !success {
			this.DeleteRememberCookie()
		}
	}()

	user := models.User{Username: username}
	if err := user.Read("Username"); err != nil {
		return false
	}

	secret := utils.EncodeMd5(user.Salt + user.Password)
	value, _ := this.Ctx.GetSecureCookie(secret, setting.CookieRememberName)
	if value != username {
		return false
	}
	this.User = &user
	this.LogUserIn(&user, true)

	return true
}
Ejemplo n.º 3
0
func (p *socialAuther) IsUserLogin(ctx *context.Context) (int, bool) {
	if username, ok := ctx.Input.CruSession.Get("AuthUsername").(string); username != "" && ok {
		user := models.User{Username: username}
		if user.Read("Username") == nil {
			return user.Id, true
		}
	}
	return 0, false
}
Ejemplo n.º 4
0
//重设密码
func (this *AuthController) ResetPassword() {
	code := this.Ctx.Input.Param(":code")
	user := models.User{}
	if !user.TestActivateCode(code) {
		this.Abort("403")
	}
	this.Data["code"] = code
	this.Data["PageTitle"] = fmt.Sprintf("重设密码 | %s", setting.AppName)
	this.Layout = "layout.html"
	this.TplNames = "reset-password.html"
	valid := validation.Validation{}
	form := ResetPasswordForm{}
	if this.Ctx.Request.Method == "POST" {
		if err := this.ParseForm(&form); err != nil {
			beego.Error(err)
		}
		b, err := valid.Valid(form)
		if err != nil {
			beego.Error(err)
		}
		if b {
			user.SetPassword(form.Password)
			if err := user.Update(); err != nil {
				beego.Error(err)
				this.Abort("500")
			}
			user.ConsumeActivateCode(code)
			this.FlashWrite("notice", "新密码已经生效,请重新登录!")
			this.Redirect("/login", 302)
		} else {
			this.Data["HasError"] = true
			this.Data["errors"] = valid.Errors
		}
	}
}
Ejemplo n.º 5
0
func (this *AuthController) ValidateEmail() {
	email := this.GetString("email")
	if email == "" {
		email = this.GetString("Email")
	}
	user := models.User{Email: email}
	if user.Read("Email") == nil {
		this.Data["json"] = "已被使用,请直接使用此电邮登录"
	} else {
		this.Data["json"] = true
	}
	this.ServeJson()
}
Ejemplo n.º 6
0
//通过session获取登录信息,并且登录
func (this *BaseController) loginViaSession() bool {
	if username, ok := this.GetSession("AuthUsername").(string); username != "" && ok {
		//beego.Trace("loginViaSession pass 1 Session[AuthUsername]" + username)
		user := models.User{Username: username}
		if user.Read("Username") == nil {
			this.User = &user
			//beego.Trace("loginViaSession pass 2 ")
			return true
		}
		beego.Trace("loginViaSession pass 2 failed ")
	}
	//beego.Trace("loginViaSession failed ")
	return false
}
Ejemplo n.º 7
0
func (this *UserController) resendValidation(user *models.User) {
	//发验证邮件
	sub := sendcloud.NewSubstitution()
	sub.AddTo(user.Email)
	sub.AddSub("%name%", user.Username)
	sub.AddSub("%appname%", setting.AppName)
	code, err := user.GenerateActivateCode()
	if err != nil {
		beego.Trace(err)
		this.Abort("500")
	}
	sub.AddSub("%url%", setting.AppUrl+beego.UrlFor("AuthController.Activate", ":code", code))
	if err := setting.Sendcloud.SendTemplate("gotalk_revalidate", setting.AppName+"邮件验证", setting.From, setting.FromName, sub); err != nil {
		beego.Error(err)
	}
}
Ejemplo n.º 8
0
func (this *AuthController) ValidateUsername() {
	username := this.GetString("username")
	if username == "" {
		username = this.GetString("Username")
	}
	user := models.User{Username: username}
	if err := user.ValidUsername(); err != nil {
		this.Data["json"] = err.Error()
	} else {
		if user.Read("Username") == nil {
			//这个用户名已经存在
			this.Data["json"] = fmt.Sprintf("%s已被使用,请使用其他用户名!", username)
		} else {
			this.Data["json"] = true
		}
	}
	this.ServeJson()
}
Ejemplo n.º 9
0
//输入email,发送重设密码邮件
func (this *AuthController) ForgetPassword() {
	this.Data["PageTitle"] = fmt.Sprintf("忘记密码 | %s", setting.AppName)
	this.Layout = "layout.html"
	this.TplNames = "forget-password.html"
	valid := validation.Validation{}
	form := ForgetPasswordForm{}
	if this.Ctx.Request.Method == "POST" {
		if err := this.ParseForm(&form); err != nil {
			beego.Error(err)
		}
		_, err := valid.Valid(form)
		if err != nil {
			beego.Error(err)
		}
		user := models.User{Email: form.Email}
		if err := user.Read("Email"); err != nil {
			beego.Trace(user)
			beego.Trace(form)
			valid.SetError("Email", "此电子邮件并未注册")
		}
		beego.Trace(valid.Errors)
		if len(valid.Errors) == 0 {
			//发送忘记密码邮件
			code, err := user.GenerateActivateCode()
			if err != nil {
				this.Abort("500")
			}
			sub := sendcloud.NewSubstitution()
			sub.AddTo(user.Email)
			sub.AddSub("%appname%", setting.AppName)
			sub.AddSub("%name%", user.Username)
			sub.AddSub("%url%", setting.AppUrl+beego.UrlFor("AuthController.ResetPassword", ":code", code))
			if err := setting.Sendcloud.SendTemplate("gotalk_password", setting.AppName+"忘记密码", setting.From, setting.FromName, sub); err != nil {
				beego.Error(err)
			}
			this.FlashWrite("notice", fmt.Sprintf("重设密码的方法已经发到%s。请查收!", user.Email))
			this.Redirect("/", 302)
		} else {
			this.Data["HasError"] = true
			this.Data["errors"] = valid.Errors
		}
	}
}
Ejemplo n.º 10
0
func (this *UserController) processUploadAvatar(user *models.User) {
	valid := validation.Validation{}
	avatarFile, header, err := this.GetFile("Avatar")
	if err != nil {
		this.Abort("400")
	}
	err = user.ValidateAndSetAvatar(avatarFile, header.Filename)
	defer avatarFile.Close()
	if err != nil {
		valid.SetError("Avatar", err.Error())
		this.Data["UserAvatarFormValidErrors"] = valid.Errors
	} else {
		if err := user.Update("Avatar"); err != nil {
			this.Abort("500")
		}
		this.FlashWrite("notice", "头像已更新!")
		this.Redirect(this.Ctx.Request.RequestURI, 302)
	}
}
Ejemplo n.º 11
0
func (this *UserController) processUserPasswordForm(user *models.User) {
	valid := validation.Validation{}
	userPasswordForm := UserPasswordForm{}
	if err := this.ParseForm(&userPasswordForm); err != nil {
		beego.Error(err)
	}
	_, err := valid.Valid(userPasswordForm)
	if err != nil {
		beego.Error(err)
		this.Abort("400")
	}
	if !user.VerifyPassword(userPasswordForm.CurrentPassword) {
		valid.SetError("CurrentPassword", "当前密码错误")
	}
	if len(valid.Errors) > 0 {
		this.Data["UserPasswordFormValidErrors"] = valid.Errors
		beego.Trace(fmt.Sprint(valid.Errors))
	} else {
		user.SetPassword(userPasswordForm.Password)
		if err := user.Update(); err != nil {
			this.Abort("500")
		}
		this.FlashWrite("notice", "密码已更新!")
		this.Redirect(this.Ctx.Request.RequestURI, 302)
	}
}
Ejemplo n.º 12
0
func (this *AuthController) DoLogin() {
	this.CheckRequestFrequency(3, 15, 30)
	if this.IsLogin {
		this.Redirect("/", 302)
	}
	valid := validation.Validation{}
	form := LoginForm{}
	if err := this.ParseForm(&form); err != nil {
		beego.Error(err)
	}
	b, err := valid.Valid(form)
	if err != nil {
		beego.Error(err)
	}
	if !b {
		this.loginPageWithErrors(form, valid.Errors)
		return
	}
	//用户不存在?
	user := models.User{Username: form.Username, Email: form.Username}
	if err := user.Read("Username"); err != nil {
		if err2 := user.Read("Email"); err2 != nil {
			errMsg := fmt.Sprintf("用户 %s 不存在!", form.Username)
			beego.Trace(errMsg)
			valid.SetError("username", errMsg)
			this.loginPageWithErrors(form, valid.Errors)
			return
		}
	}
	//用户被禁止?
	if user.IsBanned {
		beego.Trace(fmt.Sprintf("用户%s被禁用,不能登录!", user.Username))
		valid.SetError("username", "抱歉,您被禁止登录!")
		this.loginPageWithErrors(form, valid.Errors)
		return
	}
	//检查密码
	if !user.VerifyPassword(form.Password) {
		beego.Trace(fmt.Sprintf("%s 登录失败!", form.Username))
		valid.SetError("password", "密码错误")
		this.loginPageWithErrors(form, valid.Errors)
		return
	}
	//验证全部通过
	var remember bool
	if form.Remember != "" {
		remember = true
	}
	this.LogUserIn(&user, remember)
	this.Redirect(GetLoginRedirectUrl(this.Ctx), 302)
	return
}
Ejemplo n.º 13
0
func (this *SocialAuthController) processLoginForm(socialType social.SocialType) {
	valid := validation.Validation{}
	form := SocialAuthLoginForm{}
	var user models.User
	if err := this.ParseForm(&form); err != nil {
		beego.Error(err)
	}
	b, err := valid.Valid(form)
	if err != nil {
		beego.Error(err)
	}
	if !b {
		goto showLoginErrors
	}
	//用户不存在?
	user = models.User{Username: form.Username, Email: form.Username}
	if err := user.Read("Username"); err != nil {
		if err2 := user.Read("Email"); err2 != nil {
			errMsg := fmt.Sprintf("用户 %s 不存在!", form.Username)
			valid.SetError("Username", errMsg)
			goto showLoginErrors
		}
	}
	//用户被禁止?
	if user.IsBanned {
		beego.Trace(fmt.Sprintf("用户%s被禁用,不能登录!", user.Username))
		valid.SetError("Username", "抱歉,您被禁止登录!")
		goto showLoginErrors
	}
	//检查密码
	if !user.VerifyPassword(form.Password) {
		beego.Trace(fmt.Sprintf("%s 登录失败!", form.Username))
		valid.SetError("Password", "密码错误")
		goto showLoginErrors
	}
	//验证全部通过
	if loginRedirect, _, err := SocialAuth.ConnectAndLogin(this.Ctx, socialType, user.Id); err != nil {
		beego.Error("ConnectAndLogin:"******"Let's redirect ", loginRedirect)
		this.Redirect(loginRedirect, 302)
		return
	}
showLoginErrors:
	this.Data["LoginForm"] = form
	this.Data["LoginFormErrors"] = valid.Errors
	return
}
Ejemplo n.º 14
0
func (this *AuthController) Activate() {
	this.Data["PageTitle"] = fmt.Sprintf("用户激活 | %s", setting.AppName)
	code := this.Ctx.Input.Param(":code")
	user := models.User{}
	if user.VerifyActivateCode(code) {
		if this.IsStopForumSpamListed(&user) {
			this.FlashWrite("error", "由于你的ip或者电子邮件曾用来发广告,无法为你激活!")
		} else {
			user.IsActive = true
			user.Update()
			this.FlashWrite("notice", "谢谢,你的电子邮件已经验证!")
		}
	} else {
		this.FlashWrite("error", "糟糕,无法验证你的电子邮件!")
	}
	this.Redirect("/", 302)
}
Ejemplo n.º 15
0
func (this *AuthController) DoRegister() {
	this.CheckRequestFrequency(3, 15, 30)
	this.Layout = "layout.html"
	this.TplNames = "register.html"
	valid := validation.Validation{}
	form := RegisterForm{}
	if err := this.ParseForm(&form); err != nil {
		beego.Error(err)
	}
	b, err := valid.Valid(form)
	if err != nil {
		beego.Error(err)
	}
	if !b {
		this.registerPageWithErrors(form, valid.Errors)
		return
	}
	//验证用户名
	user := models.User{Username: form.Username}
	if err := user.ValidUsername(); err != nil {
		valid.SetError("username", err.Error())
		this.registerPageWithErrors(form, valid.Errors)
		return
	} else {
		if user.Read("Username") == nil {
			valid.SetError("username", fmt.Sprintf("%s已被使用,请使用其他用户名!", form.Username))
			this.registerPageWithErrors(form, valid.Errors)
			return
		}
	}
	//验证email未被注册
	user.Email = form.Email
	if user.Read("Email") == nil {
		valid.SetError("email", "已被使用,请直接使用此电邮登录")
		this.registerPageWithErrors(form, valid.Errors)
		return
	}
	//通过所有验证
	actCode, _ := user.GenerateActivateCode()
	user.SetPassword(form.Password)
	if err := user.Insert(); err != nil {
		beego.Error(err)
		this.Abort("500")
		return
	}
	sub := sendcloud.NewSubstitution()
	sub.AddTo(user.Email)
	sub.AddSub("%appname%", setting.AppName)
	sub.AddSub("%name%", user.Username)
	sub.AddSub("%url%", setting.AppUrl+beego.UrlFor("AuthController.Activate", ":code", actCode))
	if err := setting.Sendcloud.SendTemplate("gotalk_register", setting.AppName+"欢迎你", setting.From, setting.FromName, sub); err != nil {
		beego.Error(err)
	}
	this.FlashWrite("notice", fmt.Sprintf("注册成功!欢迎你, %s。建议你再花点时间上传头像、验证电子邮件!", user.Username))
	this.LogUserIn(&user, false)
	userEditUrl := beego.UrlFor("UserController.Edit", ":username", user.Username)
	this.Redirect(userEditUrl, 302)
	return
}
Ejemplo n.º 16
0
func (this *UserController) processUserEditForm(user *models.User) {
	valid := validation.Validation{}
	var usernameChanged, emailChanged bool
	userEditForm := UserEditForm{}
	if err := this.ParseForm(&userEditForm); err != nil {
		beego.Error(err)
	}
	_, err := valid.Valid(userEditForm)
	if err != nil {
		beego.Error(err)
		this.Abort("400")
	}
	if user.Username != userEditForm.Username {
		usernameChanged = true
		if time.Since(user.Created).Hours() <= 720 {
			tmpUser := models.User{Username: userEditForm.Username}
			if err := tmpUser.ValidUsername(); err != nil {
				valid.SetError("Username", err.Error())
			}
			if tmpUser.Read("Username") == nil {
				valid.SetError("Username", "用户名已经被使用")
			}
		} else {
			valid.SetError("Username", "注册超过30天后无法修改用户名")
		}
	}
	if user.Email != userEditForm.Email {
		emailChanged = true
		tmpUser := models.User{Email: userEditForm.Email}
		if err := tmpUser.Read("Email"); err == nil {
			valid.SetError("Email", "电子邮件地址已经被使用")
		}
	}
	user.Url = userEditForm.Url
	if err := user.ValidateUrl(); user.Url != "" && err != nil {
		valid.SetError("Url", err.Error())
	}
	this.Data["UserEditForm"] = &userEditForm
	if len(valid.Errors) > 0 {
		this.Data["UserEditFormValidErrors"] = valid.Errors
		beego.Trace(fmt.Sprint(valid.Errors))
	} else {
		if usernameChanged {
			user.Username = userEditForm.Username
		}
		if emailChanged {
			user.Email = userEditForm.Email
			user.IsActive = false
		}
		user.PublicEmail = userEditForm.PublicEmail
		user.Nickname = userEditForm.Nickname
		user.Info = userEditForm.Info
		user.Company = userEditForm.Company
		user.Location = userEditForm.Location
		user.Url = userEditForm.Url
		user.Qq = userEditForm.Qq
		user.Weibo = userEditForm.Weibo
		user.WeChat = userEditForm.WeChat
		if err := user.Update(); err != nil {
			this.Abort("500")
		}
		if usernameChanged && this.User.Id == user.Id {
			this.LogUserIn(user, false)
		}
		if emailChanged {
			//发验证邮件
			this.resendValidation(user)
			this.FlashWrite("notice", fmt.Sprintf("资料已经更新。由于修改了Email地址,我们向%s发送了一封验证邮件,请重新验证。", user.Email))
		} else {
			this.FlashWrite("notice", "资料已更新!")
		}
		redirectUrl := beego.UrlFor("UserController.Edit", ":username", user.Username)
		this.Redirect(redirectUrl, 302)
	}
}
Ejemplo n.º 17
0
func (this *SocialAuthController) Connect() {
	this.Data["PageTitle"] = fmt.Sprintf("社交帐号登录 | %s", setting.AppName)
	this.Layout = "layout.html"
	this.TplNames = "social-login.html"
	if this.IsLogin {
		this.Redirect("/", 302)
	}
	//检查社交帐号登录是否正常
	var socialType social.SocialType
	if !this.canConnect(&socialType) {
		beego.Error(this.GetString("error_description"))
		this.Abort("500")
		this.Redirect(SocialAuth.LoginURL, 302)
		return
	}
	p, _ := social.GetProviderByType(socialType)
	if p == nil {
		beego.Error("unknown provider")
	}
	var socialUserLogin, socialUserEmail, socialUserAvatarUrl string
	var ok bool
	if socialUserLogin, ok = this.GetSession("social_user_login").(string); !ok {
		beego.Error("error while reading session ")
		this.Abort("500")
	}
	if socialUserEmail, ok = this.GetSession("social_user_email").(string); !ok {
		beego.Error("error while reading session ")
		this.Abort("500")
	}
	if socialUserAvatarUrl, ok = this.GetSession("social_user_avatar_url").(string); !ok {
		beego.Error("error while reading session ")
		this.Abort("500")
	}
	this.Data["SocialType"] = p.GetName()
	this.Data["SocialUserLogin"] = socialUserLogin
	this.Data["SocialUserEmail"] = socialUserEmail
	this.Data["SocialUserAvatarUrl"] = socialUserAvatarUrl
	//准备注册表格初始数据
	registerForm := SocialAuthRegisterForm{}
	var user models.User
	if this.Ctx.Input.IsGet() {
		user = models.User{Username: socialUserLogin}
		if user.Read("Username") == nil {
			registerForm.Username = socialUserLogin + utils.GetRandomString(3)
			this.Data["UsernameTakenMsg"] = fmt.Sprintf("%s已经被使用,如果你不喜欢我们帮你选的%s,请修改", socialUserLogin, registerForm.Username)
		} else {
			registerForm.Username = socialUserLogin
		}
		if socialUserEmail != "" {
			user = models.User{Email: socialUserEmail}
			if user.Read("Email") == nil {
				registerForm.Email = ""
			} else {
				registerForm.Email = socialUserEmail
			}
		}
		this.Data["RegisterForm"] = registerForm
	}

	if this.Ctx.Input.IsPost() {
		this.CheckRequestFrequency(3, 15, 30)
		action := this.GetString("action")
		switch action {
		case "Register":
			this.processRegisterForm(socialType, registerForm, socialUserAvatarUrl)
		case "Login":
			this.processLoginForm(socialType)
		}
	}

}
Ejemplo n.º 18
0
func (this *SocialAuthController) processRegisterForm(socialType social.SocialType, form SocialAuthRegisterForm, socialUserAvatarUrl string) {
	valid := validation.Validation{}
	var user models.User
	var actCode string
	var sub *sendcloud.Substitution
	var resp *http.Response
	if err := this.ParseForm(&form); err != nil {
		beego.Error(err)
	}
	if err := this.ParseForm(&form); err != nil {
		beego.Error(err)
	}
	b, err := valid.Valid(form)
	if err != nil {
		beego.Error(err)
	}
	if !b {
		goto showRegisterErrors
	}
	//验证用户名
	user = models.User{Username: form.Username}
	if err := user.ValidUsername(); err != nil {
		valid.SetError("Username", err.Error())
		goto showRegisterErrors
	} else {
		if user.Read("Username") == nil {
			valid.SetError("Username", fmt.Sprintf("%s已被使用,请使用其他用户名!", form.Username))
			goto showRegisterErrors
		}
	}
	//验证email未被注册
	user.Email = form.Email
	if user.Read("Email") == nil {
		valid.SetError("Email", "已被使用,请直接使用此电邮登录")
		goto showRegisterErrors
	}
	//通过所有验证
	actCode, _ = user.GenerateActivateCode()
	user.SetPassword(form.Password)
	if err := user.Insert(); err != nil {
		beego.Error(err)
		this.Abort("500")
		return
	}
	sub = sendcloud.NewSubstitution()
	sub.AddTo(user.Email)
	sub.AddSub("%appname%", setting.AppName)
	sub.AddSub("%name%", user.Username)
	sub.AddSub("%url%", setting.AppUrl+beego.UrlFor("AuthController.Activate", ":code", actCode))
	if err := setting.Sendcloud.SendTemplate("gotalk_register", setting.AppName+"欢迎你", setting.From, setting.FromName, sub); err != nil {
		beego.Error(err)
	}
	//复制头像
	if resp, err = http.Get(socialUserAvatarUrl); err != nil {
		beego.Error(fmt.Sprintf("Error opening url:%s", socialUserAvatarUrl))
		this.Abort("500")
		return
	}
	defer resp.Body.Close()
	if err := user.ValidateAndSetAvatar(resp.Body, ""); err != nil {
		beego.Error("error copying avatar ", socialUserAvatarUrl, "error: ", err.Error())
	}
	if err := user.Update(); err != nil {
		beego.Error("error update avatar for user ", user.Username)
	}

	this.FlashWrite("notice", fmt.Sprintf("注册成功!欢迎你, %s。建议你再花点时间验证电子邮件!", user.Username))
	if loginRedirect, _, err := SocialAuth.ConnectAndLogin(this.Ctx, socialType, user.Id); err != nil {
		beego.Error("ConnectAndLogin:"******"Let's redirect ", loginRedirect)
		this.Redirect(loginRedirect, 302)
		return
	}
showRegisterErrors:
	this.Data["RegisterForm"] = form
	this.Data["RegisterormErrors"] = valid.Errors
	return
}