Skip to content

Commit

Permalink
feat(api): add multiprofiles
Browse files Browse the repository at this point in the history
  • Loading branch information
PLhery committed Jun 18, 2023
1 parent 0625aef commit 36adc60
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 8 deletions.
7 changes: 5 additions & 2 deletions unfollow-ninja-server/src/api.ts
Expand Up @@ -47,6 +47,7 @@ export interface NinjaSession {
username?: string;
profilePic?: string;
fullName?: string;
otherProfiles?: Record<string, Omit<NinjaSession, 'twitterTokenSecret' | 'otherProfiles'>>; // key: userId
}

const router = new Router()
Expand All @@ -56,7 +57,6 @@ const router = new Router()
.get('/robots.txt', (ctx) => {
ctx.body = 'User-agent: *\nDisallow: /';
})
.use('/auth', authRouter.routes(), authRouter.allowedMethods())
.use('/admin', adminRouter.routes(), adminRouter.allowedMethods())
.all(
'/(.*)',
Expand All @@ -66,6 +66,7 @@ const router = new Router()
credentials: true,
})
)
.use('/auth', authRouter.routes(), authRouter.allowedMethods())
.use('/user', userRouter.routes(), userRouter.allowedMethods())
.get('/get-status', async (ctx) => {
const session = ctx.session as NinjaSession;
Expand All @@ -88,6 +89,7 @@ const router = new Router()
lang: params.lang,
country,
profilePic: session.profilePic,
otherProfiles: Object.values(session.otherProfiles),
};
}
})
Expand All @@ -110,7 +112,8 @@ app.use(async (ctx, next) => {
set: (key, sess) => dao.setSession(key, sess),
destroy: (key) => dao.deleteSession(key),
},
maxAge: 1000 * 60 * 60 * 24 * 30 * 6, // 6 months
maxAge: 1000 * 60 * 60 * 24 * 30, // 30 days
renew: true,
},
app
)
Expand Down
56 changes: 51 additions & 5 deletions unfollow-ninja-server/src/api/auth.ts
Expand Up @@ -4,11 +4,9 @@ import geoip from 'geoip-country';

import logger from '../utils/logger';
import type Dao from '../dao/dao';
import { UserCategory } from '../dao/dao';
import type { NinjaSession } from '../api';
import { Lang } from '../utils/types';
import { WebEvent } from '../dao/userEventDao';
import { getPriceTags } from './stripe';

const authRouter = new Router();

Expand Down Expand Up @@ -156,9 +154,6 @@ export function createAuthRouter(dao: Dao) {
category = await dao.getUserDao(loginResult.userId).enable();
}
}
const session = ctx.session as NinjaSession;
session.userId = loginResult.userId;
session.username = loginResult.screenName;

const twitterApi = new TwitterApi({
accessToken: loginResult.accessToken,
Expand All @@ -167,6 +162,19 @@ export function createAuthRouter(dao: Dao) {
appSecret: process.env.DM_CONSUMER_SECRET,
});
const result = await twitterApi.v2.me({ 'user.fields': ['profile_image_url'] });

const session = ctx.session as NinjaSession;
if (session.userId && session.userId !== loginResult.userId) {
session.otherProfiles = session.otherProfiles || {};
session.otherProfiles[session.userId] = {
userId: session.userId,
username: session.username,
profilePic: session.profilePic,
fullName: session.fullName,
};
}
session.userId = loginResult.userId;
session.username = loginResult.screenName;
session.profilePic = result.data.profile_image_url.replace('_normal', '_bigger');
session.fullName = result.data.name;

Expand All @@ -181,14 +189,52 @@ export function createAuthRouter(dao: Dao) {
lang: params.lang,
country,
profilePic: session.profilePic,
otherProfiles: Object.values(session.otherProfiles),
})
);

delete ctx.session.twitterTokenSecret;
ctx.type = 'html';
ctx.body = `You successfully logged in! closing this window...
<script>
window.opener && window.opener.postMessage({msg: 'step1', content: "${msgContent}"}, '${process.env.WEB_URL}');
close();
</script>`;
})
.post('/set-profile', async (ctx) => {
const session = ctx.session as NinjaSession;
const id = ctx.request['body']?.['userId'];
if (!id || typeof id !== 'string' || session.otherProfiles?.[id] === undefined) {
ctx.body = { status: 'Oops, something went wrong.. Try again!' };
ctx.status = 401;
return;
}
session.otherProfiles[session.userId] = {
userId: session.userId,
username: session.username,
profilePic: session.profilePic,
fullName: session.fullName,
};
session.userId = session.otherProfiles[id].userId;
session.username = session.otherProfiles[id].username;
session.profilePic = session.otherProfiles[id].profilePic;
session.fullName = session.otherProfiles[id].fullName;
delete session.otherProfiles[id];

const [params, category] = await Promise.all([
dao.getUserDao(session.userId).getUserParams(),
dao.getUserDao(session.userId).getCategory(),
]);
const country = geoip.lookup(ctx.ip)?.country;
ctx.body = {
userId: session.userId,
username: session.username,
fullName: session.fullName,
category,
lang: params.lang,
country,
profilePic: session.profilePic,
otherProfiles: Object.values(session.otherProfiles),
};
});
}
2 changes: 1 addition & 1 deletion unfollow-ninja-server/src/dao/dao.ts
Expand Up @@ -216,7 +216,7 @@ export default class Dao {

public async setSession(uid: string, params: Record<string, string>): Promise<void> {
await this.redis.set(`session:${uid}`, JSON.stringify(params));
await this.redis.expire(`session:${uid}`, 3600); // 1h sessions
await this.redis.expire(`session:${uid}`, 60 * 60 * 24 * 31); // 30d sessions
}

public async deleteSession(uid: string): Promise<void> {
Expand Down

0 comments on commit 36adc60

Please sign in to comment.