コード例 #1
0
ファイル: users.go プロジェクト: GEDUtech/ridesyncer_server
func (this *Users) Login(res http.ResponseWriter, req *http.Request, render render.Render) {
	var data struct{ Username, Password string }

	if decode(req, render, &data) != nil {
		return
	}

	user, err := models.GetUserByUsername(this.db, data.Username)
	if err != nil {
		switch err {
		case gorm.RecordNotFound:
			utils.HttpError(res, http.StatusUnauthorized)
		default:
			utils.HttpError(res, http.StatusInternalServerError)
		}
		return
	}

	if auth.NewBcryptHasher().Check(user.Password, data.Password) != nil {
		utils.HttpError(res, http.StatusUnauthorized)
		return
	}

	token, err := models.GenerateApiToken(this.db)
	if err != nil {
		utils.HttpError(res, http.StatusInternalServerError)
		return
	}

	user.Token = token
	if this.db.Model(user).UpdateColumn("token", token).Error != nil {
		utils.HttpError(res, http.StatusInternalServerError)
		return
	}

	user.Password = ""

	if user.FetchSchedules(this.db) != nil {
		utils.HttpError(res, http.StatusInternalServerError)
		return
	}

	if user.FetchSyncs(this.db) != nil {
		utils.HttpError(res, http.StatusInternalServerError)
		return
	}

	render.JSON(http.StatusOK, user)
}
コード例 #2
0
ファイル: users.go プロジェクト: GEDUtech/ridesyncer_server
func (this *Users) Register(res http.ResponseWriter, req *http.Request, render render.Render) {
	var user models.RegisterUser
	if decode(req, render, &user) != nil {
		return
	}

	errors := models.NewErrors()
	if err := user.Validate(this.db, errors); err != nil {
		utils.HttpError(res, http.StatusInternalServerError)
		return
	}

	if errors.Count() > 0 {
		render.JSON(http.StatusBadRequest, map[string]*models.Errors{"errors": errors})
		return
	}

	if err := user.Geocode(); err != nil {
		utils.HttpError(res, http.StatusInternalServerError)
		return
	}

	if err := user.Register(this.db); err != nil {
		utils.HttpError(res, http.StatusInternalServerError)
		return
	}

	token, err := models.GenerateApiToken(this.db)
	if err != nil {
		utils.HttpError(res, http.StatusInternalServerError)
		return
	}

	user.Token = token
	if this.db.Model(user.User).UpdateColumn("token", token).Error != nil {
		utils.HttpError(res, http.StatusInternalServerError)
		return
	}

	user.Password = ""
	render.JSON(http.StatusOK, user)

	go this.sendVerificationCode(user.User)
}