提交 d7b34fe8 authored 作者: Whispa's avatar Whispa

commit

上级 c1ca6f5d
...@@ -19,14 +19,7 @@ import com.example.afrishop_v3.repository.UserRepository; ...@@ -19,14 +19,7 @@ import com.example.afrishop_v3.repository.UserRepository;
import com.example.afrishop_v3.security.jwt.JwtUtils; import com.example.afrishop_v3.security.jwt.JwtUtils;
import com.example.afrishop_v3.security.services.UserDetailsImpl; import com.example.afrishop_v3.security.services.UserDetailsImpl;
import com.example.afrishop_v3.util.IdUtil; import com.example.afrishop_v3.util.IdUtil;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseToken;
import org.hashids.Hashids; import org.hashids.Hashids;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
...@@ -36,11 +29,12 @@ import org.springframework.security.core.context.SecurityContextHolder; ...@@ -36,11 +29,12 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@CrossOrigin(origins = "*", maxAge = 3600) @CrossOrigin(origins = "*", maxAge = 3600)
...@@ -132,42 +126,6 @@ public class AuthController extends Controller { ...@@ -132,42 +126,6 @@ public class AuthController extends Controller {
private boolean validateFirebaseToken(String token) {
FirebaseOptions options;
try {
InputStream in = new ClassPathResource("afrishop-6e142-firebase-adminsdk-ypj91-b5e0248586.json").getInputStream();
// InputStream in = ResourceUtils.getURL("src/main/resources/afrishop-6e142-firebase-adminsdk-ypj91-b5e0248586.json").openStream();
options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(in))
.setDatabaseUrl("https://afrishop-6e142.firebaseio.com")
.build();
FirebaseApp firebaseApp;
try {
firebaseApp = FirebaseApp.getInstance("other");
} catch (IllegalStateException e) {
firebaseApp = FirebaseApp.initializeApp(options, "other");
}
FirebaseAuth instance = FirebaseAuth.getInstance(firebaseApp);
System.out.println(firebaseApp.getName());
System.out.println(token);
try {
FirebaseToken firebaseToken = instance.verifyIdToken(token);
// verify token successfully
return true;
} catch (FirebaseAuthException e) {
// verify token error
System.out.println("verify token error");
System.out.println(e.getMessage());
}
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
@PostMapping(value = "/register/user") @PostMapping(value = "/register/user")
......
...@@ -2,30 +2,90 @@ package com.example.afrishop_v3.controllers; ...@@ -2,30 +2,90 @@ package com.example.afrishop_v3.controllers;
import com.example.afrishop_v3.util.HttpClientUtil; import com.example.afrishop_v3.util.HttpClientUtil;
import com.example.afrishop_v3.util.IdUtil; import com.example.afrishop_v3.util.IdUtil;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseToken;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.FirebaseMessagingException;
import com.google.firebase.messaging.Message;
import com.google.firebase.messaging.Notification;
import org.json.JSONObject; import org.json.JSONObject;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpEntity; import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.text.NumberFormat; import java.text.NumberFormat;
import java.util.HashMap; import java.util.HashMap;
class Controller { class Controller {
String uid(){ String uid() {
return IdUtil.createIdbyUUID(); return IdUtil.createIdbyUUID();
} }
static int id = 0; static int id = 0;
NumberFormat formatter = new DecimalFormat("#0.00"); NumberFormat formatter = new DecimalFormat("#0.00");
private FirebaseApp getApp() {
FirebaseOptions options;
try {
InputStream in = new ClassPathResource("afrishop-6e142-firebase-adminsdk-ypj91-b5e0248586.json").getInputStream();
// InputStream in = ResourceUtils.getURL("src/main/resources/afrishop-6e142-firebase-adminsdk-ypj91-b5e0248586.json").openStream();
options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(in))
.setDatabaseUrl("https://afrishop-6e142.firebaseio.com")
.build();
FirebaseApp firebaseApp;
try {
firebaseApp = FirebaseApp.getInstance("other");
} catch (IllegalStateException e) {
firebaseApp = FirebaseApp.initializeApp(options, "other");
}
return firebaseApp;
} catch (IOException e) {
System.out.println(e.getMessage());
return null;
}
}
protected boolean validateFirebaseToken (String token){
FirebaseApp firebaseApp = getApp();
if( firebaseApp == null ) return false;
FirebaseAuth instance = FirebaseAuth.getInstance(firebaseApp);
System.out.println(firebaseApp.getName());
System.out.println(token);
try {
FirebaseToken firebaseToken = instance.verifyIdToken(token);
// verify token successfully
return firebaseToken != null;
} catch (FirebaseAuthException e) {
// verify token error
System.out.println("verify token error");
System.out.println(e.getMessage());
}
return false;
}
final String serverToken = "AAAAg-FJSfc:APA91bHr7OgmwmcP401YFBJZK_hkeeSO2qbMHXZaJa7Zup9U8dZ8XQqlFnF_z5q5fa9wskRu4PNiK8IMn0lYBjxJgi8srcafC1Mc-p2GU6T8v5kAQKvjwZoDJ_R0PVCvfroX09muIwln"; final String serverToken = "AAAAg-FJSfc:APA91bHr7OgmwmcP401YFBJZK_hkeeSO2qbMHXZaJa7Zup9U8dZ8XQqlFnF_z5q5fa9wskRu4PNiK8IMn0lYBjxJgi8srcafC1Mc-p2GU6T8v5kAQKvjwZoDJ_R0PVCvfroX09muIwln";
final String firebaseUrl = "https://fcm.googleapis.com/fcm/send"; final String firebaseUrl = "https://fcm.googleapis.com/fcm/send";
boolean sendNotification(String token,String title,String message){ boolean sendNotification(String token, String title, String _message) {
// Dio().post( // Dio().post(
// 'https://fcm.googleapis.com/fcm/send', // 'https://fcm.googleapis.com/fcm/send',
// options: Options(headers: <String, String>{ // options: Options(headers: <String, String>{
...@@ -48,40 +108,47 @@ class Controller { ...@@ -48,40 +108,47 @@ class Controller {
// ).then((f){print(f.data.toString());}); // ).then((f){print(f.data.toString());});
HashMap<String, Object> request = new HashMap<>(); HashMap<String, Object> request = new HashMap<>();
HashMap<String, Object> notification = new HashMap<>(); FirebaseApp firebaseApp = getApp();
HashMap<String, Object> data = new HashMap<>();
if( firebaseApp == null ) return false;
notification.put("body",message); FirebaseMessaging messaging = FirebaseMessaging.getInstance(firebaseApp);
notification.put("title",title);
data.put("click_action","FLUTTER_NOTIFICATION_CLICK");
data.put("id",id++);
data.put("status","done");
request.put("notification",notification);
request.put("data",data);
request.put("priority","high");
request.put("to",token);
String postRequest = sendPOSTRequest(request);
return postRequest != null;
Message message = Message.builder()
.putData("click_action", "FLUTTER_NOTIFICATION_CLICK")
.putData("id", String.valueOf(id++))
.putData("status", "done")
.setNotification(Notification.builder().setBody(_message).setTitle(title).build())
.setToken(token)
.build();
try {
messaging.send(message);
return true;
} catch (FirebaseMessagingException e) {
System.out.println(e.getMessage());
return false;
}
} }
private String sendPOSTRequest(HashMap<String, Object> data) { private String sendPOSTRequest(HashMap<String, Object> data) {
try { try {
RestTemplate restTemplate = new RestTemplate(); RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON); headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization","key="+serverToken); headers.set("Authorization", "key=" + serverToken);
HttpEntity entity = new HttpEntity<>(data, headers); HttpEntity entity = new HttpEntity<>(data, headers);
String answer = restTemplate.postForObject(firebaseUrl, entity, String.class); String answer = restTemplate.postForObject(firebaseUrl, entity, String.class);
System.out.println(answer); System.out.println(answer);
return answer; return answer;
}catch (Exception e){ } catch (Exception e) {
System.out.println(e.getMessage()); System.out.println(e.getMessage());
return null; return null;
} }
......
...@@ -74,14 +74,14 @@ public class PostController { ...@@ -74,14 +74,14 @@ public class PostController {
Optional<Hashtag> byName = hashtagRepository.findByName(tag); Optional<Hashtag> byName = hashtagRepository.findByName(tag);
if (!byName.isPresent()) return new ArrayList<>(); if (!byName.isPresent()) return new ArrayList<>();
return repository.findAllByOrderByIdDesc(byName.get(), PageRequest.of(pageNo, pageSize)).toList(); return repository.findAllByOrderByCreateDateDesc(byName.get(), PageRequest.of(pageNo, pageSize)).toList();
} }
@GetMapping("/listPostsLiked/{userId}") @GetMapping("/listPostsLiked/{userId}")
public List<Post> postListLiked(@PathVariable(value = "userId") String id, @RequestParam(value = "pageNo") Integer pageNo, @RequestParam(value = "pageSize") Integer pageSize) { public List<Post> postListLiked(@PathVariable(value = "userId") String id, @RequestParam(value = "pageNo") Integer pageNo, @RequestParam(value = "pageSize") Integer pageSize) {
Optional<TbCfUserInfo> byId = userRepository.findById(id); Optional<TbCfUserInfo> byId = userRepository.findById(id);
if (!byId.isPresent()) return new ArrayList<>(); if (!byId.isPresent()) return new ArrayList<>();
List<Post> postList = repository.findAllByOrderByIdDesc(byId.get(), PageRequest.of(pageNo, pageSize)).toList(); List<Post> postList = repository.findAllByOrderByCreateDateDesc(byId.get(), PageRequest.of(pageNo, pageSize)).toList();
return id == null ? postList : postList(postList, id); return id == null ? postList : postList(postList, id);
} }
......
...@@ -30,7 +30,7 @@ public class Post extends Model { ...@@ -30,7 +30,7 @@ public class Post extends Model {
private String category; private String category;
@Formula(value = "(SELECT IFNULL(COUNT(c.id),0) FROM post_like c WHERE c.post_id=id)") @Formula(value = "(SELECT IFNULL(COUNT(c.id),0) FROM post_like_v2 c WHERE c.post_id=id)")
private int likes; private int likes;
@Formula(value = "(SELECT IFNULL(COUNT(c.id),0) FROM comment c WHERE c.post_id=id)") @Formula(value = "(SELECT IFNULL(COUNT(c.id),0) FROM comment c WHERE c.post_id=id)")
private int comments; private int comments;
......
...@@ -588,6 +588,7 @@ public class TbCfUserInfo { ...@@ -588,6 +588,7 @@ public class TbCfUserInfo {
return isSend; return isSend;
} }
@JsonIgnore
public Collection<String> getRoles() { public Collection<String> getRoles() {
ArrayList<String> objects = new ArrayList<>(); ArrayList<String> objects = new ArrayList<>();
objects.add("user"); objects.add("user");
......
...@@ -15,9 +15,9 @@ public interface PostRepository extends PagingAndSortingRepository<Post, String> ...@@ -15,9 +15,9 @@ public interface PostRepository extends PagingAndSortingRepository<Post, String>
//@Query(value = "select a from #{#entityName} a WHERE EXISTS(SELECT f.follower FROM Following f WHERE f.follower=:me and f.followed=a.user)") //@Query(value = "select a from #{#entityName} a WHERE EXISTS(SELECT f.follower FROM Following f WHERE f.follower=:me and f.followed=a.user)")
//Page<Post> findAllByOrderByIdDesc(@Param("me") User user, Pageable pageable); //Page<Post> findAllByOrderByIdDesc(@Param("me") User user, Pageable pageable);
@Query(value = "select a from #{#entityName} a WHERE a IN (SELECT x.post FROM PostLike x WHERE x.userInfo=:me) order by a.createDate desc") @Query(value = "select a from #{#entityName} a WHERE a IN (SELECT x.post FROM PostLike x WHERE x.userInfo=:me) order by a.createDate desc")
Page<Post> findAllByOrderByIdDesc(@Param("me") TbCfUserInfo user, Pageable pageable); Page<Post> findAllByOrderByCreateDateDesc(@Param("me") TbCfUserInfo user, Pageable pageable);
@Query(value = "select a from #{#entityName} a WHERE a IN (SELECT x.post FROM PostHashtag x WHERE x.hashtag=:tag) order by a.createDate desc") @Query(value = "select a from #{#entityName} a WHERE a IN (SELECT x.post FROM PostHashtag x WHERE x.hashtag=:tag) order by a.createDate desc")
Page<Post> findAllByOrderByIdDesc(@Param("tag") Hashtag hashtag, Pageable pageable); Page<Post> findAllByOrderByCreateDateDesc(@Param("tag") Hashtag hashtag, Pageable pageable);
Page<Post> findAllByOrderByCreateDateDesc(Pageable pageable); Page<Post> findAllByOrderByCreateDateDesc(Pageable pageable);
//@Query(value = "select a from #{#entityName} a WHERE NOT EXISTS(SELECT f.follower FROM Following f WHERE f.follower=:me and f.followed=a.user)") //@Query(value = "select a from #{#entityName} a WHERE NOT EXISTS(SELECT f.follower FROM Following f WHERE f.follower=:me and f.followed=a.user)")
//Page<Post> _findAllByOrderByIdDesc(@Param("me") User user,Pageable pageable); //Page<Post> _findAllByOrderByIdDesc(@Param("me") User user,Pageable pageable);
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论