51 lines
2.0 KiB
TypeScript
51 lines
2.0 KiB
TypeScript
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"] }, { relations: ['groups', 'permissions'] });
|
|
if (!found_user) {
|
|
throw new UserNotFoundError()
|
|
}
|
|
if (found_user.refreshTokenCount !== decoded["refreshtokencount"]) {
|
|
throw new RefreshTokenCountInvalidError()
|
|
}
|
|
found_user.permissions = found_user.permissions || []
|
|
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;
|
|
}
|
|
} |