Skip to content

Commit

Permalink
Add google meet and calender
Browse files Browse the repository at this point in the history
  • Loading branch information
solomonfrank committed Aug 22, 2024
1 parent 104c2d9 commit 3812e3e
Show file tree
Hide file tree
Showing 53 changed files with 2,083 additions and 168 deletions.
28 changes: 28 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,34 @@
<artifactId>okhttp</artifactId>
<version>4.2.2</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.mnode.ical4j/ical4j -->
<dependency>
<groupId>org.mnode.ical4j</groupId>
<artifactId>ical4j</artifactId>
<version>4.0.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.api-client/google-api-client -->
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.35.2</version>
</dependency>

<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-calendar</artifactId>
<version>v3-rev411-1.25.0</version>
</dependency>


<dependency>
<groupId>com.google.oauth-client</groupId>
<artifactId>google-oauth-client-jetty</artifactId>
<version>1.36.0</version>
</dependency>


</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.example.springOAuth.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import lombok.Data;

@ConfigurationProperties("google")
@Configuration
@Data
public class GoogleCredentialProperties {

private CredentialDetails credentials = new CredentialDetails();

@Data
public static class CredentialDetails {

private String client_id;
private String client_secret;
private String auth_uri;
private String token_uri;
private String auth_provider_x509_cert_url;
private List<String> redirect_uris = new ArrayList<>();

private String redirectUrl;

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public void saveAuthorizationRequest(OAuth2AuthorizationRequest authorizationReq
cookieExpireSeconds);

String redirectUriAfterLogin = request.getParameter(REDIRECT_URI_PARAM_COOKIE_NAME);
;

if (StringUtils.isNotBlank(redirectUriAfterLogin)) {
CookieUtils.addCookie(response, REDIRECT_URI_PARAM_COOKIE_NAME, redirectUriAfterLogin, cookieExpireSeconds);
}
Expand Down
33 changes: 31 additions & 2 deletions src/main/java/com/example/springOAuth/config/MailConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,55 @@
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import com.example.springOAuth.service.Email.IEmailProvider;
import com.example.springOAuth.service.Email.SmtpConfigModel;
import com.example.springOAuth.service.Email.SmtpEmailProvider;

@Configuration
public class MailConfig {

@Bean
public JavaMailSender getJavaMailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("smtp.gmail.com");
mailSender.setPort(587);
// mailSender.setPort(587);

mailSender.setUsername("solomonrock13@gmail.com");
mailSender.setPassword("ijwk qghc fcfk kcan");

Properties props = mailSender.getJavaMailProperties();
// props.put("mail.transport.protocol", "smtp");
// props.put("mail.smtp.auth", "true");
// props.put("mail.smtp.starttls.enable", true);
// props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
// props.put("mail.debug", "true");

props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", true);
// props.put("mail.smtp.starttls.enable", false);
props.put("mail.smtp.ssl.enable", true);
props.put("mail.smtp.port", "465");
props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
props.put("mail.debug", "true");
props.put("mail.smtp.host", "smtp.gmail.com");

return mailSender;
}

@Bean
public IEmailProvider getSmtpEmailProvider() {
var config = SmtpConfigModel.builder()
.auth(true)
.password("ijwk qghc fcfk kcan")
.username("solomonrock13@gmail.com")
.host("smtp.gmail.com")
.port(465)
.debug("true")
.enableSSl(true)
.starttlsEnable(false)
.trust("smtp.gmail.com")
.protocol("smtp")
.build();
return new SmtpEmailProvider(config);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public void onAuthenticationFailure(HttpServletRequest request, HttpServletRespo
.orElse(("/"));

targetUrl = UriComponentsBuilder.fromUriString(targetUrl)
.queryParam("error", exception.getMessage())
.queryParam("error", exception.getMessage().toString())
.build().toUriString();

httpCookieOAuth2AuthorizationRequestRepository.removeAuthorizationRequestCookies(request, response);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriComponentsBuilder;
Expand Down Expand Up @@ -44,9 +46,8 @@ public class OAuth2SuccessHandler extends SimpleUrlAuthenticationSuccessHandler
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
// OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken)
// authentication;
// OAuth2User oauthUser = oauthToken.getPrincipal();
OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
OAuth2User oauthUser = oauthToken.getPrincipal();

// var provider = oauthToken.getAuthorizedClientRegistrationId();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,14 @@ SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
.requestMatchers("/api/v1/auth/**").permitAll()
.requestMatchers("/oauth2/**").permitAll()
.requestMatchers("/login/**").permitAll()

.requestMatchers("/api/apps/**").permitAll()
.requestMatchers("/api/integration/googlecalender/callback").permitAll()
.requestMatchers(HttpMethod.GET, "/api/v1/event-type/{userId}/{slug}")
.permitAll()
.requestMatchers(HttpMethod.GET, "/api/v1/payment/verify/{reference}")
.permitAll()
.requestMatchers(HttpMethod.POST, "/api/v1/booking").permitAll()
.requestMatchers(HttpMethod.GET, "/api/v1/booking").permitAll()
.requestMatchers("/", "/error", "/csrf", "/swagger-ui.html",
"/swagger-ui/**", "/v3/api-docs",
"/v3/api-docs/**")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
package com.example.springOAuth.controller;

import java.io.FileNotFoundException;
import java.io.IOException;

import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
Expand All @@ -10,17 +17,21 @@
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.springOAuth.entity.Booking;
import com.example.springOAuth.entity.User;
import com.example.springOAuth.model.BookingRequest;
import com.example.springOAuth.repository.BookingRepository;
import com.example.springOAuth.repository.UserRepository;
import com.example.springOAuth.response.BookingResponse;
import com.example.springOAuth.response.PagedResponse;
import com.example.springOAuth.service.BookingService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.mail.MessagingException;
import jakarta.validation.Valid;

@RestController
Expand All @@ -41,19 +52,32 @@ public class BookingController {

@Operation(security = { @SecurityRequirement(name = "bearer-key") })
@GetMapping("")
public ResponseEntity<?> getBooking(@AuthenticationPrincipal User currentUser) {
public ResponseEntity<?> getBooking(@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size, @AuthenticationPrincipal User currentUser) {
User user = userRepository.findById(currentUser.getId())
.orElseThrow(() -> new UsernameNotFoundException("User does not exist"));

var bookings = bookingRepository.findAllByUser(user);
int pageSize = Math.min(size > 0 ? size : 10, 15);

Pageable pageable = PageRequest.of(Math.max(page - 1, 0), pageSize, Sort.by("createdAt").descending());

Page<Booking> bookings = bookingRepository.findAllByUser(user, pageable);

var mappedBooking = bookings.getContent().stream()
.map(booking -> modelMapper.map(booking, BookingResponse.class)).toList();

var mappedBooking = bookings.stream().map(booking -> modelMapper.map(booking, BookingResponse.class));
var response = PagedResponse.<BookingResponse>builder().data(mappedBooking)
.totalElements(bookings.getTotalElements()).totalPages(bookings.getTotalPages())
.first(bookings.isFirst()).last(bookings.isLast())
.size(bookings.getSize())
.build();

return ResponseEntity.status(HttpStatus.OK).body(mappedBooking);
return ResponseEntity.status(HttpStatus.OK).body(response);
}

@PostMapping("")
public ResponseEntity<?> bookEvent(@Valid @RequestBody BookingRequest entity) {
public ResponseEntity<?> bookEvent(@Valid @RequestBody BookingRequest entity)
throws FileNotFoundException, MessagingException, IOException {
var booking = bookingService.handleBooking(entity);
return ResponseEntity.status(HttpStatus.CREATED).body(booking);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import com.example.springOAuth.entity.User;
import com.example.springOAuth.model.EventTypeRequest;
import com.example.springOAuth.response.EventTypeResponse;
import com.example.springOAuth.service.BookingService;
import com.example.springOAuth.service.EventTypeService;

import io.swagger.v3.oas.annotations.Operation;
Expand All @@ -37,6 +38,9 @@ public class EventTypeController {
@Autowired
private EventTypeService eventTypeService;

@Autowired
private BookingService bookingService;

@Operation(security = { @SecurityRequirement(name = "bearer-key") })
@ApiResponse(responseCode = "201", description = "Successful operation", content = {
@Content(mediaType = "application/json", schema = @Schema(implementation = EventTypeResponse.class))
Expand Down Expand Up @@ -92,4 +96,13 @@ public ResponseEntity<?> deleteEventType(@PathVariable("id") Long id,
return ResponseEntity.status(HttpStatus.OK).body(response);
}

@GetMapping("/{userId}/analysis")
public ResponseEntity<?> getAnalysis(@PathVariable("userId") Long userId) {

var response = bookingService.getAnalysisHandler(userId);

return ResponseEntity.status(HttpStatus.OK).body(response);

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.example.springOAuth.controller;

import java.io.IOException;
import java.security.GeneralSecurityException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.springOAuth.entity.User;
import com.example.springOAuth.service.CredentialService;
import com.example.springOAuth.service.Apps.CalendarService;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/api/v1/apps")
public class InstalledAppsControlled {

@Autowired
private CalendarService calendarService;

@Autowired
private CredentialService credentialService;

@GetMapping("/{appName}")
public void getMethodName(@PathVariable String appName, HttpServletRequest request,
HttpServletResponse response) throws IOException, GeneralSecurityException {
// String redirect = GoogleMeetLinkGen.createMeetingLink(null, request,
// response);

String authorizeUrl = calendarService.getAuthorizationUrl(request, response);
var stratigy = new DefaultRedirectStrategy();
stratigy.sendRedirect(request, response, authorizeUrl);
}

@GetMapping("/installed")
public ResponseEntity<?> getInstalledApps(@AuthenticationPrincipal User currentUser) {

var response = credentialService.getInstalledAppHandler(currentUser);
return ResponseEntity.status(HttpStatus.OK).body(response);
}

}
Loading

0 comments on commit 3812e3e

Please sign in to comment.