Changeset f25d07e


Ignore:
Timestamp:
09/07/22 00:51:50 (21 months ago)
Author:
Marko <Marko@…>
Branches:
master
Children:
527b93f
Parents:
dbd4834
Message:

Edited registration and login services

Location:
phonelux-backend
Files:
2 added
15 edited

Legend:

Unmodified
Added
Removed
  • phonelux-backend/pom.xml

    rdbd4834 rf25d07e  
    1818        </properties>
    1919        <dependencies>
     20
    2021                <dependency>
    2122                        <groupId>org.springframework.boot</groupId>
    2223                        <artifactId>spring-boot-starter-data-jpa</artifactId>
    2324                </dependency>
     25
    2426                <dependency>
    2527                        <groupId>org.springframework.boot</groupId>
    2628                        <artifactId>spring-boot-starter-security</artifactId>
    2729                </dependency>
     30
    2831                <dependency>
    2932                        <groupId>org.springframework.boot</groupId>
    3033                        <artifactId>spring-boot-starter-web</artifactId>
    3134                </dependency>
     35
    3236                <dependency>
    3337                        <groupId>org.springframework.boot</groupId>
    3438                        <artifactId>spring-boot-starter-mail</artifactId>
    3539                </dependency>
     40
    3641                <dependency>
    3742                        <groupId>org.postgresql</groupId>
     
    3944                        <scope>runtime</scope>
    4045                </dependency>
     46
    4147                <dependency>
    4248                        <groupId>org.projectlombok</groupId>
     
    4450                        <optional>true</optional>
    4551                </dependency>
     52
    4653                <dependency>
    4754                        <groupId>org.springframework.boot</groupId>
     
    4956                        <scope>test</scope>
    5057                </dependency>
     58
    5159                <dependency>
    5260                        <groupId>org.springframework.security</groupId>
     
    5462                        <scope>test</scope>
    5563                </dependency>
     64
     65                <dependency>
     66                        <groupId>com.auth0</groupId>
     67                        <artifactId>java-jwt</artifactId>
     68                        <version>4.0.0</version>
     69                </dependency>
     70
    5671        </dependencies>
    5772
  • phonelux-backend/src/main/java/finki/it/phoneluxbackend/controllers/PhoneController.java

    rdbd4834 rf25d07e  
    33import finki.it.phoneluxbackend.entities.Phone;
    44import finki.it.phoneluxbackend.entities.PhoneOffer;
     5import finki.it.phoneluxbackend.services.PhoneOfferService;
    56import finki.it.phoneluxbackend.services.PhoneService;
     7import lombok.AllArgsConstructor;
    68import org.springframework.beans.factory.annotation.Autowired;
    79import org.springframework.web.bind.annotation.*;
    810
     11import java.util.Comparator;
    912import java.util.List;
     13import java.util.stream.Collectors;
    1014
    1115@RestController
     16@AllArgsConstructor
    1217@RequestMapping(path = "/")
    1318public class PhoneController {
    1419    private final PhoneService phoneService;
     20    private final PhoneOfferService phoneOfferService;
    1521
    16     @Autowired
    17     public PhoneController(PhoneService phoneService) {
    18         this.phoneService = phoneService;
     22//     handle request parameters for filtering phones
     23    @GetMapping(path = "/phones")
     24    public List<Phone> getPhones(){
     25        return phoneService.getPhones().stream()
     26                .sorted(Comparator.comparing(Phone::getTotal_offers).reversed())
     27                .collect(Collectors.toList());
     28    }
     29
     30    @GetMapping(path = "/phones/{phoneId}")
     31    public Phone getPhoneById(@PathVariable("phoneId") Long phoneId)
     32    {
     33        return phoneService.getPhoneById(phoneId);
     34    }
     35
     36    @GetMapping(path = "/brands")
     37    public List<String> getBrands(){
     38        return phoneService.getBrands();
     39    }
     40
     41    @GetMapping(path = "/shops")
     42    public List<String> getShops(){
     43        return phoneOfferService.getShops();
     44    }
     45
     46    @GetMapping(path = "/lowestPrice")
     47    public int getLowestPrice()
     48    {
     49        return phoneOfferService.getLowestPrice();
     50    }
     51
     52    @GetMapping(path = "/highestPrice")
     53    public int getHighestPrice()
     54    {
     55        return phoneOfferService.getHighestPrice();
    1956    }
    2057
    2158
    22     // handle request parameters for filtering phones
    23     @GetMapping
    24     public List<Phone> getPhones(){
    25         return phoneService.getPhones();
    26     }
    27 
    2859}
  • phonelux-backend/src/main/java/finki/it/phoneluxbackend/controllers/PhoneOfferController.java

    rdbd4834 rf25d07e  
    11package finki.it.phoneluxbackend.controllers;
    22
     3import finki.it.phoneluxbackend.entities.Phone;
    34import finki.it.phoneluxbackend.entities.PhoneOffer;
    45import finki.it.phoneluxbackend.services.PhoneOfferService;
     6import finki.it.phoneluxbackend.services.PhoneService;
     7import lombok.AllArgsConstructor;
    58import org.springframework.beans.factory.annotation.Autowired;
    69import org.springframework.web.bind.annotation.GetMapping;
     
    1215
    1316@RestController
    14 @RequestMapping(path = "/phone/{phoneId}")
     17@AllArgsConstructor
     18@RequestMapping(path = "/phones/offers/{phoneId}")
    1519public class PhoneOfferController {
    1620    private final PhoneOfferService phoneOfferService;
    17 
    18     @Autowired
    19     public PhoneOfferController(PhoneOfferService phoneOfferService) {
    20         this.phoneOfferService = phoneOfferService;
    21     }
     21    private final PhoneService phoneService;
    2222
    2323    @GetMapping
     
    2525        return phoneOfferService.getPhoneOffersForPhone(phoneId);
    2626    }
     27
    2728}
  • phonelux-backend/src/main/java/finki/it/phoneluxbackend/controllers/RegistrationController.java

    rdbd4834 rf25d07e  
    44import finki.it.phoneluxbackend.services.RegistrationService;
    55import lombok.AllArgsConstructor;
     6import org.springframework.http.ResponseEntity;
    67import org.springframework.web.bind.annotation.*;
    78
     
    1314
    1415    @PostMapping
    15     public String RegisterRequest(@RequestBody RegistrationRequest request)
     16    public ResponseEntity<Object> RegisterRequest(@RequestBody RegistrationRequest request)
    1617    {
    1718        return registrationService.register(request);
  • phonelux-backend/src/main/java/finki/it/phoneluxbackend/entities/ConfirmationToken.java

    rdbd4834 rf25d07e  
    1313@Setter
    1414@NoArgsConstructor
    15 @Entity(name = "confirmation_tokens")
     15@Entity(name = "ConfirmationToken")
     16@Table(name = "confirmation_tokens")
    1617public class ConfirmationToken {
    1718
  • phonelux-backend/src/main/java/finki/it/phoneluxbackend/entities/Phone.java

    rdbd4834 rf25d07e  
    2828    private String image_url;
    2929
     30    @Column(name = "total_offers")
     31    private Integer total_offers;
     32
     33    @Column(name = "lowest_price")
     34    private Integer lowestPrice;
     35
    3036    @OneToMany(fetch = FetchType.LAZY, mappedBy = "phone")
    3137    @JsonIgnore
  • phonelux-backend/src/main/java/finki/it/phoneluxbackend/entities/PhoneOffer.java

    rdbd4834 rf25d07e  
    55
    66import javax.persistence.*;
     7import java.util.ArrayList;
    78import java.util.Date;
     9import java.util.List;
    810
    911@AllArgsConstructor
     
    7375    private String offer_shop_code;
    7476
     77    @ManyToMany(mappedBy = "favouriteOffers")
     78    private List<User> users = new ArrayList<User>();
     79
    7580    @ManyToOne(fetch = FetchType.LAZY)
    7681    @JoinColumn(name = "phone_id", referencedColumnName = "id")
  • phonelux-backend/src/main/java/finki/it/phoneluxbackend/entities/User.java

    rdbd4834 rf25d07e  
    88
    99import javax.persistence.*;
     10import java.util.ArrayList;
    1011import java.util.Collection;
    1112import java.util.Collections;
     13import java.util.List;
    1214
    1315@Getter
     
    1618@NoArgsConstructor
    1719@AllArgsConstructor
    18 @Entity(name = "users")
     20@Entity(name = "User")
     21@Table(name = "users")
    1922public class User implements UserDetails {
    2023
     
    3841    private Boolean locked = false;
    3942    private Boolean enabled = false;
     43
     44    @ManyToMany
     45    @JoinTable(
     46            name = "users_favourite_offers",
     47            joinColumns = @JoinColumn(name = "user_id"),
     48            inverseJoinColumns = @JoinColumn(name = "offer_id")
     49    )
     50    private List<PhoneOffer> favouriteOffers = new ArrayList<PhoneOffer>();
    4051
    4152    public User(String firstName, String lastName, String email, String password, UserRole userRole) {
  • phonelux-backend/src/main/java/finki/it/phoneluxbackend/repositories/ConfirmationTokenRepository.java

    rdbd4834 rf25d07e  
    1717    @Transactional
    1818    @Modifying
    19     @Query("UPDATE confirmation_tokens c " +
     19    @Query("UPDATE ConfirmationToken c " +
    2020            "SET c.confirmedAt = ?2 " +
    2121            "WHERE c.token = ?1")
  • phonelux-backend/src/main/java/finki/it/phoneluxbackend/repositories/UserRepository.java

    rdbd4834 rf25d07e  
    1818    @Transactional
    1919    @Modifying
    20     @Query("UPDATE users a " +
     20    @Query("UPDATE User a " +
    2121            "SET a.enabled = TRUE WHERE a.email = ?1")
    2222    int enableUser(String email);
  • phonelux-backend/src/main/java/finki/it/phoneluxbackend/security/configs/WebSecurityConfig.java

    rdbd4834 rf25d07e  
    11package finki.it.phoneluxbackend.security.configs;
    22
     3import finki.it.phoneluxbackend.security.CustomAuthenticationFilter;
     4import finki.it.phoneluxbackend.security.CustomAuthorizationFilter;
    35import finki.it.phoneluxbackend.services.UserService;
    46import lombok.AllArgsConstructor;
     7import org.springframework.context.annotation.Bean;
    58import org.springframework.context.annotation.Configuration;
     9import org.springframework.security.authentication.AuthenticationManager;
    610import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
    7 import org.springframework.security.config.annotation.SecurityBuilder;
    811import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    9 import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
    1012import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    1113import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    12 import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;
    1314import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    14 import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
     15import org.springframework.security.config.http.SessionCreationPolicy;
    1516import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    16 import org.springframework.security.web.SecurityFilterChain;
     17import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
     18
     19import static org.springframework.http.HttpMethod.GET;
    1720
    1821@Configuration
     
    2629    @Override
    2730    protected void configure(HttpSecurity http) throws Exception {
    28         http
    29                 .csrf().disable()
    30                 .authorizeRequests()
    31                 .antMatchers("/registration/**")
    32                 .permitAll()
    33                 .anyRequest()
    34                 .authenticated().and()
    35                 .formLogin();
     31//        http
     32//                .csrf().disable()
     33//                .authorizeRequests()
     34//                .antMatchers("/registration/**")
     35//                .permitAll()
     36//                .anyRequest()
     37//                .authenticated().and()
     38//                .formLogin();
     39
     40        http.csrf().disable();
     41        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
     42//        http.authorizeRequests().antMatchers(GET,"/phones").hasAnyAuthority("USER");
     43        http.authorizeRequests().anyRequest().permitAll();
     44        http.addFilter(new CustomAuthenticationFilter(authenticationManagerBean()));
     45        http.addFilterBefore(new CustomAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class);
    3646
    3747    }
     
    4252    }
    4353
     54    @Bean
     55    @Override
     56    public AuthenticationManager authenticationManagerBean() throws Exception {
     57        return super.authenticationManagerBean();
     58    }
    4459
    4560    public DaoAuthenticationProvider daoAuthenticationProvider(){
  • phonelux-backend/src/main/java/finki/it/phoneluxbackend/services/PhoneOfferService.java

    rdbd4834 rf25d07e  
    77
    88import java.util.ArrayList;
     9import java.util.Comparator;
    910import java.util.List;
     11import java.util.stream.Collectors;
    1012
    1113@Service
     
    2426            throw new IllegalStateException("Phone with id "+phoneId+" does not exist");
    2527
    26         return phoneRepository.findById(phoneId).get().getPhoneOffers();
     28        return phoneRepository.findById(phoneId).get().getPhoneOffers()
     29                .stream().sorted(Comparator.comparing(PhoneOffer::getPrice)).collect(Collectors.toList());
    2730    }
     31
     32    public List<String> getShops() {
     33        return phoneOfferRepository.findAll().stream()
     34                .map(PhoneOffer::getOffer_shop)
     35                .distinct()
     36                .collect(Collectors.toList());
     37    }
     38
     39
     40    public int getLowestPrice() {
     41        return phoneOfferRepository.findAll()
     42                .stream().sorted(Comparator.comparing(PhoneOffer::getPrice))
     43                .collect(Collectors.toList()).get(0).getPrice();
     44    }
     45
     46    public int getHighestPrice() {
     47        return phoneOfferRepository.findAll()
     48                .stream().sorted(Comparator.comparing(PhoneOffer::getPrice).reversed())
     49                .collect(Collectors.toList()).get(0).getPrice();
     50    }
     51
    2852}
  • phonelux-backend/src/main/java/finki/it/phoneluxbackend/services/PhoneService.java

    rdbd4834 rf25d07e  
    44import finki.it.phoneluxbackend.entities.PhoneOffer;
    55import finki.it.phoneluxbackend.repositories.PhoneRepository;
     6import org.springframework.data.domain.PageRequest;
    67import org.springframework.data.domain.Sort;
    78import org.springframework.stereotype.Service;
    89
     10import java.util.Comparator;
    911import java.util.List;
     12import java.util.stream.Collectors;
    1013
    1114@Service
     
    1720    }
    1821
     22
     23    // TODO: insert logic to filter
    1924    public List<Phone> getPhones(){
    2025        return phoneRepository.findAll();
    2126    }
    2227
     28    public List<String> getBrands(){
     29        return phoneRepository.findAll().stream()
     30                .map(Phone::getBrand).distinct()
     31                .collect(Collectors.toList());
     32    }
     33
     34    public Phone getPhoneById(Long phoneId) {
     35        boolean exists = phoneRepository.existsById(phoneId);
     36        if(!exists)
     37            throw new IllegalStateException("Phone with id "+phoneId+" does not exist");
     38        return phoneRepository.findById(phoneId).get();
     39    }
    2340}
  • phonelux-backend/src/main/java/finki/it/phoneluxbackend/services/RegistrationService.java

    rdbd4834 rf25d07e  
    11package finki.it.phoneluxbackend.services;
    22
     3import com.fasterxml.jackson.core.JsonParser;
     4import com.fasterxml.jackson.core.io.JsonStringEncoder;
     5import com.fasterxml.jackson.databind.ObjectMapper;
     6import com.fasterxml.jackson.databind.util.JSONPObject;
    37import finki.it.phoneluxbackend.data.RegistrationRequest;
    48import finki.it.phoneluxbackend.data.UserRole;
     
    812import finki.it.phoneluxbackend.security.email.EmailValidator;
    913import lombok.AllArgsConstructor;
     14import org.apache.coyote.Response;
     15import org.apache.tomcat.util.json.JSONParser;
     16import org.springframework.http.HttpStatus;
     17import org.springframework.http.ResponseEntity;
    1018import org.springframework.stereotype.Service;
    1119import org.springframework.transaction.annotation.Transactional;
    1220
    1321import java.time.LocalDateTime;
     22import java.util.HashMap;
    1423
    1524@Service
     
    2231
    2332
    24     public String register(RegistrationRequest request) {
     33    public ResponseEntity<Object> register(RegistrationRequest request) {
    2534        boolean isValidEmail = emailValidator.test(request.getEmail());
    2635
    27         // validacija za mejl na frontend ?
     36        // mail is validated on frontend already
    2837        if (!isValidEmail)
    2938            throw new IllegalStateException("Email"+request.getEmail()+" not valid!");
    3039
    31         String token = userService.signUpUser(
     40        ResponseEntity response = userService.signUpUser(
    3241                new User(request.getFirstName(),
    3342                        request.getLastName(),
     
    3645                        UserRole.USER));
    3746
    38         String link = "http://localhost:8080/registration/confirm?token="+token;
     47        if (response.getStatusCode() == HttpStatus.BAD_REQUEST)
     48        {
     49            return response;
     50        }
     51
     52        String link = "http://localhost:8080/registration/confirm?token="+response.getBody()
     53                .toString().split(":")[1];
    3954        emailSender.send(request.getEmail(), buildEmail(request.getFirstName(),link));
    40         return token;
     55
     56        return response;
    4157    }
    4258
     
    113129    @Transactional
    114130    public String confirmToken(String token) {
    115         ConfirmationToken confirmationToken = confirmationTokenService.getToken(token)
    116                 .orElseThrow(() -> new IllegalStateException("Token not found!"));
     131        boolean confirmationTokenExists = confirmationTokenService.getToken(token).isPresent();
     132
     133        ConfirmationToken confirmationToken;
     134
     135        if(confirmationTokenExists)
     136            confirmationToken = confirmationTokenService.getToken(token).get();
     137        else
     138            return "Token not found!";
    117139
    118140        if(confirmationToken.getConfirmedAt() != null)
    119             throw new IllegalStateException("Email already confirmed!");
     141            return "Email already confirmed!";
    120142
    121143        LocalDateTime expiresAt = confirmationToken.getExpiresAt();
    122144
    123145        if (expiresAt.isBefore(LocalDateTime.now())){
    124             throw new IllegalStateException("Token expired");
     146            return "Token expired";
    125147        }
    126148
  • phonelux-backend/src/main/java/finki/it/phoneluxbackend/services/UserService.java

    rdbd4834 rf25d07e  
    11package finki.it.phoneluxbackend.services;
     2
    23
    34import finki.it.phoneluxbackend.entities.User;
     
    56import finki.it.phoneluxbackend.entities.ConfirmationToken;
    67import lombok.AllArgsConstructor;
     8
     9import org.springframework.http.ResponseEntity;
    710import org.springframework.security.core.userdetails.UserDetails;
    811import org.springframework.security.core.userdetails.UserDetailsService;
     
    1215
    1316import java.time.LocalDateTime;
     17
    1418import java.util.UUID;
    1519
     
    2832    }
    2933
    30     public String signUpUser(User user)
     34    public ResponseEntity<Object> signUpUser(User user)
    3135    {
    32        boolean userExists =  userRepository.findByEmail(user.getEmail()).isPresent();
     36       boolean userExists = userRepository.findByEmail(user.getEmail()).isPresent();
    3337
    34        if (userExists && user.getEnabled()){
    35            throw new IllegalStateException("Email "+user.getEmail()+" already taken!");
     38
     39       if (userExists){
     40           User userToRegister =  userRepository.findByEmail(user.getEmail()).get();
     41           if(userToRegister.getEnabled()) {
     42               return ResponseEntity.badRequest().body("Error: Email "+user.getEmail()+" already taken!");
     43           }
     44           else {
     45               return ResponseEntity.badRequest().body("Email "+user.getEmail()+" not activated!" );
     46           }
    3647       }
    3748
     
    4960        confirmationTokenService.saveConfirmationToken(confirmationToken);
    5061
    51         return token;
     62        return ResponseEntity.ok().body("token:"+token);
    5263    }
    5364
Note: See TracChangeset for help on using the changeset viewer.