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;
// 해당 함수를 통해 카카오톡을 이용한 회원가입 혹은 로그인 처리
// isLogin : true - 카카오톡을 이용해 로그인 처리 || false - 카카오톡을 이용해 회원가입 처리
export function AuthWithKakao(isLogin) {
//authObj : response.data에 들어가 있는 부분 object 형식
Kakao.Auth.loginForm({
// 팝업 + 다른 아이디 로그인시
scope: "account_email, profile_nickname",
// 추가 동의 받을 동의 항목 ID 목록, 하나의 문자열에 여러 개의 ID를 쉼표(,)로 구분하여 전달
success: function (authObj) {
console.log(JSON.stringify(authObj));
export function LoginWithKakao() { Kakao.API.request({
//authObj : response.data에 들어가 있는 부분 object 형식 // 현재 로그인한 사용자의 카카오계정 정보 불러오기
Kakao.Auth.loginForm({ url: "/v2/user/me",
// 팝업 + 다른 아이디 로그인시 // 사용자 정보 요청 주소
scope: 'account_email, profile_nickname', data: {
// 추가 동의 받을 동의 항목 ID 목록, 하나의 문자열에 여러 개의 ID를 쉼표(,)로 구분하여 전달 property_keys: ["kakao_account.profile", "kakao_account.email"],
success: function (authObj) { // 파라미터를 통해 특정 사용자 정보만 지정해서 요청
console.log(JSON.stringify(authObj)) },
success: async function (response) {
console.log(response);
console.log(response.kakao_account.profile);
Kakao.API.request({ const nickValue = response.kakao_account.profile["nickname"];
// 현재 로그인한 사용자의 카카오계정 정보 불러오기 const emailValue = response.kakao_account.email;
url: '/v2/user/me',
// 사용자 정보 요청 주소
data: {
property_keys: ["kakao_account.profile", "kakao_account.email"]
// 파라미터를 통해 특정 사용자 정보만 지정해서 요청
},
success: async function (response) {
console.log(response);
console.log(response.kakao_account.profile);
const nickValue = response.kakao_account.profile['nickname'] await axios
const emailValue = response.kakao_account.email .post(
isLogin ? routesClient.login : routesClient.signup,
isLogin
? { email: emailValue, isOAuth: true }
: {
email: emailValue,
nick_name: nickValue,
isOAuth: true,
}
)
.then((res) => {
console.log("kakao", res);
await axios.post(routesClient.signup, { email: emailValue, nick_name: nickValue, isOauth: true }) if (
.then((res) => console.log('kakao', res)) (!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: isLogin ? "로그인 성공!" : "회원가입 성공!",
title: '로그인 성공!', text: "🙌 환영합니다 🙌",
text: '🙌 환영합니다 🙌', icon: "success",
icon: 'success', customClass: "swal-wide",
customClass: 'swal-wide', confirmButtonText: "확인",
confirmButtonText: '확인', }).then((result) => {
}).then((res) => { if (result.isConfirmed) {
if (res.isConfirmed) { window.location.replace(
// window.location.replace('/') isLogin ? "/" : "/first-local-code"
} );
else { } else {
// window.location.replace('/') 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) { });
alert(JSON.stringify(err)) },
console.log(JSON.stringify(err)) fail: function (err) {
}, alert(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;
} }
Kakao.Auth.logout(function () { Kakao.Auth.logout(function () {
// 로그인 시 발급받은 토큰을 만료시키는 함수 // 로그인 시 발급받은 토큰을 만료시키는 함수
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('/') }
} });
}) });
}) }
}
\ No newline at end of file
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 = {
display: "flex",
flexDirection: "column",
maxWidth: "80%",
justifyContent: "center",
margin: "auto",
padding: "0.5em",
color: "black",
};
const [alertShow, setAlertShow] = useState(false);
const [emailAddress, setEmailAddress] = useState("");
const [mailSend, setMailSend] = useState(false);
function addressUrl() {
const afterAt = emailAddress.split("@")[1];
if (afterAt) {
const newLink = "https://www." + afterAt;
window.location.replace(newLink);
} }
if (afterAt === "korea.ac.kr") {
const inboxstyled = { window.location.replace("https://www.gmail.com");
display: 'flex',
flexDirection: 'column',
maxWidth: '80%',
justifyContent: 'center',
margin: 'auto',
padding: '0.5em',
color: 'black'
} }
}
const [alertShow, setAlertShow] = useState(false)
const [emailAddress, setEmailAddress] = useState('') function handleChange(event) {
setEmailAddress(event.target.value);
const [mailSend, setMailSend] = useState(false) }
function addressUrl() { async function handleSubmit(event) {
const afterAt = emailAddress.split('@')[1] event.preventDefault();
if (afterAt) { const res = await axios.post(routesClient.login, {
const newLink = 'https://www.' + afterAt; email: emailAddress,
window.location.replace(newLink); isOauth: false,
} });
if (afterAt === 'korea.ac.kr') { console.log("mail_sending : ", res.data.contents.mail_sending);
window.location.replace('https://www.gmail.com'); setMailSend(res.data.contents.mail_sending);
} setAlertShow(true);
} localStorage.setItem("login", true);
}
function handleChange(event) {
setEmailAddress(event.target.value) return (
} <Row className="text-center w-100 my-2">
<Card style={cardstyled}>
async function handleSubmit(event) { <Card.Title id="impactTitle">로그인</Card.Title>
event.preventDefault(); <Card.Subtitle style={{ fontWeight: "lighter" }}>
const res = await axios.post(routesClient.login, { email: emailAddress, isOauth: false }) 이메일 또는 소셜미디어로 로그인하세요
console.log('mail_sending : ', res.data.contents.mail_sending) </Card.Subtitle>
setMailSend(res.data.contents.mail_sending) <hr />
setAlertShow(true) <Card.Text>
localStorage.setItem('login', true) <Row
} className="m-auto d-flex justify-content-center"
style={{ width: "80%" }}
>
return ( {mailSend ? (
<Row className='text-center w-100 my-2'> <Alert show={alertShow} variant={"success"}>
<Card style={cardstyled}> <Col>😍 이메일 전송이 완료 되었습니다.</Col>
<Card.Title id='impactTitle'> <Alert.Link
로그인 href=""
</Card.Title> onClick={addressUrl}
<Card.Subtitle style={{ fontWeight: 'lighter' }}> target="_blank"
이메일 또는 소셜미디어로 로그인하세요 style={{ fontSize: "0.8em" }}
</Card.Subtitle> >
<hr /> 이메일 확인 하러가기
<Card.Text> </Alert.Link>
<Row className='m-auto d-flex justify-content-center' style={{ width: '80%' }}> </Alert>
{mailSend ? ) : (
<Alert show={alertShow} variant={'success'}> <Alert show={alertShow} variant={"danger"}>
<Col> <Col>😭 이메일을 정확하게 적어주세요.</Col>
😍 이메일 전송이 완료 되었습니다. <Alert.Link
</Col> href="/signup"
<Alert.Link href="" onClick={addressUrl} target='_blank' style={{ fontSize: '0.8em' }}> target="_blank"
이메일 확인 하러가기 style={{ fontSize: "0.8em" }}
</Alert.Link> >
</Alert> 회원가입 하러가기
: </Alert.Link>
<Alert show={alertShow} variant={'danger'}> </Alert>
<Col> )}
😭 이메일을 정확하게 적어주세요. </Row>
</Col>
<Alert.Link href="/signup" target='_blank' style={{ fontSize: '0.8em' }}> <Form style={inboxstyled} onSubmit={handleSubmit}>
회원가입 하러가기 <FloatingLabel label="Email">
</Alert.Link> <Form.Control
</Alert> type="email"
} placeholder="Email"
</Row> onChange={handleChange}
required
<Form style={inboxstyled} onSubmit={handleSubmit}> />
<FloatingLabel label="Email"> </FloatingLabel>
<Form.Control type="email" placeholder="Email" onChange={handleChange} required /> <Button variant="light" className="mt-3" id="formbtn" type="submit">
</FloatingLabel> 로그인
<Button variant='light' className='mt-3' id='formbtn' type='submit'> </Button>
로그인 </Form>
</Button>
</Form> <Row className="d-flex align-items-center m-2">
<Col>
<Row className='d-flex align-items-center m-2'> <hr />
<Col> </Col>
<hr /> OR
</Col> <Col>
OR <hr />
<Col> </Col>
<hr /> </Row>
</Col>
</Row> <Row
style={{
<Row style={{ margin: 'auto', marginBottom: '5px', display: 'flex', justifyContent: 'center' }}> margin: "auto",
<a href="#;" onClick={LoginWithKakao} id='socialLink' > marginBottom: "5px",
{/* 세미콜론이 붙으면 최상단 이동 x */} display: "flex",
<img src='http://image.kmib.co.kr/online_image/2020/0626/611514110014734788_1.jpg' id='logpng' alt='KAKAO' /> justifyContent: "center",
</a> }}
>
</Row> <a href="#;" onClick={() => AuthWithKakao(true)} id="socialLink">
</Card.Text> {/* 세미콜론이 붙으면 최상단 이동 x */}
</Card> <img
src="http://image.kmib.co.kr/online_image/2020/0626/611514110014734788_1.jpg"
</Row> id="logpng"
) alt="KAKAO"
/>
</a>
</Row>
</Card.Text>
</Card>
</Row>
);
} }
export default LoginComp; export default LoginComp;
\ No newline at end of file
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 = {
margin: "auto",
padding: "1em",
display: "flex",
justifyContent: "center",
width: "100%",
borderWidth: "3px",
borderRadius: "20px",
borderColor: "rgb(110, 189, 142)",
color: "#04AB70",
};
const cardstyled = { const inboxstyled = {
margin: 'auto', display: "flex",
padding: '1em', flexDirection: "column",
display: 'flex', maxWidth: "80%",
justifyContent: 'center', justifyContent: "center",
width: '100%', margin: "auto",
borderWidth: '3px', padding: "0.5em",
borderRadius: '20px', color: "black",
borderColor: 'rgb(110, 189, 142)', };
color: '#04AB70'
}
const inboxstyled = { const initValues = {
display: 'flex', nick_name: "",
flexDirection: 'column', email: "",
maxWidth: '80%', isOAuth: false,
justifyContent: 'center', };
margin: 'auto',
padding: '0.5em',
color: 'black'
}
const initValues = { const [formValues, setFormValues] = useState(initValues);
nick_name: '',
email: '',
isOauth: false
}
const [formValues, setFormValues] = useState(initValues) const [userExist, setUserExist] = useState(false);
const [alertShow, setAlertShow] = useState(false);
const [userExist, setUserExist] = useState(false) function handleChange(event) {
const [alertShow, setAlertShow] = useState(false) const { name, value } = event.target;
setFormValues({ ...formValues, [name]: value });
}
function handleChange(event) { async function handleSubmit(event) {
const { name, value } = event.target event.preventDefault();
setFormValues({ ...formValues, [name]: value }) const res = await axios.post(routesClient.signup, formValues);
} console.log("existing_user : ", res.data.contents.existing_user);
setUserExist(res.data.contents.existing_user);
setAlertShow(true);
}
async function handleSubmit(event) { return (
event.preventDefault(); <Row className="text-center w-100 my-2">
const res = await axios.post(routesClient.signup, formValues) <Card style={cardstyled}>
console.log('existing_user : ', res.data.contents.existing_user) <Card.Title id="impactTitle">계정 생성하기</Card.Title>
setUserExist(res.data.contents.existing_user) <Card.Subtitle style={{ fontWeight: "lighter" }}>
setAlertShow(true) 이메일 또는 소셜미디어로 계정을 생성하세요
} </Card.Subtitle>
<hr />
<Card.Text>
<Row
className="m-auto d-flex justify-content-center"
style={{ width: "80%" }}
>
{!userExist ? (
<Alert show={alertShow} variant={"success"}>
<Col>😊 계정 생성이 완료 되었습니다.</Col>
<Alert.Link href="/login" style={{ fontSize: "0.8em" }}>
로그인 하러가기
</Alert.Link>
</Alert>
) : (
<Alert show={alertShow} variant={"danger"}>
<Col>🤔 이미 존재하는 계정입니다.</Col>
<Alert.Link href="/login" style={{ fontSize: "0.8em" }}>
로그인 하러가기
</Alert.Link>
</Alert>
)}
</Row>
return ( <Form style={inboxstyled} onSubmit={handleSubmit}>
<FloatingLabel label="Nickname" className="mb-3">
<Form.Control
type="text"
name="nick_name"
placeholder="Nickname"
onChange={handleChange}
required
/>
</FloatingLabel>
<FloatingLabel label="Email Address">
<Form.Control
type="email"
name="email"
placeholder="Email Address"
onChange={handleChange}
required
/>
</FloatingLabel>
<Row className='text-center w-100 my-2'> <Button variant="light" className="mt-3" id="formbtn" type="submit">
<Card style={cardstyled}> 회원가입
<Card.Title id='impactTitle'> </Button>
계정 생성하기 </Form>
</Card.Title>
<Card.Subtitle style={{ fontWeight: 'lighter' }}>
이메일 또는 소셜미디어로 계정을 생성하세요
</Card.Subtitle>
<hr />
<Card.Text>
<Row className='m-auto d-flex justify-content-center' style={{ width: '80%' }}>
{!userExist ?
<Alert show={alertShow} variant={'success'}>
<Col>
😊 계정 생성이 완료 되었습니다.
</Col>
<Alert.Link href='/login' style={{ fontSize: '0.8em' }}>
로그인 하러가기
</Alert.Link>
</Alert>
:
<Alert show={alertShow} variant={'danger'}>
<Col>
🤔 이미 존재하는 계정입니다.
</Col>
<Alert.Link href='/login' style={{ fontSize: '0.8em' }}>
로그인 하러가기
</Alert.Link>
</Alert>
}
</Row>
<Form style={inboxstyled} onSubmit={handleSubmit}> <Row className="d-flex align-items-center m-2">
<FloatingLabel <Col>
label="Nickname" <hr />
className='mb-3' </Col>
> OR
<Form.Control <Col>
type="text" <hr />
name="nick_name" </Col>
placeholder="Nickname" </Row>
onChange={handleChange}
required
/>
</FloatingLabel>
<FloatingLabel
label="Email Address"
>
<Form.Control
type="email"
name="email"
placeholder="Email Address"
onChange={handleChange}
required
/>
</FloatingLabel>
<Button variant='light' className='mt-3' id='formbtn' type='submit'> <Row
회원가입 style={{
</Button> margin: "auto",
</Form> marginBottom: "5px",
display: "flex",
<Row className='d-flex align-items-center m-2'> justifyContent: "center",
<Col> }}
<hr /> >
</Col> <a href="#;" onClick={() => AuthWithKakao(false)} id="socialLink">
OR <img
<Col> src="http://image.kmib.co.kr/online_image/2020/0626/611514110014734788_1.jpg"
<hr /> id="logpng"
</Col> alt="KAKAO"
</Row> />
</a>
<Row style={{ margin: 'auto', marginBottom: '5px', display: 'flex', justifyContent: 'center' }}> </Row>
<a href="#;" onClick={LoginWithKakao} id='socialLink' > </Card.Text>
<img src='http://image.kmib.co.kr/online_image/2020/0626/611514110014734788_1.jpg' id='logpng' alt='KAKAO' /> </Card>
</a> </Row>
</Row> );
</Card.Text>
</Card>
</Row>
)
} }
export default SignupComp; export default SignupComp;
\ No newline at end of file
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;
else { setLocalState(localName);
const localName = res[0].loc_name }
setLocalState(localName) }
} });
} }, []);
})
}, []) return (
<Col className="text-center pb-2 px-0">
<Card style={cardstyled} id="localName">
return ( <Card.Title>
<Col className='text-center pb-2 px-0'> <strong>
<Card style={cardstyled} id='localName'> {isLogined() ? <h3>{`${userNick}`}</h3> : <h3>손 님</h3>}
<Card.Title> </strong>
<strong> <p style={{ fontWeight: "300", margin: "0" }}>환영합니다</p>
{isLogined() ? </Card.Title>
<h3> <hr />
{`${userNick}`} <Row
</h3> style={{
: alignItems: "center",
<h3> margin: "auto",
justifyContent: "center",
</h3> }}
} >
</strong> <Card.Subtitle>
<p style={{ fontWeight: '300', margin: '0' }}> {isLogined() ? (
환영합니다 <div className="mb-2">
</p> <div>{showState}</div>
</Card.Title>
<hr /> <div id="local_state">
<Row style={{ alignItems: 'center', margin: 'auto', justifyContent: 'center' }}> {`${localState["doe"]}`}
<Card.Subtitle> <br />
{isLogined() ? {`${localState["sgg"]}`}
<div className='mb-2'> <br />
<div> {`${localState["emd"]}`}
{showState} </div>
</div> </div>
) : (
<div id='local_state'> <div className="mb-2">로그인 이용 가능합니다</div>
{`${localState['doe']}`} )}
<br /> </Card.Subtitle>
{`${localState['sgg']}`}
<br /> {isLogined() && (
{`${localState['emd']}`} <Button
</div> variant="light"
className="m-auto d-flex"
</div> style={btnstyled2}
: >
<div className='mb-2'> <Link
로그인 이용 가능합니다 to="/edit"
</div> className="w-100"
} style={{ textDecoration: "none", color: "rgb(110, 189, 142)" }}
</Card.Subtitle> >
변경
{isLogined() && </Link>
<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)' }}> )}
변경 </Row>
</Link> {isLogined() && (
</Button> <Card.Text>
} <hr />
</Row> <Row style={{ color: "black" }}>
{isLogined() && <p style={{ fontWeight: "300", margin: "0" }}>환경을 향한 노력</p>
<Card.Text> <h3 style={{ fontWeight: "300", color: "#2b90d9", margin: "0" }}>
<hr /> <strong>{createdTime}</strong> 일
<Row style={{ color: 'black' }}> </h3>
<p style={{ fontWeight: '300', margin: '0' }}> </Row>
환경을 향한 노력 </Card.Text>
</p> )}
<h3 style={{ fontWeight: '300', color: '#2b90d9', margin: '0' }}> </Card>
<strong>{createdTime}</strong> 일 </Col>
</h3> );
</Row>
</Card.Text>
}
</Card>
</Col>
)
} }
export default UserInfo; export default UserInfo;
\ No newline at end of file
...@@ -25,10 +25,13 @@ const postMail = async (email, token) => { ...@@ -25,10 +25,13 @@ 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}">${
}?token=${token}</a>`, envs.server.protocol
}://${envs.server.host}:${envs.server.port}${
routes.base + routes.confirm
}?token=${token}</a>`,
}; };
try { try {
...@@ -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(
res.json({ msg: resForm.msg.ok, contents: { existing_user: false } }); { 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 } });
}
} }
}; };
// 메일 확인용 토큰 발행 및 전송 처리 // 메일 확인용 토큰 발행 및 전송 처리
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,34 +114,50 @@ export const postLogin = async (req, res) => { ...@@ -85,34 +114,50 @@ export const postLogin = async (req, res) => {
logging: false, logging: false,
}); });
if (result.length != 0) { if (result.length !== 0) {
try { if (isOAuth) {
// token 발행 const payload = {
const mail_token = jwt.sign( email: email,
{ };
email: email,
},
envs.secretKey.mail,
{
expiresIn: 10 * 60,
issuer: "eue.com",
subject: "auth_checker",
}
);
// 토큰이 포함된 로그인 링크 전송 const accessT = jwt.sign(payload, envs.secretKey.access_token, {
postMail(email, mail_token); expiresIn: "14d",
issuer: "eue.com",
res.json({ subject: "userInfo",
msg: resForm.msg.ok,
contents: { existing_user: true, mail_sending: true },
});
} catch (err) {
console.log(err);
res.json({
msg: resForm.msg.err,
contents: { existing_user: true, mail_sending: false, error: err },
}); });
res
.cookie("acs_token", accessT)
.json({ msg: resForm.msg.ok, contents: { existing_user: true } });
} else {
try {
// token 발행
const mail_token = jwt.sign(
{
email: email,
},
envs.secretKey.mail,
{
expiresIn: 10 * 60,
issuer: "eue.com",
subject: "auth_checker",
}
);
// 토큰이 포함된 로그인 링크 전송
postMail(email, mail_token);
res.json({
msg: resForm.msg.ok,
contents: { existing_user: true, mail_sending: true },
});
} catch (err) {
console.log(err);
res.json({
msg: resForm.msg.err,
contents: { existing_user: true, mail_sending: false, error: err },
});
}
} }
} else { } else {
res.json({ res.json({
...@@ -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