Skip to content

Commit

Permalink
chore: bump
Browse files Browse the repository at this point in the history
  • Loading branch information
bs32g1038 committed Apr 22, 2024
1 parent d3a29fa commit 16f0332
Show file tree
Hide file tree
Showing 12 changed files with 1,264 additions and 2,351 deletions.
16 changes: 13 additions & 3 deletions server/src/main/java/com/jixialunbi/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;

/**
* Configuration file used to configure security settings of the application
Expand Down Expand Up @@ -67,10 +68,19 @@ public PasswordEncoder passwordEncoder() {
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
public CorsConfiguration corsConfiguration() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addAllowedHeader("*");
return corsConfiguration;
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity, CorsConfiguration corsConfiguration) throws Exception {
httpSecurity
.cors().and()
.csrf().disable()
.cors(cors -> cors.configurationSource(request -> corsConfiguration))
.csrf(e -> e.disable())
.exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeHttpRequests(auth ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ public R fetchPosts(
@RequestParam(required = false) Long userId,
@RequestParam(required = false, defaultValue = "false") boolean isHot,
@AuthenticationPrincipal UserDetailsImpl userDetails
) {
) {
Long authorId = null;
if (userId != null) {
authorId = userService.getById(userId.longValue()).getId();
Expand Down Expand Up @@ -164,19 +164,14 @@ public R pinnedPosts() {

@GetMapping("/posts/{postId}")
@Transactional
public R getPost(@PathVariable long postId, Principal principal) {
public R getPost(@PathVariable long postId, @AuthenticationPrincipal UserDetailsImpl userDetails) {
var post = postRepository.findById(postId);
if (!post.get().equals(null)) {
post.get().setVisitCount(post.get().getVisitCount() + 1);
}
User user;
if (principal == null) {
user = null;
} else {
user = userService.getByAccount(principal.getName());
}
// 点赞数据
if (user != null) {
if(userDetails != null){
User user = userService.getById(userDetails.getId());
// 点赞数据
var res = postLikeRepository.findOneByPostIdAndAuthorId(postId, user.getId());
post.get().setLiked(res != null && res.getDeleted() == null);
var cn = postCollectionRepository.findOneByPostIdAndAuthorId(postId, user.getId());
Expand All @@ -188,9 +183,10 @@ public R getPost(@PathVariable long postId, Principal principal) {
}

@Transactional
@PreAuthorize("hasRole('ROLE_USER')")
@PostMapping("/like-post/{postId}")
public R likePost(@PathVariable long postId, Principal principal) {
var user = userService.getByAccount(principal.getName());
public R likePost(@PathVariable long postId, @AuthenticationPrincipal UserDetailsImpl userDetails) {
var user = userService.getById(userDetails.getId());
var res = postLikeRepository.findOneByPostIdAndAuthorId(postId, user.getId());
if (res != null) {
if (res.getDeleted() == null) {
Expand All @@ -213,6 +209,7 @@ public R likePost(@PathVariable long postId, Principal principal) {
}

@Transactional
@PreAuthorize("hasRole('ROLE_USER')")
@PostMapping("/collect-post/{postId}")
public R collectPost(@PathVariable long postId, Principal principal) {
var user = userService.getByAccount(principal.getName());
Expand Down
16 changes: 10 additions & 6 deletions server/src/main/java/com/jixialunbi/security/AuthTokenFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Arrays;
import java.util.Optional;

import static com.jixialunbi.common.Constants.CANNOT_SET_AUTH;

Expand Down Expand Up @@ -59,11 +60,14 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
}

private String parseJwt(HttpServletRequest request) {
String headerAuth = request.getHeader("Authorization");

if (StringUtils.hasText(headerAuth) && headerAuth.startsWith("Bearer ")) {
return headerAuth.substring(7, headerAuth.length());
if (request.getCookies() == null) {
return null;
}
return null;
return Optional.ofNullable(request.getCookies())
.flatMap(cookies -> Arrays.stream(cookies)
.filter(e -> "token".equals(e.getName()))
.findAny())
.map(e -> e.getValue())
.orElse(null);
}
}
1 change: 0 additions & 1 deletion web/components/AppHeader/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ const NotificationIcon = () => {
export default function AppHeader() {
const router = useRouter();
const { showLoginModal, user } = useAppStore();
const [open, setOpen] = useState(false);
return (
<header className={styles.header}>
<div className={styles.headerleft}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { useSWRMutation } from '@/hooks';
import { useAppStore } from '@/store';

interface Props {
authorId: number;
authorId: string;
pinned: boolean;
postId: number;
id: number;
Expand Down
5 changes: 5 additions & 0 deletions web/components/home/useStore.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { create } from 'zustand';

export const useStore = create(() => ({
user: null,
}));
34 changes: 34 additions & 0 deletions web/components/post/components/Post/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
'use client';

import React from 'react';
import styles from '../../index.module.scss';
import Layout from '../../../Layout';
import CommentList from '../CommentList';
import WriteComment from '../WriteComment';
import { useSWR } from '@/hooks';
import TopTip from '../../../home/components/TopTip';
import TopicItem from '../TopicItem';
import { useParams } from 'next/navigation';

export default function Post({ data }) {
const { id } = useParams();
const _data = data?.data;
const resPostData = useSWR({
url: '/api/v1/post-comments',
params: {
postId: id,
},
});
return (
<Layout>
<div className={styles.wrap}>
<TopTip></TopTip>
{_data && <TopicItem item={_data}></TopicItem>}
<div className={styles.inner}>
<WriteComment postId={Number(id)}></WriteComment>
<CommentList postId={Number(id)} items={resPostData?.data?.data ?? []}></CommentList>
</div>
</div>
</Layout>
);
}
6 changes: 3 additions & 3 deletions web/components/post/components/TopicItem/index.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
'use client';
import React from 'react';
import Link from 'next/link';
import { parseTime } from '../../../../libs/time';
import styles from './index.module.scss';
import { Avatar, Button, Space, Tag, Popover, Image } from 'antd';
import { CommentOutlined, EyeOutlined, FlagOutlined, TagOutlined } from '@ant-design/icons';
import { CommentOutlined, TagOutlined } from '@ant-design/icons';
import LikeButton from '../../../LikeButton';
import { unionBy } from 'lodash';
import dynamic from 'next/dynamic';
Expand All @@ -16,7 +17,6 @@ const CImage: any = dynamic(() => import('./components/CImage') as any, {

export default function TopicItem(props: { item: any }) {
const item = props.item;
console.log(item);
const participants = unionBy(item?.participants, 'id');
return (
<div key={item.title} className={styles.item}>
Expand Down Expand Up @@ -68,7 +68,7 @@ export default function TopicItem(props: { item: any }) {
{item?.author?.username}
</Link>
<span>·</span>
<p className={styles.lastEditTime}>{parseTime(item.updatedAt)}</p>
<p className={styles.lastEditTime}>{parseTime(item?.createdAt)}</p>
</Space>
{item.content && (
<p
Expand Down
76 changes: 11 additions & 65 deletions web/components/post/index.tsx
Original file line number Diff line number Diff line change
@@ -1,69 +1,15 @@
'use client';
// 'use client';

import React, { useState } from 'react';
import styles from './index.module.scss';
import Layout from '../Layout';
import { Button, Space, Image, Tag } from 'antd';
import CommentList from './components/CommentList';
import { useRouter } from 'next/navigation';
import WriteComment from './components/WriteComment';
import { useSWR } from '@/hooks';
import LikeButton from '../LikeButton';
import classNames from 'classnames';
import { CommentOutlined } from '@ant-design/icons';
import CollectButton from '../CollectButton';
import FollowButton from '../FollowButton';
import dynamic from 'next/dynamic';
import axios from '@/libs/axios';
import Link from 'next/link';
import { parseTime } from '@/libs/time';
import TopTip from '../home/components/TopTip';
import PinnedList from '../home/components/PinnedList';
import CategoryList from '../home/components/CategoryList';
import TopicItem from './components/TopicItem';
import { useParams } from 'next/navigation';
import Post from './components/Post';

const CImage: any = dynamic(() => import('../home/components/TopicItem/components/CImage') as any, {
ssr: false,
});

export default function Post(props) {
const { id } = useParams();
const router = useRouter();
const url = '/api/v1/posts/' + id;
const { data: newData = {} } = useSWR({ url });
const data = newData?.data ?? {};
const [open, setOpen] = useState(false);
const resPostData = useSWR({
url: '/api/v1/post-comments',
params: {
postId: id,
},
});
return (
<Layout>
<div className={styles.wrap}>
<TopTip></TopTip>
{/* <PinnedList></PinnedList> */}
{/* <CategoryList></CategoryList> */}
<TopicItem item={data} key={data.id}></TopicItem>
<div className={styles.inner}>
<WriteComment postId={Number(id)}></WriteComment>
<CommentList postId={Number(id)} items={resPostData?.data?.data ?? []}></CommentList>
</div>
</div>
</Layout>
);
}

export async function getServerSideProps(context) {
const { query } = context;
const { id } = query as any;
const Index = async (props: { params: any }) => {
const { id } = props.params;
const url = '/api/v1/posts/' + id;
const post = await axios.get(url).then((res) => res.data);
return {
props: {
data: post,
},
};
}
const data = await axios
.get(url)
.then((res) => res.data)
.catch((err) => {});
return <Post data={data}></Post>;
};
export default Index;
Loading

0 comments on commit 16f0332

Please sign in to comment.