I'm migrating a project to Nuxt 3 and I don't know how to convert a Nuxt 2 code using the new setup script
I have a login that if return a 200 response I would save 2 cookie but
$fetch(`${runtimeConfig.public.BASE_API_BROWSER_URL}/user/login`, {
method: 'POST',
body: {
email: email.value,
password: password.value,
}
})
.then((resp) => {
localStorage.setItem('Bearer', resp.access_token)
// Cookie.set('Bearer', resp.data.access_token, { expires: 7 })
isSubmitting.value = false
window.location.href = '/profile/'
})
I was using js-cookie but I was wondering if I could achieve the same without the need of a dependency, I know I can use vanilla js but I was wondering if use-cookie would work as well.
I've tried this useCookie('Bearer', resp.access_token, { maxAge: 60 * 60 * 24 * 7 }) but doesn't seems to work
Leveraging the built in useCookie would look like this to set a value:
// Login Script
const myCookieToken = useCookie('myCookieToken', { maxAge: 60 * 60 * 24 * 7 })
$fetch('...').then(response => {
myCookieToken.value = response.access_token
}
To retrieve the value later in another script or component:
const myCookieToken = useCookie('myCookieToken')
console.log(myCookieToken.value)
PS... You may want to use navigateTo('/profile') instead of window.location.href so you get the nice built in page transition.
Related
I have been having trouble with a MERN stack deployment, I get a 401 error on heroku, wheni try to login or use any APi call.
I am using express-sessions andi have noticed using console.log that the session on login page shows that the user have logged in but as soon as i am redirected to Dashboard, the session changes
NOte: Using AXios
Note: everything is working perfectly fine on Localhost, only facing this issue on developemnt.. and on Heroku (free v)
Code on Server.js
var express = require('express');
var session = require('express-session');
var MongoDBStore = require('connect-mongodb-session')(session);
const bodyParser = require('body-parser');
var mongoUtil = require( './utils/mongoUtil' );
const cors = require('cors');
app.use(cors({credentials: true, origin: 'https://teamdashboard0.herokuapp.com'}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var store = new MongoDBStore(
{
uri: "mongodb+srv://teamdashboard:ONgnWv4aqRwBKo8g#teamdashboard.3ivb8.mongodb.net/TeamDashboard",
databaseName: 'TeamDashboard',
collection: 'sessions'
});
store.on('error', function(error) {
console.log(error);
});
app.use(session({
secret: 'bakdhgsjcdbcbsdm',
resave: false,
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 7, // 1 week
secure: true
},
store: store,
unset: 'destroy',
saveUninitialized: false
}));
mongoUtil.connectToServer( function( err, client ) {
var user = require( './controllers/user.js' );
var colleague = require( './controllers/colleague.js' );
var team = require( './controllers/team.js' );
var news = require( './controllers/news.js' );
app.post('/register', (req, res)=>{user.register(req,res)});
app.get('/verify',(req,res)=>{user.verify(req,res)});
app.get('/login',(req,res)=>{user.login(req,res)});
app.post('/changePasswordEmail',(req,res)=>{user.sendChangePassword(req,res)});
app.put('/changePassword',(req,res)=>{user.changePassword(req,res)});
app.post('/logout', (req,res)=>{user.logout(req,res)});
app.get('/colleague/checkLimit', (req,res)=>{colleague.checkLimit(req,res)});
app.post('/colleague/add', (req,res)=>{colleague.add(req,res)});
app.delete('/colleague/delete', (req,res)=>{colleague.delete(req,res)});
app.put('/colleague/update', (req,res)=>{colleague.update(req,res)});
app.get('/colleague/all', (req,res)=>{colleague.getAll(req,res)});
app.get('/colleague/one', (req,res)=>{colleague.getOne(req,res)});
app.get('/team/all', (req,res)=>{team.allTeams(req,res)});
app.post('/team/add', (req,res)=>{team.newTeam(req,res)});
app.delete('/team/delete', (req,res)=>{team.deleteTeam(req,res)});
app.put('/team/update', (req,res)=>{team.updateTeam(req,res)});
app.get('/team/colleague/all', (req,res)=>{team.getColleagues(req,res)});
app.post('/team/colleague/add', (req,res)=>{team.addColleague(req,res)});
app.delete('/team/colleague/delete', (req,res)=>{team.deleteColleague(req,res)});
app.get('/news',(req,res)=>{news.getNews(req,res)});
app.get('/', function(req, res) {
var msg = `
Welcome to the Team Dashboard\n
Visit:
https://app.swaggerhub.com/apis-docs/Hira172/TeamDashboard/1.0.0
to view all the api and details about the backend
`
res.send(msg)
});
if (err) console.log(err);
port = process.env.PORT || 8080;
app.listen(port, () => console.log(`Server Running at port ${port}`));
} );```
I am creating a webRTC connection to transmit data between 2 peers. Currently, I am stuck in the stage of getting the channel.readyState to get into "open" state. Can someone help me understand why the "ondatachannel()" in code block 2 and the "onopen()" in codeblock 1 eventlisteners do not fire? It works when I manually enter all the code in my dev tool consoles. I am using django backend with django channels for sdp exchange.
Instantiating RTCPeerConnection and sending localdescription to my back end.
function hostroom(){
lc = new RTCPeerConnection()
dc = lc.createDataChannel("channel")
dc.onmessage = e =>("Just got a message " + e.data);
dc.onopen = e => console.log("Connection opened!")
lc.onicecandidate = function(e){
console.log("icecandidate created");
}
lc.createOffer().then(o => lc.setLocalDescription(o)).then(a => console.log("set successfully!")).then(
function (){
var ice = JSON.stringify(lc.localDescription);
console.log(ice);
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
var p={{p.id}}
$.ajax({
type: 'POST',
url: '{% url 'createroom' %}',
data:{
"ice": ice,
"csrfmiddlewaretoken": csrftoken,
"p": p,
},
success: function (data) {
alert(data["response"])
}
});
}
)
Output on dev tool console:
Code on the remote peer's side. Runs on page load and will send the local description via the back end and then via django channels to the host.
const rc = new RTCPeerConnection();
rc.onicecandidate = function(e){
console.log("New Ice Candidate reprinting SDP " + JSON.stringify(rc.localDescription));
}
rc.ondatachannel = e => {
rc.dc = e.channel;
rc.dc.onmessage = e => console.log("new message from client! " + e.data);
rc.dc.onopen = e => console.log("Connection opened!");
};
var offer = {{icecandidate|safe}}
rc.setRemoteDescription(offer).then(a => console.log("offer set!"));
rc.createAnswer().then(a => rc.setLocalDescription(a)).then(a => console.log("local d set!")).then(
function(){
var answer = JSON.stringify(rc.localDescription)
console.log(answer)
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
var user = document.getElementById("account").text.split(":")[1];
var room_name="{{room_name}}"
console.log(room_name);
$.post("{% url 'connecttoleader' %}", {
"answer": answer,
"csrfmiddlewaretoken": csrftoken,
"user": user,
"room_name": room_name,
});
}
);
Output on dev tool console:
back to the host's side. Code fires upon triggering djangochannelsocket.onmessage() on the same browser tab as code block 1(first code block above).
...
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
console.log(JSON.parse(sdp))
lc.setRemoteDescription(JSON.parse(sdp))
console.log("set")
channel = "dc"
$.ajax({
type: 'POST',
url: '{% url 'connectpeer' %}',
data:{
"channel": channel,
"csrfmiddlewaretoken": csrftoken,
"user": user,
},
success: function (data) {
alert(data["response"])
}
});
...
Output on dev tool console:(as you can see the "connection opened!" string from the onopen() eventlistener does not print and dc.readyState command in the browser dev tools console only shows "connecting")
You are not exchanging ice candidates, merely printing the updated SDP.
Without exchanging ice candidates, the connection won't get established and the datachannel won't open.
I have the following set up in my nuxt.config.js file:
auth: {
redirect: {
login: '/accounts/login',
logout: '/',
callback: '/accounts/login',
home: '/'
},
strategies: {
local: {
endpoints: {
login: { url: 'http://localhost:8000/api/login2/', method: 'post' },
user: {url: 'http://localhost:8000/api/user/', method: 'get', propertyName: 'user' },
tokenRequired: false,
tokenType: false
}
}
},
localStorage: false,
cookie: true
},
I am using django sessions for my authentication backend, which means that upon a successful login, i will have received a session-id in my response cookie. When i authenticate with nuxt however, i see the cookie in the response, but the cookie is not saved to be used in further requests. Any idea what else i need to be doing?
This is how I handled this, which came from a forum post that I cannot find since. First get rid of nuxt/auth and roll your own with vuex store. You will want two middleware, one to apply to pages you want auth on, and another for the opposite.
This assumes you have a profile route and a login route that returns a user json on successful login.
I'm also writing the user to a cookie called authUser, but that was just for debugging and can be removed if you don't need it.
store/index
import state from "./state";
import * as actions from "./actions";
import * as mutations from "./mutations";
import * as getters from "./getters";
export default {
state,
getters,
mutations,
actions,
modules: {},
};
store/state
export default () => ({
user: null,
isAuthenticated: false,
});
store/actions
export async function nuxtServerInit({ commit }, { _req, res }) {
await this.$axios
.$get("/api/users/profile")
.then((response) => {
commit("setUser", response);
commit("setAuthenticated", true);
})
.catch((error) => {
commit("setErrors", [error]); // not covered in this demo
commit("setUser", null);
commit("setAuthenticated", false);
res.setHeader("Set-Cookie", [
`session=false; expires=Thu, 01 Jan 1970 00:00:00 GMT`,
`authUser=false; expires=Thu, 01 Jan 1970 00:00:00 GMT`,
]);
});
}
store/mutations
export const setUser = (state, payload) => (state.user = payload);
export const setAuthenticated = (state, payload) =>
(state.isAuthenticated = payload);
store/getters
export const getUser = (state) => state.user;
export const isAuthenticated = (state) => state.isAuthenticated;
middleware/redirectIfNoUser
export default function ({ app, redirect, _route, _req }) {
if (!app.store.state.user || !app.store.state.isAuthenticated) {
return redirect("/auth/login");
}
}
middleware/redirectIfUser
export default function ({ app, redirect, _req }) {
if (app.store.state.user) {
if (app.store.state.user.roles.includes("customer")) {
return redirect({
name: "panel",
params: { username: app.store.state.user.username },
});
} else if (app.store.state.user.roles.includes("admin")) {
return redirect("/admin/dashboard");
} else {
return redirect({
name: "panel",
});
}
} else {
return redirect("/");
}
}
pages/login- login method
async userLogin() {
if (this.form.username !== "" && this.form.password !== "") {
await this.$axios
.post("/api/auth/login", this.form)
.then((response) => {
this.$store.commit("setUser", response.data);
this.$store.commit("setAuthenticated", true);
this.$cookies.set("authUser", JSON.stringify(response.data), {
maxAge: 60 * 60 * 24 * 7,
});
if (this.$route.query.redirect) {
this.$router.push(this.$route.query.redirect);
}
this.$router.push("/panel");
})
.catch((e) => {
this.$toast
.error("Error logging in", { icon: "error" })
.goAway(800);
The cookie is sent by the server but the client won't read it, until you set the property withCredentials in your client request (about withCredentials read here)
To fix your problem you have to extend your auth config with withCredentials property.
endpoints: {
login: {
url: 'http://localhost:8000/api/login2/',
method: 'post'
withCredentials: true
}
}
Also don't forget to set CORS policies on your server as well to support cookie exchange
Example from ExpressJS
app.use(cors({ credentials: true, origin: "http://localhost:8000" }))
More information about this issue on auth-module github
What I am trying to do is to change the data in firestore using cloud function and cloud task on a scheduled time. But cloud task doesn't run on time. It is executed right after adding task.
My code is like this.
index.js
exports.addTasks = functions.https.onCall((data, context) => {
const client = new tasks.CloudTasksClient()
const projectId = ...
const queue = ...
const location = ...
const parent = client.queuePath(projectId, location, queue)
const url = ... .cloudfunctions.net/doSomething?docId=' + docId
const task = {
httpRequest: {
httpMethod: 'POST',
url: url,
scheduleTime: {
seconds: 3 * 60 + Date.now() / 1000,
},
}
}
const request = {
parent: parent,
task: task,
}
client.createTask(request)
})
exports.doSomething = functions.https.onRequest((req, res) => {
var db = admin.firestore()
var docId = req.query.docId
var docRef = db.collection('people').doc(docId)
docRef.update({
changeHere: true,
})
})
I want to run doSomething function 3 minutes after addTasks is executed. What am I wrong with this?
scheduleTime is a property of the task object and not a property of httpRequest.
const task = {
httpRequest: {
httpMethod: 'POST',
url: url,
},
scheduleTime: {
seconds: 3 * 60 + Date.now() / 1000,
},
}
Here is the reference doc and sample code showing this.
I am trying out Urban Airship with Appcelerator but I am having problems with using it.
This is my code in App.js:
Will it be "activated" when the user opens the app and then register automatically with Urban Airship?
UrbanAirship = require('ti.urbanAirship');
Ti.API.info("module is => "+UrbanAirship);
Ti.include('common/urbanairship.js');
UrbanAirship.key='XXX';
UrbanAirship.secret ='XXX';
UrbanAirship.master_secret='XXX';
UrbanAirship.baseurl = 'https://go.urbanairship.com';
Ti.Network.registerForPushNotifications({
types: [
Ti.Network.NOTIFICATION_TYPE_BADGE,
Ti.Network.NOTIFICATION_TYPE_ALERT,
Ti.Network.NOTIFICATION_TYPE_SOUND
],
success:function(e){
var deviceToken = e.deviceToken;
Ti.API.info('successfully registered for apple device token with '+e.deviceToken);
var params = {
tags: ['version'+Ti.App.getVersion()],
alias: 'testing'
};
UrbanAirship.register(params, function(data) {
Ti.API.debug("registerUrban success: " + JSON.stringify(data));
}, function(errorregistration) {
Ti.API.warn("Couldn't register for Urban Airship");
});
},
error:function(e) {
Ti.API.warn("push notifications disabled: "+e);
},
callback:function(e) {
var a = Ti.UI.createAlertDialog({
title:'New Message',
message:e.data.alert
});
a.show();
}
});
The modules are always hit or miss for me.
Very rarely have they worked without a lot of troubleshooting.
I've gone the old-school route and it has worked fine for me - although I did change urbanairship.js to add eventlisteners on windowfocus to the register/alias fields in the final app.
But for testing just leave as is. Hope this helps - http://wiki.appcelerator.org/display/guides/Push+Notifications