i'm trying to add team with auth user i have route with middleware('auth')
But i can't get auth user. I'm new in node.js so i think its really easy problem but really can't see how can i solve this problem...
public async store({ request, auth, response }: HttpContextContract) {
const user = auth.user
const validations = await schema.create({
name: schema.string({}),
size: schema.string({}),
})
const data = await request.validate({ schema: validations })
const team = await Team.create(data)
console.log(Object.keys(team));
return response.created(team)
}
You need to be sure that the user is authenticated to use the auth.user object.
add this
await auth.use('web').authenticate()
public async store({ request, auth, response }: HttpContextContract) {
await auth.use('web').authenticate()
const user = auth.user
const validations = await schema.create({
name: schema.string({}),
size: schema.string({}),
})
const data = await request.validate({ schema: validations })
const team = await Team.create(data)
console.log(Object.keys(team));
return response.created(team)
}
Related
I obtained a service account JSON file and also attached domain wide delegation permissions to that service account. Next I set the service account file path using the GOOGLE_APPLICATION_CREDENTIALS env variable. After that I tried to access google groups of the domain like this:
import { google } from 'googleapis';
const admin = await google.admin({
version: 'directory_v1',
});
const groupsResponse = await admin.groups.list({
domain: process.env.GOOGLE_DOMAIN,
});
This gives me the following error:
Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
What am I missing here?
You need to apply the client to the service object.
auth: client
you may want to check out using-the-keyfile-property
Try this
const google = require("googleapis").google;
const SRVC_ACCOUNT_CREDS = require('./keys.json');
const getClient = async (scopes: string[], user: string)=>{
const auth = new google.auth.GoogleAuth({
credentials: SRVC_ACCOUNT_CREDS,
scopes: scopes
});
const client = await auth.getClient();
client.subject = user;
return client;
};
const listUsers = async (query = "", limit = 500, pageToken = null, user, fields, getAll = false)=>{
const scopes = ["https://www.googleapis.com/auth/admin.directory.user"];
const client = await getClient(scopes, user);
const service = google.admin({version: "directory_v1", auth: client});
const result = {
users: [],
nextPageToken: ""
};
if(!fields) {
fields = "users(name.fullName,primaryEmail,organizations(department,primary,title),thumbnailPhotoUrl),nextPageToken";
}
do{
const request = await service.users.list({
customer: "my_customer",
fields: fields,
orderBy: "givenName",
maxResults: limit,
pageToken: pageToken,
query: query,
viewType: "admin_view"
});
pageToken = getAll ? request.data.nextPageToken : null;
const users = request.data.users;
if(users && users.length){
result.users.push(...users);
result.nextPageToken = request.data.nextPageToken;
}
} while(pageToken);
return result;
};
This is my code:
exports.saveUserEmail = functions.region('europe-central2').auth.user().onCreate((user) => {
const email = user.email;
const uid = user.uid;
const dt = dateTime.create();
const formatted = dt.format("Y-m-d H:M:S");
return admin.firestore().collection('users').doc(uid).set({uid: uid, email: email, created_at: formatted});
});
and i tried do update like this:
exports.saveEditedEmail = functions.region('europe-central2').auth.user().updateUser((user, uid) => {
const email = user.email;
return admin.firestore().collection('users').doc(uid).set({uid: uid, email: email,});
})
Where is my mistake?
There isn't any onUpdate() auth trigger for Cloud functions. Instead your can create a callable function and call it directly from client side to update your user.
exports.addMessage = functions.https.onCall((data, context) => {
const { email } = data;
// update email in Firebase Auth and Firestore
});
Alternatively, you can directly update the document in Firestore if the user tries to update their own profile. You can setup the following security rules so a user can update their own profile only:
match /users/{userId} {
allow update: if request.auth.uid == userId;
}
userSchema.methods.generateAuthToken = async function() {
const user = this
const token = jwt.sign({_id:user._id.toString()},'thisisnewcourse')
return token}
const token = await User.generateAuthToken()
When I call the generateAuthToken(), its showing type error. Line 1 is showing error.
I think there is naming error, Try this.
userSchema.methods.generateAuthToken = async function() {
//try using Camel notation here(User(U with uppercase))
const User = this
const token = jwt.sign({_id:user._id.toString()},'thisisnewcourse')
return token}
const token = await User.generateAuthToken()
I'm not sure if you are calling generateAuthToken() method at schema or not.
when calling generateAuthToken() method it refers to the instance of the user model getting from request, not to the User it self. so wehn you create a schema first assign the methods to it and then pass this schema to your model.
Example: User model
const userSchema = new mongoose.Schema({
// your scehma
});
// assign methods to schema
userSchema.methods.generateAuthToken = async function() {
const user = this
const token = await jwt.sign({_id:user._id.toString()},'thisisnewcourse')
return token
}
// now pass this schema to User model
const User = mongoose.model('User', userSchema);
now call the method based on your logic.
// when calling generateAuthToken() method
const token = await user.generateAuthToken();
// here 'user' is the instance of the 'User model' which holds the request body data.
// if it's post request for authentication
e.g. let user = await User.findOne({ name: req.body.name });
Change:
const token = await User.generateAuthToken()
To:
const token = await user.generateAuthToken()
I try to create some API to external adobe stock.
Like in the title, first time i get query from Link router of undefined, but after reload page it work correctly. My
main page
<Link
href={{
pathname: "/kategoria-zdjec",
query: images.zdjecia_kategoria
}}
as={`/kategoria-zdjec?temat=${images.zdjecia_kategoria}`}
className={classes.button}>
</Link>
and my server
app
.prepare()
.then(() => {
server.get("/kategoria-zdjec", async (req, res) => {
const temat = await req.query.temat;
console.log(temat)
const url = `https://stock.adobe.io/Rest/Media/1/Search/Files?locale=pl_PL&search_parameters[words]=${temat}&search_parameters[limit]=24&search_parameters[offset]=1`;
try {
const fetchData = await fetch(url, {
headers: { ... }
});
const objectAdobeStock = await fetchData.json();
res.json(objectAdobeStock);
const totalObj = await objectAdobeStock.nb_results;
const adobeImages = await objectAdobeStock.files;
} catch (error) {
console.log(error);
}
});
and that looks like getInitialProps on page next page
Zdjecia.getInitialProps = async ({req}) => {
const res = await fetch("/kategoria-zdjec");
const json = await res.json();
return { total: json.nb_results, images: json.files };
}
I think it is problem due asynchronous.
I think this might be due to the fact that you are using fetch which is actually part of the Web API and this action fails when executed on server.
You could either use isomorphic-fetch which keeps fetch API consistent between client and server, or use node-fetch when fetch is called on the server:
Zdjecia.getInitialProps = async ({ req, isServer }) => {
const fetch = isServer ? require('node-fetch') : window.fetch;
const res = await fetch("/kategoria-zdjec");
const json = await res.json();
return { total: json.nb_results, images: json.files };
}
This problem is solved, the issue was in another part of my app, directly in state management, just created new variables, and pass to link state value.
currently I am using Express, Node.js, Graphql to build backend server,
I want to POST data into an online payment system, when I successfully used request to post data, I found that it can console an HTML body in my terminal, but what I want is the Graphql interface can redirect to the platform rather than just output the HTML body, what can I do to solve this problem? Here is my code for the reference.
Mutation: {
createPayment: async (parent, args, { models, user }) => {
const MerchantID = Merchantvalue;
const TotalAmt = await args.TotalAmt;
const ItemName = await args.ItemName;
const ChoosePayment = await args.ChoosePayment;
const PaymentType = payment value;
const TradeDesc = await args.TradeDesc;
const ReturnURL = returnurl;
const EncryptType = encry;
const MerchantTradeNo = await CheckMacValue.random;
const MerchantTradeDate = await CheckMacValue.datetime;
const TheCheckMacValue = await CheckMacValue.PaymentOnceValue(
MerchantID, PaymentType, TotalAmt, TradeDesc,
ItemName, ReturnURL, ChoosePayment, EncryptType,
);
const formData = {
MerchantID: MerchantID,
MerchantTradeNo: MerchantTradeNo,
MerchantTradeDate: MerchantTradeDate,
TotalAmount: TotalAmt,
ItemName: ItemName,
ChoosePayment: ChoosePayment,
PaymentType: PaymentType,
TradeDesc: TradeDesc,
ReturnURL: ReturnURL,
EncryptType: EncryptType,
CheckMacValue: TheCheckMacValue,
};
//In here I can successfully post data, but I want to redirect rather than just console the body in terminal.
request.post(
{ url: 'https://payment-stage.ecpay.com.tw/Cashier/AioCheckOut/V5', formData: formData },
function optionalCallback (err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log(body);
});
},
},
what you need to do is to pass the right response (code, message) to the client and handle that redirect logic on the client side (web, mobile, etc.)