Add aditional user information when signup supabase - postgresql

I am trying to add additional data in a user record in supabase, I have created a trigger that is called after a record has been inserted in auth user that should add the user id and username in the profiles table. This happens but it doesn't add the user name, it's still null in the profiles table. That data is supposed to go in the raw_user_meta_data column but it still doesn't add in the column
Trigger function:
BEGIN
INSERT INTO public.profiles(id, username)
VALUES (
NEW.id,
NEW.raw_user_meta_data -> 'username'
);
RETURN NEW;
END;
Front:
const createNewUser = async() => {
const { username, email, password } = credentials;
await supabase.auth.signUp({
email: email,
password: password,
data: {
"username": 'hello'
}
});
}

Just to follow up. Maybe this is the change with supabase v2 and supabasejs update, but now it seems to work with one argument, but slightly different than you had it in first post. Here is the link:
https://supabase.com/docs/reference/javascript/auth-signup#sign-up-with-additional-user-metadata
and the code:
const { data, error } = await supabase.auth.signUp({
email: userEmail.value,
password: password,
options: {
data: {
user_name: userName.value,
},
},
});

I found the solution reading over there, in case it helps anyone. My mistake was that in the signUp function I passed only 1 argument that had included the additional data that would be included in the trigger function. However, this signUp function must be passed 2 objects as arguments and it is this second argument that is passed that saves the object with the username extracted from the function in the front in the raw_user_meta_data column.
As additional data that can help you in the search for the error. You can know what the logs of the authentication process print. You can also insert a record directly in auth.users so you can see why it does not add additional data and be able to review the logs, I attach an example:
insert into auth.users(id, email, encrypted_password, raw_user_meta_data)
values (
'eb23060d-71ea-4112-a1c7-203d6f87fa2d',
'example#mail.com',
'$2y$10$WpAA2remsZRnZivgRaM9L.1BcjvAtUa966AICxv1RGte68BICsZkS',
'{"username": "user_example"}'
)
Final solution:
const { user, session, error } = await supabase.auth.signUp(
{
email: 'example#email.com',
password: 'example-password',
},
{
data: {
username: 'John'(variable)
}
}
)

Related

Postgres leftJoinAndMapMany Query using TypeORM (property undefined)

I've been using PostgreSQL using TypeORM and I've got some problem at getting Follower table and check if the user is in that table.
Here's my code:
// queryTest.ts
data = await getRepository(User)
.createQueryBuilder('user')
.leftJoinAndMapMany('user.id', Post, 'post', 'post.userId = user.id')
.leftJoinAndMapMany('post.id', Follow, 'follow', 'follow.userId = user.id')
// Post author's follower
.where(new Brackets(qb => {
qb.where('post.publicScope = :follower', { follower: 'Follower' })
.andWhere('post.userId = follow.followeeId')
.andWhere(':myId = follow.userId', { myId: user.id })
}))
.getMany()
And when I try to send this query, I get { } (supposed to get some user, post, follower data)
I have User, Post, Follow entities and I'm trying to get this data:
my followee's post that he set as 'Follower' (suppose I'm following some celebrity and he posted something that is just for followers, and I'm trying to get that data)
OR I'm also thinking of makig 2 entities (Follower, Followee) that have ManyToMany relation. Could any body help me with this?
The problem is that you are mapping Post and Follow to the wrong property, the first param that you gave 'user.id' is wrong, this param must be the property that you want to save the Post or Follow in, so it should be something like this:
data = await getRepository(User)
.createQueryBuilder('user')
.leftJoinAndMapMany('user.post', Post, 'post', 'post.userId = user.id')
.leftJoinAndMapMany('post.follow', Follow, 'follow', 'follow.userId = user.id')
.where(new Brackets(qb => {
qb.where('post.publicScope = :follower', { follower: 'Follower' })
.andWhere('post.userId = follow.followeeId')
.andWhere(':myId = follow.userId', { myId: user.id })
}))
.getMany()
Note that you MUST create these properties (post, follow) in the User entity.
However, if you used OneToMany or ManyToOne or OneToOne relations in there, you shouldn't use leftJoinAndMapMany, just use leftJoinAndSelect

Seed with relation in knex

Hi guys I'm trying to seed my data with knex and knex cli
I have 2 models: User & User Profile
User
CREATE TABLE users(
id SERIAL PRIMARY KEY NOT NULL,
name TEXT,
screenname TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
User Profile
CREATE TABLE userProfile(
email TEXT,
password TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
user_id INTEGER,
PRIMARY KEY (user_id),
FOREIGN KEY (user_id) REFERENCES users (id)
)
Note that user Profile points to User and its 1:1 relationship
Os I'm trying to insert my users and along with that, to insert their profile data
I have created seed file like this:
exports.seed = function(knex) {
// Deletes ALL existing entries
return knex('users').del()
.then(function () {
return knex('userprofile').del();
})
.then(() => {
return knex('authenticationproviders').del();
})
.then(function () {
return knex('users')
.insert([
{
name: 'john',
screenname: 'admin'
},
{
name: 'stephan',
screenname: 'maras'
},
])
})
.then(function (users) {
// here insert profile info about user
// but user param doesn't contain userIds that are created
})
};
Here is how my profiles array looks:
[{
email: 'test#gmail.com',
user_id: 1, // this should be from existing user
password: 'pass1'
},
{
email: 'test2#gmail.com',
user_id: 2, // this should be from existing user that was created
password: 'pass2'
}]
Is there anyway how can I get userId from existing user, since users param is does not contain array of created users ??

How to add users manually to Meteor.users collection?

I am having super user which I added manually and this user can other users manually through a form I give him.
lets say if I save the input entered by the user like the code shown below:
Session.set('name', t.find('#name').value);
Session.set('password', t.find('#pass').value);
Session.set('email', t.find('#email').value);
how do I store those values in those sessions in the Meteor.users, after checking that there is no match in the email and username?
and how do I encrypt the password before storing it in my database?
This code when called from the client side as:
Meteor.call('createUser','someemail#gmail.com','password123',function(err,res){
.....
})
creates a user in Meteor.users collection with the id given below in the method
Meteor.methods({
createUser(email,password){
check(email,String);
check(password,String);
let id = Accounts.createUser({
email: email,
password: password,
profile: {} //anything you like to add to profile.
})
}
})

MongoDB Duplicate Entry

I have the following schema
var customerSchema = new Schema({
customerID: String,
phoneNumber: String
})
customerSchema.path('customerID').validate(function (customerID, next) {
Customer.findOne({customerID: customerID}, function (err, user) {
if (err) {
return next(false);
}
if (!user) {
return next(true); //Valid
} else {
return next(false);
}
});
}, 'customerID Already Exists');
This works perfectly when I was trying to add the same customerID. It will not let me. But previously I tried to press the ADD button at the same time on different computer. Somehow the same customerID gets added.
How to prevent such edge cases from happening? I am using MongoLab. Does the latency present a big problem?
It's very possible to have this type of behavior:
Press add button on computer1
Press add button on computer2
Validation occurs for the first add and the customer does not exist
Validation occurs for the second add BEFORE the first insert is done and the customer does not yet exist
Both adds succeed
You can put a unique constraint on the field at the database level to prevent this - https://docs.mongodb.org/v3.0/tutorial/create-a-unique-index/
Depending on your needs, you can also have an "upsert" that updates or inserts a new record. In your case, if you're concerned about two users creating a new user with the same ID, just put an index on it at the database.

bookshelf js save() command not updating rows in postgresql db

JS beginner trying to get a PostgreSQL DB talking to express.js through bookshelf.js.
github: https://github.com/duskyshelf/bookers-academy/blob/master/booker.js
var knex = require('knex')({
client: 'pg',
connection: "postgres://localhost/bookers"
});
var bookshelf = require('bookshelf')(knex);
var User = bookshelf.Model.extend({
tableName: 'users'
});
var bob = new User({id: 2});
bob.save()
bookshelf.js seems unable to add any content to the db.
Current error message is: "Unhandled rejection CustomError: No Rows Updated'
When you create your model providing your own id, like in
var bob = new User({id: 2});
Bookshelf assumes it is an update operation, not an insertion. It sets the internal isNew attribute to false, and when save() is invoked, instead of INSERT INTO user(id, ...) VALUES (2, ...);, it executes UPDATE user ... WHERE id = 2;.
If there is no user with id = 2 the update will almost silently DO NOTHING.
To force an insert you must change the save() to:
bob.save(null, {method: 'insert'});
Bookshelf save() documentation describes this behavior.
Did you create a User table using knex? One potential problem I can think of is that you do not have any logic that actually creates the table for your Postgres DB. Here is some sample code that will create a table in your database if it doesn't yet exist.
bookshelf.knex.schema.hasTable('User').then(function(exists) {
if(!exists) {
bookshelf.knex.schema.createTable('User'), function(user) {
user.increments('id').primary();
user.timestamps();
}).then(function(table){
console.log('Created Table:', table);
});
}
});
new User({id: 2}).
save().
then((model) => {
res.json({ success: true });
});
No no! new User returns a PROMISE! You can't use it like that.
Try
new User().save()