예제 #1
0
func (this *UserController) Login() {
	if this.Ctx.Input.Method() == "GET" {
		if this.GetSession("user") != nil {
			this.Redirect("/", 302)
		}
		this.TplNames = "console/login.html"
		return
	}

	json := this.ReqJson()
	email := json.Get("email").MustString()
	password := json.Get("password").MustString()

	valid := validation.Validation{}
	valid.Email(email, "email")
	valid.MinSize(password, 6, "passwordMin")
	valid.MaxSize(password, 12, "passwordMax")

	if valid.HasErrors() {
		this.CustomAbort(enum.RespCode.BadRequest.Code(), enum.RespCode.BadRequest.Str())
	}

	user := user.GetUserByEmail(email)
	if user == nil {
		//用户不存在
		this.RespJson(enum.RespCode.UserNotExist, nil)
	} else if util.Md5(user.Salt+password) != user.Password {
		//密码错误
		this.RespJson(enum.RespCode.PasswordIncorrect, nil)
	} else {
		this.SetSession("user", user)
		this.RespJson(enum.RespCode.OK, map[string]interface{}{"url": "/"})
	}
}
예제 #2
0
파일: user.go 프로젝트: elvizlai/MGBlog
//用户登录
func (this *User) Login() {
	json := this.ReqJson()
	if json != nil {
		email := json.Get("email").MustString()
		password := json.Get("password").MustString()

		valid := validation.Validation{}
		valid.Email(email, "email")
		valid.MinSize(password, 6, "passwordMin")
		valid.MaxSize(password, 12, "passwordMax")

		if valid.HasErrors() {
			this.CustomAbort(enum.BadRequest.Code(), enum.BadRequest.Str())
		}

		u := user.GetUserByEmail(email)
		if u == nil {
			//用户不存在
			this.RespJson(enum.UserNotExist, nil)
		} else if util.Md5(u.Salt+password) != u.Password {
			//密码错误
			this.RespJson(enum.PasswordIncorrect, nil)
		} else {
			this.SetSession("uId", u.Id.Hex())
			user.SetToken(u.Id, this.StartSession().SessionID()) //using cookie as token
			this.RespJson(enum.OK, map[string]interface{}{"url": "/"})
		}
	}
}
예제 #3
0
파일: user.go 프로젝트: elvizlai/Blog-mysql
//注册 todo 错误处理的优雅封装
func (this *User) Register() {
	reqBody := this.Ctx.Input.RequestBody
	reqJson, err := simplejson.NewJson(reqBody)

	//非法请求
	if err != nil {
		this.Abort("400")
	}

	email := reqJson.Get("email").MustString()
	nickname := reqJson.Get("nickname").MustString()
	password := reqJson.Get("password").MustString()

	valid := validation.Validation{}
	valid.Email(email, "email")            //邮箱
	valid.MinSize(nickname, 5, "nickname") //昵称至少5位
	valid.MinSize(password, 6, "password") //密码至少6位

	//非法请求
	if valid.HasErrors() {
		this.Abort("400")
	}

	enumResult := user.AddUser(email, nickname, password)
	fmt.Println(enumResult)

	this.Data["json"] = map[string]interface{}{"code": enumResult, "msg": enumResult.String()}
	this.ServeJson()
}
예제 #4
0
func (l *LoginController) Recovery() {

	email := l.GetString("email")
	valid := validation.Validation{}
	valid.Email(email, "email")
	if valid.HasErrors() {
		var msg string
		for _, err := range valid.Errors {
			msg += fmt.Sprintf("%s: %s\r", err.Key, err.Message)
		}
		l.Ctx.ResponseWriter.WriteHeader(400)
		l.Data["json"] = &map[string]interface{}{"status": "error", "message": msg}
		l.ServeJson()
		return
	}

	user, _ := rbacModels.UserGetByEmail(email)
	if user.Id == 0 {
		l.Data["json"] = &map[string]interface{}{"status": "error", "message": "Пользователь не найден"}
	} else {
		site_url := beego.AppConfig.String("site_url")
		reset_token, _ := user.GenResetPassToken()
		params := map[string]interface{}{}
		params["user:one-time-login-url"] = fmt.Sprintf("%s/admin/reset?token=%s", site_url, reset_token)
		msg := emailSystem.New()
		msg.Template = "email_password_reset"
		msg.Params = &params
		msg.User = user
		if err := msg.SendMail(); err == nil {
			l.Data["json"] = &map[string]interface{}{"status": "info", "message": "Дальнейшие инструкции высланы на указанный почтовый ящик"}
		}
	}

	l.ServeJson()
}
예제 #5
0
파일: user.go 프로젝트: elvizlai/MGBlog
//用户注册
func (this *User) Register() {
	req := this.ReqJson()
	if req != nil {
		email := req.Get("email").MustString()
		nickName := req.Get("nickName").MustString()
		password := req.Get("password").MustString()

		valid := validation.Validation{}
		valid.Email(email, "email")
		valid.MinSize(nickName, 6, "nickNameMin")
		valid.MaxSize(nickName, 12, "nickNameMax")
		valid.MinSize(password, 6, "passwordMin")
		valid.MaxSize(password, 12, "passwordMax")

		if valid.HasErrors() {
			this.CustomAbort(enum.BadRequest.Code(), enum.BadRequest.Str())
		}

		err := user.AddUser(email, nickName, password)
		if err == nil {
			this.RespJson(enum.OK, nil)
		} else {
			if strings.Contains(err.Error(), "email") {
				this.RespJson(enum.EmailAlreadyExist, nil)
			} else if strings.Contains(err.Error(), "nickname") {
				this.RespJson(enum.NickNameAlreadyExist, nil)
			} else {
				beego.Error(err)
			}
		}
	}
}
예제 #6
0
func (form *LoginForm) Valid(v *validation.Validation) {
	valid := validation.Validation{}
	valid.Email(form.Email, "email")
	if valid.HasErrors() {
		v.SetError("Email", form.Locale.Tr("valid.invalid_email"))
	}
}
예제 #7
0
func TestEmailValidate(t *testing.T) {
	mail := "406504302qq.com"
	valid := validation.Validation{}

	if !valid.Email(mail, "email").Ok {
		fmt.Println("mail 格式错误")
	}
}
예제 #8
0
파일: validation.go 프로젝트: sndnvaps/gooa
//表单验证
func ValidUser(m *BUser) string {
	v := validation.Validation{}
	v.Required(m.Username, "username").Message("邮箱不能为空")
	v.Required(m.Password, "password").Message("密码不能为空")
	v.Email(m.Username, "username").Message("邮箱格式不正确")
	if v.HasErrors() {
		// 如果有错误信息,证明验证没通过
		return utils.WrapErrors(v.Errors)
	}
	return ""
}
예제 #9
0
파일: user.go 프로젝트: cnitfarmer/blog
//编辑用户
func (this *UserController) Edit() {
	id, _ := this.GetInt("id")
	user := models.User{Id: id}
	if err := user.Read(); err != nil {
		this.showmsg("用户不存在")
	}

	errmsg := make(map[string]string)

	if this.Ctx.Request.Method == "POST" {
		password := strings.TrimSpace(this.GetString("password"))
		password2 := strings.TrimSpace(this.GetString("password2"))
		email := strings.TrimSpace(this.GetString("email"))
		active, _ := this.GetInt("active")
		valid := validation.Validation{}

		if password != "" {
			if v := valid.Required(password2, "password2"); !v.Ok {
				errmsg["password2"] = "请再次输入密码"
			} else if password != password2 {
				errmsg["password2"] = "两次输入的密码不一致"
			} else {
				user.Password = models.Md5([]byte(password))
			}
		}
		if v := valid.Required(email, "email"); !v.Ok {
			errmsg["email"] = "请输入email地址"
		} else if v := valid.Email(email, "email"); !v.Ok {
			errmsg["email"] = "Email无效"
		} else {
			user.Email = email
		}

		if active > 0 {
			user.Active = 1
		} else {
			user.Active = 0
		}

		if len(errmsg) == 0 {
			user.Update()
			this.Redirect("/admin/user/list", 302)
		}
	}
	this.Data["errmsg"] = errmsg
	this.Data["user"] = user
	this.display()
}
예제 #10
0
파일: users.go 프로젝트: Jackgris/mstock
// We will check if the user data are valid
func (u User) Valid() bool {
	v := validation.Validation{}
	v.Required(u.Name, "name")
	v.MaxSize(u.Name, 20, "nameMax")
	v.Required(u.Pass, "pass")
	v.MaxSize(u.Pass, 30, "passMax")
	v.Email(u.Email, "email")

	if v.HasErrors() {
		for _, e := range v.Errors {
			log.Println("Check valid user data:", e)
		}
		return false
	}

	return true
}
예제 #11
0
func (c *TUserController) ValidEmail() {
	email := c.GetString("email")
	valid := validation.Validation{}
	valid.Email(email, "Email")
	valid.MaxSize(email, 50, "Email")
	if valid.HasErrors() {
		c.Data["json"] = map[string]string{"error": "邮箱不正确"}
	} else {
		err := models.ValidEmail(email)
		if err == nil {
			c.Data["json"] = map[string]string{"error": "邮箱已经存在"}
		} else {
			c.Data["json"] = map[string]string{"message": "这个邮箱未被注册"}
		}
	}
	c.ServeJson()
}
예제 #12
0
func CheckUserMail(mail string) error {

	valid := validation.Validation{}

	if !valid.Email(mail, "email").Ok {
		return errors.New("邮箱格式错误")
	}

	orm := orm.NewOrm()

	count, err := orm.QueryTable("user").Filter("mail", mail).Count()

	if nil != err || count > 0 {
		return exception.USER_MAIL_EXISTENT
	}

	return nil
}
예제 #13
0
func (this *MainController) Forgot() {
	this.activeContent("user/forgot")

	if this.Ctx.Input.Method() == "POST" {
		email := this.GetString("email")
		valid := validation.Validation{}
		valid.Email(email, "email")
		if valid.HasErrors() {
			errormap := make(map[string]string)
			for _, err := range valid.Errors {
				errormap[err.Key] = err.Message
			}
			this.Data["Errors"] = errormap
			return
		}

		flash := beego.NewFlash()

		o := orm.NewOrm()
		o.Using("default")
		user := models.AuthUser{Email: email}
		err := o.Read(&user, "Email")
		if err != nil {
			flash.Error("No such user/email in our records")
			flash.Store(&this.Controller)
			return
		}

		u := uuid.NewV4()
		user.Reset_key = u.String()
		_, err = o.Update(&user)
		if err != nil {
			flash.Error("Internal error")
			flash.Store(&this.Controller)
			return
		}
		domainname := this.Data["domainname"]
		this.sendRequestReset(email, u.String(), domainname.(string))
		flash.Notice("You've been sent a reset password link. You must check your email.")
		flash.Store(&this.Controller)
		this.Redirect("/notice", 302)
	}
}
예제 #14
0
func FundUser(name string, password string) (entities.User, error) {
	var err error
	var user entities.User

	orm := orm.NewOrm()
	querySetter := orm.QueryTable("user").Filter("password", password)

	valid := validation.Validation{}

	if valid.Email(name, "email").Ok {
		querySetter = querySetter.Filter("mail", name)
	} else {
		querySetter = querySetter.Filter("name", name)
	}

	err = querySetter.One(&user, "id", "name", "nick", "password", "age", "cell", "mail", "sex", "CreatedAt", "UpdatedAt")

	return user, err
}
예제 #15
0
파일: user.go 프로젝트: elvizlai/Blog-mysql
//登录
func (this *User) Login() {
	fmt.Println(this)
	reqBody := this.Ctx.Input.RequestBody
	fmt.Println(string(reqBody))
	reqJson, err := simplejson.NewJson(reqBody)

	//非法请求
	if err != nil {
		this.Abort("400")
	}
	fmt.Println(reqJson)

	email := reqJson.Get("email").MustString()
	password := reqJson.Get("password").MustString()

	valid := validation.Validation{}
	valid.Email(email, "email")
	valid.MinSize(password, 6, "password") //密码至少6位

	//非法请求
	if valid.HasErrors() {
		this.Abort("400")
	}
	fmt.Println(reqJson)

	if currentUser := user.FindUser(email); currentUser == nil {
		this.Data["json"] = map[string]interface{}{"code": enum.UserNotExist, "msg": enum.UserNotExist.String()}
	} else {
		if currentUser.Password != common.Md5(password+currentUser.Salt) {
			this.Data["json"] = map[string]interface{}{"code": enum.PasswordError, "msg": enum.PasswordError.String()}
		} else {
			this.Data["json"] = map[string]interface{}{"code": enum.OK, "msg": enum.OK.String()}
			//讲token写入cookie
			token := user.UpdateCookieToken(*currentUser)
			this.SetSession(this.Ctx.GetCookie("token"), token)
		}
	}
	this.ServeJson()
}
예제 #16
0
func (this *UserController) Register() {
	if this.Ctx.Input.Method() == "GET" {
		if can, err := beego.AppConfig.Bool("CanBeRegister"); err == nil && can {
			this.Data["CanBeRegister"] = true
		}
		this.TplNames = "console/register.html"
		return
	}

	req := this.ReqJson()
	email := req.Get("email").MustString()
	nickName := req.Get("nickName").MustString()
	password := req.Get("password").MustString()

	valid := validation.Validation{}
	valid.Email(email, "email")
	valid.MinSize(nickName, 6, "nickNameMin")
	valid.MaxSize(nickName, 12, "nickNameMax")
	valid.MinSize(password, 6, "passwordMin")
	valid.MaxSize(password, 12, "passwordMax")

	if valid.HasErrors() {
		this.CustomAbort(enum.RespCode.BadRequest.Code(), enum.RespCode.BadRequest.Str())
	}

	err := user.AddUser(email, nickName, password)
	if err == nil {
		this.RespJson(enum.RespCode.OK, nil)
	} else {
		if strings.Contains(err.Error(), "email") {
			this.RespJson(enum.RespCode.EmailExist, nil)
		} else if strings.Contains(err.Error(), "nick_name") {
			this.RespJson(enum.RespCode.NickNameExist, nil)
		} else {
			beego.Error(err)
		}
	}
}
예제 #17
0
파일: main.go 프로젝트: sndnvaps/gooa
func (this *MainController) DoReg() {
	var (
		name       string = strings.TrimSpace(this.GetString("name"))
		phone      string = this.GetString("phone")
		address    string = strings.TrimSpace(this.GetString("address"))
		email      string = strings.TrimSpace(this.GetString("email"))
		pw         string = strings.TrimSpace(this.GetString("pw"))
		pw_confirm string = strings.TrimSpace(this.GetString("pw_confirm"))
	)
	flash := beego.NewFlash()

	c := &models.BCompany{Name: name, Phone: phone, Address: address}
	u := &models.BUser{Username: email, Password: pw, Email: email}

	v := validation.Validation{}
	v.Required(c.Name, "name").Message("单位名称不能为空")
	v.Required(c.Phone, "phone").Message("电话不能为空")
	v.Required(c.Address, "address").Message("地址不能为空")
	v.Required(u.Username, "username").Message("邮箱不能为空")
	v.Required(u.Password, "password").Message("密码不能为空")
	v.Email(u.Username, "username").Message("邮箱格式不正确")

	if pw != pw_confirm {
		v.SetError("password", "密码与确认密码不匹配")
	}

	errorString := ""
	if v.HasErrors() {
		errorString = utils.WrapErrors(v.Errors)
	}

	if errorString != "" {
		// validation does not pass
		log.Println(errorString)
		flash.Set("error", errorString)
		flash.Set("name", name)
		flash.Set("phone", phone)
		flash.Set("address", address)
		flash.Set("email", email)
		flash.Store(&this.Controller)

		url := utils.U("reg")
		this.Redirect(url, 302)
	} else {
		//insert into db
		//check email exists
		if buser.IsUserEmailExists(email) {
			v.SetError("username", "邮件已存在,不能重复注册。")
			flash.Set("error", utils.WrapErrors(v.Errors))
			flash.Store(&this.Controller)
			url := utils.U("reg")
			this.Redirect(url, 302)
		} else {
			c.Createdate = time.Now().Unix()
			u.Created_on = time.Now().Unix()

			u.Password = utils.Md5(u.Password)
			cid, err := bcompany.Insert(c)

			if err == nil && cid > 0 {
				u.Cid = cid
				uid, uerr := buser.Insert(u)
				if uerr == nil && uid > 0 {
					url := utils.U("home")
					this.Redirect(url, 302)
				}
			}

			flash.Set("error", utils.WrapString("注册出错,请联系管理员"))
			flash.Store(&this.Controller)
			url := utils.U("reg")
			this.Redirect(url, 302)
		}

	}
}
예제 #18
0
파일: user.go 프로젝트: cnitfarmer/blog
//添加用户
func (this *UserController) Add() {
	input := make(map[string]string)
	errmsg := make(map[string]string)
	if this.Ctx.Request.Method == "POST" {
		username := strings.TrimSpace(this.GetString("username"))
		password := strings.TrimSpace(this.GetString("password"))
		password2 := strings.TrimSpace(this.GetString("password2"))
		email := strings.TrimSpace(this.GetString("email"))
		active, _ := this.GetInt("active")

		input["username"] = username
		input["password"] = password
		input["password2"] = password2
		input["email"] = email

		valid := validation.Validation{}

		if v := valid.Required(username, "username"); !v.Ok {
			errmsg["username"] = "******"
		} else if v := valid.MaxSize(username, 15, "username"); !v.Ok {
			errmsg["username"] = "******"
		}

		if v := valid.Required(password, "password"); !v.Ok {
			errmsg["password"] = "******"
		}

		if v := valid.Required(password2, "password2"); !v.Ok {
			errmsg["password2"] = "请再次输入密码"
		} else if password != password2 {
			errmsg["password2"] = "两次输入的密码不一致"
		}

		if v := valid.Required(email, "email"); !v.Ok {
			errmsg["email"] = "请输入email地址"
		} else if v := valid.Email(email, "email"); !v.Ok {
			errmsg["email"] = "Email无效"
		}

		if active > 0 {
			active = 1
		} else {
			active = 0
		}

		if len(errmsg) == 0 {
			var user models.User
			user.Username = username
			user.Password = models.Md5([]byte(password))
			user.Email = email
			user.Active = int8(active)
			if err := user.Insert(); err != nil {
				this.showmsg(err.Error())
			}
			this.Redirect("/admin/user/list", 302)
		}

	}

	this.Data["input"] = input
	this.Data["errmsg"] = errmsg
	this.display()
}
예제 #19
0
// 自定义数据验证
func (this *Accounts) Valid(v *validation.Validation) {
	//登录名必须是email
	if this.LoginName != "" {
		v.Email(this.LoginName, "loginName")
	}
}
예제 #20
0
func (this *MainController) Profile() {
	this.activeContent("user/profile")

	//******** This page requires login
	sess := this.GetSession("acme")
	if sess == nil {
		this.Redirect("/user/login/home", 302)
		return
	}
	m := sess.(map[string]interface{})

	flash := beego.NewFlash()

	//******** Read password hash from database
	var x pk.PasswordHash

	x.Hash = make([]byte, 32)
	x.Salt = make([]byte, 16)

	o := orm.NewOrm()
	o.Using("default")
	user := models.AuthUser{Username: m["username"].(string)}
	err := o.Read(&user, "Username")
	if err == nil {
		// scan in the password hash/salt
		if x.Hash, err = hex.DecodeString(user.Password[:64]); err != nil {
			fmt.Println("ERROR:", err)
		}
		if x.Salt, err = hex.DecodeString(user.Password[64:]); err != nil {
			fmt.Println("ERROR:", err)
		}
	} else {
		flash.Error("Internal error")
		flash.Store(&this.Controller)
		return
	}

	// Create an applist

	//Get all running apps
	url := "http://107.167.184.225:8080/v2/apps/"
	//bytestring := []byte(newstring)
	req, err := http.NewRequest("GET", url, nil)

	if err != nil {
		panic(err)
	}

	//Make the request
	res, err := http.DefaultClient.Do(req)

	if err != nil {
		panic(err) //Something is wrong while sending request
	}

	body, err := ioutil.ReadAll(res.Body)

	if err != nil {
		panic(err)
	}

	JSONSPLIT := strings.Split(string(body), strings.ToLower(user.Username))
	numberOfApps := len(JSONSPLIT) - 1
	//this.Data["AppList"] = string(body)
	appNames := make([]string, numberOfApps)

	fmt.Println("Number of apps for user: "******"' {
				break
			}
			appNames[i-1] = appNames[i-1] + string(JSONBYTES[j])
		}
		fmt.Println(appNames[i-1])
	}

	formstring := ""

	for i := 0; i < len(appNames); i++ {
		formstring = formstring + "<tr><td>" + appNames[i] + "</td>"
		formstring = formstring + "<td><a href='http://" + appNames[i] + ".klouds.org' target='_blank'> GO TO SITE</a></td>"
		formstring = formstring + "<td><a href='../deleteApp/" + appNames[i] + "'> DELETE APP </a></td>"
	}
	formstring = formstring + "</tr></table>"
	this.Data["AppList"] = formstring

	// this deferred function ensures that the correct fields from the database are displayed
	defer func(this *MainController, user *models.AuthUser) {
		this.Data["First"] = user.First
		this.Data["Last"] = user.Last
		this.Data["Username"] = user.Username
		this.Data["Email"] = user.Email
	}(this, &user)

	if this.Ctx.Input.Method() == "POST" {
		first := this.GetString("first")
		last := this.GetString("last")
		username := this.GetString("username")
		email := this.GetString("email")
		current := this.GetString("current")
		password := this.GetString("password")
		password2 := this.GetString("password2")
		valid := validation.Validation{}
		valid.Required(first, "first")
		valid.Email(email, "email")
		valid.Required(current, "current")

		if valid.HasErrors() {
			errormap := []string{}
			for _, err := range valid.Errors {
				errormap = append(errormap, "Validation failed on "+err.Key+": "+err.Message+"\n")
			}
			this.Data["Errors"] = errormap
			return
		}

		if password != "" {
			valid.MinSize(password, 6, "password")
			valid.Required(password2, "password2")
			if valid.HasErrors() {
				errormap := []string{}
				for _, err := range valid.Errors {
					errormap = append(errormap, "Validation failed on "+err.Key+": "+err.Message+"\n")
				}
				this.Data["Errors"] = errormap
				return
			}

			if password != password2 {
				flash.Error("Passwords don't match")
				flash.Store(&this.Controller)
				return
			}
			h := pk.HashPassword(password)

			// Convert password hash to string
			user.Password = hex.EncodeToString(h.Hash) + hex.EncodeToString(h.Salt)
		}

		//******** Compare submitted password with database
		if !pk.MatchPassword(current, &x) {
			flash.Error("Bad current password")
			flash.Store(&this.Controller)
			return
		}

		//******** Save user info to database
		user.First = first
		user.Last = last
		user.Username = username
		user.Email = email

		_, err := o.Update(&user)
		if err == nil {
			flash.Notice("Profile updated")
			flash.Store(&this.Controller)
			m["username"] = email
		} else {
			flash.Error("Internal error")
			flash.Store(&this.Controller)
			return
		}
	}
}
예제 #21
0
파일: user_add.go 프로젝트: wcreate/wuc
// POST /api/user/signup
func AddUser(ctx *macaron.Context, as rest.AuthService, cpt *captcha.Captcha) {
	var uar rest.UserAddReq
	ok := getBody(ctx, &uar)
	if !ok {
		return
	}

	log.Debugf("retrive CaptchaId = %s, CaptchaValue= %s", uar.CaptchaId, uar.CaptchaValue)
	if !cpt.Verify(uar.CaptchaId, uar.CaptchaValue) {
		ctx.JSON(http.StatusBadRequest, rest.INVALID_CAPTCHA)
		return
	}

	valid := validation.Validation{}
	valid.Email(uar.Email, "Email")
	valid.Match(uar.Username, rest.ValidPasswd,
		"Username").Message(rest.UsernamePrompt)
	valid.Match(uar.Passwd, rest.ValidPasswd,
		"Passwd").Message(rest.PasswdPrompt)
	if !validMember(ctx, &valid) {
		return
	}

	// check user whether existed
	u := &models.User{}
	if err := u.Find(uar.Email, uar.Username, ""); err != orm.ErrNoRows {
		ctx.JSON(http.StatusBadRequest, rest.INVALID_SIGNUP)
		return
	}

	// check reserve users
	if _, ok := rest.ReserveUsers[uar.Username]; ok {
		ctx.JSON(http.StatusBadRequest, rest.INVALID_SIGNUP)
		return
	}

	// generate password mask
	pwd, salt := tkits.GenPasswd(uar.Passwd, 8)
	u.Salt = salt
	u.Password = pwd
	u.Updated = time.Now()
	u.Username = uar.Username
	u.Email = uar.Email
	if id, err := u.Insert(); err != nil {
		ctx.JSON(http.StatusInternalServerError, tkits.DB_ERROR)
		return
	} else {
		u.Id = id
	}

	// generate a token
	if token, err := as.GenUserToken(ctx.RemoteAddr(), u.Id, 15, rest.TokenUser); err != nil {
		ctx.JSON(http.StatusInternalServerError, tkits.SYS_ERROR)
		return
	} else {
		rsp := &rest.UserAddRsp{u.Id, u.Username, token}

		// set some cookies
		if uar.CookieMaxAge == 0 {
			uar.CookieMaxAge = 60 * 60 * 12 //half of one day
		}

		suid := fmt.Sprintf("%v", u.Id)
		ctx.SetCookie("token", token, uar.CookieMaxAge)
		ctx.SetCookie("uid", suid, uar.CookieMaxAge)

		ctx.JSON(http.StatusOK, rsp)
	}
}
예제 #22
0
func (this *MainController) Register() {
	this.activeContent("user/register")

	if this.Ctx.Input.Method() == "POST" {
		flash := beego.NewFlash()
		first := this.GetString("first")
		last := this.GetString("last")
		email := this.GetString("email")
		username := this.GetString("username")
		password := this.GetString("password")
		password2 := this.GetString("password2")

		valid := validation.Validation{}
		valid.Required(first, "first")
		valid.Email(email, "email")
		valid.MinSize(password, 6, "password")
		valid.Required(password2, "password2")
		if valid.HasErrors() {
			errormap := []string{}
			for _, err := range valid.Errors {
				errormap = append(errormap, "Validation failed on "+err.Key+": "+err.Message+"\n")
			}
			this.Data["Errors"] = errormap
			return
		}
		if password != password2 {
			flash.Error("Passwords don't match")
			flash.Store(&this.Controller)
			return
		}
		h := pk.HashPassword(password)

		//******** Save user info to database
		o := orm.NewOrm()
		o.Using("default")

		user := models.AuthUser{First: first, Last: last, Username: username, Email: email}

		// Convert password hash to string
		user.Password = hex.EncodeToString(h.Hash) + hex.EncodeToString(h.Salt)

		// Add user to database with new uuid and send verification email
		u := uuid.NewV4()
		user.Reg_key = u.String()
		_, err := o.Insert(&user)
		if err != nil {
			flash.Error(email + " already registered")
			flash.Store(&this.Controller)
			return
		}

		if !sendVerification(email, u.String()) {
			flash.Error("Unable to send verification email")
			flash.Store(&this.Controller)
			return
		}
		flash.Notice("Your account has been created. You must verify the account in your email.")
		flash.Store(&this.Controller)
		this.Redirect("/notice", 302)
	}
}
예제 #23
0
func (this *MainController) Login() {
	this.activeContent("user/login")

	sess := this.GetSession("acme")
	if sess != nil {
		this.Redirect("/home", 302)
	}

	back := strings.Replace(this.Ctx.Input.Param(":back"), ">", "/", -1) // allow for deeper URL such as l1/l2/l3 represented by l1>l2>l3
	fmt.Println("back is", back)
	if this.Ctx.Input.Method() == "POST" {
		fmt.Println("es un POST")
		//flash := beego.NewFlash()
		email := this.GetString("email")
		password := this.GetString("password")
		valid := validation.Validation{}
		valid.Email(email, "email")
		valid.Required(password, "password")
		if valid.HasErrors() {
			errormap := make(map[string]string)
			for _, err := range valid.Errors {
				errormap[err.Key] = err.Message
			}
			this.Data["Errors"] = errormap
			return
		}
		fmt.Println("Authorization is", email, ":", password)

		//******** Read password hash from database
		var x pk.PasswordHash

		x.Hash = make([]byte, 32)
		x.Salt = make([]byte, 16)

		o := orm.NewOrm()
		o.Using("default")
		user := models.AuthUser{Email: email}
		/*
			err := o.Read(&user, "Email")

			if err == nil {
				if user.Reg_key != "" {
					flash.Error("Account not verified")
					flash.Store(&this.Controller)
					return
				}

				// scan in the password hash/salt
				fmt.Println("Password to scan:", user.Password)
				if x.Hash, err = hex.DecodeString(user.Password[:64]); err != nil {
					fmt.Println("ERROR:", err)
				}
				if x.Salt, err = hex.DecodeString(user.Password[64:]); err != nil {
					fmt.Println("ERROR:", err)
				}
				fmt.Println("decoded password is", x)
			} else {
				flash.Error("No such user/email")
				flash.Store(&this.Controller)
				return
			}

			//******** Compare submitted password with database
			if !pk.MatchPassword(password, &x) {
				flash.Error("Bad password")
				flash.Store(&this.Controller)
				return
			}
		*/
		//******** Create session and go back to previous page
		m := make(map[string]interface{})
		m["first"] = user.First
		m["username"] = email
		m["timestamp"] = time.Now()
		this.SetSession("acme", m)
		this.Redirect("/"+back, 302)
	}
}