Vue로 PWA 개발 - 그랜파 개발자
Firebase 인증 서비스 중 이메일/패스워드 방식을 이용하여 구글에 계정을 생성하고, 구글 계정의 uid와 함께 사용자가 입력한 정보를 mylog의 계정 DB에 저장합니다. 즉, 로그인 등 사용자 인증은 구글 인증 서비스를 이용하고 mylog에 저장된 계정 정보는 mylog 서비스에 사용합니다.
다음과 같은 단계를 거쳐 계정이 만들어집니다.
To implement the ability to create an account using Google's Email/Password authentication with Firebase in a Vue.js application, we will use Vuex to manage the authentication state. Here's how you can do it:
Vue.js 애플리케이션에서 Firebase를 사용하여 Google의 이메일/비밀번호 인증을 사용하여 계정을 생성하는 기능을 구현하기 위해 Vuex를 사용하여 인증 상태를 관리하겠습니다. 방법은 다음과 같습니다.
Node.js and npm: Ensure they are installed. You can download them from nodejs.org.
Node.js 및 npm: 설치되어 있는지 확인하세요. nodejs.org에서 다운로드할 수 있습니다.
Vue CLI: Ensure you have the Vue CLI installed. If not, install it globally using npm:
Vue CLI: Vue CLI가 설치되어 있는지 확인하세요. 그렇지 않은 경우 npm을 사용하여 전역적으로 설치합니다.
npm install -g @vue/cli
Use the Vue CLI to create a new Vue.js project:
Vue CLI를 사용하여 새 Vue.js 프로젝트를 만듭니다.
vue create vue-firebase-auth
Choose the default settings or manually select features like Vuex.
기본 설정을 선택하거나 Vuex와 같은 기능을 수동으로 선택하세요.
cd vue-firebase-auth
You may have Vuex installed by default, but you need to install Firebase:
기본적으로 Vuex가 설치되어 있을 수 있지만 Firebase를 설치해야 합니다.
npm install firebase
Create a firebase.js file in the src directory:
src 디렉터리에 firebase.js 파일을 만듭니다.
touch src/firebase.js
Open src/firebase.js and add the following code:
src/firebase.js를 열고 다음 코드를 추가하세요.
// src/firebase.js
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
const firebaseConfig = {
apiKey: process.env.VUE_APP_FIREBASE_API_KEY,
authDomain: process.env.VUE_APP_FIREBASE_AUTH_DOMAIN,
projectId: process.env.VUE_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.VUE_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.VUE_APP_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.VUE_APP_FIREBASE_APP_ID,
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
export { auth };
In the root directory, create a .env file:
루트 디렉터리에서 '.env' 파일을 만듭니다.
touch .env
Add your Firebase configuration:
Firebase 구성을 추가합니다.
VUE_APP_FIREBASE_API_KEY=your_api_key
VUE_APP_FIREBASE_AUTH_DOMAIN=your_project_id.firebaseapp.com
VUE_APP_FIREBASE_PROJECT_ID=your_project_id
VUE_APP_FIREBASE_STORAGE_BUCKET=your_project_id.appspot.com
VUE_APP_FIREBASE_MESSAGING_SENDER_ID=your_messaging_sender_id
VUE_APP_FIREBASE_APP_ID=your_app_id
Replace the placeholders with your actual Firebase project details.
자리표시자를 실제 Firebase 프로젝트 세부정보로 바꿉니다.
If not already created, create a store directory and an index.js file:
아직 생성되지 않은 경우 store 디렉터리와 index.js 파일을 생성합니다.
mkdir src/store
touch src/store/index.js
Open src/store/index.js and add the following code:
src/store/index.js를 열고 다음 코드를 추가하세요.
// src/store/index.js
import { createStore } from "vuex";
import { auth } from "../firebase";
import { createUserWithEmailAndPassword } from "firebase/auth";
const store = createStore({
state: {
user: null,
error: null,
},
mutations: {
setUser(state, user) {
state.user = user;
},
setError(state, error) {
state.error = error;
},
},
actions: {
async register({ commit }, { email, password }) {
try {
const userCredential = await createUserWithEmailAndPassword(auth, email, password);
commit("setUser", userCredential.user);
commit("setError", null);
} catch (error) {
commit("setError", error.message);
}
},
},
getters: {
getUser(state) {
return state.user;
},
getError(state) {
return state.error;
},
},
});
export default store;
State: Holds the user and error objects.
상태: user 및 error 개체를 보유합니다.
Mutations: setUser updates the user state, and setError updates the error state.
변형: setUser는 사용자 상태를 업데이트하고 setError는 오류 상태를 업데이트합니다.
Actions: register handles the registration logic using Firebase's createUserWithEmailAndPassword method. It commits the setUser and setError mutations based on the outcome.
작업: register는 Firebase의 createUserWithEmailAndPassword 메서드를 사용하여 등록 로직을 처리합니다. 결과에 따라 setUser 및 setError 변형을 커밋합니다.
Getters: getUser and getError provide easy access to the user and error state.
Getters: getUser 및 getError는 사용자 및 오류 상태에 대한 쉬운 액세스를 제공합니다.
Open src/main.js and register the Vuex store:
src/main.js를 열고 Vuex 스토어를 등록하세요.
// src/main.js
import { createApp } from "vue";
import App from "./App.vue";
import store from "./store"; // Import Vuex store
createApp(App)
.use(store) // Use the Vuex store
.mount("#app");
Create a new Register.vue component in the src/components directory:
src/comComponents 디렉터리에 새로운 Register.vue 구성 요소를 만듭니다.
touch src/components/Register.vue
Open src/components/Register.vue and add the following code:
src/comComponents/Register.vue를 열고 다음 코드를 추가하세요.
<template>
<div>
<h2>Register</h2>
<form @submit.prevent="registerUser">
<input v-model="email" type="email" placeholder="Email" required />
<input v-model="password" type="password" placeholder="Password" required />
<button type="submit">Register</button>
</form>
<p v-if="error">{{ error }}</p>
</div>
</template>
<script>
import { mapActions, mapGetters } from "vuex";
export default {
data() {
return {
email: "",
password: "",
};
},
computed: {
...mapGetters(["getError"]),
},
methods: {
...mapActions(["register"]),
registerUser() {
this.register({ email: this.email, password: this.password });
},
},
};
</script>
Form Inputs: Bind the email and password inputs to the component's data using v-model.
양식 입력: v-model을 사용하여 이메일 및 비밀번호 입력을 구성 요소의 데이터에 바인딩합니다.
Register Method: Calls the Vuex register action with the email and password.
등록 방법: 이메일과 비밀번호를 사용하여 Vuex '등록' 작업을 호출합니다.
Error Handling: Displays any error messages from the Vuex store.
오류 처리: Vuex 스토어의 오류 메시지를 표시합니다.
Open src/App.vue and include the Register component:
src/App.vue를 열고 Register 구성 요소를 포함합니다.
<template>
<div id="app">
<Register />
</div>
</template>
<script>
import Register from "./components/Register.vue";
export default {
components: {
Register,
},
};
</script>
Finally, run your application to see the registration form in action:
마지막으로 애플리케이션을 실행하여 실제 등록 양식을 확인하세요.
npm run serve
You should now have a working Vue.js application where you can register a new user using Google's Email/Password authentication through Firebase, managed with Vuex.
이제 Vuex로 관리되는 Firebase를 통해 Google의 이메일/비밀번호 인증을 사용하여 새 사용자를 등록할 수 있는 Vue.js 애플리케이션이 작동해야 합니다.
This setup uses Vuex to manage the state of Firebase Authentication, allowing you to keep the authentication logic centralized and easy to manage. By following this approach, you ensure that your application is well-organized, modular, and scalable for further development.
이 설정은 Vuex를 사용하여 Firebase 인증 상태를 관리하므로 인증 논리를 중앙 집중화하고 쉽게 관리할 수 있습니다. 이 접근 방식을 따르면 애플리케이션이 잘 구성되고 모듈식이며 추가 개발을 위해 확장 가능하다는 것을 확인할 수 있습니다.