박권수

feat. authorization logic implemented

1 //회원가입, 로그인 및 로그아웃에 관한 api 1 //회원가입, 로그인 및 로그아웃에 관한 api
2 const User = require('../../models/user'); 2 const User = require('../../models/user');
3 const Joi = require('joi'); 3 const Joi = require('joi');
4 -const jwt = require('jsonwebtoken');
5 4
6 exports.register = async(ctx) => { 5 exports.register = async(ctx) => {
7 - ctx.body = 'register' 6 + const { userId, password, passwordCheck } = ctx.request.body;
7 +
8 + const schema = Joi.object.keys({
9 + userId : Joi.string().min(8).max(15).required(),
10 + password : Joi.string().required(),
11 + passwordCheck : Joi.string().required(),
12 + })
13 +
14 + const result = schema.validate(ctx.request.body);
15 + if(result.error || password !== passwordCheck) {
16 + ctx.status = 400;
17 + return;
18 + }
19 +
20 + const existUser = await User.findByUserId(userId);
21 + if(existUser) {
22 + ctx.status = 409;
23 + return;
24 + }
25 +
26 + const user = new User({
27 + userId
28 + });
29 +
30 + await user.setPassword(password);
31 + await user.save();
32 +
33 + ctx.status = 200;
34 +
8 }; 35 };
9 36
10 exports.login = async(ctx) => { 37 exports.login = async(ctx) => {
11 - ctx.body = 'login' 38 + const { userId, password } = ctx.request.body;
39 +
40 + const schema = Joi.object.keys({
41 + userId : Joi.string().min(8).max(15).required(),
42 + password : Joi.string().required()
43 + })
44 +
45 + const result = schema.validate(ctx.request.body);
46 + if(result.error) {
47 + ctx.status = 400;
48 + return;
49 + }
50 +
51 + const user = await User.findByUserId(userId);
52 + if(!user) {
53 + ctx.stauts = 401;
54 + return;
55 + }
56 +
57 + const isPasswordTrue = await user.checkPassword(password);
58 + if(!isPasswordTrue) {
59 + ctx.status = 401;
60 + return;
61 + }
62 +
63 + const token = await user.generateToken();
64 + ctx.cookies.set('access_token', token, {
65 + httpOnly : true,
66 + maxAge : 1000 * 60 * 60 * 24 * 30
67 + });
68 +
69 + ctx.status = 201;
70 + ctx.body = user;
71 +
12 }; 72 };
13 73
14 exports.logout = async(ctx) => { 74 exports.logout = async(ctx) => {
15 - ctx.body = 'logout' 75 + ctx.cookies.set('access_token', null, {
76 + httpOnly : true,
77 + maxAge : 0
78 + });
79 + ctx.status = 204;
80 + ctx.body = null;
16 }; 81 };
...\ No newline at end of file ...\ No newline at end of file
......