Commit a5190988 authored by DESPRES Damien's avatar DESPRES Damien
Browse files

get token from redis

parent 4d6664af
Pipeline #13970 passed with stage
in 1 minute and 8 seconds
......@@ -45,7 +45,7 @@ export class ConfigService {
async initilizePublicPrivateKeys() {
try {
const redis = new Redis(this.config.redis.sentinelPort, this.config.redis.sentinelHost, this.config.redis.groupName);
const redis = new Redis(this.config.redis);
let keys: any = await redis.getValueByKey('encryptionKeys');
if (keys) {
......
export interface RedisCfg{
sentinel:boolean, // config simple ou sentinel
sentinelPort: number,
sentinelHost: string,
groupName: string,
ttl:number
}
export const Config = {
legacyAuthServiceUrl: '',
legacyAuthOidcUrl: '',
......@@ -15,9 +26,11 @@ export const Config = {
},
resetPasswordSessionTtl: 86400, // 24 hours
redis: {
sentinel:true, //false in dev with simple redis server
sentinelPort: null,
sentinelHost: '',
groupName: '',
ttl: 3600, // in seconds
},
imageHost: '',
apiKey: '',
......
import { InternalServerErrorException, Logger } from '@nestjs/common';
import { handleError } from '../legacy/errorHandlingHelper';
import * as IORedis from 'ioredis';
import { RedisCfg } from 'configuration/config';
export class Redis {
constructor(
private redisSentinelPort: number,
private redisSentinelHost: string,
private redisGroupName: string,
private redisConfig: RedisCfg
) { }
connect() {
Logger.log(`Entering function`, `Redis.connect`);
const client = new IORedis({
sentinels: [
{ host: this.redisSentinelHost, port: this.redisSentinelPort },
],
name: this.redisGroupName,
});
let cfg:any={
host: this.redisConfig.sentinelHost, port: this.redisConfig.sentinelPort ,
name: this.redisConfig.groupName,
};
if(this.redisConfig.sentinel){
cfg={
sentinels: [
{ host: this.redisConfig.sentinelHost, port: this.redisConfig.sentinelPort },
],
name: this.redisConfig.groupName,
};
}
const client = new IORedis(cfg);
client.on('error', (error) => {
Logger.error('Redis client error.', `${error}`, `Redis.connect`);
......
......@@ -2,9 +2,10 @@ import { Module } from '@nestjs/common';
import { LegacyService } from './legacy.service';
import { LegacyServiceOIDC } from './legacy.service.oidc';
import { LegacyController } from './legacy.controller';
import { TokenService } from './token.service';
@Module({
providers: [LegacyService, LegacyServiceOIDC],
providers: [LegacyService, LegacyServiceOIDC,TokenService],
controllers: [LegacyController],
})
export class LegacyModule {}
......@@ -20,25 +20,40 @@ import { Redis } from '../helpers/redis.helper';
import * as jwt from 'jsonwebtoken';
moment.tz.setDefault('Europe/Paris');
import { LegacyService } from './legacy.service'
import { TokenService } from './token.service';
@Injectable()
export class LegacyServiceOIDC extends LegacyService {
async createAccount(token): Promise<void> {
constructor(
protected configService: ConfigService,
private tokenService: TokenService,
) {
super(configService);
}
async createAccount(email): Promise<void> {
this.logger.log('Entering function', `${LegacyServiceOIDC.name} - ${this.createAccount.name}`);
try {
this.logger.log('token ', email);
if(email) {
var tokenInfos= await this.tokenService.getTokenInfos(email);
if(token) {
let url=`${this.conf.legacyAuthOidcUrl}/add_user/`;
this.logger.log('url ', url);
let options = {
method: 'POST',
headers:{
'Authorization': 'Bearer ' + token,
'Authorization': 'Bearer ' + tokenInfos.access_token,
},
url: `${this.conf.legacyAuthOidcUrl}/add_user/`,
url: url,
};
let token_data = jwt.decode(tokenInfos.access_token);
let token_data = jwt.decode(token);
// Get the list of the accessible services by the user
this.logger.log(`OIDC user account validation for : ${token_data['http://wso2.org/claims/emailaddress']}`, `${LegacyServiceOIDC.name} - ${this.createAccount.name}`);
......
......@@ -33,7 +33,7 @@ export class LegacyService {
) {
this.conf = this.configService.config;
this.logger = new Logger(LegacyService.name);
this.redis = new Redis(this.conf.redis.sentinelPort, this.conf.redis.sentinelHost, this.conf.redis.groupName);
this.redis = new Redis(this.conf.redis);
}
async getUser(loginForm: LoginForm): Promise<UserInfoWithEcryptedPassword> {
......
import { Injectable, InternalServerErrorException, Logger } from "@nestjs/common";
import { ConfigService } from "configuration/config.service";
import { Redis } from "helpers/redis.helper";
import * as request from 'request-promise-native';
import * as jwt from 'jsonwebtoken';
interface TokenInfos{
access_token: string;
refresh_token: string;
}
@Injectable()
export class TokenService {
conf: any = {};
private logger: Logger;
private redis:Redis;
constructor(
private configService: ConfigService,
) {
this.conf = this.configService.config;
this.redis = new Redis(this.conf.redis);
}
async storeTokenInfos(email: any, body: any) {
let tokenInfos:TokenInfos={
"access_token":body.access_token,
"refresh_token":body.refresh_token,
}
return this.redis.setKeyValue(email,JSON.stringify(tokenInfos), this.conf.redis.ttl);
}
async getTokenInfos(email: any):Promise<TokenInfos>{
const value = await this.redis.getValueByKey(email);
let tokenInfos=JSON.parse(value);
let token_data = jwt.decode(tokenInfos.access_token);
//Check expiration
if (Date.now() >= token_data.exp * 1000) {
tokenInfos= await this.renewToken(email,tokenInfos);
}
return tokenInfos;
}
async renewToken(email:String,tokenInfos: TokenInfos): Promise<any> {
const idpConf = this.conf.providers['OIDC'];
const payload = {
grant_type: 'refresh_token',
refresh_token:tokenInfos.refresh_token,
};
Logger.log(' [*] payload sent: ', JSON.stringify(payload));
Logger.log('[-] Token Request');
let options = {
url: idpConf.TokenUrl,
strictSSL: this.conf.useStrictSSL,
}
// Exchange the code against an id_token and an access_token
let body = await request.post(options)
.form(payload)
.auth(idpConf.client_id, idpConf.client_secret, true)
.catch((error)=>{
Logger.log('[-] error '+error);
});
let token_data=JSON.parse(body);
tokenInfos.access_token=token_data.access_token;
tokenInfos.refresh_token=token_data.refresh_token;
await this.storeTokenInfos(email,tokenInfos);
return tokenInfos;
}
}
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment