Example #1
0
File: saml.go Project: tsuru/tsuru
func (s *SAMLAuthScheme) Create(user *auth.User) (*auth.User, error) {
	user.Password = ""
	if err := user.Create(); err != nil {
		return nil, err
	}
	return user, nil
}
Example #2
0
func (s *OAuthScheme) Create(user *auth.User) (*auth.User, error) {
	err := user.Create()
	if err != nil {
		return nil, err
	}
	return user, nil
}
func (s *InstanceSuite) TestGetServiceinstancesByServicesAndTeamsUserAdmin(c *check.C) {
	u := auth.User{Email: "*****@*****.**"}
	err := u.Create()
	c.Assert(err, check.IsNil)
	defer s.conn.Users().Remove(bson.M{"email": u.Email})
	team := auth.Team{Name: "admin", Users: []string{u.Email}}
	err = s.conn.Teams().Insert(team)
	c.Assert(err, check.IsNil)
	defer s.conn.Teams().RemoveId(team.Name)
	srvc := Service{Name: "mysql", Teams: []string{s.team.Name}, IsRestricted: true}
	err = s.conn.Services().Insert(&srvc)
	c.Assert(err, check.IsNil)
	defer s.conn.Services().RemoveId(srvc.Name)
	instance := ServiceInstance{
		Name:        "j4sql",
		ServiceName: srvc.Name,
		Teams:       []string{s.team.Name},
		Apps:        []string{},
		Units:       []string{},
	}
	err = s.conn.ServiceInstances().Insert(&instance)
	c.Assert(err, check.IsNil)
	defer s.conn.ServiceInstances().Remove(bson.M{"name": instance.Name})
	instances, err := GetServiceInstancesByServicesAndTeams([]Service{srvc}, &u, "")
	c.Assert(err, check.IsNil)
	c.Assert(instances, check.DeepEquals, []ServiceInstance{instance})
}
Example #4
0
func createUser(w http.ResponseWriter, r *http.Request) error {
	var u auth.User
	err := json.NewDecoder(r.Body).Decode(&u)
	if err != nil {
		return &errors.HTTP{Code: http.StatusBadRequest, Message: err.Error()}
	}
	if !validation.ValidateEmail(u.Email) {
		return &errors.HTTP{Code: http.StatusBadRequest, Message: emailError}
	}
	if !validation.ValidateLength(u.Password, passwordMinLen, passwordMaxLen) {
		return &errors.HTTP{Code: http.StatusBadRequest, Message: passwordError}
	}
	if _, err = auth.GetUserByEmail(u.Email); err == nil {
		return &errors.HTTP{Code: http.StatusConflict, Message: "This email is already registered"}
	}
	gURL := repository.ServerURL()
	c := gandalf.Client{Endpoint: gURL}
	if _, err := c.NewUser(u.Email, keyToMap(u.Keys)); err != nil {
		return fmt.Errorf("Failed to create user in the git server: %s", err)
	}
	u.Quota = quota.Unlimited
	if limit, err := config.GetInt("quota:apps-per-user"); err == nil && limit > -1 {
		u.Quota.Limit = limit
	}
	if err := u.Create(); err == nil {
		rec.Log(u.Email, "create-user")
		w.WriteHeader(http.StatusCreated)
		return nil
	}
	return err
}
Example #5
0
func (s *S) TestCreateTokenRemoveOldTokens(c *gocheck.C) {
	config.Set("auth:max-simultaneous-sessions", 2)
	u := auth.User{Email: "*****@*****.**", Password: "******"}
	err := u.Create()
	c.Assert(err, gocheck.IsNil)
	defer s.conn.Users().Remove(bson.M{"email": u.Email})
	defer s.conn.Tokens().RemoveAll(bson.M{"useremail": u.Email})
	t1, err := newUserToken(&u)
	c.Assert(err, gocheck.IsNil)
	t2 := t1
	t2.Token += "aa"
	err = s.conn.Tokens().Insert(t1, t2)
	_, err = createToken(&u, "123456")
	c.Assert(err, gocheck.IsNil)
	ok := make(chan bool, 1)
	go func() {
		for {
			ct, err := s.conn.Tokens().Find(bson.M{"useremail": u.Email}).Count()
			c.Assert(err, gocheck.IsNil)
			if ct == 2 {
				ok <- true
				return
			}
			runtime.Gosched()
		}
	}()
	select {
	case <-ok:
	case <-time.After(2e9):
		c.Fatal("Did not remove old tokens after 2 seconds")
	}
}
Example #6
0
func (s *S) TestCreateTokenShouldValidateThePassword(c *gocheck.C) {
	u := auth.User{Email: "*****@*****.**", Password: "******"}
	err := u.Create()
	c.Assert(err, gocheck.IsNil)
	defer s.conn.Users().Remove(bson.M{"email": u.Email})
	_, err = createToken(&u, "123")
	c.Assert(err, gocheck.NotNil)
}
Example #7
0
func (s *S) TestNativeCreateExistingEmail(c *gocheck.C) {
	existingUser := auth.User{Email: "*****@*****.**"}
	existingUser.Create()
	scheme := NativeScheme{}
	user := &auth.User{Email: "*****@*****.**", Password: "******"}
	_, err := scheme.Create(user)
	c.Assert(err, gocheck.Equals, ErrEmailRegistered)
}
Example #8
0
func (s *S) TestPasswordTokenUser(c *check.C) {
	u := auth.User{Email: "*****@*****.**", Password: "******"}
	err := u.Create()
	c.Assert(err, check.IsNil)
	defer u.Delete()
	t, err := createPasswordToken(&u)
	c.Assert(err, check.IsNil)
	u2, err := t.user()
	c.Assert(err, check.IsNil)
	c.Assert(*u2, check.DeepEquals, u)
}
Example #9
0
func (s *S) TestPasswordTokenUser(c *gocheck.C) {
	u := auth.User{Email: "*****@*****.**", Password: "******"}
	err := u.Create()
	c.Assert(err, gocheck.IsNil)
	defer s.conn.Users().Remove(bson.M{"email": u.Email})
	t, err := createPasswordToken(&u)
	c.Assert(err, gocheck.IsNil)
	u2, err := t.user()
	u2.Keys = u.Keys
	c.Assert(err, gocheck.IsNil)
	c.Assert(*u2, gocheck.DeepEquals, u)
}
Example #10
0
func (s *S) TestCreateTokenShouldSaveTheTokenInTheDatabase(c *gocheck.C) {
	u := auth.User{Email: "*****@*****.**", Password: "******"}
	err := u.Create()
	c.Assert(err, gocheck.IsNil)
	defer s.conn.Users().Remove(bson.M{"email": u.Email})
	_, err = createToken(&u, "123456")
	c.Assert(err, gocheck.IsNil)
	var result Token
	err = s.conn.Tokens().Find(bson.M{"useremail": u.Email}).One(&result)
	c.Assert(err, gocheck.IsNil)
	c.Assert(result.Token, gocheck.NotNil)
}
Example #11
0
func (s *S) TestCreateTokenUsesDefaultCostWhenHasCostIsUndefined(c *gocheck.C) {
	err := config.Unset("auth:hash-cost")
	c.Assert(err, gocheck.IsNil)
	defer config.Set("auth:hash-cost", bcrypt.MinCost)
	u := auth.User{Email: "*****@*****.**", Password: "******"}
	err = u.Create()
	c.Assert(err, gocheck.IsNil)
	defer s.conn.Users().Remove(bson.M{"email": u.Email})
	cost = 0
	tokenExpire = 0
	_, err = createToken(&u, "123456")
	c.Assert(err, gocheck.IsNil)
}
Example #12
0
func (s *S) TestResetPasswordThirdToken(c *gocheck.C) {
	scheme := NativeScheme{}
	u := auth.User{Email: "*****@*****.**"}
	err := u.Create()
	c.Assert(err, gocheck.IsNil)
	defer s.conn.Users().Remove(bson.M{"email": u.Email})
	t, err := createPasswordToken(&u)
	c.Assert(err, gocheck.IsNil)
	defer s.conn.PasswordTokens().Remove(bson.M{"_id": t.Token})
	u2 := auth.User{Email: "*****@*****.**"}
	err = scheme.ResetPassword(&u2, t.Token)
	c.Assert(err, gocheck.Equals, auth.ErrInvalidToken)
}
Example #13
0
func (s *S) TestResetPassword(c *check.C) {
	scheme := NativeScheme{}
	defer s.server.Reset()
	u := auth.User{Email: "*****@*****.**"}
	err := u.Create()
	c.Assert(err, check.IsNil)
	defer u.Delete()
	p := u.Password
	err = scheme.StartPasswordReset(&u)
	c.Assert(err, check.IsNil)
	err = tsurutest.WaitCondition(time.Second, func() bool {
		s.server.RLock()
		defer s.server.RUnlock()
		return len(s.server.MailBox) == 1
	})
	c.Assert(err, check.IsNil)
	var token passwordToken
	err = s.conn.PasswordTokens().Find(bson.M{"useremail": u.Email}).One(&token)
	c.Assert(err, check.IsNil)
	err = scheme.ResetPassword(&u, token.Token)
	c.Assert(err, check.IsNil)
	u2, _ := auth.GetUserByEmail(u.Email)
	c.Assert(u2.Password, check.Not(check.Equals), p)
	var m authtest.Mail
	err = tsurutest.WaitCondition(time.Second, func() bool {
		s.server.RLock()
		defer s.server.RUnlock()
		if len(s.server.MailBox) != 2 {
			return false
		}
		m = s.server.MailBox[1]
		return true
	})
	c.Assert(err, check.IsNil)
	c.Assert(m.From, check.Equals, "root")
	c.Assert(m.To, check.DeepEquals, []string{u.Email})
	var buf bytes.Buffer
	template, err := getEmailResetPasswordSucessfullyTemplate()
	c.Assert(err, check.IsNil)
	err = template.Execute(&buf, map[string]string{"email": u.Email, "password": ""})
	c.Assert(err, check.IsNil)
	expected := strings.Replace(buf.String(), "\n", "\r\n", -1) + "\r\n"
	lines := strings.Split(string(m.Data), "\r\n")
	lines[len(lines)-4] = ""
	c.Assert(strings.Join(lines, "\r\n"), check.Equals, expected)
	err = s.conn.PasswordTokens().Find(bson.M{"useremail": u.Email}).One(&token)
	c.Assert(err, check.IsNil)
	c.Assert(token.Used, check.Equals, true)
}
Example #14
0
func (s *S) TestReserveUserAppForwardQuotaExceeded(c *gocheck.C) {
	user := auth.User{
		Email: "*****@*****.**",
		Quota: quota.Quota{Limit: 1, InUse: 1},
	}
	err := user.Create()
	c.Assert(err, gocheck.IsNil)
	defer s.conn.Users().Remove(bson.M{"email": user.Email})
	app := App{
		Name:     "clap",
		Platform: "django",
	}
	previous, err := reserveUserApp.Forward(action.FWContext{Params: []interface{}{app, user}})
	c.Assert(previous, gocheck.IsNil)
	_, ok := err.(*quota.QuotaExceededError)
	c.Assert(ok, gocheck.Equals, true)
}
Example #15
0
func (c *DBTokenCache) PutToken(t *goauth2.Token) error {
	if t.AccessToken == "" {
		return ErrEmptyAccessToken
	}
	var email string
	if t.Extra == nil || t.Extra["email"] == "" {
		conf, err := c.scheme.loadConfig()
		if err != nil {
			return err
		}
		transport := &goauth2.Transport{Config: &conf}
		transport.Token = t
		client := transport.Client()
		response, err := client.Get(c.scheme.InfoUrl)
		if err != nil {
			return err
		}
		email, err = c.scheme.Parser.Parse(response)
		if email == "" {
			return ErrEmptyUserEmail
		}
		_, err = auth.GetUserByEmail(email)
		if err != nil {
			if err != auth.ErrUserNotFound {
				return err
			}
			registrationEnabled, _ := config.GetBool("auth:user-registration")
			if !registrationEnabled {
				return err
			}
			user := auth.User{Email: email}
			err := user.Create()
			if err != nil {
				return err
			}
			err = user.CreateOnGandalf()
			if err != nil {
				return err
			}
		}
		t.Extra = make(map[string]string)
		t.Extra["email"] = email
	}
	return makeToken(t).save()
}
Example #16
0
func (s NativeScheme) Create(user *auth.User) (*auth.User, error) {
	if !validation.ValidateEmail(user.Email) {
		return nil, ErrInvalidEmail
	}
	if !validation.ValidateLength(user.Password, passwordMinLen, passwordMaxLen) {
		return nil, ErrInvalidPassword
	}
	if _, err := auth.GetUserByEmail(user.Email); err == nil {
		return nil, ErrEmailRegistered
	}
	if err := hashPassword(user); err != nil {
		return nil, err
	}
	if err := user.Create(); err != nil {
		return nil, err
	}
	return user, nil
}
Example #17
0
func (s *InstanceSuite) TestGetServiceInstancesByServicesAndTeamsForUsersThatAreNotMembersOfAnyTeam(c *gocheck.C) {
	u := auth.User{Email: "*****@*****.**"}
	err := u.Create()
	c.Assert(err, gocheck.IsNil)
	defer s.conn.Users().Remove(bson.M{"email": u.Email})
	srvc := Service{Name: "mysql", Teams: []string{s.team.Name}, IsRestricted: true}
	err = s.conn.Services().Insert(&srvc)
	c.Assert(err, gocheck.IsNil)
	defer s.conn.Services().RemoveId(srvc.Name)
	instance := ServiceInstance{
		Name:        "j4sql",
		ServiceName: srvc.Name,
	}
	err = s.conn.ServiceInstances().Insert(&instance)
	c.Assert(err, gocheck.IsNil)
	defer s.conn.ServiceInstances().Remove(bson.M{"name": instance.Name})
	instances, err := GetServiceInstancesByServicesAndTeams([]Service{srvc}, &u)
	c.Assert(err, gocheck.IsNil)
	c.Assert(instances, gocheck.IsNil)
}
Example #18
0
func (s *S) TestReserveUserAppBackward(c *gocheck.C) {
	user := auth.User{
		Email: "*****@*****.**",
		Quota: quota.Quota{Limit: 1, InUse: 1},
	}
	err := user.Create()
	c.Assert(err, gocheck.IsNil)
	defer s.conn.Users().Remove(bson.M{"email": user.Email})
	app := App{
		Name:     "clap",
		Platform: "django",
	}
	ctx := action.BWContext{
		FWResult: map[string]string{
			"app":  app.Name,
			"user": user.Email,
		},
	}
	reserveUserApp.Backward(ctx)
	err = auth.ReserveApp(&user)
	c.Assert(err, gocheck.IsNil)
}
Example #19
0
func (s *S) TestResetPassword(c *gocheck.C) {
	scheme := NativeScheme{}
	defer s.server.Reset()
	u := auth.User{Email: "*****@*****.**"}
	err := u.Create()
	c.Assert(err, gocheck.IsNil)
	p := u.Password
	defer s.conn.Users().Remove(bson.M{"email": u.Email})
	err = scheme.StartPasswordReset(&u)
	c.Assert(err, gocheck.IsNil)
	time.Sleep(1e6) // Let the email flow
	var token passwordToken
	err = s.conn.PasswordTokens().Find(bson.M{"useremail": u.Email}).One(&token)
	c.Assert(err, gocheck.IsNil)
	err = scheme.ResetPassword(&u, token.Token)
	c.Assert(err, gocheck.IsNil)
	u2, _ := auth.GetUserByEmail(u.Email)
	c.Assert(u2.Password, gocheck.Not(gocheck.Equals), p)
	time.Sleep(1e9) // Let the email flow
	s.server.Lock()
	defer s.server.Unlock()
	c.Assert(s.server.MailBox, gocheck.HasLen, 2)
	m := s.server.MailBox[1]
	c.Assert(m.From, gocheck.Equals, "root")
	c.Assert(m.To, gocheck.DeepEquals, []string{u.Email})
	var buf bytes.Buffer
	err = passwordResetConfirm.Execute(&buf, map[string]string{"email": u.Email, "password": ""})
	c.Assert(err, gocheck.IsNil)
	expected := strings.Replace(buf.String(), "\n", "\r\n", -1) + "\r\n"
	lines := strings.Split(string(m.Data), "\r\n")
	lines[len(lines)-4] = ""
	c.Assert(strings.Join(lines, "\r\n"), gocheck.Equals, expected)
	err = s.conn.PasswordTokens().Find(bson.M{"useremail": u.Email}).One(&token)
	c.Assert(err, gocheck.IsNil)
	c.Assert(token.Used, gocheck.Equals, true)
}
Example #20
0
func (s *S) TestReserveUserAppForwardAppNotPointer(c *gocheck.C) {
	user := auth.User{
		Email: "*****@*****.**",
		Quota: quota.Quota{Limit: 1},
	}
	err := user.Create()
	c.Assert(err, gocheck.IsNil)
	defer s.conn.Users().Remove(bson.M{"email": user.Email})
	app := App{
		Name:     "clap",
		Platform: "django",
	}
	expected := map[string]string{"user": user.Email, "app": app.Name}
	previous, err := reserveUserApp.Forward(action.FWContext{Params: []interface{}{app, user}})
	c.Assert(err, gocheck.IsNil)
	c.Assert(previous, gocheck.DeepEquals, expected)
	err = auth.ReserveApp(&user)
	_, ok := err.(*quota.QuotaExceededError)
	c.Assert(ok, gocheck.Equals, true)
	err = auth.ReleaseApp(&user)
	c.Assert(err, gocheck.IsNil)
	err = auth.ReserveApp(&user)
	c.Assert(err, gocheck.IsNil)
}