Beispiel #1
0
func TestGenerateAndValidateClaim(t *testing.T) {

	certs, err := GenerateTestCerts()
	if assert.NoError(t, err) {

		claim, err := GenerateClaim(certs, &models.User{
			ID:       models.String("123"),
			Login:    models.String("wolfeidau"),
			Email:    models.String("*****@*****.**"),
			Name:     models.String("Mark Wolfe"),
			Password: models.String("LkSquwzxdgzSTqqc7Rku5NF8/uR7TBFO1IRF1Yj2c0sM4HEVGgp0bJadWtRAaINP"), //Somewh3r3 there is a cow!
		})

		if assert.NoError(t, err) {

			usr, err := ValidateClaim(certs, claim)
			if assert.NoError(t, err) {
				assert.NotNil(t, usr)
				assert.Equal(t, "123", models.StringValue(usr.ID))
				assert.Equal(t, "wolfeidau", models.StringValue(usr.Login))
				assert.Equal(t, "*****@*****.**", models.StringValue(usr.Email))
			}
		}
	}
}
Beispiel #2
0
func (ur UserResource) createUser(req *restful.Request, resp *restful.Response) {

	usr := new(models.User)
	err := req.ReadEntity(usr)

	if err != nil {
		resp.WriteHeaderAndEntity(http.StatusInternalServerError, errorMsg("Server error."))
		return
	}

	allErrs := validation.ValidateUserRegister(usr)

	if len(allErrs) != 0 {
		resp.WriteHeaderAndEntity(http.StatusBadRequest, validationErrors("validation failed", allErrs))
		return
	}

	exists, err := ur.store.Exists(models.StringValue(usr.Login))

	if err != nil {
		resp.WriteHeaderAndEntity(http.StatusInternalServerError, errorMsg("Server error."))
		return
	}

	if exists {
		resp.WriteHeaderAndEntity(http.StatusConflict, errorMsg("User already exists."))
		return
	}

	// hash the password
	pass := models.StringValue(usr.Password)

	pass, err = util.HashPassword(pass)

	if err != nil {
		resp.WriteHeaderAndEntity(http.StatusInternalServerError, errorMsg("Server error."))
		return
	}

	usr.Password = models.String(pass)

	nusr, err := ur.store.Create(usr)

	if err != nil {
		resp.WriteHeaderAndEntity(http.StatusInternalServerError, errorMsg("Server error."))
		return
	}

	nusr.Password = nil

	resp.WriteHeaderAndEntity(http.StatusCreated, nusr)
}
Beispiel #3
0
// GenerateClaim generate a JWT token containing a claim using the supplied
// certificates and user
func GenerateClaim(certs *Certs, usr *models.User) (string, error) {
	// generate a token
	var claims = jws.Claims{
		"user_id": models.StringValue(usr.ID),
		"login":   models.StringValue(usr.Login),
		"email":   models.StringValue(usr.Email),
		"exp":     time.Now().Add(24 * time.Hour).Unix(),
	}

	j := jws.NewJWT(claims, crypto.SigningMethodRS512)
	b, err := j.Serialize(certs.PrivateKey)

	return string(b), err
}
Beispiel #4
0
// BuildJWTAuthFunc build the JWT authentication filter function
func BuildJWTAuthFunc(store users.UserStore, certs *auth.Certs) restful.FilterFunction {
	return func(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
		encoded := req.Request.Header.Get("Authorization")

		if len(encoded) == 0 {
			resp.WriteErrorString(401, "401: Not Authorized")
			return
		}

		if !strings.HasPrefix(encoded, "Bearer ") {
			resp.WriteErrorString(401, "401: Not Authorized")
			return
		}

		tokens := strings.Split(encoded, " ")

		usr, err := auth.ValidateClaim(certs, tokens[1])

		if err != nil {
			resp.WriteErrorString(401, "401: Not Authorized")
			return
		}

		// Extract the user_id
		req.SetAttribute("user_id", models.StringValue(usr.ID))

		chain.ProcessFilter(req, resp)
	}
}
Beispiel #5
0
// GetPasswordByLogin retrieve the users password for authentication
func (usl *UserStoreLocal) GetPasswordByLogin(login string) (string, error) {
	for _, v := range usl.users {
		if reflect.DeepEqual(v.Login, models.String(login)) {
			return models.StringValue(v.Password), nil
		}
	}
	return "", ErrUserNotFound
}
Beispiel #6
0
func validateFieldLength(value *string, fldPath *field.Path, min, max int, fieldName string) field.ErrorList {
	allErrs := field.ErrorList{}

	if v := models.StringValue(value); !checkFieldLength(v, min, max) {
		allErrs = append(allErrs, field.Invalid(fldPath.Child(fieldName), v, fmt.Sprintf("%s: %s must be between %d and %d characters", fldPath.String(), fieldName, min, max)))
	}

	return allErrs
}
Beispiel #7
0
// Update the user, this is currently limited to changing the users name.
func (usl *UserStoreLocal) Update(user *models.User) error {
	cusr, ok := usl.users[models.StringValue(user.ID)]

	if !ok {
		return ErrUserNotFound
	}

	cusr.Name = user.Name

	return nil
}
Beispiel #8
0
// Create create a new user in the system with the given information
func (usl *UserStoreLocal) Create(user *models.User) (*models.User, error) {

	var id string

	// check for unique login
	if usl.loginExists(models.StringValue(user.Login)) {
		return nil, ErrUserAlreadyExists
	}

	if user.ID == nil {
		id = newID()
		user.ID = models.String(id)
	} else {
		id = models.StringValue(user.ID)
	}

	usl.users[id] = user

	return user, nil
}
Beispiel #9
0
func TestGetUserByLoginRethinkDB(t *testing.T) {

	_, userStore, userID, err := createUserStoreAndSession()

	if assert.NoError(t, err, "connecting to rethinkdb") {

		usr, err := userStore.GetByLogin("wolfeidau")

		if assert.Nil(t, err) {
			assert.Equal(t, "*****@*****.**", models.StringValue(usr.Email))
			assert.Equal(t, userID, models.StringValue(usr.ID))
		}

		usr, err = userStore.GetByLogin("nothere")

		if assert.Error(t, err) {
			assert.Equal(t, err, ErrUserNotFound)
		}
	}
}
Beispiel #10
0
// Update the user in RethinkDB
func (us *UserStoreRethinkDB) Update(user *models.User) error {

	userID := models.StringValue(user.ID)

	if user.Name == nil {
		return nil
	}

	res, err := r.DB(DBName).Table(TableName).Get(userID).Update(map[string]interface{}{
		"name": models.StringValue(user.Name),
	}).RunWrite(us.session)
	if err != nil {
		return err
	}

	if res.Replaced != 1 {
		return ErrUserNotFound
	}

	return nil
}
Beispiel #11
0
// GetPasswordByLogin retrieve the password for a user using their login
func (us *UserStoreRethinkDB) GetPasswordByLogin(login string) (string, error) {
	res, err := r.DB(DBName).Table(TableName).Filter(map[string]interface{}{
		"login": login,
	}).Run(us.session)
	if err != nil {
		return "", err
	}

	defer res.Close()

	if res.IsNil() {
		return "", ErrUserNotFound
	}

	usr := new(models.User)
	err = res.One(&usr)
	if err != nil {
		return "", err
	}

	return models.StringValue(usr.Password), nil
}
Beispiel #12
0
func TestGetUserRethinkDB(t *testing.T) {

	_, userStore, userID, err := createUserStoreAndSession()

	if assert.NoError(t, err, "connecting to rethinkdb") {

		usr, err := userStore.GetByID(userID)
		if assert.NoError(t, err, "getting user from rethinkdb") {

			if assert.NotNil(t, usr) {
				assert.Equal(t, models.StringValue(usr.Email), "*****@*****.**")
			}
		}

		usr, err = userStore.GetByID("123")

		if assert.Error(t, err) {
			assert.Equal(t, err, ErrUserNotFound)
		}

	}
}