Login token is retrieved but not stored.

This commit is contained in:
Patrick Fic
2019-12-05 19:32:51 -08:00
parent 19e76d0fe5
commit d2f684f4ed
5 changed files with 130 additions and 83 deletions

View File

@@ -2,7 +2,7 @@ import React from "react";
import "./App.css"; import "./App.css";
import { auth, createUserProfileDocument } from "../firebase/firebase.utils"; import { auth, createUserProfileDocument } from "../firebase/firebase.utils";
import { gql } from "apollo-boost"; // import { gql } from "apollo-boost";
import firebase from "../firebase/firebase.utils" import firebase from "../firebase/firebase.utils"
@@ -27,16 +27,15 @@ class App extends React.Component {
componentDidMount() { componentDidMount() {
const { setCurrentUser } = this.props; const { setCurrentUser } = this.props;
this.unsubscribeFromAuth = auth.onAuthStateChanged(async userAuth => { this.unsubscribeFromAuth = auth.onAuthStateChanged(async userAuth => {
console.log("userAuth", userAuth);
if (userAuth) { if (userAuth) {
const token = await userAuth.getIdToken(); const token = await userAuth.getIdToken();
console.log("token", token); console.log("User auth token", token);
const idTokenResult = await userAuth.getIdTokenResult(); const idTokenResult = await userAuth.getIdTokenResult();
const hasuraClaim = const hasuraClaim =
idTokenResult.claims["https://hasura.io/jwt/claims"]; idTokenResult.claims["https://hasura.io/jwt/claims"];
if (hasuraClaim) { if (hasuraClaim) {
console.log("status should be in"); console.log("status should be in1", hasuraClaim);
//setAuthState({ status: "in", user, token }); //setAuthState({ status: "in", user, token });
} else { } else {
// Check if refresh is required. // Check if refresh is required.
@@ -48,10 +47,11 @@ class App extends React.Component {
// Force refresh to pick up the latest custom claims changes. // Force refresh to pick up the latest custom claims changes.
const token = await userAuth.getIdToken(true); const token = await userAuth.getIdToken(true);
//setAuthState({ status: "in", user, token }); //setAuthState({ status: "in", user, token });
console.log("status should be in"); console.log("status should be in2");
}); });
} }
} else { } else {
console.log("else statement.")
//setAuthState({ status: "out" }); //setAuthState({ status: "out" });
} }

View File

@@ -1,76 +1,77 @@
import React from "react"; import React from "react";
import { auth } from "../../firebase/firebase.utils";
import FormInput from "../form-input/form-input.component"; import { Form, Icon, Input, Button, Alert } from "antd";
import CustomButton from "../custom-button/custom-button.component";
import { auth, signInWithGoogle } from "../../firebase/firebase.utils";
//Styling imports
import { Typography } from "antd";
import { Input } from "antd";
import { Button } from "antd";
class SignIn extends React.Component { class SignIn extends React.Component {
constructor(props) { constructor() {
super(props); super();
this.state = { this.state = {
email: "", errorMessage: null
password: ""
}; };
} }
handleSubmit = async event => { handleSubmit = e => {
event.preventDefault(); e.preventDefault();
this.props.form.validateFields(async (err, values) => {
const { email, password } = this.state; if (!err) {
const { email, password } = values;
try { try {
await auth.signInWithEmailAndPassword(email, password); await auth.signInWithEmailAndPassword(email, password);
this.setState({ email: "", password: "" }); this.props.form.resetFields();
} catch (error) { } catch (error) {
console.log(error); this.setState({ ...this.state, errorMessage: error.message });
} }
}; }
});
handleChange = event => {
const { value, name } = event.target;
this.setState({ [name]: value });
}; };
render() { render() {
const { getFieldDecorator } = this.props.form;
const { errorMessage } = this.state;
return ( return (
<div className="sign-in"> <Form onSubmit={this.handleSubmit} className="login-form">
<Typography.Title>Sign In</Typography.Title> <Form.Item label="E-mail">
<form onSubmit={this.handleSubmit}> {getFieldDecorator("email", {
<Input rules: [
placeholder="Email" {
name="Email" type: "email",
type="email" message: "Please enter a valid email."
handleChange={this.handleChange} },
value={this.state.email} {
label="email" required: true,
required message: "Please your email."
/> }
<Input.Password ]
name="password" })(<Input />)}
type="password" </Form.Item>
value={this.state.password} <Form.Item>
handleChange={this.handleChange} {getFieldDecorator("password", {
label="password" rules: [{ required: true, message: "Please enter your password." }]
required })(
/> <Input
<div className="buttons"> prefix={<Icon type="lock" style={{ color: "rgba(0,0,0,.25)" }} />}
<Button type="submit"> Sign in </Button> type="password"
<Button onClick={signInWithGoogle}> placeholder="Password"
Sign in with Google />
</Button> )}
</div> </Form.Item>
</form> <Form.Item>
</div> <div className="login-form-forgot">Forgot password</div>
<Button
type="primary"
htmlType="submit"
className="login-form-button"
>
Log in
</Button>
</Form.Item>
{errorMessage ? (
<Alert message={errorMessage} type="error" />
) : (
null
)}
</Form>
); );
} }
} }
export default Form.create({ name: "sign_in" })(SignIn);
export default SignIn;

View File

@@ -16,6 +16,7 @@ const config = {
firebase.initializeApp(config); firebase.initializeApp(config);
export const createUserProfileDocument = async (userAuth, additionalData) => { export const createUserProfileDocument = async (userAuth, additionalData) => {
//Needs to be redone to write to GQL database.
console.log("userAuth from firebase Utils", userAuth); console.log("userAuth from firebase Utils", userAuth);
if (!userAuth) return; if (!userAuth) return;

View File

@@ -29,7 +29,10 @@ const client = new ApolloClient({
client.writeData({ client.writeData({
data: { data: {
currentUser: null currentSelectedNavItem: null,
currentUser: null,
authState: null,
gqlToken: null
} }
}); });

View File

@@ -5,31 +5,73 @@
// response.send("Hello from Firebase!"); // response.send("Hello from Firebase!");
// }); // });
const functions = require("firebase-functions"); // const functions = require("firebase-functions");
const admin = require("firebase-admin"); // const admin = require("firebase-admin");
// admin.initializeApp(functions.config().firebase);
// // On sign up.
// exports.processSignUp = functions.auth.user().onCreate(user => {
// const customClaims = {
// "https://hasura.io/jwt/claims": {
// "x-hasura-default-role": "user",
// "x-hasura-allowed-roles": ["user"],
// "x-hasura-user-id": user.uid
// }
// };
// return admin
// .auth()
// .setCustomUserClaims(user.uid, customClaims)
// .then(() => {
// // Update real-time database to notify client to force refresh.
// const metadataRef = admin.database().ref("metadata/" + user.uid);
// // Set the refresh time to the current UTC timestamp.
// // This will be captured on the client to force a token refresh.
// return metadataRef.set({ refreshTime: new Date().getTime() });
// })
// .catch(error => {
// console.log(error);
// });
// });
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase); admin.initializeApp(functions.config().firebase);
// On sign up. // On sign up.
exports.processSignUp = functions.auth.user().onCreate(user => { exports.processSignUp = functions.auth.user().onCreate(user => {
const customClaims = { console.log(user);
"https://hasura.io/jwt/claims": { // Check if user meets role criteria:
"x-hasura-default-role": "user", // Your custom logic here: to decide what roles and other `x-hasura-*` should the user get
"x-hasura-allowed-roles": ["user"], let customClaims;
"x-hasura-user-id": user.uid if (user.email && user.email.indexOf('@thinkimex.com') !== -1) {
} customClaims = {
}; 'https://hasura.io/jwt/claims': {
'x-hasura-default-role': 'admin',
return admin 'x-hasura-allowed-roles': ['user', 'admin'],
.auth() 'x-hasura-user-id': user.uid
.setCustomUserClaims(user.uid, customClaims) }
};
}
else {
customClaims = {
'https://hasura.io/jwt/claims': {
'x-hasura-default-role': 'user',
'x-hasura-allowed-roles': ['user'],
'x-hasura-user-id': user.uid
}
};
}
// Set custom user claims on this newly created user.
return admin.auth().setCustomUserClaims(user.uid, customClaims)
.then(() => { .then(() => {
// Update real-time database to notify client to force refresh. // Update real-time database to notify client to force refresh.
const metadataRef = admin.database().ref("metadata/" + user.uid); const metadataRef = admin.database().ref("metadata/" + user.uid);
// Set the refresh time to the current UTC timestamp. // Set the refresh time to the current UTC timestamp.
// This will be captured on the client to force a token refresh. // This will be captured on the client to force a token refresh.
return metadataRef.set({ refreshTime: new Date().getTime() }); return metadataRef.set({refreshTime: new Date().getTime()});
}) })
.catch(error => { .catch(error => {
console.log(error); console.log(error);
}); });
}); });