React/Rails Authentication: Client to API Communication

class ApplicationController < ActionController::Base
skip_before_action :verify_authenticity_token
before_action :set_current_user
def set_current_user
if session[:user_id]
@current_user = User.find(session[:user_id]
end
end
end
class SessionsController < ApplicationController def create
user = User.find_by(username: params[:username])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
render json: {
logged_in: true,
user: @current_user
}
else
render json: {
logged_in: false,
error: 'Invalid username/password combination'
}
end
def destroy
session.clear
render json: { logged_in: false }
end
def logged_in
if @current_user
render json: { logged_in: true, user: @current_user }
else
render json: { logged_in: false }
end
end
end
Rails.application.routes.draw do
post "/login", to: "sessions#create"
get "/logged_in", to: "sessions#logged_in"
get "/logout", to: "sessions#destroy"
end
import React from 'react';const Dashboard = props => {
return(
<div>
<h1>Dashboard</h1>
<button type="submit" onClick={props.logout}>Log Out</button>
</div>
)
}
export default Dashboard;
import React { Component } from "react";
import './App.css';
import Home from './Home.js';
import { BrowserRouter, Switch } from 'react-router-dom';
import axios from 'axios';
export default class App extends Component {
state = {
currentUser: undefined
}
render() {
return(
<div className="App">
<BrowserRouter>
<Switch>
<Route exact path={'/'}
render={props =>
<Home {...props}
handleLogin={this.handleLogin}
/>}
/>
<Route exact path={'/dashboard'}
render={props =>
<Dashboard {...props}
currentUser={this.state.currentUser}
/>}
/>
</Switch>
</BrowserRouter>
</div>
)
}
}
handleLogin = data => { 
axios.post('http://localhost:5000/login',
{
username: data.username,
password: data.password
},
{ withCredentials: true }
)
.then(response => {
this.setState({
currentUser: response.data
})
}
}
{ user: { username: 'ctd', password: 'ENCRYPTED_SALTED_KEY' },  
logged_in: true
}
handleSubmit = event => {
event.preventDefault();
this.props.login(this.state);
this.setState({
username: '',
password: ''
})
}
handleLogout = () => {
axios.get('http://localhost:5000/logout', { withCredentials: true})
.then(response => this.setState({ currentUser: undefined}))
}
<Route exact path={'/dashboard'}
render={props =>
<Dashboard {...props}
currentUser={this.state.currentUser}
logout={this.handleLogout}
/>}
/>

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

State Management with MobX State Tree

Experience of DataHub PathWay`s

The myth of AngularJS migration: Moving from JS to Angular 11 is going to feel like replatforming…

What are the lists of available write/save modes in Spark with examples?

Connecting the JavaScript to the Server Code

Generate pdf from dom with multiple pages and without cutting

Understanding React’s useMemo hook through a simple example

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Cody Dupuis

Cody Dupuis

More from Medium

Why should you use Devise gem for Rails authentication?

WHAT IS RESTFUL API

Introduction of NodeJS, KoaJS, and Restful services

**Secure Password Hashing**