Skip to content

Commit

Permalink
提交下噢
Browse files Browse the repository at this point in the history
  • Loading branch information
yinMrsir committed Apr 13, 2023
1 parent 81909ca commit 386ba92
Show file tree
Hide file tree
Showing 12 changed files with 101 additions and 36 deletions.
9 changes: 9 additions & 0 deletions Nest-server/src/common/guards/jwt-web-auth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class JwtWebAuthGuard extends AuthGuard('jwt-web') {
canActivate(context: ExecutionContext) {
return super.canActivate(context);
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { PartialType } from '@nestjs/mapped-types';
import {IsNotEmpty, IsNumber } from 'class-validator';
import { IsNotEmpty, IsNumber } from 'class-validator';
import { CreateActorListDto } from './create-actor-list.dto';

export class UpdateActorListDto extends PartialType(CreateActorListDto) {
Expand Down
21 changes: 21 additions & 0 deletions Nest-server/src/modules/web/auth/strategies/jwt-web.strategies.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { jwtConstants } from '../../../system/auth/auth.constants';

@Injectable()
export class JwtWebStrategies extends PassportStrategy(Strategy, 'jwt-web') {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: jwtConstants.secret,
passReqToCallback: true, //设置回调的第一个参数是 request
});
}

async validate(request: Request, payload) {
const { userId } = payload;
return { userId };
}
}
3 changes: 2 additions & 1 deletion Nest-server/src/modules/web/auth/web-auth.module.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { Module } from '@nestjs/common';
import { LocalWebStrategy } from './strategies/local-web.strategy';
import { JwtWebStrategies } from './strategies/jwt-web.strategies';
import { WebAuthService } from './web-auth.service';
import { WebUserModule } from '../user/web-user.module';

@Module({
imports: [WebUserModule],
providers: [LocalWebStrategy, WebAuthService],
providers: [LocalWebStrategy, JwtWebStrategies, WebAuthService],
})
export class WebAuthModule {}
13 changes: 9 additions & 4 deletions Nest-server/src/modules/web/user/web-user.controller.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { Body, Controller, Get, Post, Req, UseGuards } from '@nestjs/common';
import { WebUserService } from './web-user.service';
import { Request } from 'express';
import { Public } from '../../../common/decorators/public.decorator';
import { LoginWebUserDto, RegWebUserDto } from './dto/req-web-user.dto';
import { LocalWebAuthGuard } from 'src/common/guards/local-web-auth.guard';
import { Request } from 'express';
import { JwtWebAuthGuard } from '../../../common/guards/jwt-web-auth.guard';
import { DataObj } from '../../../common/class/data-obj.class';

@Controller('web/user')
export class WebUserController {
Expand All @@ -22,8 +24,11 @@ export class WebUserController {
return this.webUserService.login(req);
}

@Get('getUserInfo')
getUserInfo() {
console.log(1);
@Public()
@Get('info')
@UseGuards(JwtWebAuthGuard)
async info(@Req() req) {
const data = await this.webUserService.info(req.user.userId);
return new DataObj(data);
}
}
4 changes: 4 additions & 0 deletions Nest-server/src/modules/web/user/web-user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,8 @@ export class WebUserService {
token: jwtSign,
};
}

info(userId: number) {
return this.webUserRepository.findOneBy({ userId });
}
}
2 changes: 1 addition & 1 deletion Nuxt-web/components/LoginPop.vue
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ async function login(formEl: FormInstance | undefined) {
if (!formEl) return
await formEl.validate(async (valid) => {
if (valid) {
const { data } = await useFetch<any>('/api/common/login', { method: 'post', body: form })
const { data } = await useFetch<any>('/api/user/login', { method: 'post', body: form })
if (data.value?.code === 200) {
ElMessage({
message: '登录成功',
Expand Down
10 changes: 6 additions & 4 deletions Nuxt-web/composables/useHttp.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
import {SearchParams} from "ohmyfetch";

export const useGet = <T>(url: string, params?: SearchParams): Promise<T> => {
export const useGet = <T>(url: string, params?: SearchParams, headers?: any): Promise<T> => {
const { baseUrl } = useRuntimeConfig()
return $fetch(baseUrl + url, {
method: 'get',
params
params,
headers
})
}

export const usePost = <T>(url: string, body?: Record<string, any>) => {
export const usePost = <T>(url: string, body?: Record<string, any>, headers?: any): Promise<T> => {
const { baseUrl } = useRuntimeConfig()
return $fetch(baseUrl + url, {
method: 'post',
body
body,
headers
})
}
62 changes: 37 additions & 25 deletions Nuxt-web/pages/user/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -4,44 +4,56 @@
<Title>个人中心</Title>
<Style type="text/css" children="body { background-color: #f7f7f7; }" />
</Head>
<el-row :gutter="30" class="mt-20">
<el-col :span="6">
<div class="bg-fff user-index__head flex">
<img src="../../assets/images/toux.png" alt="">
<div>
542968439@qq.com
<p class="grey">ID: 449892</p>
<a class="lv lv1"></a>
</div>
</div>
</el-col>
<el-col :span="18" class="bg-fff">
<el-tabs
v-model="activeName"
class="demo-tabs"
@tab-click="handleClick"
>
<el-tab-pane label="我的收藏" name="first">我的收藏</el-tab-pane>
<el-tab-pane label="我的点赞" name="second">我的点赞</el-tab-pane>
<el-tab-pane label="我的评论" name="third">我的评论</el-tab-pane>
</el-tabs>
</el-col>
</el-row>
<ClientOnly>
<el-row :gutter="30" class="mt-20">
<el-col :span="6">
<div class="bg-fff user-index__head flex">
<img src="../../assets/images/toux.png" alt="">
<div>
{{ userInfo?.email }}
<p class="grey">ID: 449892</p>
<a class="lv lv1"></a>
</div>
</div>
</el-col>
<el-col :span="18" class="bg-fff">
<el-tabs
v-model="activeName"
class="demo-tabs"
@tab-click="handleClick"
>
<el-tab-pane label="我的收藏" name="first">我的收藏</el-tab-pane>
<el-tab-pane label="我的点赞" name="second">我的点赞</el-tab-pane>
<el-tab-pane label="我的评论" name="third">我的评论</el-tab-pane>
</el-tabs>
</el-col>
</el-row>
</ClientOnly>
</div>
</template>
<script setup lang="ts">
import type { TabsPaneContext } from 'element-plus'
definePageMeta({
middleware: ["auth"]
middleware: ["auth"],
layout: false
})
const activeName = ref('first')
const userInfo = ref({
email: 11
})
const handleClick = (tab: TabsPaneContext, event: Event) => {
console.log(tab, event)
}
if (process.client) {
const { data } = await useFetch('/api/user/info')
console.log(data)
userInfo.value = data.value
}
</script>
<style lang="scss" scoped>
Expand Down
5 changes: 5 additions & 0 deletions Nuxt-web/server/api/user/info.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import {useGet} from "~/composables/useHttp";

export default defineEventHandler((event) => {
return useGet<{data: any}>('/web/user/info', {}, { Authorization: event.context.Authorization })
})
File renamed without changes.
6 changes: 6 additions & 0 deletions Nuxt-web/server/middleware/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export default defineEventHandler((event) => {
let userInfo = getCookie(event, 'userInfo') || undefined
if (userInfo) {
event.context.Authorization = 'Bearer ' + JSON.parse(userInfo).token
}
})

0 comments on commit 386ba92

Please sign in to comment.