Changeset 84d0fbb


Ignore:
Timestamp:
12/19/21 19:39:00 (3 years ago)
Author:
Ema <ema_spirova@…>
Branches:
master
Children:
bdd6491
Parents:
1ad8e64
Message:

spring security 2.0

Files:
12 added
1 deleted
29 edited

Legend:

Unmodified
Added
Removed
  • trip-planner-front/src/app/_models/dto/plannerDto.ts

    r1ad8e64 r84d0fbb  
    1 import { Location } from "../location";
    21
    32export class PlannerDto{
  • trip-planner-front/src/app/_models/planner.ts

    r1ad8e64 r84d0fbb  
    11export class Planner{
     2   
    23    id: number;
    34    name: string;
  • trip-planner-front/src/app/_services/planner.service.ts

    r1ad8e64 r84d0fbb  
    1 import { HttpClient } from "@angular/common/http";
     1import { HttpClient, HttpHeaders } from "@angular/common/http";
    22import { Injectable } from "@angular/core";
    33import { Observable } from "rxjs";
     
    88    providedIn: 'root'
    99})
    10 export class PlannerService{
    11    
     10export class PlannerService {
     11
     12    httpHeaders: HttpHeaders = new HttpHeaders({
     13        'Authorization': ''+sessionStorage.getItem("token"),
     14        'Accept': 'application/json',
     15        'Content-Type': 'application/json'
     16      });
     17     
     18
    1219    constructor(private httpClient: HttpClient){
    1320    }
    1421
     22   
    1523    getAllPlanners():Observable<Planner[]>{
    16         let url = "http://localhost:8080/api/planners";
    17         return this.httpClient.get<Planner[]>(url);
     24        let url = "http://localhost:8080/api/planners/user";
     25        console.log("SERVID: " + sessionStorage.getItem("token"));
     26        console.log(this.httpHeaders.get('Authorization'))  ;
     27        return this.httpClient.get<Planner[]>(url, {headers: this.httpHeaders});     
    1828    }
    1929
    20     postInitialPlanner(planner: Planner): Observable<Object>{     
     30    postInitialPlanner(planner: Planner): Observable<Planner>{     
    2131        let url = "http://localhost:8080/api/planner/new";
    2232        return this.httpClient.post<Planner>(url, planner);
     
    2535    updatePlanner(id: number, plannerDto : PlannerDto):Observable<Planner>{   
    2636    let url = "http://localhost:8080/api/edit/planner/" + id;
    27     return this.httpClient.put<Planner>(url, plannerDto);
     37    return this.httpClient.put<Planner>(url, plannerDto, {headers: this.httpHeaders});
    2838    }
    2939
  • trip-planner-front/src/app/app-routing.module.ts

    r1ad8e64 r84d0fbb  
    11import { NgModule } from '@angular/core';
    22import { RouterModule, Routes } from '@angular/router';
     3import { AuthGuard } from './auth/auth.guard';
    34import { HomepageComponent } from './homepage/homepage.component';
     5import { LoginComponent } from './homepage/login/login.component';
    46import { LocationDetailsComponent } from './location/location-details/location-details.component';
    57import { LocationComponent } from './location/location.component';
     
    1416  {path: 'locations', component: LocationComponent},
    1517  {path: '', component: HomepageComponent},
     18  {path: '', component:LoginComponent},
    1619  {path: 'location', component: LocationDetailsComponent}
    1720];
  • trip-planner-front/src/app/app.module.ts

    r1ad8e64 r84d0fbb  
    44import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';
    55import { FormsModule, ReactiveFormsModule } from '@angular/forms';
    6 import { HttpClient, HttpClientModule } from '@angular/common/http';
     6import { HttpClient, HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
    77import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
    88import { CategoryService } from './_services/cateogry.service';
     
    4747import { RegisterComponent } from './homepage/register/register.component';
    4848import { LoginComponent } from './homepage/login/login.component';
     49import { AuthGuard } from './auth/auth.guard';
     50import { AuthInterceptor } from './auth/auth.interceptor';
    4951
    5052@NgModule({
     
    109111    PlannerService,
    110112    {
    111       provide: MatDialogRef,
    112       useValue: {}
     113      provide: MatDialogRef,
     114      useValue: {},
     115   
     116    },
     117    {
     118      provide: HTTP_INTERCEPTORS,
     119      useClass: AuthInterceptor,
     120      multi: true
    113121    },
    114122    DialogService,
    115123    MessageService,
    116     ConfirmationService
    117 
     124    ConfirmationService,
     125    AuthGuard
    118126  ],
    119127 
  • trip-planner-front/src/app/create-initial-planner/create-initial-planner.component.ts

    r1ad8e64 r84d0fbb  
    1212
    1313  planner: Planner;
    14   plannerDto: PlannerDto;
    1514
    1615  constructor( private ref: DynamicDialogRef) {
    1716                this.planner = new Planner;
    18                 this.plannerDto = new PlannerDto();
    1917              }
    2018
    2119  ngOnInit(): void {
    2220    this.planner = new Planner();
    23     this.plannerDto = new PlannerDto();
    2421  }
    2522
  • trip-planner-front/src/app/homepage/homepage.component.html

    r1ad8e64 r84d0fbb  
    2121        </li>
    2222        <li class="nav-item">
    23           <button class="btn btn-dark">Sign in</button>
     23          <button class="btn btn-dark" (click)="onClickLogIn()">Sign in</button>
    2424        </li>
    2525      </ul>
     
    3030    <img src={{imageURI}} />
    3131    <h4></h4>
    32 
    33     <div class="content-section implementation carousel-demo" style="padding-top: 2em;">
     32<!--
     33  <div class="content-section implementation carousel-demo" style="padding-top: 2em;">
    3434      <div class="card">
    3535        <p-carousel [value]="locations" [numVisible]="3" [numScroll]="3" [circular]="false"
     
    9191      </div>
    9292    </div>
     93-->
     94 
    9395  </main>
    9496<br>
  • trip-planner-front/src/app/homepage/homepage.component.ts

    r1ad8e64 r84d0fbb  
    11import { Component, OnInit } from '@angular/core';
     2import { Router } from '@angular/router';
    23import { DialogService, DynamicDialogRef } from 'primeng/dynamicdialog';
     4import { LoginRequest } from '../_models/dto/loginRequest';
     5import { UserDto } from '../_models/dto/userDto';
    36import { Location } from '../_models/location';
    47import { LocationService } from '../_services/location.service';
     8import { UserService } from '../_services/user.service';
     9import { LoginComponent } from './login/login.component';
    510import { RegisterComponent } from './register/register.component';
    611
     
    2025   ref: DynamicDialogRef;
    2126
    22    constructor(private locationService: LocationService, private dialogService: DialogService) {
     27   constructor(private locationService: LocationService, private dialogService: DialogService, private userService: UserService,
     28      private router: Router) {
    2329      this.responsiveOptions = [
    2430         {
     
    4450
    4551   ngOnInit(): void {
    46 
     52/*
    4753      this.locationService.getWeekendGetaways().subscribe(
    4854         data => {
     
    5561         }
    5662      );
     63      */
    5764   }
    5865
    59    onClickSignUp(){
    60       console.log("VLEGOV");
     66   onClickSignUp() {
    6167      this.ref = this.dialogService.open(RegisterComponent, {
    6268         header: 'Register form',
     
    6470         contentStyle: { "max-height": "500px", "overflow": "auto" },
    6571         baseZIndex: 10000
    66        });
     72      });
     73
     74      this.ref.onClose.subscribe((user: UserDto) => {
     75         this.userService.registerUser(user).subscribe(
     76            data  => {
     77               console.log(data);
     78             
     79            }
     80         );
     81      });
     82   }
     83
     84   
     85   onClickLogIn() {
     86      this.ref = this.dialogService.open(LoginComponent, {
     87         header: 'Log in if you already have an account',
     88         width: '70%',
     89         contentStyle: { "max-height": "500px", "overflow": "auto" },
     90         baseZIndex: 10000
     91      });
     92      this.ref.onClose.subscribe((loginRequest : LoginRequest) => {
     93         this.userService.authenticateUser(loginRequest).subscribe(
     94            (data : any)  => {
     95               console.log(data);
     96               if(this.userService.isUserLoggedIn()){
     97                  this.router.navigate(['planners']);
     98               }
     99            }
     100         );
     101      });
    67102   }
    68103}
  • trip-planner-front/src/app/homepage/login/login.component.html

    r1ad8e64 r84d0fbb  
    1 <p>login works!</p>
     1<div class="p-col-12 p-md-4">
     2    <div class="p-inputgroup">
     3        <span class="p-inputgroup-addon"><i class="pi pi-user"></i></span>
     4        <input type="text" pInputText placeholder="Email address (Username)"
     5             [(ngModel)]="loginRequest.username" name="username">
     6    </div>
     7</div>
     8<div class="p-col-12 p-md-4">
     9    <div class="p-inputgroup">
     10        <span class="p-inputgroup-addon"><i class="pi pi-password"></i></span>
     11        <input type="password" pInputText placeholder="Password" name="password" [(ngModel)]="loginRequest.password">
     12    </div>
     13</div>
     14
     15<div class="p-col-12 p-md-4">
     16    <button pButton pRipple label="Log in" class="p-button-secondary" type="submit"
     17        (click)="onFormLogIn(loginRequest)"></button>
     18</div>
  • trip-planner-front/src/app/homepage/login/login.component.ts

    r1ad8e64 r84d0fbb  
    11import { Component, OnInit } from '@angular/core';
     2import { Router } from '@angular/router';
     3import { DynamicDialogRef } from 'primeng/dynamicdialog';
     4import { LoginRequest } from 'src/app/_models/dto/loginRequest';
     5import { UserService } from 'src/app/_services/user.service';
    26
    37@Component({
     
    812export class LoginComponent implements OnInit {
    913
    10   constructor() { }
     14
     15  loginRequest : LoginRequest;
     16
     17  constructor(private ref: DynamicDialogRef, private router: Router, private userService : UserService) {
     18    this.loginRequest = new LoginRequest();
     19   
     20  }
    1121
    1222  ngOnInit(): void {
    1323  }
    1424
     25  onFormLogIn(loginRequest){
     26    this.ref.close(loginRequest);
     27   
     28  }
    1529}
  • trip-planner-front/src/app/homepage/register/register.component.html

    r1ad8e64 r84d0fbb  
    1 <div class="p-grid p-fluid">
    2     <div class="p-col-12 p-md-4">
    3         <div class="p-inputgroup">
    4             <span class="p-inputgroup-addon"><i class="pi pi-user"></i></span>
    5             <input type="text" pInputText placeholder="Full name">         
     1
     2    <div class="p-grid p-fluid">
     3        <div class="p-col-12 p-md-4">
     4            <div class="p-inputgroup">
     5                <span class="p-inputgroup-addon"><i class="pi pi-user"></i></span>
     6                <input type="text" pInputText placeholder="Full name" [(ngModel)]="user.fullName" name="fullName"
     7            >         
     8            </div>
    69        </div>
    7     </div>
    8 
    9     <div class="p-col-12 p-md-4">
    10         <div class="p-inputgroup">
    11             <span class="p-inputgroup-addon"><i class="pi pi-user"></i></span>
    12             <input type="text" pInputText placeholder="Ema address (Username)">         
     10   
     11        <div class="p-col-12 p-md-4">
     12            <div class="p-inputgroup">
     13                <span class="p-inputgroup-addon"><i class="pi pi-user"></i></span>
     14                <input type="text" pInputText placeholder="Email address (Username)" [(ngModel)]="user.username" name="username"
     15              >         
     16            </div>
    1317        </div>
    14     </div>
    15     <div class="p-col-12 p-md-4">
    16         <div class="p-inputgroup">
    17             <span class="p-inputgroup-addon"><i class="pi pi-password"></i></span>
    18             <input type="text" pInputText placeholder="Password">         
     18        <div class="p-col-12 p-md-4">
     19            <div class="p-inputgroup">
     20                <span class="p-inputgroup-addon"><i class="pi pi-password"></i></span>
     21                <input type="password" pInputText placeholder="Password" [(ngModel)]="user.password" name="password"
     22                >         
     23            </div>
    1924        </div>
    20     </div>
    21     <div class="p-col-12 p-md-4">
    22         <div class="p-inputgroup">
    23             <span class="p-inputgroup-addon"><i class="pi pi-password"></i></span>
    24             <input type="text" pInputText placeholder="Repeat password">         
     25        <div class="p-col-12 p-md-4">
     26            <div class="p-inputgroup">
     27                <span class="p-inputgroup-addon"><i class="pi pi-password"></i></span>
     28                <input type="password" pInputText placeholder="Repeat password" [(ngModel)]="user.confirmPassword" name="confirmPassword"
     29                >         
     30            </div>
    2531        </div>
    26     </div>
    27 
    28     <div class="p-col-12 p-md-4">
    29         <button pButton pRipple type="button" label="Submit" class="p-button-secondary"></button>
    30     </div>
    31 </div>
     32   
     33        <div class="p-col-12 p-md-4">
     34            <button pButton pRipple label="Submit" class="p-button-secondary" type="submit" (click)="onFormSubmitSignUp(user)"></button>
     35        </div>
     36    </div> 
  • trip-planner-front/src/app/homepage/register/register.component.ts

    r1ad8e64 r84d0fbb  
    11import { Component, OnInit } from '@angular/core';
     2import { DynamicDialogRef } from 'primeng/dynamicdialog';
     3import { UserDto } from 'src/app/_models/dto/userDto';
    24
    35@Component({
     
    810export class RegisterComponent implements OnInit {
    911
    10   constructor() { }
     12  user : UserDto;
     13
     14  constructor(private ref: DynamicDialogRef) {
     15    this.user = new UserDto();
     16   }
    1117
    1218  ngOnInit(): void {
    1319  }
    14 
     20 
     21  onFormSubmitSignUp(user){
     22    this.ref.close(user);
     23    //window.location.reload();
     24  }
    1525}
  • trip-planner-front/src/app/planner/planner.component.ts

    r1ad8e64 r84d0fbb  
    77import { DialogService, DynamicDialogRef } from 'primeng/dynamicdialog';
    88import { MessageService, PrimeNGConfig } from 'primeng/api';
     9import { UserDto } from '../_models/dto/userDto';
     10import { UserService } from '../_services/user.service';
    911
    1012
     
    2022  plannerDto: PlannerDto;
    2123  ref: DynamicDialogRef;
    22 
     24  user: UserDto;
    2325
    2426  constructor(private plannerService: PlannerService, private router: Router,
    25     private dialogService: DialogService, private primengConfig: PrimeNGConfig, private messageService: MessageService) {
     27    private dialogService: DialogService, private primengConfig: PrimeNGConfig, private messageService: MessageService,
     28    private userService : UserService) {
    2629    this.planners = [];
    2730    this.plannerDto = new PlannerDto();
    2831    this.ref = new DynamicDialogRef;
     32    this.user = new UserDto();
    2933  }
    3034
     
    3640      data => {
    3741        this.planners = data;
     42        localStorage.getItem("token");
    3843      }
    39     );
     44    ); 
    4045  }
    4146
  • trip-planner/src/main/java/finki/diplomska/tripplanner/TripPlannerApplication.java

    r1ad8e64 r84d0fbb  
    66import org.springframework.context.annotation.Bean;
    77import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
     8import org.springframework.web.cors.CorsConfiguration;
     9import org.springframework.web.cors.CorsConfigurationSource;
     10import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
     11
     12import java.util.Arrays;
    813
    914@SpringBootApplication
     
    1520        return new BCryptPasswordEncoder();
    1621    }
     22
     23
    1724    public static void main(String[] args) {
    1825        SpringApplication.run(TripPlannerApplication.class, args);
  • trip-planner/src/main/java/finki/diplomska/tripplanner/models/Planner.java

    r1ad8e64 r84d0fbb  
    11package finki.diplomska.tripplanner.models;
    22
     3import com.fasterxml.jackson.annotation.JsonIgnore;
    34import lombok.*;
    4 import reactor.util.annotation.Nullable;
    55
    66import javax.persistence.*;
     
    1010@Data
    1111@Table(name = "planners")
    12 @NoArgsConstructor
    1312@AllArgsConstructor
    1413@Getter
     
    3433    private List<Location> locationList;
    3534
     35    @ManyToOne(fetch = FetchType.EAGER)
     36    private User user;
    3637
    37     public Planner(String name, String description, List<Location> locationList){
     38    public Planner(){
     39    }
     40
     41    public Planner(String name, String description, List<Location> locationList, User user){
    3842            this.name = name;
    3943            this.description = description;
    4044            this.locationList = locationList;
     45            this.user = user;
    4146    }
    4247
  • trip-planner/src/main/java/finki/diplomska/tripplanner/models/User.java

    r1ad8e64 r84d0fbb  
    1111import javax.validation.constraints.Email;
    1212import javax.validation.constraints.NotBlank;
     13import java.util.ArrayList;
    1314import java.util.Collection;
    1415import java.util.Date;
     16import java.util.List;
    1517
    1618@Entity
     
    3840    private Date update_At;
    3941
    40     //OneToMany with Project
     42    //OneToMany with Planners
     43    @OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.EAGER, mappedBy = "user", orphanRemoval = true)
     44    @JsonIgnore
     45    private List<Planner> planners = new ArrayList<>();
    4146
    4247    public User() {
    4348    }
    4449
     50    public User(String username, String fullName, String password, String confirmPassword) {
     51        this.username = username;
     52        this.fullName = fullName;
     53        this.password = password;
     54        this.confirmPassword = confirmPassword;
     55    }
    4556
    4657    @PrePersist
  • trip-planner/src/main/java/finki/diplomska/tripplanner/models/dto/PlannerDto.java

    r1ad8e64 r84d0fbb  
    99    private String name;
    1010    private String description;
     11    private String user;
    1112
    12     public PlannerDto(String name, String description) {
     13    public PlannerDto(String name, String description, String user) {
    1314        this.name = name;
    1415        this.description = description;
     16        this.user = user;
    1517    }
    1618}
  • trip-planner/src/main/java/finki/diplomska/tripplanner/models/dto/UserDto.java

    r1ad8e64 r84d0fbb  
    2020    private Date update_At;
    2121
    22     public UserDto(String username, String fullName, String password, String confirmPassword, Date create_At, Date update_At) {
     22    public UserDto(String username, String fullName, String password, String confirmPassword) {
    2323        this.username = username;
    2424        this.fullName = fullName;
    2525        this.password = password;
    2626        this.confirmPassword = confirmPassword;
    27         this.create_At = create_At;
    28         this.update_At = update_At;
     27
    2928    }
    3029}
  • trip-planner/src/main/java/finki/diplomska/tripplanner/repository/jpa/JpaPlannerRepository.java

    r1ad8e64 r84d0fbb  
    44import finki.diplomska.tripplanner.models.Planner;
    55import org.springframework.data.jpa.repository.JpaRepository;
     6import org.springframework.data.jpa.repository.Query;
     7import org.springframework.data.repository.query.Param;
    68import org.springframework.stereotype.Repository;
    79
     
    1113public interface JpaPlannerRepository extends JpaRepository<Planner, Long> {
    1214
    13 
     15        @Query(value = "SELECT * FROM planners AS p left JOIN users AS u ON p.user_id = u.id WHERE u.username like :username", nativeQuery = true)
     16        List<Planner> getPlannersByUser(@Param("username") String username );
    1417}
  • trip-planner/src/main/java/finki/diplomska/tripplanner/repository/jpa/JpaUserRepository.java

    r1ad8e64 r84d0fbb  
    77@Repository
    88public interface JpaUserRepository extends CrudRepository<User, Long> {
     9    User findByUsername(String username);
     10    User getById(Long id);
    911}
  • trip-planner/src/main/java/finki/diplomska/tripplanner/security/SecurityConfig.java

    r1ad8e64 r84d0fbb  
    22
    33
     4import finki.diplomska.tripplanner.service.impl.CustomUserDetailsServiceImpl;
    45import org.springframework.beans.factory.annotation.Autowired;
     6import org.springframework.context.annotation.Bean;
    57import org.springframework.context.annotation.Configuration;
     8import org.springframework.security.authentication.AuthenticationManager;
     9import org.springframework.security.config.BeanIds;
     10import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    611import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
    712import org.springframework.security.config.annotation.web.builders.HttpSecurity;
     
    914import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    1015import org.springframework.security.config.http.SessionCreationPolicy;
     16import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
     17import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
     18
     19import static finki.diplomska.tripplanner.security.SecurityConstants.MARIADB_URL;
     20import static finki.diplomska.tripplanner.security.SecurityConstants.SIGN_UP_URLS;
    1121
    1222@Configuration
     
    2131    @Autowired
    2232    private JwtAuthenticationEntryPoint unauthorizedHandler;
     33
     34    @Autowired
     35    private CustomUserDetailsServiceImpl customUserDetailsService;
     36
     37    @Bean
     38    public JwtAuthenticationFilter jwtAuthenticationFilter() {return  new JwtAuthenticationFilter();}
     39
     40
     41    @Autowired
     42    private BCryptPasswordEncoder bCryptPasswordEncoder;
     43
     44    @Override
     45    protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
     46        authenticationManagerBuilder.userDetailsService(customUserDetailsService).passwordEncoder(bCryptPasswordEncoder);
     47    }
     48
     49    @Override
     50    @Bean(BeanIds.AUTHENTICATION_MANAGER)
     51    protected AuthenticationManager authenticationManager() throws Exception {
     52        return super.authenticationManager();
     53    }
    2354
    2455    @Override
     
    4374                        "/**/*.js"
    4475                ).permitAll()
    45                 .antMatchers("/api/users/**").permitAll()
     76                .antMatchers(SIGN_UP_URLS).permitAll()
     77                .antMatchers(MARIADB_URL).permitAll()
    4678                .anyRequest().authenticated();
     79        http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
     80
    4781    }
    4882}
  • trip-planner/src/main/java/finki/diplomska/tripplanner/service/PlannerService.java

    r1ad8e64 r84d0fbb  
    1111
    1212        Planner createPlannerWithRequestParams(String description, String name, List<Location> locationList);
    13         Optional<Planner> editPlanner(Long id, PlannerDto plannerDto);
     13        Optional<Planner> editPlanner(Long id, PlannerDto plannerDto, String username);
    1414        List<Planner> getAllPlaners();
     15        List<Planner> getPlannersByUser(String username);
    1516        Optional<Planner> findById(Long id);
    1617        Planner editPlannerWithRequestParams(Long id, String description, String name, List<Location> locationList);
    17         Optional<Planner> newPlanner(PlannerDto plannerDto);
     18        Optional<Planner> newPlanner(PlannerDto plannerDto, String username);
    1819}
  • trip-planner/src/main/java/finki/diplomska/tripplanner/service/UserService.java

    r1ad8e64 r84d0fbb  
    22
    33import finki.diplomska.tripplanner.models.User;
     4import finki.diplomska.tripplanner.models.dto.UserDto;
    45
     6import java.util.Optional;
    57
    68
  • trip-planner/src/main/java/finki/diplomska/tripplanner/service/impl/PlannerServiceImpl.java

    r1ad8e64 r84d0fbb  
    33import finki.diplomska.tripplanner.models.Location;
    44import finki.diplomska.tripplanner.models.Planner;
     5import finki.diplomska.tripplanner.models.User;
    56import finki.diplomska.tripplanner.models.dto.PlannerDto;
    67import finki.diplomska.tripplanner.models.exceptions.LocationNotFoundException;
     
    89import finki.diplomska.tripplanner.repository.jpa.JpaLocationRepository;
    910import finki.diplomska.tripplanner.repository.jpa.JpaPlannerRepository;
    10 import finki.diplomska.tripplanner.service.LocationService;
     11import finki.diplomska.tripplanner.repository.jpa.JpaUserRepository;
    1112import finki.diplomska.tripplanner.service.PlannerService;
    1213import org.springframework.stereotype.Service;
    13 import reactor.util.annotation.Nullable;
    1414
    15 import java.util.ArrayList;
     15import javax.jws.soap.SOAPBinding;
    1616import java.util.List;
    1717import java.util.Optional;
     
    2222    private final JpaPlannerRepository plannerRepository;
    2323    private final JpaLocationRepository locationRepository;
     24    private final JpaUserRepository userRepository;
    2425
    25     public PlannerServiceImpl(JpaPlannerRepository plannerRepository, JpaLocationRepository locationRepository) {
     26    public PlannerServiceImpl(JpaPlannerRepository plannerRepository, JpaLocationRepository locationRepository, JpaUserRepository userRepository) {
    2627        this.plannerRepository = plannerRepository;
    2728        this.locationRepository = locationRepository;
     29        this.userRepository = userRepository;
    2830    }
    2931
     
    3133    public List<Planner> getAllPlaners() {
    3234        return this.plannerRepository.findAll();
     35    }
     36
     37    @Override
     38    public List<Planner> getPlannersByUser(String username) {
     39        User user = this.userRepository.findByUsername(username);
     40        return this.plannerRepository.getPlannersByUser(user.getUsername());
    3341    }
    3442
     
    4048
    4149    @Override
    42     public Optional<Planner> newPlanner(PlannerDto plannerDto) {
     50    public Optional<Planner> newPlanner(PlannerDto plannerDto, String username) {
    4351        /*
    4452        List<Location> locationList  = new ArrayList<>();
     
    4856            locationList.add(loc);
    4957        }
    50 
    5158         */
    52            return Optional.of(this.plannerRepository.save(new Planner(plannerDto.getName(), plannerDto.getDescription(), null)));
     59        User user = this.userRepository.findByUsername(username);
     60        plannerDto.setUser(user.getUsername());
     61        return Optional.of(this.plannerRepository.save(new Planner(plannerDto.getName(), plannerDto.getDescription(), null, user)));
    5362    }
    5463
     
    6978
    7079    @Override
    71     public Optional<Planner> editPlanner(Long id, PlannerDto plannerDto) {
     80    public Optional<Planner> editPlanner(Long id, PlannerDto plannerDto, String username) {
    7281        Planner planner = this.plannerRepository.findById(id).orElseThrow(() -> new PlannerNotFoundException(id));
     82        User user = this.userRepository.findByUsername(username);
    7383
    7484        planner.setName(plannerDto.getName());
    7585        planner.setDescription(plannerDto.getDescription());
     86        plannerDto.setUser(user.getUsername());
     87        planner.setUser(user);
    7688/*
    7789        List<Location> locationList  = new ArrayList<>();
  • trip-planner/src/main/java/finki/diplomska/tripplanner/service/impl/UserServiceImpl.java

    r1ad8e64 r84d0fbb  
    99import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    1010import org.springframework.stereotype.Service;
     11
     12import java.util.Optional;
    1113
    1214
     
    2830            // We don't persist or show the confirmPassword
    2931            newUser.setConfirmPassword("");
    30             return this.userRepository.save(newUser);
     32             return this.userRepository.save(newUser);
    3133        }catch(Exception e){
    3234            throw new UsernameAlreadyExistsException("Username '"+newUser.getUsername()+ "' already exists");
  • trip-planner/src/main/java/finki/diplomska/tripplanner/web/rest/PlannerRestController.java

    r1ad8e64 r84d0fbb  
    33import finki.diplomska.tripplanner.models.Location;
    44import finki.diplomska.tripplanner.models.Planner;
     5import finki.diplomska.tripplanner.models.User;
    56import finki.diplomska.tripplanner.models.dto.PlannerDto;
    67import finki.diplomska.tripplanner.service.LocationService;
     
    910import org.springframework.http.MediaType;
    1011import org.springframework.http.ResponseEntity;
     12import org.springframework.security.core.Authentication;
    1113import org.springframework.web.bind.annotation.*;
    1214import org.springframework.web.bind.annotation.RestController;
    1315
     16import javax.validation.Valid;
    1417import java.util.ArrayList;
    1518import java.util.List;
     
    1720
    1821@RestController
    19 @CrossOrigin(origins = "http://localhost:4200")
     22@CrossOrigin(origins = "http://localhost:4200",  exposedHeaders = "token")
    2023@RequestMapping(value = "/api")
    2124public class PlannerRestController {
     
    3134    public List<Planner> getAllPlanners(){
    3235        return this.plannerService.getAllPlaners();
     36    }
     37
     38
     39    @GetMapping(value = "/planners/user")
     40    public List<Planner> getPlannersByUser(Authentication authentication){
     41        User user = (User) authentication.getPrincipal();
     42        return this.plannerService.getPlannersByUser(user.getUsername());
    3343    }
    3444
     
    5767    @PostMapping(value = "/planner/new", consumes= MediaType.APPLICATION_JSON_VALUE)
    5868    @ResponseStatus(HttpStatus.CREATED)
    59     public ResponseEntity<Planner> newPlanner(@RequestBody PlannerDto plannerDto)  {
    60         return this.plannerService.newPlanner(plannerDto)
     69    public ResponseEntity<?> newPlanner(@Valid @RequestBody PlannerDto plannerDto, Authentication authentication)  {
     70
     71        User user = (User) authentication.getPrincipal();
     72        return this.plannerService.newPlanner(plannerDto, user.getUsername())
    6173                .map(planner -> ResponseEntity.ok().body(planner))
    6274                .orElseGet(() -> ResponseEntity.badRequest().build());
     
    6577
    6678    @PutMapping(value ="edit/planner/{id}", consumes= MediaType.APPLICATION_JSON_VALUE)
    67     public ResponseEntity<Planner> editPlanner(@PathVariable Long id, @RequestBody PlannerDto plannerDto){
    68         return this.plannerService.editPlanner(id, plannerDto)
     79    public ResponseEntity<Planner> editPlanner(@PathVariable Long id, @Valid @RequestBody PlannerDto plannerDto, Authentication authentication){
     80        User user = (User) authentication.getPrincipal();
     81        return this.plannerService.editPlanner(id, plannerDto, user.getUsername())
    6982                .map(planner -> ResponseEntity.ok().body(planner))
    7083                .orElseGet(()-> ResponseEntity.badRequest().build());
  • trip-planner/src/main/java/finki/diplomska/tripplanner/web/rest/UserController.java

    r1ad8e64 r84d0fbb  
    33import finki.diplomska.tripplanner.models.User;
    44import finki.diplomska.tripplanner.models.dto.UserDto;
     5import finki.diplomska.tripplanner.payload.JWTLoginSucessReponse;
     6import finki.diplomska.tripplanner.payload.LoginRequest;
     7import finki.diplomska.tripplanner.security.JwtTokenProvider;
     8import finki.diplomska.tripplanner.security.SecurityConstants;
    59import finki.diplomska.tripplanner.service.UserService;
    610import finki.diplomska.tripplanner.service.impl.MapValidationErrorService;
     
    913import org.springframework.http.HttpStatus;
    1014import org.springframework.http.ResponseEntity;
     15import org.springframework.security.authentication.AuthenticationManager;
     16import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
     17import org.springframework.security.core.context.SecurityContextHolder;
    1118import org.springframework.validation.BindingResult;
    1219import org.springframework.web.bind.annotation.*;
    13 
     20import org.springframework.security.core.Authentication;
    1421import javax.validation.Valid;
    1522
     
    2835    private UserValidator userValidator;
    2936
    30     @PostMapping("/register")
     37    @Autowired
     38    private JwtTokenProvider tokenProvider;
     39
     40    @Autowired
     41    private AuthenticationManager authenticationManager;
     42
     43    @PostMapping(value = "/login")
     44    public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest, BindingResult result){
     45        ResponseEntity<?> errorMap = mapValidationErrorService.MapValidationService(result);
     46        if(errorMap != null) return errorMap;
     47
     48        Authentication authentication = authenticationManager.authenticate(
     49                new UsernamePasswordAuthenticationToken(
     50                        loginRequest.getUsername(),
     51                        loginRequest.getPassword()
     52                )
     53        );
     54
     55        SecurityContextHolder.getContext().setAuthentication(authentication);
     56        String jwt = SecurityConstants.TOKEN_PREFIX +  tokenProvider.generateToken(authentication);
     57
     58        return ResponseEntity.ok(new JWTLoginSucessReponse(true, jwt));
     59    }
     60
     61    @PostMapping(value = "/register")
    3162    public ResponseEntity<?> registerUser(@Valid @RequestBody User user, BindingResult result){
    3263        // Validate passwords match
     
    3869
    3970        return  new ResponseEntity<User>(newUser, HttpStatus.CREATED);
     71
    4072    }
    4173}
  • trip-planner/src/main/resources/application.properties

    r1ad8e64 r84d0fbb  
    66jasypt.encryptor.iv-generator-classname=org.jasypt.iv.NoIvGenerator
    77jasypt.encryptor.algorithm=PBEWithMD5AndDES
     8spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
    89
    910spring.jpa.show-sql=true
  • trip-planner/src/test/api.http

    r1ad8e64 r84d0fbb  
    7575GET http://localhost:8080/api/images?locationId=1
    7676Content-Type: application/x-www-form-urlencoded
     77
     78###
     79POST http://localhost:8080/api/users/register
     80Content-Type: application/json
     81
     82{"username": "teshht@test.com", "fullName": "nikola", "password" : "nikolce", "confirmPassword": "nikolce"}
     83
     84###
     85POST http://localhost:8080/api/users/login
     86Content-Type: application/json
     87
     88{"username": "test@test.com", "password" : "nikolce"}
     89
     90
     91###
     92GET http://localhost:8080/api/planners/user
     93Content-Type: application/json
Note: See TracChangeset for help on using the changeset viewer.