oauth2-provider/src/controller/tokens/password.ts

111 lines
2.7 KiB
TypeScript

import {
ServerError,
InvalidRequest,
InvalidScope,
InvalidClient,
} from '../../model/error';
import {
OAuth2,
OAuth2Client,
OAuth2User,
OAuth2TokenResponse,
} from '../../model/model';
/**
* Implicit access token response
* @param oauth2 - OAuth2 instance
* @param client - OAuth2 client
* @param username
* @param password
* @param scope - Requested scopes
* @returns Access token
*/
export async function password(
oauth2: OAuth2,
client: OAuth2Client,
username: string,
password: string,
scope: string | string[]
): Promise<OAuth2TokenResponse> {
let user: OAuth2User | null = null;
const resObj: OAuth2TokenResponse = {
token_type: 'bearer',
};
if (!username) {
throw new InvalidRequest('Username is mandatory for password grant type');
}
if (!password) {
throw new InvalidRequest('Password is mandatory for password grant type');
}
scope = oauth2.model.client.transformScope(scope);
if (!oauth2.model.client.checkScope(client, scope)) {
throw new InvalidScope('Client does not allow access to this scope');
} else {
oauth2.logger.debug('Scope check passed: ', scope);
}
try {
user = await oauth2.model.user.fetchByUsername(username);
} catch (err) {
throw new ServerError('Failed to call user.fetchByUsername function');
}
if (!user) {
throw new InvalidClient('User not found');
}
const valid = await oauth2.model.user.checkPassword(user, password);
if (!valid) {
throw new InvalidClient('Wrong password');
}
try {
await oauth2.model.refreshToken.removeByUserIdClientId(
oauth2.model.user.getId(user),
oauth2.model.client.getId(client)
);
} catch (err) {
throw new ServerError(
'Failed to call refreshToken.removeByUserIdClientId function'
);
}
oauth2.logger.debug('Refresh token removed');
if (!oauth2.model.client.checkGrantType(client, 'refresh_token')) {
oauth2.logger.debug(
'Client does not allow grant type refresh_token, skip creation'
);
} else {
try {
resObj.refresh_token = await oauth2.model.refreshToken.create(
oauth2.model.user.getId(user),
oauth2.model.client.getId(client),
scope
);
} catch (err) {
throw new ServerError('Failed to call refreshToken.create function');
}
}
try {
resObj.access_token = await oauth2.model.accessToken.create(
oauth2.model.user.getId(user),
oauth2.model.client.getId(client),
scope,
oauth2.model.accessToken.ttl
);
} catch (err) {
throw new ServerError('Failed to call accessToken.create function');
}
resObj.expires_in = oauth2.model.accessToken.ttl;
oauth2.logger.debug('Access token saved ', resObj.access_token);
return resObj;
}