簡體   English   中英

在 Rails 上的 Ruby 中帶有 devise_token_auth 的“不允許的參數::用戶,:會話”

[英]"Unpermitted parameters: :user, :session" with devise_token_auth in Ruby on Rails

我在 Rails 上使用 React 和 Ruby 創建了一個應用程序。

我想用devise_token_auth注冊應用程序。 但是當我在 React 中使用 devise 時,我在 docker-compose 中看到了這個:

ruby_1      |   ↳ /usr/local/bundle/gems/activerecord-5.2.5/lib/active_record/log_subscriber.rb:98
ruby_1      | Processing by DeviseTokenAuth::RegistrationsController#create as HTML
ruby_1      |   Parameters: {"user"=>{"name"=>"KAITO", "email"=>"kaito24262426@gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "registration"=>{"user"=>{"name"=>"KAITO", "email"=>"kaito24262426@gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}}}
ruby_1      | Unpermitted parameters: :user, :registration
ruby_1      | Filter chain halted as :validate_sign_up_params rendered or redirected
ruby_1      | Completed 422 Unprocessable Entity in 1740ms (Views: 0.3ms | ActiveRecord: 0.0ms)
ruby_1      |

或者


ruby_1      | Started POST "/api/v1/auth/sign_in" for 172.20.0.1 at 2021-05-16 16:10:58 +0900
ruby_1      | Processing by DeviseTokenAuth::SessionsController#create as HTML
ruby_1      | Parameters: {"user"=>{"email"=>"kaito24262426@gmail.com"}, "session"=>{"user"=>{"email"=>"kaito24262426@gmail.com"}}}
ruby_1      | Unpermitted parameters: :user, :session
ruby_1      | Completed 401 Unauthorized in 3ms (Views: 0.3ms | ActiveRecord: 0.0ms)

但是當我使用 curl 時,我可以成功

curl localhost:8000/api/v1/auth -X POST \
-d '{"email":"example@example.comm", "password":"password", "password_confirmation": "password", "name": "name"}' \
-H "content-type:application/json" 

{"status":"success", "data":{"id":9,"provider":"email","uid":"example@example.comm","allow_password_change":false,"name":null,"nickname":null,"image":null,"email":"example@example.comm","created_at":"2021-05-16T06:43:00.574Z","updated_at":"2021-05-16T06:43:00.836Z"}}

我可以解析為“Unpermitted parameters:” “name” or “email” or “password” 等等。 但在這種情況下,像“Unpermitted parameters::user:register”這樣的情況,我無法查找要解決的問題

應用程序/控制器/application_controller.rb

class ApplicationController < ActionController::API
  include DeviseTokenAuth::Concerns::SetUserByToken
  before_action :authenticate_user!, if: :devise_controller?, except: [:new, :create]
  skip_before_action :verify_authenticity_token, if: :devise_controller?, raise: false
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:user, :registration, :name, :email, :password, :password_confirmation])
  end
end

配置/路由.rb

Rails.application.routes.draw do
  # devise_for :users
  namespace :api do
    namespace :v1 do
      mount_devise_token_auth_for 'User', at: 'auth'
      resources :works
      resources :contents do
        resources :articles, only: %i[index]
      end
    end
  end
end

signUp.js (這是使用 axios 的 React 文件)

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import axios from 'axios';
import { Button, Form, FormGroup, Input, FormFeedback, Spinner } from 'reactstrap';
import { withRouter } from 'react-router-dom'
import { Formik } from 'formik';
import * as Yup from 'yup';
import "./Sign.css";

class SignUp extends Component {
  static propTypes = {
    show: PropTypes.bool, 
    setShow: PropTypes.func,
    anotherSetShow: PropTypes.func,
  };

  state = {
    loading: false,
  }

  _isMounted = false;

  handleOnSubmit = (values) => {
    if (this._isMounted) this.setState({ loading: true })
    axios.post("http://localhost:8000/api/v1/auth",
      {
        user: {
          name: values.name,
          email: values.email,
          password: values.password,
          password_confirmation: values.password_confirmation,
        }
      },
    )
    .then(res => {
      if (this._isMounted) this.setState({ loading: false });
      this.props.history.push("/works");
    })
    .catch(error => {
      console.log(error.response)
      if (this._isMounted) this.setState({ loading: false });
    });
  }

  componentDidMount = () => {
    this._isMounted = true;
  }

  componentWillUnmount = () => {
    this._isMounted = false;
  }

  openSignup = () => {
    this.props.setShow(false)
    this.props.anotherSetShow(true)
  }

  render() {
      return (
        <div className="container">
          <div className="text-right"><div className="batsu" onClick={() => this.props.setShow(false)}>✖︎</div></div>
          <h5><strong className="text-muted">アカウントを作成</strong></h5>
          <p><small className="text-muted">
            アカウントを作成することにより、利用規約 および プライバシポリシーに同意するものとします。<br />
            ユーザー名はランキングに表示されます。(設定で編集や非表示が可能です)
          </small></p>
          <div className="mx-auto" style={{ padding: 5, marginTop: 10 }}>
            <Formik
              initialValues={{ name: '', email: '', password: '', password_confirmation: '' }}
              onSubmit={(values) => this.handleOnSubmit(values)}
              validationSchema={Yup.object().shape({
                name: Yup.string(),
                email: Yup.string().email().required(),
                password: Yup.string().required(),
                password_confirmation: Yup.string().required(),
              })}
            >
              {
                ({ handleSubmit, handleChange, handleBlur, values, errors, touched }) => (
                  <Form onSubmit={handleSubmit}>
                    <FormGroup>
                      <Input
                        className="input"
                        type="text"
                        name="name"
                        id="name"
                        value={values.name}
                        placeholder="ユーザー名"
                        onChange={handleChange}
                        onBlur={handleBlur}
                        invalid={touched.name && errors.name ? true : false}
                      />
                      <FormFeedback>
                        {errors.name}
                      </FormFeedback>
                    </FormGroup>
                    <FormGroup>
                      <Input
                        className="input"
                        type="email"
                        name="email"
                        id="email"
                        value={values.email}
                        placeholder="メールアドレス"
                        onChange={handleChange}
                        onBlur={handleBlur}
                        invalid={touched.email && errors.email ? true : false}
                      />
                      <FormFeedback>
                        {errors.email}
                      </FormFeedback>
                    </FormGroup>
                    <FormGroup>
                      <Input
                        className="input"
                        type="password"
                        name="password"
                        id="password"
                        value={values.password}
                        placeholder="パスワード"
                        onChange={handleChange}
                        onBlur={handleBlur}
                        invalid={touched.password && errors.password ? true : false}
                      />
                      <FormFeedback>
                        {errors.password}
                      </FormFeedback>
                    </FormGroup>
                    <FormGroup>
                      <Input
                        className="input"
                        type="password"
                        name="password_confirmation"
                        id="password_confirmation"
                        value={values.password_confirmation}
                        placeholder="パスワード(確認)"
                        onChange={handleChange}
                        onBlur={handleBlur}
                        invalid={touched.password_confirmation && errors.password_confirmation ? true : false}
                      />
                      <FormFeedback>
                        {errors.password_confirmation}
                      </FormFeedback>
                    </FormGroup>
                    <div style={{ textAlign: 'center' }}>
                      <Button className="mx-auto" color="info" type="submit" style={{ width: 400, minWidth: 270, padding: 10}} disabled={this.state.loading}>
                        <Spinner className="font-weight-bold mr-2" size="sm" color="light" hidden={!this.state.loading} />
                        新規登録
                      </Button>
                    </div>
                  </Form>
                )
              }
            </Formik>
          </div>
          <div className="text-muted">すでにアカウントをお持ちですか?<div style={{ color: "#0000ff", cursor: 'pointer'}} onClick={() => this.openSignup(true)}>ログイン</div></div>
        </div>
      );
  }
}

export default withRouter(SignUp);

似乎問題就在這里。

 def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:user, :registration, :name, :email, :password, :password_confirmation])
  end

將其更改為

 def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:name, :email, :password, :password_confirmation])
  end

handleOnSubmit

 handleOnSubmit = (values) => {
    if (this._isMounted) this.setState({ loading: true })
    axios.post("http://localhost:8000/api/v1/auth",
      {
          name: values.name,
          email: values.email,
          password: values.password,
          password_confirmation: values.password_confirmation,
        
      },
    )
    .then(res => {
      if (this._isMounted) this.setState({ loading: false });
      this.props.history.push("/works");
    })
    .catch(error => {
      console.log(error.response)
      if (this._isMounted) this.setState({ loading: false });
    });
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM