Skip to content

Commit

Permalink
fix login and more structures
Browse files Browse the repository at this point in the history
  • Loading branch information
SeaniaTwix committed Jun 30, 2022
1 parent d0e073c commit bad1209
Show file tree
Hide file tree
Showing 26 changed files with 387 additions and 110 deletions.
1 change: 1 addition & 0 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,6 @@ module.exports = {
},
rules: {
'no-async-promise-executor': 'off',
'@typescript-eslint/no-non-null-assertion': 'off',
}
};
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"scripts": {
"dev": "svelte-kit dev --port 60000",
"build": "svelte-kit build",
"start": "node run.js",
"package": "svelte-kit package",
"preview": "svelte-kit preview",
"prepare": "svelte-kit sync",
Expand All @@ -17,6 +18,7 @@
"@playwright/test": "^1.22.2",
"@sveltejs/adapter-auto": "next",
"@sveltejs/kit": "next",
"@types/js-cookie": "^3.0.2",
"@types/lodash-es": "^4.17.6",
"@types/secure-random": "^1.1.0",
"@typescript-eslint/eslint-plugin": "^5.27.0",
Expand All @@ -42,12 +44,15 @@
"argon2": "^0.28.5",
"date-fns": "^2.28.0",
"date-fns-tz": "^1.3.5",
"dto-mapping": "^1.1.0",
"http-status-codes": "^2.2.0",
"js-cookie": "^3.0.1",
"ky": "^0.31.0",
"ky-universal": "^0.10.1",
"lodash-es": "^4.17.21",
"material-icons": "^1.11.3",
"njwt": "^1.2.0",
"polka": "^0.5.2",
"sass": "^1.53.0",
"secure-random": "^1.1.2",
"svelte-material-icons": "^2.0.2"
Expand Down
75 changes: 63 additions & 12 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions run.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import polka from 'polka';
import {handler} from './build/handler';

const server = polka();

server
.use(handler)
.listen(process?.env?.PORT ?? 3000)
44 changes: 43 additions & 1 deletion src/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,55 @@
import type {RequestEvent, ResolveOptions} from '@sveltejs/kit';
import type {MaybePromise} from '@sveltejs/kit/types/private';

import _ from 'lodash-es';
import njwt from 'njwt';
import {CookieParser} from './lib/cookie-parser';
import {key} from './lib/auth/user/server';

/** @type {import('@sveltejs/kit').Handle} */
export async function handle({event, resolve}: HandleParameter) {
try {
event.locals.user = await getUser(event.request.headers.get('cookie'));
} catch (e) {
console.error('[hooks]', e);
}
const response = await resolve(event);
return response;
}

async function getUser(cookie: string | null) {
if (_.isEmpty(cookie)) {
return undefined;
}

const cookies = (new CookieParser(cookie!)).get();
if (!cookies.token) {
return undefined;
}

const jwt = njwt.verify(cookies.token, key);
if (!jwt) {
return undefined;
}

if (jwt.isExpired()) {
const refresh = njwt.verify(cookies.refresh ?? '');
if (refresh?.isExpired() === false) {
// todo: sign again
}
}

const body = jwt.body.toJSON();
}

declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace App {
interface Locals {
user: any
}
}
}

interface HandleParameter {
event: RequestEvent,
resolve: (event: RequestEvent, opts?: ResolveOptions) => MaybePromise<Response>
Expand Down
53 changes: 41 additions & 12 deletions src/lib/auth/user/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,28 @@ import {aql} from 'arangojs/aql';
import type {IArangoDocumentIdentifier} from '$lib/database';
import njwt from 'njwt';
import secureRandom from 'secure-random';
import {EUserRanks} from '$lib/types/UserRanks';
import {EUserRanks} from '$lib/types/user-ranks';

const key =
export const key =
process.env.USE_SPECIFIC_KEY ?? secureRandom(256, {type: 'Buffer'});

console.log(key);

export class User {
constructor(private readonly id: string) {
constructor(readonly id: string) {
}

private stored: IUserInfo | undefined;

get data(): Promise<IUserInfo> {
return new Promise<IUserInfo>(async (resolve, reject) => {
if (!await this.exists) {
return reject('user not exists');
}

db.query(aql`
for user in users
filter user._key == ${this.id}
filter user.id == ${this.id}
return user`)
.then(async (cursor) => {
if (!cursor.hasNext) {
Expand All @@ -40,25 +46,48 @@ export class User {

get exists(): Promise<boolean> {
return new Promise(async (resolve, reject) => {
const user = await this.loadUserData();
})
db.query(aql`
for user in users
filter user.id == ${this.id}
return user`)
.then(async (r) => {
resolve(r.hasNext);
})
.catch(reject);
});
}

async register(password: string) {
if (await this.exists) {
throw Error('user exists already');
}

const hashed = await argon2.hash(password);

await db.query(aql`
insert ${{_key: this.id, password, rank: EUserRanks.User}} into users`);
insert ${{id: this.id, password: hashed, rank: EUserRanks.User}} into users`);
}

async verify(password: string) {
const user = await this.loadUserData();
return await argon2.verify(user.password, password);
/**
*
* @param password 비밀번호 평문
*/
async verify(password: string): Promise<boolean> {
try {
const user = await this.loadUserData();
return await argon2.verify(user.password, password);
} catch (e) {
console.log(e)
return false;
}
}

token(type: 'user' | 'refesh') {
token(type: 'user' | 'refesh', payload: Rec<string> = {}) {
return njwt.create({
iss: 'https://now.gd/',
sub: `users/${this.id}`,
sub: `user/${this.id}`,
scope: type,
...payload,
}, key);
}
}
Expand Down
Loading

0 comments on commit bad1209

Please sign in to comment.