본문 바로가기
Programming/Javascript

Vue todolist 만들기 - 6. Kakao 로그인 구현

by Wilkyway 2023. 5. 4.
반응형

Kakao 로그인을 프론트에서 작업하고, 사용자 정보 중 이름, 메일주소 등 몇가지만 백엔드에 등록하는 방식으로 진행하겠습니다. 이를 위해서는 우선 main.js에 아래의 코드를 추가해야 합니다.

 

1. main.js

import { createApp } from 'vue'
import App from './App.vue'
import { store } from './store/store.js'
import router from './router'

createApp(App)
.use(router)
.use(store)
.mount('#app')

// 아래 추가
window.Kakao.init('ce8a7d7f75e0322350135c938a5f7182');

 

2. components/KakaoLogin.vue 신규 생성

<template>
	<div class="kakaobox">
		<a id="custom-login-btn" @click="kakaoLogin()">
		<!-- <a id="custom-login-btn" @click="kakaoLogin()"> -->
			<img src="//k.kakaocdn.net/14/dn/btqCn0WEmI3/nijroPfbpCa4at5EIsjyf0/o.jpg" width="222" />
		</a>
	</div>
</template>

<script>
import axios from 'axios';

export default{
	
methods: {	
	kakaoLogin(){
		window.Kakao.Auth.login({
			scope: 'profile_nickname,profile_image, account_email',
			success:() =>{
				this.getKakaoAccount();					
			},
			fail: error => {
				console.log(error);
			},
		});
	},
	getKakaoAccount(){
		window.Kakao.API.request({
			url:'/v2/user/me',				
			success : async res => {
				const kakao_account = res.kakao_account;
				const data={
					username: kakao_account.profile.nickname,
					email : kakao_account.email,
					password: "1234"
				}
				await axios.post('/auth/register', data);
				alert("로그인 성공!");
				// console.log(result);

				this.$store.dispatch('login', data);
				this.$router.push('/')
			},
			fail: error => {
				console.log(error);
			}
		})
	}
}

}
</script>
<style scoped>
.kakaobox{
	text-align: center;
}
</style>

 

3. store/store.js 수정

import { createStore } from 'vuex';
import axios from 'axios';


axios.defaults.baseURL = 'http://localhost:3000';
axios.defaults.headers.post['Content-Type']='application/json;charset=utf-8';
axios.defaults.headers.post['Access-Control-Allow-Origin']='*';


export const store = createStore({
// export default createStore({
  state:{
    user:{
      // {username: '홍길동 email: 'abcd@abcd.com', password: '1234'}
    },
    posts: [
      // {_id: '1', title: 'apple', body: 'Im apple'},
      // {_id: '2', title: 'apple', body: 'Im apple'},
      // {_id: '3', title: 'apple', body: 'Im apple'}
    ]
  },
  mutations:{
    LOGIN(state, payload){
      state.user = payload;
    },
    updateState(state, payload) {      
      // read, create
      Object.keys(payload).forEach((key) => {
        state[key] = payload[key];        
      });
    },
    DELETEPOST(state, post_id){            
      const delete_index = state.posts.findIndex(p=> p._id === post_id);      // 삭제할 포스트의 index 찾기
      state.posts.splice(delete_index,1);      
    },
    UPDATEPOST(state,updatePost){      
      const update_store_item = state.posts.find(p => p._id === updatePost._id);      
      // console.log(updatePost)
      update_store_item.title = updatePost.title;
      update_store_item.body = updatePost.body;
    }
  },
  actions:{   
    addPost(context, newPost){      
      const id= context.state.posts.length+1;      
      const post={
        _id: id,
        title: newPost.title,
        body: newPost.body,
        creator: newPost.title
      }
      context.commit("updateState", {
        posts: [...context.state.posts, post],
      })              
    },
    deletePost(context, post_id){
      context.commit("DELETEPOST", post_id);
    },
    updatePost(context, updatePost){
      context.commit("UPDATEPOST", updatePost)
    },
    login(context, name){     
      context.commit('LOGIN', name);
    }
  }
});

 

4. views/HomeView.vue 파일 수정

<template>  
  <div class="logincheck">
    <div v-if="isloggedin">안녕하세요, {{ user.username }}님</div>    
    <router-link to="/kakaologin" v-else>Kakao Login</router-link>
  </div>
  <h1 class="appname">Real Estate Groth Status</h1>  

  <AddPost />
  <ListofPost />
</template>

<script>
import ListofPost from '../components/ListofPost.vue'
import AddPost from '../components/AddPost.vue'

export default {
  name: 'HomeView',
  components: {
    ListofPost,
    AddPost,
  },
  computed:{
    user(){
      return this.$store.state.user
    },
    isloggedin(){
      return this.$store.state.user.username? true : false;
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;  
  color: #2c3e50;
  margin-top: 60px;  
}
.appname {
  color:#373738;
  text-align: center;
}
.addbutton{
  margin: auto;
  display:flex;
  align-items:center;
  justify-content: center;
  width:50px;
  height:50px;  
  border-radius: 50%;
  background-color:blue ; 
  font-size: 36px;
  font-weight: bold;
  color:beige;
}
.logincheck{  
  text-align: right;  
  margin-right: 15px;
}
</style>

반응형

댓글