Example #1
0
func createTestAccount(t *testing.T) *models.Account {
	acc := &models.Account{
		Id: bson.NewObjectId(),
		Profile: models.AccountProfile{
			Nickname:  bson.NewObjectId().Hex(), // random username
			FirstName: bson.NewObjectId().Hex(),
			LastName:  bson.NewObjectId().Hex(),
		},
		Type:        "registered",
		SocialApiId: bson.NewObjectId().Hex(),
	}

	if err := modelhelper.CreateAccount(acc); err != nil {
		t.Error(err)
	}

	return acc
}
Example #2
0
func CreateAccountInBothDbsWithNick(nick string) (*Account, error) {
	accId := bson.NewObjectId()
	accHex := nick

	oldAcc, err := modelhelper.GetAccount(nick)
	if err == mgo.ErrNotFound {

		oldAcc = &kodingmodels.Account{
			Id: accId,
			Profile: struct {
				Nickname  string `bson:"nickname" json:"nickname"`
				FirstName string `bson:"firstName" json:"firstName"`
				LastName  string `bson:"lastName" json:"lastName"`
				Hash      string `bson:"hash" json:"hash"`
			}{
				Nickname: nick,
			},
		}

		err := modelhelper.CreateAccount(oldAcc)
		if err != nil {
			return nil, err
		}
	}

	oldUser, err := modelhelper.GetUser(nick)
	if err == mgo.ErrNotFound {
		oldUser = &kodingmodels.User{
			ObjectId:       bson.NewObjectId(),
			Password:       accHex,
			Salt:           accHex,
			Name:           nick,
			Email:          accHex + "@koding.com",
			Status:         "confirmed",
			EmailFrequency: &kodingmodels.EmailFrequency{},
		}

		err = modelhelper.CreateUser(oldUser)
		if err != nil {
			return nil, err
		}
	}

	a := NewAccount()
	a.Nick = nick
	a.OldId = accId.Hex()

	if err := a.ByNick(nick); err == bongo.RecordNotFound {
		if err := a.Create(); err != nil {
			return nil, err
		}
	}

	if oldAcc.SocialApiId != strconv.FormatInt(a.Id, 10) {
		s := modelhelper.Selector{"_id": oldAcc.Id}
		o := modelhelper.Selector{"$set": modelhelper.Selector{
			"socialApiId": strconv.FormatInt(a.Id, 10),
		}}

		if err := modelhelper.UpdateAccount(s, o); err != nil {
			return nil, err
		}
	}

	return a, nil
}
Example #3
0
func testFixture(t *testing.T) (*models.User, *models.Group, *models.Machine, *models.Account, func()) {
	var c cleaner

	user := &models.User{
		ObjectId: bson.NewObjectId(),
		Name:     "testuser",
	}

	if err := modelhelper.CreateUser(user); err != nil {
		c.clean()
		t.Fatalf("error creating user: %s", err)
	}

	c.add(user)

	account := &models.Account{
		Id: bson.NewObjectId(),
		Profile: models.AccountProfile{
			Nickname:  user.Name,
			FirstName: bson.NewObjectId().Hex(),
			LastName:  bson.NewObjectId().Hex(),
		},
		Type: "registered",
	}

	if err := modelhelper.CreateAccount(account); err != nil {
		c.clean()
		t.Fatalf("error creating account: %s", err)
	}

	c.add(account)

	group, err := createGroup()
	if err != nil {
		c.clean()
		t.Fatalf("error creating group: %s", err)
	}

	c.add(group)

	machine := &models.Machine{
		ObjectId: bson.NewObjectId(),
		Uid:      bson.NewObjectId().Hex(),
		Provider: "koding",
		Users: []models.MachineUser{
			{
				Id:    user.ObjectId,
				Owner: true,
			},
		},
	}

	if err := modelhelper.CreateMachine(machine); err != nil {
		c.clean()
		t.Fatalf("error creating machine: %s", err)
	}

	c.add(machine)

	return user, group, machine, account, c.clean
}
Example #4
0
func CreateUser(opts *UserOptions) (*User, error) {
	username := opts.Username
	groupname := opts.Groupname
	provider := opts.Provider
	template := opts.Template

	privateKey, publicKey, err := sshutil.TemporaryKey()
	if err != nil {
		return nil, err
	}

	labels, err := machineLabels([]byte(template))
	if err != nil {
		return nil, err
	}

	relationExists := true

	// jAccounts
	account, err := modelhelper.GetAccount(username)
	if err == mgo.ErrNotFound {
		relationExists = false

		account = &models.Account{
			Id: bson.NewObjectId(),
			Profile: models.AccountProfile{
				Nickname: username,
			},
		}

		err = modelhelper.CreateAccount(account)
	}
	if err != nil {
		return nil, errors.New("failure looking up jAccounts: " + err.Error())
	}

	// jGroups
	group, err := modelhelper.GetGroup(groupname)
	if err == mgo.ErrNotFound {
		relationExists = false

		group = &models.Group{
			Id:    bson.NewObjectId(),
			Title: groupname,
			Slug:  groupname,
		}

		err = modelhelper.CreateGroup(group)
	}
	if err != nil {
		return nil, errors.New("failure looking up jGroups: " + err.Error())
	}

	if !relationExists {
		// add relation between use and group
		relationship := &models.Relationship{
			Id:         bson.NewObjectId(),
			TargetId:   account.Id,
			TargetName: "JAccount",
			SourceId:   group.Id,
			SourceName: "JGroup",
			As:         "member",
		}

		err := modelhelper.AddRelationship(relationship)
		if err != nil {
			return nil, errors.New("failure insering relationship: " + err.Error())
		}
	}

	// jUsers
	user, err := modelhelper.GetUser(username)
	if err == nil && len(user.SshKeys) != 0 {
		publicKey = user.SshKeys[0].Key
	}
	if err == mgo.ErrNotFound {
		user = &models.User{
			ObjectId:      bson.NewObjectId(),
			Email:         username + "@" + username + ".com",
			LastLoginDate: time.Now().UTC(),
			RegisteredAt:  time.Now().UTC(),
			Name:          username, // bson equivelant is username
			Password:      "******",
			Status:        "confirmed",
			SshKeys: []struct {
				Title string `bson:"title"`
				Key   string `bson:"key"`
			}{
				{Key: publicKey},
			},
		}

		err = modelhelper.CreateUser(user)
	}
	if err != nil {
		return nil, errors.New("failure looking up jUsers: " + err.Error())
	}

	queryString := protocol.Kite{ID: opts.KlientID}.String()

	cred := &models.Credential{
		Id:         bson.NewObjectId(),
		Provider:   opts.Provider,
		Identifier: bson.NewObjectId().Hex(),
		OriginId:   account.Id,
	}

	credData := &models.CredentialData{
		Id:         bson.NewObjectId(),
		Identifier: cred.Identifier,
		OriginId:   account.Id,
		Meta: bson.M{
			"queryString": queryString,
			"memory":      0,
			"cpu":         0,
			"box":         "",
		},
	}

	if err := modelhelper.InsertCredential(cred, credData); err != nil {
		return nil, err
	}

	relationship := &models.Relationship{
		Id:         bson.NewObjectId(),
		TargetId:   cred.Id,
		TargetName: "JCredential",
		SourceId:   account.Id,
		SourceName: "JAccount",
		As:         "owner",
	}

	if err := modelhelper.AddRelationship(relationship); err != nil {
		return nil, err
	}

	// jComputeStack and jStackTemplates
	stackTemplateId := bson.NewObjectId()
	stackTemplate := &models.StackTemplate{
		Id: stackTemplateId,
		Credentials: map[string][]string{
			"vagrant": {cred.Identifier},
		},
	}
	stackTemplate.Template.Content = template

	if err := modelhelper.CreateStackTemplate(stackTemplate); err != nil {
		return nil, err
	}

	// later we can add more users with "Owner:false" to test sharing capabilities
	users := []models.MachineUser{
		{Id: user.ObjectId, Sudo: true, Owner: true},
	}

	machineIds := make([]bson.ObjectId, len(labels))

	for i, label := range labels {
		machineId := bson.NewObjectId()
		machine := &models.Machine{
			ObjectId:   machineId,
			Label:      label,
			Domain:     username + ".dev.koding.io",
			Provider:   provider,
			CreatedAt:  time.Now().UTC(),
			Users:      users,
			Meta:       make(bson.M, 0),
			Groups:     make([]models.MachineGroup, 0),
			Credential: username,
		}

		machine.Assignee.InProgress = false
		machine.Assignee.AssignedAt = time.Now().UTC()
		machine.Status.State = machinestate.NotInitialized.String()
		machine.Status.ModifiedAt = time.Now().UTC()

		machineIds[i] = machine.ObjectId

		if err := modelhelper.CreateMachine(machine); err != nil {
			return nil, err
		}
	}

	computeStackID := bson.NewObjectId()
	computeStack := &models.ComputeStack{
		Id:          computeStackID,
		BaseStackId: stackTemplateId,
		Machines:    machineIds,
	}

	if err := modelhelper.CreateComputeStack(computeStack); err != nil {
		return nil, err
	}

	return &User{
		MachineIDs:      machineIds,
		MachineLabels:   labels,
		StackID:         computeStackID.Hex(),
		StackTemplateID: stackTemplate.Id.Hex(),
		AccountID:       account.Id,
		CredID:          cred.Id.Hex(),
		CredDataID:      credData.Id.Hex(),
		PrivateKey:      privateKey,
		PublicKey:       publicKey,
		Identifiers:     []string{cred.Identifier},
	}, nil
}
Example #5
0
func TestChannelUpdatedCalculateUnreadItemCount(t *testing.T) {
	r := runner.New("test")
	if err := r.Init(); err != nil {
		t.Fatalf("couldnt start bongo %s", err.Error())
	}
	defer r.Close()

	appConfig := config.MustRead(r.Conf.Path)
	modelhelper.Initialize(appConfig.Mongo)
	defer modelhelper.Close()

	groupName := models.RandomGroupName()

	Convey("while testing get account", t, func() {
		Convey("if cookie is not set, should return nil", func() {
			a := getAccount(&http.Request{}, models.Channel_KODING_NAME)
			So(a, ShouldNotBeNil)
			So(a.Id, ShouldBeZeroValue)
		})

		Convey("if cookie value is not set, should return nil", func() {
			req, _ := http.NewRequest("GET", "/", nil)

			expire := time.Now().AddDate(0, 0, 1)
			cookie := http.Cookie{
				Name:    "clientId",
				Value:   "",
				Path:    "/",
				Domain:  "localhost",
				Expires: expire,
			}

			req.AddCookie(&cookie)

			a := getAccount(req, models.Channel_KODING_NAME)
			So(a, ShouldNotBeNil)
			So(a.Id, ShouldBeZeroValue)
		})

		Convey("if session doesnt have username, should return nil", func() {
			ses, err := modelhelper.CreateSessionForAccount("", groupName)
			So(err, ShouldBeNil)
			So(ses, ShouldNotBeNil)

			req, _ := http.NewRequest("GET", "/", nil)
			expire := time.Now().AddDate(0, 0, 1)
			cookie := http.Cookie{
				Name:    "clientId",
				Value:   ses.ClientId,
				Path:    "/",
				Domain:  "localhost",
				Expires: expire,
			}

			req.AddCookie(&cookie)

			a := getAccount(req, models.Channel_KODING_NAME)
			So(a, ShouldNotBeNil)
			So(a.Id, ShouldBeZeroValue)
		})

		Convey("if session is valid, should return account", func() {
			acc, err := models.CreateAccountInBothDbs()
			So(err, ShouldBeNil)
			So(acc, ShouldNotBeNil)

			ses, err := modelhelper.CreateSessionForAccount(acc.Nick, groupName)
			So(err, ShouldBeNil)
			So(ses, ShouldNotBeNil)

			req, _ := http.NewRequest("GET", "/", nil)
			expire := time.Now().AddDate(0, 0, 1)
			cookie := http.Cookie{
				Name:    "clientId",
				Value:   ses.ClientId,
				Path:    "/",
				Domain:  "localhost",
				Expires: expire,
			}

			req.AddCookie(&cookie)

			res := getAccount(req, models.Channel_KODING_NAME)
			So(res, ShouldNotBeNil)
			So(acc.Id, ShouldEqual, res.Id)
		})
	})

	Convey("while making sure account", t, func() {
		Convey("if account is not in postgres", func() {

			nick := models.RandomName()
			oldAcc := &kodingmodels.Account{
				Id: bson.NewObjectId(),
				Profile: kodingmodels.AccountProfile{
					Nickname: nick,
				},
			}
			err := modelhelper.CreateAccount(oldAcc)
			So(err, ShouldBeNil)

			oldUser := &kodingmodels.User{
				ObjectId:       bson.NewObjectId(),
				Password:       nick,
				Salt:           nick,
				Name:           nick,
				Email:          nick + "@koding.com",
				EmailFrequency: &kodingmodels.EmailFrequency{},
			}

			err = modelhelper.CreateUser(oldUser)
			So(err, ShouldBeNil)

			groupName := models.RandomGroupName()
			_, err = makeSureAccount(groupName, nick)
			So(err, ShouldBeNil)

			Convey("should create it in postgres", func() {
				a := models.NewAccount()
				err = a.ByNick(nick)
				So(err, ShouldBeNil)
				So(a.OldId, ShouldEqual, oldAcc.Id.Hex())

				Convey("should set socialAPI id in mongo", func() {
					oldAccFromDB, err := modelhelper.GetAccount(nick)
					So(err, ShouldBeNil)
					So(oldAccFromDB.SocialApiId, ShouldEqual, strconv.FormatInt(a.Id, 10))
				})
			})
		})

		Convey("if account is in postgres", func() {
			acc, err := models.CreateAccountInBothDbs()
			So(err, ShouldBeNil)
			So(acc, ShouldNotBeNil)

			groupName := models.RandomGroupName()

			_, err = makeSureAccount(groupName, acc.Nick)
			So(err, ShouldBeNil)

			Convey("should be in postgres", func() {
				a := models.NewAccount()
				err = a.ByNick(acc.Nick)
				So(err, ShouldBeNil)
				So(a.OldId, ShouldEqual, acc.OldId)

				Convey("should have socialAPI set", func() {
					oldAccFromDB, err := modelhelper.GetAccount(acc.Nick)
					So(err, ShouldBeNil)
					So(oldAccFromDB.SocialApiId, ShouldEqual, strconv.FormatInt(a.Id, 10))
				})
			})
		})
	})

	Convey("while making sure group membership", t, func() {
		Convey("if account is not not a member", func() {
			account := models.CreateAccountWithTest()
			requester := models.CreateAccountWithTest()
			groupChannel := models.CreateTypedPublicChannelWithTest(account.Id, models.Channel_TYPE_GROUP)

			err := makeSureMembership(groupChannel, requester.Id)
			So(err, ShouldBeNil)

			Convey("should add as participant", func() {
				status, err := groupChannel.IsParticipant(requester.Id)
				So(err, ShouldBeNil)
				So(status, ShouldBeTrue)

				Convey("if account is a member", func() {
					err := makeSureMembership(groupChannel, requester.Id)
					So(err, ShouldBeNil)

					Convey("should be a participant", func() {
						status, err := groupChannel.IsParticipant(requester.Id)
						So(err, ShouldBeNil)
						So(status, ShouldBeTrue)
					})
				})
			})

		})
	})
}