I have a Sign Up/Sign in/Sign Out issue. I am creating a React/Redux project, and am using Axios for my GET & POST requests. I am newer to Axios and have read through the documentation to no avail.
Here is the issue.
1. I can successfully create a user with Sign Up in a sign up form.
2. I can make a Post request(a couple of strings) with a basic Redux form.
3. The user and post both are persisting in MongoDB, and I am getting token back.
4. When I log out of that new user, and sign back in with that new user, I am able to sign in, but my post shows up as a 401. Intuition and research tell me that this is an issue with the token, but then again, I'm not sure why I'm able to sign in with the newly created user, but not able to make another post. Any help would be greatly appreciate. Here are my Axios methods:
var config = {
headers: { authorization: localStorage.getItem('token') }
}
export function signinUser({ email, password }){
return function(dispatch){
axios.post(`${ROOT_URL}/signin`, {email, password})
.then(response => {
dispatch({ type: AUTH_USER });
localStorage.setItem('token', response.data.token);
browserHistory.push('/newitem');
})
.catch(response => dispatch(authError("There was a something wrong with your request.")));
}
}
export function signoutUser(){
localStorage.removeItem('token');
return {type: UNAUTH_USER};
}
export function signupUser({ email, password }) {
return function(dispatch) {
// Submit email/password to the server
axios.post(`${ROOT_URL}/signup`, { email, password })
.then(response => {
dispatch({type: AUTH_USER});
//update the token
localStorage.setItem('token', response.data.token);
browserHistory.push('/newitem');
})
.catch(response => dispatch(authError(response.data.error)));
}
}
export function createPost(props) {
return function(dispatch){
axios.post(`${ROOT_URL}/newitem`, { props }, config )
.then(request => {
dispatch({
type: CREATE_POSTS,
payload: request
})
browserHistory.push('/items');
});
}
}
Related
So im trying to build my register method without re-enventing nothing crazy with the create-t3-app stack with nextjs, trpc and nextauth:
export const signUpRouter = router({
signup: publicProcedure.input(UserModel).mutation(async ({ ctx, input }) => {
debugger;
try {
const { nickname, email, password } = input;
//check duplicate users
const checkingUsers = await ctx.prisma.user.findFirst({
where: {
email,
},
});
if (checkingUsers) {
return { message: "User already exists..." };
}
//hash password
return await ctx.prisma.user.create({
data: {
nickname,
email,
password: await hash(password, 12),
},
});
} catch (error: any) {
console.log("error", error);
throw new Error(error);
}
}),
});
export default signUpRouter;
This file is inside pages/api/auth/signup.ts
Should I have this on the server part ?
I have the router on my appRouter file
export const appRouter = router({
userLogin: userLoginRouter,
auth: authRouter,
signin: signInRouter,
signup: signUpRouter,
});
And when clicking on the register button:
async function onSumitRegisterValues(values: any) {
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(values),
};
await fetch("http://localhost:3000/api/auth/signup", options)
.then((res) => res.json())
.then((data) => {
if (data?.ok) router.push("http://localhost:3000");
});
}
The values form contains nickname, email, password and cpassword to confirm password.
im getting a 500 on post
Server Error
TypeError: resolver is not a function
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Maybe its my lack of knowledge with trpc and next but ngl, its making me want to separate my backend into something different. But since im not rushing in building this project i really want to try to figure out what i shoud be doing better.
Why are you using fetch instead of using your useQuery method from trpc? The whole point of trpc is that you can skip fetch and will also have type safety.
https://trpc.io/docs/useQuery
I'm using the following interceptors in a Vuejs v2 website to push a firebase token to my node backend. There in the backend, I detect/verify the token, pull some data using the uid from a database and then process any api calls.
Even though I am using the firebase onIdTokenChanged to automatically retrieve new ID tokens, sometimes, if the user is logged in, yet inactive for an hour, the token expires without refreshing. Now, this isn't a huge deal - I could check in the axios response interceptor and push them to a login page, but that seems annoying, if I can detect a 401 token expired, resend the axios call and have a refreshed token, the user won't even know it happened if they happen to interact with a component that requires data from an API call. So here is what I have:
main.js
Vue.prototype.$axios.interceptors.request.use(function (config) {
const token = store.getters.getSessionToken;
config.headers.Authorization = `Bearer ${token}`;
return config;
});
Vue.prototype.$axios.interceptors.response.use((response) => {
return response }, async function (error) {
let originalRequest = error.config
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
let user = auth.currentUser;
await store.dispatch("setUser", {user: user, refresh: true}).then(() => {
const token = store.getters.getSessionToken;
Vue.prototype.$axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
return Vue.prototype.$axios.request(originalRequest);
});
}
return Promise.reject(error); });
let app;
auth.onAuthStateChanged(async user => {
await store.dispatch("setUser", {user: user, refresh: false}).then(() => {
if (!app) {
app = new Vue({
router,
store,
vuetify,
render: h => h(App)
}).$mount('#app')
}
})
.catch(error => {
console.log(error);
});
});
vuex
setUser({dispatch, commit}, {user, refresh}) {
return new Promise((resolve) => {
if(user)
{
user.getIdToken(refresh).then(token => {
commit('SET_SESSION_TOKEN', token);
this._vm.$axios.get('/api/user/session').then((response) => {
if(response.status === 200) {
commit('SET_SESSION_USER', response.data);
resolve(response);
}
})
.catch(error => {
dispatch('logout');
dispatch('setSnackbar', {
color: "error",
timeout: 4000,
text: 'Server unavailable: '+error
});
resolve();
});
})
.catch(error => {
dispatch('logout');
dispatch('setSnackbar', {
color: "error",
timeout: 4000,
text: 'Unable to verify auth token.'+error
});
resolve();
});
}
else
{
console.log('running logout');
commit('SET_SESSION_USER', null);
commit('SET_SESSION_TOKEN', null);
resolve();
}
})
},
I am setting the token in vuex and then using it in the interceptors for all API calls. So the issue I am seeing with this code is, I'm making an API call with an expired token to the backend. This returns a 401 and the axios response interceptor picks it up and goes through the process of refreshing the firebase token. This then makes a new API call with the same config as the original to the backend with the updated token and returns it to the original API call (below).
This all seems to work, and I can see in dev tools/network, the response from the API call is sending back the correct data. However, it seems to be falling into the catch of the following api call/code. I get an "undefined" when trying to load the form field with response.data.server, for example. This page loads everything normally if I refresh the page (again, as it should with the normal token/loading process), so I know there aren't loading issues.
vue component (loads smtp settings into the page)
getSMTPSettings: async function() {
await this.$axios.get('/api/smtp')
.then((response) => {
this.form.server = response.data.server;
this.form.port = response.data.port;
this.form.authemail = response.data.authemail;
this.form.authpassword = response.data.authpassword;
this.form.sendemail = response.data.sendemail;
this.form.testemail = response.data.testemail;
this.form.protocol = response.data.protocol;
})
.catch(error => {
console.log(error);
});
},
I have been looking at this for a few days and I can't figure out why it won't load it. The data seems to be there. Is the timing of what I'm doing causing me issues? It doesn't appear to be a CORS problem, I am not getting any errors there.
Your main issue is mixing async / await with .then(). Your response interceptor isn't returning the next response because you've wrapped that part in then() without returning the outer promise.
Keep things simple with async / await everywhere.
Also, setting common headers defeats the point in using interceptors. You've already got a request interceptor, let it do its job
// wait for this to complete
await store.dispatch("setUser", { user, refresh: true })
// your token is now in the store and can be used by the request interceptor
// re-run the original request
return Vue.prototype.$axios.request(originalRequest)
Your store action also falls into the explicit promise construction antipattern and can be simplified
async setUser({ dispatch, commit }, { user, refresh }) {
if(user) {
try {
const token = await user.getIdToken(refresh);
commit('SET_SESSION_TOKEN', token);
try {
const { data } = await this._vm.$axios.get('/api/user/session');
commit('SET_SESSION_USER', data);
} catch (err) {
dispatch('logout');
dispatch('setSnackbar', {
color: "error",
timeout: 4000,
text: `Server unavailable: ${err.response?.data ?? err.message}`
})
}
} catch (err) {
dispatch('logout');
dispatch('setSnackbar', {
color: "error",
timeout: 4000,
text: `Unable to verify auth token. ${error}`
})
}
} else {
console.log('running logout');
commit('SET_SESSION_USER', null);
commit('SET_SESSION_TOKEN', null);
}
}
Notice: I have seen this question, but creating a whole landing page just to verify a user seems a bit much.
I added a login functionality to my react-native app using firebase/auth with email and password. This works well so far and I have no issues doing that.
I then continued to send a verification email to a new user and only allow him/her to use the app, once the email is verified. Again, no issues here.
The next step would be to login the user right after the email was verified. This is where I'm stuck, since the onAuthStateChanged eventhandler doesn't update after the user pressed the verification link in the email.
Is there any way to listen to the emailVerified state in real-time? I tried to use polling with setInterval() but this is not great since there is a notable delay between verification and login. I read about a continueLink you can pass to sendEmailVerification, but I couldn't figure out how to make that work in react-native.
I'm using Expo and therefore the Firebase SDK, not the Firebase react native package.
Here is the code I use for the signup:
export const signUp = async (username: string, email: string, password: string) => {
try {
const auth = getAuth();
if (email && password && username) {
// sign up
const userCredential = await createUserWithEmailAndPassword(auth, email, password);
// save username in firestore
await setUserName(userCredential, username);
// send Email Verification
await sendEmailVerification(userCredential.user);
return true;
}
} catch (error) {
onError(error);
}
};
And this is my onAuthStateChanged handler:
auth.onAuthStateChanged(authenticatedUser => {
try {
if (authenticatedUser?.emailVerified) {
setUser(authenticatedUser)
} else {
setUser(null)
}
} catch (error) {
console.log(error);
}
});
So in the end I did follow this question, but I changed it a bit to fit my needs. I'll post my steps for anyone who's doing the same.
Create a simple static website with firebase init and host it on firebase or somewhere else (check the hosting tab in your firebase console to get started)
Follow this guide to create the appropriate handlers on the website
Add the following to your verificationHandler to update the user (don't forget to import firestore) (I send the userId via the continueURL, but there are probably better ways)
// You can also use realtime database if you want
firebase.firestore().collection("users").doc(userId).set({
emailVerified: true
}, {merge: true}).then(() => {
message.textContent = "Your email has been verified.";
}).catch((error) => {
message.textContent = "The verification was invalid or is expired. Please try to send another verification email from within the app.";
});
Got to authentication -> templates in your firebase console and change the action url to your hosted website's url
Add a listener to the firestore doc to your react-native app
const onUserDataChanged = (uid, callback) => {
onSnapshot(doc(firestore, "users", uid), doc => callback(doc.data()));
}
Use the data from the callback to update the login state in the app
// As an example
auth.onAuthStateChanged(authenticatedUser => {
if (authenticatedUser && !authenticatedUser.emailVerified) {
unsubscribeFirestoreListener?.();
unsubscribeFirestoreListener = onUserDataChanged(authenticatedUser.uid, (data: any) => {
if (data?.emailVerified) {
setUser(authenticatedUser);
unsubscribeFirestoreListener?.();
}
});
}
}
use the codes below for your authentication context. for user id, you should use 'user.uid'
import React, { useState, createContext } from "react";
import * as firebase from "firebase";
import { loginRequest } from "./authentication.service";
export const AuthenticationContext = createContext();
export const AuthenticationContextProvider = ({ children }) => {
const [isLoading, setIsLoading] = useState(false);
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
firebase.auth().onAuthStateChanged((usr) => {
if (usr) {
setUser(usr);
setIsLoading(false);
} else {
setIsLoading(false);
}
});
const onLogin = (email, password) => {
setIsLoading(true);
firebase.auth().signInWithEmailAndPassword(email, password)
.then((u) => {
setUser(u);
setIsLoading(false);
})
.catch((e) => {
setIsLoading(false);
setError(e.toString());
});
};
const onRegister = (email, password, repeatedPassword) => {
setIsLoading(true);
if (password !== repeatedPassword) {
setError("Error: Passwords do not match");
return;
}
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then((u) => {
setUser(u);
setIsLoading(false);
})
.catch((e) => {
setIsLoading(false);
setError(e.toString());
});
};
const onLogout = () => {
setUser(null);
firebase.auth().signOut();
};
return (
<AuthenticationContext.Provider
value={{
isAuthenticated: !!user,
user,
isLoading,
error,
onLogin,
onRegister,
onLogout,
}}
>
{children}
</AuthenticationContext.Provider>
);
};
I am new to redux, and working on an application. My sign-in and sign-up functionalities are working almost fine, except the fact that if some incorrect actions are being dispatched and not able to locate which part of the code is doing it. Below I am posting some code snippets.
Look at the second ghost LOGIN_FULFILLED Request, it should not occur as I don't have that user in the DB yet!
Screenshot for the actions and state transitions
Login action creators:
import request from 'axios';
import thunk from 'redux-thunk';
import store from '../store'
export function loginFunc(username, password) {
return {
type: 'LOGIN',
username,
password,
payload : request
.post("http://localhost:5000/users/authenticate",
{
username : username,
password: password
}
)
.then(function (response) {
console.log(response);
if (response.data.message === "user_found")
store.dispatch({type: 'LOGIN_FULFILLED', payload : response.data.results});
else
store.dispatch({type: 'LOGIN_REJECTED', payload : "user_not_found"});
})
.catch(function (error) {
console.log(error);
store.dispatch({type: 'LOGIN_REJECTED', payload : error});
})
}
}
Redux Thunk middleware allows you to write action creators that return a function instead of an action (as written in official guide).
You need to make few changes to make use of thunk. You need not import store to use getState and dispatch as they are arguments to the callback.
return function(dispatch, getState)
This dispatch, getState is same as store.dispatch and store.getState.
import request from 'axios';
export function loginFunc(username, password) {
return function(dispatch) {
request
.post("http://localhost:5000/users/authenticate", {
username: username,
password: password
})
.then(function(response) {
console.log(response);
if (response.data.message === "user_found")
dispatch({
type: 'LOGIN_FULFILLED',
payload: response.data.results
});
else
dispatch({
type: 'LOGIN_REJECTED',
payload: "user_not_found"
});
})
.catch(function(error) {
console.log(error);
dispatch({
type: 'LOGIN_REJECTED',
payload: error
});
})
}
}
I'm authenticating users iva JWT Auth on WP Rest API from a React Native app, so, something like that:
export function userAuth(username, password) {
return dispatch => {
dispatch(requestLogin());
const appAuth = new FormData();
appAuth.append('username', username);
appAuth.append('password', password);
return fetch(wp.jwtEndpoint, {
method: 'POST',
body: appAuth
})
.then(function(res) {
return res.json();
})
.then(function(body) {
if(body.token){
getUserDataFromUsername(body.user_nicename, body.token, dispatch);
return dispatch(userSuccessLogin(body));
}
else {
return dispatch(userFailLogin(body));
}
});
}
}
The response for this request is:
{ token: 'eyJ0eXAiOiJKXXXQ',
user_email: 'supertest#gmail.com',
user_nicename: 'super-test-avatar',
user_display_name: 'TEST TEST' }
My issue is: as I can't get user ID from there, how can I retrieve user data form a request like https://www.wp.com/wp-json/wp/v2/users/${userId}?
I tried using https://github.com/dest81/wp-api-get-user-by-username, which would allow me to do that based on username, but its endpoints goes to 404, so I think it's outdated.