Merge branch 'dev' of https://git.odit.services/lfk/backend into dev
This commit is contained in:
50
src/models/actions/RefreshAuth.ts
Normal file
50
src/models/actions/RefreshAuth.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import { IsString } from 'class-validator';
|
||||
import * as jsonwebtoken from 'jsonwebtoken';
|
||||
import { getConnectionManager } from 'typeorm';
|
||||
import { config } from '../../config';
|
||||
import { IllegalJWTError, JwtNotProvidedError, RefreshTokenCountInvalidError, UserNotFoundError } from '../../errors/AuthError';
|
||||
import { User } from '../entities/User';
|
||||
import { Auth } from '../responses/ResponseAuth';
|
||||
|
||||
export class RefreshAuth {
|
||||
@IsString()
|
||||
token: string;
|
||||
|
||||
public async toAuth(): Promise<Auth> {
|
||||
let newAuth: Auth = new Auth();
|
||||
if (!this.token || this.token === undefined) {
|
||||
throw new JwtNotProvidedError()
|
||||
}
|
||||
let decoded
|
||||
try {
|
||||
decoded = jsonwebtoken.verify(this.token, config.jwt_secret)
|
||||
} catch (error) {
|
||||
throw new IllegalJWTError()
|
||||
}
|
||||
const found_user = await getConnectionManager().get().getRepository(User).findOne({ id: decoded["userid"] });
|
||||
if (!found_user) {
|
||||
throw new UserNotFoundError()
|
||||
}
|
||||
if (found_user.refreshTokenCount !== decoded["refreshtokencount"]) {
|
||||
throw new RefreshTokenCountInvalidError()
|
||||
}
|
||||
delete found_user.password;
|
||||
const timestamp_accesstoken_expiry = Math.floor(Date.now() / 1000) + 5 * 60
|
||||
delete found_user.password;
|
||||
newAuth.access_token = jsonwebtoken.sign({
|
||||
userdetails: found_user,
|
||||
exp: timestamp_accesstoken_expiry
|
||||
}, config.jwt_secret)
|
||||
newAuth.access_token_expires_at = timestamp_accesstoken_expiry
|
||||
//
|
||||
const timestamp_refresh_expiry = Math.floor(Date.now() / 1000) + 10 * 36000
|
||||
newAuth.refresh_token = jsonwebtoken.sign({
|
||||
refreshtokencount: found_user.refreshTokenCount,
|
||||
userid: found_user.id,
|
||||
exp: timestamp_refresh_expiry
|
||||
}, config.jwt_secret)
|
||||
newAuth.refresh_token_expires_at = timestamp_refresh_expiry
|
||||
|
||||
return newAuth;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user