SvelteKit - get protocol - sveltekit

Is it possible in SvelteKit to get protocol of current page (HTTP or HTTPS)?
Something like:
import {page} from '$app/stores';
console.log($page.protocol);
So far, I only see:
{
host: 'localhost:3000',
path: '/projektDetalji',
query: URLSearchParams { 'id' => '1' },
params: {}
}

You could use browser to make sure you are running in browser, then grab protocol from window.location.protocol.
<script context="module">
import { browser } from "$app/env"
if (browser) {
console.log(window.location.protocol);
}
</script>
From $app/env module section of sveltekit docs

Here's one way...
Within the handle() function of your hooks.server.js, the protocol can be gleaned using event.url?.protocol and then passed into the rest of your application via the locals object. For example...
/** #type {import('#sveltejs/kit').Handle} */
export async function handle({ event, resolve }) {
// Store the protocol in the locals object, which is passed
// in to handlers in +server.js and server load() functions
event.locals.protocol = event.url?.protocol;
return await resolve(event);
}
Later, retrieve it from the locals object in your +page.server.js files...
export async function load({params, locals}) {
if (locals.protocol) {
console.log ('Protocol is ' + locals.protocol);
}
}

Related

Sveltekit call API from server and pass the data to the front-end

I'm learning Sveltekit and i've been stuck on passing data from backend to frontend. I have a 3rd party API that i want to call and send back the results that gives me the bearer needed for all the other API calls.
The problem is that the CORS policys of this server (that i have no control over) isn't configured well and i can't call the API from the browser.
So i wanted to call it from the backend and send the result to the front, what I did is a "+page.server.ts" file with the API call in the "load" function and puts the results in a store that i created in the stores.ts file :
import { writable } from 'svelte/store';
export const token = writable('');
So in the front (+page.svelte) I just imported the token from the store and showed it :
<script>
import { token } from "../stores";
</script>
<h1>{$token}</h1>
And it works for a second before the token is overriden with an empty string and i don't get why.
Do you have any idea of what could cause this ?
Feel free to ask for more informations if needed, because i'm lost right now
You cannot access a svelte store from within a server file.
To call a api from +page.server.js. Create a folder in your routes and add a +page.server.js file and add the following:
/** #type {import('./$types').PageServerLoad} */
export async function load({ fetch }) {
const res = await fetch('https://api.agify.io/?name=bella', {
method: 'GET'
});
const data = await res.json();
console.log(data);
return {
props: {
data: data
}
};
}
Then create a +page.svelte with the following code:
<script>
/** #type {import('./$types').PageData} */
export let data;
console.log(data);
let name = data.props.data.name;
let age = data.props.data.age;
</script>
<h1>
{name} <!-- bella -->
{age} <!-- the age -->
</h1>
SvelteKit docs have info that could be of use. SvelteKit docs loading data

SvelteKit - /routes/a/+page.server.ts fetch('/b/') url confusion, version #sveltejs/kit#1.0.0-next.512

When I try to fetch('/b/') within the load function of /routes/a/+page.server.ts it refuses to accept local URL references.
Instead of being able to do
/b/
I have to use url:
http://localhost:3000/b/
Because the fetch() call refuses to accept the url (error: "Failed to parse URL"). I'm trying to consume my own api to reuse code. I thought SvelteKit fetch was supposed to support these local routes for api calls?
The example in documentation: https://kit.svelte.dev/docs/routing
Shows +page.svelte calling url '/api/add/' from fetch(), but not from within +page.server.ts - is there some reason they would not allow the same convention?
Thank you.
SvelteKit developers got back to me and indicated that there are two choices of fetch(url) function.
// /src/routes/test/[param0]/[param1]/+page.server.ts
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ params }) => {
// ERROR: this will fail with URL parsing
let fetchResult = fetch('/api/target/');
}
SvelteKit aware fetch passed as load function parameter:
export const load: PageServerLoad = async ({ params, fetch }) => {
// NOTE: fetch was passed in as a parameter to this function
let fetchResult = fetch('/api/target/');
}
Confusing!
When I have an internal API route I want to hit within my sveltekit application, I structure it as so:
├src
|├routes
||├api
|||├example
||||├+server.js
Now, elsewhere in the app, you can hit the route like so using the fetch api:
let res = await fetch("/api/example")
refer to this section of the SvelteKit docs for a better understanding:
https://kit.svelte.dev/docs/routing

react-fine-uploader to authenticate in the backend with redux-token-auth

In my stack I am using redux-token-auth to authenticate users with my rails backend (devise_token_auth). In my app I need to allow authenticated users to upload images, for this I'm using react-fine-uploader.
My problem is that I'm not seeing a way to have ract-fine-uploader to POST the images in an authenticated way. and in general how to use redux-token-auth to upload data to my backend with authentication.
I found that redux-token-auth stores authentication tokens in the localStorage, so I'm kinda able to retrieve it and authenticate my requests. Though I don't like accessing such data directly with a localStorage.get("access-token") (It's written by the package, it just seems fair to use the package to handle it).
Also with react-fine-uploader the response object doesn't contain the headers from the server response, so I'm not sure on how to get the new tokens to store them.
Here's the code I got so far:
my ImagesUploader:
import React from "react";
import PropTypes from "prop-types";
import FineUploaderTraditional from "fine-uploader-wrappers";
import Gallery from "react-fine-uploader";
import { backend } from "../../libs/itemTools";
import "react-fine-uploader/gallery/gallery.css";
const ImagesUploader = props => {
const uploader = new FineUploaderTraditional({
options: {
multiple: false,
validation: {
itemLimit: 1
},
request: {
endpoint: backend.createImage,
customHeaders: {
"access-token": localStorage.getItem("access-token"),
"token-type": localStorage.getItem("token-type"),
client: localStorage.getItem("client"),
uid: localStorage.getItem("uid")
}
},
session: {
endpoint: backend.loadImages(props.itemId)
},
deleteFile: {
enabled: true,
endpoint: backend.deleteImage(props.itemId)
},
cors: {
expected: true
},
callbacks: {
onComplete: (id, name, response, xhr) => {
if (response.success) {
response.image.id;
//TODO save new access-token
// ####### THIS DOESN'T work, #########
//fine-uploader doesn't include headers in the response object.
localStorage.setItem("access-token", response.headers["access-token"]);
localStorage.setItem("token-type", response.headers("token-type"));
localStorage.setItem("client", response.headers(client));
localStorage.setItem("uid", response.headers(uid));
} else {
// [...]
}
},
onSessionRequestComplete: (...params) => {
console.log(
"onSessionRequestComplete: " + JSON.stringify(params, 0, 2)
);
}
}
}
});
return (
<div id="upload-area">
<Gallery uploader={uploader} />
</div>
);
};
ImagesUploader.propTypes = {
userId: PropTypes.number.isRequired,
itemId: PropTypes.number.isRequired
};
export default ImagesUploader;
It seems strange to me that redux-token-auth packages doesn't account for authenticated backend calls, and that fine-uploader doesn't give access to the response headers..
Is there maybe something I'm missing?
From taking a look at redux-token-auth, it expects to handle all auth calls and doesn't give you an escape hatch in the code - so yanking the localstorage seems like a prudent thing to do there. You can see in the code that it sets it for every request: https://github.com/kylecorbelli/redux-token-auth/blob/8c5a8fe573918d406a733ca1b21c0b4349f137ab/src/actions.ts#L160
As for fine-uploader it looks like you can grab the rawheaders by using xhr.response
https://github.com/FineUploader/fine-uploader/blob/master/client/js/traditional/traditional.xhr.upload.handler.js#L59
The response variable that you get back has been JSON parsed via the qq variable you pass in: https://github.com/FineUploader/fine-uploader/blob/master/client/js/traditional/traditional.xhr.upload.handler.js#L109

Error: User credentials required in Google Cloud Print API

I'm trying to use Google Cloud Print(GCP) API, but I can't make it works.
Maybe I've understood bad the workflow because is the first time I'm using the google api, please help me to understand how to make it works.
Initial considerations:
I'm trying to implement it in reactJS, but It is indifferent because the logic to make GCP works is independent of the technology. Then you also can help me understand the workflow.
What exactly I want:
To make my first test, I am looking to get all information about my printer.
What I did:
I created a project in: https://console.developers.google.com
Inside the project created, I created a credential:
create credentials -> OAuth client ID
And I chose Application type: Web, and also configure the restrictions to source and redirection to my localhost.
Manually in https://www.google.com/cloudprint, I added my printer, I made a test printing a PDF and was OK.
I created a project in reactJS to get the information of my printer I've added.
Component:
Explanation:
I'm using a component react-google-login to obtain easily the user accessToken: https://github.com/anthonyjgrove/react-google-login
This component only obtains the access token and save it in localStorage, in a variable called googleToken and it draws a button to call a function to obtain the information about the printer.
code:
import React, { Component } from 'react'
import GoogleLogin from 'react-google-login';
import { connect } from 'react-redux'
import { getPrinters } from '../actions/settings'
class Setting extends Component {
responseGoogle(response) {
const accessToken = response.accessToken
localStorage.setItem('googleToken', accessToken)
}
render() {
return (
<div>
<GoogleLogin
clientId="CLIENT_ID_REMOVED_INTENTIONALLY.apps.googleusercontent.com"
buttonText="Login"
onSuccess={this.responseGoogle}
onFailure={this.responseGoogle}
/>
<button
onClick = {() => {
this.props.getPrinters()
}}
>test printer</button>
</div>
)
}
}
const mapStateToProps = state => {
return {
state: state
}
}
const mapDispatchToProps = dispatch => {
return {
getPrinters() {
dispatch(getPrinters())
}
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(Setting)
Action or Function to get information printer:
Explanation:
I'm passing the parameter printerid to get information about that printer.
In authorization, I'm using OAuth ... because in the documentation says that(second paragraph).: https://developers.google.com/cloud-print/docs/appInterfaces
The next two headers I wrote it because I tried solutions as:
Google Cloud Print API: User credentials required
Google Cloud Print User credentials required
code:
import axios from 'axios'
axios.defaults.headers.common['Authorization'] = 'OAuth ' + localStorage.getItem('googleToken')
axios.defaults.headers.common['scope'] = 'https://www.googleapis.com/auth/cloudprint'
axios.defaults.headers.common['X-CloudPrint-Proxy'] = 'printingTest'
const getPrinters = () => {
return () => {
return axios.get('https://www.google.com/cloudprint/printer'
, {
params: {
printeid: 'PRINTER_ID_REMOVED_INTENTIONALLY'
}
}
)
.then(response => {
console.log('response of google cloud print')
console.log(response)
})
}
}
export { getPrinters }
Error:
After all explained before, I got the next error:
User credentials required
Error 403
Note:
I'm using CORS plugin by recommendation of:
Chrome extensions for silent print?
because initially, I had cors error.
Any suggestion or recommendation would be very useful, thanks.
I've resolved my problem, my main problem about User Credential required were because I was using the incorrect access token and It was because I was getting the access token incorrectly.
I'm going to explain my whole solution because there are few examples of codes with this API.
Solutions:
The steps described were Ok until the fourth step where I used the external component react-google-login to trying to get the access token, instead I used googleapis module: Link Github googleapis
Also to avoid CORS problem(and not use CORS chrome plugin) I wrote the requests to Google API in server side.(NODEJS)
I had also a problem in the frontend when I tried to generate a popup to give permission for printer(problems about CORS), my solution was to use this very simple module for authentication: Link Github oauth-open
General scheme:
Explanation:
Knowing I have all data described in my question post(until the third step).
Authentication:
The next step in getting a URL and use it to the user can authenticate.
As I said before I used the module oauth-open in the frontend to generate the popup and only this module need the URL. To get the URL in the backend I used the endpoint /googleurl, where here I used the method generateAuthUrl of the module googleapis to generate the URL.
After that In the frontend, I got the authentication_code(that returned the module oauth-open), I send It to my endpoint /googletoken and here I process the authentication_code to generate access token, refresh token and expiration date with the method getToken of the module googleapis. Finally, these data are stored in the database.
Print:
For print, since the frontend, I send what data I need send to the printer. I used my endpoint /print
In the backend endpoint, my logic was the next:
Recover tokens and expiration date from database, with the expiration date check if the token has expired, and if It has already expired then gets another token and replace the old access token with the new one, replacing also with the new expiration date, to obtain this new data only is necessary call to method refreshAccessToken of module googleapis.Note: the refresh token never expires.
After having the access token updated, use it to send data to the printer with Google route(.../submit)
Code:
All the next codes are in only 1 file
Some data as validation, static variables, error handler, etc, has been removed to better understanding.
Route get URL authentication.
const express = require('express');
const google = require('googleapis');
const router = express.Router();
var OAuth2 = google.auth.OAuth2;
const redirect_url = 'http://localhost:3001/setting'; //Your redirect URL
var oauth2Client = new OAuth2(
'CLIENT ID', //Replace it with your client id
'CLIEND SECRET', //Replace it with your client secret
redirect_url
);
var url = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: 'https://www.googleapis.com/auth/cloudprint'
});
router.get('/googleurl', (req, res) => {
return res.status(200).send({
result: { googleURLToken: url }
});
});
To get tokens using the authentication code and save these in the database.
const Setting = require('../models/setting'); // My model(Mongoose)
router.post('/googletoken', (req, res) => {
oauth2Client.getToken(req.body.code, function (err, tokens) {
oauth2Client.credentials = tokens;
// If refresh token exits save it
// because the refresh token it returned only 1 time! IMPORTANT
if (tokens.hasOwnProperty('refresh_token')) {
let setting = new Setting();
setting.refreshTokenGoogle = tokens.refresh_token;
setting.expirationTokenGoogle = tokens.expiry_date;
setting.tokenGoogle = tokens.access_token;
setting.save()
.then((settingCreated) => {
return res.status(200).send({
message: 'OK'
});
})
}
});
});
To print
const axios = require('axios');
const moment = require('moment');
router.post('/print',async (req, res) => {
const tickeProperties = {
'version': '1.0',
'print': {
'vendor_ticket_item': [],
'color': { 'type': 'STANDARD_MONOCHROME' },
'copies': { 'copies': 1 }
}
};
const accessToken = await getTokenGoogleUpdated();
axios.get(
'https://www.google.com/cloudprint/submit',
{
params: {
printerid : printerID, // Replace by your printer ID
title: 'title printer',
ticket: tickeProperties,
content : 'print this text of example!!!',
contentType: 'text/plain'
},
headers: {
'Authorization': 'Bearer ' + accessToken
}
}
)
.then(response => {
return res.status(200).send({
result: response.data
});
})
}
);
async function getTokenGoogleUpdated() {
return await Setting.find({})
.then(async setting => {
const refreshTokenGoogle = setting[0].refreshTokenGoogle;
const expirationTokenGoogle = setting[0].expirationTokenGoogle;
const tokenGoogle = setting[0].tokenGoogle;
const dateToday = new Date();
// 1 minute forward to avoid exact time
const dateTodayPlus1Minute = moment(dateToday).add(1, 'm').toDate();
const dateExpiration = new Date(expirationTokenGoogle);
// Case date expiration, get new token
if (dateExpiration < dateTodayPlus1Minute) {
console.log('Updating access token');
oauth2Client.credentials['refresh_token'] = refreshTokenGoogle;
return await oauth2Client.refreshAccessToken( async function(err, tokens) {
// Save new token and new expiration
setting[0].expirationTokenGoogle = tokens.expiry_date;
setting[0].tokenGoogle = tokens.access_token;
await setting[0].save();
return tokens.access_token;
});
} else {
console.log('Using old access token');
return tokenGoogle;
}
})
.catch(err => {
console.log(err);
});
}
I hope It helps you if you want to use Google Cloud Print to not waste a lot of time as I did.
The important part there is a scope https://www.googleapis.com/auth/cloudprint which is not obvious and took one day for me to figure out.

FeathersJS custom API method that retrieves enum Type, to fill a Dropdown in React

So I'm trying to fill a select component with a enum type from mongoose
In my user service the schema looks something like :
firstName: { type:String, required: true },
...
ris:{type: String, default: 'R', enum:['R', 'I', 'S']},
In my feathers service I can access the Model with "this.Model"
so in any hook I can do:
this.Model.schema.path('ris').enumValues); //['R','C','I']
and I get the values from the enum type.
Now since I can't create custom API methods other that the officials ones
Feathers calling custom API method
https://docs.feathersjs.com/clients/readme.html#caveats
https://docs.feathersjs.com/help/faq.html#can-i-expose-custom-service-methods
How can I create a service method/call/something so that I can call it in my
componentDidMount(){ var optns= this.props.getMyEnumsFromFeathers}
and have the enum ['R','C','I'] to setup my dropdown
I'm Using React/Redux/ReduxSaga-FeathersJS
I'd create a service for listing Enums in the find method:
class EnumService {
find(params) {
const { service, path } = params.query;
const values = this.app.service(service).Model.schema.path(path).enumValues;
return Promise.resolve(values);
}
setup(app) {
this.app = app;
}
}
app.use('/enums', new EnumService())
Then on the client you can do
app.service('enums').find({ query: {
service: 'myservice',
path: 'ris'
}
}).then(value => console.log('Got ', values));
I was trying to use this code, but, it does not work like plug and play.
after some play with the app service I figured out the code below
async find(params) {
const { service, path } = params.query;
const values = await this.app.service(service).Model.attributes[path].values;
return values || [];
}
setup(app) {
this.app = app;
}
I am not sure if it is a thing of what database is been used, in my case I am in development environment, so, I am using sqlite.

Resources