Commit 7b62eb2e authored by KangMin An's avatar KangMin An
Browse files

Update: Kakao OAuth Process를 위한 front와 back 코드 수정.

parent c5c2b1e1
import axios from 'axios'; import axios from "axios";
import Swal from 'sweetalert2' import Swal from "sweetalert2";
import '../App.css' import "../App.css";
import { routesClient } from './../routesClient'; import { routesClient } from "./../routesClient";
// export const KAKAO_AUTH_URL = `https://kauth.kakao.com/oauth/authorize?client_id=${CLIENT_ID}&redirect_uri=${REDIRECT_URI}&response_type=code`; // export const KAKAO_AUTH_URL = `https://kauth.kakao.com/oauth/authorize?client_id=${CLIENT_ID}&redirect_uri=${REDIRECT_URI}&response_type=code`;
const { Kakao } = window; const { Kakao } = window;
// 해당 함수를 통해 카카오톡을 이용한 회원가입 혹은 로그인 처리
export function LoginWithKakao() { // isLogin : true - 카카오톡을 이용해 로그인 처리 || false - 카카오톡을 이용해 회원가입 처리
export function AuthWithKakao(isLogin) {
//authObj : response.data에 들어가 있는 부분 object 형식 //authObj : response.data에 들어가 있는 부분 object 형식
Kakao.Auth.loginForm({ Kakao.Auth.loginForm({
// 팝업 + 다른 아이디 로그인시 // 팝업 + 다른 아이디 로그인시
scope: 'account_email, profile_nickname', scope: "account_email, profile_nickname",
// 추가 동의 받을 동의 항목 ID 목록, 하나의 문자열에 여러 개의 ID를 쉼표(,)로 구분하여 전달 // 추가 동의 받을 동의 항목 ID 목록, 하나의 문자열에 여러 개의 ID를 쉼표(,)로 구분하여 전달
success: function (authObj) { success: function (authObj) {
console.log(JSON.stringify(authObj)) console.log(JSON.stringify(authObj));
Kakao.API.request({ Kakao.API.request({
// 현재 로그인한 사용자의 카카오계정 정보 불러오기 // 현재 로그인한 사용자의 카카오계정 정보 불러오기
url: '/v2/user/me', url: "/v2/user/me",
// 사용자 정보 요청 주소 // 사용자 정보 요청 주소
data: { data: {
property_keys: ["kakao_account.profile", "kakao_account.email"] property_keys: ["kakao_account.profile", "kakao_account.email"],
// 파라미터를 통해 특정 사용자 정보만 지정해서 요청 // 파라미터를 통해 특정 사용자 정보만 지정해서 요청
}, },
success: async function (response) { success: async function (response) {
console.log(response); console.log(response);
console.log(response.kakao_account.profile); console.log(response.kakao_account.profile);
const nickValue = response.kakao_account.profile['nickname'] const nickValue = response.kakao_account.profile["nickname"];
const emailValue = response.kakao_account.email const emailValue = response.kakao_account.email;
await axios.post(routesClient.signup, { email: emailValue, nick_name: nickValue, isOauth: true }) await axios
.then((res) => console.log('kakao', res)) .post(
isLogin ? routesClient.login : routesClient.signup,
isLogin
? { email: emailValue, isOAuth: true }
: {
email: emailValue,
nick_name: nickValue,
isOAuth: true,
}
)
.then((res) => {
console.log("kakao", res);
if (
(!isLogin && !res.data.contents.existing_user) ||
(isLogin && res.data.contents.existing_user)
) {
// 회원 가입 또는 로그인 성공
localStorage.setItem("login", true);
// localStorage.setItem('login', true)
Swal.fire({ Swal.fire({
title: '로그인 성공!', title: isLogin ? "로그인 성공!" : "회원가입 성공!",
text: '🙌 환영합니다 🙌', text: "🙌 환영합니다 🙌",
icon: 'success', icon: "success",
customClass: 'swal-wide', customClass: "swal-wide",
confirmButtonText: '확인', confirmButtonText: "확인",
}).then((res) => { }).then((result) => {
if (res.isConfirmed) { if (result.isConfirmed) {
// window.location.replace('/') window.location.replace(
isLogin ? "/" : "/first-local-code"
);
} else {
window.location.replace("/");
} }
else { });
// window.location.replace('/') } else {
Swal.fire({
title: isLogin ? "로그인 실패!" : "회원가입 실패!",
text: isLogin
? "🙌 회원가입을 먼저 진행하세요! 🙌"
: "🙌 이미 존재하는 사용자 입니다! 🙌",
icon: "success",
customClass: "swal-wide",
confirmButtonText: "확인",
}).then((result) => {
if (result.isConfirmed) {
window.location.replace(isLogin ? "/signup" : "/login");
} else {
window.location.replace("/");
} }
}) });
} }
}); });
}, },
});
},
fail: function (err) { fail: function (err) {
alert(JSON.stringify(err)) alert(JSON.stringify(err));
console.log(JSON.stringify(err)) console.log(JSON.stringify(err));
}, },
} });
)
} }
export function kakaoLogout() { export function kakaoLogout() {
// 토큰을 만료시켜 더 이상 해당 액세스 토큰으로 카카오 API를 호출할 수 없도록 // 토큰을 만료시켜 더 이상 해당 액세스 토큰으로 카카오 API를 호출할 수 없도록
console.log('geAccesToken()', Kakao.Auth.getAccessToken()) console.log("geAccesToken()", Kakao.Auth.getAccessToken());
if (!Kakao.Auth.getAccessToken()) { if (!Kakao.Auth.getAccessToken()) {
alert('Not logged in.') alert("Not logged in.");
localStorage.clear(); localStorage.clear();
return; return;
} }
...@@ -73,18 +109,17 @@ export function kakaoLogout() { ...@@ -73,18 +109,17 @@ export function kakaoLogout() {
// 로그인 시 발급받은 토큰을 만료시키는 함수 // 로그인 시 발급받은 토큰을 만료시키는 함수
localStorage.clear(); localStorage.clear();
Swal.fire({ Swal.fire({
title: '로그아웃 성공!', title: "로그아웃 성공!",
text: '🙏 안녕히 가세요 🙏', text: "🙏 안녕히 가세요 🙏",
icon: 'warning', icon: "warning",
customClass: 'swal-wide', customClass: "swal-wide",
confirmButtonText: '확인', confirmButtonText: "확인",
}).then((res) => { }).then((res) => {
if (res.isConfirmed) { if (res.isConfirmed) {
window.location.replace('/') window.location.replace("/");
} } else {
else { window.location.replace("/");
window.location.replace('/')
} }
}) });
}) });
} }
import React, { useState } from 'react'; import React, { useState } from "react";
import '../App.css' import "../App.css";
import { Form, Button, Row, Col, Card, Alert, FloatingLabel } from 'react-bootstrap'; import {
import { LoginWithKakao } from '../utils/Oauth'; Form,
import axios from 'axios'; Button,
import { routesClient } from '../routesClient'; Row,
Col,
Card,
Alert,
FloatingLabel,
} from "react-bootstrap";
import { AuthWithKakao } from "../utils/Oauth";
import axios from "axios";
import { routesClient } from "../routesClient";
function LoginComp() { function LoginComp() {
const cardstyled = { const cardstyled = {
margin: 'auto', margin: "auto",
padding: '1em', padding: "1em",
display: 'flex', display: "flex",
justifyContent: 'center', justifyContent: "center",
width: '100%', width: "100%",
borderWidth: '3px', borderWidth: "3px",
borderRadius: '20px', borderRadius: "20px",
borderColor: 'rgb(110, 189, 142)', borderColor: "rgb(110, 189, 142)",
color: '#04AB70' color: "#04AB70",
} };
const inboxstyled = { const inboxstyled = {
display: 'flex', display: "flex",
flexDirection: 'column', flexDirection: "column",
maxWidth: '80%', maxWidth: "80%",
justifyContent: 'center', justifyContent: "center",
margin: 'auto', margin: "auto",
padding: '0.5em', padding: "0.5em",
color: 'black' color: "black",
} };
const [alertShow, setAlertShow] = useState(false) const [alertShow, setAlertShow] = useState(false);
const [emailAddress, setEmailAddress] = useState('') const [emailAddress, setEmailAddress] = useState("");
const [mailSend, setMailSend] = useState(false) const [mailSend, setMailSend] = useState(false);
function addressUrl() { function addressUrl() {
const afterAt = emailAddress.split('@')[1] const afterAt = emailAddress.split("@")[1];
if (afterAt) { if (afterAt) {
const newLink = 'https://www.' + afterAt; const newLink = "https://www." + afterAt;
window.location.replace(newLink); window.location.replace(newLink);
} }
if (afterAt === 'korea.ac.kr') { if (afterAt === "korea.ac.kr") {
window.location.replace('https://www.gmail.com'); window.location.replace("https://www.gmail.com");
} }
} }
function handleChange(event) { function handleChange(event) {
setEmailAddress(event.target.value) setEmailAddress(event.target.value);
} }
async function handleSubmit(event) { async function handleSubmit(event) {
event.preventDefault(); event.preventDefault();
const res = await axios.post(routesClient.login, { email: emailAddress, isOauth: false }) const res = await axios.post(routesClient.login, {
console.log('mail_sending : ', res.data.contents.mail_sending) email: emailAddress,
setMailSend(res.data.contents.mail_sending) isOauth: false,
setAlertShow(true) });
localStorage.setItem('login', true) console.log("mail_sending : ", res.data.contents.mail_sending);
setMailSend(res.data.contents.mail_sending);
setAlertShow(true);
localStorage.setItem("login", true);
} }
return ( return (
<Row className='text-center w-100 my-2'> <Row className="text-center w-100 my-2">
<Card style={cardstyled}> <Card style={cardstyled}>
<Card.Title id='impactTitle'> <Card.Title id="impactTitle">로그인</Card.Title>
로그인 <Card.Subtitle style={{ fontWeight: "lighter" }}>
</Card.Title>
<Card.Subtitle style={{ fontWeight: 'lighter' }}>
이메일 또는 소셜미디어로 로그인하세요 이메일 또는 소셜미디어로 로그인하세요
</Card.Subtitle> </Card.Subtitle>
<hr /> <hr />
<Card.Text> <Card.Text>
<Row className='m-auto d-flex justify-content-center' style={{ width: '80%' }}> <Row
{mailSend ? className="m-auto d-flex justify-content-center"
<Alert show={alertShow} variant={'success'}> style={{ width: "80%" }}
<Col> >
😍 이메일 전송이 완료 되었습니다. {mailSend ? (
</Col> <Alert show={alertShow} variant={"success"}>
<Alert.Link href="" onClick={addressUrl} target='_blank' style={{ fontSize: '0.8em' }}> <Col>😍 이메일 전송이 완료 되었습니다.</Col>
<Alert.Link
href=""
onClick={addressUrl}
target="_blank"
style={{ fontSize: "0.8em" }}
>
이메일 확인 하러가기 이메일 확인 하러가기
</Alert.Link> </Alert.Link>
</Alert> </Alert>
: ) : (
<Alert show={alertShow} variant={'danger'}> <Alert show={alertShow} variant={"danger"}>
<Col> <Col>😭 이메일을 정확하게 적어주세요.</Col>
😭 이메일을 정확하게 적어주세요. <Alert.Link
</Col> href="/signup"
<Alert.Link href="/signup" target='_blank' style={{ fontSize: '0.8em' }}> target="_blank"
style={{ fontSize: "0.8em" }}
>
회원가입 하러가기 회원가입 하러가기
</Alert.Link> </Alert.Link>
</Alert> </Alert>
} )}
</Row> </Row>
<Form style={inboxstyled} onSubmit={handleSubmit}> <Form style={inboxstyled} onSubmit={handleSubmit}>
<FloatingLabel label="Email"> <FloatingLabel label="Email">
<Form.Control type="email" placeholder="Email" onChange={handleChange} required /> <Form.Control
type="email"
placeholder="Email"
onChange={handleChange}
required
/>
</FloatingLabel> </FloatingLabel>
<Button variant='light' className='mt-3' id='formbtn' type='submit'> <Button variant="light" className="mt-3" id="formbtn" type="submit">
로그인 로그인
</Button> </Button>
</Form> </Form>
<Row className='d-flex align-items-center m-2'> <Row className="d-flex align-items-center m-2">
<Col> <Col>
<hr /> <hr />
</Col> </Col>
...@@ -111,18 +131,27 @@ function LoginComp() { ...@@ -111,18 +131,27 @@ function LoginComp() {
</Col> </Col>
</Row> </Row>
<Row style={{ margin: 'auto', marginBottom: '5px', display: 'flex', justifyContent: 'center' }}> <Row
<a href="#;" onClick={LoginWithKakao} id='socialLink' > style={{
margin: "auto",
marginBottom: "5px",
display: "flex",
justifyContent: "center",
}}
>
<a href="#;" onClick={() => AuthWithKakao(true)} id="socialLink">
{/* 세미콜론이 붙으면 최상단 이동 x */} {/* 세미콜론이 붙으면 최상단 이동 x */}
<img src='http://image.kmib.co.kr/online_image/2020/0626/611514110014734788_1.jpg' id='logpng' alt='KAKAO' /> <img
src="http://image.kmib.co.kr/online_image/2020/0626/611514110014734788_1.jpg"
id="logpng"
alt="KAKAO"
/>
</a> </a>
</Row> </Row>
</Card.Text> </Card.Text>
</Card> </Card>
</Row> </Row>
) );
} }
export default LoginComp; export default LoginComp;
import React, { useState } from 'react' import React, { useState } from "react";
import '../App.css' import "../App.css";
import { Form, Button, Row, Col, Card, Alert, FloatingLabel } from 'react-bootstrap'; import {
import { LoginWithKakao } from '../utils/Oauth'; Form,
import axios from 'axios'; Button,
import { routesClient } from './../routesClient'; Row,
Col,
Card,
Alert,
FloatingLabel,
} from "react-bootstrap";
import { AuthWithKakao } from "../utils/Oauth";
import axios from "axios";
import { routesClient } from "./../routesClient";
function SignupComp() { function SignupComp() {
const cardstyled = { const cardstyled = {
margin: 'auto', margin: "auto",
padding: '1em', padding: "1em",
display: 'flex', display: "flex",
justifyContent: 'center', justifyContent: "center",
width: '100%', width: "100%",
borderWidth: '3px', borderWidth: "3px",
borderRadius: '20px', borderRadius: "20px",
borderColor: 'rgb(110, 189, 142)', borderColor: "rgb(110, 189, 142)",
color: '#04AB70' color: "#04AB70",
} };
const inboxstyled = { const inboxstyled = {
display: 'flex', display: "flex",
flexDirection: 'column', flexDirection: "column",
maxWidth: '80%', maxWidth: "80%",
justifyContent: 'center', justifyContent: "center",
margin: 'auto', margin: "auto",
padding: '0.5em', padding: "0.5em",
color: 'black' color: "black",
} };
const initValues = { const initValues = {
nick_name: '', nick_name: "",
email: '', email: "",
isOauth: false isOAuth: false,
} };
const [formValues, setFormValues] = useState(initValues) const [formValues, setFormValues] = useState(initValues);
const [userExist, setUserExist] = useState(false) const [userExist, setUserExist] = useState(false);
const [alertShow, setAlertShow] = useState(false) const [alertShow, setAlertShow] = useState(false);
function handleChange(event) { function handleChange(event) {
const { name, value } = event.target const { name, value } = event.target;
setFormValues({ ...formValues, [name]: value }) setFormValues({ ...formValues, [name]: value });
} }
async function handleSubmit(event) { async function handleSubmit(event) {
event.preventDefault(); event.preventDefault();
const res = await axios.post(routesClient.signup, formValues) const res = await axios.post(routesClient.signup, formValues);
console.log('existing_user : ', res.data.contents.existing_user) console.log("existing_user : ", res.data.contents.existing_user);
setUserExist(res.data.contents.existing_user) setUserExist(res.data.contents.existing_user);
setAlertShow(true) setAlertShow(true);
} }
return ( return (
<Row className="text-center w-100 my-2">
<Row className='text-center w-100 my-2'>
<Card style={cardstyled}> <Card style={cardstyled}>
<Card.Title id='impactTitle'> <Card.Title id="impactTitle">계정 생성하기</Card.Title>
계정 생성하기 <Card.Subtitle style={{ fontWeight: "lighter" }}>
</Card.Title>
<Card.Subtitle style={{ fontWeight: 'lighter' }}>
이메일 또는 소셜미디어로 계정을 생성하세요 이메일 또는 소셜미디어로 계정을 생성하세요
</Card.Subtitle> </Card.Subtitle>
<hr /> <hr />
<Card.Text> <Card.Text>
<Row className='m-auto d-flex justify-content-center' style={{ width: '80%' }}> <Row
{!userExist ? className="m-auto d-flex justify-content-center"
<Alert show={alertShow} variant={'success'}> style={{ width: "80%" }}
<Col> >
😊 계정 생성이 완료 되었습니다. {!userExist ? (
</Col> <Alert show={alertShow} variant={"success"}>
<Alert.Link href='/login' style={{ fontSize: '0.8em' }}> <Col>😊 계정 생성이 완료 되었습니다.</Col>
<Alert.Link href="/login" style={{ fontSize: "0.8em" }}>
로그인 하러가기 로그인 하러가기
</Alert.Link> </Alert.Link>
</Alert> </Alert>
: ) : (
<Alert show={alertShow} variant={'danger'}> <Alert show={alertShow} variant={"danger"}>
<Col> <Col>🤔 이미 존재하는 계정입니다.</Col>
🤔 이미 존재하는 계정입니다. <Alert.Link href="/login" style={{ fontSize: "0.8em" }}>
</Col>
<Alert.Link href='/login' style={{ fontSize: '0.8em' }}>
로그인 하러가기 로그인 하러가기
</Alert.Link> </Alert.Link>
</Alert> </Alert>
} )}
</Row> </Row>
<Form style={inboxstyled} onSubmit={handleSubmit}> <Form style={inboxstyled} onSubmit={handleSubmit}>
<FloatingLabel <FloatingLabel label="Nickname" className="mb-3">
label="Nickname"
className='mb-3'
>
<Form.Control <Form.Control
type="text" type="text"
name="nick_name" name="nick_name"
...@@ -100,9 +100,7 @@ function SignupComp() { ...@@ -100,9 +100,7 @@ function SignupComp() {
required required
/> />
</FloatingLabel> </FloatingLabel>
<FloatingLabel <FloatingLabel label="Email Address">
label="Email Address"
>
<Form.Control <Form.Control
type="email" type="email"
name="email" name="email"
...@@ -112,12 +110,12 @@ function SignupComp() { ...@@ -112,12 +110,12 @@ function SignupComp() {
/> />
</FloatingLabel> </FloatingLabel>
<Button variant='light' className='mt-3' id='formbtn' type='submit'> <Button variant="light" className="mt-3" id="formbtn" type="submit">
회원가입 회원가입
</Button> </Button>
</Form> </Form>
<Row className='d-flex align-items-center m-2'> <Row className="d-flex align-items-center m-2">
<Col> <Col>
<hr /> <hr />
</Col> </Col>
...@@ -127,15 +125,26 @@ function SignupComp() { ...@@ -127,15 +125,26 @@ function SignupComp() {
</Col> </Col>
</Row> </Row>
<Row style={{ margin: 'auto', marginBottom: '5px', display: 'flex', justifyContent: 'center' }}> <Row
<a href="#;" onClick={LoginWithKakao} id='socialLink' > style={{
<img src='http://image.kmib.co.kr/online_image/2020/0626/611514110014734788_1.jpg' id='logpng' alt='KAKAO' /> margin: "auto",
marginBottom: "5px",
display: "flex",
justifyContent: "center",
}}
>
<a href="#;" onClick={() => AuthWithKakao(false)} id="socialLink">
<img
src="http://image.kmib.co.kr/online_image/2020/0626/611514110014734788_1.jpg"
id="logpng"
alt="KAKAO"
/>
</a> </a>
</Row> </Row>
</Card.Text> </Card.Text>
</Card> </Card>
</Row> </Row>
) );
} }
export default SignupComp; export default SignupComp;
import React, { useState, useEffect } from 'react' import React, { useState, useEffect } from "react";
import { Row, Card, Button, Col } from 'react-bootstrap'; import { Row, Card, Button, Col } from "react-bootstrap";
import '../App.css' import "../App.css";
import { Link } from 'react-router-dom'; import { Link } from "react-router-dom";
import { callUserInfo } from '../utils/CheckDB'; import { callUserInfo } from "../utils/CheckDB";
import { isLogined } from '../utils/Auth'; import { isLogined } from "../utils/Auth";
function UserInfo() { function UserInfo() {
const cardstyled = { const cardstyled = {
margin: 'auto', margin: "auto",
padding: '1em 0.5em 1em 0.5em', padding: "1em 0.5em 1em 0.5em",
display: 'flex', display: "flex",
justifyContent: 'center', justifyContent: "center",
width: '100%', width: "100%",
borderWidth: '3px', borderWidth: "3px",
borderRadius: '20px', borderRadius: "20px",
borderColor: 'rgba(195, 195, 195, 0.753)', borderColor: "rgba(195, 195, 195, 0.753)",
color: 'rgb(110, 189, 142)', color: "rgb(110, 189, 142)",
} };
const btnstyled2 = { const btnstyled2 = {
background: 'white', background: "white",
margin: 'auto', margin: "auto",
borderWidth: '2px', borderWidth: "2px",
fontSize: '0.7em', fontSize: "0.7em",
color: 'rgb(110, 189, 142)', color: "rgb(110, 189, 142)",
borderColor: 'rgba(195, 195, 195, 0.753)', borderColor: "rgba(195, 195, 195, 0.753)",
width: '50%' width: "50%",
} };
const [userNick, setUserNick] = useState('') const [userNick, setUserNick] = useState("");
const [createdTime, setCreatedTime] = useState('') const [createdTime, setCreatedTime] = useState("");
useEffect(() => { useEffect(() => {
callUserInfo().then((res) => { callUserInfo().then((res) => {
if (isLogined()) { if (isLogined()) {
setUserNick(res[0]['nick_name']) setUserNick(res[0]["nick_name"]);
const dateStr = res[0]['created_at'].split('T')[0].split('-') const dateStr = res[0]["created_at"].split("T")[0].split("-");
const now = new Date(); const now = new Date();
const year = now.getFullYear(); // 년 const year = now.getFullYear(); // 년
const month = now.getMonth() + 1; // 월 0부터 시작 const month = now.getMonth() + 1; // 월 0부터 시작
const day = now.getDate(); // 일 const day = now.getDate(); // 일
const stDate = new Date(dateStr[0], dateStr[1], dateStr[2]) // 가입 날짜 const stDate = new Date(dateStr[0], dateStr[1], dateStr[2]); // 가입 날짜
const endDate = new Date(year, month, day) // 현재 시간 const endDate = new Date(year, month, day); // 현재 시간
const btMs = endDate.getTime() - stDate.getTime() // 주어진 날짜 사이의 경과 시간 (밀리 초) const btMs = endDate.getTime() - stDate.getTime(); // 주어진 날짜 사이의 경과 시간 (밀리 초)
const btDay = btMs / (1000 * 60 * 60 * 24) // Ms -> 일 const btDay = btMs / (1000 * 60 * 60 * 24); // Ms -> 일
setCreatedTime(btDay) setCreatedTime(btDay);
} }
}) });
}, []) }, []);
const [showState, setShowState] = useState('') const [showState, setShowState] = useState("");
const [localState, setLocalState] = useState([]) const [localState, setLocalState] = useState([]);
useEffect(() => { useEffect(() => {
// user-info 에서 loc_code // user-info 에서 loc_code
callUserInfo().then((res) => { callUserInfo().then((res) => {
if (isLogined()) { if (isLogined()) {
const dbloc = res[0].loc_code const dbloc = res[0].loc_code;
if (dbloc === null) { if (dbloc === null) {
setShowState('지역을 입력해주세요') setShowState("지역을 입력해주세요");
const localstyle = document.getElementById('local_state') const localstyle = document.getElementById("local_state");
localstyle.style.display = 'none' localstyle.style.display = "none";
} else {
const localName = res[0].loc_name;
setLocalState(localName);
} }
else {
const localName = res[0].loc_name
setLocalState(localName)
} }
} });
}) }, []);
}, [])
return ( return (
<Col className='text-center pb-2 px-0'> <Col className="text-center pb-2 px-0">
<Card style={cardstyled} id='localName'> <Card style={cardstyled} id="localName">
<Card.Title> <Card.Title>
<strong> <strong>
{isLogined() ? {isLogined() ? <h3>{`${userNick}`}</h3> : <h3>손 님</h3>}
<h3>
{`${userNick}`}
</h3>
:
<h3>
</h3>
}
</strong> </strong>
<p style={{ fontWeight: '300', margin: '0' }}> <p style={{ fontWeight: "300", margin: "0" }}>환영합니다</p>
환영합니다
</p>
</Card.Title> </Card.Title>
<hr /> <hr />
<Row style={{ alignItems: 'center', margin: 'auto', justifyContent: 'center' }}> <Row
style={{
alignItems: "center",
margin: "auto",
justifyContent: "center",
}}
>
<Card.Subtitle> <Card.Subtitle>
{isLogined() ? {isLogined() ? (
<div className='mb-2'> <div className="mb-2">
<div> <div>{showState}</div>
{showState}
</div>
<div id='local_state'> <div id="local_state">
{`${localState['doe']}`} {`${localState["doe"]}`}
<br /> <br />
{`${localState['sgg']}`} {`${localState["sgg"]}`}
<br /> <br />
{`${localState['emd']}`} {`${localState["emd"]}`}
</div> </div>
</div> </div>
: ) : (
<div className='mb-2'> <div className="mb-2">로그인 이용 가능합니다</div>
로그인 이용 가능합니다 )}
</div>
}
</Card.Subtitle> </Card.Subtitle>
{isLogined() && {isLogined() && (
<Button variant='light' className='m-auto d-flex' style={btnstyled2}> <Button
<Link to='/edit' className='w-100' style={{ textDecoration: 'none', color: 'rgb(110, 189, 142)' }}> variant="light"
className="m-auto d-flex"
style={btnstyled2}
>
<Link
to="/edit"
className="w-100"
style={{ textDecoration: "none", color: "rgb(110, 189, 142)" }}
>
변경 변경
</Link> </Link>
</Button> </Button>
} )}
</Row> </Row>
{isLogined() && {isLogined() && (
<Card.Text> <Card.Text>
<hr /> <hr />
<Row style={{ color: 'black' }}> <Row style={{ color: "black" }}>
<p style={{ fontWeight: '300', margin: '0' }}> <p style={{ fontWeight: "300", margin: "0" }}>환경을 향한 노력</p>
환경을 향한 노력 <h3 style={{ fontWeight: "300", color: "#2b90d9", margin: "0" }}>
</p>
<h3 style={{ fontWeight: '300', color: '#2b90d9', margin: '0' }}>
<strong>{createdTime}</strong> 일 <strong>{createdTime}</strong> 일
</h3> </h3>
</Row> </Row>
</Card.Text> </Card.Text>
} )}
</Card> </Card>
</Col> </Col>
) );
} }
export default UserInfo; export default UserInfo;
...@@ -25,9 +25,12 @@ const postMail = async (email, token) => { ...@@ -25,9 +25,12 @@ const postMail = async (email, token) => {
from: `EUE Auth Supply <${envs.api.nodemailer.user}>`, from: `EUE Auth Supply <${envs.api.nodemailer.user}>`,
to: email, to: email,
subject: "EUE 사용자 계정 확인용 메일.", subject: "EUE 사용자 계정 확인용 메일.",
html: `<a href="${envs.server.protocol}://${envs.server.host}:${envs.server.port html: `<a href="${envs.server.protocol}://${envs.server.host}:${
}${routes.base + routes.confirm}?token=${token}">${envs.server.protocol envs.server.port
}://${envs.server.host}:${envs.server.port}${routes.base + routes.confirm }${routes.base + routes.confirm}?token=${token}">${
envs.server.protocol
}://${envs.server.host}:${envs.server.port}${
routes.base + routes.confirm
}?token=${token}</a>`, }?token=${token}</a>`,
}; };
...@@ -58,7 +61,7 @@ export const getEditProfile = (req, res) => { ...@@ -58,7 +61,7 @@ export const getEditProfile = (req, res) => {
// 회원 가입 처리 // 회원 가입 처리
export const postSignup = async (req, res) => { export const postSignup = async (req, res) => {
const { const {
body: { email, nick_name }, body: { email, nick_name, isOAuth },
} = req; } = req;
const result = await db.User.findAll({ const result = await db.User.findAll({
...@@ -66,18 +69,44 @@ export const postSignup = async (req, res) => { ...@@ -66,18 +69,44 @@ export const postSignup = async (req, res) => {
logging: false, logging: false,
}); });
if (result.length != 0) { if (result.length !== 0) {
res.json({ msg: resForm.msg.err, contents: { existing_user: true } }); res.json({ msg: resForm.msg.err, contents: { existing_user: true } });
} else { } else {
db.User.create({ email: email, nick_name: nick_name }, { logging: false }); await db.User.create(
{ email: email, nick_name: nick_name },
{ logging: false }
);
const result = await db.User.findAll({
where: { email: email },
logging: false,
});
const user_info = result[0];
if (isOAuth) {
const payload = {
email: email,
};
const accessT = jwt.sign(payload, envs.secretKey.access_token, {
expiresIn: "14d",
issuer: "eue.com",
subject: "userInfo",
});
res
.cookie("acs_token", accessT)
.json({ msg: resForm.msg.ok, contents: { existing_user: false } });
} else {
res.json({ msg: resForm.msg.ok, contents: { existing_user: false } }); res.json({ msg: resForm.msg.ok, contents: { existing_user: false } });
} }
}
}; };
// 메일 확인용 토큰 발행 및 전송 처리 // 메일 확인용 토큰 발행 및 전송 처리
export const postLogin = async (req, res) => { export const postLogin = async (req, res) => {
const { const {
body: { email }, body: { email, isOAuth },
} = req; } = req;
const result = await db.User.findAll({ const result = await db.User.findAll({
...@@ -85,7 +114,22 @@ export const postLogin = async (req, res) => { ...@@ -85,7 +114,22 @@ export const postLogin = async (req, res) => {
logging: false, logging: false,
}); });
if (result.length != 0) { if (result.length !== 0) {
if (isOAuth) {
const payload = {
email: email,
};
const accessT = jwt.sign(payload, envs.secretKey.access_token, {
expiresIn: "14d",
issuer: "eue.com",
subject: "userInfo",
});
res
.cookie("acs_token", accessT)
.json({ msg: resForm.msg.ok, contents: { existing_user: true } });
} else {
try { try {
// token 발행 // token 발행
const mail_token = jwt.sign( const mail_token = jwt.sign(
...@@ -114,6 +158,7 @@ export const postLogin = async (req, res) => { ...@@ -114,6 +158,7 @@ export const postLogin = async (req, res) => {
contents: { existing_user: true, mail_sending: false, error: err }, contents: { existing_user: true, mail_sending: false, error: err },
}); });
} }
}
} else { } else {
res.json({ res.json({
msg: resForm.msg.err, msg: resForm.msg.err,
...@@ -158,7 +203,6 @@ export const getConfirm = async (req, res) => { ...@@ -158,7 +203,6 @@ export const getConfirm = async (req, res) => {
`${envs.client.protocol}://${envs.client.host}:${envs.client.port}/first-local-code` `${envs.client.protocol}://${envs.client.host}:${envs.client.port}/first-local-code`
); );
} catch (err) { } catch (err) {
console.log('22', err);
res.json({ msg: resForm.msg.err, contents: { error: err } }); res.json({ msg: resForm.msg.err, contents: { error: err } });
} }
}; };
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment