Call api with axios since my component and my store - axios

I'm new to Vue 3 (cli) and I'm not at all comfortable with front-end technology, so I'm having a hard time understanding the information I'm reading.
I succeeded in creating a registration/login interface with an api and JWT. The user information needs to be persisted everywhere in the project I'm doing to train myself, so I configured axios in my store.
store/index.js
import { createStore } from 'vuex'
import axios from 'axios';
const api = axios.create({
baseURL: 'http://127.0.0.1:7000'
});
let user = localStorage.getItem('user');
if(null === user) {
user = {uuid: '', token: ''};
} else {
try {
user = JSON.parse(user);
api.defaults.headers.common['Authorization'] = 'Bearer ' + user.token;
} catch (e) {
user = {uuid: '', token: ''};
}
}
export default createStore({
state: {
status: '',
user: user,
userInfos: {},
},
mutations: {
[...]
},
getters: {
},
actions: {
[...]
},
modules: {
}
})
I would like to be able to use api from my components. I have had several approaches:
1 - I have imported axios into my component, but this is not correct at all, as I will need axios in all my components.
2 - I've looked at different documentations that explain how to configure axios globally, but no two are the same and I couldn't get anything to work.
3 - I've tried calling api through strangenesses like this.$store.api in my methods, but obviously this is abused.
Can anyone help me understand what is the right way to use axios from my components and from the store with only one configuration? Knowing that I need to be able to keep my headers up to date for authentication with the Bearer Token (a mutation updates it in the store at user login).
main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap/dist/js/bootstrap.js'
import { library } from '#fortawesome/fontawesome-svg-core'
import { FontAwesomeIcon } from '#fortawesome/vue-fontawesome'
import { faMedal } from '#fortawesome/free-solid-svg-icons'
import { faLaptopMedical } from '#fortawesome/free-solid-svg-icons'
import { faCookieBite } from '#fortawesome/free-solid-svg-icons'
import { faCoins } from '#fortawesome/free-solid-svg-icons'
import { faHourglassStart } from '#fortawesome/free-solid-svg-icons'
import { faUpRightFromSquare } from '#fortawesome/free-solid-svg-icons'
import { faInfo } from '#fortawesome/free-solid-svg-icons'
import { faGears } from '#fortawesome/free-solid-svg-icons'
library.add(
faMedal,
faCoins,
faLaptopMedical,
faCookieBite,
faHourglassStart,
faUpRightFromSquare,
faInfo,
faGears
);
createApp(App)
.component('font-awesome-icon', FontAwesomeIcon)
.use(store)
.use(router)
.mount('#app')
Thank you very much for your help.

If you're creating a new app, I would use Pinia, which is really the next version of VueX. Don't put the user in localStorage, but in a store that you can access from all views and components.
So Axios setup in composables/myaxiosfile.js
// src/stores/oneStore.js
import { defineStore } from "pinia";
// Possibly import and deconstruct functions from #/api.js and use
// those functions in the "actions" section of the store,
// updating the state according to the answer of the api call.
export const useOneStore = defineStore("oneStore", {
state: () => {
return {
user: true
}
}
// actions
// getters
})
and in a component :
import { useOneStore } from '../stores/oneStore';
const oneStore = useOneStore()

I don't know if this is the right way, but by doing so, it allows me to use the store api in my components.
store/index.js
state: {
api: {},
[...]
},
mutations: {
setApi: function (state, api) {
state.api = api;
},
connexionUser: function (state, user) {
state.user = user;
api.defaults.headers.common['Authorization'] = 'Bearer ' + user.token;
state.api = api;
},
[...]
},
actions: {
setApi: ({commit}) => {
commit('setApi', api);
},
[...]
},
App.vue
mounted() {
this.$store.dispatch('setApi');
[...]
}
Like this, offline, it loads api which is set at the top of my store (see in my question) and when I log in, I update api in state to have JWT authentication.

Related

Nest JS user authentication issue with parameter name

I am just learning nestjs for about a day and I came across this strange bug, probably has something to do with me not understanding what Im doing and rushing the project so please bear with me. My main issue is that while using JWT authentication, JSON coming from body is "username" and I can't change it. I want to log in using {"email":"test#gmail.com", "password": "password123"}, but instead it only accepts {"username":"test#gmail.com", "password": "password123"}. The word "username" is not defined or mentioned anywhere in my codebase
users.controller.ts
import { Controller, Get, Post, Body, Param, UseGuards } from '#nestjs/common';
import { UsersService} from './users.service';
import { CreateUserDto} from './dto/create-user.dto';
import { AuthGuard} from '#nestjs/passport';
#Controller('/users')
export class UsersController {
// constructor(private readonly usersService: UsersService) {}
constructor(private readonly userService: UsersService) {}
#UseGuards(AuthGuard('jwt'))
#Get('username')
getUserByEmail(#Param() param) {
return this.userService.getUserByEmail(param.email);
}
#Post('register')
registerUser(#Body() createUserDto: CreateUserDto) {
return this.userService.registerUser(createUserDto);
}
}
users.service.ts
import { Injectable, BadRequestException } from '#nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { Model } from 'mongoose';
import { InjectModel } from '#nestjs/mongoose';
import { HashService } from './hash.service';
import { User, UserDocument} from '../schemas/user.schema'
#Injectable()
export class UsersService {
constructor(#InjectModel(User.name) private userModel: Model < UserDocument > , private hashService: HashService) {}
async getUserByEmail(email: string) {
return this.userModel.findOne({
email
})
.exec();
}
async registerUser(createUserDto: CreateUserDto) {
// validate DTO
const createUser = new this.userModel(createUserDto);
// check if user exists
const user = await this.getUserByEmail(createUser.email);
if (user) {
throw new BadRequestException();
}
// Hash Password
createUser.password = await this.hashService.hashPassword(createUser.password);
return createUser.save();
}
}
auth.controller.ts
import { AuthService} from './auth.service';
import { Controller, Request, UseGuards, Post} from '#nestjs/common';
import { AuthGuard } from '#nestjs/passport';
#Controller('auth')
export class AuthController {
constructor(private authService: AuthService) {}
#UseGuards(AuthGuard('local'))
#Post(`/login`)
async login(#Request() req) {
console.log(req.user, "here")
return this.authService.login(req.user);
}
}
Here is the source code https://github.com/networkdavit/pillicam_test
Any help or suggestion is highly appreciated!
I tried changing all the parameter names, user schemas, adding a DTO, I googled how to add a custom parameter name or override it, tried to find if "default username param" actually exists. Nothing has worked for me so far
It's in there username in your code. https://github.com/networkdavit/pillicam_test/blob/main/src/users/entities/user.entity.ts#:~:text=class%20User%20%7B-,username%3A%20string%3B,-password%3A%20string
You can change it.
Or you can refer to this article for JWT implementation in nest.js
Just in case anyone ever gets this problem, I found a solution.
All I had to do was to add this to my local.strategy.ts file in constructor
super({
usernameField: 'email',
passwordField: 'password'
});
The default expects a username and password, so have to modify it manually

Is there a way to detect server side cookie for all pages in nextjs? [duplicate]

So I'm creating authentication logic in my Next.js app. I created /api/auth/login page where I handle request and if user's data is good, I'm creating a httpOnly cookie with JWT token and returning some data to frontend. That part works fine but I need some way to protect some pages so only the logged users can access them and I have problem with creating a HOC for that.
The best way I saw is to use getInitialProps but on Next.js site it says that I shouldn't use it anymore, so I thought about using getServerSideProps but that doesn't work either or I'm probably doing something wrong.
This is my HOC code:
(cookie are stored under userToken name)
import React from 'react';
const jwt = require('jsonwebtoken');
const RequireAuthentication = (WrappedComponent) => {
return WrappedComponent;
};
export async function getServerSideProps({req,res}) {
const token = req.cookies.userToken || null;
// no token so i take user to login page
if (!token) {
res.statusCode = 302;
res.setHeader('Location', '/admin/login')
return {props: {}}
} else {
// we have token so i return nothing without changing location
return;
}
}
export default RequireAuthentication;
If you have any other ideas how to handle auth in Next.js with cookies I would be grateful for help because I'm new to the server side rendering react/auth.
You should separate and extract your authentication logic from getServerSideProps into a re-usable higher-order function.
For instance, you could have the following function that would accept another function (your getServerSideProps), and would redirect to your login page if the userToken isn't set.
export function requireAuthentication(gssp) {
return async (context) => {
const { req, res } = context;
const token = req.cookies.userToken;
if (!token) {
// Redirect to login page
return {
redirect: {
destination: '/admin/login',
statusCode: 302
}
};
}
return await gssp(context); // Continue on to call `getServerSideProps` logic
}
}
You would then use it in your page by wrapping the getServerSideProps function.
// pages/index.js (or some other page)
export const getServerSideProps = requireAuthentication(context => {
// Your normal `getServerSideProps` code here
})
Based on Julio's answer, I made it work for iron-session:
import { GetServerSidePropsContext } from 'next'
import { withSessionSsr } from '#/utils/index'
export const withAuth = (gssp: any) => {
return async (context: GetServerSidePropsContext) => {
const { req } = context
const user = req.session.user
if (!user) {
return {
redirect: {
destination: '/',
statusCode: 302,
},
}
}
return await gssp(context)
}
}
export const withAuthSsr = (handler: any) => withSessionSsr(withAuth(handler))
And then I use it like:
export const getServerSideProps = withAuthSsr((context: GetServerSidePropsContext) => {
return {
props: {},
}
})
My withSessionSsr function looks like:
import { GetServerSidePropsContext, GetServerSidePropsResult, NextApiHandler } from 'next'
import { withIronSessionApiRoute, withIronSessionSsr } from 'iron-session/next'
import { IronSessionOptions } from 'iron-session'
const IRON_OPTIONS: IronSessionOptions = {
cookieName: process.env.IRON_COOKIE_NAME,
password: process.env.IRON_PASSWORD,
ttl: 60 * 2,
}
function withSessionRoute(handler: NextApiHandler) {
return withIronSessionApiRoute(handler, IRON_OPTIONS)
}
// Theses types are compatible with InferGetStaticPropsType https://nextjs.org/docs/basic-features/data-fetching#typescript-use-getstaticprops
function withSessionSsr<P extends { [key: string]: unknown } = { [key: string]: unknown }>(
handler: (
context: GetServerSidePropsContext
) => GetServerSidePropsResult<P> | Promise<GetServerSidePropsResult<P>>
) {
return withIronSessionSsr(handler, IRON_OPTIONS)
}
export { withSessionRoute, withSessionSsr }

Using VUEX necessary with NODE.js REST Backend

I´m not very experienced with Frontend/Backend Architecture, but i created a simple REST Backend with NODE.js and want to build up a Frontend based on Vue.js and Framework7.
So do you recommend using VUEX there? Or how do you deal with the sessions or the different requests you sending to the Backend?
Thanks a lot!
You don't have to use Vuex, but I'd suggest using Vuex. Here's an example using Vuex and rest api.
In store/actions.js
import {
fetchSomething,
} from '../api/index.js';
export const actions = {
getSomething({ commit }) {
fetchSomething().then((something) => {
commit('UPATED_SOMETHING', something);
});
},
}
In api/index.js
export const fetchSomething = () => {
const url = 'Some endpoint';
return new Promise((resolve) => {
axios.get(url).then((res) => {
const data = res.data;
resolve(data);
}).catch((err) => {
console.log(err);
})
})
}
In store/mutations.js
export const mutations = {
UPATED_SOMETHING(state, data) {
state.something = data;
},
}
In store/index.js
import { getters } from './getters'
import { actions } from './actions'
import { mutations } from './mutations'
// initial state
const state = {
something: null,
}
export default {
state,
getters,
actions,
mutations,
}
In store/getters.js
export const getters = {
getSomething: state => {
return state.something;
},
}

Best way to connect ionic 2 nativ facebook with firebase

at the moment iam implementing a signIn into my ionic 2 app.
I want to use ionic 2 native facebook and somehow save the data to my firebase app.
Is there any way to archive that?
One way is to create a new firebase auth user with the facebook email adress and some password hash, but maybe there is a better solution.
Here is what i got so far (i know, not much) :)
import {NavController, Loading, Platform, Storage, LocalStorage} from "ionic-angular";
import {OnInit, Inject, Component} from "#angular/core";
import {ForgotPasswordPage} from "../forgot-password/forgot-password";
import {SignUpPage} from "../sign-up/sign-up";
import {HomePage} from "../../home/home";
import * as firebase from 'firebase';
import {Facebook} from 'ionic-native';
/*
Generated class for the LoginPage page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
*/
#Component({
templateUrl: 'build/pages/auth/login/login.html',
})
export class LoginPage {
private local: any;
constructor(private navCtrl: NavController, private platform:Platform) {
this.local = new Storage(LocalStorage);
}
openForgotPasswordPage():void {
this.navCtrl.push(ForgotPasswordPage);
}
openSignUpPage():void {
this.navCtrl.push(SignUpPage);
}
login() {
firebase.auth().signInWithEmailAndPassword("test#test.com", "correcthorsebatterystaple").then(function (result) {
console.log("AUTH OK "+ result);
}, function (error) {
console.log("dawdaw");
});
}
facebookLogin() {
Facebook.login(['public_profile', 'user_birthday']).then(() => {
this.local.set('logged', true);
this.navCtrl.setRoot(HomePage);
}, (...args) => {
console.log(args);
})
} }
facebookLogin() {
Facebook.login(['public_profile', 'user_birthday']).then((result) => {
var creds = firebase.auth.FacebookAuthProvider.credential(result.access_token);
return firebase.auth().signInWithCredential(creds);
})
.then((_user) => {
console.log("_user:", _user);
})
.catch((_error) => {
console.error("Error:", _error);
});
}
see more info here - https://firebase.google.com/docs/auth/web/facebook-login#advanced-handle-the-sign-in-flow-manually
I have not tried this, so might not be 100% working, but try this Gist I found: https://gist.github.com/katowulf/de9ef6b04552091864fb807092764224

currentUser fetched in Authentication with Torii?

Trying to change a torii authenticator to return an account id from the response, so it's available in the session for fetching the account.
In trying to adapt the example to the torii authenticator, I have this starting point (obviously wrong, hitting on my js knowledge limits):
import Ember from 'ember';
import Torii from 'simple-auth-torii/authenticators/torii';
import Configuration from 'simple-auth-oauth2/configuration';
export default Torii.extend({
authenticate: function(credentials) {
return this._super(provider).then((authResponse) => {
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.$.ajax({
url: Configuration.serverTokenEndpoint,
type: 'POST',
data: { 'auth_code': authResponse.authorizationCode }
}).then(function(response) {
Ember.run(function() {
// all properties this promise resolves
// with will be available through the session
resolve({ access_token: response.access_token, account_id: response.account_id });
});
}, function(xhr, status, error) {
Ember.run(function() {
reject(xhr.responseText);
});
});
});
});
}
});
Ember doesn't complain with any errors, but of course facebook's auth dialog doesn't pop. Lost at this point, any pointers would be greatly appreciated.
Update
This is the provider code, which was working before changing the authenticator to try and return the account_id as well:
import Ember from 'ember';
import FacebookOauth2 from 'torii/providers/facebook-oauth2';
let { resolve } = Ember.RSVP;
export default FacebookOauth2.extend({
fetch(data) {
return resolve(data);
},
close() {
return resolve();
}
});
This is the previous, working authenticator:
import Ember from 'ember';
import Torii from 'simple-auth-torii/authenticators/torii';
import Configuration from 'simple-auth-oauth2/configuration';
export default Torii.extend({
authenticate(provider) {
return this._super(provider).then((authResponse) => {
return Ember.$.post(Configuration.serverTokenEndpoint, { 'auth_code': authResponse.authorizationCode }).then(function(response) {
return { 'access_token': response['access_token'], provider };
});
});
}
});