Esempio n. 1
0
// set a new password to user
func (this *UserService) SaveNewPassword(u *user.User, password string) error {
	salt := GetUserSalt()
	u.Password = fmt.Sprintf("%s$%s", salt, utils.EncodePassword(password, salt))
	u.PasswordSalt = salt
	_, err := orm.NewOrm().Update(u, "Password", "PasswordSalt", "Updated")
	return err
}
Esempio n. 2
0
// Active implemented check Email actice code.
func (this *RegisterController) Active() {
	this.TplName = "auth/active.html"

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

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

	var user user.User
	if this.UserService.VerifyUserActiveCode(&user, code) {
		user.Active = true
		user.PasswordSalt = userServ.GetUserSalt()
		if err := this.UserService.Update(&user, "Active", "PasswordSalt", "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
	}
}
Esempio n. 3
0
// register a user
func (this *UserService) RegisterUser(u *user.User, username, email, password string, userType *user.UserType, role *user.Role) error {
	u.UserType = userType
	// use random salt encode password
	salt := GetUserSalt()
	pwd := utils.EncodePassword(password, salt)

	u.Username = strings.ToLower(username)
	u.Email = strings.ToLower(email)

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

	var err error
	tr := orm.NewOrm()
	tr.Begin()
	if err = this.InsertWithScope(tr, u); err == nil {
		roleService := RoleService{}
		err = roleService.InsertUsersWithScope(tr, role, u)
	}
	if err == nil {
		tr.Commit()
	} else {
		tr.Rollback()
	}
	return err
}
Esempio n. 4
0
// Reset implemented user password reset.
func (this *ForgotController) ResetPost() {
	this.TplName = "auth/reset.html"

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

	var user user.User

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

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

		user.Active = true
		user.PasswordSalt = userServ.GetUserSalt()

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

	} else {
		this.Data["Success"] = false
	}
}
Esempio n. 5
0
// check if exist user by username or email, ignore "deleted" users
func (this *UserService) HasUser(user *user.User, username string) bool {
	var err error
	qs := orm.NewOrm()
	if strings.IndexRune(username, '@') == -1 {
		user.Username = username
		err = qs.Read(user, "Username", "Deleted")
	} else {
		user.Email = username
		err = qs.Read(user, "Email", "Deleted")
	}
	if err == nil {
		return true
	}
	return false
}
Esempio n. 6
0
func (this *BaseController) LoginUserFromRememberCookie(u *user.User, ctx *context.Context) (success bool) {
	userName := ctx.GetCookie(setting.CookieUsername)
	if len(userName) == 0 {
		return false
	}

	defer func() {
		if !success {
			this.DeleteRememberCookie(ctx)
		}
	}()
	u.Username = userName
	if err := this.UserService.Read(u, "Username"); err != nil {
		return false
	}

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

	this.LoginUserRememberCookie(u, ctx, true)

	return true
}
Esempio n. 7
0
// Register implemented Post method for RegisterController.
func (this *RegisterController) Register() {
	this.Data["IsRegister"] = true
	this.TplName = "auth/register.html"

	// no need login
	if this.CheckLoginRedirect(false) {
		return
	}

	form := RegisterForm{Locale: this.Locale}
	// valid form and put errors to template context
	if this.ValidFormSets(&form) == false {
		return
	}

	// Create new user.
	u := new(user.User)
	//set to default usertype
	ut := new(user.UserType)
	ut.Id = 1

	role := new(user.Role)
	role.Id = 1
	if !setting.IsActivationRequired {
		u.Active = true
	}
	if err := this.UserService.RegisterUser(u, form.Username, form.Email, form.Password, ut, role); err == nil {
		if setting.IsActivationRequired {
			email.SendRegisterMail(this.Locale, u)
		}

		loginRedirect := this.LoginUser(u, false)
		if loginRedirect == "/" {
			//this.FlashRedirect("/settings/profile", 302, "RegSuccess")
			this.FlashRedirect("/", 302, "RegSuccess")
		} else {
			this.Redirect(loginRedirect, 302)
		}

		return

	} else {
		beego.Error("Register: Failed ", err)
	}
}
Esempio n. 8
0
func (this UserService) InsertWithScope(tr orm.Ormer, u *user.User) error {
	u.PasswordSalt = GetUserSalt()

	if !utils.IsEmail(u.Email) {
		return errors.New("invalid email")
	}

	beego.Info(setting.SystemAdminEmails)

	if strings.Index(setting.SystemAdminEmails, u.Email) >= 0 {
		u.IsSystemAccount = true
		beego.Info(setting.SystemAdminEmails)
	}
	if _, err := tr.Insert(u); err != nil {
		return err
	}
	return nil
}
Esempio n. 9
0
// get user if key exist in session
func (this *BaseController) GetUserFromSession(u *user.User, sess session.Store) bool {
	id := this.GetUserIdFromSession(sess)
	if id > 0 {
		u.Id = id
		if this.UserService.Read(u) == nil {
			return true
		}
	}

	return false
}
Esempio n. 10
0
func (this *AdminApiController) ResetPassword() {
	var ChangePasswordModel = struct {
		Id       int64
		Password string
	}{}
	this.CheckPermission(permissions.UserAdminUpdate)
	var u user.User
	json.Unmarshal(this.Ctx.Input.RequestBody, &ChangePasswordModel)
	u.Id = ChangePasswordModel.Id
	u.Password = ChangePasswordModel.Password
	var err error
	if u.Id > 0 {
		err = this.UserService.SaveNewPassword(&u, u.Password)
		if err != nil {
			this.Ctx.Abort(500, err.Error())
		}
	} else {
		this.Ctx.Abort(500, "invalid user id")
	}
	this.ServeJSON()
}
Esempio n. 11
0
func (this *UserController) getUser(u *user.User) bool {
	username := this.GetString(":username")
	u.Username = username
	err := this.UserService.Read(u, "Username")
	if err != nil {
		this.Abort("404")
		return true
	}
	this.Data["TheUser"] = &u

	return false
}
Esempio n. 12
0
// load roles
func (this *UserService) LoadRoles(u *user.User) error {
	if len(u.Roles) > 0 {
		return nil
	}
	_, err := orm.NewOrm().LoadRelated(u, "Roles")
	if err == nil {
		for _, r := range u.Roles {
			if r.IsSystemRole {
				u.IsSystemAccount = true
			}
		}
		cachemanager.Put(fmt.Sprintf(USER_ID_CACHE_PATTERN, u.Id, u.Deleted), *u)
	}
	return err
}
Esempio n. 13
0
// get user by erify code
func (this *UserService) getVerifyUser(u *user.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 {
		u.Username = string(b)
		if this.Read(u, "Username") == nil {
			return true
		}
	}

	return false
}
Esempio n. 14
0
func (form *ProfileForm) SaveUserProfile(u *user.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(u, form)
	if len(changes) > 0 {
		// if email changed then need re-active
		if u.Email != form.Email {
			u.Active = false
			changes = append(changes, "Active")
		}
		serv := &userServ.UserService{}
		utils.SetFormValues(form, u)
		return serv.Update(u, changes...)
	}
	return nil
}
Esempio n. 15
0
func TestPasswordSpec(t *testing.T) {
	password := "******"
	var err error
	Convey("Authentication Testing", t, func() {
		Convey("generateSalt()", func() {
			salt := GetUserSalt()
			So(salt, ShouldNotBeBlank)
			So(len(salt), ShouldEqual, 10)
		})

		Convey("hashPassword()", func() {
			hash := utils.EncodePassword(password, GetUserSalt())
			So(hash, ShouldNotBeBlank)
			So(len(hash), ShouldEqual, 100)
		})

		Convey("Create a user", func() {
			u := new(user.User)
			u.Username = "******"
			u.Password = password
			db := orm.NewOrm()
			//ensure testuser not exist in the database
			_, err = db.Raw("delete from role where role_info_id = (select id from user_info where user_name = ? limit 1)", u.Username).Exec()
			if err != nil {
				Println(err)
			}
			_, err = db.Raw("delete from user_info where user_name=?", u.Username).Exec()
			if err != nil {
				Println(err)
			}
			err := userServ.RegisterUser(u, "testuser", "*****@*****.**", password, &model.UserType{Id: 1}, &model.Role{Id: 2})
			if err != nil {
				Println(err)
			}
			So(err, ShouldEqual, nil)
			So(u.Id, ShouldBeGreaterThan, 0)

			Convey("VerifyUser()", func() {
				So(userServ.VerifyUser(u, u.Username, password), ShouldEqual, true)
			})

			Convey("CanRegister()", func() {
				var canName, canEmail bool = true, true
				canName, canEmail, _ = userServ.CanRegistered("testuser", "*****@*****.**")
				So(canName, ShouldEqual, false)
				So(canEmail, ShouldEqual, false)
				canName, canEmail, _ = userServ.CanRegistered("testuser", "*****@*****.**")
				So(canName, ShouldEqual, false)
				So(canEmail, ShouldEqual, true)
				canName, canEmail, _ = userServ.CanRegistered("whatever", "*****@*****.**")
				So(canName, ShouldEqual, true)
				So(canEmail, ShouldEqual, false)
				canName, canEmail, _ = userServ.CanRegistered("whatever", "*****@*****.**")
				So(canName, ShouldEqual, true)
				So(canEmail, ShouldEqual, true)
			})

			Convey("HasUser()", func() {
				So(userServ.HasUser(u, "testuser"), ShouldEqual, true)
			})

			Convey("SaveNewPassword()", func() {
				newPassword := "******"
				userServ.SaveNewPassword(u, newPassword)
				So(userServ.VerifyUser(u, u.Username, password), ShouldEqual, false)
				So(userServ.VerifyUser(u, u.Username, newPassword), ShouldEqual, true)
			})

			Convey("FuzzySearch()", func() {
				var users []*model.User
				userServ.FuzzySearch(&users, "t", 2, 0, 200)
				So(len(users), ShouldBeGreaterThanOrEqualTo, 1)
			})
		})

	})
}