CREATE OR REPLACE FUNCTION
  public.handle_new_user()
  RETURNS TRIGGER AS
  $$
  DECLARE name TEXT;
  BEGIN   
  IF new.raw_user_meta_data ->> 'name' IS NOT NULL
  THEN
    name = new.raw_user_meta_data ->> 'name';
  ELSE
    name = CONCAT (new.raw_user_meta_data ->> 'first_name', ' ', new.raw_user_meta_data ->> 'last_name');
  END IF;

  INSERT INTO public.profiles (id, name, email, avatar_url)
  VALUES (new.id, name, new.email, new.raw_user_meta_data ->> 'avatar_url');
  RETURN new;
END;
  $$ LANGUAGE plpgsql SECURITY DEFINER;