Esempio n. 1
0
func (p *UserService) getAllUserByName(username string) (user []entity.User, err error) {
	query := strings.Join([]string{"{\"username\": \"", username, "\"}"}, "")

	selector := make(bson.M)
	err = json.Unmarshal([]byte(query), &selector)
	if err != nil {
		return
	}
	selector, err = mejson.Unmarshal(selector)
	if err != nil {
		return
	}

	user = []entity.User{}
	queryStruct := dao.QueryStruct{
		CollectionName: p.userCollectionName,
		Selector:       selector,
		Skip:           0,
		Limit:          0,
		Sort:           ""}

	_, err = dao.HandleQueryAll(&user, queryStruct)

	return
}
Esempio n. 2
0
func bsonify() {
	in := map[string]interface{}{
		"_id": map[string]interface{}{
			"$oid": "123412341234123412341234",
		},
		"test": map[string]interface{}{
			"subid": map[string]interface{}{
				"$oid": "123412341234123412341234",
			},
		},
		"time": map[string]interface{}{
			"$date": 1392227630711,
		},
		"timestamp": map[string]interface{}{
			"$timestamp": map[string]interface{}{
				"t": 18,
				"i": 1,
			},
		},
		"binary": map[string]interface{}{
			"$binary": "b2ggaGk=",
			"$type":   "00",
		},
	}
	m, err := mejson.Unmarshal(in)
	if err != nil {
		panic(err)
	}
	fmt.Printf("bson: %+v\n", m)
}
Esempio n. 3
0
// GetRoleByName return the role by the role name.
func (p *RoleService) getRoleByName(rolename string) (role *entity.Role, err error) {
	query := strings.Join([]string{"{\"rolename\": \"", rolename, "\"}"}, "")

	selector := make(bson.M)
	err = json.Unmarshal([]byte(query), &selector)
	if err != nil {
		return
	}
	selector, err = mejson.Unmarshal(selector)
	if err != nil {
		return
	}

	role = new(entity.Role)
	queryStruct := dao.QueryStruct{
		CollectionName: p.collectionName,
		Selector:       selector,
		Skip:           0,
		Limit:          0,
		Sort:           ""}

	err = dao.HandleQueryOne(role, queryStruct)

	return
}
Esempio n. 4
0
func (t *Transformer) toMsg(incoming interface{}, msg *message.Msg) error {

	switch newMsg := incoming.(type) {
	case map[string]interface{}: // we're a proper message.Msg, so copy the data over
		msg.Op = message.OpTypeFromString(newMsg["op"].(string))
		msg.Timestamp = newMsg["ts"].(int64)
		msg.Namespace = newMsg["ns"].(string)

		switch data := newMsg["data"].(type) {
		case otto.Value:
			exported, err := data.Export()
			if err != nil {
				t.pipe.Err <- t.transformerError(ERROR, err, msg)
				return nil
			}
			d, err := mejson.Unmarshal(exported.(map[string]interface{}))
			if err != nil {
				t.pipe.Err <- t.transformerError(ERROR, err, msg)
				return nil
			}
			msg.Data = map[string]interface{}(d)
		case map[string]interface{}:
			d, err := mejson.Unmarshal(data)
			if err != nil {
				t.pipe.Err <- t.transformerError(ERROR, err, msg)
				return nil
			}
			msg.Data = map[string]interface{}(d)
		default:
			msg.Data = data
		}
	case bool: // skip this doc if we're a bool and we're false
		if !newMsg {
			msg.Op = message.Noop
			return nil
		}
	default: // something went wrong
		return fmt.Errorf("returned doc was not a map[string]interface{}")
	}

	return nil
}
Esempio n. 5
0
//
// Updates or inserts document(/s) in collection.
// Depending on request method
// 	POST - insert
// 	PUT  - update
//
func (d *Resource) CollectionUpdateHandler(req *restful.Request, resp *restful.Response) {
	// Read a document from request
	document := bson.M{}
	// Handle JSON parsing manually here, instead of relying on go-restful's
	// req.ReadEntity. This is because ReadEntity currently parses JSON with
	// UseNumber() which turns all numbers into strings. See:
	// https://github.com/emicklei/mora/pull/31
	decoder := json.NewDecoder(req.Request.Body)
	err := decoder.Decode(&document) //将body赋值给document
	if err != nil {
		WriteStatusError(http.StatusBadRequest, err, resp)
		return
	}

	document, err = mejson.Unmarshal(document)
	if err != nil {
		WriteStatusError(http.StatusBadRequest, err, resp)
		return
	}

	// Mongo session
	session, needclose, err := d.SessMng.Get(getParam("alias", req))
	if err != nil {
		WriteError(err, resp)
		return
	}

	// Close session if it's needed
	if needclose {
		defer session.Close()
	}

	// Mongo Collection
	col := d.GetMongoCollection(req, session)

	// Compose a selector from request
	selector, one, err := getSelector(req)
	if err != nil {
		WriteError(err, resp)
		return
	}
	//isStrict := getParam("strict", req)

	// Insert if request method is POST or no selector otherwise update
	if req.Request.Method == "POST" { //如果是PUT请求,那么则新增
		d.handleInsert(col, selector, document, req, resp)
		return
	}

	//否则,就更新
	d.handleUpdate(col, one, selector, document, req, resp)
}
Esempio n. 6
0
func (p *AuthService) format(ret map[string]interface{}) (bson.M, error) {
	if ret == nil || len(ret) <= 0 {
		return bson.M{}, nil
	}

	query, err := mejson.Unmarshal(ret)
	if err != nil {
		logrus.Warnln("unmarshal query ret to bson error %v", err)
		return nil, errors.New("unmarshal query ret to bson error")
	}

	return query, nil
}
Esempio n. 7
0
func (p *TenantService) deleteTenantByName(tenantname string) (err error) {
	query := strings.Join([]string{"{\"tenantname\": \"", tenantname, "\"}"}, "")

	selector := make(bson.M)
	err = json.Unmarshal([]byte(query), &selector)
	if err != nil {
		return
	}
	selector, err = mejson.Unmarshal(selector)
	if err != nil {
		return
	}

	return dao.HandleDelete(p.collectionName, true, selector)
}
Esempio n. 8
0
// UserChangePasswdHandler parses the http request and change
// password of an exist user.
// Usage :
//		PUT v1/user/changepassword/{ParamID}
// Params :
//		ParamID : storage identifier of user
// If successful,response code will be set to 201.
func (p *Resource) UserChangePasswdHandler(req *restful.Request, resp *restful.Response) {
	logrus.Infof("UserChangePasswdHandler is called!")
	token := req.HeaderParameter("X-Auth-Token")
	id := req.PathParameter(ParamID)
	if len(id) <= 0 {
		logrus.Warnln("user id should not be null for change password operation")
		response.WriteStatusError(services.COMMON_ERROR_INVALIDATE, errors.New("user id should not be null for update operation"), resp)
		return
	}

	document := bson.M{}
	decoder := json.NewDecoder(req.Request.Body)
	err := decoder.Decode(&document)
	if err != nil {
		logrus.Errorf("decode change password object err is %v", err)
		response.WriteStatusError(services.COMMON_ERROR_INTERNAL, err, resp)
		return
	}

	document, err = mejson.Unmarshal(document)
	if err != nil {
		logrus.Errorf("unmarshal change password obejct err is %v", err)
		response.WriteStatusError(services.COMMON_ERROR_INTERNAL, err, resp)
		return
	}

	password := document["password"]
	newpwd1 := document["newpassword"]
	newpwd2 := document["confirm_newpassword"]
	if password == nil || newpwd1 == nil || newpwd2 == nil {
		logrus.Errorln("invalid parameter! password and newpassword field should not be null")
		response.WriteStatusError(services.COMMON_ERROR_INVALIDATE, errors.New("invalid parameter!password, newpassword and confirm_newpassword should not be null!"), resp)
		return
	}

	created, errorCode, err := services.GetUserService().UserChangePassword(token, id, password.(string), newpwd1.(string), newpwd2.(string))
	if err != nil {
		response.WriteStatusError(errorCode, err, resp)
		return
	}

	p.successUpdate(id, created, req, resp)

}
Esempio n. 9
0
// TokenReGenerateHandler parses the http request and generate
// another user's token from current token.
// Usage :
//		POST /v1/token/regenerate
// If successful,response code will be set to 201.
func (p *Resource) TokenReGenerateHandler(req *restful.Request, resp *restful.Response) {
	logrus.Infoln("TokenReGenerateHandler is called!")
	token := req.HeaderParameter("X-Auth-Token")

	document := bson.M{}
	decoder := json.NewDecoder(req.Request.Body)
	err := decoder.Decode(&document)
	if err != nil {
		logrus.Errorf("decode token generate err is %v", err)
		response.WriteStatusError(services.TOKEN_ERROR_CREATE, err, resp)
		return
	}

	document, err = mejson.Unmarshal(document)
	if err != nil {
		logrus.Errorf("unmarshal token generate err is %v", err)
		response.WriteStatusError(services.TOKEN_ERROR_CREATE, err, resp)
		return
	}

	userid := document["user_id"]
	tenantid := document["tenant_id"]
	if userid == nil || tenantid == nil {
		logrus.Errorln("invalid parameter! user and tenant should not be null!")
		response.WriteStatusError(services.COMMON_ERROR_INVALIDATE, errors.New("invalid parameter! user and tenant should not be null!"), resp)
		return
	}

	tokenId, errorCode, err := services.GetTokenService().TokenReGenerate(token, userid.(string), tenantid.(string))
	if err != nil {
		response.WriteStatusError(errorCode, err, resp)
		return
	}

	response.WriteResponse(tokenId, resp)

	return
}
Esempio n. 10
0
//
// Composes a mongo selector from request
// If _id in the path is present `one` is true and query parameter is not inclued.
//
// Param(ws.PathParameter(ParamID, "query in json format")).
// Param(ws.QueryParameter("query", "query in json format")).
func getSelector(req *restful.Request) (selector bson.M, one bool, err error) {
	selector = make(bson.M)
	// If id is included in path, dont include query
	// It only select's one item
	if id := req.PathParameter(ParamID); id != "" {
		selector[ParamID] = id
	} else {
		// Unmarshal json query if any
		if query := req.QueryParameter("query"); len(query) > 0 {
			query, err = url.QueryUnescape(query)
			if err != nil {
				return
			}
			err = json.Unmarshal([]byte(query), &selector)
			if err != nil {
				return
			}
			selector, err = mejson.Unmarshal(selector)
			if err != nil {
				return
			}
		}
	}

	// Transform string HexId to ObjectIdHex
	if selid, _ := selector[ParamID].(string); selid != "" {
		// Transform to ObjectIdHex if required
		if bson.IsObjectIdHex(selid) {
			selector[ParamID] = bson.ObjectIdHex(selid)
		} else {
			selector[ParamID] = selid
		}
		one = true
	}

	return
}
Esempio n. 11
0
func (t *Transformer) transformOne(msg *message.Msg) (*message.Msg, error) {

	var (
		doc    interface{}
		value  otto.Value
		outDoc otto.Value
		result interface{}
		err    error
	)

	// short circuit for deletes and commands
	if msg.Op == message.Delete || msg.Op == message.Command {
		return msg, nil
	}

	now := time.Now().Nanosecond()
	if msg.IsMap() {
		if doc, err = mejson.Marshal(msg.Data); err != nil {
			t.pipe.Err <- t.transformerError(ERROR, err, msg)
			return msg, nil
		}
	} else {
		doc = msg.Data
	}

	if value, err = t.vm.ToValue(doc); err != nil {
		t.pipe.Err <- t.transformerError(ERROR, err, msg)
		return msg, nil
	}

	// now that we have finished casting our map to a bunch of different types,
	// lets run our transformer on the document
	beforeVM := time.Now().Nanosecond()
	if outDoc, err = t.vm.Call(`module.exports`, nil, value); err != nil {
		t.pipe.Err <- t.transformerError(ERROR, err, msg)
		return msg, nil
	}

	if result, err = outDoc.Export(); err != nil {
		t.pipe.Err <- t.transformerError(ERROR, err, msg)
		return msg, nil
	}

	afterVM := time.Now().Nanosecond()

	switch r := result.(type) {
	case map[string]interface{}:
		doc, err := mejson.Unmarshal(r)
		if err != nil {
			t.pipe.Err <- t.transformerError(ERROR, err, msg)
			return msg, nil
		}
		msg.Data = map[string]interface{}(doc)
	default:
		msg.Data = r
	}

	if t.debug {
		then := time.Now().Nanosecond()
		fmt.Printf("document transformed in %dus.  %d to marshal, %d in the vm, %d to unmarshal\n", (then-now)/1000, (beforeVM-now)/1000, (afterVM-beforeVM)/1000, (then-afterVM)/1000)
	}

	return msg, nil
}
func (t *Transformer) transformOne(msg *message.Msg) (*message.Msg, error) {

	var (
		doc    interface{}
		value  otto.Value
		outDoc otto.Value
		result interface{}
		err    error
	)

	// short circuit for deletes and commands
	if msg.Op == message.Command {
		return msg, nil
	}

	now := time.Now().Nanosecond()
	fullDoc := map[string]interface{}{
		"data": msg.Data,
		"ts":   msg.Timestamp,
		"op":   msg.Op.String(),
	}
	if msg.IsMap() {
		if doc, err = mejson.Marshal(msg.Data); err != nil {
			t.pipe.Err <- t.transformerError(ERROR, err, msg)
			return msg, nil
		}
		fullDoc["data"] = doc
	}

	if value, err = t.vm.ToValue(fullDoc); err != nil {
		t.pipe.Err <- t.transformerError(ERROR, err, msg)
		return msg, nil
	}

	// now that we have finished casting our map to a bunch of different types,
	// lets run our transformer on the document
	beforeVM := time.Now().Nanosecond()
	if outDoc, err = t.vm.Call(`module.exports`, nil, value); err != nil {
		t.pipe.Err <- t.transformerError(ERROR, err, msg)
		return msg, nil
	}

	if result, err = outDoc.Export(); err != nil {
		t.pipe.Err <- t.transformerError(ERROR, err, msg)
		return msg, nil
	}

	afterVM := time.Now().Nanosecond()

	fullDoc, ok := result.(map[string]interface{})
	if !ok {
		t.pipe.Err <- t.transformerError(ERROR, fmt.Errorf("returned doc was not a map[string]interface{}"), msg)
		return msg, fmt.Errorf("returned doc was not a map[string]interface{}")
	}

	msg.Op = message.OpTypeFromString(fullDoc["op"].(string))
	msg.Timestamp = fullDoc["ts"].(int64)
	switch data := fullDoc["data"].(type) {
	case otto.Value:
		exported, err := data.Export()
		if err != nil {
			t.pipe.Err <- t.transformerError(ERROR, err, msg)
			return msg, nil
		}
		d, err := mejson.Unmarshal(exported.(map[string]interface{}))
		if err != nil {
			t.pipe.Err <- t.transformerError(ERROR, err, msg)
			return msg, nil
		}
		msg.Data = map[string]interface{}(d)
	case map[string]interface{}:
		d, err := mejson.Unmarshal(data)
		if err != nil {
			t.pipe.Err <- t.transformerError(ERROR, err, msg)
			return msg, nil
		}
		msg.Data = map[string]interface{}(d)
	default:
		msg.Data = data
	}

	if t.debug {
		then := time.Now().Nanosecond()
		fmt.Printf("document transformed in %dus.  %d to marshal, %d in the vm, %d to unmarshal\n", (then-now)/1000, (beforeVM-now)/1000, (afterVM-beforeVM)/1000, (then-afterVM)/1000)
	}

	return msg, nil
}