Browse Source

Merge pull request #5764 from nocodb/fix/refresh-token

fix: set refresh-token on login and correction in refresh-token based api
pull/5774/head
Pranav C 2 years ago committed by GitHub
parent
commit
cf3e4beeac
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 2
      packages/nocodb-sdk/src/lib/Api.ts
  2. 105
      packages/nocodb/src/controllers/users/users.controller.ts
  3. 4
      packages/nocodb/src/schema/swagger.json
  4. 4
      packages/nocodb/src/services/users/users.service.ts

2
packages/nocodb-sdk/src/lib/Api.ts

@ -2319,6 +2319,8 @@ export interface UserType {
* @example org-level-viewer * @example org-level-viewer
*/ */
roles?: string; roles?: string;
/** Access token version */
token_version?: string;
} }
/** /**

105
packages/nocodb/src/controllers/users/users.controller.ts

@ -1,5 +1,3 @@
import { promisify } from 'util';
import { AuditOperationSubTypes, AuditOperationTypes } from 'nocodb-sdk';
import { import {
Body, Body,
Controller, Controller,
@ -19,23 +17,17 @@ import {
Acl, Acl,
ExtractProjectIdMiddleware, ExtractProjectIdMiddleware,
} from '../../middlewares/extract-project-id/extract-project-id.middleware'; } from '../../middlewares/extract-project-id/extract-project-id.middleware';
import Noco from '../../Noco'; import { User } from '../../models';
import { GoogleStrategy } from '../../strategies/google.strategy/google.strategy';
import extractRolesObj from '../../utils/extractRolesObj';
import { Audit, User } from '../../models';
import { import {
genJwt,
randomTokenString, randomTokenString,
setTokenCookie, setTokenCookie,
} from '../../services/users/helpers'; } from '../../services/users/helpers';
import { UsersService } from '../../services/users/users.service'; import { UsersService } from '../../services/users/users.service';
import extractRolesObj from '../../utils/extractRolesObj';
@Controller() @Controller()
export class UsersController { export class UsersController {
constructor( constructor(private readonly usersService: UsersService) {}
private readonly usersService: UsersService,
private googleStrategy: GoogleStrategy,
) {}
@Post([ @Post([
'/auth/user/signup', '/auth/user/signup',
@ -59,56 +51,14 @@ export class UsersController {
'/api/v1/auth/token/refresh', '/api/v1/auth/token/refresh',
]) ])
@HttpCode(200) @HttpCode(200)
async refreshToken(@Request() req: any, @Request() res: any): Promise<any> { async refreshToken(@Request() req: any, @Response() res: any): Promise<any> {
return await this.usersService.refreshToken({ res.json(
await this.usersService.refreshToken({
body: req.body, body: req.body,
req, req,
res, res,
}); }),
} );
async successfulSignIn({ user, err, info, req, res, auditDescription }) {
try {
if (!user || !user.email) {
if (err) {
return res.status(400).send(err);
}
if (info) {
return res.status(400).send(info);
}
return res.status(400).send({ msg: 'Your signin has failed' });
}
await promisify((req as any).login.bind(req))(user);
const refreshToken = randomTokenString();
if (!user.token_version) {
user.token_version = randomTokenString();
}
await User.update(user.id, {
refresh_token: refreshToken,
email: user.email,
token_version: user.token_version,
});
setTokenCookie(res, refreshToken);
await Audit.insert({
op_type: AuditOperationTypes.AUTHENTICATION,
op_sub_type: AuditOperationSubTypes.SIGNIN,
user: user.email,
ip: req.clientIp,
description: auditDescription,
});
res.json({
token: genJwt(user, Noco.getConfig()),
} as any);
} catch (e) {
console.log(e);
throw e;
}
} }
@Post([ @Post([
@ -118,8 +68,9 @@ export class UsersController {
]) ])
@UseGuards(AuthGuard('local')) @UseGuards(AuthGuard('local'))
@HttpCode(200) @HttpCode(200)
async signin(@Request() req) { async signin(@Request() req, @Response() res) {
return this.usersService.login(req.user); await this.setRefreshToken({ req, res });
res.json(this.usersService.login(req.user));
} }
@Post('/api/v1/auth/user/signout') @Post('/api/v1/auth/user/signout')
@ -136,18 +87,15 @@ export class UsersController {
@Post(`/auth/google/genTokenByCode`) @Post(`/auth/google/genTokenByCode`)
@HttpCode(200) @HttpCode(200)
@UseGuards(AuthGuard('google')) @UseGuards(AuthGuard('google'))
async googleSignin(@Request() req) { async googleSignin(@Request() req, @Response() res) {
return this.usersService.login(req.user); await this.setRefreshToken({ req, res });
res.json(this.usersService.login(req.user));
} }
@Get('/auth/google') @Get('/auth/google')
@UseGuards(AuthGuard('google')) @UseGuards(AuthGuard('google'))
googleAuthenticate(@Request() req) { googleAuthenticate(@Request() req) {
// this.googleStrategy.authenticate(req, { // google strategy will take care the request
// scope: ['profile', 'email'],
// state: req.query.state,
// callbackURL: req.ncSiteUrl + Noco.getConfig().dashboardPath,
// });
} }
@Get(['/auth/user/me', '/api/v1/db/auth/user/me', '/api/v1/auth/user/me']) @Get(['/auth/user/me', '/api/v1/db/auth/user/me', '/api/v1/auth/user/me'])
@ -269,4 +217,27 @@ export class UsersController {
return res.status(400).json({ msg: e.message }); return res.status(400).json({ msg: e.message });
} }
} }
async setRefreshToken({ res, req }) {
const userId = req.user?.id;
if (!userId) return;
const user = await User.get(userId);
if (!user) return;
const refreshToken = randomTokenString();
if (!user.token_version) {
user.token_version = randomTokenString();
}
await User.update(user.id, {
refresh_token: refreshToken,
email: user.email,
token_version: user.token_version,
});
setTokenCookie(res, refreshToken);
}
} }

4
packages/nocodb/src/schema/swagger.json

@ -20014,6 +20014,10 @@
"description": "The roles of the user", "description": "The roles of the user",
"example": "org-level-viewer", "example": "org-level-viewer",
"type": "string" "type": "string"
},
"token_version": {
"description": "Access token version",
"type": "string"
} }
}, },
"required": ["email", "email_verified", "firstname", "id", "lastname"], "required": ["email", "email_verified", "firstname", "id", "lastname"],

4
packages/nocodb/src/services/users/users.service.ts

@ -486,9 +486,9 @@ export class UsersService {
return this.login(user); return this.login(user);
} }
async login(user: any) { login(user: UserType) {
return { return {
token: genJwt(user, Noco.getConfig()), //this.jwtService.sign(payload), token: genJwt(user, Noco.getConfig()),
}; };
} }

Loading…
Cancel
Save