Skip to content

Commit

Permalink
fix: userId type
Browse files Browse the repository at this point in the history
Signed-off-by: ZTL-UwU <zhangtianli2006@163.com>
  • Loading branch information
ZTL-UwU committed Apr 27, 2024
1 parent b1a5d23 commit 170c76c
Show file tree
Hide file tree
Showing 8 changed files with 53 additions and 62 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
"@radix-icons/vue": "^1.0.0",
"@types/bcrypt": "^5.0.2",
"dotenv": "^16.4.5",
"drizzle-kit": "^0.20.14",
"drizzle-kit": "^0.20.17",
"eslint": "^8.57.0",
"eslint-plugin-drizzle": "^0.2.3",
"happy-dom": "^13.10.1",
Expand Down
39 changes: 28 additions & 11 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions server/db/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { drizzle } from 'drizzle-orm/libsql';
import { createClient } from '@libsql/client';
import { env } from '../env';

import type { refreshTokens, users } from './schema';
import type { users } from './schema';
import * as schema from './schema';

const options = (() => {
Expand All @@ -17,4 +17,3 @@ export const db = drizzle(client, { schema });

export type TRawUser = typeof users.$inferSelect;
export type TNewUser = typeof users.$inferInsert;
export type TRefreshToken = typeof refreshTokens.$inferInsert;
17 changes: 11 additions & 6 deletions server/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,6 @@ export const usersRelations = relations(users, ({ many }) => ({
contents: many(contents),
}));

export const refreshTokens = sqliteTable('refresh_tokens', {
id: integer('id').primaryKey({ autoIncrement: true }),
token: text('token').notNull(),
owner: integer('owner').references(() => users.id, cascade).notNull(),
});

export const programs = sqliteTable('programs', {
id: integer('id').primaryKey({ autoIncrement: true }),
name: text('name').notNull(),
Expand Down Expand Up @@ -113,6 +107,17 @@ export const programsToPools = sqliteTable('programs_to_pools', {
pk: primaryKey({ columns: [t.programId, t.poolId] }),
}));

export const programsToPoolsRelations = relations(programsToPools, ({ one }) => ({
program: one(programs, {
fields: [programsToPools.programId],
references: [programs.id],
}),
pool: one(pools, {
fields: [programsToPools.poolId],
references: [pools.id],
}),
}));

export const poolsRelations = relations(pools, ({ many }) => ({
contents: many(contents),
programsToPools: many(programsToPools),
Expand Down
27 changes: 6 additions & 21 deletions server/trpc/controllers/user.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { LibsqlError } from '@libsql/client';
import bcrypt from 'bcrypt';
import { and, eq } from 'drizzle-orm';
import { eq } from 'drizzle-orm';
import { TRPCError } from '@trpc/server';
import type { TNewUser, TRawUser } from '../../db/db';
import { db } from '../../db/db';
import { refreshTokens, users } from '../../db/schema/user';
import { users } from '../../db/schema';
import { Auth } from '../utils/auth';
import { TRPCForbidden } from '../../trpc/utils/shared';

Expand Down Expand Up @@ -38,7 +38,7 @@ export class UserController {
}
}

async modifyPassword(user: TRawUser, id: string, oldPassword: string, newPassword: string) {
async modifyPassword(user: TRawUser, id: number, oldPassword: string, newPassword: string) {
if (user.role !== 'admin' && user.id !== id)
throw TRPCForbidden;

Expand All @@ -65,7 +65,6 @@ export class UserController {
throw new TRPCError({ code: 'UNAUTHORIZED', message: '用户名或密码错误' });

const accessToken = await this.auth.produceAccessToken(user.id);
const refreshToken = await this.auth.produceRefreshToken(user.id);

const {
password: _password,
Expand All @@ -75,29 +74,15 @@ export class UserController {
return {
...info,
accessToken,
refreshToken,
};
}

async refreshAccessToken(refreshToken: string, id: string) {
const token = await db
.delete(refreshTokens)
.where(and(eq(refreshTokens.token, refreshToken), eq(refreshTokens.owner, id)))
.returning();
if (!token[0])
throw new TRPCError({ code: 'UNAUTHORIZED', message: '请重新登陆' });

const newRefreshToken = await this.auth.produceRefreshToken(id);
const newAccessToken = await this.auth.produceAccessToken(id);
return { accessToken: newAccessToken, refreshToken: newRefreshToken };
}

async modify(id: string, newUser: Partial<Omit<TRawUser, 'password' | 'createdAt'>>) {
async modify(id: number, newUser: Partial<Omit<TRawUser, 'password' | 'createdAt'>>) {
await db.update(users).set(newUser).where(eq(users.id, id));
return '修改成功';
}

async getProfile(id: string) {
async getProfile(id: number) {
const basicUser = await db.query.users.findFirst({
where: eq(users.id, id),
});
Expand All @@ -124,7 +109,7 @@ export class UserController {
});
}

async remove(id: string) {
async remove(id: number) {
try {
await db.delete(users).where(eq(users.id, id));
return '删除成功';
Expand Down
10 changes: 1 addition & 9 deletions server/trpc/routers/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { protectedProcedure, publicProcedure, requireRoles, router } from '../tr
import { passwordRegex } from '~/constants/user';

const roleEnumZod = z.enum(['admin', 'club'], { errorMap: () => ({ message: '提交了不存在的用户身份' }) });
const userIdZod = z.string().min(1, { message: '用户不存在' });
const userIdZod = z.number().int().min(1, { message: '用户不存在' });
const usernameZod = z.string().min(2, { message: '用户名长度应至少为2' }).max(15, { message: '用户名超出长度范围' });
const newPasswordZod = z.string().min(8, { message: '用户密码长度应至少为8' }).regex(passwordRegex, '密码必须包含大小写字母、数字与特殊符号');

Expand All @@ -14,8 +14,6 @@ export const userRouter = router({
role: roleEnumZod,
username: usernameZod,
password: newPasswordZod,
groupId: z.string().optional(),
classId: z.string().optional(),
}))
.mutation(async ({ ctx, input }) => {
return await ctx.userController.register(input);
Expand Down Expand Up @@ -47,12 +45,6 @@ export const userRouter = router({
tokenValidity: protectedProcedure
.query(() => { }), // protectedProcedure will check if user is logged in

refreshAccessToken: publicProcedure
.input(z.object({ username: z.string(), refreshToken: z.string() }))
.mutation(async ({ ctx, input }) => {
return await ctx.userController.refreshAccessToken(input.refreshToken, input.username);
}),

modify: protectedProcedure
.input(z.object({
id: userIdZod,
Expand Down
12 changes: 3 additions & 9 deletions server/trpc/utils/auth.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as jose from 'jose';
import { eq } from 'drizzle-orm';
import { db } from '../../db/db';
import { refreshTokens, users } from '../../db/schema/user';
import { users } from '../../db/schema';
import { env } from '../../env';
import { makeId } from '../../trpc/utils/shared';

Expand All @@ -12,7 +12,7 @@ const encPublicKey = await jose.importSPKI(env.ENC_PUBLIC_KEY, 'RSA-OAEP-256');
const signPrivateKey = await jose.importPKCS8(env.SIGN_PRIVATE_KEY, 'RS512');

export class Auth {
async produceAccessToken(id: string) {
async produceAccessToken(id: number) {
const jwt = await new jose.SignJWT({})
.setSubject(id.toString())
.setIssuedAt()
Expand Down Expand Up @@ -40,7 +40,7 @@ export class Auth {
const encPrivateKey = await jose.importPKCS8(env.ENC_PRIVATE_KEY, 'RSA-OAEP-256');
const { plaintext: decryptedJwt } = await jose.compactDecrypt(token, encPrivateKey);
const { payload } = await jose.jwtVerify(decode(decryptedJwt), signPublicKey);
const userSelectResult = await db.select().from(users).where(eq(users.id, payload.sub as string));
const userSelectResult = await db.select().from(users).where(eq(users.id, Number.parseInt(payload.sub!)));
return { user: userSelectResult[0] };
} catch (err) {
if (err instanceof jose.errors.JWEDecryptionFailed)
Expand All @@ -50,10 +50,4 @@ export class Auth {
else return { err: 'ERR_INVALID_TOKEN' };
}
}

async produceRefreshToken(owner: string) {
const token = makeId(128);
await db.insert(refreshTokens).values({ token, owner });
return token;
}
}
5 changes: 2 additions & 3 deletions stores/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,14 @@ export const useUserStore = defineStore('user', () => {
const loggedIn = ref(false);
const accessToken = ref('');
const refreshToken = ref('');
const userId = ref('');
const userId = ref<number>();
const username = ref('');
const role = ref<TRole>('club');

const login = (data: TUserLogin) => {
loggedIn.value = true;

accessToken.value = data.accessToken;
refreshToken.value = data.refreshToken;

userId.value = data.id;
username.value = data.username;
Expand All @@ -26,7 +25,7 @@ export const useUserStore = defineStore('user', () => {
accessToken.value = '';
refreshToken.value = '';

userId.value = '';
userId.value = undefined;
username.value = '';

role.value = 'club';
Expand Down

0 comments on commit 170c76c

Please sign in to comment.