Ejemplo n.º 1
0
func (s *S) TestDissociateRole(c *check.C) {
	_, err := permission.NewRole("test", "team")
	c.Assert(err, check.IsNil)
	token := userWithPermission(c, permission.Permission{
		Scheme:  permission.PermRoleUpdateDissociate,
		Context: permission.Context(permission.CtxGlobal, ""),
	})
	u, err := auth.GetUserByEmail("*****@*****.**")
	c.Assert(err, check.IsNil)
	err = u.AddRole("test", "myteam")
	c.Assert(err, check.IsNil)
	c.Assert(u.Roles, check.HasLen, 2)
	req, err := http.NewRequest("DELETE", "/roles/test/user/[email protected]?context=myteam", nil)
	c.Assert(err, check.IsNil)
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Authorization", "bearer "+token.GetValue())
	recorder := httptest.NewRecorder()
	server := RunServer(true)
	server.ServeHTTP(recorder, req)
	c.Assert(err, check.IsNil)
	c.Assert(recorder.Code, check.Equals, http.StatusOK)
	u, err = auth.GetUserByEmail("*****@*****.**")
	c.Assert(err, check.IsNil)
	c.Assert(u.Roles, check.HasLen, 1)
}
Ejemplo n.º 2
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
}
Ejemplo n.º 3
0
// removeUser removes the user from the database and from repository server
//
// If the user is the only one in a team an error will be returned.
func removeUser(w http.ResponseWriter, r *http.Request, t auth.Token) error {
	u, err := t.User()
	if err != nil {
		return err
	}
	email := r.URL.Query().Get("user")
	if email != "" {
		if !permission.Check(t, permission.PermUserDelete) {
			return permission.ErrUnauthorized
		}
		u, err = auth.GetUserByEmail(email)
		if err != nil {
			return &errors.HTTP{Code: http.StatusNotFound, Message: err.Error()}
		}
	}
	appNames, err := deployableApps(u)
	if err != nil {
		return err
	}
	manager := repository.Manager()
	for _, name := range appNames {
		manager.RevokeAccess(name, u.Email)
	}
	rec.Log(u.Email, "remove-user")
	if err := manager.RemoveUser(u.Email); err != nil {
		log.Errorf("Failed to remove user from repository manager: %s", err)
	}
	return app.AuthScheme.Remove(u)
}
Ejemplo n.º 4
0
func addUserToTeam(w http.ResponseWriter, r *http.Request, t auth.Token) error {
	teamName := r.URL.Query().Get(":team")
	email := r.URL.Query().Get(":user")
	u, err := t.User()
	if err != nil {
		return err
	}
	rec.Log(u.Email, "add-user-to-team", "team="+teamName, "user="******"Team not found"}
	}
	if !team.ContainsUser(u) {
		msg := fmt.Sprintf("You are not authorized to add new users to the team %s", team.Name)
		return &errors.HTTP{Code: http.StatusForbidden, Message: msg}
	}
	user, err := auth.GetUserByEmail(email)
	if err != nil {
		return &errors.HTTP{Code: http.StatusNotFound, Message: "User not found"}
	}
	actions := []*action.Action{
		&addUserToTeamInRepositoryAction,
		&addUserToTeamInDatabaseAction,
	}
	pipeline := action.NewPipeline(actions...)
	return pipeline.Execute(user, team)
}
Ejemplo n.º 5
0
func (s *QuotaSuite) TestChangeUserQuota(c *check.C) {
	conn, err := db.Conn()
	c.Assert(err, check.IsNil)
	defer conn.Close()
	user := &auth.User{
		Email:    "*****@*****.**",
		Password: "******",
		Quota:    quota.Quota{Limit: 4, InUse: 2},
	}
	_, err = nativeScheme.Create(user)
	c.Assert(err, check.IsNil)
	defer conn.Users().Remove(bson.M{"email": user.Email})
	body := bytes.NewBufferString("limit=40")
	request, _ := http.NewRequest("PUT", "/users/[email protected]/quota", body)
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	recorder := httptest.NewRecorder()
	handler := RunServer(true)
	handler.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusOK)
	user, err = auth.GetUserByEmail(user.Email)
	c.Assert(err, check.IsNil)
	c.Assert(user.Quota.Limit, check.Equals, 40)
	c.Assert(user.Quota.InUse, check.Equals, 2)
}
Ejemplo n.º 6
0
Archivo: auth.go Proyecto: tsuru/tsuru
// title: regenerate token
// path: /users/api-key
// method: POST
// produce: application/json
// responses:
//   200: OK
//   401: Unauthorized
//   404: User not found
func regenerateAPIToken(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
	r.ParseForm()
	email := r.URL.Query().Get("user")
	if email == "" {
		email = t.GetUserName()
	}
	allowed := permission.Check(t, permission.PermUserUpdateToken,
		permission.Context(permission.CtxUser, email),
	)
	if !allowed {
		return permission.ErrUnauthorized
	}
	evt, err := event.New(&event.Opts{
		Target:     userTarget(email),
		Kind:       permission.PermUserUpdateToken,
		Owner:      t,
		CustomData: event.FormToCustomData(r.Form),
		Allowed:    event.Allowed(permission.PermUserReadEvents, permission.Context(permission.CtxUser, email)),
	})
	if err != nil {
		return err
	}
	defer func() { evt.Done(err) }()
	u, err := auth.GetUserByEmail(email)
	if err != nil {
		return &errors.HTTP{Code: http.StatusNotFound, Message: err.Error()}
	}
	apiKey, err := u.RegenerateAPIKey()
	if err != nil {
		return err
	}
	w.Header().Add("Content-Type", "application/json")
	return json.NewEncoder(w).Encode(apiKey)
}
Ejemplo n.º 7
0
Archivo: auth.go Proyecto: tsuru/tsuru
// title: reset password
// path: /users/{email}/password
// method: POST
// responses:
//   200: Ok
//   400: Invalid data
//   401: Unauthorized
//   403: Forbidden
//   404: Not found
func resetPassword(w http.ResponseWriter, r *http.Request) (err error) {
	managed, ok := app.AuthScheme.(auth.ManagedScheme)
	if !ok {
		return &errors.HTTP{Code: http.StatusBadRequest, Message: nonManagedSchemeMsg}
	}
	r.ParseForm()
	email := r.URL.Query().Get(":email")
	token := r.FormValue("token")
	evt, err := event.New(&event.Opts{
		Target:     userTarget(email),
		Kind:       permission.PermUserUpdateReset,
		RawOwner:   event.Owner{Type: event.OwnerTypeUser, Name: email},
		CustomData: event.FormToCustomData(r.Form),
		Allowed:    event.Allowed(permission.PermUserReadEvents, permission.Context(permission.CtxUser, email)),
	})
	if err != nil {
		return err
	}
	defer func() { evt.Done(err) }()
	u, err := auth.GetUserByEmail(email)
	if err != nil {
		if err == auth.ErrUserNotFound {
			return &errors.HTTP{Code: http.StatusNotFound, Message: err.Error()}
		} else if e, ok := err.(*errors.ValidationError); ok {
			return &errors.HTTP{Code: http.StatusBadRequest, Message: e.Error()}
		}
		return err
	}
	if token == "" {
		return managed.StartPasswordReset(u)
	}
	return managed.ResetPassword(u, token)
}
Ejemplo n.º 8
0
func (s *QuotaSuite) TestChangeUserQuota(c *check.C) {
	conn, err := db.Conn()
	c.Assert(err, check.IsNil)
	defer conn.Close()
	user := &auth.User{
		Email:    "*****@*****.**",
		Password: "******",
		Quota:    quota.Quota{Limit: 4, InUse: 2},
	}
	_, err = nativeScheme.Create(user)
	c.Assert(err, check.IsNil)
	defer conn.Users().Remove(bson.M{"email": user.Email})
	body := bytes.NewBufferString("limit=40")
	request, _ := http.NewRequest("PUT", "/users/[email protected]/quota", body)
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	recorder := httptest.NewRecorder()
	handler := RunServer(true)
	handler.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusOK)
	user, err = auth.GetUserByEmail(user.Email)
	c.Assert(err, check.IsNil)
	c.Assert(user.Quota.Limit, check.Equals, 40)
	c.Assert(user.Quota.InUse, check.Equals, 2)
	c.Assert(eventtest.EventDesc{
		Target: event.Target{Type: event.TargetTypeUser, Value: user.Email},
		Owner:  s.token.GetUserName(),
		Kind:   "user.update.quota",
		StartCustomData: []map[string]interface{}{
			{"name": ":email", "value": user.Email},
			{"name": "limit", "value": "40"},
		},
	}, eventtest.HasEvent)
}
Ejemplo n.º 9
0
// title: dissociate role from user
// path: /roles/{name}/user/{email}
// method: DELETE
// responses:
//   200: Ok
//   400: Invalid data
//   401: Unauthorized
//   404: Role not found
func dissociateRole(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
	r.ParseForm()
	if !permission.Check(t, permission.PermRoleUpdateDissociate) {
		return permission.ErrUnauthorized
	}
	roleName := r.URL.Query().Get(":name")
	evt, err := event.New(&event.Opts{
		Target:     event.Target{Type: event.TargetTypeRole, Value: roleName},
		Kind:       permission.PermRoleUpdateDissociate,
		Owner:      t,
		CustomData: event.FormToCustomData(r.Form),
		Allowed:    event.Allowed(permission.PermRoleReadEvents),
	})
	if err != nil {
		return err
	}
	defer func() { evt.Done(err) }()
	email := r.URL.Query().Get(":email")
	contextValue := r.URL.Query().Get("context")
	user, err := auth.GetUserByEmail(email)
	if err != nil {
		return err
	}
	err = canUseRole(t, roleName, contextValue)
	if err != nil {
		return err
	}
	err = runWithPermSync([]auth.User{*user}, func() error {
		return user.RemoveRole(roleName, contextValue)
	})
	return err
}
Ejemplo n.º 10
0
func removeUserFromTeam(w http.ResponseWriter, r *http.Request, t auth.Token) error {
	email := r.URL.Query().Get(":user")
	teamName := r.URL.Query().Get(":team")
	u, err := t.User()
	if err != nil {
		return err
	}
	rec.Log(u.Email, "remove-user-from-team", "team="+teamName, "user="******"Team not found"}
	}
	if !team.ContainsUser(u) {
		msg := fmt.Sprintf("You are not authorized to remove a member from the team %s", team.Name)
		return &errors.HTTP{Code: http.StatusUnauthorized, Message: msg}
	}
	if len(team.Users) == 1 {
		msg := "You can not remove this user from this team, because it is the last user within the team, and a team can not be orphaned"
		return &errors.HTTP{Code: http.StatusForbidden, Message: msg}
	}
	user, err := auth.GetUserByEmail(email)
	if err != nil {
		return &errors.HTTP{Code: http.StatusNotFound, Message: err.Error()}
	}
	err = removeUserFromTeamInDatabase(user, team)
	if err != nil {
		return err
	}
	return removeUserFromTeamInRepository(user, team)
}
Ejemplo n.º 11
0
func (s *S) TestOAuthRemove(c *check.C) {
	scheme := OAuthScheme{}
	s.rsps["/token"] = `access_token=my_token`
	s.rsps["/user"] = `{"email":"*****@*****.**"}`
	params := make(map[string]string)
	params["code"] = "abcdefg"
	params["redirectUrl"] = "http://localhost"
	token, err := scheme.Login(params)
	c.Assert(err, check.IsNil)
	u, err := token.User()
	c.Assert(err, check.IsNil)
	err = scheme.Remove(u)
	c.Assert(err, check.IsNil)
	conn, err := db.Conn()
	c.Assert(err, check.IsNil)
	defer conn.Close()
	var tokens []Token
	coll := collection()
	defer coll.Close()
	err = coll.Find(bson.M{"useremail": "*****@*****.**"}).All(&tokens)
	c.Assert(err, check.IsNil)
	c.Assert(tokens, check.HasLen, 0)
	_, err = auth.GetUserByEmail("*****@*****.**")
	c.Assert(err, check.Equals, auth.ErrUserNotFound)
}
Ejemplo n.º 12
0
// removeUser removes the user from the database and from repository server
//
// If the user is the only one in a team an error will be returned.
func removeUser(w http.ResponseWriter, r *http.Request, t auth.Token) error {
	u, err := t.User()
	if err != nil {
		return err
	}
	email := r.URL.Query().Get("user")
	if email != "" && u.IsAdmin() {
		u, err = auth.GetUserByEmail(email)
		if err != nil {
			return &errors.HTTP{Code: http.StatusNotFound, Message: err.Error()}
		}
	} else if u.IsAdmin() {
		return &errors.HTTP{Code: http.StatusBadRequest, Message: "please specify the user you want to remove"}
	} else if email != "" {
		return &errors.HTTP{Code: http.StatusForbidden, Message: "you're not allowed to remove this user"}
	}
	alwdApps, err := u.AllowedApps()
	if err != nil {
		return err
	}
	manager := repository.Manager()
	for _, app := range alwdApps {
		manager.RevokeAccess(app, u.Email)
	}
	teams, err := u.Teams()
	if err != nil {
		return err
	}
	conn, err := db.Conn()
	if err != nil {
		return err
	}
	defer conn.Close()
	for _, team := range teams {
		if len(team.Users) < 2 {
			msg := fmt.Sprintf(`This user is the last member of the team "%s", so it cannot be removed.

Please remove the team, then remove the user.`, team.Name)
			return &errors.HTTP{Code: http.StatusForbidden, Message: msg}
		}
		err = team.RemoveUser(u)
		if err != nil {
			return err
		}
		// this can be done without the loop
		err = conn.Teams().Update(bson.M{"_id": team.Name}, team)
		if err != nil {
			return err
		}
	}
	rec.Log(u.Email, "remove-user")
	if err := manager.RemoveUser(u.Email); err != nil {
		log.Errorf("Failed to remove user from repository manager: %s", err)
	}
	return app.AuthScheme.Remove(u)
}
Ejemplo n.º 13
0
func (s *S) TestOAuthCreate(c *gocheck.C) {
	scheme := OAuthScheme{}
	user := auth.User{Email: "*****@*****.**"}
	_, err := scheme.Create(&user)
	c.Assert(err, gocheck.IsNil)
	dbUser, err := auth.GetUserByEmail(user.Email)
	c.Assert(err, gocheck.IsNil)
	c.Assert(dbUser.Email, gocheck.Equals, user.Email)
	c.Assert(s.testHandler.Url, gocheck.Equals, "")
}
Ejemplo n.º 14
0
func (s *S) TestSamlCreate(c *check.C) {
	scheme := SAMLAuthScheme{}
	user := auth.User{Email: "*****@*****.**"}
	_, err := scheme.Create(&user)
	c.Assert(err, check.IsNil)
	dbUser, err := auth.GetUserByEmail(user.Email)
	c.Assert(err, check.IsNil)
	c.Assert(dbUser.Email, check.Equals, user.Email)
	c.Assert(dbUser.Password, check.Equals, "")
}
Ejemplo n.º 15
0
func (s *S) TestOAuthCreate(c *check.C) {
	scheme := OAuthScheme{}
	user := auth.User{Email: "*****@*****.**", Password: "******"}
	_, err := scheme.Create(&user)
	c.Assert(err, check.IsNil)
	dbUser, err := auth.GetUserByEmail(user.Email)
	c.Assert(err, check.IsNil)
	c.Assert(dbUser.Email, check.Equals, user.Email)
	c.Assert(dbUser.Password, check.Equals, "")
	c.Assert(repositorytest.Users(), check.DeepEquals, []string{user.Email})
}
Ejemplo n.º 16
0
func (s *S) TestNativeCreate(c *gocheck.C) {
	scheme := NativeScheme{}
	user := &auth.User{Email: "*****@*****.**", Password: "******"}
	retUser, err := scheme.Create(user)
	c.Assert(err, gocheck.IsNil)
	c.Assert(retUser, gocheck.Equals, user)
	dbUser, err := auth.GetUserByEmail(user.Email)
	c.Assert(err, gocheck.IsNil)
	c.Assert(dbUser.Email, gocheck.Equals, user.Email)
	c.Assert(dbUser.Password, gocheck.Not(gocheck.Equals), "123456")
	c.Assert(dbUser.Password, gocheck.Equals, user.Password)
}
Ejemplo n.º 17
0
func getUserQuota(w http.ResponseWriter, r *http.Request, t auth.Token) error {
	email := r.URL.Query().Get(":email")
	user, err := auth.GetUserByEmail(email)
	if err == auth.ErrUserNotFound {
		return &errors.HTTP{
			Code:    http.StatusNotFound,
			Message: err.Error(),
		}
	} else if err != nil {
		return err
	}
	return json.NewEncoder(w).Encode(user.Quota)
}
Ejemplo n.º 18
0
// Delete deletes an app.
//
// Delete an app is a process composed of three steps:
//
//       1. Destroy the app unit
//       2. Unbind all service instances from the app
//       3. Remove the app from the database
func Delete(app *App) error {
	appName := app.Name
	wg := asyncDestroyAppProvisioner(app)
	wg.Add(1)
	defer wg.Done()
	go func() {
		defer ReleaseApplicationLock(appName)
		wg.Wait()
		logConn, err := db.LogConn()
		if err != nil {
			log.Errorf("Unable to delete app %s from db: %s", appName, err.Error())
		}
		defer logConn.Close()
		conn, err := db.Conn()
		if err != nil {
			log.Errorf("Unable to delete app %s from db: %s", appName, err.Error())
		}
		defer conn.Close()
		err = logConn.Logs(appName).DropCollection()
		if err != nil {
			log.Errorf("Ignored error dropping logs collection for app %s: %s", appName, err.Error())
		}
		err = conn.Apps().Remove(bson.M{"name": appName})
		if err != nil {
			log.Errorf("Error trying to destroy app %s from db: %s", appName, err.Error())
		}
		err = markDeploysAsRemoved(appName)
		if err != nil {
			log.Errorf("Error trying to mark old deploys as removed for app %s: %s", appName, err.Error())
		}
	}()
	err := repository.Manager().RemoveRepository(appName)
	if err != nil {
		log.Errorf("failed to remove app %q from repository manager: %s", appName, err)
	}
	token := app.Env["TSURU_APP_TOKEN"].Value
	err = AuthScheme.Logout(token)
	if err != nil {
		log.Errorf("Unable to remove app token in destroy: %s", err.Error())
	}
	owner, err := auth.GetUserByEmail(app.Owner)
	if err != nil {
		log.Errorf("Unable to get app owner in destroy: %s", err.Error())
	} else {
		err = auth.ReleaseApp(owner)
		if err != nil {
			log.Errorf("Unable to release app quota: %s", err.Error())
		}
	}
	return nil
}
Ejemplo n.º 19
0
func (createRootUserCmd) Run(context *cmd.Context, client *cmd.Client) error {
	context.RawOutput()
	scheme, err := config.GetString("auth:scheme")
	if err != nil {
		scheme = "native"
	}
	app.AuthScheme, err = auth.GetScheme(scheme)
	if err != nil {
		return err
	}
	email := context.Args[0]
	user, err := auth.GetUserByEmail(email)
	if err == nil {
		err = addSuperRole(user)
		if err != nil {
			return err
		}
		fmt.Fprintln(context.Stdout, "Root user successfully updated.")
	}
	var confirm, password string
	if scheme == "native" {
		fmt.Fprint(context.Stdout, "Password: "******"\nConfirm: ")
		confirm, err = cmd.PasswordFromReader(context.Stdin)
		if err != nil {
			return err
		}
		fmt.Fprintln(context.Stdout)
		if password != confirm {
			return errors.New("Passwords didn't match.")
		}
	}
	user, err = app.AuthScheme.Create(&auth.User{
		Email:    email,
		Password: password,
	})
	if err != nil {
		return err
	}
	err = addSuperRole(user)
	if err != nil {
		return err
	}
	fmt.Fprintln(context.Stdout, "Root user successfully created.")
	return nil
}
Ejemplo n.º 20
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)
}
Ejemplo n.º 21
0
func (s *ActionsSuite) TestAddKeyInDatabaseActionForward(c *gocheck.C) {
	key := &auth.Key{Name: "mysshkey", Content: "my-ssh-key"}
	u := &auth.User{Email: "*****@*****.**", Password: "******"}
	err := u.Create()
	defer s.conn.Users().Remove(bson.M{"email": u.Email})
	c.Assert(err, gocheck.IsNil)
	ctx := action.FWContext{
		Params: []interface{}{key, u},
	}
	result, err := addKeyInDatabaseAction.Forward(ctx)
	c.Assert(err, gocheck.IsNil)
	c.Assert(result, gocheck.IsNil) // we do not need it
	u, err = auth.GetUserByEmail(u.Email)
	c.Assert(err, gocheck.IsNil)
	c.Assert(u.Keys, gocheck.DeepEquals, []auth.Key{*key})
}
Ejemplo n.º 22
0
func (s *ActionsSuite) TestAddKeyInDatabaseActionBackward(c *gocheck.C) {
	key := &auth.Key{Name: "mysshkey", Content: "my-ssh-key"}
	u := &auth.User{Email: "*****@*****.**", Password: "******"}
	u.AddKey(*key)
	err := u.Create()
	c.Assert(err, gocheck.IsNil)
	defer s.conn.Users().Remove(bson.M{"email": u.Email})
	c.Assert(u.Keys, gocheck.DeepEquals, []auth.Key{*key}) // just in case
	ctx := action.BWContext{
		Params: []interface{}{key, u},
	}
	addKeyInDatabaseAction.Backward(ctx)
	u, err = auth.GetUserByEmail(u.Email)
	c.Assert(err, gocheck.IsNil)
	c.Assert(u.Keys, gocheck.DeepEquals, []auth.Key{})
}
Ejemplo n.º 23
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
		}
		defer response.Body.Close()
		email, err = c.scheme.Parser.Parse(response)
		if email == "" {
			return ErrEmptyUserEmail
		}
		user, 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 {
			log.Errorf("Ignored error trying to create user on gandalf: %s", err.Error())
		}
		t.Extra = make(map[string]string)
		t.Extra["email"] = email
	}
	return makeToken(t).save()
}
Ejemplo n.º 24
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
}
Ejemplo n.º 25
0
func getUserQuota(w http.ResponseWriter, r *http.Request, t auth.Token) error {
	allowed := permission.Check(t, permission.PermUserUpdateQuota)
	if !allowed {
		return permission.ErrUnauthorized
	}
	email := r.URL.Query().Get(":email")
	user, err := auth.GetUserByEmail(email)
	if err == auth.ErrUserNotFound {
		return &errors.HTTP{
			Code:    http.StatusNotFound,
			Message: err.Error(),
		}
	}
	if err != nil {
		return err
	}
	return json.NewEncoder(w).Encode(user.Quota)
}
Ejemplo n.º 26
0
Archivo: oauth.go Proyecto: tsuru/tsuru
func (s *OAuthScheme) handleToken(t *oauth2.Token) (*Token, error) {
	if t.AccessToken == "" {
		return nil, ErrEmptyAccessToken
	}
	conf, err := s.loadConfig()
	if err != nil {
		return nil, err
	}
	client := conf.Client(context.Background(), t)
	response, err := client.Get(s.InfoUrl)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()
	email, err := s.Parser.Parse(response)
	if err != nil {
		return nil, err
	}
	if email == "" {
		return nil, ErrEmptyUserEmail
	}
	user, err := auth.GetUserByEmail(email)
	if err != nil {
		if err != auth.ErrUserNotFound {
			return nil, err
		}
		registrationEnabled, _ := config.GetBool("auth:user-registration")
		if !registrationEnabled {
			return nil, err
		}
		user = &auth.User{Email: email}
		err = user.Create()
		if err != nil {
			return nil, err
		}
	}
	token := Token{*t, email}
	err = token.save()
	if err != nil {
		return nil, err
	}
	return &token, nil
}
Ejemplo n.º 27
0
func (s NativeScheme) Login(params map[string]string) (auth.Token, error) {
	email, ok := params["email"]
	if !ok {
		return nil, ErrMissingEmailError
	}
	password, ok := params["password"]
	if !ok {
		return nil, ErrMissingPasswordError
	}
	user, err := auth.GetUserByEmail(email)
	if err != nil {
		return nil, err
	}
	token, err := createToken(user, password)
	if err != nil {
		return nil, err
	}
	return token, nil
}
Ejemplo n.º 28
0
func resetPassword(w http.ResponseWriter, r *http.Request) error {
	email := r.URL.Query().Get(":email")
	token := r.URL.Query().Get("token")
	u, err := auth.GetUserByEmail(email)
	if err != nil {
		if err == auth.ErrUserNotFound {
			return &errors.HTTP{Code: http.StatusNotFound, Message: err.Error()}
		} else if e, ok := err.(*errors.ValidationError); ok {
			return &errors.HTTP{Code: http.StatusBadRequest, Message: e.Error()}
		}
		return err
	}
	if token == "" {
		rec.Log(email, "reset-password-gen-token")
		return u.StartPasswordReset()
	}
	rec.Log(email, "reset-password")
	return u.ResetPassword(token)
}
Ejemplo n.º 29
0
func dissociateRole(w http.ResponseWriter, r *http.Request, t auth.Token) error {
	if !permission.Check(t, permission.PermRoleUpdateDissociate) {
		return permission.ErrUnauthorized
	}
	roleName := r.URL.Query().Get(":name")
	email := r.URL.Query().Get(":email")
	contextValue := r.URL.Query().Get("context")
	user, err := auth.GetUserByEmail(email)
	if err != nil {
		return err
	}
	err = runWithPermSync([]auth.User{*user}, func() error {
		return user.RemoveRole(roleName, contextValue)
	})
	if err == nil {
		w.WriteHeader(http.StatusOK)
	}
	return err
}
Ejemplo n.º 30
0
func (s *S) TestNativeRemove(c *gocheck.C) {
	scheme := NativeScheme{}
	params := make(map[string]string)
	params["email"] = "*****@*****.**"
	params["password"] = "******"
	token, err := scheme.Login(params)
	c.Assert(err, gocheck.IsNil)
	err = scheme.Remove(token)
	c.Assert(err, gocheck.IsNil)
	conn, err := db.Conn()
	c.Assert(err, gocheck.IsNil)
	defer conn.Close()
	var tokens []Token
	err = conn.Tokens().Find(bson.M{"useremail": "*****@*****.**"}).All(&tokens)
	c.Assert(err, gocheck.IsNil)
	c.Assert(len(tokens), gocheck.Equals, 0)
	_, err = auth.GetUserByEmail("*****@*****.**")
	c.Assert(err, gocheck.Equals, auth.ErrUserNotFound)
}