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
Related
I have been trying to set user data into Sentry's scope globally, so every time there's an error or event, user info is passed to it.
My app is built in Next.js, so naturally I added the config as it is in Sentry's documentation for Next.js.
I haven't got the idea on where to add the Sentry.setUser({id: user.Id}) method in order for it to set the user globally.
So far I have added it to the Sentry's _error.js file, inside the getInitialProps method:
import NextErrorComponent from 'next/error';
import * as Sentry from '#sentry/nextjs';
import { getUser } from '../lib/session';
const MyError = ({ statusCode, hasGetInitialPropsRun, err }) => {
if (!hasGetInitialPropsRun && err) {
Sentry.captureException(err);
}
return <NextErrorComponent statusCode={statusCode} />;
};
MyError.getInitialProps = async (context) => {
const errorInitialProps = await NextErrorComponent.getInitialProps(context);
const { req, res, err, asPath } = context;
errorInitialProps.hasGetInitialPropsRun = true;
const user = await getUser(req, res);
// Set user information
if (user) {
console.log('Setting user');
Sentry.setUser({ id: user.Id });
}
else {
console.log('Removing user');
Sentry.configureScope(scope => scope.setUser(null));
}
if (res?.statusCode === 404) {
return errorInitialProps;
}
if (err) {
Sentry.captureException(err);
await Sentry.flush(2000);
return errorInitialProps;
}
Sentry.captureException(
new Error(`_error.js getInitialProps missing data at path: ${asPath}`),
);
await Sentry.flush(2000);
return errorInitialProps;
};
export default MyError;
But when trying to log errors, the user info doesn't show in Sentry, only the default user ip:
I have also tried setting the user after successful login, and still nothing..
Help is appreciated!!
Not sure if this is the right way, but the above solutions didn't work for me. So I tried calling setUser inside _app.tsx.
import { useEffect } from "react";
import { setUser } from "#sentry/nextjs";
import { UserProvider, useUser } from "#auth0/nextjs-auth0";
import type { AppProps } from "next/app";
function SentryUserManager() {
const { user } = useUser();
useEffect(() => {
if (user) {
setUser({
email: user.email ?? undefined,
username: user.name ?? undefined,
});
} else {
setUser(null);
}
}, [user]);
return null;
}
export default function MyApp({ Component, pageProps }: AppProps) {
return (
<UserProvider>
<Component {...pageProps} />
<SentryUserManager />
</UserProvider>
);
}
Still not sure why this worked for me and the other solutions didn't, but figured it was worth sharing.
I would suggest using the callback handler to set your Sentry user context.
import { handleAuth, handleLogin, handleCallback } from "#auth0/nextjs-auth0";
import * as Sentry from "#sentry/nextjs";
import { NextApiHandler } from "next";
const afterCallback = (_req, _res, session, _state) => {
Sentry.setUser({
id: session.user.sub,
email: session.user.email,
username: session.user.nickname,
name: session.user.name,
avatar: session.user.picture,
});
return session;
};
const handler: NextApiHandler = handleAuth({
async login(req, res) {
await handleLogin(req, res, {
returnTo: "/dashboard",
});
},
async callback(req, res) {
try {
await handleCallback(req, res, { afterCallback });
} catch (error) {
res.status(error.status || 500).end(error.message);
}
},
});
export default Sentry.withSentry(handler);
You can set the user in Sentry right after successful login
const handleLogin = {
try {
const res = await axios.post("/login", {"john#example.com", "password"})
if (res && res?.data) {
// Do other stuff
Sentry.setUser({ email: "john#example.com" });
}
}
}
Additionaly you can clear the user while logging out
const handleLogout = {
// Do othe stuff
Sentry.configureScope(scope => scope.setUser(null));
}
Router:
check auth before render
router.beforeEach((to, from, next) => {
const requireAuth = to.meta.auth
if (requireAuth && store.getters['auth/isAuthenticated']) {
next()
} else if (requireAuth && !store.getters['auth/isAuthenticated']) {
next({name: 'login'})
} else if (!requireAuth && store.getters['auth/isAuthenticated']) {
next({name: 'admin'})
} else {
next()
}
})
Vuex:
state() {
return {
isAuth: false,
user: null,
emailFormFactor: ''
}
},
getters: {
isAuthenticated(state) {
return state.isAuth
},
getEmailFormFactor(state) {
return state.emailFormFactor
},
getUser(state) {
return state.user
}
}
App
onBeforeMount(
() => {
if (localStorage.getItem('auth-token')) {
store.dispatch('auth/checkAuth')
}
}
)
Before,i hve to check the validity of the token and after that, if there is a change of state.
Does it need to be tracked in the router?
Thanks
I am trying to check if a user is authenticated and redirect them depending on the page they are in. for example if the user is logged in and they try to visit the login or signup page, they should be redirected. I have a middleware for that.
when I log in the user, the authenticateUser action runs and the user is created, when I check my cookies and local storage on the browser, I see that it is set correctly, but when I visit the login page after logging in, it doesn't redirect me.
middleware/altauth.js
export default function (context) {
console.log(context.store.getters('profile/isAuthenticated'))
if (context.store.getters.isAuthenticated) {
context.redirect('/')
}
}
also the token is both saved using Cookies and local storage and is persistence is through this middleware
middleware/checkauth.js
export default function (context) {
if(context.hasOwnProperty('ssrContext')) {
context.store.dispatch('profile/initAuth', context.ssrContext.req);
} else {
context.store.dispatch('profile/initAuth', null);
}
}
and below are the values for my store
import Cookie from 'js-cookie';
export const state = () => ({
token: null,
})
export const mutations = {
setToken(state, token) {
state.token = token
},
clearToken(state) {
state.token = null
}
}
export const actions = {
async authenticateUser(vuexContext, authData) {
let authUrl = 'https://look.herokuapp.com/signup/'
if (authData.isLogin) {
authUrl = 'https://look.herokuapp.com/login/'
}
return this.$axios
.$post(authUrl, authData.form)
.then(data => {
console.log(data);
const token = data.token
vuexContext.commit('setToken', token)
localStorage.setItem("token", token)
Cookie.set('jwt', token);
})
.catch(e => console.log(e))
},
initAuth(vuexContext, req) {
let token
if (req) {
if (!req.headers.cookie) {
return;
}
const jwtCookie = req.headers.cookie
.split(';')
.find(c => c.trim().startsWith('jwt='));
if (!jwtCookie) {
return;
}
token = jwtCookie.split('=')[1];
} else {
token = localStorage.getItem('token');
if (!token) {
return;
}
}
vuexContext.commit('setToken', token);
}
}
export const getters = {
isAuthenticated(state) {
return state.token != null;
},
}
please help, i don't know what the problem can be
Here is a basic but full example for auth system in SSR nuxt
You will need two apis for this, one will return token info with user info, and the other will return user info only.
for example
POST http://example.com/api/auth/authorizations
{
token: 'abcdefghijklmn',
expired_at: 12345678,
user: {
name: 'Tom',
is_admin: true
}
}
// this need authed
GET http://example.com/api/auth/user
{
name: 'Tom',
is_admin: true
}
nuxt.config.js
plugins:[
'~plugins/axios',
],
buildModules: [
'#nuxtjs/axios',
],
router: {
middleware: [
'check-auth'
]
},
./pages/login.vue
<template>
<form #submit.prevent="login">
<input type="text" name="username" v-model="form.username">
<input type="password" name="password" v-model="form.password">
</form>
</template>
<script type="text/javascript">
export default{
data(){
return {
form: {username: '', password: ''}
}
},
methods: {
login(){
this.$axios.post(`/auth/authorizations`, this.form)
.then(({ data }) => {
let { user, token } = data;
this.$store.commit('auth/setToken', token);
this.$store.commit('auth/updateUser', user);
this.$router.push('/');
})
}
}
}
</script>
store/index.js
const cookieFromRequest = (request, key) => {
if (!request.headers.cookie) {
return;
}
const cookie = request.headers.cookie.split(';').find(
c => c.trim().startsWith(`${key}=`)
);
if (cookie) {
return cookie.split('=')[1];
}
}
export const actions = {
nuxtServerInit({ commit, dispatch, route }, { req }){
const token = cookieFromRequest(req, 'token');
if (!!token) {
commit('auth/setToken', token);
}
}
};
middleware/check-auth.js
export default async ({ $axios, store }) => {
const token = store.getters['auth/token'];
if (process.server) {
if (token) {
$axios.defaults.headers.common.Authorization = `Bearer ${token}`;
} else {
delete $axios.defaults.headers.common.Authorization;
}
}
if (!store.getters['auth/check'] && token) {
await store.dispatch('auth/fetchUser');
}
}
store/auth.js
import Cookie from 'js-cookie';
export const state = () => ({
user: null,
token: null
});
export const getters = {
user: state => state.user,
token: state => state.token,
check: state => state.user !== null
};
export const mutations = {
setToken(state, token){
state.token = token;
},
fetchUserSuccess(state, user){
state.user = user;
},
fetchUserFailure(state){
state.user = null;
},
logout(state){
state.token = null;
state.user = null;
},
updateUser(state, { user }){
state.user = user;
}
}
export const actions = {
saveToken({ commit }, { token, remember }){
commit('setToken', token);
Cookie.set('token', token);
},
async fetchUser({ commit }){
try{
const { data } = await this.$axios.get('/auth/user');
commit('fetchUserSuccess', data);
}catch(e){
Cookie.remove('token');
commit('fetchUserFailure');
}
},
updateUser({ commit }, payload){
commit('updateUser', payload);
},
async logout({ commit }){
try{
await this.$axios.delete('/auth/authorizations');
}catch(e){}
Cookie.remove('token');
commit('logout');
}
}
plugins/axios.js
export default ({ $axios, store }) => {
$axios.setBaseURL('http://example.com/api');
const token = store.getters['auth/token'];
if (token) {
$axios.setToken(token, 'Bearer')
}
$axios.onResponseError(error => {
const { status } = error.response || {};
if (status === 401 && store.getters['auth/check']) {
store.commit('auth/logout');
}
else{
return Promise.reject(error);
}
});
}
Then you can do what you want in your middleware, such as check auth
middleware/auth.js
export default function ({ store, redirect }){
if (!store.getters['auth/check']) {
return redirect(`/login`);
}
}
After the user is logged in i dont want the user to access the log in page. I have tried this one down below but it's seem like it's not working. What should I do to make it works?
[Updated]
When I console.log(store.getters.loggedIn inside else if statement it returns false so I think the problem maybe is with store.getters. Since I'm a beginner in Vuejs I'm really not sure how to fix it. I will add my vuex code down below. Hope I can get some helps.
Thanks before hand!
// vuex
export default new Vuex.Store({
state: {
accessToken: null,
refreshToken: null,
APIData: "",
},
mutations: {
updateStorage(state, { access, refresh }) {
state.accessToken = access;
state.refreshToken = refresh;
},
destroyToken(state) {
state.accessToken = null;
state.refreshToken = null;
},
},
getters: {
loggedIn(state) {
return state.accessToken != null;
},
},
actions: {
userLogout(context) {
console.log("hello");
if (context.getters.loggedIn) {
context.commit("destroyToken");
}
},
userLogin(context, usercredentials) {
return new Promise((resolve, reject) => {
getAPI
.post("/rest-api-token/", {
email: usercredentials.email,
password: usercredentials.password,
})
.then((response) => {
context.commit("updateStorage", {
access: response.data.access,
refresh: response.data.refresh,
});
resolve();
console.log(this.getters.loggedIn); <-- return true
})
.catch((err) => {
reject(err);
});
});
},
},
modules: {},
});
// main.js
router.beforeEach((to, from, next) => {
if (to.matched.some((record) => record.meta.requiresLogin)) {
if (!store.getters.loggedIn) {
next({ name: "login" });
}
else {
next();
}
}
// if user is logged in and go to log in page redirect them to home page
else if (to.matched.some(record => record.meta.requiresVisitor)) {
if (store.getters.loggedIn) {
next({ name: 'home'});
}
else {
next();
}
}
//
else {
next();
}
});
//index.js (router)
const routes = [
{
path: "/",
name: "login",
component: Login,
meta: {
requiresVisitor: true,
},
},
{
path: "/home",
name: "home",
component: Home,
meta: {
requiresLogin: true,
},
},
{
path: "/logout",
name: "logout",
component: Logout,
},
];
i would add a state in my store called:
state: {
accessToken: null,
refreshToken: null,
APIData: "",
loggedIn: false //<<<<<<<<<<<<<<<<<<<<< HERE
},
then i would add a mutation for the Login Process, if the User Loggedin successfully
mutations: {
updateStorage(state, { access, refresh }) {
state.accessToken = access;
state.refreshToken = refresh;
},
destroyToken(state) {
state.accessToken = null;
state.refreshToken = null;
},
loginAttempt(state, payload) { //<<<<<<<<<<<<<<HERE
state.loggedIn = payload
}
},
and toggle the login state to true if success or false if failed.
then i add a v-if="userIsLoggedIn" in your login component and be toggle the Login if user is not logged in and show the Login Component or hide it
of course the userIsLoggedIn should be a computed:
computed: {
userIsLoggedIn: function() {
return this.$store.state.loggedIn
}
}
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>
}
}