auth.ctrl.js 11.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
const Joi = require('@hapi/joi');
const User = require('../../models/user');
const Book = require('../../models/book');
const Page = require('../../models/page');
const nodemailer = require('nodemailer');
const config = require('../../lib/config');
const { Mongoose } = require('mongoose');
const { exist, allow } = require('@hapi/joi');
const fs = require('fs');
exports.test = async (ctx) => {
  console.log('cookie');
  ctx.cookies.set('second', 22222, {
    httpOnly: false
  })
  ctx.body = {code: 200, message: 'success'}
};

exports.signupLocal = async (ctx) => {
  const { email, password, address } = ctx.request.body;
  console.log(ctx.request.body);
  const schema = Joi.object().keys({
    email: Joi.string().min(3).required(),
    password: Joi.string().required(),
    phone: Joi.string().allow(null, ''),
    nickname:Joi.string().allow(null, '')
  });

  //검증 결과
  try {
    const value = await schema.validateAsync(ctx.request.body);
  } catch (err) {
    console.log(err);
    ctx.status = 400;
    return;
  }

  try {
    // email 이미 존재하는지 확인
    const exists = await User.findByEmail(email);
    if (exists) {
      ctx.status = 409; // Conflict
      return;
    }

    let account = null;
    try {
        account = await User.localRegister(ctx.request.body);
    } catch (e) {
        ctx.throw(500, e);
    }

    let token = null;
    try {
        token = await account.generateToken();
        console.log('token ok');
    } catch (e) {
        ctx.throw(500, e);
    }
    ctx.cookies.set('access_token', token, { maxAge: 1000 * 60 * 60 * 24 * 7 ,httpOnly: true,});
    console.log('set cookie ok');

    // 응답할 데이터에서 hashedPassword 필드 제거
    ctx.status = 200;
    ctx.body = await account.serialize();
  } catch (e) {
    ctx.throw(500, e);
  }
};
exports.signinLocal = async (ctx) => {
  // 로그인
  const { email, password } = ctx.request.body;

  //handle error
  if (!email || !password) {
    ctx.status = 401; //Unauthorized
    return;
  }
  try {
    const user = await User.findOne({ email: email });
    //const user = await User.findByEmail(email);
    //계정없으면 에러처리
    console.log(user);
    if (!user) {
      ctx.status = 401;
      return;
    }

    const valid = await user.checkPassword(password);
    if (!valid) {
      ctx.status = 401;
      return;
    }
    ctx.body = await user.serialize();
    const token = user.generateToken();
    ctx.cookies.set('access_token', token, {
      maxAge: 1000 * 60 * 60 * 24 * 7, // 7일
      httpOnly: false,
    });
    ctx.status = 200;
    console.log('토큰나옴');
  } catch (e) {
    ctx.throw(500, e);
  }
};


/*
exports.localLogin = async (ctx) => {
  // 데이터 검증
  const schema = Joi.object().keys({
      email: Joi.string().email().required(),
      password: Joi.string().required()
  });

  const result = Joi.validate(ctx.request.body, schema);

  if (result.error) {
      ctx.status = 400; // Bad Request
      return;
  }

  const { email, password } = ctx.request.body;

  let account = null;
  try {
      // 이메일로 계정 찾기
      account = await User.findByEmail(email);
  }
  catch (e) {
      ctx.throw(500, e);
  }

  if (!account || !account.checkPassword(password)) {
      // 유저가 존재하지 않거나 || 비밀번호가 일치하지 않으면
      ctx.status = 403; // Forbidden
      return;
  }

  let token = null;
  try {
      token = await account.generateToken();
  } catch (e) {
      ctx.throw(500, e);
  }

  ctx.cookies.set('access_token', token, { httpOnly: true, maxAge: 1000 * 60 * 60 * 24 * 7 });
  ctx.body = account.email;
};*/
exports.userlist = async (ctx) => {
  let user;

    try {
        user = await User.find()
            .sort({created: -1})
            .exec();
    } catch (e) {
        return ctx.throw(500, e);
    }

    ctx.body = user;
}

exports.exists = async (ctx) => {
  const { email } = ctx.request.body;
  
  try {
    const exists = await User.findByEmail(email);
    if (exists) {
      ctx.status = 409; 
      return;
    }
    ctx.status = 200;
  } catch (e) {
    ctx.throw(500, e);
  }
};

exports.checkPassword = async (ctx) => {
  const { email, password } = ctx.request.body;
  
  try {
    const user = await User.findOne({ email: email });
    const valid = await user.checkPassword(password);
    if (valid) {
      ctx.status = 200;
      console.log("Check password success");
      return;
    } else if(!valid){
      ctx.status = 401;
      console.log("Check password fail");
      return;
    }
  } catch (e) {
    ctx.throw(500, e);
  }
};
//회원가입
exports.signup = async (ctx) => {
  const { email, password, phone, fcmToken } = ctx.request.body;
  const schema = Joi.object().keys({
    email: Joi.string().min(3).required(),
    password: Joi.string().required().min(6),
    phone: Joi.string().allow(null, ''),
    fcmToken: Joi.string().allow(null, ''),
    nickname:Joi.string().allow(null, '')
  });

  let value= null;
  try {
    value = await schema.validateAsync(ctx.request.body);
  } catch (err) {
    console.log(err);
    ctx.status = 400;
    return;
  }

  try {
    // email 이미 존재하는지 확인
    const exists = await User.findByEmail(email);
    if (exists) {
      ctx.status = 409; // Conflict
      ctx.body = {
        key: exists.email === ctx.request.body.email ? 'email' : 'username'
    };
      return;
    }
  }catch(e)
  {
    ctx.throw(500, e);
  }

    let account = null;
    try {
        account = await User.localRegister(ctx.request.body);
    } catch (e) {
        ctx.throw(500, e);
    }

    let token = null;
    try {
        token = await account.generateToken();
        console.log('token ok');
    } catch (e) {
        ctx.throw(500, e);
    }
    ctx.cookies.set('access_token', token, { maxAge: 1000 * 60 * 60 * 24 * 7 ,httpOnly: true,});
    console.log('set cookie ok');

   // const user = new User(ctx.request.body);
    console.log(ctx.cookies);
    ctx.status = 200;
};

exports.signin = async (ctx) => {
  // 로그인
  const { email, password } = ctx.request.body;

  //handle error
  if (!email || !password) {
    ctx.status = 401; //Unauthorized
    return;
  }
  let user = null;
  try {
    user = await User.findOne({ email: email });
    //const user = await User.findByEmail(email);
    //계정없으면 에러처리
    if (!user) {
      ctx.status = 401;
      return;
    }
  } catch (e) {
    ctx.throw(500, e);
  }
    const valid = await user.checkPassword(password);
    if (!valid) {
      ctx.status = 401;
      return;
    }
    console.log(user);
    console.log('check password');
    let token = null;
    try{
      token = await user.generateToken();
    }catch (e) {
    ctx.throw(500, e);
  }
    ctx.cookies.set('access_token', token, {
      maxAge: 1000 * 60 * 60 * 24 * 7, // 7일
      httpOnly: true,
    });
    console.log('login cookie');
    
    ctx.status = 200;
    console.log('200');
};

exports.check = async (ctx) => {
  const { user } = ctx.state;
  if (!user) {
    ctx.status = 401;
    return;
  }
  ctx.body = user;
  // 로그인 상태 확인
};
exports.check2 = (ctx) => {
  const { user } = ctx.request;

  if(!user) {
      ctx.status = 403; // Forbidden
      return;
  }

  ctx.body = user.profile;
};



exports.signout = async (ctx) => {
  ctx.cookies.set('access_token');
  ctx.status = 204;
};

exports.Withdrawal = async (ctx) => {
    try {
      ctx.cookies.set('access_token');
      await Book. //delete pets owned by user
      User.deleteOne({ email: ctx.state.user.email }, function (err) {}); //delete user
    } catch (err) {
      ctx.throw(500, e);
    }
  
  ctx.status = 200;
};

exports.userinfo = async (ctx) => {
  const { _id } = ctx.state.user;
  try {
    const user = await User.findById(_id).exec();
    ctx.status = 200;
    ctx.body = await user.serialize();
  } catch (e) {
    ctx.throw(500, e);
  }
};

exports.updateUser = async (ctx) => {
  // 이메일 변경 불가
  // 비밀번호 변경은 따로
  //책과 게시글은 따로
  const schema = Joi.object().keys({
    // password: Joi.string().min(6).max(20).required(),
    username: Joi.string().allow(null, ''),
    phone: Joi.string().allow(null, ''),
    nickname: Joi.string().allow(null, ''),
    fcmToken: Joi.string(),
    // birth: Joi.date()
  });
  
  try {
    const value = await schema.validateAsync(ctx.request.body);
  } catch (err) {
    console.log(err);
    ctx.status = 400;
    return;
  }

  ctx.request.body.email = ctx.state.user.email;

  try {
    User.updateUser(ctx.request.body);
  } catch (e) {
    ctx.throw(500, e);
  }
  ctx.status = 200;
};

exports.changePassword = async (ctx) => {
  const schema = Joi.object().keys({
    email: Joi.string(),
    password: Joi.string().min(6).max(20).required(),
  });

  try {
    const value = await schema.validateAsync(ctx.request.body);
  } catch (err) {
    ctx.status = 400;
    return;
  }
  User.updatePassword(ctx.request.body.email, ctx.request.body.password);
  ctx.status = 200;
  ctx.body = { message: '비밀번호 변경 완료' };
};

exports.findPassword = async (ctx) => {
  var status = 400;

  // 전송 옵션 설정
  // trainsporter: is going to be an object that is able to send mail
  let transporter = nodemailer.createTransport({
    service: 'gmail',
    host: 'smtp.gmail.com',
    // port: 587,
    port: 465,
    secure: true,
    auth: {
      user: config.mailer.user, //gmail주소입력
      pass: config.mailer.password, //gmail패스워드 입력
    },
  });

  var mailOptions = {
    from: `"Like project"<${config.mailer.user}>`, //enter the send's name and email
    to: ctx.request.body.email, // recipient's email
    subject: 'Like password', // title of mail
    html: `안녕하세요, 글을 나누는 즐거움 Like 입니다.
              <br />
              인증번호는 다음과 같습니다.
              <br />
              ${ctx.request.body.numsend}`,
  };

  try {
    await transporter.sendMail(mailOptions, async function (error, info) {
      if (error) {
        ctx.status = 401;
        return;
      } else {
        console.log('Email sent: ' + info.response);
        ctx.body = { success: true };
        status = 200;
      }
    });
  } catch (e) {
    ctx.throw(500, e);
  }
  ctx.status = 200;

};

//favorite(즐겨찾기)
exports.addFavorite = async (ctx) => {
  id = ctx.request.body.contentsid;
  try {
    await User.updateFavorite(ctx.state.user.email, id);
  } catch (e) {
    console.log(e);
  }

  ctx.status = 200;
};

exports.delFavorite = async (ctx) => {
  try {
    await User.delFavorites(ctx.state.user.email, ctx.query.contentsid);
  } catch (e) {
    ctx.throw(500, e);
  }
  ctx.status = 200;
};

exports.showFavorite = async (ctx) => {
  try {
    const user = await User.findById(ctx.state.user._id).exec();
    //url, title, image
    const favbooks = await Book.find({_id:{$in:user.favorite}});
    ctx.status = 200;
    ctx.body = favbooks;
  } catch (e) {
    ctx.throw(500, e);
  }
};


exports.getUserBook = async (ctx) => {
  const user = await User.findById(ctx.state.user._id).exec();
    try {
      const mybook = await Book.find({_id:{$in:user.books}});
      ctx.body = mybook;
    } catch (e) {
      ctx.throw(500, e);
    }
      //const user = await User.findById(mybook.author).exec();

    
};