iT邦幫忙

2022 iThome 鐵人賽

DAY 25
0
Software Development

30天學習.Net MAUI系列 第 25

25.MAUI使用firebase進行Auth (二)

  • 分享至 

  • xImage
  •  

創建Firebase專案

創建一個firebase專案
https://ithelp.ithome.com.tw/upload/images/20221010/20108931wKlfLl92xm.png

建立專案
https://ithelp.ithome.com.tw/upload/images/20221010/20108931QbLQzaltUS.png

啟用Auth
https://ithelp.ithome.com.tw/upload/images/20221010/20108931rYLeYvqXeS.png
使用電子郵件
https://ithelp.ithome.com.tw/upload/images/20221010/20108931rUIeqZeJl1.png
https://ithelp.ithome.com.tw/upload/images/20221010/20108931lqD1EnTJ3F.png

打開專案設定
https://ithelp.ithome.com.tw/upload/images/20221010/20108931SpBSzKWKpz.png

複製API金鑰
https://ithelp.ithome.com.tw/upload/images/20221010/20108931hpoOsk954S.png

安裝套件

MAUI安裝套件
https://ithelp.ithome.com.tw/upload/images/20221010/20108931I2KDMDHRAe.png
安裝
https://ithelp.ithome.com.tw/upload/images/20221010/20108931vQZPvsCANC.png

創建Models

我們首先創建UserModel

Todo\Models\UserModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Todo.Models
{
    public class UserModel
    {
        public string email { get; set; }
        public string password { get; set; }
    }
}

創建Services

在Service中創建AuthService

首先創建interface
https://ithelp.ithome.com.tw/upload/images/20221010/20108931TsJFRGNIU0.png

https://ithelp.ithome.com.tw/upload/images/20221010/20108931DAVvUqL0UC.png

Todo\Services\IAuthService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Todo.Models;

namespace Todo.Services
{
    public interface IAuthService
    {
        Task<bool> RegisterUserWithEmail(UserModel user);
    }
}

並將firebase的api貼到private readonly String webApikey

Todo\Services\AuthService.cs

using Firebase.Auth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Todo.Models;

namespace Todo.Services
{
    public class AuthService : IAuthService
    {
        private readonly String webApikey = "........."; // Type your web api key
        public async Task<bool> RegisterUserWithEmail(UserModel user)
        {
            try {
                var authProvider = new FirebaseAuthProvider(new FirebaseConfig(webApikey));
                var auth = await authProvider.CreateUserWithEmailAndPasswordAsync(user.email, user.password);

                return true;
            } catch {
                return false;
            }

        }
    }
}

創建ViewModels

創建Todo\ViewModels\AuthViewModel.cs

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Todo.Models;
using Todo.Services;

namespace Todo.ViewModels
{
    [QueryProperty(nameof(User), "User")]
    public partial class AuthViewModel : ObservableObject
    {
        [ObservableProperty]
        private UserModel _user = new UserModel();
        private readonly IAuthService _authService;
        public AuthViewModel(IAuthService authService)
        {
            _authService = authService;
        }

        [RelayCommand]
        public async void RegisterUserWithEmailAndPassword()
        {
            var result = await _authService.RegisterUserWithEmail(new Models.UserModel
            {
                email=User.email,
                password=User.password,
            });
            if (result) {
                await Shell.Current.DisplayAlert("Status: Register Success", "User registed", "Ok");
            } else {
                await Shell.Current.DisplayAlert("Status: Register Failed", "Something is failed", "Ok");
            }
        }
    }
}

註冊viewmodel和service

打開Todo\MauiProgram.cs,加入

		builder.Services.AddSingleton<IAuthService, AuthService>();
		
		builder.Services.AddSingleton<RegisterPage>();
		
		builder.Services.AddSingleton<AuthViewModel>();

MauiProgram.cs

using Todo.Services;
using Todo.ViewModels;

namespace Todo;

public static class MauiProgram
{
	public static MauiApp CreateMauiApp()
	{
		var builder = MauiApp.CreateBuilder();
		builder
			.UseMauiApp<App>()
			.ConfigureFonts(fonts =>
			{
				fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
				fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
			});

		// Add TodoItem Service
		builder.Services.AddSingleton<ITodoService, TodoService>();
		builder.Services.AddSingleton<IAuthService, AuthService>();

		// Add Views
		builder.Services.AddSingleton<AddTodoPage>();
        builder.Services.AddSingleton<TodoPage>();
		builder.Services.AddSingleton<RegisterPage>();

        // Add ViewModel
        builder.Services.AddSingleton<TodoListViewModel>();
		builder.Services.AddSingleton<AddUpdateTodoViewModel>();
		builder.Services.AddSingleton<AuthViewModel>();

		return builder.Build();
	}
}

加入到Pages

加入到我們Todo\Pages\RegisterPage.xaml.cs

using Todo.ViewModels;

namespace Todo;

public partial class RegisterPage : ContentPage
{
	public RegisterPage(AuthViewModel vm)
	{
		InitializeComponent();
        this.BindingContext = vm;
    }
}

進入到我們的xaml,在ContentPage屬性中加入

             xmlns:models="clr-namespace:Todo.Models"
             xmlns:viewModels="clr-namespace:Todo.ViewModels"
             x:DataType="viewModels:AuthViewModel"

Todo\Pages\RegisterPage.xaml裡的Entry和Button資料做綁定

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:models="clr-namespace:Todo.Models"
             xmlns:viewModels="clr-namespace:Todo.ViewModels"
             x:DataType="viewModels:AuthViewModel"
             x:Class="Todo.RegisterPage"
             Title="RegisterPage">
    <VerticalStackLayout>
        <Label 
            Text="Register"
            VerticalOptions="Center" 
            HorizontalOptions="Center" />
        <Entry Placeholder="Email" Text="{Binding User.email}" />
        <Entry Placeholder="Password" Text="{Binding User.password}" IsPassword="true" />
        <Button Text="Register Account" Command="{Binding RegisterUserWithEmailAndPasswordCommand}"/>
    </VerticalStackLayout>
</ContentPage>

測試

https://ithelp.ithome.com.tw/upload/images/20221010/20108931vOLhTNsPB2.png

https://ithelp.ithome.com.tw/upload/images/20221010/20108931xDEPlbbvUk.png

回到fiebase觀看
https://ithelp.ithome.com.tw/upload/images/20221010/20108931FMIa7KfuqZ.png


今天我們先簡單完成註冊的功能,明天再繼續實現登入功能,大家明天見。


上一篇
24.MAUI使用firebase進行Auth (一)
下一篇
26.MAUI使用firebase進行Auth (三)
系列文
30天學習.Net MAUI30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
yhanshuang
iT邦新手 5 級 ‧ 2023-11-13 15:02:30

您好,
Todo\Services\AuthService.cs
我直接把這段程式碼貼上之後出現錯誤:
CS0246 找不到類型或命名空間名稱 'FirebaseAuthProvider' (是否遺漏了 using 指示詞或組件參考?)
CS0246 找不到類型或命名空間名稱 'FirebaseConfig' (是否遺漏了 using 指示詞或組件參考?)

當我把using加上去(using Firebase.Auth.Providers;)
出現錯誤:
CS0144 無法建立抽象類型或介面 'FirebaseAuthProvider' 的執行個體
CS0246 找不到類型或命名空間名稱 'FirebaseConfig' (是否遺漏了 using 指示詞或組件參考?)-->這跟上面一樣
想請教您該怎麼解決

Felix阿甫 iT邦研究生 5 級 ‧ 2023-11-13 15:44:43 檢舉

我猜測是版本不同。FirebaseAuthentication.net 4.1.0
FirebaseAuthentication.net 3.7.2

如果是新版的,你可能要看一下docs怎麼做。https://stackoverflow.com/questions/76134826/i-am-trying-to-implement-firebase-into-my-maui-app-but-have-run-into-a-problem-w

好的 謝謝指教

我要留言

立即登入留言