Skip to content

Commit

Permalink
Merge pull request #19 from warriorBrian/hotfix/getLocation
Browse files Browse the repository at this point in the history
Hotfix/get location
  • Loading branch information
warriorBrian authored Dec 30, 2021
2 parents 7526fa7 + 08ebcbd commit 10bb988
Show file tree
Hide file tree
Showing 8 changed files with 103 additions and 35 deletions.
8 changes: 4 additions & 4 deletions nuxt/modules/components/post-chain.vue
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,16 @@
<section>
<el-form :model="postChainModel" status-icon ref="postChain" :rules="rules" label-position="top" label-width="80px" class="post-chain">
<el-form-item label="姓名" prop="name">
<el-input v-model.number="postChainModel.name" size="small" :placeholder="placeholder.name"></el-input>
<el-input v-model="postChainModel.name" size="small" :placeholder="placeholder.name"></el-input>
</el-form-item>
<el-form-item label="链接" prop="link">
<el-input v-model.number="postChainModel.link" size="small" :placeholder="placeholder.link"></el-input>
<el-input v-model="postChainModel.link" size="small" :placeholder="placeholder.link"></el-input>
</el-form-item>
<el-form-item label="邮箱" prop="email">
<el-input v-model.number="postChainModel.email" size="small" :placeholder="placeholder.email"></el-input>
<el-input v-model="postChainModel.email" size="small" :placeholder="placeholder.email"></el-input>
</el-form-item>
<el-form-item label="头像链接" prop="avatarLink">
<el-input v-model.number="postChainModel.avatarLink" size="small" :placeholder="placeholder.avatarLink"></el-input>
<el-input v-model="postChainModel.avatarLink" size="small" :placeholder="placeholder.avatarLink"></el-input>
</el-form-item>
<el-form-item class="post-chain-btn">
<el-button type="info" size="small" @click="postChainSubmitHandle('postChain')">提 交</el-button>
Expand Down
21 changes: 19 additions & 2 deletions nuxt/modules/components/post-form.vue
Original file line number Diff line number Diff line change
Expand Up @@ -149,13 +149,17 @@ export default {
{ validator: validateCaptcha, trigger: 'blur', required: true }
]
},
comment_status: 1
comment_status: 1,
comment_record_ip: 0,
headerConfigs: {}
}
},
async fetch () {
await this.getGeetestCaptcha();
// 评论开启状态
await this.getCommentStatus();
// 根据记录IP状态决定是否调用获取IP地址
this.comment_record_ip && await this.getIpLocation();
},
methods: {
async getCommentStatus () {
Expand All @@ -164,6 +168,19 @@ export default {
this.placeholder = { username: '', email: '', content: '评论已关闭' };
}
this.comment_status = data.comment_status;
this.comment_record_ip = data.comment_record_ip;
},
async getIpLocation () {
// 获取请求IP地址
console.log('调用获取IP');
if (process.browser) {
try {
const { data: { query, country, city } } = await this.$axios.get('http://ip-api.com/json', {});
this.headerConfigs = { ip: query || '', city: city || '', country: country || '' };
} catch (e) {
this.headerConfigs = {};
}
}
},
submitForm (formName) {
this.$refs[formName].validate((valid) => {
Expand All @@ -180,7 +197,7 @@ export default {
},
// 提交评论
async postComment () {
const { data } = await this.$axios.post('/comment', { ...this.postModel, article_id: this.$route.params.id });
const { data } = await this.$axios.post('/comment', { ...this.postModel, article_id: this.$route.params.id }, { headers: { ...this.headerConfigs } });
if (success(data.code)) {
this.$notify({ title: '成功', message: '评论成功', type: 'success' });
this.resetForm('postForm');
Expand Down
21 changes: 18 additions & 3 deletions nuxt/modules/pages/archive/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,18 @@ export default {
return {
tagLists: [],
archiveLists: {},
list: {}
list: {},
headerConfigs: {}
}
},
async fetch () {
await this.getBannerData();
await this.getTagLists();
await this.getArchiveLists();
},
async created () {
await this.getIpLocation();
await this.getBannerData();
},
head () {
return {
title: '归档'
Expand All @@ -56,14 +60,25 @@ export default {
// 获取banner数据
async getBannerData () {
try {
const { data: { data } } = await this.$axios.get('/site-config/list', {});
const { data: { data } } = await this.$axios.get('/site-config/list', { headers: { ...this.headerConfigs } });
// 查找数据与路由进行对应
const index = data.list.findIndex(v => v.link === this.$route.path);
this.list = data.list[index];
} catch (e) {
this.$nuxt.error({ ...e.response.data });
}
},
async getIpLocation () {
// 获取请求IP地址
if (process.browser) {
try {
const { data: { query, country, city } } = await this.$axios.get('http://ip-api.com/json', {});
this.headerConfigs = { ip: query || '', city: city || '', country: country || '' };
} catch (e) {
this.headerConfigs = {};
}
}
},
async getTagLists () {
const { data: { data } } = await this.$axios.get('/archive/tag/list', { params: { 'no-pagination': true } })
this.tagLists = data;
Expand Down
23 changes: 19 additions & 4 deletions nuxt/modules/pages/chain/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,17 @@ export default {
data () {
return {
list: {},
chainLists: []
chainLists: [],
headerConfigs: {}
}
},
async fetch () {
await this.getBannerData();
await this.getChainLists();
},
async created () {
await this.getIpLocation();
await this.getBannerData();
},
head () {
return {
title: '友链'
Expand All @@ -54,7 +58,7 @@ export default {
// 获取banner数据
async getBannerData () {
try {
const { data: { data } } = await this.$axios.get('/site-config/list', {});
const { data: { data } } = await this.$axios.get('/site-config/list', { headers: { ...this.headerConfigs } });
// 查找数据与路由进行对应
const index = data.list.findIndex(v => v.link === this.$route.path);
this.list = data.list[index];
Expand All @@ -70,7 +74,18 @@ export default {
// 跳转友链
navigationChainHandle (chain) {
window.open(chain.link, '_blank');
}
},
async getIpLocation () {
// 获取请求IP地址
if (process.browser) {
try {
const { data: { query, country, city } } = await this.$axios.get('http://ip-api.com/json', {});
this.headerConfigs = { ip: query || '', city: city || '', country: country || '' };
} catch (e) {
this.headerConfigs = {};
}
}
},
}
}
</script>
Expand Down
23 changes: 19 additions & 4 deletions nuxt/modules/pages/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,12 @@ export default {
author: ''
},
count: 0,
list: {}
list: {},
headerConfigs: {}
}
},
async fetch () {
await this.getBannerData();
await this.getSiteMetaConfig();
await this.getArticleLists();
},
head () {
return {
Expand All @@ -51,11 +50,16 @@ export default {
]
}
},
async created () {
await this.getIpLocation();
await this.getBannerData();
await this.getArticleLists();
},
methods: {
// 获取banner数据
async getBannerData () {
try {
const { data: { data } } = await this.$axios.get('/site-config/list', {});
const { data: { data } } = await this.$axios.get('/site-config/list', { headers: { ...this.headerConfigs } });
// 查找数据与路由进行对应
const index = data.list.findIndex(v => v.link === this.$route.path);
this.list = data.list[index];
Expand All @@ -68,6 +72,17 @@ export default {
const { data: { data } } = await this.$axios.get('/site-config/site');
this.meta = data;
},
async getIpLocation () {
// 获取请求IP地址
if (process.browser) {
try {
const { data: { query, country, city } } = await this.$axios.get('http://ip-api.com/json', {});
this.headerConfigs = { ip: query || '', city: city || '', country: country || '' };
} catch (e) {
this.headerConfigs = {};
}
}
},
// 获取文章列表渲染
async getArticleLists () {
try {
Expand Down
24 changes: 13 additions & 11 deletions server/modules/src/middleware/blacklist.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ import {LocationService} from 'src/modules/location/location.service';
export class BlacklistMiddleware implements NestMiddleware {
constructor(
@InjectRepository(BlacklistEntity) private readonly blackRepository: Repository<BlacklistEntity>,
@InjectRepository(OptionsEntity) private readonly optionRepository: Repository<OptionsEntity>,
private readonly locationService: LocationService
@InjectRepository(OptionsEntity) private readonly optionRepository: Repository<OptionsEntity>
) {}

private async deleteBlackList (id) {
Expand All @@ -32,15 +31,18 @@ export class BlacklistMiddleware implements NestMiddleware {
return false;
}
const nowTime = Number(Math.round(new Date().getTime()/1000));
const { query_ip_location: { result } } = await this.locationService.getLocation();
const blacklist = await this.blackRepository.findOne({ip: result.ip});
if (blacklist) {
// 时间过期则删除,否则更新次数
if (nowTime > blacklist.exp) {
this.deleteBlackList(blacklist.id)
} else {
this.updateBlackListCount(result.ip, blacklist.count + 1);
throw new ForbiddenException('访问被拒绝');
// 通过前端来传递访问ip
const ip: any = request.headers['ip'];
if (ip) {
const blacklist = await this.blackRepository.findOne({ip});
if (blacklist) {
// 时间过期则删除,否则更新次数
if (nowTime > blacklist.exp) {
this.deleteBlackList(blacklist.id)
} else {
this.updateBlackListCount(ip, blacklist.count + 1);
throw new ForbiddenException('访问被拒绝');
}
}
}
next();
Expand Down
8 changes: 4 additions & 4 deletions server/modules/src/modules/comment/comment.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {Controller, Post, Body, Query, Get, UsePipes, Delete, UploadedFile, UseInterceptors, HttpService} from '@nestjs/common';
import {Controller, Post, Body, Query, Get, UsePipes, Delete, UploadedFile, UseInterceptors, HttpService, Headers} from '@nestjs/common';
import {CommentService} from './comment.service';
import {AuthStrategy} from 'src/auth/auth.decorator';
import {ValidateToEmptyPipe} from 'src/pipe/validateToEmptyPipe.pipe';
Expand Down Expand Up @@ -53,8 +53,8 @@ export class CommentController {
@UsePipes(new ValidateToEmptyPipe([ 'email', 'username', 'content', 'article_id' ]))
@RateLimit({ points: 5, duration: 60})
@UseInterceptors(RateLimiterInterceptor)
protected createComment (@Body() body) {
return this.commentService.createComment(body);
protected createComment (@Body() body, @Headers('ip') ip) {
return this.commentService.createComment(body, ip);
}

/**
Expand All @@ -76,7 +76,7 @@ export class CommentController {
* */
@Get('/switch')
protected getCommentSwitchStatus () {
return this.commentService.getCommentSwitchStatus(['comment_status']);
return this.commentService.getCommentSwitchStatus(['comment_status', 'comment_record_ip']);
}
/**
* @desc 获取评论开启状态及记录IP状态
Expand Down
10 changes: 7 additions & 3 deletions server/modules/src/modules/comment/comment.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ export class CommentService {
* @param data {Object} email, content article_id
* @return create result
* */
public async createComment (data) {
public async createComment (data, getHeadersIp) {
const { email, content, article_id, username, captcha } = data;
const value = await this.optionsRepository.createQueryBuilder('options')
.select(['options.key', 'options.value'])
Expand Down Expand Up @@ -189,8 +189,12 @@ export class CommentService {
throw new BadRequestException(MESSAGES.WEBSERVICE_KEY_EMPTY);
}
// 获取IP地址,IP解析实际地址
const {query_ip_location: { result: {ip} }, detail_location: { result: { address } } } = await this.locationService.getLocation();
Object.assign(params, {ip, address});
if (getHeadersIp) {
const {query_ip_location: { result: {ip} }, detail_location: { result: { address } } } = await this.locationService.getLocation(getHeadersIp);
Object.assign(params, {ip, address});
} else {
Object.assign(params, {ip: '无法获取', address: '无法获取'});
}
}
// 过滤空格,转换小写
const text = content.toLowerCase().replace(/\s*/g, '');
Expand Down

0 comments on commit 10bb988

Please sign in to comment.