Skip to content

Commit

Permalink
Add login mechanism for react native
Browse files Browse the repository at this point in the history
  • Loading branch information
tpaulshippy committed Feb 8, 2024
1 parent 4e6a6f3 commit 2bf767f
Show file tree
Hide file tree
Showing 6 changed files with 139 additions and 10 deletions.
18 changes: 18 additions & 0 deletions app/controllers/sessions_controller.rb
@@ -0,0 +1,18 @@
class SessionsController < ApplicationController
skip_before_action :authenticate_user!
skip_before_action :verify_authenticity_token

respond_to :json
def create
resource = User.find_by_email(params[:login])
return head :unauthorized unless resource

if resource.valid_password?(params[:password])
sign_in("user", resource)
render json: { success: true }
return
end
return head :unauthorized
end

end
2 changes: 2 additions & 0 deletions config/routes.rb
Expand Up @@ -16,4 +16,6 @@
root "counters#index"
end
end

post "sessions/create" => "sessions#create"
end
16 changes: 14 additions & 2 deletions counting-rn/App.js
@@ -1,13 +1,25 @@
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import CountersList from './components/CountersList';
import Login from './Login';
import { useEffect, useState } from 'react';
import { getCookie } from './client';

export default function App() {
const [view, setView] = useState('login');
const showCounters = () => {
setView('counters');
};
useEffect(() => {
if (getCookie() !== '') {
showCounters();
}
});
return (
<View style={styles.container}>
<Text style={styles.title}>Counters</Text>
<StatusBar style="auto" />
<CountersList />
{view === 'counters' ? <CountersList /> : <Login onLogin={showCounters} />}
</View>
);
}
Expand All @@ -23,6 +35,6 @@ const styles = StyleSheet.create({
flex: 1,
backgroundColor: '#000',
alignItems: 'left',
justifyContent: 'center',
justifyContent: 'center',
},
});
70 changes: 70 additions & 0 deletions counting-rn/Login.js
@@ -0,0 +1,70 @@
import { StyleSheet, Text, View, TextInput, Button } from 'react-native';
import React, { useState } from 'react';
import { fetchData, setCookie } from './client';

export default function Login({ onLogin }) {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');

const handleLogin = () => {
fetchData('/sessions/create', 'POST', { login: username, password }).then((response) => {
if (response.error) {
console.error(response.error);
}
else if (response.status === 200) {
console.log('Logged in');
// hold the cookie for future requests
cookie = response.headers.map['set-cookie'];
setCookie(cookie);
onLogin();
}
else if (response.status === 401) {
console.error('Login failed');
}
});

};

return (
<View style={styles.container}>
<TextInput
style={styles.input}
placeholder="Username"
placeholderTextColor={'#aaa'}
value={username}
onChangeText={setUsername}
/>
<TextInput
style={styles.input}
placeholder="Password"
placeholderTextColor={'#aaa'}
secureTextEntry
value={password}
onChangeText={setPassword}
/>
<Button title="Login" onPress={handleLogin} />
</View>
);
}

const styles = StyleSheet.create({
title: {
fontSize: 48,
fontWeight: 'bold',
padding: 20,
color: '#fff',
},
container: {
flex: 1,
backgroundColor: '#000',

alignItems: 'stretch',
justifyContent: 'top',
},
input: {
height: 40,
margin: 12,
borderWidth: 1,
color: '#fff',
},
});
33 changes: 29 additions & 4 deletions counting-rn/client.js
@@ -1,6 +1,31 @@
const baseUrl = 'http://192.168.1.176:3000';
let cookie = '';

export const fetchData = () => {
return fetch('http://192.168.1.176:3000/counters.json')
.then(response => response.json())
export const fetchData = (endpoint, method, data) => {
const headers = {
'Content-Type': 'application/json',
'Accept': 'application/json'
};
if (cookie) {
headers['Cookie'] = cookie;
}
const options = {
method: method,
headers: headers
};
if (method === 'POST' || method === 'PUT') {
options.body = JSON.stringify(data);
}
console.log(options)
return fetch(`${baseUrl}${endpoint}`, options)
.then(response => response)
.catch(error => console.error('Error:', error));
};
};

export const setCookie = (c) => {
cookie = c;
}

export const getCookie = () => {
return cookie;
}
10 changes: 6 additions & 4 deletions counting-rn/components/CountersList.js
Expand Up @@ -10,17 +10,19 @@ export default function CountersList() {

const onRefresh = async () => {
setRefreshing(true);
const data = await fetchData();
const response = await fetchData("/counters.json", "GET");
const data = await response.json();
setCounters(data);
setRefreshing(false);
};

useEffect(() => {
async function init() {
const data = await fetchData();
if (data.error)
console.error(data.error);
const response = await fetchData("/counters.json", "GET");
if (response.error)
console.error(response.error);
else {
const data = await response.json();
setCounters(data);
}

Expand Down

0 comments on commit 2bf767f

Please sign in to comment.