Exemple #1
0
// ParseSend does the same thing with Parse but responses the http request
// with a formatted json error mesages for invalids fields and returns a bool
// according to any invalid fields found or not
func ParseSend(w http.ResponseWriter, r *http.Request, out interface{}) (invalid bool) {
	invalids, err := Parse(r, out)

	if err != nil {
		log.Println(err)
		w.WriteHeader(http.StatusInternalServerError)
		return true
	}

	return eres.New(w).SetFields(invalids).WeakSend()
}
Exemple #2
0
func CreateTokenHandler(w http.ResponseWriter, r *http.Request) {
	fields := createTokenForm{}

	if formutils.ParseSend(w, r, &fields) {
		return
	}

	var user model.User

	if err := ctx.M(r).DB("").C("users").Find(bson.M{
		"email": strings.TrimSpace(fields.Email),
	}).One(&user); err != nil {
		if err == mgo.ErrNotFound {
			eres.New(w).SetMessage("bad credentials").Send()
			return
		}

		log.Println(err)
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(fields.Password)); err != nil {
		eres.New(w).SetMessage("bad credentials").Send()
		return
	}

	token := model.NewToken(user.ID, fields.Forever)

	if err := ctx.M(r).DB("").C("tokens").Insert(&token); err != nil {
		log.Println(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	httpres.Json(w, http.StatusCreated, tokenResponse{token.Token})
}
Exemple #3
0
func CreateUserHandler(w http.ResponseWriter, r *http.Request) {
	fields := createUserForm{}

	if formutils.ParseSend(w, r, &fields) {
		return
	}

	hash, err := cryptoutils.Hash(fields.Password, conf.PasswordLevel)
	if err != nil {
		log.Println(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	user := model.User{
		ID:           bson.NewObjectId(),
		Name:         fields.Name,
		Email:        strings.TrimSpace(fields.Email),
		PasswordHash: hash,
		CreatedAt:    time.Now(),
	}

	if err := ctx.M(r).DB("").C("users").Insert(&user); err != nil {
		if mgo.IsDup(err) {
			eres.New(w).AddField("email", "already exists").Send()
			return
		}

		log.Println(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	token := model.NewToken(user.ID, false)

	if err := ctx.M(r).DB("").C("tokens").Insert(&token); err != nil {
		log.Println(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	rp := userResponse{
		User:        user,
		AccessToken: token.Token,
	}

	httpres.Json(w, http.StatusCreated, rp)
}