angular

supabase auth ( angular를 사용하여 회원가입, 로그인, 로그아웃 구현하기 )

호리둥절 2023. 4. 11. 16:05

 

https://supabase.com/docs/guides/auth

 

Auth | Supabase Docs

Need some help? Not to worry, our specialist engineers are here to help. Submit a support ticket through the Dashboard.

supabase.com

이전에 supabase를 알아보는 시간에 프로젝트를 만들어보았습니다.

https://develop-const.tistory.com/16

 

Supabase란?

정말 쉽고 간단하게 백앤드 서버를 구축할 수 있고, 비용도 firebase만큼 저렴하여 정말 강추드리는 서비스입니다. 물론 백앤드를 공부해야된다면 지양하겠지만, 간단하고 적은 비용, 노력으로 애

develop-const.tistory.com

이제 auth에 관한것을 구현해봅시다.

이번 포스팅은 angular를 알고있다는 가정하에 진행하겠습니다.

🔨 supabase설치하기

npm install @supabase/supabase-js

 

🍊 supabase.service.ts 생성하기

이전페이지에서 발급받은 api key와 url을 이용하여 SupabaseService라는 서비스파일을 생성할것 입니다. 

ng generate service supabase --skip-tests=true

위에 project url을 supabaseUrl에 project api keys를 supabaseKey에 넣어주세요. 😃

@Injectable({
  providedIn: 'root'
})
export class SupabaseService {
  private supabaseUrl = [your project url]
  private supabaseKey = [your project api keys]
  private supabase = createClient(this.supabaseUrl, this.supabaseKey);

  public getSupabase() {
    return this.supabase;
  }
}

위에 코드에서 createClient()함수를 사용하여 supabase클라이언트를 생성합니다. getSupabase 메서드를 사용하여 supabase 클라이언트 객체를 다른 서비스 파일에서 사용하도록 합니다.

🍋 auth.service.ts 생성하기

Supabase 인증 기능을 구현하기 위한 authService.ts 파일을 생성해줍니다.

supabase 인증과 관련된 코드는 authServic.ts 파일에 작성하였습니다.

ng generate service auth --skip-tests=true
import { Injectable } from '@angular/core';
import { SupabaseService } from './supabase.service';
import { IUser } from 'src/interface/user';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  constructor(private readonly supabase: SupabaseService) { }

  // 사용자 등록 (sign up) 메서드
  async signIn(userForm: IUser) {
    const { email, password } = userForm;
    const { data, error } = await this.supabase.getSupabase().auth.signUp({ email, password });

    if (error) {
      throw error;
    }

    return data.user?.id
  }

  // 사용자 로그인 (sign in) 메서드
  async signUp(userForm: IUser) {
    return await this.supabase.getSupabase().auth.signInWithPassword({
      email: userForm.email,
      password: userForm.password,
    });
  }

  // 사용자 로그아웃 (sign out) 메서드
  async signOut() {
    return this.supabase.getSupabase().auth.signOut();
  }

  // 현재 로그인된 사용자의 프로필 정보를 가져오는 메서드
  async getProfile() {
    const { data, error } = await this.supabase.getSupabase().auth.getUser();

    return data.user?.id
  }

  // 현재 세션에 로그인된 사용자 ID를 반환하는 메서드
  async getSession() {
    const session = await this.supabase.getSupabase().auth.getSession();

    if (session) {
      return session.data.session?.user.id;
    } else {
      return null
    }
  }
}

 

🍐userTable 생성하기

table editer 을 클릭하고 new table 클릭해줍니다.

table name과 column들의 name과 type을 입력한후 save 해주면 users table이 생성됩니다.

🍉user.service.ts 생성하기

사용자가 사용하는 메서드는 user.service.ts에 작성하였습니다.

ng generate service user --skip-tests=true
import { Injectable } from '@angular/core';
import { SupabaseService } from './supabase.service';
import { IUser } from 'src/interface/user';
import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root'
})
export class UserService {

  constructor(
    private readonly supabase: SupabaseService,
    private readonly authService: AuthService
  ) { }

  // 사용자 등록 메서드
  async signIn(userForm: IUser) {
    const userId = await this.authService.signIn(userForm);

    return await this.supabase.getSupabase().from('users')
      .insert({ user_id: userId, name: userForm.name });
  }

  // 사용자 로그인 메서드
  async signUp(userForm: IUser) {
    return await this.authService.signUp(userForm)
  }

  // 사용자 로그아웃 메서드
  async signOut() {
    return await this.authService.signOut();
  }

  // 현재 로그인된 사용자의 프로필 정보를 가져오는 메서드
  async getProfile() {
    const userId = await this.authService.getProfile()

    return this.supabase.getSupabase().from('users')
      .select('username')
      .eq('id', userId)
      .single();
  }

  // 사용자 프로필 정보 업데이트 메서드
  async updateProfile(userUpdate: IUser) {
    const userId = await this.authService.getProfile()

    const updateUser = {
      username: userUpdate.name,
      user_id: userId,
    };

    return this.supabase.getSupabase().from('users').upsert(updateUser);
  }
}
  • signIn(userForm: IUser): 사용자를 등록하고, users테이블에 insert 합니다. 
  • signUp(userForm: IUser): 이메일과 비밀번호를 입력받아 Supabase에 로그인하고, 로그인된 사용자 객체를 반환합니다.
  • signOut(): 현재 로그인된 사용자를 Supabase에서 로그아웃합니다.
  • getProfile(): 현재 로그인된 사용자의 프로필 정보를 가져오고, 프로필 정보 객체에서 사용자 이름(username)을 반환합니다.
  • updateProfile(userUpdate: IUser): 사용자 이름을 업데이트하고, 업데이트된 사용자 정보 객체를 반환합니다.

 화면보기

위에 코드를 사용하여 회원가입 로그인 로그아웃을 진행하는 화면입니다.

위와같이 같이 이메일과 비밀번호, 이름을 입력하고 회원가입을하면 입력한 이메일계정으로 확인메일이 갑니다.

confirm your mail을 클릭하면 waiting for verification에서 11 Apr, 2023 15:44로 변경된것을 보실수 있습니다.

인증을 완료한 후 로그인을 하면 로그인된 후 memo 페이지로 이동한 것을 보실수 있습니다.

로그인 완료후 getsession을 찍으면 access_token과 refresh_token, 로그인한 user정보들을 반환해줍니다. supabase를 통해 기존에 백엔드로 jwt 토큰을 이용해 access_token, refresh_token을 구현할 필요없이 supabase에서 내부적으로 해주기때문에 더 쉽고 간단하게 인증부분을 구현할 수 있습니다.

 

다음페이지에서는 메모앱에 crud 기능을 구현해보겠습니다 💓