AuthService.js
import axios from 'axios';
const GET_AUTH_API_BASE_URL = "http://localhost:8087/auth";
class AuthService {
login(user){
return axios.post(GET_AUTH_API_BASE_URL+"/login",user);
}
getRole(userName,password){
return axios.get(GET_AUTH_API_BASE_URL+"/role/"+userName+"/"+password);
}
}
export default new AuthService();
LoginComponent.js
class LoginUserComponent extends Component {
constructor(props) {
super(props);
this. State = {
userName: "",
password: "",
};
this.changeHandler = this.changeHandler.bind(this);
this.login = this.login.bind(this);
}
changeHandler(event) {
this.setState({ [event.target.name]: event.target.value });
// console.log(this.state.user.userName);
}
login(event) {
let userDet = {
userName: this.state.userName,
password: this.state.password,
};
console.log(userDet);
AuthService.login(userDet).then(
(res) => {
sessionStorage.setItem("token", res.data);
AuthService.getRole(userDet).then((res) => {
sessionStorage.setItem("role", res.data);
});
if (sessionStorage.getItem("role") === "Admin") {
console.log("Admin");
this.props.navigate("/employees");
}
if (sessionStorage.getItem("role") === "User") {
console.log("User");
this.props.navigate("/add-employee");
}
},
(error) => {
const resMessage =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString();
alert(resMessage);
}
);
event.preventDefault();
}
RegisterComponent.js
class RegisterUserComponent extends Component {
constructor(props) {
super(props)
this.state ={
userId:0,
userName:'',
password:'',
role:{
roleId:0,
roleName:''
}
}
this.changeHandler=this.changeHandler.bind(this);
}
changeHandler(event){
this.setState({[event.target.name]:event.target.value});
// console.log(this.state.user.userName);
}
submitData=(event)=>{
console.log(this.state.user);
let userDet={
userId:this.state.userId,
userName:this.state.userName,
password:this.state.password,
role:{
roleId:this.state.roleId,
roleName:this.state.roleName
}
}
console.log(userDet);
// axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
axios.post('http://localhost:8087/auth/users',userDet);
event.preventDefault();
this.props.navigate("/")
}
I can able to register a user with role like admin,user.But when I login the registered user, I am getting a axios error as http://localhost:8087/auth/role/[object%20Object]/undefined. My token is storing in session storage but the role(key, value) is not storing.
I have now added my register component. Kindly rectify
Issue
getRole takes two arguments, userName and password
getRole(userName, password) {
return axios.get(GET_AUTH_API_BASE_URL + "/role/" + userName + "/" + password);
}
but the UI is passing a single object
let userDet = {
userName: this.state.userName,
password: this.state.password,
};
...
AuthService.getRole(userDet)
.then((res) => {
sessionStorage.setItem("role", res.data);
});
userName is an object and password is undefined in the getRole function.
Solution
Pass two args.
const { userName, password } = this.state;
...
AuthService.getRole(userName, password)
.then((res) => {
sessionStorage.setItem("role", res.data);
});
Related
I have added authorization to my Nuxt app, but something is wrong. When i enter wrong password or email, I am still redirected to the main page of the application, although I have to stay on the authorization page and try to log in again.
Here is my code:
import {
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
signOut
} from 'firebase/auth'
export default {
data() {
return {
snackBar: false,
snackBarText: 'No Error Message',
auth: {
email: '',
password: ''
}
}
},
methods: {
login() {
let that = this
this.$fire.auth.signInWithEmailAndPassword(this.auth.email, this.auth.password)
.catch(function (error) {
console.log(error.message);
that.snackBarText = error.message
that.snackBar = true
// $nuxt.$router.push('/login')
}).then((user) => {
console.log(user);
$nuxt.$router.push('/')
})
}
}
}
middleware:
export default function ({ app, route, redirect }) {
if (route.path !== '/login') {
// we are on the protected route
if (!app.$fire.auth.currentUser) {
// take them to sign in in a page
return redirect('/login')
}
} else if (route.path === '/login') {
if (!app.$fire.auth.currentUser) {
// leave them on the sign in page
} else {
return redirect('/')
}
}
}
store:
const state = () => ({
user: null,
};
const mutations = {
SET_USER(state, user) {
state.user = user
},
}
const actions = {
async onAuthStateChangedAction(context, { authUser, claims }) {
if (!authUser) {
context.commit('SET_USER', null)
this.$router.push({
path: '/login'
})
} else {
const { uid, email } = authUser;
context.commit('SET_USER', {
uid,
email
})
}
}
}
const getters = {
getUser(state) {
return state.user
}
}
export default {
state,
actions,
mutations,
getters,
}
Form for authorization is in component popup, which is sent to page login.vue
I do not know how to implement a method in which when using the updateProfile () function, it checks the firestore if such mail already exists and then an error would pop up. I did a test method in MyAccount.vue, but it doesn't work, if I don't type anything and click, nothing updates, but that's not the point, I would like it to check if such mail exists.
./src/views/MyAccount.vue
import { mapState } from 'vuex';
export default {
data() {
return {
user: {
username: '',
email: '',
password: ''
}
};
},
computed: {
...mapState(['userProfile']),
},
methods: {
updateProfile() {
this.$store.dispatch('updateProfile', {
username:
this.user.username !== ''
? this.user.username
: this.userProfile.username,
email:
this.user.email !== ''
? this.user.email
: this.userProfile.email,
password:
this.user.password !== ''
? this.user.password
: this.userProfile.password
});
this.user.username = '';
this.user.email = '';
this.user.password = '';
this.showSuccess = true;
setTimeout(() => {
this.showSuccess = false;
}, 2000);
}
}
};
</script>
./src/store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
import * as fb from '../firebase';
import router from '../router/index';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
userProfile: {},
notes: []
},
mutations: {
setUserProfile(state, val) {
state.userProfile = val;
},
setNotes(state, val) {
state.notes = val;
}
},
actions: {
async updateProfile({ commit, dispatch }, user) {
const userId = fb.auth.currentUser.uid;
await fb.usersCollection.doc(userId).update({
username: user.username,
email: user.email,
password: user.password
});
dispatch('fetchUserProfile', { uid: userId });
},
async fetchUserProfile({ commit }, user) {
// fetch user profile
const userProfile = await fb.usersCollection.doc(user.uid).get();
// set user profile in state
commit('setUserProfile', userProfile.data());
// change router to dashboard
if (router.currentRoute.path === '/login') {
router.push('/');
}
}
},
modules: {}
});
export default store;
Before updating, try this:
const current = await fb.usersCollection.where('email', '==', user.email).get()
if (current.empty === true) {
// You are free to do the update, because the email is not in use already
}
Of course, this works best if you make sure to alway lowercase your emails before querying or storing them in the database
First I apologize for my English. I have been working on React to native applications for 4 months. But sometimes I get this error and don't mind.
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in %s.%s, the componentWillUnmount method,
in CustomerDetailScreen (at SceneView.tsx:123)
This is because when I click the button, I open a screen, and when the screen is not fully loaded I press the back button. How can I resolve this warning? I'll show you some sample code examples.
I hope I could explain. Can you help me with this topic? I want to fully understand the logic. I've read something called AbortController in some articles but I don't know exactly.
constructor(props) {
super(props);
this._isMounted = false;
this.state = {
id: props.route.params.id,
username: '',
token: null,
cityId: 1,
townId: 1,
cityData: [],
townData: [],
selectedIndex: 0,
selectedCity: new IndexPath(0),
selectedTown: new IndexPath(0),
}
}
componentDidMount() {
this._isMounted = true;
this._isMounted && this._getToken();
}
componentWillUnmount() {
this._isMounted = false;
}
_getToken = async () => {
try {
const username = await AsyncStorage.getItem('username');
const token = await AsyncStorage.getItem('token');
if(token === null) {
await AsyncStorage.removeItem('token');
}else {
this.setState({ username: username, token: token });
this._isMounted && this.loadCustomerDetail();
}
} catch (error) {
console.log(error);
}
};
loadCustomerDetail() {
try {
const { username, token } = this.state;
if(token) {
const { id } = this.state;
var credentials = Base64.btoa(username + ':' + token);
var URL = `https://portal.xxxxxx.com/api/v1/Customer/${id}`;
axios.get(URL, {headers : { 'Espo-Authorization' : credentials }})
.then(this.dataSuccess.bind(this))
.catch(this.dataFail.bind(this));
}
}catch (err) {
console.log(err);
}
};
dataSuccess(response) {
this.setState({
isLoading: false,
cityId: response.data.cityId,
townId: response.data.townId
}, () => {
this.getCities();
});
}
getCities() {
const { username, token, cityId } = this.state;
let credentials = Base64.btoa(username + ':' + token);
axios.get('https://portal.xxxxx.com/api/v1/Cities', { headers : { 'Espo-Authorization' : credentials }})
.then((response) => {
response.data.list.sort(function(a, b) {
return Number(a.id) > Number(b.id);
});
this.setState({cityData: response.data.list}, () => {
this.setState({ selectedCity: new IndexPath(this.state.cityData[cityId-1].id - 1) });
this.getTowns(this.state.cityData[cityId-1].id);
});
}).catch((error) => {
console.log(error);
});
}
getTowns(cityId) {
this.setState({ townLoading: true });
const { username, token } = this.state;
let credentials = Base64.btoa(username + ':' + token);
axios.get(`https://portal.xxxxx.com/api/v1/Towns/action/TownList?cityId=${cityId}`, { headers : { 'Espo-Authorization' : credentials }})
.then((response) => {
this.setState({ townData: response.data, townLoading: false }, () => {
for (const [key, value] of Object.entries(this.state.townData)) {
if(value.id === this.state.townId) {
this.setState({ selectedTown: new IndexPath(key) })
}
}
});
}).catch((error) => {
console.log(error);
});
}
An example area:
this.setState({ username: username, token: token });
this._isMounted && this.loadCustomerDetail();
You can see that setState will be called even if the component is no longer mounted.
Fix
Ensure component is mounted before changing state:
if (this._isMounted) {
this.setState({ username: username, token: token });
this.loadCustomerDetail();
}
I'm building a website where users can register, but when registration is complete nothing happens, its supposed to enter the site.
I have tested it with console.log and found out that my user.id is undefined.
this is my register on the server side:
const handleRegister = (req, res, db, bcrypt) => {
const { email, name, password } = req.body;
if (!email || !name || !password) {
return res.status(400).json('incorrect form submission');
}
const hash = bcrypt.hashSync(password);
db.transaction(trx => {
trx.insert({
hash: hash,
email: email
})
.into('login')
.returning('email')
.then(loginEmail => {
console.log(email)
return trx('users')
.returning('*')
.insert({
email: email,
name: name,
joined: new Date()
})
.then(user => {
res.json(user[0]);
})
})
.then(trx.commit)
.catch(trx.rollback)
})
.catch(err => res.status(400).json('unable to register ' + err))
}module.exports = {
handleRegister: handleRegister
};
and this is my register on the frontend:
import React from 'react';
class Register extends React.Component {
constructor(props){
super(props);
this.state = {
name: '',
email: '',
password: ''
}
}
onNameChange = (event) => {
this.setState({name: event.target.value})
}
onEmailChange = (event) => {
this.setState({email: event.target.value})
}
onPasswordChange = (event) => {
this.setState({password: event.target.value})
}
onSubmitSignIn = () => {
fetch('http://localhost:3000/register', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
name: this.state.name,
email: this.state.email,
password: this.state.password
})
})
.then(response => response.json())
.then(user => {
console.log(user.id);
if (user.id) {
console.log(user, user.id);
this.props.loadUser(user)
this.props.onRouteChange('home');
}console.log(user.id);
})
}
It is on the frontend I have set the console.log and it never enters the if statement.
How do I fix this?
If you are using mongodb the id field is defined as _id
I have this Javascript code to handle ActiveDirectory authentication.
I need to create a React component that uses this code, what is the best way to achieve this in React?
var config = { url: 'ldap://compandomain.com:389',
baseDN: 'dc=domainname,dc=com',
username: 'user',
password: 'pass' };
var ad = new ActiveDirectory(config);
var username = 'john.smith#domain.com';
var password = 'password';
ad.authenticate(username, password, function(err, auth) {
if (err) {
console.log('ERROR: '+JSON.stringify(err));
return;
}
if (auth) {
console.log('Authenticated!');
}
else {
console.log('Authentication failed!');
}
});
The React component looks like this:
export default class ActiveDirectory extends React.Component {
..
......
.........
render() {
return <div ..../>;
}
}
you should be abler to handle this authentication in the componentDidMount lifecycle method. it should probably look like this.
import React from 'react';
import ActiveDirectory from 'activedirectory';
export default class ActiveDirectoryComponent extends React.Component {
state = {
authResponse: undefined
};
componentDidMount() {
var config = {
url: 'ldap://compandomain.com:389',
baseDN: 'dc=domainname,dc=com',
username: 'user',
password: 'pass'
};
var ad = new ActiveDirectory(config);
var username = 'john.smith#domain.com';
var password = 'password';
ad.authenticate(username, password, function (err, auth) {
if (err) {
this.setState({ authResponse: { error: JSON.stringify(err) } });
return;
}
if (auth) {
this.setState({ authResponse: auth });
} else {
console.log('Authentication failed!');
this.setState({ authResponse: { authFailed: true } });
}
});
}
render() {
if (!this.state.authResponse) {
return <div>Authenticating....</div>;
}
if (this.state.authResponse.error) {
return <div>{this.state.authResponse.error}</div>
}
if (this.state.authResponse.authFailed) {
return <div>Authentication Failed</div>
}
return <div>.....</div>
}
}