import uuidv4 from 'uuid/v4'; export async function createUser( server: ChaiHttp.Agent, user?: { display_name?: string; email: string; password: string }, ) { const res = await server .post('/signup') .type('form') .send(user ? user : {email: `${uuidv4()}@example.com`, password: uuidv4()}); if (res.status !== 201) { throw new Error(`When creating user got response ${res.status} with body ${res.text}`); } return res; } export async function clearUsers(server: ChaiHttp.Agent) { const resUsers = await server.get('/v1/users'); const resDel = resUsers.body.users.map((user: { id: string }) => server.del(`/v1/users/${user.id}`), ); return Promise.all(resDel); } export async function authorize(server: ChaiHttp.Agent, scopes?: string[]) { const res = await server .get(`/authorize`) .query({ client_id: '1', redirect_uri: encodeURIComponent('http://localhost:3000/'), response_type: 'token', scope: scopes ? encodeURIComponent(scopes.join(' ')) : undefined, }) .redirects(0); const tokenType = fromRedirectHash(res.header.location, 'token_type'); const accessToken = fromRedirectHash(res.header.location, 'access_token'); return `${tokenType} ${accessToken}`; } export function fromRedirectHash(location: string, name: string) { const match = RegExp('[#&]' + name + '=([^&]*)').exec(location); return match ? decodeURIComponent(match[1].replace(/\+/g, ' ')) : undefined; }