Esempio n. 1
0
// URL: /change_password
// 修改密码
func changePasswordHandler(w http.ResponseWriter, r *http.Request) {
	user, ok := currentUser(r)

	if !ok {
		http.Redirect(w, r, "/signin?next=/change_password", http.StatusFound)
		return
	}

	form := wtforms.NewForm(
		wtforms.NewPasswordField("current_password", "当前密码", wtforms.Required{}),
		wtforms.NewPasswordField("new_password", "新密码", wtforms.Required{}),
		wtforms.NewPasswordField("confirm_password", "新密码确认", wtforms.Required{}),
	)

	if r.Method == "POST" && form.Validate(r) {
		if form.Value("new_password") == form.Value("confirm_password") {
			currentPassword := encryptPassword(form.Value("current_password"))
			if currentPassword == user.Password {
				c := DB.C("users")
				c.Update(bson.M{"_id": user.Id_}, bson.M{"$set": bson.M{"password": encryptPassword(form.Value("new_password"))}})
				message(w, r, "密码修改成功", `密码修改成功`, "success")
				return
			} else {
				form.AddError("current_password", "当前密码错误")
			}
		} else {
			form.AddError("confirm_password", "密码不匹配")
		}
	}

	renderTemplate(w, r, "account/change_password.html", map[string]interface{}{"form": form})
}
Esempio n. 2
0
// URL: /change_password
// 修改密码
func changePasswordHandler(handler Handler) {
	user, _ := currentUser(handler)

	form := wtforms.NewForm(
		wtforms.NewPasswordField("current_password", "当前密码", wtforms.Required{}),
		wtforms.NewPasswordField("new_password", "新密码", wtforms.Required{}),
		wtforms.NewPasswordField("confirm_password", "新密码确认", wtforms.Required{}),
	)

	if handler.Request.Method == "POST" && form.Validate(handler.Request) {
		if form.Value("new_password") == form.Value("confirm_password") {
			currentPassword := encryptPassword(form.Value("current_password"))
			if currentPassword == user.Password {
				c := handler.DB.C(USERS)
				c.Update(bson.M{"_id": user.Id_}, bson.M{"$set": bson.M{"password": encryptPassword(form.Value("new_password"))}})
				message(handler, "密码修改成功", `密码修改成功`, "success")
				return
			} else {
				form.AddError("current_password", "当前密码错误")
			}
		} else {
			form.AddError("confirm_password", "密码不匹配")
		}
	}

	renderTemplate(handler, "account/change_password.html", BASE, map[string]interface{}{"form": form})
}
Esempio n. 3
0
// URL: /user_center/change_password
// 修改密码
func changePasswordHandler(handler *Handler) {
	user, _ := currentUser(handler)

	form := wtforms.NewForm(
		wtforms.NewPasswordField("current_password", "当前密码", wtforms.Required{}),
		wtforms.NewPasswordField("new_password", "新密码", wtforms.Required{}),
		wtforms.NewPasswordField("confirm_password", "新密码确认", wtforms.Required{}),
	)

	if handler.Request.Method == "POST" && form.Validate(handler.Request) {
		if form.Value("new_password") == form.Value("confirm_password") {
			if user.CheckPassword(form.Value("current_password")) {
				c := handler.DB.C(USERS)
				salt := strings.Replace(uuid.NewUUID().String(), "-", "", -1)
				c.Update(bson.M{"_id": user.Id_}, bson.M{"$set": bson.M{
					"password": encryptPassword(form.Value("new_password"), salt),
					"salt":     salt,
				}})
				message(handler, "密码修改成功", `密码修改成功`, "success")
				return
			} else {
				form.AddError("current_password", "当前密码错误")
			}
		} else {
			form.AddError("confirm_password", "密码不匹配")
		}
	}

	handler.renderTemplate("user_center/change_password.html", BASE, map[string]interface{}{
		"form":   form,
		"active": "change_password",
	})
}
Esempio n. 4
0
// URL: /login
// 处理用户登录,如果登录成功,设置Cookie
func loginHandler(handler Handler) {

	form := wtforms.NewForm(
		wtforms.NewTextField("username", "用户名", "", &wtforms.Required{}),
		wtforms.NewPasswordField("password", "密码", &wtforms.Required{}),
	)

	if handler.Request.Method == "POST" {
		if form.Validate(handler.Request) {

			if form.Value("username") == "sll" &&
				form.Value("password") == "123456" {
			} else {
				form.AddError("password", "密码和用户名不匹配")

				renderHtml(handler, "login.html", map[string]interface{}{"form": form})
				return
			}

			session, _ := store.Get(handler.Request, "user")
			session.Values["username"] = form.Value("username")
			session.Save(handler.Request, handler.ResponseWriter)

			http.Redirect(handler.ResponseWriter, handler.Request, "/", http.StatusFound)

			return
		}
	}

	renderHtml(handler, "login.html", map[string]interface{}{"form": form})
}
Esempio n. 5
0
File: account.go Progetto: nosqldb/G
// wrapAuthHandler返回符合 go.auth包要求签名的函数.
func wrapAuthHandler(handler *Handler) func(w http.ResponseWriter, r *http.Request, u auth.User) {
	return func(w http.ResponseWriter, r *http.Request, u auth.User) {
		c := handler.DB.C(USERS)
		user := User{}
		session, _ := store.Get(r, "user")
		c.Find(bson.M{"username": u.Id()}).One(&user)
		//关联github帐号,直接登录
		if user.Provider == GITHUB_COM {
			session.Values["username"] = user.Username
			session.Save(r, w)
			http.Redirect(w, r, "/", http.StatusSeeOther)
		}
		form := wtforms.NewForm(wtforms.NewTextField("username", "用户名", "", wtforms.Required{}),
			wtforms.NewPasswordField("password", "密码", wtforms.Required{}))
		session.Values[GITHUB_EMAIL] = u.Email()
		session.Values[GITHUB_ID] = u.Id()
		session.Values[GITHUB_LINK] = u.Link()
		session.Values[GITHUB_NAME] = u.Name()
		session.Values[GITHUB_ORG] = u.Org()
		session.Values[GITHUB_PICTURE] = u.Picture()
		session.Values[GITHUB_PROVIDER] = u.Provider()
		session.Save(r, w)

		//关联已有帐号
		if handler.Request.Method == "POST" {
			if form.Validate(handler.Request) {
				user := User{}
				err := c.Find(bson.M{"username": form.Value("username")}).One(&user)
				if err != nil {
					form.AddError("username", "该用户不存在")
					handler.renderTemplate("accoun/auth_login.html", BASE, map[string]interface{}{"form": form})
					return
				}

				if !ComparePwd(form.Value("password"), user.Password) {
					form.AddError("password", "密码和用户名不匹配")

					handler.renderTemplate("account/auth_login.html", BASE, map[string]interface{}{"form": form, "captchaId": captcha.New()})
					return
				}
				c.UpdateId(user.Id_, bson.M{"$set": bson.M{
					"emal":       session.Values[GITHUB_EMAIL],
					"accountref": session.Values[GITHUB_NAME],
					"username":   session.Values[GITHUB_ID],
					"idref":      session.Values[GITHUB_ID],
					"linkref":    session.Values[GITHUB_LINK],
					"orgref":     session.Values[GITHUB_ORG],
					"pictureref": session.Values[GITHUB_PICTURE],
					"provider":   session.Values[GITHUB_PROVIDER],
				}})
				deleteGithubValues(session)
				session.Values["username"] = u.Name()
				session.Save(r, w)
				http.Redirect(handler.ResponseWriter, handler.Request, "/", http.StatusFound)
			}
		}
		handler.renderTemplate("account/auth_login.html", BASE, map[string]interface{}{"form": form})
	}
}
Esempio n. 6
0
// URL: /reset/{code}
// 用户点击邮件中的链接,根据code找到对应的用户,设置新密码,修改完成后清除code
func resetPasswordHandler(handler *Handler) {
	vars := mux.Vars(handler.Request)
	code := vars["code"]

	var user User
	c := handler.DB.C(USERS)
	err := c.Find(bson.M{"resetcode": code}).One(&user)

	if err != nil {
		message(handler, "重设密码", `无效的重设密码标记,可能你已经重新设置过了或者链接已经失效,请通过<a href="/forgot_password">忘记密码</a>进行重设密码`, "error")
		return
	}

	form := wtforms.NewForm(
		wtforms.NewPasswordField("new_password", "新密码", wtforms.Required{}),
		wtforms.NewPasswordField("confirm_password", "确认新密码", wtforms.Required{}),
	)

	if handler.Request.Method == "POST" && form.Validate(handler.Request) {
		if form.Value("new_password") == form.Value("confirm_password") {
			salt := strings.Replace(uuid.NewUUID().String(), "-", "", -1)
			c.Update(
				bson.M{"_id": user.Id_},
				bson.M{
					"$set": bson.M{
						"password":  encryptPassword(form.Value("new_password"), salt),
						"salt":      salt,
						"resetcode": "",
					},
				},
			)
			message(handler, "重设密码成功", `密码重设成功,你现在可以 <a href="/signin" class="btn btn-primary">登录</a> 了`, "success")
			return
		} else {
			form.AddError("confirm_password", "密码不匹配")
		}
	}

	handler.renderTemplate("account/reset_password.html", BASE, map[string]interface{}{"form": form, "code": code, "account": user.Username})
}
Esempio n. 7
0
// URL: /signin
// 处理用户登录,如果登录成功,设置Cookie
func signinHandler(w http.ResponseWriter, r *http.Request) {
	next := r.FormValue("next")

	form := wtforms.NewForm(
		wtforms.NewHiddenField("next", next),
		wtforms.NewTextField("username", "用户名", "", &wtforms.Required{}),
		wtforms.NewPasswordField("password", "密码", &wtforms.Required{}),
	)

	if r.Method == "POST" {
		if form.Validate(r) {
			c := DB.C("users")
			user := User{}

			err := c.Find(bson.M{"username": form.Value("username")}).One(&user)

			if err != nil {
				form.AddError("username", "该用户不存在")

				renderTemplate(w, r, "account/signin.html", map[string]interface{}{"form": form})
				return
			}

			if !user.IsActive {
				form.AddError("username", "邮箱没有经过验证,如果没有收到邮件,请联系管理员")
				renderTemplate(w, r, "account/signin.html", map[string]interface{}{"form": form})
				return
			}

			if user.Password != encryptPassword(form.Value("password")) {
				form.AddError("password", "密码和用户名不匹配")

				renderTemplate(w, r, "account/signin.html", map[string]interface{}{"form": form})
				return
			}

			session, _ := store.Get(r, "user")
			session.Values["username"] = user.Username
			session.Save(r, w)

			if form.Value("next") == "" {
				http.Redirect(w, r, "/", http.StatusFound)
			} else {
				http.Redirect(w, r, next, http.StatusFound)
			}

			return
		}
	}

	renderTemplate(w, r, "account/signin.html", map[string]interface{}{"form": form})
}
Esempio n. 8
0
// URL: /reset/{code}
// 用户点击邮件中的链接,根据code找到对应的用户,设置新密码,修改完成后清除code
func resetPasswordHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	code := vars["code"]

	var user User
	c := DB.C("users")
	err := c.Find(bson.M{"resetcode": code}).One(&user)

	if err != nil {
		message(w, r, "重设密码", `无效的重设密码标记,可能你已经重新设置过了或者链接已经失效,请通过<a href="/forgot_password">忘记密码</a>进行重设密码`, "error")
		return
	}

	form := wtforms.NewForm(
		wtforms.NewPasswordField("new_password", "新密码", wtforms.Required{}),
		wtforms.NewPasswordField("confirm_password", "确认新密码", wtforms.Required{}),
	)

	if r.Method == "POST" && form.Validate(r) {
		if form.Value("new_password") == form.Value("confirm_password") {
			c.Update(
				bson.M{"_id": user.Id_},
				bson.M{
					"$set": bson.M{
						"password":  encryptPassword(form.Value("new_password")),
						"resetcode": "",
					},
				},
			)
			message(w, r, "重设密码成功", `密码重设成功,你现在可以 <a href="/signin" class="btn btn-primary">登录</a> 了`, "success")
			return
		} else {
			form.AddError("confirm_password", "密码不匹配")
		}
	}

	renderTemplate(w, r, "account/reset_password.html", map[string]interface{}{"form": form, "code": code, "account": user.Username})
}
Esempio n. 9
0
// URL: /signup
// 处理用户注册,要求输入用户名,密码和邮箱
func signupHandler(w http.ResponseWriter, r *http.Request) {
	form := wtforms.NewForm(
		wtforms.NewTextField("username", "用户名", "", wtforms.Required{}, wtforms.Regexp{Expr: `^[a-zA-Z0-9_]{3,16}$`, Message: "请使用a-z, A-Z, 0-9以及下划线, 长度3-16之间"}),
		wtforms.NewPasswordField("password", "密码", wtforms.Required{}),
		wtforms.NewTextField("email", "电子邮件", "", wtforms.Required{}, wtforms.Email{}),
	)

	if r.Method == "POST" {
		if form.Validate(r) {
			c := DB.C("users")

			result := User{}

			// 检查用户名
			err := c.Find(bson.M{"username": form.Value("username")}).One(&result)
			if err == nil {
				form.AddError("username", "该用户名已经被注册")

				renderTemplate(w, r, "account/signup.html", map[string]interface{}{"form": form})
				return
			}

			// 检查邮箱
			err = c.Find(bson.M{"email": form.Value("email")}).One(&result)

			if err == nil {
				form.AddError("email", "电子邮件地址已经被注册")

				renderTemplate(w, r, "account/signup.html", map[string]interface{}{"form": form})
				return
			}

			c2 := DB.C("status")
			var status Status
			c2.Find(nil).One(&status)

			id := bson.NewObjectId()
			username := form.Value("username")
			validateCode := strings.Replace(uuid.NewUUID().String(), "-", "", -1)
			index := status.UserIndex + 1
			err = c.Insert(&User{
				Id_:          id,
				Username:     username,
				Password:     encryptPassword(form.Value("password")),
				Email:        form.Value("email"),
				ValidateCode: validateCode,
				IsActive:     true,
				JoinedAt:     time.Now(),
				Index:        index,
			})

			if err != nil {
				panic(err)
			}

			c2.Update(bson.M{"_id": status.Id_}, bson.M{"$inc": bson.M{"userindex": 1, "usercount": 1}})

			// 发送邮件
			/*
							subject := "欢迎加入Golang 中国"
							message2 := `欢迎加入Golang 中国。请访问下面地址激活你的帐户。

				<a href="%s/activate/%s">%s/activate/%s</a>

				如果你没有注册,请忽略这封邮件。

				©2012 Golang 中国`
							message2 = fmt.Sprintf(message2, config["host"], validateCode, config["host"], validateCode)
							sendMail(subject, message2, []string{form.Value("email")})

							message(w, r, "注册成功", "请查看你的邮箱进行验证,如果收件箱没有,请查看垃圾邮件,如果还没有,请给[email protected]发邮件,告知你的用户名。", "success")
			*/
			// 注册成功后设成登录状态
			session, _ := store.Get(r, "user")
			session.Values["username"] = username
			session.Save(r, w)

			// 跳到修改用户信息页面
			http.Redirect(w, r, "/profile", http.StatusFound)
			return
		}
	}

	renderTemplate(w, r, "account/signup.html", map[string]interface{}{"form": form})
}
Esempio n. 10
0
// URL: /signin
// 处理用户登录,如果登录成功,设置Cookie
func signinHandler(handler *Handler) {
	// 如果已经登录了,跳转到首页
	_, has := currentUser(handler)
	if has {
		handler.Redirect("/")
	}

	next := handler.Request.FormValue("next")

	form := wtforms.NewForm(
		wtforms.NewHiddenField("next", next),
		wtforms.NewTextField("username", "用户名", "", &wtforms.Required{}),
		wtforms.NewPasswordField("password", "密码", &wtforms.Required{}),
		wtforms.NewTextField("geetest_challenge", "challenge", ""),
		wtforms.NewTextField("geetest_validate", "validate", ""),
		wtforms.NewTextField("geetest_seccode", "seccode", ""),
	)

	geeTest := geetest.NewGeeTest(Config.GtCaptchaId, Config.GtPrivateKey)

	if handler.Request.Method == "POST" {
		if form.Validate(handler.Request) {
			// 检查验证码
			if !geeTest.Validate(form.Value("geetest_challenge"), form.Value("geetest_validate"), form.Value("geetest_seccode")) {
				handler.renderTemplate("account/signin.html", BASE, map[string]interface{}{
					"form":       form,
					"captchaErr": true,
				})
				return
			}

			c := handler.DB.C(USERS)
			user := User{}

			err := c.Find(bson.M{"username": form.Value("username")}).One(&user)

			if err != nil {
				form.AddError("username", "该用户不存在")

				handler.renderTemplate("account/signin.html", BASE, map[string]interface{}{
					"form":  form,
					"gtUrl": geeTest.EmbedURL(),
				})
				return
			}

			if !user.IsActive {
				form.AddError("username", "邮箱没有经过验证,如果没有收到邮件,请联系管理员")

				handler.renderTemplate("account/signin.html", BASE, map[string]interface{}{
					"form":  form,
					"gtUrl": geeTest.EmbedURL(),
				})
				return
			}

			if !user.CheckPassword(form.Value("password")) {
				form.AddError("password", "密码和用户名不匹配")

				handler.renderTemplate("account/signin.html", BASE, map[string]interface{}{
					"form":  form,
					"gtUrl": geeTest.EmbedURL(),
				})
				return
			}

			session, _ := store.Get(handler.Request, "user")
			session.Values["username"] = user.Username
			session.Save(handler.Request, handler.ResponseWriter)

			if form.Value("next") == "" {
				http.Redirect(handler.ResponseWriter, handler.Request, "/", http.StatusFound)
			} else {
				http.Redirect(handler.ResponseWriter, handler.Request, next, http.StatusFound)
			}

			return
		}
	}

	handler.renderTemplate("account/signin.html", BASE, map[string]interface{}{
		"form":  form,
		"gtUrl": geeTest.EmbedURL(),
	})
}
Esempio n. 11
0
// URL: /signup
// 处理用户注册,要求输入用户名,密码和邮箱
func signupHandler(handler *Handler) {
	// 如果已经登录了,跳转到首页
	_, has := currentUser(handler)
	if has {
		handler.Redirect("/")
	}

	geeTest := geetest.NewGeeTest(Config.GtCaptchaId, Config.GtPrivateKey)

	var username string
	var email string
	session, _ := store.Get(handler.Request, "user")
	if handler.Request.Method == "GET" {
		//如果是从新建关联过来的就自动填充字段
		if session.Values[GITHUB_PROVIDER] == GITHUB_COM {
			username = session.Values[GITHUB_ID].(string)
			email = session.Values[GITHUB_EMAIL].(string)
		}
	}
	form := wtforms.NewForm(
		wtforms.NewTextField("username", "用户名", username, wtforms.Required{}, wtforms.Regexp{Expr: `^[a-zA-Z0-9_]{3,16}$`, Message: "请使用a-z, A-Z, 0-9以及下划线, 长度3-16之间"}),
		wtforms.NewPasswordField("password", "密码", wtforms.Required{}),
		wtforms.NewTextField("email", "电子邮件", email, wtforms.Required{}, wtforms.Email{}),
		wtforms.NewTextField("geetest_challenge", "challenge", ""),
		wtforms.NewTextField("geetest_validate", "validate", ""),
		wtforms.NewTextField("geetest_seccode", "seccode", ""),
	)

	if handler.Request.Method == "POST" {
		if form.Validate(handler.Request) {
			// 检查验证码
			if !geeTest.Validate(form.Value("geetest_challenge"), form.Value("geetest_validate"), form.Value("geetest_seccode")) {
				handler.renderTemplate("account/signup.html", BASE, map[string]interface{}{
					"form":       form,
					"gtUrl":      geeTest.EmbedURL(),
					"captchaErr": true,
				})
				return
			}

			c := handler.DB.C(USERS)

			result := User{}

			// 检查用户名
			err := c.Find(bson.M{"username": form.Value("username")}).One(&result)
			if err == nil {
				form.AddError("username", "该用户名已经被注册")

				handler.renderTemplate("account/signup.html", BASE, map[string]interface{}{
					"form":  form,
					"gtUrl": geeTest.EmbedURL(),
				})
				return
			}

			// 检查邮箱
			err = c.Find(bson.M{"email": form.Value("email")}).One(&result)

			if err == nil {
				form.AddError("email", "电子邮件地址已经被注册")

				handler.renderTemplate("account/signup.html", BASE, map[string]interface{}{
					"form":  form,
					"gtUrl": geeTest.EmbedURL(),
				})
				return
			}

			c2 := handler.DB.C(STATUS)
			var status Status
			c2.Find(nil).One(&status)

			id := bson.NewObjectId()
			username := form.Value("username")
			validateCode := strings.Replace(uuid.NewUUID().String(), "-", "", -1)
			salt := strings.Replace(uuid.NewUUID().String(), "-", "", -1)
			index := status.UserIndex + 1
			u := &User{
				Id_:          id,
				Username:     username,
				Password:     encryptPassword(form.Value("password"), salt),
				Avatar:       "", // defaultAvatars[rand.Intn(len(defaultAvatars))],
				Salt:         salt,
				Email:        form.Value("email"),
				ValidateCode: validateCode,
				IsActive:     true,
				JoinedAt:     time.Now(),
				Index:        index,
			}
			if session.Values[GITHUB_PROVIDER] == GITHUB_COM {
				u.GetGithubValues(session)
				defer deleteGithubValues(session)
			}
			err = c.Insert(u)
			if err != nil {
				logger.Println(err)
				return
			}

			c2.Update(nil, bson.M{"$inc": bson.M{"userindex": 1, "usercount": 1}})

			// 重新生成users.json字符串
			generateUsersJson(handler.DB)

			// 注册成功后设成登录状态
			session, _ := store.Get(handler.Request, "user")
			session.Values["username"] = username
			session.Save(handler.Request, handler.ResponseWriter)

			// 跳到修改用户信息页面
			handler.redirect("/user_center/edit_info", http.StatusFound)
			return
		}
	}
	handler.renderTemplate("account/signup.html", BASE, map[string]interface{}{
		"form":  form,
		"gtUrl": geeTest.EmbedURL(),
	})
}
Esempio n. 12
0
// URL: /signin
// 处理用户登录,如果登录成功,设置Cookie
func signinHandler(handler *Handler) {
	// 如果已经登录了,跳转到首页
	_, has := currentUser(handler)
	if has {
		handler.Redirect("/")
	}

	next := handler.Request.FormValue("next")

	form := wtforms.NewForm(
		wtforms.NewHiddenField("next", next),
		wtforms.NewTextField("username", "用户名", "", &wtforms.Required{}),
		wtforms.NewPasswordField("password", "密码", &wtforms.Required{}),
		wtforms.NewTextField("captcha", "验证码", "", wtforms.Required{}),
		wtforms.NewHiddenField("captchaId", ""),
	)

	if handler.Request.Method == "POST" {
		if form.Validate(handler.Request) {
			// 检查验证码
			if !captcha.VerifyString(form.Value("captchaId"), form.Value("captcha")) {
				form.AddError("captcha", "验证码错误")
				form.SetValue("captcha", "")

				handler.renderTemplate("account/signin.html", BASE, map[string]interface{}{"form": form, "captchaId": captcha.New()})
				return
			}

			c := handler.DB.C(USERS)
			user := User{}

			err := c.Find(bson.M{"username": form.Value("username")}).One(&user)

			if err != nil {
				form.AddError("username", "该用户不存在")
				form.SetValue("captcha", "")

				handler.renderTemplate("account/signin.html", BASE, map[string]interface{}{"form": form, "captchaId": captcha.New()})
				return
			}

			if !user.IsActive {
				form.AddError("username", "邮箱没有经过验证,如果没有收到邮件,请联系管理员")
				form.SetValue("captcha", "")

				handler.renderTemplate("account/signin.html", BASE, map[string]interface{}{"form": form, "captchaId": captcha.New()})
				return
			}

			if user.Password != encryptPassword(form.Value("password"), user.Salt) {
				form.AddError("password", "密码和用户名不匹配")
				form.SetValue("captcha", "")

				handler.renderTemplate("account/signin.html", BASE, map[string]interface{}{"form": form, "captchaId": captcha.New()})
				return
			}

			session, _ := store.Get(handler.Request, "user")
			session.Values["username"] = user.Username
			session.Save(handler.Request, handler.ResponseWriter)

			if form.Value("next") == "" {
				http.Redirect(handler.ResponseWriter, handler.Request, "/", http.StatusFound)
			} else {
				http.Redirect(handler.ResponseWriter, handler.Request, next, http.StatusFound)
			}

			return
		}
	}

	form.SetValue("captcha", "")
	handler.renderTemplate("account/signin.html", BASE, map[string]interface{}{"form": form, "captchaId": captcha.New()})
}
Esempio n. 13
0
// URL: /signup
// 处理用户注册,要求输入用户名,密码和邮箱
func signupHandler(handler *Handler) {
	// 如果已经登录了,跳转到首页
	_, has := currentUser(handler)
	if has {
		handler.Redirect("/")
	}

	var username string
	var email string
	session, _ := store.Get(handler.Request, "user")
	if handler.Request.Method == "GET" {
		//如果是从新建关联过来的就自动填充字段
		if session.Values[GITHUB_PROVIDER] == GITHUB_COM {
			username = session.Values[GITHUB_ID].(string)
			email = session.Values[GITHUB_EMAIL].(string)
		}
	}
	form := wtforms.NewForm(
		wtforms.NewTextField("username", "用户名", username, wtforms.Required{}, wtforms.Regexp{Expr: `^[a-zA-Z0-9_]{3,16}$`, Message: "请使用a-z, A-Z, 0-9以及下划线, 长度3-16之间"}),
		wtforms.NewPasswordField("password", "密码", wtforms.Required{}),
		wtforms.NewTextField("email", "电子邮件", email, wtforms.Required{}, wtforms.Email{}),
		wtforms.NewTextField("captcha", "验证码", "", wtforms.Required{}),
		wtforms.NewHiddenField("captchaId", ""),
	)

	if handler.Request.Method == "POST" {
		if form.Validate(handler.Request) {
			// 检查验证码
			if !captcha.VerifyString(form.Value("captchaId"), form.Value("captcha")) {
				form.AddError("captcha", "验证码错误")
				fmt.Println("captcha")
				form.SetValue("captcha", "")

				handler.renderTemplate("account/signup.html", BASE, map[string]interface{}{"form": form, "captchaId": captcha.New()})
				return
			}

			c := handler.DB.C(USERS)

			result := User{}

			// 检查用户名
			err := c.Find(bson.M{"username": form.Value("username")}).One(&result)
			if err == nil {
				form.AddError("username", "该用户名已经被注册")
				form.SetValue("captcha", "")

				handler.renderTemplate("account/signup.html", BASE, map[string]interface{}{"form": form, "captchaId": captcha.New()})
				return
			}

			// 检查邮箱
			err = c.Find(bson.M{"email": form.Value("email")}).One(&result)

			if err == nil {
				form.AddError("email", "电子邮件地址已经被注册")
				form.SetValue("captcha", "")

				handler.renderTemplate("account/signup.html", BASE, map[string]interface{}{"form": form, "captchaId": captcha.New()})
				return
			}

			c2 := handler.DB.C(STATUS)
			var status Status
			c2.Find(nil).One(&status)

			id := bson.NewObjectId()
			username := form.Value("username")
			validateCode := strings.Replace(uuid.NewUUID().String(), "-", "", -1)
			salt := strings.Replace(uuid.NewUUID().String(), "-", "", -1)
			index := status.UserIndex + 1
			u := &User{
				Id_:          id,
				Username:     username,
				Password:     encryptPassword(form.Value("password"), salt),
				Avatar:       "", // defaultAvatars[rand.Intn(len(defaultAvatars))],
				Salt:         salt,
				Email:        form.Value("email"),
				ValidateCode: validateCode,
				IsActive:     true,
				JoinedAt:     time.Now(),
				Index:        index,
			}
			if session.Values[GITHUB_PROVIDER] == GITHUB_COM {
				u.GetGithubValues(session)
				defer deleteGithubValues(session)
			}
			err = c.Insert(u)
			if err != nil {
				logger.Println(err)
				return
			}

			c2.Update(nil, bson.M{"$inc": bson.M{"userindex": 1, "usercount": 1}})

			// 重新生成users.json字符串
			generateUsersJson(handler.DB)

			// 发送邮件
			/*
							subject := "欢迎加入Golang 中国"
							message2 := `欢迎加入Golang 中国。请访问下面地址激活你的帐户。

				<a href="%s/activate/%s">%s/activate/%s</a>

				如果你没有注册,请忽略这封邮件。

				©2012 Golang 中国`
							message2 = fmt.Sprintf(message2, config["host"], validateCode, config["host"], validateCode)
							sendMail(subject, message2, []string{form.Value("email")})

							message(w, r, "注册成功", "请查看你的邮箱进行验证,如果收件箱没有,请查看垃圾邮件,如果还没有,请给[email protected]发邮件,告知你的用户名。", "success")
			*/
			// 注册成功后设成登录状态
			session, _ := store.Get(handler.Request, "user")
			session.Values["username"] = username
			session.Save(handler.Request, handler.ResponseWriter)

			// 跳到修改用户信息页面
			http.Redirect(handler.ResponseWriter, handler.Request, "/profile", http.StatusFound)
			return
		}
	}
	form.SetValue("captcha", "")
	handler.renderTemplate("account/signup.html", BASE, map[string]interface{}{"form": form, "captchaId": captcha.New()})
}