Supabase Backend as a Service · درس

إدارة جلسات المستخدمين وملفاتهم الشخصية

تعلّموا إدارة جلسات المستخدمين واسترداد بياناتهم الوصفية وتحديث ملفاتهم الشخصية بأمان داخل تطبيقكم.

الدرس 3 من 412 خطوة

إدارة جلسات المستخدمين وملفاتهم الشخصية درس مجاني في Supabase Backend as a Service على CoddyKit. هذا هو الدرس 3 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Supabase Backend as a Service، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Supabase Backend as a Service 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

User Sessions & Profiles Intro

Welcome! In this lesson, we'll dive into managing user sessions and updating user profiles securely with Supabase.

When a user logs in, Supabase creates a session. This session keeps track of who the user is and ensures they remain authenticated across requests.

A user's profile often includes details like their name, avatar, or preferences. Supabase helps you store and manage this data.

Accessing the Current Session

To interact with the currently logged-in user, you first need to access their session. Supabase stores session tokens securely, usually in local storage or cookies.

You can retrieve the active session using supabase.auth.getSession(). This call returns a Promise that resolves with the session data.

import { createClient } from '@supabase/supabase-js';

const supabaseUrl = 'YOUR_SUPABASE_URL';
const supabaseAnonKey = 'YOUR_SUPABASE_ANON_KEY';

const supabase = createClient(supabaseUrl, supabaseAnonKey);

async function getCurrentSession() {
  const { data: { session }, error } = await supabase.auth.getSession();

  if (error) {
    console.error('Error getting session:', error.message);
    return;
  }

  if (session) {
    console.log('Current session:', session);
    console.log('User ID:', session.user.id);
    console.log('User email:', session.user.email);
  } else {
    console.log('No active session.');
  }
}

getCurrentSession();

Exploring the User Object

The session object contains a user property, which holds important information about the authenticated user.

Key properties within the user object include:

  • id: A unique identifier for the user.
  • email: The user's email address.
  • created_at: When the user account was created.
  • user_metadata: A JSON object for custom profile data.

We often store things like a user's display name or avatar URL in user_metadata.

Accessing User Profile Data

The user_metadata field within the user object is where you can store custom profile information. This data is part of the authentication service, not your main database tables.

It's a flexible JSON object, allowing you to store various details directly tied to the user's authentication record.

import { createClient } from '@supabase/supabase-js';

const supabaseUrl = 'YOUR_SUPABASE_URL';
const supabaseAnonKey = 'YOUR_SUPABASE_ANON_KEY';

const supabase = createClient(supabaseUrl, supabaseAnonKey);

async function getUserProfile() {
  const { data: { user }, error } = await supabase.auth.getUser();

  if (error) {
    console.error('Error getting user:', error.message);
    return;
  }

  if (user) {
    console.log('User ID:', user.id);
    console.log('Email:', user.email);
    console.log('User Metadata:', user.user_metadata);

    // Access specific metadata
    const displayName = user.user_metadata?.display_name || 'Guest';
    console.log('Display Name:', displayName);
  } else {
    console.log('No user logged in.');
  }
}

getUserProfile();

Modifying User Profile Data

To update a user's profile information, specifically their user_metadata, you use the supabase.auth.updateUser() method.

You pass an object to this method, with a data property that contains the new user_metadata. Supabase will merge this new data with any existing metadata.

  • Security Note: Always ensure you have appropriate Row-Level Security (RLS) policies in your database if you store sensitive profile data there. For user_metadata, Supabase handles its security.

Live Update User Metadata

Let's update a user's display name and add an avatar URL to their user_metadata.

Remember, the data property is for fields like user_metadata. Other fields like email or password are updated differently.

import { createClient } from '@supabase/supabase-js';

const supabaseUrl = 'YOUR_SUPABASE_URL';
const supabaseAnonKey = 'YOUR_SUPABASE_ANON_KEY';

const supabase = createClient(supabaseUrl, supabaseAnonKey);

async function updateProfile() {
  // This assumes a user is already logged in
  const { data: { user }, error: getUserError } = await supabase.auth.getUser();

  if (getUserError || !user) {
    console.error('No user logged in or error getting user:', getUserError?.message);
    return;
  }

  const { data, error } = await supabase.auth.updateUser({
    data: {
      display_name: 'Coddy Learner',
      avatar_url: 'https://example.com/coddy_avatar.png'
    }
  });

  if (error) {
    console.error('Error updating user metadata:', error.message);
  } else {
    console.log('Profile updated successfully!', data.user.user_metadata);
  }
}

// In a real app, you'd call this after a user logs in
// or on a profile settings page.
// For this example, assume a user is logged in.
updateProfile();

Changing Email & Password

Besides user_metadata, users can also update their email address and password.

  • Updating Email: Requires a confirmation flow. The user receives an email with a link to confirm the new address.
  • Updating Password: Directly changes the password. For security, always prompt the user to re-authenticate or enter their current password before allowing a change.

These are also handled via supabase.auth.updateUser(), but you pass the email or password property directly, not within the data object.

Ending a User Session

When a user wants to log out, you need to terminate their active session. This securely removes their authentication tokens and prevents further access to protected resources.

The supabase.auth.signOut() method handles this process for you. It invalidates the session and clears any stored tokens.

After signing out, it's good practice to redirect the user to a public page (e.g., login screen) and clear any client-side application state related to the user.

Logging Out a User

This simple code snippet demonstrates how to sign out a user. After this, their session will be invalid.

import { createClient } from '@supabase/supabase-js';

const supabaseUrl = 'YOUR_SUPABASE_URL';
const supabaseAnonKey = 'YOUR_SUPABASE_ANON_KEY';

const supabase = createClient(supabaseUrl, supabaseAnonKey);

async function signOutUser() {
  const { error } = await supabase.auth.signOut();

  if (error) {
    console.error('Error signing out:', error.message);
  } else {
    console.log('User signed out successfully!');
    // You might redirect the user here
    // window.location.href = '/login';
  }
}

// Call this function when a user clicks a "Logout" button
signOutUser();

Security for Profile Management

When managing user profiles, security is paramount:

  • Row-Level Security (RLS): If you store profile data in separate database tables (e.g., a profiles table), always implement RLS to ensure users can only read/update their own data.
  • Client-side Validation: While important for user experience, never rely solely on client-side validation. Always validate data on the server (e.g., using Edge Functions or database constraints).
  • Sensitive Data: Avoid storing highly sensitive information directly in user_metadata. For truly sensitive data, consider encrypted storage or dedicated, strictly controlled database tables.

Profile Update Check

You want to update a user's display name and favorite color, which are stored in their custom profile data.

Which method and property should you use with the Supabase client library?

Session & Profile Recap

Great job! You've learned how to manage user sessions and profiles:

  • Accessed the current user's session and user object.
  • Retrieved and updated custom user_metadata using supabase.auth.updateUser({ data: {...} }).
  • Understood how to handle email/password updates.
  • Implemented user logout with supabase.auth.signOut().
  • Reviewed key security considerations for profile data.

Next, you might explore integrating social logins or advanced RLS for profile tables!

البدء مجانًا

تعلم Supabase Backend as a Service مع معلم ذكاء اصطناعي — مجانًا

اكتب وقم بتشغيل أكوادك الفعلية في المتصفح، واحصل على مساعدة فورية من معلم ذكاء اصطناعي متاح 24/7، واستمر من حيث توقفت على الويب أو في التطبيق.

الدورات
11
الدروس
40

الأسئلة الشائعة

هل درس «إدارة جلسات المستخدمين وملفاتهم الشخصية» مجاني؟

نعم — نص درس «إدارة جلسات المستخدمين وملفاتهم الشخصية» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Supabase Backend as a Service، انتقل إلى CoddyKit PRO. تتضمن دورة Supabase Backend as a Service 4 دروس في المجموع.

ماذا ستتعلم في «إدارة جلسات المستخدمين وملفاتهم الشخصية»؟

تعلّموا إدارة جلسات المستخدمين واسترداد بياناتهم الوصفية وتحديث ملفاتهم الشخصية بأمان داخل تطبيقكم. تتمرن على Supabase Backend as a Service مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Supabase Backend as a Service؟

لا تُشترط خبرة سابقة. Supabase Backend as a Service على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 3 من أصل 4.

كم من الوقت يستغرق درس «إدارة جلسات المستخدمين وملفاتهم الشخصية»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Supabase Backend as a Service هذا؟

نعم. كل درس في Supabase Backend as a Service يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. تسجيل المستخدمين بالبريد الإلكتروني وكلمة المرور
  2. تسجيل الدخول الاجتماعي (موفرو OAuth)
  3. إدارة جلسات المستخدمين وملفاتهم الشخصية
  4. إعادة تعيين كلمة المرور والمصادقة عبر الروابط السحرية
← العودة إلى Supabase Backend as a Service