Next.js应用程序中的React-Apollo身份验证

时间:2018-04-30 19:18:03

标签: graphql react-apollo apollo-client nextjs

我尝试使用React-Apollo和Next.js在应用中设置身份验证。它的设置是在发送凭证后返回包含jwt令牌的cookie,这非常有效。尝试为当前用户运行查询时,它返回null。如果我刷新页面,查询仍然有效,我回到当前用户。我注意到即使响应为空,也会使用正确的数据更新缓存。

组件:

class Index extends Component{
  constructor(props){
    super(props)

    this.usernameInput = ''
    this.passwordInput = ''

    this.state = {
      error: null,
    }
  }

  getCurrentAccount = async () => {
    return await this.props.getCurrentAccount
  }

  sendCreds = async (e) => {
    e.preventDefault()

    const result = await this.props.authenticate({
      variables: {
        username: this.usernameInput,
        password: this.passwordInput,
      },
      update: (store, {data: { currentAccount } } ) => {
        const data = store.readQuery({
          query: QUERY_CURRENT_ACCOUNT,
        })
        console.log('after authenitcation', data)
      }
    })

    if (result.error) {
      console.log('error on authentication', result.error)
      this.setState({error: 'There was an error with our server.'})
    } else if (result) {

      //this.login()
    }
  }

  login = async () => {
    const data = await this.getCurrentAccount()

    if (data.error) {
      console.log('error on fetching account', data.error)
      this.setState({error: 'There was an error with our server.'})
    } else if (data.currentAccount.role) {
      Router.push('/dashboard')
    } else {
      this.setState({error: 'The ID or password you entered is incorrect.'})
    }
  }

  render() {
    return (
        <form onSubmit={this.sendCreds}>
          { this.state.error ? <FormError>{this.state.error}</FormError> : null}
          <fieldset>
            <InputField id="username" label="usrname" placeholder="username" pattern="^[a-zA-Z0-9_]*$" required inputValue={val=>this.usernameInput = val}/>
            <InputField id="password" type="password" label="Password" placeholder="Password" required inputValue={val=>this.passwordInput = val}/>
          </fieldset>
          <ButtonPrimary type="submit" label="Send Credentials" width="full"/>
          <ButtonPrimary label="Get Current User to Login" width="full" clickAction={()=>this.login()}/>
          <footer>
            <Link href="forgot-username">
              <a>Forgot my username</a>
            </Link>
            <Link href="forgot-password">
              <a>Forgot my password</a>
            </Link>
          </footer>
        </form>
  )}
}

GrahpQL:

const MUTATION_AUTH = gql`
  mutation authenticate($username: String!, $password: String!) {
    authenticate(input: {
        username: $username,
        password: $password
    }) {
      jwtToken
    }
  }
`

const QUERY_CURRENT_ACCOUNT = gql`
   {
    currentAccount {
      account {
        firstName
        profileImageUrl
      }
      role
    }
  }
`

export default withData(compose(
  graphql(MUTATION_AUTH, { name: 'authenticate' }),
  graphql(QUERY_CURRENT_ACCOUNT, { name: 'getCurrentAccount'} )
)
(withApollo(Index)))

0 个答案:

没有答案