Skip to content

Commit

Permalink
Merge pull request #97 from CartoonIsArt/development
Browse files Browse the repository at this point in the history
라이브러리 최신화 및 JWT 기반 인증 구현
  • Loading branch information
droplet92 committed Mar 13, 2021
2 parents 3462b10 + 96b3c5d commit 7be28f9
Show file tree
Hide file tree
Showing 35 changed files with 1,425 additions and 984 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Expand Up @@ -4,4 +4,5 @@ node_modules
.vscode
yarn-error.log
.idea
db
db/
*.sql
16 changes: 0 additions & 16 deletions .travis.yml

This file was deleted.

Binary file removed db/test.sql
Binary file not shown.
2 changes: 1 addition & 1 deletion ormconfig.json
@@ -1,6 +1,6 @@
{
"type": "sqlite",
"database": "db/test.sql",
"database": "db/test.sqlite",
"synchronize": true,
"logging": false,
"entities": [
Expand Down
9 changes: 6 additions & 3 deletions package.json
Expand Up @@ -4,14 +4,17 @@
"description": "koa restful example",
"main": "app.js",
"dependencies": {
"@koa/cors": "2",
"@koa/cors": "^3.1.0",
"@mapbox/node-pre-gyp": "^1.0.0",
"@types/node": "^8.0.47",
"koa": "^2.3.0",
"jsonwebtoken": "^8.5.1",
"koa": "^2.13.1",
"koa-bodyparser": "^4.2.0",
"koa-jwt": "^4.0.0",
"koa-logger": "^3.1.0",
"koa-router": "^7.2.1",
"koa-views": "^6.1.1",
"sqlite3": "^3.1.13",
"sqlite3": "^5.0.2",
"typeorm": "next",
"typescript": "^2.6.1"
},
Expand Down
28 changes: 18 additions & 10 deletions src/app.ts
Expand Up @@ -4,16 +4,16 @@ import * as logger from "koa-logger"
import * as Serve from "koa-static"
import * as path from "path"
import "reflect-metadata"
import { Connection, createConnection } from "typeorm"
// import leaver from "./leaver"
import { router } from "./route"
import session from "./session"
import { createConnection } from "typeorm"
import { router } from "./middleware/route"
import refresher from "./middleware/refresher"

const cors = require('@koa/cors')
const jwt = require('koa-jwt')

const app = new Koa()
app.proxy = true
app.use(cors())
app.use(cors({ origin: '*', credentials: true }))

/* DB와 연결을 맺고 Connection Pool을 생성함 */
// tslint:disable-next-line
Expand All @@ -30,11 +30,19 @@ if (process.env.NODE_ENV !== "production") {
app.use(Serve(path.join("test-restful", "dist")))
}

/* DB에 탈퇴 회원 추가 */
// app.use(leaver)

/* 세션 */
app.use(session)
/* authentication */
app.use(jwt({
secret: 'secretKey',
cookie: 'accessToken',
key: 'token',
passthrough: true,
})
.unless({
path: [/^\/api\/public(?:\/)?/]
})
)

app.use(refresher)

/* 라우팅 */
app.use(router.routes())
Expand Down
16 changes: 0 additions & 16 deletions src/auth/auth.ts

This file was deleted.

23 changes: 23 additions & 0 deletions src/auth/index.ts
@@ -0,0 +1,23 @@
import { Connection, getConnection } from "typeorm"
import * as crypto from "crypto"
import User from "../entities/user"

export async function Authenticate (username: string, password: string): Promise<User> {
const conn: Connection = getConnection()
const users: User[] = await conn
.getRepository(User)
.find({
where: {
username,
},
relations: ['profileImage']
})
const user = users[0]

const [encryptedKey, salt] = user.password.split("@")
const derivedKey = crypto.pbkdf2Sync(password, salt, 131071, 64, 'sha512')

if (derivedKey.toString('hex') !== encryptedKey)
throw new Error('password mismatch')
return user
}
60 changes: 60 additions & 0 deletions src/controllers/authenticationToken.ts
@@ -0,0 +1,60 @@
import { Connection, getConnection } from "typeorm"
import AuthenticationToken from "../entities/authenticationToken"
import { ipToInt } from "../lib/ip2int"
import { cookieExpirationDate } from "../lib/date"
import { Authenticate } from "../auth"

const jwt = require('jsonwebtoken')

/* 로그인 */
export const Login = async (ctx, next) => {
const authenticationToken: AuthenticationToken = new AuthenticationToken()
const conn: Connection = getConnection()

try {
// 1. User authentication
const {
username,
password,
} = ctx.request.body

const user = await Authenticate(username, password)

// 2. Issue access token and refresh token
const accessToken = jwt.sign({ user }, 'secretKey', { expiresIn: '1h' })
const refreshToken = jwt.sign({ user }, 'secretKey', { expiresIn: '14d' })

// 3. Set authentication token cookie
ctx.cookies.set('accessToken', accessToken, { expires: cookieExpirationDate() })

// 4. Save refresh token to database
authenticationToken.accessToken = accessToken
authenticationToken.refreshToken = refreshToken
authenticationToken.accessIp = ipToInt(ctx.ip)

await conn.manager.save(authenticationToken)
}
catch (e){
ctx.throw(400, e)
}

/* 로그인 완료 응답 */
ctx.response.status = 200
}

/* 로그아웃 */
export const Logout = async (ctx, next) => {
try {
const conn: Connection = getConnection()
await conn.manager.delete(AuthenticationToken, ctx.authenticationToken.id)

ctx.status = 204
ctx.redirect("/")
}
catch (e) {
ctx.throw(400, e)
}

/* 로그아웃 완료 응답 */
ctx.response.status = 204
}
101 changes: 0 additions & 101 deletions src/controllers/cia.ts

This file was deleted.

0 comments on commit 7be28f9

Please sign in to comment.