示例#1
1
文件: friends.go 项目: cedmundo/hablo
// Update inserts a new friendship in database
func Update(c *echo.Context) (int, interface{}) {
	digitsID, ok := c.Get("digitsID").(int64)
	if !ok {
		return msg.Forbidden("session required")
	}

	friendID, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		return msg.BadRequest(err)
	}

	// Bind body request to friend
	var friend models.FriendUpdate
	err = c.Bind(&friend)
	if err != nil {
		return msg.BadRequest(err)
	}

	// Validate input
	err = validator.Validate(friend)
	if err != nil {
		return msg.BadRequest(err)
	}

	// Insert into database
	err = mangos.Update(constants.CFriends, bson.M{"friend_id": int64(friendID), "digits_id": digitsID}, friend)
	if err != nil {
		return msg.InternalError(err)
	}

	return msg.Ok(friend)
}
示例#2
0
文件: app.go 项目: arbrix/go-test
//login provide JWT in response if login success.
func (a *App) login(c *echo.Context) error {
	loginData := &model.LoginJSON{}
	err := c.Bind(loginData)
	log.Printf("login:%s; passwd:%s\n", loginData.Email, loginData.Password)
	if err != nil {
		c.JSON(http.StatusBadRequest, err)
		return err
	}
	if loginData.Email == "" {
		err = errors.New("email could't be empty.")
		c.JSON(http.StatusNotFound, err)
		return err
	}
	if loginData.Password == "" {
		err = errors.New("password could't be empty.")
		c.JSON(http.StatusNotFound, err)
		return err
	}
	user := &model.User{}
	user.Email, user.Password = loginData.Email, loginData.Password
	status, err := user.CheckPass(a.GetDB())
	if err != nil {
		c.JSON(status, err)
		return err
	}
	tokenizer := jwt.NewTokenizer(a)
	status, err = tokenizer.Create(c, user)
	if err != nil {
		c.JSON(status, err)
		return err
	}
	return a.sendJWT(c)
}
示例#3
0
func (r *UserResource) Create(c echo.Context) error {
	input := struct {
		Username string `json:"username"`
		Password string `json:"password"`
	}{}

	if err := c.Bind(&input); err != nil {
		return BadRequest(c, "Payload must be a valid JSON object")
	}

	if input.Username == "" {
		return Invalid(c, "Username is required")
	}

	if input.Password == "" {
		return Invalid(c, "Password is required")
	}

	user := &models.User{
		Username: input.Username,
		Password: input.Password,
	}

	if err := r.store.CreateUser(user); err != nil {
		return InternalServerError(c, err)
	}

	return Created(c, user)
}
示例#4
0
func (r *FeatureResource) Create(c echo.Context) error {
	input := struct {
		Name string `json:"name"`
	}{}

	if err := c.Bind(&input); err != nil {
		return BadRequest(c, "Payload must be a valid JSON object")
	}

	if input.Name == "" {
		return Invalid(c, "Name is required")
	}

	found, err := r.store.GetFeatureByName(input.Name)
	if err != nil && err != store.ErrNoRows {
		return InternalServerError(c, err)
	}

	if found != nil {
		return Conflict(c, "Feature already exists")
	}

	feature := &models.Feature{
		Name: input.Name,
	}

	if err := r.store.CreateFeature(feature); err != nil {
		return InternalServerError(c, err)
	}

	return OK(c, feature)
}
示例#5
0
文件: friends.go 项目: cedmundo/hablo
// Create inserts a new friendship in database
func Create(c *echo.Context) (int, interface{}) {
	digitsID, ok := c.Get("digitsID").(int64)
	if !ok {
		return msg.Forbidden("session required")
	}

	// Bind body request to friend
	var friend models.Friend
	err := c.Bind(&friend)
	if err != nil {
		return msg.BadRequest(err)
	}

	// Validate input
	err = validator.Validate(friend)
	if err != nil {
		return msg.BadRequest(err)
	}

	// Set internal fields
	friend.ID = bson.NewObjectId()
	friend.DigitsID = digitsID
	friend.CreatedAt = time.Now()

	// Insert into database
	err = mangos.Insert(constants.CFriends, friend)
	if err != nil {
		return msg.InternalError(err)
	}

	return msg.Ok(friend)
}
示例#6
0
// http DELETE localhost:5025/admin/remove-users userIds:='["56bf19d65a1d18b704000001", "56be731d5a1d18accd000001"]' X-Diskette-Session-Token:<session_token>
func (service *serviceImpl) RemoveUsers(c echo.Context) error {
	var request struct {
		UserIds []string `json:"userIds"`
	}
	c.Bind(&request)

	if request.UserIds == nil {
		return c.JSON(http.StatusBadRequest, util.CreateErrResponse(errors.New("Missing parameter 'userIds'")))
	}

	objectIds := []bson.ObjectId{}
	for _, userId := range request.UserIds {
		objectIds = append(objectIds, bson.ObjectIdHex(userId))
	}

	info, err := service.userCollection.RemoveAll(bson.M{
		"_id": bson.M{
			"$in": objectIds,
		},
	})
	if err != nil {
		err = errors.New("No such user.")
		c.JSON(http.StatusNotFound, util.CreateErrResponse(err))
		return err
	}

	return c.JSON(http.StatusOK, util.CreateOkResponse(info.Removed))
}
示例#7
0
文件: users.go 项目: mewben/onix
// Login POST /auth/login
func (*UsersController) Login(c echo.Context) error {
	var payload models.LoginPayload
	var user models.User

	an, _, err := net.SplitHostPort(c.Request().RemoteAddress())
	if err != nil {
		return c.JSON(400, utils.ErrMarshal(err.Error()))
	}

	if err = c.Bind(&payload); err != nil {
		return c.JSON(400, utils.ErrMarshal(err.Error()))
	}

	ret, err := user.Login(payload)
	if err != nil {
		msg := err.Error()
		// login failed
		err = utils.ST.Infraction(an, "Login")
		if err != nil {
			msg = msg + " " + err.Error()
			return c.JSON(400, utils.ErrMarshal(msg))
		}

		// auth fails, increment infraction
		_, err = utils.ST.Strikes(an, "Login")

		return c.JSON(400, utils.ErrMarshal(msg))
	}

	return c.JSON(200, ret)
}
示例#8
0
func saveSite(c *echo.Context) error {
	id, iderr := strconv.Atoi(c.Param("id"))
	if iderr != nil {
		return c.String(http.StatusNotAcceptable, "Invalid ID")
	}

	site := new(SiteType)
	if binderr := c.Bind(site); binderr != nil {
		log.Println(binderr.Error())
		return binderr
	}
	log.Println(site)

	_, err := ExecDb(db,
		`update site
			set name=$2,
			    address=$3,
			    phone=$4,
			    contactname=$5
			where id=$1`,
		id,
		site.Name,
		site.Address,
		site.Phone,
		site.ContactName)

	if err != nil {
		log.Println(err.Error())
	}

	return c.JSON(http.StatusOK, site)
}
示例#9
0
func saveEquipType(c *echo.Context) error {
	id, iderr := strconv.Atoi(c.Param("id"))
	if iderr != nil {
		return c.String(http.StatusNotAcceptable, "Invalid ID")
	}

	et := new(EquipType)
	if binderr := c.Bind(et); binderr != nil {
		log.Println(binderr.Error())
		return binderr
	}
	//log.Println(et)

	_, err := ExecDb(db,
		`update equip_type
			set name=$2,
			    is_consumable=$3,
			    is_asset=$4
			where id=$1`,
		id,
		et.Name,
		et.Consumable,
		et.Asset)

	if err != nil {
		log.Println(err.Error())
	}

	return c.JSON(http.StatusOK, et)
}
示例#10
0
文件: auth.go 项目: hobeone/rss2go
// Expects username & password to be passed as JSON in the POST body
// This is how Ember does it.
func (s *APIServer) login(c echo.Context) error {
	a := new(AuthInfo)

	if err := c.Bind(a); err != nil {
		return err
	}

	dbuser, err := s.DBH.GetUserByEmail(a.Username)
	if err == nil {
		//if bcrypt.CompareHashAndPassword([]byte(dbuser.Password), []byte(a.Password)) == nil {
		token := jwt.New(jwt.SigningMethodHS256)

		// Set claims
		claims := token.Claims.(jwt.MapClaims)
		claims["name"] = dbuser.Email
		claims["admin"] = false
		claims["exp"] = time.Now().Add(time.Hour * 72).Unix()

		// Generate encoded token and send it as response.
		t, err := token.SignedString([]byte("secret"))
		if err != nil {
			return err
		}
		return c.JSON(http.StatusOK, map[string]string{
			"token": t,
		})
		//}
	}

	logrus.Infof("Unknown user or bad password for: %s", a.Username)
	return c.String(http.StatusUnauthorized, "Bad username or password")
}
示例#11
0
func login(c *echo.Context) error {
	l := new(loginCreds)
	err := c.Bind(&l)
	if err != nil {
		log.Println("Bind Error:", err.Error())
	}
	//log.Println("Login Credentials", l)

	sqlResult, _ := SQLMap(db,
		`select u.username,u.role,u.site,s.name as sitename
		from users u
			left outer join site s on (s.id=u.site)
		where u.username=$1 and u.passwd=$2`,
		l.Username,
		l.Password)
	log.Println("SQLResult", sqlResult)

	if len(sqlResult) == 1 {
		r := new(loginResponse)
		r.Username = l.Username
		r.Role = sqlResult[0]["role"]
		r.Token = "98023840238402840"
		r.Site = sqlResult[0]["site"]
		r.SiteName = sqlResult[0]["sitename"]
		return c.JSON(http.StatusOK, r)
	} else {
		return c.String(http.StatusUnauthorized, "invalid")
	}
}
示例#12
0
func addBook(c *echo.Context) error {
	var b Book
	b.Author = nil

	err := c.Bind(&b)
	if err != nil {
		log.Fatal(err)
		return err
	}

	if b.Author == nil {
		var m Message
		m.Error = "Author can not be empty."
		c.JSON(203, m)
		return ErrAuthorEmpty
	}

	err = c.JSON(201, b)
	if err != nil {
		log.Fatal(err)
		return err
	}

	fmt.Println("Added ", b.Title)
	saveBook(b)
	return nil
}
示例#13
0
文件: groups.go 项目: cedmundo/hablo
// Create inserts a new group into database
func Create(c *echo.Context) (int, interface{}) {
	digitsID, ok := c.Get("digitsID").(int64)
	if !ok {
		return msg.Forbidden("session required")
	}

	// Bind request body with group
	var group models.Group
	err := c.Bind(&group)

	// Validate group
	err = validator.Validate(group)
	if err != nil {
		return msg.BadRequest(err)
	}

	// Set values
	group.ID = bson.NewObjectId()
	group.Admins = []int64{digitsID}
	group.Creator = digitsID
	group.Members = []int64{digitsID}

	// Create group
	err = mangos.Insert(constants.CGroups, group)
	if err != nil {
		return msg.InternalError(err)
	}

	return msg.Ok(group)
}
示例#14
0
文件: places.go 项目: jtprog/geotrack
// putPlace изменяет определение уже существующего места.
func putPlace(c *echo.Context) error {
	groupID := c.Get("GroupID").(string)
	placeID := c.Query("place-id")
	if !bson.IsObjectIdHex(placeID) {
		return echo.NewHTTPError(http.StatusNotFound)
	}
	var place places.Place // описание места
	err := c.Bind(&place)  // разбираем описание места из запроса
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if place.Circle == nil && place.Polygon == nil {
		return echo.NewHTTPError(http.StatusBadRequest)
	}
	place.ID = bson.ObjectIdHex(placeID)
	place.GroupID = groupID
	_, err = placesDB.Save(place)
	if err == mgo.ErrNotFound {
		return echo.NewHTTPError(http.StatusNotFound)
	}
	if err != nil {
		llog.Error("placesDB error: %v", err)
		return err
	}
	return c.NoContent(http.StatusOK)
}
示例#15
0
文件: http.go 项目: chop-dbhi/scds
func addSubscribersHandler(c echo.Context) error {
	cfg := c.Get("config").(*Config)

	var (
		err    error
		emails []string
	)

	if err = c.Bind(&emails); err != nil {
		return c.JSON(StatusUnprocessableEntity, map[string]interface{}{
			"message": "problem decoding request body",
			"error":   err,
		})
	}

	subs, err := SubscribeEmail(cfg, emails...)

	if err != nil {
		return c.JSON(StatusUnprocessableEntity, map[string]interface{}{
			"message": "problem subscribing emails",
			"error":   err,
		})
	}

	return c.JSON(http.StatusOK, map[string]interface{}{
		"subscribed": len(subs),
	})
}
示例#16
0
// http POST localhost:5025/user/forgot-password [email protected]
func (service *serviceImpl) ForgotPassword(c echo.Context) error {
	var request struct {
		Email string `json:"email"`
	}
	c.Bind(&request)

	if request.Email == "" {
		return c.JSON(http.StatusBadRequest, util.CreateErrResponse(errors.New("Missing parameter 'email'")))
	}

	resetKey := uuid.NewV4().String()

	err := service.userCollection.Update(
		bson.M{"email": request.Email},
		bson.M{
			"$set": bson.M{
				"resetKey":         resetKey,
				"requestedResetAt": time.Now(),
			},
		},
	)
	if err != nil {
		return c.JSON(http.StatusNotFound, util.CreateErrResponse(errors.New("The user doesn't exist.")))
	}

	token := tokens.ResetToken{Key: resetKey}
	tokenStr, err := token.ToString(service.jwtKey)
	if err != nil {
		return c.JSON(http.StatusInternalServerError, util.CreateErrResponse(err))
	}

	return c.JSON(http.StatusOK, util.CreateOkResponse(bson.M{"ResetToken": tokenStr}))
}
示例#17
0
文件: server.go 项目: hobeone/rss2go
func (s *APIServer) getFeeds(c echo.Context) error {
	dbuser := c.Get("dbuser").(*db.User)
	b := new(feedsReqBinder)

	if err := c.Bind(b); err != nil {
		return newError(c, "Unable to parse request", err)
	}

	var feeds []*db.FeedInfo
	var err error
	if b.Name != "" {
		feeds, err = s.DBH.GetUsersFeedsByName(dbuser, b.Name)
	} else {
		feeds, err = s.DBH.GetUsersFeeds(dbuser)
	}
	if err != nil {
		return newError(c, "Unable to get feeds", err)
	}

	feedInterface := make([]interface{}, len(feeds))

	for i, f := range feeds {
		feedInterface[i] = f
	}

	c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
	c.Response().WriteHeader(http.StatusOK)
	return jsonapi.MarshalManyPayload(c.Response(), feedInterface)
}
示例#18
0
func postDevicePairing(c *echo.Context) error {
	groupID := c.Get("GroupID").(string)
	deviceID := c.Param("device-id")
	_, _ = groupID, deviceID
	var pairingKey struct {
		Key string
	}
	err := c.Bind(&pairingKey) // читаем ключ из запроса
	if err != nil || len(pairingKey.Key) < 4 {
		return echo.NewHTTPError(http.StatusBadRequest)
	}
	var deviceIDResp string
	err = nce.Request(serviceNamePairingKey, pairingKey.Key, &deviceIDResp, natsRequestTimeout)
	if err != nil {
		llog.Error("NATS Pairing Key response error: %v", err)
		return err
	}
	if deviceIDResp == "" {
		return echo.NewHTTPError(http.StatusNotFound)
	}
	if deviceIDResp == deviceID {
		// TODO: реально связать в базе
		return echo.NewHTTPError(http.StatusOK)
	}
	if deviceID == "" {
		return c.JSON(http.StatusOK, map[string]string{"ID": deviceIDResp})
	}
	return echo.NewHTTPError(http.StatusBadRequest)
}
示例#19
0
func AuthRegister(c *echo.Context) error {
	var auth AuthParams
	c.Bind(&auth)

	err := utils.Validator.Struct(auth)
	if err != nil {
		return err
	}

	check := fmt.Sprintf("https://api.vk.com/method/users.get?v=5.37&access_token=%s", auth.AccessToken)
	_, body, errs := gorequest.New().Get(check).End()
	if errs != nil {
		return errs[0]
	}
	var resp map[string]*json.RawMessage
	err = json.Unmarshal([]byte(body), &resp)
	if err != nil {
		return err
	}
	if _, ok := resp["response"]; !ok {
		return fmt.Errorf("Data structure is broken")
	}
	var users []VkUserInfo
	err = json.Unmarshal(*resp["response"], &users)
	if err != nil {
		return err
	}
	if users[0].Id != auth.UserId {
		return fmt.Errorf("User id is wrong")
	}
	return c.JSON(http.StatusOK, users[0])
}
示例#20
0
// http POST localhost:5025/session/set-profile?st=<session_token> profile:='{"profession": "Software Developer"}'
func (service *serviceImpl) SetProfile(c echo.Context) error {
	sessionToken := c.Get("sessionToken").(tokens.SessionToken)

	var request struct {
		Profile map[string]interface{} `json:"profile"`
	}
	c.Bind(&request)

	if request.Profile == nil {
		return c.JSON(http.StatusBadRequest, util.CreateErrResponse(errors.New("Missing parameter 'profile'")))
	}

	err := service.userCollection.UpdateId(
		bson.ObjectIdHex(sessionToken.UserId),
		bson.M{
			"$set": bson.M{
				"profile": request.Profile,
			},
		},
	)
	if err != nil {
		return c.JSON(http.StatusInternalServerError, util.CreateErrResponse(err))
	}

	return c.JSON(http.StatusOK, util.CreateOkResponse(nil))
}
示例#21
0
文件: api.go 项目: flike/kingshard
func (s *ApiServer) ChangeMasterStatus(c echo.Context) error {
	args := struct {
		Opt  string `json:"opt"`
		Node string `json:"node"`
		Addr string `json:"addr"`
	}{}

	err := c.Bind(&args)
	if err != nil {
		return err
	}

	args.Opt = strings.ToLower(args.Opt)
	if args.Opt != "up" && args.Opt != "down" {
		return errors.New("opt only can be up or down")
	}
	if args.Opt == "down" {
		err = s.proxy.DownMaster(args.Node, args.Addr)
	} else {
		err = s.proxy.UpMaster(args.Node, args.Addr)
	}
	if err != nil {
		return err
	}
	return c.JSON(http.StatusOK, "ok")
}
示例#22
0
文件: users.go 项目: mewben/onix
// Password Change password of logged user
func (*UsersController) Password(c echo.Context) error {
	type pl struct {
		Oldp string `json:"old_password"`
		Newp string `json:"new_password"`
		Conp string `json:"confirm_password"`
	}

	var payload pl
	var model models.User

	if err := c.Bind(&payload); err != nil {
		return c.JSON(400, utils.ErrMarshal(err.Error()))
	}

	if payload.Newp != payload.Conp {
		return c.JSON(400, utils.ErrMarshal("Password did not match."))
	}

	userID := int(c.Get("userID").(float64))
	ret, err := model.ChangePassword(userID, payload.Oldp, payload.Newp)
	if err != nil {
		return c.JSON(400, utils.ErrMarshal(err.Error()))
	}

	return c.JSON(200, ret)
}
示例#23
0
// http POST localhost:5025/admin/suspend-users userIds:='["56bf19d65a1d18b704000001", "56be731d5a1d18accd000001"]' X-Diskette-Session-Token:<session_token>
func (service *serviceImpl) SuspendUsers(c echo.Context) error {
	var request struct {
		UserIds []string `json:"userIds"`
	}
	c.Bind(&request)

	if request.UserIds == nil {
		return c.JSON(http.StatusBadRequest, util.CreateErrResponse(errors.New("Missing parameter 'userIds'")))
	}

	objectIds := []bson.ObjectId{}
	for _, userId := range request.UserIds {
		objectIds = append(objectIds, bson.ObjectIdHex(userId))
	}

	info, err := service.userCollection.UpdateAll(
		bson.M{
			"_id": bson.M{
				"$in": objectIds,
			},
		},
		bson.M{
			"$set": bson.M{
				"isSuspended": true,
			},
		},
	)

	if err != nil {
		return c.JSON(http.StatusInternalServerError, util.CreateErrResponse(err))
	}

	return c.JSON(http.StatusOK, util.CreateOkResponse(info.Updated))
}
示例#24
0
文件: setup.go 项目: gogrademe/api
// SetupApp allows the creation of a admin account if no accounts exist.
func SetupApp(c echo.Context) error {
	db := ToDB(c)
	accts, err := db.GetAccountList()
	if len(accts) > 0 || err != nil {
		return ErrForbidden.Log(err, fmt.Sprintf("total accounts: %s", len(accts)))
	}

	p := &Setup{}
	if err := c.Bind(p); err != nil {
		return ErrBind.Log(err)
	}

	p.IsAdmin = true
	if err := db.InsertPerson(&p.Person); err != nil {
		return ErrSaving.Log(err)
	}

	u, _ := model.NewAccountFor(p.PersonID, p.Email)
	if err := u.SetPassword(p.Password); err != nil {
		return ErrPasswordSimple.Log(err)
	}

	u.SetActive()

	if err := db.InsertAccount(u); err != nil {
		return ErrSaving.Log(err)
	}

	return c.NoContent(http.StatusCreated)
}
示例#25
0
文件: http.go 项目: chop-dbhi/scds
func putHandler(c echo.Context) error {
	var val map[string]interface{}

	if err := c.Bind(&val); err != nil {
		return err
	}

	cfg := c.Get("config").(*Config)

	key := c.Param("key")
	obj, err := Put(cfg, key, val)

	if err != nil {
		// Failed validation.
		if errs, ok := err.(ResultErrors); ok {
			return c.JSON(StatusUnprocessableEntity, errs)
		}

		return err
	}

	// No change.
	if obj == nil {
		return c.NoContent(http.StatusNoContent)
	}

	return c.JSON(http.StatusOK, obj)
}
示例#26
0
// http POST localhost:5025/user/confirm token=<confirmation_token>
func (service *serviceImpl) ConfirmSignup(c echo.Context) error {
	var request struct {
		Token string `json:"token"`
	}
	c.Bind(&request)

	if request.Token == "" {
		return c.JSON(http.StatusBadRequest, util.CreateErrResponse(errors.New("Missing parameter 'token'")))
	}

	token, err := tokens.ParseConfirmationToken(service.jwtKey, request.Token)
	if err != nil || token.Key == "" {
		return c.JSON(http.StatusForbidden, util.CreateErrResponse(err))
	}

	err = service.userCollection.Update(
		bson.M{"confirmationKey": token.Key},
		bson.M{
			"$set": bson.M{
				"isConfirmed": true,
			},
		},
	)

	if err != nil {
		return c.JSON(http.StatusInternalServerError, util.CreateErrResponse(err))
	}

	return c.JSON(http.StatusOK, util.CreateOkResponse(nil))
}
示例#27
0
文件: groups.go 项目: cedmundo/hablo
// Update patches a group in database
func Update(c *echo.Context) (int, interface{}) {
	digitsID, ok := c.Get("digitsID").(int64)
	if !ok {
		return msg.Forbidden("session required")
	}

	// Bind request body to a group update
	var group models.GroupUpdate
	err := c.Bind(&group)
	if err != nil {
		return msg.BadRequest(err)
	}

	// Get group id and convert from string to objectId
	rawGID := c.Param("gid")
	if !bson.IsObjectIdHex(rawGID) {
		return msg.BadRequest("bad id: not a ObjectId")
	}

	// Update the object, only if its a admin
	groupID := bson.ObjectIdHex(rawGID)
	err = mangos.Update(constants.CGroups, bson.M{
		"$and": []bson.M{
			bson.M{"_id": groupID},
			bson.M{"admins": digitsID},
		},
	}, bson.M{"$set": group})
	if err != nil {
		return msg.InternalError(err)
	}

	return msg.Ok(group)
}
示例#28
0
func (r *EnvironmentResource) Update(c echo.Context) error {
	name := c.Param("name")

	environment, err := r.store.GetEnvironmentByName(name)
	if err != nil {
		if err == store.ErrNoRows {
			return NotFound(c)
		}

		return InternalServerError(c, err)
	}

	input := struct {
		Name string `json:"name"`
	}{}

	if err := c.Bind(&input); err != nil {
		return BadRequest(c, "Payload must be a valid JSON object")
	}

	if input.Name != "" {
		environment.Name = input.Name
	}

	if err := r.store.UpdateEnvironment(environment); err != nil {
		return InternalServerError(c, err)
	}

	return OK(c, environment)
}
示例#29
0
// http POST localhost:5025/user/signup [email protected] password=abc profile:='{"name": "Joe Doe", "language": "en" }'
func (service *serviceImpl) Signup(c echo.Context) error {
	var request struct {
		Email    string                 `json:"email"`
		Password string                 `json:"password"`
		Profile  map[string]interface{} `json:"profile"`
	}
	c.Bind(&request)

	if request.Email == "" {
		return c.JSON(http.StatusBadRequest, util.CreateErrResponse(errors.New("Missing parameter 'email'")))
	}

	if request.Password == "" {
		return c.JSON(http.StatusBadRequest, util.CreateErrResponse(errors.New("Missing parameter 'password'")))
	}

	if request.Profile == nil {
		return c.JSON(http.StatusBadRequest, util.CreateErrResponse(errors.New("Missing parameter 'profile'")))
	}

	count, err := service.userCollection.Find(bson.M{"email": request.Email}).Count()
	if err != nil {
		return c.JSON(http.StatusInternalServerError, util.CreateErrResponse(err))
	}

	if count > 0 {
		return c.JSON(http.StatusConflict, util.CreateErrResponse(errors.New("This email address is already being used.")))
	}

	hashedPass, err := bcrypt.GenerateFromPassword([]byte(request.Password), bcrypt.DefaultCost)
	if err != nil {
		return c.JSON(http.StatusInternalServerError, util.CreateErrResponse(err))
	}

	userDoc := collections.UserDocument{
		Id:          bson.NewObjectId(),
		Email:       request.Email,
		HashedPass:  hashedPass,
		Profile:     request.Profile,
		CreatedAt:   time.Now(),
		IsSuspended: false,
	}

	userDoc.ConfirmationKey = uuid.NewV4().String()

	token := tokens.ConfirmationToken{Key: userDoc.ConfirmationKey}

	tokenStr, err := token.ToString(service.jwtKey)
	if err != nil {
		return c.JSON(http.StatusInternalServerError, util.CreateErrResponse(err))
	}

	err = service.userCollection.Insert(userDoc)
	if err != nil {
		return c.JSON(http.StatusInternalServerError, util.CreateErrResponse(err))
	}

	return c.JSON(http.StatusOK, util.CreateOkResponse(bson.M{"ConfirmationToken": tokenStr}))
}
示例#30
0
func createUser(c *echo.Context) error {
	u := new(user)
	if err := c.Bind(u); err != nil {
		return err
	}
	users[u.ID] = *u
	return c.JSON(http.StatusCreated, u)
}